Repository navigation
Expand file tree
/
Copy pathCloudfrontUrlBuilder.java
More file actions
462 lines (419 loc) · 17.4 KB
/
Copy pathCloudfrontUrlBuilder.java
File metadata and controls
462 lines (419 loc) · 17.4 KB
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
package com.widen.urlbuilder;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
import java.security.Signature;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* Utility class for constructing signed Amazon CloudFront URLs using a fluent method-chaining API.
*
* <p>This builder creates "canned policy" CloudFront signed URLs that allow temporary access to
* private CloudFront distributions. The URLs include cryptographic signatures generated using
* RSA-SHA1 with your CloudFront trusted signer credentials.
*
* <p><b>Typical usage:</b>
* <pre>{@code
* PrivateKey privateKey = CloudfrontPrivateKeyUtils.fromPemString(pemString);
*
* String signedUrl = new CloudfrontUrlBuilder("d123.cloudfront.net", "/videos/movie.mp4", "APKAEIBAERJR2EXAMPLE", privateKey)
* .withSsl()
* .expireIn(Duration.ofHours(1))
* .toString();
* }</pre>
*
* <p><b>With attachment filename:</b>
* <pre>{@code
* String signedUrl = new CloudfrontUrlBuilder("d123.cloudfront.net", "/docs/report.pdf", keyPairId, privateKey)
* .withSsl()
* .withAttachmentFilename("quarterly-report.pdf")
* .expireAt(expirationDate)
* .toString();
* }</pre>
*
* <p>The generated URL includes three signing parameters:
* <ul>
* <li>{@code Expires} - Unix timestamp when the URL expires</li>
* <li>{@code Signature} - RSA-SHA1 signature of the canned policy, base64 encoded with CloudFront-safe characters</li>
* <li>{@code Key-Pair-Id} - The CloudFront key pair ID used for signing</li>
* </ul>
*
* <p>This class uses the generic {@link UrlSigner} mechanism internally for URL signing.
*
* <p>Once a builder is configured, concurrent calls to {@link #toString()} are safe.
* The configuration methods are not synchronized.
*
* @see CloudfrontPrivateKeyUtils
* @see UrlSigner
* @since 1.0.0
*/
public class CloudfrontUrlBuilder
{
private String distributionHostname;
private String key;
private boolean ssl = true;
private final TrustedSignerCredentials trustedSignerCredentials;
private String attachmentFilename;
private String contentType;
private final ExpireDateHolder expireDate = new ExpireDateHolder();
private final Map<String, String> parameters = new LinkedHashMap<>();
/** The query parameters CloudFront reads the signature from. */
private static final Set<String> SIGNING_PARAMETERS =
new HashSet<>(Arrays.asList("Expires", "Signature", "Key-Pair-Id", "Policy"));
/**
* Constructs a CloudFront URL builder for creating "canned policy" signed URLs.
*
* <p>Uses the default "SunRsaSign" crypto provider for RSA-SHA1 signature generation.
*
* @param distributionHostname The CloudFront distribution hostname (e.g., "d123.cloudfront.net")
* @param key The path to the resource (e.g., "/videos/movie.mp4")
* @param keyPairId The CloudFront key pair ID associated with your trusted signer
* @param privateKey The RSA private key for signing
* @see #CloudfrontUrlBuilder(String, String, String, PrivateKey, String)
*/
public CloudfrontUrlBuilder(String distributionHostname, String key, String keyPairId, PrivateKey privateKey)
{
this(distributionHostname, key, keyPairId, privateKey, "SunRsaSign");
}
/**
* Constructs a CloudFront URL builder for creating "canned policy" signed URLs with a custom crypto provider.
*
* <p>Use "BC" to use Bouncy Castle as the crypto provider when generating SHA1 signatures.
* This may be necessary in environments where the default SunRsaSign provider is not available.
*
* @param distributionHostname The CloudFront distribution hostname (e.g., "d123.cloudfront.net")
* @param key The path to the resource (e.g., "/videos/movie.mp4")
* @param keyPairId The CloudFront key pair ID associated with your trusted signer
* @param privateKey The RSA private key for signing
* @param cryptoProvider The JCE crypto provider name (e.g., "SunRsaSign" or "BC" for Bouncy Castle)
* @throws IllegalArgumentException if key is blank or only slashes
*/
public CloudfrontUrlBuilder(String distributionHostname, String key, String keyPairId, PrivateKey privateKey, String cryptoProvider)
{
this.distributionHostname = distributionHostname;
withKey(key);
this.trustedSignerCredentials = new TrustedSignerCredentials(keyPairId, privateKey, cryptoProvider);
}
/**
* Sets the CloudFront distribution hostname.
*
* @param hostname The distribution hostname (e.g., "d123.cloudfront.net")
* @return This builder for method chaining
*/
public CloudfrontUrlBuilder withDistributionHostname(String hostname)
{
this.distributionHostname = hostname;
return this;
}
/**
* Sets the resource key (path) within the CloudFront distribution.
*
* <p>The key is literal text: the builder encodes every character except letters, digits,
* {@code -._~}, and {@code /}, so an S3 origin does not read the {@code +} in {@code a+b.pdf}
* as a space. Leading slashes are dropped, and every other slash is kept, so {@code folder/}
* and {@code a//b} reach the origin as given.
*
* @param key The path to the resource (e.g., "/videos/movie.mp4")
* @return This builder for method chaining
* @throws IllegalArgumentException if key is blank or only slashes
*/
public CloudfrontUrlBuilder withKey(String key)
{
// A key of only slashes would sign the distribution root
InternalUtils.checkNotBlank(AwsUrls.stripLeadingSlashes(key), "key");
this.key = key;
return this;
}
/**
* Sets a filename hint for Content-Disposition header.
*
* <p>When set, CloudFront will include a {@code response-content-disposition} parameter
* that instructs the browser to download the file with the specified filename rather
* than displaying it inline.
*
* @param attachmentFilename The suggested filename for downloads
* @return This builder for method chaining
*/
public CloudfrontUrlBuilder withAttachmentFilename(String attachmentFilename)
{
this.attachmentFilename = attachmentFilename;
return this;
}
/**
* Sets a content type hint for the response.
*
* <p>When set, CloudFront will include a {@code response-content-type} parameter
* that overrides the Content-Type header in the response.
*
* @param contentType The MIME type for the response (e.g., "application/pdf")
* @return This builder for method chaining
*/
public CloudfrontUrlBuilder withContentType(String contentType)
{
this.contentType = contentType;
return this;
}
/**
* Adds a custom query parameter to the URL.
*
* <p>Custom parameters are included in the signed URL and will be part of the
* signature calculation. Adding a name again replaces its value, unlike
* {@link UrlBuilder#addParameter(String, Object)}, which keeps both.
*
* @param key The parameter name
* @param value The parameter value, or null to add the name alone
* @return This builder for method chaining
* @throws IllegalArgumentException if key is {@code Expires}, {@code Signature}, {@code Key-Pair-Id}, or
* {@code Policy}, which CloudFront reads the signature from
*/
public CloudfrontUrlBuilder addParameter(String key, String value)
{
if (SIGNING_PARAMETERS.contains(key))
{
throw new IllegalArgumentException("CloudFront reserves the parameter name " + key + " for the signature.");
}
parameters.put(key, value);
return this;
}
/**
* Sets the generated URL to use the "https" scheme, which is the default.
*
* @return This builder for method chaining
*/
public CloudfrontUrlBuilder withSsl()
{
ssl = true;
return this;
}
/**
* Sets the scheme of the generated URL. The signature covers the scheme, so CloudFront rejects a signed
* {@code http} URL that is requested over {@code https}, and the reverse.
*
* @param useSsl true to use "https", the default, or false to use "http"
* @return This builder for method chaining
* @since 3.0.0
*/
public CloudfrontUrlBuilder withSsl(boolean useSsl)
{
ssl = useSsl;
return this;
}
/**
* Sets the relative duration until the URL expires.
*
* <p>The actual expiration time is calculated when {@link #toString()} is called,
* allowing the same builder to generate URLs with fresh expiration times.
*
* <p>Replaces an expiration set earlier with {@code expireAt}.
*
* @param duration The time from URL generation until the URL expires (must be positive)
* @return This builder for method chaining
* @throws IllegalArgumentException if {@code duration} is null or not positive
* @since 3.0.0
*/
public CloudfrontUrlBuilder expireIn(Duration duration)
{
expireDate.expireIn(duration);
return this;
}
/**
* Sets the relative duration until the URL expires, as a count of a {@link TimeUnit}.
* Behaves as {@link #expireIn(Duration)}.
*
* @param duration The duration value (must be positive)
* @param unit The time unit for the duration
* @return This builder for method chaining
* @throws IllegalArgumentException if {@code unit} is null or {@code duration} is not positive
*/
public CloudfrontUrlBuilder expireIn(long duration, TimeUnit unit)
{
expireDate.expireIn(duration, unit);
return this;
}
/**
* Sets the absolute expiration time for the URL.
*
* <p>The expiration time is accurate to seconds (milliseconds are truncated).
*
* @param date The absolute date/time when the URL should expire
* @return This builder for method chaining
* @throws IllegalArgumentException if date is null
* @deprecated Use {@link #expireAt(Instant)} instead. This method will be removed in a future version.
*/
@Deprecated
public CloudfrontUrlBuilder expireAt(Date date)
{
InternalUtils.checkNotNull(date, "date");
return expireAt(date.toInstant());
}
/**
* Sets the absolute expiration time for the URL using a Java 8+ Instant.
*
* <p>The expiration time is accurate to seconds (nanoseconds are truncated).
* It replaces an expiration set earlier with {@code expireIn}.
*
* <p>Example usage:
* <pre>{@code
* builder.expireAt(Instant.now().plus(Duration.ofHours(1)));
* }</pre>
*
* @param instant The absolute instant when the URL should expire
* @return This builder for method chaining
* @throws IllegalArgumentException if instant is null
* @since 3.0.0
*/
public CloudfrontUrlBuilder expireAt(Instant instant)
{
expireDate.expireAt(instant);
return this;
}
/**
* Generates the signed CloudFront URL.
*
* <p>This method constructs the complete URL including:
* <ul>
* <li>The distribution hostname and resource path</li>
* <li>Any custom parameters and content disposition/type headers</li>
* <li>CloudFront signing parameters (Expires, Signature, Key-Pair-Id)</li>
* </ul>
*
* <p>The URL is signed using the {@link UrlSigner} mechanism with the
* trusted signer credentials provided at construction time.
*
* @return The fully-qualified signed CloudFront URL
* @throws IllegalArgumentException if the expiration date has not been set or the distribution hostname is blank
*/
@Override
public String toString()
{
InternalUtils.checkNotNull(expireDate.getExpireDate(), "Expire date");
InternalUtils.checkNotBlank(distributionHostname, "Distribution hostname");
// An S3 origin reads "+" in a path as a space, so encode keys as S3UrlBuilder does
UrlBuilder builder = new UrlBuilder().usingPathEncoder(new QueryParameterEncoder());
// CloudFront rebuilds the signed resource from the request, so sign the host as the client sends it
builder.withHostname(AwsUrls.hostAsClientsSendIt(distributionHostname, ssl));
builder.withExactPathSegments(AwsUrls.objectKeySegments(key));
builder.usingSsl(ssl);
builder.addParameters(parameters);
builder.modeFullyQualified();
if (StringUtilsInternal.isNotBlank(attachmentFilename))
{
builder.addParameter("response-content-disposition", HttpUtils.createContentDispositionHeader("attachment", attachmentFilename));
}
if(StringUtilsInternal.isNotBlank(contentType))
{
builder.addParameter("response-content-type", contentType);
}
builder.usingUrlSigner(this::signUrl);
return builder.toString();
}
/**
* Signs the URL for CloudFront canned policy authentication.
* This method implements the UrlSigner functional interface.
*
* @param context The signing context containing the unsigned URL
* @return Map of CloudFront signing parameters (Expires, Signature, Key-Pair-Id)
*/
private Map<String, String> signUrl(UrlSigner.SigningContext context)
{
// Read the expiry once: a relative expiry moves with the clock, and the policy must match the Expires parameter.
long expires = expireDate.getExpireDate().getEpochSecond();
String cannedPolicy = String.format("{\"Statement\":[{\"Resource\":\"%s\",\"Condition\":{\"DateLessThan\":{\"AWS:EpochTime\":%s}}}]}", context.getUrl(), expires);
String signature = trustedSignerCredentials.sign(cannedPolicy);
Map<String, String> params = new LinkedHashMap<>();
params.put("Expires", String.valueOf(expires));
params.put("Signature", signature);
params.put("Key-Pair-Id", trustedSignerCredentials.accessKeyId);
return params;
}
/**
* Holds the CloudFront trusted signer credentials and provides signature generation.
*
* <p>This class encapsulates the RSA-SHA1 signing process used by CloudFront for
* authenticating canned policy URLs. The signature is:
* <ol>
* <li>Generated using SHA1WithRSA algorithm</li>
* <li>Base64 encoded</li>
* <li>Modified with CloudFront-safe character replacements (+ → -, = → _, / → ~)</li>
* </ol>
*/
public static class TrustedSignerCredentials
{
private final String accessKeyId;
private final PrivateKey privateKey;
private final String cryptoProvider;
/**
* Creates trusted signer credentials for CloudFront URL signing.
*
* @param accessKeyId The CloudFront key pair ID
* @param privateKey The RSA private key for signing
* @param cryptoProvider The JCE crypto provider name
* @throws RuntimeException if the crypto provider or algorithm is not available
*/
public TrustedSignerCredentials(String accessKeyId, PrivateKey privateKey, String cryptoProvider)
{
this.accessKeyId = accessKeyId;
this.privateKey = privateKey;
this.cryptoProvider = cryptoProvider;
try
{
// Reject an unusable provider or key here instead of on the first sign().
newSigner();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
// A Signature holds the state of one signing operation, so each call to sign() needs its own.
private Signature newSigner() throws GeneralSecurityException
{
Signature signer = Signature.getInstance("SHA1WithRSA", cryptoProvider);
signer.initSign(privateKey);
return signer;
}
/**
* Signs the given text using RSA-SHA1 and returns a CloudFront-compatible signature.
*
* <p>The signature process:
* <ol>
* <li>Sign the UTF-8 encoded text using RSA-SHA1</li>
* <li>Base64 encode the signature bytes</li>
* <li>Replace characters not safe for CloudFront URLs:
* <ul>
* <li>{@code +} is replaced with {@code -}</li>
* <li>{@code =} is replaced with {@code _}</li>
* <li>{@code /} is replaced with {@code ~}</li>
* </ul>
* </li>
* </ol>
*
* @param text The text to sign (typically the CloudFront canned policy JSON)
* @return The CloudFront-safe base64-encoded signature
* @throws RuntimeException if signing fails
*/
public String sign(String text)
{
try
{
Signature signer = newSigner();
signer.update(text.getBytes(StandardCharsets.UTF_8));
byte[] bytes = signer.sign();
String encodedBytes = Base64.getEncoder().encodeToString(bytes);
return encodedBytes.replace("+", "-").replace("=", "_").replace("/", "~");
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
}
}