001/* 002 * Copyright 2022-2026 Revetware LLC. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package com.soklet; 018 019import org.jspecify.annotations.NonNull; 020import org.jspecify.annotations.Nullable; 021 022import javax.annotation.concurrent.NotThreadSafe; 023import javax.annotation.concurrent.ThreadSafe; 024import java.net.HttpCookie; 025import java.time.Duration; 026import java.time.Instant; 027import java.util.ArrayList; 028import java.util.List; 029import java.util.Objects; 030import java.util.Optional; 031import java.util.stream.Collectors; 032 033import static com.soklet.Utilities.printableChar; 034import static com.soklet.Utilities.printableString; 035import static com.soklet.Utilities.trimAggressivelyToNull; 036import static java.lang.String.format; 037import static java.util.Objects.requireNonNull; 038 039/** 040 * HTTP "response" Cookie representation which supports {@code Set-Cookie} header encoding. 041 * <p> 042 * Threadsafe instances can be acquired via these builder factory methods: 043 * <ul> 044 * <li>{@link #with(String, String)} (builder primed with name and value)</li> 045 * <li>{@link #withName(String)} (builder primed with name only)</li> 046 * </ul> 047 * 048 * @author <a href="https://www.revetkn.com">Mark Allen</a> 049 */ 050@ThreadSafe 051public final class ResponseCookie { 052 @NonNull 053 private final String name; 054 @Nullable 055 private final String value; 056 @Nullable 057 private final Duration maxAge; 058 @Nullable 059 private final Instant expires; 060 @Nullable 061 private final String domain; 062 @Nullable 063 private final String path; 064 @NonNull 065 private final Boolean secure; 066 @NonNull 067 private final Boolean httpOnly; 068 @Nullable 069 private final SameSite sameSite; 070 @Nullable 071 private final Priority priority; 072 @NonNull 073 private final Boolean partitioned; 074 075 /** 076 * Acquires a builder for {@link ResponseCookie} instances. 077 * 078 * @param name the cookie name 079 * @param value the cookie value, or {@code null} to leave the value unspecified 080 * @return the builder 081 */ 082 @NonNull 083 public static Builder with(@NonNull String name, 084 @Nullable String value) { 085 requireNonNull(name); 086 return new Builder(name, value); 087 } 088 089 /** 090 * Acquires a builder for {@link ResponseCookie} instances without specifying the cookie's value. 091 * 092 * @param name the cookie name 093 * @return the builder 094 */ 095 @NonNull 096 public static Builder withName(@NonNull String name) { 097 requireNonNull(name); 098 return new Builder(name); 099 } 100 101 /** 102 * Vends a mutable copier seeded with this instance's data, suitable for building new instances. 103 * 104 * @return a copier for this instance 105 */ 106 @NonNull 107 public Copier copy() { 108 return new Copier(this); 109 } 110 111 /** 112 * Given a {@code Set-Cookie} header representation, provide a {@link ResponseCookie} that matches it. 113 * <p> 114 * An example of a {@code Set-Cookie} header representation is {@code Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>; Secure; HttpOnly} 115 * <p> 116 * Each header should describe one cookie. Folded headers containing multiple cookies are not supported. 117 * Invalid {@code Max-Age} attributes are ignored; nonpositive values expire the cookie immediately. 118 * <p> 119 * See <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie">https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie</a> for details. 120 * 121 * @param setCookieHeaderRepresentation a {@code Set-Cookie} header representation 122 * @return a {@link ResponseCookie} representation of the {@code Set-Cookie} header, or {@link Optional#empty()} if the header is null, empty, or does not include cookie data 123 * @throws IllegalArgumentException if the {@code Set-Cookie} header representation is malformed 124 */ 125 @NonNull 126 public static Optional<@NonNull ResponseCookie> fromSetCookieHeaderRepresentation(@Nullable String setCookieHeaderRepresentation) { 127 setCookieHeaderRepresentation = setCookieHeaderRepresentation == null ? null : setCookieHeaderRepresentation.trim(); 128 129 if (setCookieHeaderRepresentation == null || setCookieHeaderRepresentation.length() == 0) 130 return Optional.empty(); 131 132 String normalizedSetCookieHeaderRepresentation = stripSetCookiePrefix(setCookieHeaderRepresentation); 133 134 if (normalizedSetCookieHeaderRepresentation == null || normalizedSetCookieHeaderRepresentation.length() == 0) 135 return Optional.empty(); 136 137 List<String> components = List.of(normalizedSetCookieHeaderRepresentation.split(";", -1)); 138 ParsedSetCookieAttributes attributes = parseSetCookieAttributes(components); 139 // HttpCookie throws on malformed Max-Age and uses different expiry-date 140 // rules. Parse explicit expiry attributes ourselves while retaining its 141 // existing handling of the cookie pair and other standard attributes. 142 List<String> httpCookieComponents = new ArrayList<>(); 143 httpCookieComponents.add(components.get(0)); 144 for (int i = 1; i < components.size(); i++) { 145 String component = components.get(i); 146 int equalsIndex = component.indexOf('='); 147 String name = trimSetCookieComponent(equalsIndex == -1 ? component : component.substring(0, equalsIndex)); 148 if (!"max-age".equalsIgnoreCase(name)) 149 httpCookieComponents.add(component); 150 } 151 List<HttpCookie> cookies = HttpCookie.parse(String.join(";", httpCookieComponents)); 152 153 if (cookies.size() == 0) 154 return Optional.empty(); 155 156 // Folded headers are unsupported; preserve the existing first-cookie selection. 157 HttpCookie httpCookie = cookies.get(0); 158 159 return Optional.of(ResponseCookie.with(httpCookie.getName(), httpCookie.getValue()) 160 .maxAge(attributes.maxAge) 161 .expires(attributes.getExpires().orElse(null)) 162 .domain(httpCookie.getDomain()) 163 .httpOnly(httpCookie.isHttpOnly()) 164 .secure(httpCookie.getSecure()) 165 .path(httpCookie.getPath()) 166 .sameSite(attributes.getSameSite().orElse(null)) 167 .priority(attributes.getPriority().orElse(null)) 168 .partitioned(attributes.getPartitioned()) 169 .build()); 170 } 171 172 @Nullable 173 private static String stripSetCookiePrefix(@NonNull String setCookieHeaderRepresentation) { 174 requireNonNull(setCookieHeaderRepresentation); 175 176 String trimmed = trimAggressivelyToNull(setCookieHeaderRepresentation); 177 178 if (trimmed == null) 179 return null; 180 181 String prefix = "set-cookie:"; 182 183 if (trimmed.length() >= prefix.length() 184 && trimmed.regionMatches(true, 0, prefix, 0, prefix.length())) 185 return trimAggressivelyToNull(trimmed.substring(prefix.length())); 186 187 return trimmed; 188 } 189 190 @NonNull 191 private static ParsedSetCookieAttributes parseSetCookieAttributes(@NonNull List<@NonNull String> components) { 192 ParsedSetCookieAttributes attributes = new ParsedSetCookieAttributes(); 193 194 if (components.size() <= 1) 195 return attributes; 196 197 for (int i = 1; i < components.size(); i++) { 198 String component = trimSetCookieComponent(components.get(i)); 199 if (component == null) 200 continue; 201 202 int equalsIndex = component.indexOf('='); 203 String attributeName = trimSetCookieComponent(equalsIndex == -1 ? component : component.substring(0, equalsIndex)); 204 205 if (attributeName == null) 206 continue; 207 208 String attributeValue = equalsIndex == -1 ? null : trimSetCookieComponent(component.substring(equalsIndex + 1)); 209 210 // Preserve explicit Max-Age only: HttpCookie also synthesizes it from 211 // Expires using different date rules. That can incorrectly override a 212 // valid cookie expiry. Nonpositive Max-Age means immediate expiry. 213 if ("max-age".equalsIgnoreCase(attributeName)) { 214 if (attributes.maxAge == null && attributeValue != null) 215 attributes.maxAge = parseMaxAge(stripOptionalQuotes(attributeValue)); 216 continue; 217 } 218 219 if ("samesite".equalsIgnoreCase(attributeName)) { 220 if (attributes.sameSite == null && attributeValue != null) { 221 attributeValue = stripOptionalQuotes(attributeValue); 222 attributes.sameSite = SameSite.fromHeaderRepresentation(attributeValue).orElse(null); 223 } 224 continue; 225 } 226 227 if ("expires".equalsIgnoreCase(attributeName)) { 228 if (attributes.expires == null && attributeValue != null) { 229 attributeValue = stripOptionalQuotes(attributeValue); 230 attributes.expires = CookieDate.parse(attributeValue).orElse(null); 231 } 232 continue; 233 } 234 235 if ("priority".equalsIgnoreCase(attributeName)) { 236 if (attributes.priority == null && attributeValue != null) { 237 attributeValue = stripOptionalQuotes(attributeValue); 238 attributes.priority = Priority.fromHeaderRepresentation(attributeValue).orElse(null); 239 } 240 continue; 241 } 242 243 if ("partitioned".equalsIgnoreCase(attributeName)) 244 attributes.partitioned = true; 245 } 246 247 return attributes; 248 } 249 250 @Nullable 251 private static String trimSetCookieComponent(@NonNull String value) { 252 int start = 0; 253 int end = value.length(); 254 while (start < end && (Character.isWhitespace(value.charAt(start)) || Character.isSpaceChar(value.charAt(start)))) 255 start++; 256 while (end > start && (Character.isWhitespace(value.charAt(end - 1)) || Character.isSpaceChar(value.charAt(end - 1)))) 257 end--; 258 return start == end ? null : value.substring(start, end); 259 } 260 261 @Nullable 262 private static Duration parseMaxAge(@NonNull String value) { 263 boolean negative = value.startsWith("-"); 264 int start = negative ? 1 : 0; 265 if (start == value.length()) 266 return null; 267 long seconds = 0; 268 for (int i = start; i < value.length(); i++) { 269 char character = value.charAt(i); 270 if (character < '0' || character > '9') 271 return null; 272 int digit = character - '0'; 273 // Very distant expiration dates saturate instead of overflowing. 274 seconds = seconds > (Long.MAX_VALUE - digit) / 10 ? Long.MAX_VALUE : seconds * 10 + digit; 275 } 276 return Duration.ofSeconds(negative ? 0 : seconds); 277 } 278 279 @NonNull 280 private static String stripOptionalQuotes(@NonNull String value) { 281 requireNonNull(value); 282 283 if (value.length() >= 2 && value.startsWith("\"") && value.endsWith("\"")) 284 return value.substring(1, value.length() - 1); 285 286 return value; 287 } 288 289 private ResponseCookie(@NonNull Builder builder) { 290 requireNonNull(builder); 291 292 this.name = builder.name; 293 this.value = builder.value; 294 this.maxAge = builder.maxAge; 295 this.expires = builder.expires; 296 this.domain = builder.domain; 297 this.path = trimAggressivelyToNull(builder.path); // Can't specify blank paths. Must be null (omitted) or start with "/" 298 this.secure = builder.secure == null ? false : builder.secure; 299 this.httpOnly = builder.httpOnly == null ? false : builder.httpOnly; 300 this.sameSite = builder.sameSite; 301 this.priority = builder.priority; 302 this.partitioned = builder.partitioned == null ? false : builder.partitioned; 303 304 // Extra validation to ensure we are not creating cookies that are illegal according to the spec 305 306 Rfc6265Utils.validateCookieName(getName()); 307 Rfc6265Utils.validateCookieValue(getValue().orElse(null)); 308 Rfc6265Utils.validateDomain(getDomain().orElse(null)); 309 Rfc6265Utils.validatePath(getPath().orElse(null)); 310 311 if (this.maxAge != null && this.maxAge.isNegative()) 312 throw new IllegalArgumentException("Max-Age must be >= 0"); 313 314 if (this.sameSite == SameSite.NONE && (this.secure == null || !this.secure)) 315 throw new IllegalArgumentException(format("Specifying %s value %s.%s requires that you also set secure=true, otherwise browsers will likely discard the cookie", 316 ResponseCookie.class.getSimpleName(), SameSite.class.getSimpleName(), SameSite.NONE.name())); 317 318 if (this.name.startsWith("__Secure-") && !this.secure) 319 throw new IllegalArgumentException("__Secure- cookies require secure=true"); 320 321 if (this.name.startsWith("__Host-")) { 322 if (!this.secure) 323 throw new IllegalArgumentException("__Host- cookies require secure=true"); 324 325 if (!"/".equals(this.path)) 326 throw new IllegalArgumentException("__Host- cookies require path=\"/\""); 327 328 if (this.domain != null) 329 throw new IllegalArgumentException("__Host- cookies must not specify a domain"); 330 } 331 332 if (this.partitioned) { 333 if (this.secure == null || !this.secure) 334 throw new IllegalArgumentException("Partitioned cookies require secure=true"); 335 336 String cookiePath = getPath().orElse(null); 337 if (cookiePath == null || !cookiePath.equals("/")) 338 throw new IllegalArgumentException("Partitioned cookies require path=\"/\""); 339 340 if (this.sameSite != SameSite.NONE) 341 throw new IllegalArgumentException("Partitioned cookies require SameSite=None"); 342 } 343 } 344 345 /** 346 * Generates a {@code Set-Cookie} header representation of this response cookie, for example {@code Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>; Secure; HttpOnly} 347 * <p> 348 * See <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie">https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie</a> for details. 349 * 350 * @return this response cookie in {@code Set-Cookie} header format 351 */ 352 @NonNull 353 public String toSetCookieHeaderRepresentation() { 354 List<String> components = new ArrayList<>(10); 355 356 components.add(format("%s=%s", getName(), getValue().orElse(""))); 357 358 if (getPath().isPresent()) 359 components.add(format("Path=%s", getPath().get())); 360 361 if (getDomain().isPresent()) 362 components.add(format("Domain=%s", getDomain().get())); 363 364 long maxAge = getMaxAge().isPresent() ? getMaxAge().get().toSeconds() : -1; 365 366 if (maxAge >= 0) 367 components.add("Max-Age=" + maxAge); 368 369 if (getExpires().isPresent()) 370 components.add(format("Expires=%s", HttpDate.toHeaderValue(getExpires().get()))); 371 372 if (getSecure()) 373 components.add("Secure"); 374 375 if (getHttpOnly()) 376 components.add("HttpOnly"); 377 378 if (getSameSite().isPresent()) 379 components.add(format("SameSite=%s", getSameSite().get().getHeaderRepresentation())); 380 381 if (getPriority().isPresent()) 382 components.add(format("Priority=%s", getPriority().get().getHeaderRepresentation())); 383 384 if (getPartitioned()) 385 components.add("Partitioned"); 386 387 return components.stream().collect(Collectors.joining("; ")); 388 } 389 390 @Override 391 public int hashCode() { 392 return Objects.hash( 393 getName(), 394 getValue(), 395 getMaxAge(), 396 getExpires(), 397 getDomain(), 398 getPath(), 399 getSecure(), 400 getHttpOnly(), 401 getSameSite(), 402 getPriority(), 403 getPartitioned() 404 ); 405 } 406 407 @Override 408 public boolean equals(@Nullable Object object) { 409 if (this == object) 410 return true; 411 412 if (!(object instanceof ResponseCookie responseCookie)) 413 return false; 414 415 return Objects.equals(getName(), responseCookie.getName()) 416 && Objects.equals(getValue(), responseCookie.getValue()) 417 && Objects.equals(getMaxAge(), responseCookie.getMaxAge()) 418 && Objects.equals(getExpires(), responseCookie.getExpires()) 419 && Objects.equals(getDomain(), responseCookie.getDomain()) 420 && Objects.equals(getPath(), responseCookie.getPath()) 421 && Objects.equals(getSecure(), responseCookie.getSecure()) 422 && Objects.equals(getHttpOnly(), responseCookie.getHttpOnly()) 423 && Objects.equals(getSameSite(), responseCookie.getSameSite()) 424 && Objects.equals(getPriority(), responseCookie.getPriority()) 425 && Objects.equals(getPartitioned(), responseCookie.getPartitioned()); 426 } 427 428 @Override 429 @NonNull 430 public String toString() { 431 return format("%s{name=<redacted>, value=<redacted>, maxAge=%s, " 432 + "expires=%s, domain=%s, path=%s, secure=%s, httpOnly=%s, " 433 + "sameSite=%s, priority=%s, partitioned=%s}", 434 getClass().getSimpleName(), getMaxAge().orElse(null), 435 getExpires().orElse(null), 436 getDomain().isPresent() ? "<redacted>" : null, 437 getPath().isPresent() ? "<redacted>" : null, getSecure(), 438 getHttpOnly(), getSameSite().orElse(null), 439 getPriority().orElse(null), getPartitioned()); 440 } 441 442 /** 443 * Gets the cookie's name. 444 * 445 * @return the name of the cookie 446 */ 447 @NonNull 448 public String getName() { 449 return this.name; 450 } 451 452 /** 453 * Gets the cookie's value, if present. 454 * 455 * @return the value of the cookie, or {@link Optional#empty()} if there is none 456 */ 457 @NonNull 458 public Optional<@NonNull String> getValue() { 459 return Optional.ofNullable(this.value); 460 } 461 462 /** 463 * Gets the cookie's {@code Max-Age} value expressed as a {@link Duration}, if present. 464 * 465 * @return the {@code Max-Age} value of the cookie, or {@link Optional#empty()} if there is none 466 */ 467 @NonNull 468 public Optional<@NonNull Duration> getMaxAge() { 469 return Optional.ofNullable(this.maxAge); 470 } 471 472 /** 473 * Gets the cookie's {@code Expires} value, if present. 474 * 475 * @return the {@code Expires} value of the cookie, or {@link Optional#empty()} if there is none 476 */ 477 @NonNull 478 public Optional<@NonNull Instant> getExpires() { 479 return Optional.ofNullable(this.expires); 480 } 481 482 /** 483 * Gets the cookie's {@code Domain} value, if present. 484 * 485 * @return the {@code Domain} value of the cookie, or {@link Optional#empty()} if there is none 486 */ 487 @NonNull 488 public Optional<@NonNull String> getDomain() { 489 return Optional.ofNullable(this.domain); 490 } 491 492 /** 493 * Gets the cookie's {@code Path} value, if present. 494 * 495 * @return the {@code Path} value of the cookie, or {@link Optional#empty()} if there is none 496 */ 497 @NonNull 498 public Optional<@NonNull String> getPath() { 499 return Optional.ofNullable(this.path); 500 } 501 502 /** 503 * Gets the cookie's {@code Secure} flag, if present. 504 * 505 * @return {@code true} if the {@code Secure} flag of the cookie is present, {@code false} otherwise 506 */ 507 @NonNull 508 public Boolean getSecure() { 509 return this.secure; 510 } 511 512 /** 513 * Gets the cookie's {@code HttpOnly} flag, if present. 514 * 515 * @return {@code true} if the {@code HttpOnly} flag of the cookie is present, {@code false} otherwise 516 */ 517 @NonNull 518 public Boolean getHttpOnly() { 519 return this.httpOnly; 520 } 521 522 /** 523 * Gets the cookie's {@code SameSite} value, if present. 524 * 525 * @return the {@code SameSite} value of the cookie, or {@link Optional#empty()} if there is none 526 */ 527 @NonNull 528 public Optional<@NonNull SameSite> getSameSite() { 529 return Optional.ofNullable(this.sameSite); 530 } 531 532 /** 533 * Gets the cookie's {@code Priority} value, if present. 534 * 535 * @return the {@code Priority} value of the cookie, or {@link Optional#empty()} if there is none 536 */ 537 @NonNull 538 public Optional<@NonNull Priority> getPriority() { 539 return Optional.ofNullable(this.priority); 540 } 541 542 /** 543 * Gets the cookie's {@code Partitioned} flag. 544 * 545 * @return {@code true} if the {@code Partitioned} flag is present, {@code false} otherwise 546 */ 547 @NonNull 548 public Boolean getPartitioned() { 549 return this.partitioned; 550 } 551 552 /** 553 * Values which control whether a response cookie is sent with cross-site requests, providing some protection against cross-site request forgery attacks (CSRF). 554 * <p> 555 * See <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value">https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value</a> for details. 556 * 557 * <p> 558 * This type may gain reviewed constants in Soklet 4.x; use a forward-compatible default when switching over its values. 559 * 560 * @author <a href="https://www.revetkn.com">Mark Allen</a> 561 */ 562 public enum SameSite { 563 /** 564 * Means that the browser sends the cookie only for same-site requests, that is, requests originating from the same site that set the cookie. 565 * If a request originates from a different domain or scheme (even with the same domain), no cookies with the {@code SameSite=Strict} attribute are sent. 566 */ 567 STRICT("Strict"), 568 /** 569 * Means that the cookie is not sent on cross-site requests, such as on requests to load images or frames, but is sent when a user is navigating to the origin site from an external site (for example, when following a link). 570 * This is the default behavior if the {@code SameSite} attribute is not specified. 571 */ 572 LAX("Lax"), 573 /** 574 * Means that the browser sends the cookie with both cross-site and same-site requests. 575 * The {@code Secure} attribute must also be set when setting this value, like so {@code SameSite=None; Secure}. If {@code Secure} is missing, an error will be logged. 576 */ 577 NONE("None"); 578 579 @NonNull 580 private final String headerRepresentation; 581 582 SameSite(@NonNull String headerRepresentation) { 583 requireNonNull(headerRepresentation); 584 this.headerRepresentation = headerRepresentation; 585 } 586 587 /** 588 * Returns the {@link SameSite} enum value that matches the corresponding {@code SameSite} response header value representation (one of {@code Strict}, {@code Lax}, or {@code None} - case-insensitive). 589 * 590 * @param headerRepresentation a case-insensitive HTTP header value - one of {@code Strict}, {@code Lax}, or {@code None} 591 * @return the enum value that corresponds to the given the header representation, or {@link Optional#empty()} if none matches 592 */ 593 @NonNull 594 public static Optional<@NonNull SameSite> fromHeaderRepresentation(@NonNull String headerRepresentation) { 595 requireNonNull(headerRepresentation); 596 597 headerRepresentation = headerRepresentation.trim(); 598 599 for (SameSite sameSite : values()) 600 if (headerRepresentation.equalsIgnoreCase(sameSite.getHeaderRepresentation())) 601 return Optional.of(sameSite); 602 603 return Optional.empty(); 604 } 605 606 /** 607 * The HTTP header value that corresponds to this enum value - one of {@code Strict}, {@code Lax}, or {@code None}. 608 * 609 * @return the HTTP header value for this enum 610 */ 611 @NonNull 612 public String getHeaderRepresentation() { 613 return this.headerRepresentation; 614 } 615 } 616 617 /** 618 * Represents the {@code Priority} response cookie attribute. 619 * <p> 620 * This type may gain reviewed constants in Soklet 4.x; use a forward-compatible default when switching over its values. 621 * 622 */ 623 public enum Priority { 624 LOW("Low"), 625 MEDIUM("Medium"), 626 HIGH("High"); 627 628 @NonNull 629 private final String headerRepresentation; 630 631 Priority(@NonNull String headerRepresentation) { 632 requireNonNull(headerRepresentation); 633 this.headerRepresentation = headerRepresentation; 634 } 635 636 @NonNull 637 public String getHeaderRepresentation() { 638 return this.headerRepresentation; 639 } 640 641 @NonNull 642 public static Optional<@NonNull Priority> fromHeaderRepresentation(@NonNull String headerRepresentation) { 643 requireNonNull(headerRepresentation); 644 645 String normalized = headerRepresentation.trim(); 646 647 for (Priority priority : values()) 648 if (normalized.equalsIgnoreCase(priority.getHeaderRepresentation())) 649 return Optional.of(priority); 650 651 return Optional.empty(); 652 } 653 } 654 655 /** 656 * Builder used to construct instances of {@link ResponseCookie} via {@link ResponseCookie#withName(String)} 657 * or {@link ResponseCookie#with(String, String)}. 658 * <p> 659 * This class is intended for use by a single thread. 660 * 661 * @author <a href="https://www.revetkn.com">Mark Allen</a> 662 */ 663 @NotThreadSafe 664 public static final class Builder { 665 @NonNull 666 private String name; 667 @Nullable 668 private String value; 669 @Nullable 670 private Duration maxAge; 671 @Nullable 672 private Instant expires; 673 @Nullable 674 private String domain; 675 @Nullable 676 private String path; 677 @Nullable 678 private Boolean secure; 679 @Nullable 680 private Boolean httpOnly; 681 @Nullable 682 private SameSite sameSite; 683 @Nullable 684 private Priority priority; 685 @Nullable 686 private Boolean partitioned; 687 688 protected Builder(@NonNull String name) { 689 requireNonNull(name); 690 this.name = name; 691 } 692 693 protected Builder(@NonNull String name, 694 @Nullable String value) { 695 requireNonNull(name); 696 this.name = name; 697 this.value = value; 698 } 699 700 @NonNull 701 public Builder name(@NonNull String name) { 702 requireNonNull(name); 703 this.name = name; 704 return this; 705 } 706 707 /** 708 * Configures the cookie value. 709 * 710 * @param value cookie value, or {@code null} to leave the value unspecified 711 * @return this builder 712 */ 713 @NonNull 714 public Builder value(@Nullable String value) { 715 this.value = value; 716 return this; 717 } 718 719 /** 720 * Configures the cookie's {@code Max-Age} attribute. 721 * 722 * @param maxAge maximum age, or {@code null} to omit {@code Max-Age} 723 * @return this builder 724 */ 725 @NonNull 726 public Builder maxAge(@Nullable Duration maxAge) { 727 this.maxAge = maxAge; 728 return this; 729 } 730 731 /** 732 * Configures the cookie's {@code Expires} attribute. 733 * 734 * @param expires expiration time, or {@code null} to omit {@code Expires} 735 * @return this builder 736 */ 737 @NonNull 738 public Builder expires(@Nullable Instant expires) { 739 this.expires = expires; 740 return this; 741 } 742 743 /** 744 * Configures the cookie's {@code Domain} attribute. 745 * 746 * @param domain cookie domain, or {@code null} to omit {@code Domain} 747 * @return this builder 748 */ 749 @NonNull 750 public Builder domain(@Nullable String domain) { 751 this.domain = domain; 752 return this; 753 } 754 755 /** 756 * Configures the cookie's {@code Path} attribute. 757 * 758 * @param path cookie path, or {@code null} or blank to omit {@code Path} 759 * @return this builder 760 */ 761 @NonNull 762 public Builder path(@Nullable String path) { 763 this.path = path; 764 return this; 765 } 766 767 /** 768 * Configures the cookie's {@code Secure} flag. 769 * 770 * @param secure whether to include {@code Secure}, or {@code null} to use the default of {@code false} 771 * @return this builder 772 */ 773 @NonNull 774 public Builder secure(@Nullable Boolean secure) { 775 this.secure = secure; 776 return this; 777 } 778 779 /** 780 * Configures the cookie's {@code HttpOnly} flag. 781 * 782 * @param httpOnly whether to include {@code HttpOnly}, or {@code null} to use the default of {@code false} 783 * @return this builder 784 */ 785 @NonNull 786 public Builder httpOnly(@Nullable Boolean httpOnly) { 787 this.httpOnly = httpOnly; 788 return this; 789 } 790 791 /** 792 * Configures the cookie's {@code SameSite} attribute. 793 * 794 * @param sameSite same-site policy, or {@code null} to omit {@code SameSite} 795 * @return this builder 796 */ 797 @NonNull 798 public Builder sameSite(@Nullable SameSite sameSite) { 799 this.sameSite = sameSite; 800 return this; 801 } 802 803 /** 804 * Configures the cookie's {@code Priority} attribute. 805 * 806 * @param priority cookie priority, or {@code null} to omit {@code Priority} 807 * @return this builder 808 */ 809 @NonNull 810 public Builder priority(@Nullable Priority priority) { 811 this.priority = priority; 812 return this; 813 } 814 815 /** 816 * Configures the cookie's {@code Partitioned} flag. 817 * 818 * @param partitioned whether to include {@code Partitioned}, or {@code null} to use the default of {@code false} 819 * @return this builder 820 */ 821 @NonNull 822 public Builder partitioned(@Nullable Boolean partitioned) { 823 this.partitioned = partitioned; 824 return this; 825 } 826 827 @NonNull 828 public ResponseCookie build() { 829 return new ResponseCookie(this); 830 } 831 } 832 833 /** 834 * Builder used to copy instances of {@link ResponseCookie} via {@link ResponseCookie#copy()}. 835 * <p> 836 * This class is intended for use by a single thread. 837 * 838 * @author <a href="https://www.revetkn.com">Mark Allen</a> 839 */ 840 @NotThreadSafe 841 public static final class Copier { 842 @NonNull 843 private final Builder builder; 844 845 Copier(@NonNull ResponseCookie responseCookie) { 846 requireNonNull(responseCookie); 847 848 this.builder = new Builder(responseCookie.getName()) 849 .value(responseCookie.getValue().orElse(null)) 850 .maxAge(responseCookie.getMaxAge().orElse(null)) 851 .expires(responseCookie.getExpires().orElse(null)) 852 .domain(responseCookie.getDomain().orElse(null)) 853 .path(responseCookie.getPath().orElse(null)) 854 .secure(responseCookie.getSecure()) 855 .httpOnly(responseCookie.getHttpOnly()) 856 .sameSite(responseCookie.getSameSite().orElse(null)) 857 .priority(responseCookie.getPriority().orElse(null)) 858 .partitioned(responseCookie.getPartitioned()); 859 } 860 861 @NonNull 862 public Copier name(@NonNull String name) { 863 requireNonNull(name); 864 this.builder.name(name); 865 return this; 866 } 867 868 /** 869 * Replaces the copied cookie value. 870 * 871 * @param value cookie value, or {@code null} to leave the value unspecified 872 * @return this copier 873 */ 874 @NonNull 875 public Copier value(@Nullable String value) { 876 this.builder.value(value); 877 return this; 878 } 879 880 /** 881 * Replaces the copied cookie's {@code Max-Age} attribute. 882 * 883 * @param maxAge maximum age, or {@code null} to omit {@code Max-Age} 884 * @return this copier 885 */ 886 @NonNull 887 public Copier maxAge(@Nullable Duration maxAge) { 888 this.builder.maxAge(maxAge); 889 return this; 890 } 891 892 /** 893 * Replaces the copied cookie's {@code Expires} attribute. 894 * 895 * @param expires expiration time, or {@code null} to omit {@code Expires} 896 * @return this copier 897 */ 898 @NonNull 899 public Copier expires(@Nullable Instant expires) { 900 this.builder.expires(expires); 901 return this; 902 } 903 904 /** 905 * Replaces the copied cookie's {@code Domain} attribute. 906 * 907 * @param domain cookie domain, or {@code null} to omit {@code Domain} 908 * @return this copier 909 */ 910 @NonNull 911 public Copier domain(@Nullable String domain) { 912 this.builder.domain(domain); 913 return this; 914 } 915 916 /** 917 * Replaces the copied cookie's {@code Path} attribute. 918 * 919 * @param path cookie path, or {@code null} or blank to omit {@code Path} 920 * @return this copier 921 */ 922 @NonNull 923 public Copier path(@Nullable String path) { 924 this.builder.path(path); 925 return this; 926 } 927 928 /** 929 * Replaces the copied cookie's {@code Secure} flag. 930 * 931 * @param secure whether to include {@code Secure}, or {@code null} to use the default of {@code false} 932 * @return this copier 933 */ 934 @NonNull 935 public Copier secure(@Nullable Boolean secure) { 936 this.builder.secure(secure); 937 return this; 938 } 939 940 /** 941 * Replaces the copied cookie's {@code HttpOnly} flag. 942 * 943 * @param httpOnly whether to include {@code HttpOnly}, or {@code null} to use the default of {@code false} 944 * @return this copier 945 */ 946 @NonNull 947 public Copier httpOnly(@Nullable Boolean httpOnly) { 948 this.builder.httpOnly(httpOnly); 949 return this; 950 } 951 952 /** 953 * Replaces the copied cookie's {@code SameSite} attribute. 954 * 955 * @param sameSite same-site policy, or {@code null} to omit {@code SameSite} 956 * @return this copier 957 */ 958 @NonNull 959 public Copier sameSite(@Nullable SameSite sameSite) { 960 this.builder.sameSite(sameSite); 961 return this; 962 } 963 964 /** 965 * Replaces the copied cookie's {@code Priority} attribute. 966 * 967 * @param priority cookie priority, or {@code null} to omit {@code Priority} 968 * @return this copier 969 */ 970 @NonNull 971 public Copier priority(@Nullable Priority priority) { 972 this.builder.priority(priority); 973 return this; 974 } 975 976 /** 977 * Replaces the copied cookie's {@code Partitioned} flag. 978 * 979 * @param partitioned whether to include {@code Partitioned}, or {@code null} to use the default of {@code false} 980 * @return this copier 981 */ 982 @NonNull 983 public Copier partitioned(@Nullable Boolean partitioned) { 984 this.builder.partitioned(partitioned); 985 return this; 986 } 987 988 @NonNull 989 public ResponseCookie finish() { 990 return this.builder.build(); 991 } 992 } 993 994 @ThreadSafe 995 private static final class ParsedSetCookieAttributes { 996 @Nullable 997 private Duration maxAge; 998 @Nullable 999 private Instant expires; 1000 @Nullable 1001 private SameSite sameSite; 1002 @Nullable 1003 private Priority priority; 1004 @NonNull 1005 private Boolean partitioned = false; 1006 1007 @NonNull 1008 private Optional<@NonNull Instant> getExpires() { 1009 return Optional.ofNullable(this.expires); 1010 } 1011 1012 @NonNull 1013 private Optional<@NonNull SameSite> getSameSite() { 1014 return Optional.ofNullable(this.sameSite); 1015 } 1016 1017 @NonNull 1018 private Optional<@NonNull Priority> getPriority() { 1019 return Optional.ofNullable(this.priority); 1020 } 1021 1022 @NonNull 1023 private Boolean getPartitioned() { 1024 return this.partitioned; 1025 } 1026 } 1027 1028 /** 1029 * See https://github.com/spring-projects/spring-framework/blob/main/spring-web/src/main/java/org/springframework/http/ResponseCookie.java 1030 * <p> 1031 * Copyright 2002-2023 the original author or authors. 1032 * <p> 1033 * Licensed under the Apache License, Version 2.0 (the "License"); 1034 * you may not use this file except in compliance with the License. 1035 * You may obtain a copy of the License at 1036 * <p> 1037 * https://www.apache.org/licenses/LICENSE-2.0 1038 * <p> 1039 * Unless required by applicable law or agreed to in writing, software 1040 * distributed under the License is distributed on an "AS IS" BASIS, 1041 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1042 * See the License for the specific language governing permissions and 1043 * limitations under the License. 1044 * <p> 1045 * 1046 * @author Rossen Stoyanchev 1047 * @author Brian Clozel 1048 */ 1049 @ThreadSafe 1050 private static class Rfc6265Utils { 1051 @NonNull 1052 private static final String SEPARATOR_CHARS = new String(new char[]{ 1053 '(', ')', '<', '>', '@', ',', ';', ':', '\\', '"', '/', '[', ']', '?', '=', '{', '}', ' ' 1054 }); 1055 1056 @NonNull 1057 private static final String DOMAIN_CHARS = 1058 "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-"; 1059 1060 public static void validateCookieName(@NonNull String name) { 1061 requireNonNull(name); 1062 1063 for (int i = 0; i < name.length(); i++) { 1064 char c = name.charAt(i); 1065 // CTL = <US-ASCII control chars (octets 0 - 31) and DEL (127)> 1066 if (c <= 0x1F || c == 0x7F) { 1067 throw new IllegalArgumentException( 1068 printableString(name) + ": RFC2616 token cannot have control chars"); 1069 } 1070 if (SEPARATOR_CHARS.indexOf(c) >= 0) { 1071 throw new IllegalArgumentException( 1072 printableString(name) + ": RFC2616 token cannot have separator chars such as '" + printableChar(c) + "'"); 1073 } 1074 if (c >= 0x80) { 1075 throw new IllegalArgumentException( 1076 printableString(name) + ": RFC2616 token can only have US-ASCII: 0x" + Integer.toHexString(c)); 1077 } 1078 } 1079 } 1080 1081 public static void validateCookieValue(@Nullable String value) { 1082 if (value == null) { 1083 return; 1084 } 1085 int start = 0; 1086 int end = value.length(); 1087 if (end > 1 && value.charAt(0) == '"' && value.charAt(end - 1) == '"') { 1088 start = 1; 1089 end--; 1090 } 1091 for (int i = start; i < end; i++) { 1092 char c = value.charAt(i); 1093 if (c < 0x21 || c == 0x22 || c == 0x2c || c == 0x3b || c == 0x5c || c == 0x7f) { 1094 throw new IllegalArgumentException( 1095 "RFC2616 cookie value cannot have '" + printableChar(c) + "'"); 1096 } 1097 if (c >= 0x80) { 1098 throw new IllegalArgumentException( 1099 "RFC2616 cookie value can only have US-ASCII chars: 0x" + Integer.toHexString(c)); 1100 } 1101 } 1102 } 1103 1104 public static void validateDomain(@Nullable String domain) { 1105 if (domain == null || domain.trim().length() == 0) { 1106 return; 1107 } 1108 int char1 = domain.charAt(0); 1109 int charN = domain.charAt(domain.length() - 1); 1110 if (char1 == '-' || charN == '.' || charN == '-') { 1111 throw new IllegalArgumentException("Invalid first/last char in cookie domain: " + printableString(domain)); 1112 } 1113 for (int i = 0, c = -1; i < domain.length(); i++) { 1114 int p = c; 1115 c = domain.charAt(i); 1116 if (DOMAIN_CHARS.indexOf(c) == -1 || (p == '.' && (c == '.' || c == '-')) || (p == '-' && c == '.')) { 1117 throw new IllegalArgumentException(printableString(domain) + ": invalid cookie domain char '" + printableChar((char) c) + "'"); 1118 } 1119 } 1120 } 1121 1122 public static void validatePath(@Nullable String path) { 1123 if (path == null) 1124 return; 1125 1126 // Check for path traversal attempts 1127 if (path.contains("..")) { 1128 throw new IllegalArgumentException( 1129 "Cookie path must not contain '..' segments (path traversal): " + printableString(path) 1130 ); 1131 } 1132 1133 // Check for query strings 1134 if (path.contains("?")) { 1135 throw new IllegalArgumentException( 1136 "Cookie path must not contain query strings: " + printableString(path) 1137 ); 1138 } 1139 1140 // Check for fragments 1141 if (path.contains("#")) { 1142 throw new IllegalArgumentException( 1143 "Cookie path must not contain fragments: " + printableString(path) 1144 ); 1145 } 1146 1147 // Check for backslashes (Windows-style paths) 1148 if (path.contains("\\")) { 1149 throw new IllegalArgumentException( 1150 "Cookie path must not contain backslashes: " + printableString(path) 1151 ); 1152 } 1153 1154 // Check for URL-encoded dots (potential bypass attempt) 1155 if (path.contains("%2E") || path.contains("%2e")) { 1156 throw new IllegalArgumentException( 1157 "Cookie path must not contain encoded dots: " + printableString(path) 1158 ); 1159 } 1160 1161 // Must start with forward slash 1162 if (!path.startsWith("/")) { 1163 throw new IllegalArgumentException( 1164 "Cookie path must start with '/': " + printableString(path) 1165 ); 1166 } 1167 1168 // Check for null bytes 1169 if (path.contains("\0") || path.contains("%00")) { 1170 throw new IllegalArgumentException( 1171 "Cookie path must not contain null bytes: " + printableString(path) 1172 ); 1173 } 1174 1175 for (int i = 0; i < path.length(); i++) { 1176 char c = path.charAt(i); 1177 if (c < 0x20 || c > 0x7E || c == ';') { 1178 throw new IllegalArgumentException(printableString(path) + ": Invalid cookie path char '" + printableChar(c) + "'"); 1179 } 1180 } 1181 } 1182 } 1183}