Skip to content

Commit

Permalink
feat(http): Add Cookie domain validation (#1009)
Browse files Browse the repository at this point in the history
Cookie domain should not start with - and end with . or -.
https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.2.3
  • Loading branch information
getspooky authored Jul 8, 2021
1 parent 6f62e9c commit 3f44647
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
21 changes: 20 additions & 1 deletion http/cookie.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ function toString(cookie: Cookie): string {
out.push(`Max-Age=${cookie.maxAge}`);
}
if (cookie.domain) {
validateDomain(cookie.domain);
out.push(`Domain=${cookie.domain}`);
}
if (cookie.sameSite) {
Expand Down Expand Up @@ -115,7 +116,7 @@ function validatePath(path: string | null): void {
}

/**
*Validate Cookie Value.
* Validate Cookie Value.
* @see https://tools.ietf.org/html/rfc6265#section-4.1
* @param value Cookie value.
*/
Expand All @@ -141,6 +142,24 @@ function validateValue(name: string, value: string | null): void {
}
}

/**
* Validate Cookie Domain.
* @see https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.2.3
* @param domain Cookie domain.
*/
function validateDomain(domain: string): void {
if (domain == null) {
return;
}
const char1 = domain.charAt(0);
const charN = domain.charAt(domain.length - 1);
if (char1 == "-" || charN == "." || charN == "-") {
throw new Error(
"Invalid first/last char in cookie domain: " + domain,
);
}
}

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

Deno.test({
name: "Cookie Domain Validation",
fn(): void {
const res: Response = {};
const tokens = ["-domain.com", "domain.org.", "domain.org-"];
res.headers = new Headers();
tokens.forEach((domain) => {
assertThrows(
(): void => {
setCookie(res, {
name: "Space",
value: "Cat",
httpOnly: true,
secure: true,
domain,
maxAge: 3,
});
},
Error,
"Invalid first/last char in cookie domain: " + domain,
);
});
},
});

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

0 comments on commit 3f44647

Please sign in to comment.