/
SignatureInfo.java
402 lines (331 loc) · 13.9 KB
/
SignatureInfo.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
/*
* Copyright 2015 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.storage;
import static com.google.cloud.storage.SignedUrlEncodingHelper.Rfc3986UriEncode;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.hash.Hashing;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.TreeMap;
/**
* Signature Info holds payload components of the string that requires signing.
*
* @see <a href=
* "https://cloud.google.com/storage/docs/access-control/signed-urls#string-components">
* Components</a>
*/
public class SignatureInfo {
public static final char COMPONENT_SEPARATOR = '\n';
public static final String GOOG4_RSA_SHA256 = "GOOG4-RSA-SHA256";
public static final String SCOPE = "/auto/storage/goog4_request";
private static final List<String> RESERVED_PARAMS_LOWER =
ImmutableList.<String>of(
// V2:
"expires",
"googleaccessid",
// V4:
"x-goog-algorithm",
"x-goog-credential",
"x-goog-date",
"x-goog-expires",
"x-goog-signedheaders");
private final HttpMethod httpVerb;
private final String contentMd5;
private final String contentType;
private final long expiration;
private final Map<String, String> canonicalizedExtensionHeaders;
private final Map<String, String> queryParams;
private final URI canonicalizedResource;
private final Storage.SignUrlOption.SignatureVersion signatureVersion;
private final String accountEmail;
private final long timestamp;
private final String yearMonthDay;
private final String exactDate;
private SignatureInfo(Builder builder) {
this.httpVerb = builder.httpVerb;
this.contentMd5 = builder.contentMd5;
this.contentType = builder.contentType;
this.expiration = builder.expiration;
this.canonicalizedResource = builder.canonicalizedResource;
this.signatureVersion = builder.signatureVersion;
this.accountEmail = builder.accountEmail;
this.timestamp = builder.timestamp;
ImmutableMap.Builder<String, String> headerBuilder =
new ImmutableMap.Builder<String, String>().putAll(builder.canonicalizedExtensionHeaders);
// The "host" header only needs to be present and signed if using V4.
if (Storage.SignUrlOption.SignatureVersion.V4.equals(signatureVersion)
&& (!builder.canonicalizedExtensionHeaders.containsKey("host"))) {
headerBuilder.put("host", "storage.googleapis.com");
}
canonicalizedExtensionHeaders = headerBuilder.build();
queryParams = ImmutableMap.<String, String>copyOf(builder.queryParams);
Date date = new Date(timestamp);
SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat exactDateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
yearMonthDayFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
exactDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
yearMonthDay = yearMonthDayFormat.format(date);
exactDate = exactDateFormat.format(date);
}
/**
* Constructs payload to be signed.
*
* @return payload to sign
* @see <a href="https://cloud.google.com/storage/docs/access-control#Signed-URLs">Signed URLs</a>
*/
public String constructUnsignedPayload() {
// TODO reverse order when V4 becomes default
if (Storage.SignUrlOption.SignatureVersion.V4.equals(signatureVersion)) {
return constructV4UnsignedPayload();
}
return constructV2UnsignedPayload();
}
private String constructV2UnsignedPayload() {
StringBuilder payload = new StringBuilder();
payload.append(httpVerb.name()).append(COMPONENT_SEPARATOR);
if (contentMd5 != null) {
payload.append(contentMd5);
}
payload.append(COMPONENT_SEPARATOR);
if (contentType != null) {
payload.append(contentType);
}
payload.append(COMPONENT_SEPARATOR);
payload.append(expiration).append(COMPONENT_SEPARATOR);
if (canonicalizedExtensionHeaders.size() > 0) {
payload.append(
new CanonicalExtensionHeadersSerializer(Storage.SignUrlOption.SignatureVersion.V2)
.serialize(canonicalizedExtensionHeaders));
}
payload.append(canonicalizedResource);
return payload.toString();
}
private String constructV4UnsignedPayload() {
StringBuilder payload = new StringBuilder();
payload.append(GOOG4_RSA_SHA256).append(COMPONENT_SEPARATOR);
payload.append(exactDate).append(COMPONENT_SEPARATOR);
payload.append(yearMonthDay).append(SCOPE).append(COMPONENT_SEPARATOR);
payload.append(constructV4CanonicalRequestHash());
return payload.toString();
}
private String constructV4CanonicalRequestHash() {
StringBuilder canonicalRequest = new StringBuilder();
CanonicalExtensionHeadersSerializer serializer =
new CanonicalExtensionHeadersSerializer(Storage.SignUrlOption.SignatureVersion.V4);
canonicalRequest.append(httpVerb.name()).append(COMPONENT_SEPARATOR);
canonicalRequest.append(canonicalizedResource).append(COMPONENT_SEPARATOR);
canonicalRequest.append(constructV4QueryString()).append(COMPONENT_SEPARATOR);
canonicalRequest
.append(serializer.serialize(canonicalizedExtensionHeaders))
.append(COMPONENT_SEPARATOR);
canonicalRequest
.append(serializer.serializeHeaderNames(canonicalizedExtensionHeaders))
.append(COMPONENT_SEPARATOR);
canonicalRequest.append("UNSIGNED-PAYLOAD");
return Hashing.sha256()
.hashString(canonicalRequest.toString(), StandardCharsets.UTF_8)
.toString();
}
/**
* Returns a TreeMap containing the user-supplied query parameters that do not have reserved keys.
*/
private TreeMap<String, String> getNonReservedUserQueryParams() {
TreeMap<String, String> sortedParamMap = new TreeMap<String, String>();
// Skip any instances of well-known required headers that might have been supplied by the
// caller.
for (Map.Entry<String, String> entry : queryParams.entrySet()) {
// Convert to (and check for the existence of) lowercase keys to prevent cases like a user
// supplying "x-goog-algorithm", in order to prevent the resulting query string from
// containing "x-goog-algorithm" and "X-Goog-Algorithm".
if (!RESERVED_PARAMS_LOWER.contains(entry.getKey().toLowerCase())) {
// URI encode user-supplied parameter, both the name and the value.
sortedParamMap.put(
Rfc3986UriEncode(entry.getKey(), true), Rfc3986UriEncode(entry.getValue(), true));
}
}
return sortedParamMap;
}
private String queryStringFromParamMap(Map<String, String> map) {
StringBuilder queryStringBuilder = new StringBuilder();
String sep = "";
for (Map.Entry<String, String> entry : map.entrySet()) {
queryStringBuilder.append(sep);
sep = "&";
queryStringBuilder.append(entry.getKey()).append('=').append(entry.getValue());
}
return queryStringBuilder.toString();
}
/**
* Returns a query string constructed from this object's stored query parameters, sorted in code
* point order. Note that these query parameters are not used when constructing the URL's
* signature. The returned value does not include the leading ? character, as this is not part of
* a query string.
*
* @return A URI query string. Returns an empty string if the user supplied no query parameters.
*/
public String constructV2QueryString() {
TreeMap<String, String> sortedParamMap = getNonReservedUserQueryParams();
// The "GoogleAccessId", "Expires", and "Signature" params are not included here.
return queryStringFromParamMap(sortedParamMap);
}
/**
* Returns a query string constructed from this object's stored query parameters, sorted in code
* point order so that the query string can be used in a V4 canonical request string. The returned
* value does not include the leading ? character, as this is not part of a query string.
*
* @see <a href= "https://cloud.google.com/storage/docs/authentication/canonical-requests">
* Canonical Requests</a>
*/
public String constructV4QueryString() {
TreeMap<String, String> sortedParamMap = getNonReservedUserQueryParams();
// Add in the reserved auth-specific query params.
sortedParamMap.put("X-Goog-Algorithm", Rfc3986UriEncode(GOOG4_RSA_SHA256, true));
sortedParamMap.put(
"X-Goog-Credential", Rfc3986UriEncode(accountEmail + "/" + yearMonthDay + SCOPE, true));
sortedParamMap.put("X-Goog-Date", Rfc3986UriEncode(exactDate, true));
sortedParamMap.put("X-Goog-Expires", Rfc3986UriEncode(Long.toString(expiration), true));
StringBuilder signedHeadersBuilder =
new CanonicalExtensionHeadersSerializer(Storage.SignUrlOption.SignatureVersion.V4)
.serializeHeaderNames(canonicalizedExtensionHeaders);
sortedParamMap.put(
"X-Goog-SignedHeaders", Rfc3986UriEncode(signedHeadersBuilder.toString(), true));
// The "X-Goog-Signature" param is not included here.
return queryStringFromParamMap(sortedParamMap);
}
public HttpMethod getHttpVerb() {
return httpVerb;
}
public String getContentMd5() {
return contentMd5;
}
public String getContentType() {
return contentType;
}
public long getExpiration() {
return expiration;
}
public Map<String, String> getCanonicalizedExtensionHeaders() {
return canonicalizedExtensionHeaders;
}
public Map<String, String> getQueryParams() {
return queryParams;
}
public URI getCanonicalizedResource() {
return canonicalizedResource;
}
public Storage.SignUrlOption.SignatureVersion getSignatureVersion() {
return signatureVersion;
}
public long getTimestamp() {
return timestamp;
}
public String getAccountEmail() {
return accountEmail;
}
public static final class Builder {
private final HttpMethod httpVerb;
private String contentMd5;
private String contentType;
private final long expiration;
private Map<String, String> canonicalizedExtensionHeaders;
private Map<String, String> queryParams;
private final URI canonicalizedResource;
private Storage.SignUrlOption.SignatureVersion signatureVersion;
private String accountEmail;
private long timestamp;
/**
* Constructs builder.
*
* @param httpVerb the HTTP method
* @param expiration the EPOX expiration date
* @param canonicalizedResource the resource URI
* @throws IllegalArgumentException if required field is not provided.
*/
public Builder(HttpMethod httpVerb, long expiration, URI canonicalizedResource) {
this.httpVerb = httpVerb;
this.expiration = expiration;
this.canonicalizedResource = canonicalizedResource;
}
public Builder(SignatureInfo signatureInfo) {
this.httpVerb = signatureInfo.httpVerb;
this.contentMd5 = signatureInfo.contentMd5;
this.contentType = signatureInfo.contentType;
this.expiration = signatureInfo.expiration;
this.canonicalizedExtensionHeaders = signatureInfo.canonicalizedExtensionHeaders;
this.queryParams = signatureInfo.queryParams;
this.canonicalizedResource = signatureInfo.canonicalizedResource;
this.signatureVersion = signatureInfo.signatureVersion;
this.accountEmail = signatureInfo.accountEmail;
this.timestamp = signatureInfo.timestamp;
}
public Builder setContentMd5(String contentMd5) {
this.contentMd5 = contentMd5;
return this;
}
public Builder setContentType(String contentType) {
this.contentType = contentType;
return this;
}
public Builder setCanonicalizedExtensionHeaders(
Map<String, String> canonicalizedExtensionHeaders) {
this.canonicalizedExtensionHeaders = canonicalizedExtensionHeaders;
return this;
}
public Builder setCanonicalizedQueryParams(Map<String, String> queryParams) {
this.queryParams = queryParams;
return this;
}
public Builder setSignatureVersion(Storage.SignUrlOption.SignatureVersion signatureVersion) {
this.signatureVersion = signatureVersion;
return this;
}
public Builder setAccountEmail(String accountEmail) {
this.accountEmail = accountEmail;
return this;
}
public Builder setTimestamp(long timestamp) {
this.timestamp = timestamp;
return this;
}
/** Creates an {@code SignatureInfo} object from this builder. */
public SignatureInfo build() {
checkArgument(httpVerb != null, "Required HTTP method");
checkArgument(canonicalizedResource != null, "Required canonicalized resource");
checkArgument(expiration >= 0, "Expiration must be greater than or equal to zero");
if (Storage.SignUrlOption.SignatureVersion.V4.equals(signatureVersion)) {
checkArgument(accountEmail != null, "Account email required to use V4 signing");
checkArgument(timestamp > 0, "Timestamp required to use V4 signing");
checkArgument(
expiration <= 604800, "Expiration can't be longer than 7 days to use V4 signing");
}
if (canonicalizedExtensionHeaders == null) {
canonicalizedExtensionHeaders = new HashMap<>();
}
if (queryParams == null) {
queryParams = new HashMap<>();
}
return new SignatureInfo(this);
}
}
}