forked from jooby-project/jooby
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCookie.java
More file actions
615 lines (556 loc) · 17.1 KB
/
Cookie.java
File metadata and controls
615 lines (556 loc) · 17.1 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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
/**
* Jooby https://jooby.io
* Apache License Version 2.0 https://jooby.io/LICENSE.txt
* Copyright 2014 Edgar Espina
*/
package io.jooby;
import com.typesafe.config.Config;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
import java.util.function.Consumer;
/**
* Response cookie implementation. Response are send it back to client using
* {@link Context#setResponseCookie(Cookie)}.
*
* @author edgar
* @since 2.0.0
*/
public class Cookie {
/** Algorithm name. */
public static final String HMAC_SHA256 = "HmacSHA256";
private static final DateTimeFormatter fmt = DateTimeFormatter
.ofPattern("EEE, dd-MMM-yyyy HH:mm:ss z", Locale.US)
.withZone(ZoneId.of("GMT"));
/** Cookie's name. */
private String name;
/** Cookie's value. */
private String value;
/** Cookie's domain. */
private String domain;
/** Cookie's path. */
private String path;
/** HttpOnly flag. */
private boolean httpOnly;
/** True, ensure that the session cookie is only transmitted via HTTPS. */
private boolean secure;
/**
* By default, <code>-1</code> is returned, which indicates that the cookie will persist until
* browser shutdown. In seconds.
*/
private long maxAge = -1;
/**
* Value for the 'SameSite' cookie attribute.
*
* @see <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite">
* https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite</a>
*/
private SameSite sameSite;
/**
* Creates a response cookie.
*
* @param name Cookie's name.
* @param value Cookie's value or <code>null</code>.
*/
public Cookie(@Nonnull String name, @Nullable String value) {
this.name = name;
this.value = value;
}
/**
* Creates a response cookie without a value.
*
* @param name Cookie's name.
*/
public Cookie(@Nonnull String name) {
this(name, null);
}
private Cookie(@Nonnull Cookie cookie) {
this.domain = cookie.domain;
this.value = cookie.value;
this.name = cookie.name;
this.maxAge = cookie.maxAge;
this.path = cookie.path;
this.secure = cookie.secure;
this.httpOnly = cookie.httpOnly;
this.sameSite = cookie.sameSite;
}
/**
* Copy all state from this cookie and creates a new cookie.
*
* @return New cookie.
*/
public @Nonnull Cookie clone() {
return new Cookie(this);
}
/**
* Cookie's name.
*
* @return Cookie's name.
*/
public @Nonnull String getName() {
return name;
}
/**
* Set cookie's name.
*
* @param name Cookie's name.
* @return This cookie.
*/
public @Nonnull Cookie setName(@Nonnull String name) {
this.name = name;
return this;
}
/**
* Cookie's value.
*
* @return Cookie's value.
*/
public @Nullable String getValue() {
return value;
}
/**
* Set cookie's value.
*
* @param value Cookie's value.
* @return This cookie.
*/
public @Nonnull Cookie setValue(@Nonnull String value) {
this.value = value;
return this;
}
/**
* Cookie's domain.
*
* @return Cookie's domain.
*/
public @Nullable String getDomain() {
return domain;
}
/**
* Get cookie's domain.
*
* @param domain Defaults cookie's domain.
* @return Cookie's domain..
*/
public @Nonnull String getDomain(@Nonnull String domain) {
return this.domain == null ? domain : domain;
}
/**
* Set cookie's domain.
*
* @param domain Cookie's domain.
* @return This cookie.
*/
public @Nonnull Cookie setDomain(@Nonnull String domain) {
this.domain = domain;
return this;
}
/**
* Cookie's path.
*
* @return Cookie's path.
*/
public @Nullable String getPath() {
return path;
}
/**
* Cookie's path.
*
* @param path Defaults path.
* @return Cookie's path.
*/
public @Nonnull String getPath(@Nonnull String path) {
return this.path == null ? path : this.path;
}
/**
* Set cookie's path.
*
* @param path Cookie's path.
* @return This cookie.
*/
public @Nonnull Cookie setPath(@Nonnull String path) {
this.path = path;
return this;
}
/**
* Cookie's http-only flag.
*
* @return Htto-only flag.
*/
public boolean isHttpOnly() {
return httpOnly;
}
/**
* Set cookie's http-only.
*
* @param httpOnly Cookie's http-only.
* @return This cookie.
*/
public Cookie setHttpOnly(boolean httpOnly) {
this.httpOnly = httpOnly;
return this;
}
/**
* Secure cookie.
*
* @return Secure cookie flag.
*/
public boolean isSecure() {
return secure;
}
/**
* Set cookie secure flag.
*
* @param secure Cookie's secure.
* @return This cookie.
* @throws IllegalArgumentException if {@code false} is specified and the 'SameSite'
* attribute value requires a secure cookie.
*/
public @Nonnull Cookie setSecure(boolean secure) {
if (sameSite != null && sameSite.requiresSecure() && !secure) {
throw new IllegalArgumentException("Cookies with SameSite=" + sameSite.getValue()
+ " must be flagged as Secure. Call Cookie.setSameSite(...) with an argument"
+ " allowing non-secure cookies before calling Cookie.setSecure(false).");
}
this.secure = secure;
return this;
}
/**
* Max age value:
*
* - <code>-1</code>: indicates a browser session. It is deleted when user closed the browser.
* - <code>0</code>: indicates a cookie has expired and browser must delete the cookie.
* - <code>positive value</code>: indicates the number of seconds from current date, where browser
* must expires the cookie.
*
* @return Max age, in seconds.
*/
public long getMaxAge() {
return maxAge;
}
/**
* Set max age value:
*
* - <code>-1</code>: indicates a browser session. It is deleted when user closed the browser.
* - <code>0</code>: indicates a cookie has expired and browser must delete the cookie.
* - <code>positive value</code>: indicates the number of seconds from current date, where browser
* must expires the cookie.
*
* @param maxAge Cookie max age.
* @return This options.
*/
public @Nonnull Cookie setMaxAge(@Nonnull Duration maxAge) {
return setMaxAge(maxAge.getSeconds());
}
/**
* Set max age value:
*
* - <code>-1</code>: indicates a browser session. It is deleted when user closed the browser.
* - <code>0</code>: indicates a cookie has expired and browser must delete the cookie.
* - <code>positive value</code>: indicates the number of seconds from current date, where browser
* must expires the cookie.
*
* @param maxAge Cookie max age, in seconds.
* @return This options.
*/
public @Nonnull Cookie setMaxAge(long maxAge) {
if (maxAge >= 0) {
this.maxAge = maxAge;
} else {
this.maxAge = -1;
}
return this;
}
/**
* Returns the value for the 'SameSite' parameter.
* <ul>
* <li>{@link SameSite#LAX} - Cookies are allowed to be sent with top-level navigations and
* will be sent along with GET request initiated by third party website. This is the default
* value in modern browsers.</li>
* <li>{@link SameSite#STRICT} - Cookies will only be sent in a first-party context and not be
* sent along with requests initiated by third party websites.</li>
* <li>{@link SameSite#NONE} - Cookies will be sent in all contexts, i.e sending cross-origin
* is allowed. Requires the {@code Secure} attribute in latest browser versions.</li>
* <li>{@code null} - Not specified.</li>
* </ul>
*
* @return the value for 'SameSite' parameter.
* @see #setSecure(boolean)
* @see <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite">
* https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite</a>
*/
@Nullable
public SameSite getSameSite() {
return sameSite;
}
/**
* Sets the value for the 'SameSite' parameter.
* <ul>
* <li>{@link SameSite#LAX} - Cookies are allowed to be sent with top-level navigations and
* will be sent along with GET request initiated by third party website. This is the default
* value in modern browsers.</li>
* <li>{@link SameSite#STRICT} - Cookies will only be sent in a first-party context and not be
* sent along with requests initiated by third party websites.</li>
* <li>{@link SameSite#NONE} - Cookies will be sent in all contexts, i.e sending cross-origin
* is allowed. Requires the {@code Secure} attribute in latest browser versions.</li>
* <li>{@code null} - Not specified.</li>
* </ul>
*
* @param sameSite the value for the 'SameSite' parameter.
* @return this instance.
* @throws IllegalArgumentException if a value requiring a secure cookie is specified and this
* cookie is not flagged as secure.
* @see #setSecure(boolean)
* @see <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite">
* https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite</a>
*/
public Cookie setSameSite(@Nullable SameSite sameSite) {
if (sameSite != null && sameSite.requiresSecure() && !isSecure()) {
throw new IllegalArgumentException("Cookies with SameSite=" + sameSite.getValue()
+ " must be flagged as Secure. Call Cookie.setSecure(true)"
+ " before calling Cookie.setSameSite(...).");
}
this.sameSite = sameSite;
return this;
}
@Override public String toString() {
StringBuilder buff = new StringBuilder();
buff.append(name).append("=");
if (value != null) {
buff.append(value);
}
return buff.toString();
}
/**
* Generates a cookie string. This is the value we sent to the client as <code>Set-Cookie</code>
* header.
*
* @return Cookie string.
*/
public @Nonnull String toCookieString() {
StringBuilder sb = new StringBuilder();
// name = value
append(sb, name);
sb.append("=");
if (value != null) {
append(sb, value);
}
// Path
if (path != null) {
sb.append(";Path=");
append(sb, path);
}
// Domain
if (domain != null) {
sb.append(";Domain=");
append(sb, domain);
}
// SameSite
if (sameSite != null) {
sb.append(";SameSite=");
append(sb, sameSite.getValue());
}
// Secure
if (secure) {
sb.append(";Secure");
}
// HttpOnly
if (httpOnly) {
sb.append(";HttpOnly");
}
// Max-Age
if (maxAge >= 0) {
sb.append(";Max-Age=").append(maxAge);
/** Old browsers don't support Max-Age. */
long expires;
if (maxAge > 0) {
expires = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(maxAge);
} else {
expires = 0;
}
sb.append(";Expires=").append(fmt.format(Instant.ofEpochMilli(expires)));
}
return sb.toString();
}
/**
* Sign a value using a secret key. A value and secret key are required. Sign is done with
* {@link #HMAC_SHA256}.
* Signed value looks like:
*
* <pre>
* [signed value] '|' [raw value]
* </pre>
*
* @param value A value to sign.
* @param secret A secret key.
* @return A signed value.
*/
public static @Nonnull String sign(final @Nonnull String value, final @Nonnull String secret) {
try {
Mac mac = Mac.getInstance(HMAC_SHA256);
mac.init(new SecretKeySpec(secret.getBytes(), HMAC_SHA256));
byte[] bytes = mac.doFinal(value.getBytes());
return Base64.getEncoder().withoutPadding().encodeToString(bytes) + "|" + value;
} catch (Exception x) {
throw SneakyThrows.propagate(x);
}
}
/**
* Un-sign a value, previously signed with {@link #sign(String, String)}.
* Produces a nonnull value or <code>null</code> for invalid.
*
* @param value A signed value.
* @param secret A secret key.
* @return A new signed value or null.
*/
public static @Nullable String unsign(final @Nonnull String value, final @Nonnull String secret) {
int sep = value.indexOf("|");
if (sep <= 0) {
return null;
}
String str = value.substring(sep + 1);
return sign(str, secret).equals(value) ? str : null;
}
/**
* Encode a hash into cookie value, like: <code>k1=v1&...&kn=vn</code>. Also,
* <code>key</code> and <code>value</code> are encoded using {@link URLEncoder}.
*
* @param attributes Map to encode.
* @return URL encoded from map attributes.
*/
public static @Nonnull String encode(@Nullable Map<String, String> attributes) {
if (attributes == null || attributes.size() == 0) {
return "";
}
try {
StringBuilder joiner = new StringBuilder();
String enc = StandardCharsets.UTF_8.name();
for (Map.Entry<String, String> attribute : attributes.entrySet()) {
joiner.append(URLEncoder.encode(attribute.getKey(), enc))
.append('=')
.append(URLEncoder.encode(attribute.getValue(), enc))
.append('&');
}
if (joiner.length() > 0) {
joiner.setLength(joiner.length() - 1);
}
return joiner.toString();
} catch (UnsupportedEncodingException x) {
throw SneakyThrows.propagate(x);
}
}
/**
* Decode a cookie value using, like: <code>k=v</code>, multiple <code>k=v</code> pair are
* separated by <code>&</code>. Also, <code>k</code> and <code>v</code> are decoded using
* {@link URLDecoder}.
*
* @param value URL encoded value.
* @return Decoded as map.
*/
public static @Nonnull Map<String, String> decode(@Nullable String value) {
if (value == null || value.length() == 0) {
return Collections.emptyMap();
}
try {
Map<String, String> attributes = new HashMap<>();
String enc = StandardCharsets.UTF_8.name();
int start = 0;
int len = value.length();
do {
int end = value.indexOf('&', start + 1);
if (end < 0) {
end = len;
}
// parse attribute
int eq = value.indexOf('=', start);
if (eq > 0 && eq < len - 1) {
attributes.put(URLDecoder.decode(value.substring(start, eq), enc),
URLDecoder.decode(value.substring(eq + 1, end), enc));
}
start = end + 1;
} while (start < len);
return attributes.isEmpty()
? Collections.emptyMap()
: Collections.unmodifiableMap(attributes);
} catch (UnsupportedEncodingException x) {
throw SneakyThrows.propagate(x);
}
}
/**
* Attempt to create/parse a cookie from application configuration object. The namespace given
* must be present and must defined a <code>name</code> property.
*
* The namespace might optionally defined: value, path, domain, secure, httpOnly and maxAge.
*
* @param namespace Cookie namespace/prefix.
* @param conf Configuration object.
* @return Parsed cookie or empty.
*/
public static @Nonnull Optional<Cookie> create(@Nonnull String namespace, @Nonnull Config conf) {
if (conf.hasPath(namespace)) {
Cookie cookie = new Cookie(conf.getString(namespace + ".name"));
value(conf, namespace + ".value", Config::getString, cookie::setValue);
value(conf, namespace + ".path", Config::getString, cookie::setPath);
value(conf, namespace + ".domain", Config::getString, cookie::setDomain);
value(conf, namespace + ".secure", Config::getBoolean, cookie::setSecure);
value(conf, namespace + ".httpOnly", Config::getBoolean, cookie::setHttpOnly);
value(conf, namespace + ".maxAge", (c, path) -> c.getDuration(path, TimeUnit.SECONDS),
cookie::setMaxAge);
value(conf, namespace + ".sameSite", (c, path) -> SameSite.of(c.getString(path)),
cookie::setSameSite);
return Optional.of(cookie);
}
return Optional.empty();
}
private static <T> void value(Config conf, String name, BiFunction<Config, String, T> mapper,
Consumer<T> consumer) {
if (conf.hasPath(name)) {
consumer.accept(mapper.apply(conf, name));
}
}
private void append(StringBuilder sb, String str) {
if (needQuote(str)) {
sb.append('"');
for (int i = 0; i < str.length(); ++i) {
char c = str.charAt(i);
if (c == '"' || c == '\\') {
sb.append('\\');
}
sb.append(c);
}
sb.append('"');
} else {
sb.append(str);
}
}
private static boolean needQuote(final String value) {
if (value.length() > 1 && value.charAt(0) == '"' && value.charAt(value.length() - 1) == '"') {
return false;
}
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
// "\",;\\ \t"
if (c == '\"' || c == ',' || c == ';' || c == '\\' || c == ' ' || c == '\t') {
return true;
}
}
return false;
}
}