Skip to content

Commit bf6b69e

Browse files
committed
[fit] validate cookie before adding to collection
1 parent ab8e415 commit bf6b69e

2 files changed

Lines changed: 29 additions & 0 deletions

File tree

framework/fit/java/fit-builtin/services/fit-http-classic/definition/src/main/java/modelengine/fit/http/support/DefaultCookieCollection.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,9 @@ public void add(Cookie cookie) {
8888
if (cookie == null || StringUtils.isBlank(cookie.name())) {
8989
return;
9090
}
91+
if (!HttpUtils.isValidCookiePair(cookie.name(), cookie.value())) {
92+
throw new IllegalArgumentException("Invalid cookie: name or value is not allowed");
93+
}
9194
store.computeIfAbsent(cookie.name(), k -> new ArrayList<>());
9295
List<Cookie> list = store.get(cookie.name());
9396
list.removeIf(c ->

framework/fit/java/fit-builtin/services/fit-http-classic/definition/src/test/java/modelengine/fit/http/header/ConfigurableCookieCollectionTest.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,32 @@ void shouldReturnAllCookie() {
5454
assertThat(cookies).hasSize(1);
5555
}
5656

57+
@Test
58+
@DisplayName("添加非法 Cookie 应抛异常")
59+
void shouldThrowExceptionForInvalidCookie() {
60+
ConfigurableCookieCollection collection = ConfigurableCookieCollection.create();
61+
62+
Cookie invalidNameCookie = Cookie.builder().name("inva;lid").value("123").build();
63+
assertThatThrownBy(() -> collection.add(invalidNameCookie)).isInstanceOf(IllegalArgumentException.class);
64+
65+
Cookie invalidValueCookie = Cookie.builder().name("validName").value("v@lue;").build();
66+
assertThatThrownBy(() -> collection.add(invalidValueCookie)).isInstanceOf(IllegalArgumentException.class);
67+
68+
Cookie nullValueCookie = Cookie.builder().name("someName").value(null).build();
69+
assertThatThrownBy(() -> collection.add(nullValueCookie)).isInstanceOf(IllegalArgumentException.class);
70+
}
71+
72+
@Test
73+
@DisplayName("允许空字符串 value")
74+
void shouldHandleEmptyAndNullValue() {
75+
ConfigurableCookieCollection collection = ConfigurableCookieCollection.create();
76+
77+
// 空字符串 value 是允许的
78+
Cookie emptyValueCookie = Cookie.builder().name("token").value("").build();
79+
collection.add(emptyValueCookie);
80+
assertThat(collection.get("token")).isPresent().get().extracting(Cookie::value).isEqualTo("");
81+
}
82+
5783
@Test
5884
@DisplayName("同名 Cookie 不同路径可共存")
5985
void shouldAllowMultipleCookiesWithDifferentPath() {

0 commit comments

Comments
 (0)