Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

getOrigin.test.ts

62 lines2.1 KB

1import { describe, expect, test } from 'vitest'
2import { getOrigin } from '../src/ssr/ssr-server'
3​
4describe('getOrigin security', () => {
5 test('should not trust spoofed Origin header', () => {
6 // An attacker could send a malicious Origin header to try to manipulate
7 // the router's origin, which could affect redirect handling (CVE-2024-34351)
8 const maliciousRequest = new Request('https://legitimate.com/api/action', {
9 headers: {
10 Origin: 'https://evil.com',
11 },
12 })
13​
14 const origin = getOrigin(maliciousRequest)
15​
16 // The origin should come from request.url, not the spoofed Origin header
17 // This prevents SSRF-like attacks where an attacker tries to manipulate
18 // how redirects are processed by providing a malicious Origin header
19 expect(origin).toBe('https://legitimate.com')
20 expect(origin).not.toBe('https://evil.com')
21 })
22​
23 test('should derive origin from request URL', () => {
24 const request = new Request('https://myapp.com/page')
25 const origin = getOrigin(request)
26 expect(origin).toBe('https://myapp.com')
27 })
28​
29 test('should handle localhost requests', () => {
30 const request = new Request('http://localhost:3000/api')
31 const origin = getOrigin(request)
32 expect(origin).toBe('http://localhost:3000')
33 })
34​
35 test('should return fallback for invalid request URL', () => {
36 // This should be rare, but handle gracefully
37 const request = {
38 url: 'not-a-valid-url',
39 headers: new Headers(),
40 } as unknown as Request
41​
42 const origin = getOrigin(request)
43 expect(origin).toBe('http://localhost')
44 })
45​
46 test('should ignore Origin header even if request URL parse fails', () => {
47 // Even if the request URL is somehow invalid, we should not fall back
48 // to trusting the Origin header
49 const request = {
50 url: 'invalid-url',
51 headers: new Headers({
52 Origin: 'https://evil.com',
53 }),
54 } as unknown as Request
55​
56 const origin = getOrigin(request)
57​
58 // Should fall back to localhost, not use the potentially malicious Origin
59 expect(origin).toBe('http://localhost')
60 expect(origin).not.toBe('https://evil.com')
61 })
62})