Unverified Commit 2b1f28db authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

[16.3.x] Add CSP nonce to script tags of loading and template files (#98403)

Backport https://github.com/vercel/next.js/pull/98398Co-authored-by: 's avatarLuke Taylor <luket@anthropic.com>
parent 4b56cee3
......@@ -37,6 +37,7 @@ export async function createComponentStylesAndScripts({
src: `${ctx.assetPrefix}/_next/${encodeURIPath(href)}${getAssetQueryString(ctx, true)}`,
async: true,
key: `script-${scriptIndex}`,
nonce: ctx.nonce,
})
)
scriptIndex++
......
export default function RootLayout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Layout({ children }) {
return <section>{children}</section>
}
import { Marker } from './marker'
export default function Loading() {
return <Marker id="loading" />
}
'use client'
import { useState } from 'react'
export function Marker({ id }) {
const [label] = useState(id)
return <p id={id}>{label}</p>
}
'use client'
import { useEffect, useState } from 'react'
export function PageOnly() {
const [hydrated, setHydrated] = useState(false)
const [count, setCount] = useState(0)
useEffect(() => setHydrated(true), [])
return (
<button
id="page-only"
data-hydrated={hydrated}
onClick={() => setCount(count + 1)}
>
{count}
</button>
)
}
import { connection } from 'next/server'
import { Marker } from './marker'
import { PageOnly } from './page-only'
export default async function Page() {
await connection()
return (
<>
<Marker id="page" />
<PageOnly />
</>
)
}
import { Marker } from './marker'
export default function Template({ children }) {
return (
<>
<Marker id="template" />
{children}
</>
)
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('csp-nonce-segment-scripts', () => {
const { next } = nextTestSetup({
files: __dirname,
})
// The loading and template files import a client component that the page
// also imports, so their chunk is not already loaded by a layout or by a
// client reference, and it gets a script tag of its own.
it('should add the nonce to the script tags of loading and template files', async () => {
const $ = await next.render$('/with-boundaries')
const scripts = $('script[src]')
.toArray()
.map((element) => ({
src: $(element).attr('src'),
nonce: $(element).attr('nonce'),
}))
expect(scripts.length).toBeGreaterThan(0)
expect(scripts.filter((script) => script.nonce !== 'test-nonce')).toEqual(
[]
)
})
it('should run the client code without CSP violations', async () => {
const browser = await next.browser('/with-boundaries')
await browser.waitForElementByCss('#page-only[data-hydrated="true"]')
await browser.elementByCss('#page-only').click()
await retry(async () => {
expect(await browser.elementByCss('#page-only').text()).toBe('1')
})
if (global.browserName === 'chrome') {
const logs = await browser.log()
const cspViolations = logs.filter((log) =>
log.message.includes('Content Security Policy')
)
expect(cspViolations).toEqual([])
}
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
// Nonces are added when a request is rendered. With Cache Components the
// layouts and loading files would be prerendered into a static shell, which
// has no nonce, so this test opts out.
cacheComponents: false,
experimental: {
cachedNavigations: false,
},
}
module.exports = nextConfig
import { NextResponse } from 'next/server'
export function proxy(request) {
const nonce = 'test-nonce'
const csp = `default-src 'self'; script-src 'nonce-${nonce}' 'strict-dynamic' 'unsafe-eval'; style-src 'self' 'unsafe-inline'`
const requestHeaders = new Headers(request.headers)
requestHeaders.set('Content-Security-Policy', csp)
const response = NextResponse.next({ request: { headers: requestHeaders } })
response.headers.set('Content-Security-Policy', csp)
return response
}
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