Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(std/http): Add Cookie value validation #8471

Merged
merged 9 commits into from
Dec 1, 2020
26 changes: 26 additions & 0 deletions std/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.value);
out.push(`${cookie.name}=${cookie.value}`);

// Fallback for invalid Set-Cookie
Expand Down Expand Up @@ -114,6 +115,31 @@ 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(value: string | null): void {
if (value == 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 value cannot have '" + c + "'");
getspooky marked this conversation as resolved.
Show resolved Hide resolved
}
if (c > String.fromCharCode(0x80)) {
throw new Error(
"RFC2616 cookie value can only have US-ASCII chars" +
c.charCodeAt(0).toString(16),
);
}
getspooky marked this conversation as resolved.
Show resolved Hide resolved
}
}

/**
* Parse the cookies of the Server Request
* @param req An object which has a `headers` property
Expand Down
38 changes: 38 additions & 0 deletions std/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 value",
);
});
},
});

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