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

csp.spec.ts

178 lines6.1 KB

1import { expect, type Page } from '@playwright/test'
2import { test } from '@tanstack/router-e2e-utils'
3​
4async function getRawHtml(page: Page) {
5 let rawHtml = ''
6​
7 await page.route('/', async (route) => {
8 const response = await route.fetch()
9 rawHtml = await response.text()
10 await route.fulfill({ response, body: rawHtml })
11 })
12​
13 const response = await page.goto('/')
14 await page.unrouteAll({ behavior: 'ignoreErrors' })
15​
16 return { rawHtml, response }
18​
19test('CSP header is set with nonce', async ({ page }) => {
20 const response = await page.goto('/')
21 const csp = response?.headers()['content-security-policy']
22 expect(csp).toContain("script-src 'self' 'nonce-")
23 expect(csp).toContain("style-src 'self' 'nonce-")
24})
25​
26test('Inline scripts have nonce attribute', async ({ page }) => {
27 await page.goto('/')
28 const scripts = await page.locator('script[nonce]').all()
29 expect(scripts.length).toBeGreaterThan(0)
30})
31​
32test('Inline styles have nonce attribute', async ({ page }) => {
33 await page.goto('/')
34 const styles = await page.locator('style[nonce]').all()
35 expect(styles.length).toBeGreaterThan(0)
36})
37​
38test('External script has nonce attribute', async ({ page }) => {
39 const { rawHtml } = await getRawHtml(page)
40 expect(rawHtml).toMatch(
41 /<script(?=[^>]*\bsrc="\/external\.js")(?=[^>]*\bnonce="[^"]+")[^>]*>/,
42 )
43})
44​
45test('External stylesheet has nonce attribute', async ({ page }) => {
46 await page.goto('/')
47 const externalStylesheet = page.locator('link[href="/external.css"]')
48 await expect(externalStylesheet).toHaveAttribute('nonce')
49})
50​
51test('Nonces match between header and elements', async ({ page }) => {
52 // Intercept the HTML response to get raw content before browser strips nonces
53 const { rawHtml, response } = await getRawHtml(page)
54​
55 const csp = response?.headers()['content-security-policy'] || ''
56​
57 // Extract nonce from CSP header
58 const nonceMatch = csp.match(/nonce-([a-f0-9]+)/)
59 expect(nonceMatch).toBeTruthy()
60 const headerNonce = nonceMatch![1]
61​
62 // Check script nonces match - look for nonce attribute anywhere in the script tag
63 const scriptNonces = [
64 ...rawHtml.matchAll(/<script[^>]*\bnonce="([^"]+)"[^>]*>/g),
65 ].map((m) => m[1])
66 expect(scriptNonces.length).toBeGreaterThan(0)
67 for (const nonce of scriptNonces) {
68 expect(nonce).toBe(headerNonce)
69 }
70​
71 // Check style nonces match
72 const styleNonces = [
73 ...rawHtml.matchAll(/<style[^>]*\bnonce="([^"]+)"[^>]*>/g),
74 ].map((m) => m[1])
75 expect(styleNonces.length).toBeGreaterThan(0)
76 for (const nonce of styleNonces) {
77 expect(nonce).toBe(headerNonce)
78 }
79​
80 // Check external script nonce matches (nonce can be before or after src)
81 const externalScriptMatch = rawHtml.match(
82 /<script[^>]*\bsrc="\/external\.js"[^>]*\bnonce="([^"]+)"[^>]*>|<script[^>]*\bnonce="([^"]+)"[^>]*\bsrc="\/external\.js"[^>]*>/,
83 )
84 expect(externalScriptMatch).toBeTruthy()
85 expect(externalScriptMatch![1] || externalScriptMatch![2]).toBe(headerNonce)
86​
87 // Check external stylesheet nonce matches (nonce can be before or after href)
88 const externalStyleMatch = rawHtml.match(
89 /<link[^>]*\bhref="\/external\.css"[^>]*\bnonce="([^"]+)"[^>]*>|<link[^>]*\bnonce="([^"]+)"[^>]*\bhref="\/external\.css"[^>]*>/,
90 )
91 expect(externalStyleMatch).toBeTruthy()
92 expect(externalStyleMatch![1] || externalStyleMatch![2]).toBe(headerNonce)
93})
94​
95test('Hydration works - counter increments', async ({ page }) => {
96 await page.goto('/')
97 await expect(page.getByTestId('counter-value')).toContainText('0')
98​
99 // Keep clicking until Solid hydrates and the counter increments
100 // This handles the race between test execution and hydration
101 await expect
102 .poll(
103 async () => {
104 await page.getByTestId('counter-btn').click()
105 return page.getByTestId('counter-value').textContent()
106 },
107 { timeout: 10000, intervals: [100, 200, 500, 1000] },
108 )
109 .not.toBe('0')
110​
111 // Now that hydration is confirmed, verify further increments work
112 const currentValue = parseInt(
113 (await page.getByTestId('counter-value').textContent()) || '0',
114 )
115 await page.getByTestId('counter-btn').click()
116 await expect(page.getByTestId('counter-value')).toContainText(
117 String(currentValue + 1),
118 )
119})
120​
121test('Inline styles work with CSP', async ({ page }) => {
122 await page.goto('/')
123 const el = page.getByTestId('inline-styled')
124 await expect(el).toBeVisible()
125 // Verify the style was applied (green color)
126 const color = await el.evaluate((e) => getComputedStyle(e).color)
127 expect(color).toBe('rgb(0, 128, 0)') // green
128})
129​
130test('External styles work with CSP', async ({ page }) => {
131 await page.goto('/')
132 const el = page.getByTestId('external-styled')
133 await expect(el).toBeVisible()
134 // Verify the style was applied (blue color)
135 const color = await el.evaluate((e) => getComputedStyle(e).color)
136 expect(color).toBe('rgb(0, 0, 255)') // blue
137})
138​
139test('External script executes with CSP', async ({ page }) => {
140 await page.goto('/')
141 // Check that the external script set its window global
142 await expect
143 .poll(() => page.evaluate(() => (window as any).__EXTERNAL_SCRIPT_LOADED__))
144 .toBe(true)
145})
146​
147test('No CSP violations in console', async ({ page }) => {
148 const violations: string[] = []
149 page.on('console', (msg) => {
150 if (msg.text().toLowerCase().includes('content security policy')) {
151 violations.push(msg.text())
152 }
153 })
154 page.on('pageerror', (err) => {
155 if (err.message.toLowerCase().includes('content security policy')) {
156 violations.push(err.message)
157 }
158 })
159 await page.goto('/')
160 await page.getByTestId('counter-btn').click()
161 // Small wait to ensure any async violations are caught
162 await page.waitForTimeout(100)
163 expect(violations).toEqual([])
164})
165​
166test('Each request gets a unique nonce', async ({ page }) => {
167 const response1 = await page.goto('/')
168 const csp1 = response1?.headers()['content-security-policy'] || ''
169 const nonce1 = csp1.match(/nonce-([a-f0-9]+)/)?.[1]
170​
171 const response2 = await page.goto('/')
172 const csp2 = response2?.headers()['content-security-policy'] || ''
173 const nonce2 = csp2.match(/nonce-([a-f0-9]+)/)?.[1]
174​
175 expect(nonce1).toBeTruthy()
176 expect(nonce2).toBeTruthy()
177 expect(nonce1).not.toBe(nonce2)
178})