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/gentle-clouds-heal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/backend': patch
---

Fixes an issue with host header parsing that would cause Clerk to throw an exception when receiving malformed host values.
33 changes: 33 additions & 0 deletions packages/backend/src/tokens/__tests__/clerkRequest.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,39 @@ describe('createClerkRequest', () => {
const req2 = new Request('http://localhost:3000////path');
expect(createClerkRequest(req2).clerkUrl.toString()).toBe('http://localhost:3000////path');
});

it('handles malicious host header with script injection gracefully', () => {
const req = new Request('http://localhost:3000/path', {
headers: {
'x-forwarded-host': 'z2cgvm.xfh"></script><script>alert(document.domain);</script>/',
'x-forwarded-proto': 'https',
},
});
expect(() => createClerkRequest(req)).not.toThrow();
expect(createClerkRequest(req).clerkUrl.toString()).toBe('http://localhost:3000/path');
});

it('handles malicious host header with invalid characters gracefully', () => {
const req = new Request('http://localhost:3000/path?foo=bar', {
headers: {
'x-forwarded-host': '<invalid>host',
'x-forwarded-proto': 'https',
},
});
expect(() => createClerkRequest(req)).not.toThrow();
expect(createClerkRequest(req).clerkUrl.toString()).toBe('http://localhost:3000/path?foo=bar');
});

it('handles empty forwarded headers gracefully', () => {
const req = new Request('http://localhost:3000/path', {
headers: {
'x-forwarded-host': '',
'x-forwarded-proto': '',
},
});
expect(() => createClerkRequest(req)).not.toThrow();
expect(createClerkRequest(req).clerkUrl.toString()).toBe('http://localhost:3000/path');
});
});

describe('toJSON', () => {
Expand Down
7 changes: 6 additions & 1 deletion packages/backend/src/tokens/clerkRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,12 @@ class ClerkRequest extends Request {
if (origin === initialUrl.origin) {
return createClerkUrl(initialUrl);
}
return createClerkUrl(initialUrl.pathname + initialUrl.search, origin);

try {
return createClerkUrl(initialUrl.pathname + initialUrl.search, origin);
} catch {
return createClerkUrl(initialUrl);
}
}

private getFirstValueFromHeader(value?: string | null) {
Expand Down
Loading