Skip to content

Commit

Permalink
feat(http): Add Cookie value validation (denoland/deno#8471)
Browse files Browse the repository at this point in the history
  • Loading branch information
getspooky authored and caspervonb committed Jan 31, 2021
1 parent b0cb662 commit 3307a28
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
28 changes: 28 additions & 0 deletions http/cookie.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ function toString(cookie: Cookie): string {
}
const out: string[] = [];
validateCookieName(cookie.name);
validateCookieValue(cookie.name, cookie.value);
out.push(`${cookie.name}=${cookie.value}`);

// Fallback for invalid Set-Cookie
Expand Down Expand Up @@ -114,6 +115,33 @@ function validatePath(path: string | null): void {
}
}

/**
*Validate Cookie Value.
* @see https://tools.ietf.org/html/rfc6265#section-4.1
* @param value Cookie value.
*/
function validateCookieValue(name: string, value: string | null): void {
if (value == null || name == null) return;
for (let i = 0; i < value.length; i++) {
const c = value.charAt(i);
if (
c < String.fromCharCode(0x21) || c == String.fromCharCode(0x22) ||
c == String.fromCharCode(0x2c) || c == String.fromCharCode(0x3b) ||
c == String.fromCharCode(0x5c) || c == String.fromCharCode(0x7f)
) {
throw new Error(
"RFC2616 cookie '" + name + "' cannot have '" + c + "' as value",
);
}
if (c > String.fromCharCode(0x80)) {
throw new Error(
"RFC2616 cookie '" + name + "' can only have US-ASCII chars as value" +
c.charCodeAt(0).toString(16),
);
}
}
}

/**
* Parse the cookies of the Server Request
* @param req An object which has a `headers` property
Expand Down
38 changes: 38 additions & 0 deletions http/cookie_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,44 @@ Deno.test({
},
});

Deno.test({
name: "Cookie Value Validation",
fn(): void {
const res: Response = {};
const tokens = [
"1f\tWa",
"\t",
"1f Wa",
"1f;Wa",
'"1fWa',
"1f\\Wa",
'1f"Wa',
'"',
"1fWa\u0005",
"1f\u0091Wa",
];
res.headers = new Headers();
tokens.forEach((value) => {
assertThrows(
(): void => {
setCookie(
res,
{
name: "Space",
value,
httpOnly: true,
secure: true,
maxAge: 3,
},
);
},
Error,
"RFC2616 cookie 'Space'",
);
});
},
});

Deno.test({
name: "Cookie Path Validation",
fn(): void {
Expand Down

0 comments on commit 3307a28

Please sign in to comment.