Unverified Commit 3370022a authored by Josh Story's avatar Josh Story Committed by GitHub

add test case for CSP with bootstrap scripts and preinit modules (#54348)

in #54059 the nonce attribute was added to preinitialized scripts to when using this CSP directive. The test added asserts there is at least one script that has the nonce attribute. I've changed this to 2 because currently our builds produce at least two "main" scripts, the main chunk and the webpack runtime. The way we bootstrap there is always exactly one bootstrap script which means if we only assert that there is one script with a nonce we might not be asserting anything about the preinit script path. If we ever update our webpack config to produce a single main script this test will fail but we should never do that (it's bad for caching) and so it shouldn't happen and if it does it will hopefully force us to consider if we're making a mistake

Additionally I've added another test that is more e2e. it asserts that the page bootstraps even when using CSP (in prod). In Dev it asserts the CSP attributes but it expects the bootstrap to fail because our dev mode violates the CSP directive with eval.
parent b7eb6d43
'use client'
import { useState, useEffect } from 'react'
export function ClientComponent() {
const [val, setVal] = useState('initial')
useEffect(() => {
setVal('[[updated]]')
}, [])
return <span id="val">{val}</span>
}
import { ClientComponent } from './ClientComponent'
export default async function Page() {
return (
<>
<div>
This fixture is to assert where the bootstrap scripts and other required
scripts emit during SSR
</div>
<div>
<ClientComponent />
</div>
</>
)
}
export default async function Page() {
return (
<div>
This fixture is to assert where the bootstrap scripts and other required
scripts emit during SSR
</div>
)
}
...@@ -1373,8 +1373,9 @@ createNextDescribe( ...@@ -1373,8 +1373,9 @@ createNextDescribe(
// Find all the script tags without src attributes. // Find all the script tags without src attributes.
const elements = $('script[src]') const elements = $('script[src]')
// Expect there to be at least 1 script tag without a src attribute. // Expect there to be at least 2 script tag with a src attribute.
expect(elements.length).toBeGreaterThan(0) // The main chunk and the webpack runtime.
expect(elements.length).toBeGreaterThan(1)
// Expect all inline scripts to have the nonce value. // Expect all inline scripts to have the nonce value.
elements.each((i, el) => { elements.each((i, el) => {
...@@ -1899,6 +1900,39 @@ createNextDescribe( ...@@ -1899,6 +1900,39 @@ createNextDescribe(
expect($('script[async]').length).toBeGreaterThan(1) expect($('script[async]').length).toBeGreaterThan(1)
expect($('body').find('script[async]').length).toBe(1) expect($('body').find('script[async]').length).toBe(1)
}) })
if (!isDev) {
it('should successfully bootstrap even when using CSP', async () => {
// This path has a nonce applied in middleware
const browser = await next.browser('/bootstrap/with-nonce')
const response = await next.fetch('/bootstrap/with-nonce')
// We expect this page to response with CSP headers requiring a nonce for scripts
expect(response.headers.get('content-security-policy')).toContain(
"script-src 'nonce"
)
// We expect to find the updated text which demonstrates our app
// was able to bootstrap successfully (scripts run)
expect(
await browser.eval('document.getElementById("val").textContent')
).toBe('[[updated]]')
})
} else {
it('should fail to bootstrap when using CSP in Dev due to eval', async () => {
// This test is here to ensure that we don't accidentally turn CSP off
// for the prod version.
const browser = await next.browser('/bootstrap/with-nonce')
const response = await next.fetch('/bootstrap/with-nonce')
// We expect this page to response with CSP headers requiring a nonce for scripts
expect(response.headers.get('content-security-policy')).toContain(
"script-src 'nonce"
)
// We expect our app to fail to bootstrap due to invalid eval use in Dev.
// We assert the html is in it's SSR'd state.
expect(
await browser.eval('document.getElementById("val").textContent')
).toBe('initial')
})
}
}) })
} }
) )
...@@ -3,9 +3,9 @@ import { NextResponse } from 'next/server' ...@@ -3,9 +3,9 @@ import { NextResponse } from 'next/server'
/** /**
* @param {import('next/server').NextRequest} request * @param {import('next/server').NextRequest} request
* @returns {NextResponse | undefined} * @returns {Promise<NextResponse | undefined>}
*/ */
export function middleware(request) { export async function middleware(request) {
if (request.nextUrl.pathname === '/searchparams-normalization-bug') { if (request.nextUrl.pathname === '/searchparams-normalization-bug') {
const headers = new Headers(request.headers) const headers = new Headers(request.headers)
headers.set('test', request.nextUrl.searchParams.get('val') || '') headers.set('test', request.nextUrl.searchParams.get('val') || '')
...@@ -25,6 +25,17 @@ export function middleware(request) { ...@@ -25,6 +25,17 @@ export function middleware(request) {
return NextResponse.rewrite(new URL('/dashboard', request.url)) return NextResponse.rewrite(new URL('/dashboard', request.url))
} }
// In dev this route will fail to bootstrap because webpack uses eval which is dissallowed by
// this policy. In production this route will work
if (request.nextUrl.pathname === '/bootstrap/with-nonce') {
const nonce = crypto.randomUUID()
return NextResponse.next({
headers: {
'Content-Security-Policy': `script-src 'nonce-${nonce}' 'strict-dynamic';`,
},
})
}
if (request.nextUrl.pathname.startsWith('/internal/test')) { if (request.nextUrl.pathname.startsWith('/internal/test')) {
const method = request.nextUrl.pathname.endsWith('rewrite') const method = request.nextUrl.pathname.endsWith('rewrite')
? 'rewrite' ? 'rewrite'
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment