Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/tidy-cookies-smile.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/backend': patch
---

Decode request cookie values only after parsing cookie boundaries, preserving malformed percent encodings and preventing encoded delimiters from being treated as separate cookies.
32 changes: 28 additions & 4 deletions packages/backend/src/tokens/__tests__/clerkRequest.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,36 @@ describe('createClerkRequest', () => {
expect(req.cookies.get('foo')).toBe('bar');
});

it('should parse and return cookies with special characters', () => {
it('should decode values after parsing cookie pairs', () => {
const req = createClerkRequest(
new Request('http://localhost:3000', { headers: new Headers({ cookie: 'foo=%20bar%3B%20baz%3Dqux' }) }),
new Request('http://localhost:3000', {
headers: new Headers({ cookie: 'foo=%20bar%3B%20baz%3Dqux; after=parsed' }),
}),
);
expect(req.cookies.get('foo')).toBe('bar');
expect(req.cookies.get('baz')).toBe('qux');

expect(req.cookies.get('foo')).toBe(' bar; baz=qux');
expect(req.cookies.get('baz')).toBeUndefined();
expect(req.cookies.get('after')).toBe('parsed');
});

it.each(['%E2%9', '%98', '%C0%80'])('should preserve a malformed encoded cookie value: %s', value => {
const req = createClerkRequest(
new Request('http://localhost:3000', {
headers: new Headers({ cookie: `__session=abc; analytics_id=${value}; after=parsed` }),
}),
);

expect(req.cookies.get('__session')).toBe('abc');
expect(req.cookies.get('analytics_id')).toBe(value);
expect(req.cookies.get('after')).toBe('parsed');
});

it('should decode lowercase percent escapes', () => {
const req = createClerkRequest(
new Request('http://localhost:3000', { headers: new Headers({ cookie: 'foo=%c3%a9' }) }),
);

expect(req.cookies.get('foo')).toBe('é');
});

it('should parse and return cookies even if no cookie header exists', () => {
Expand Down
6 changes: 1 addition & 5 deletions packages/backend/src/tokens/clerkRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,13 +94,9 @@ class ClerkRequest extends Request {
}

private parseCookies(req: Request) {
const cookiesRecord = parse(this.decodeCookieValue(req.headers.get('cookie') || ''));
const cookiesRecord = parse(req.headers.get('cookie') || '');
return new Map(Object.entries(cookiesRecord));
}

private decodeCookieValue(str: string) {
return str ? str.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent) : str;
}
}

export const createClerkRequest = (...args: ConstructorParameters<typeof ClerkRequest>): ClerkRequest => {
Expand Down
Loading