Skip to content

Commit 1711a29

Browse files
committed
validate samesite attribute in ResponseCookie
Signed-off-by: dxbjavid <dxbjavid@gmail.com>
1 parent 0c60266 commit 1711a29

2 files changed

Lines changed: 24 additions & 0 deletions

File tree

spring-web/src/main/java/org/springframework/http/ResponseCookie.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@ private ResponseCookie(String name, @Nullable String value, Duration maxAge, @Nu
7575
Rfc6265Utils.validateCookieValue(value);
7676
Rfc6265Utils.validateDomain(domain);
7777
Rfc6265Utils.validatePath(path);
78+
Rfc6265Utils.validateSameSite(sameSite);
7879
}
7980

8081

@@ -433,6 +434,18 @@ public static void validatePath(@Nullable String path) {
433434
}
434435
}
435436
}
437+
438+
public static void validateSameSite(@Nullable String sameSite) {
439+
if (sameSite == null) {
440+
return;
441+
}
442+
for (int i = 0; i < sameSite.length(); i++) {
443+
char c = sameSite.charAt(i);
444+
if (c < 0x20 || c > 0x7E || c == ';') {
445+
throw new IllegalArgumentException(sameSite + ": Invalid cookie SameSite char '" + c + "'");
446+
}
447+
}
448+
}
436449
}
437450

438451

spring-web/src/test/java/org/springframework/http/ResponseCookieTests.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,17 @@ void domainChecks() {
8282
.hasMessageContaining("invalid cookie domain char"));
8383
}
8484

85+
@Test
86+
void sameSiteChecks() {
87+
88+
Arrays.asList("Strict", "Lax", "None")
89+
.forEach(sameSite -> ResponseCookie.from("n", "v").sameSite(sameSite).build());
90+
91+
Arrays.asList("Lax\r\nSet-Cookie: x=y", "Lax\n", "La;x", "Lax\t", "Lax\u0005")
92+
.forEach(sameSite -> assertThatThrownBy(() -> ResponseCookie.from("n", "v").sameSite(sameSite).build())
93+
.hasMessageContaining("Invalid cookie SameSite char"));
94+
}
95+
8596
@Test // gh-24663
8697
void domainWithEmptyDoubleQuotes() {
8798

0 commit comments

Comments
 (0)