diff --git a/http/cookie.ts b/http/cookie.ts index 98d9fc2fe1df..6f2cb925de30 100644 --- a/http/cookie.ts +++ b/http/cookie.ts @@ -263,9 +263,10 @@ export function getCookies( ): Partial> { const cookie = headers.get("Cookie"); const out: Partial> = Object.create(null); - if (cookie !== null) { + if (cookie) { const c = cookie.split(";"); for (const kv of c) { + if (kv.trim() === "") continue; const [cookieKey, ...cookieVal] = kv.split("="); if (cookieKey === "") { throw new SyntaxError("Cookie cannot start with '='"); diff --git a/http/cookie_test.ts b/http/cookie_test.ts index fac04877a33d..4f5c3a231440 100644 --- a/http/cookie_test.ts +++ b/http/cookie_test.ts @@ -40,6 +40,31 @@ Deno.test({ }, }); +Deno.test("getCookies() handles empty cookie headers", () => { + for (const cookie of ["", " \t "]) { + const headers = new Headers({ Cookie: cookie }); + const cookies = getCookies(headers); + assertEquals(cookies, {}); + assertEquals(Object.getPrototypeOf(cookies), null); + } +}); + +Deno.test("getCookies() ignores empty cookie pairs", () => { + for (const cookie of ["a=1;", "a=1; \t ;", "; a=1", "a=1;;;"]) { + assertEquals(getCookies(new Headers({ Cookie: cookie })), { a: "1" }); + } + assertEquals(getCookies(new Headers({ Cookie: "; ;\t;" })), {}); + assertEquals( + getCookies(new Headers({ Cookie: "a=1; ; b=two ;" })), + { a: "1", b: "two " }, + ); + assertThrows( + () => getCookies(new Headers({ Cookie: "a=1;=invalid;" })), + SyntaxError, + "Cookie cannot start with '='", + ); +}); + Deno.test({ name: "getCookies() has correct types", fn() {