Unverified Commit 318a1bf3 authored by Steven's avatar Steven Committed by GitHub

Add "nonce" from <Head> to the injected <style> to satisfy CSP (#19150)

Fixes #18557 
parent 29694572
...@@ -648,12 +648,19 @@ function doRender(input: RenderRouteInfo): Promise<any> { ...@@ -648,12 +648,19 @@ function doRender(input: RenderRouteInfo): Promise<any> {
currentStyleTags.map((tag) => tag.getAttribute('data-n-href')) currentStyleTags.map((tag) => tag.getAttribute('data-n-href'))
) )
const noscript = document.querySelector('noscript[data-n-css]')
const nonce = noscript?.getAttribute('data-n-css')
styleSheets.forEach(({ href, text }) => { styleSheets.forEach(({ href, text }) => {
if (!currentHrefs.has(href)) { if (!currentHrefs.has(href)) {
const styleTag = document.createElement('style') const styleTag = document.createElement('style')
styleTag.setAttribute('data-n-href', href) styleTag.setAttribute('data-n-href', href)
styleTag.setAttribute('media', 'x') styleTag.setAttribute('media', 'x')
if (nonce) {
styleTag.setAttribute('nonce', nonce)
}
document.head.appendChild(styleTag) document.head.appendChild(styleTag)
styleTag.appendChild(document.createTextNode(text)) styleTag.appendChild(document.createTextNode(text))
} }
......
...@@ -508,7 +508,7 @@ export class Head extends Component< ...@@ -508,7 +508,7 @@ export class Head extends Component<
{process.env.__NEXT_OPTIMIZE_FONTS {process.env.__NEXT_OPTIMIZE_FONTS
? this.makeStylesheetInert(this.getCssLinks(files)) ? this.makeStylesheetInert(this.getCssLinks(files))
: this.getCssLinks(files)} : this.getCssLinks(files)}
<noscript data-n-css /> <noscript data-n-css={this.props.nonce ?? ''} />
{!disableRuntimeJS && this.getPreloadDynamicChunks()} {!disableRuntimeJS && this.getPreloadDynamicChunks()}
{!disableRuntimeJS && this.getPreloadMainLinks(files)} {!disableRuntimeJS && this.getPreloadMainLinks(files)}
{this.context.isDevelopment && ( {this.context.isDevelopment && (
......
...@@ -104,7 +104,7 @@ describe('Build Output', () => { ...@@ -104,7 +104,7 @@ describe('Build Output', () => {
expect(parseFloat(err404FirstLoad) - 65).toBeLessThanOrEqual(0) expect(parseFloat(err404FirstLoad) - 65).toBeLessThanOrEqual(0)
expect(err404FirstLoad.endsWith('kB')).toBe(true) expect(err404FirstLoad.endsWith('kB')).toBe(true)
expect(parseFloat(sharedByAll) - 61.5).toBeLessThanOrEqual(0) expect(parseFloat(sharedByAll) - 61.6).toBeLessThanOrEqual(0)
expect(sharedByAll.endsWith('kB')).toBe(true) expect(sharedByAll.endsWith('kB')).toBe(true)
if (_appSize.endsWith('kB')) { if (_appSize.endsWith('kB')) {
......
module.exports = {
async headers() {
return [
{
source: '/(.*)',
headers: [
{
key: 'Content-Security-Policy',
value: `style-src 'self' 'nonce-VmVyY2Vs';`,
},
],
},
]
},
}
import Document, { Html, Head, Main, NextScript } from 'next/document'
export default class MyDocument extends Document {
render() {
return (
<Html lang="en">
<Head nonce="VmVyY2Vs" />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
import Link from 'next/link'
import css from './index.module.css'
export default function Home() {
return (
<main>
<Link href="/other" prefetch={false}>
<a id="link-other">other page</a>
</Link>
<h1 id="green-title" className={css.green}>
Green
</h1>
</main>
)
}
import Link from 'next/link'
import css from './other.module.css'
export default function Other() {
return (
<main>
<Link href="/">
<a id="link-index">index page</a>
</Link>
<br />
<h1 id="blue-title" className={css.blue}>
Blue
</h1>
</main>
)
}
...@@ -1157,6 +1157,160 @@ describe('CSS Support', () => { ...@@ -1157,6 +1157,160 @@ describe('CSS Support', () => {
}) })
}) })
// https://github.com/vercel/next.js/issues/18557
describe('CSS page transition inject <style> with nonce so it works with CSP header', () => {
const appDir = join(fixturesDir, 'csp-style-src-nonce')
let app, appPort
function tests() {
async function checkGreenTitle(browser) {
await browser.waitForElementByCss('#green-title')
const titleColor = await browser.eval(
`window.getComputedStyle(document.querySelector('#green-title')).color`
)
expect(titleColor).toBe('rgb(0, 128, 0)')
}
async function checkBlueTitle(browser) {
await browser.waitForElementByCss('#blue-title')
const titleColor = await browser.eval(
`window.getComputedStyle(document.querySelector('#blue-title')).color`
)
expect(titleColor).toBe('rgb(0, 0, 255)')
}
it('should have correct color on index page (on load)', async () => {
const browser = await webdriver(appPort, '/')
try {
await checkGreenTitle(browser)
} finally {
await browser.close()
}
})
it('should have correct color on index page (on hover)', async () => {
const browser = await webdriver(appPort, '/')
try {
await checkGreenTitle(browser)
await browser.waitForElementByCss('#link-other').moveTo()
await waitFor(2000)
await checkGreenTitle(browser)
} finally {
await browser.close()
}
})
it('should not change color on hover', async () => {
const browser = await webdriver(appPort, '/')
try {
await checkGreenTitle(browser)
await browser.waitForElementByCss('#link-other').moveTo()
await waitFor(2000)
await checkGreenTitle(browser)
} finally {
await browser.close()
}
})
it('should have correct CSS injection order', async () => {
const browser = await webdriver(appPort, '/')
try {
await checkGreenTitle(browser)
const prevSiblingHref = await browser.eval(
`document.querySelector('link[rel=stylesheet][data-n-p]').previousSibling.getAttribute('href')`
)
const currentPageHref = await browser.eval(
`document.querySelector('link[rel=stylesheet][data-n-p]').getAttribute('href')`
)
expect(prevSiblingHref).toBeDefined()
expect(prevSiblingHref).toBe(currentPageHref)
// Navigate to other:
await browser.waitForElementByCss('#link-other').click()
await checkBlueTitle(browser)
const newPrevSibling = await browser.eval(
`document.querySelector('style[data-n-href]').previousSibling.getAttribute('data-n-css')`
)
const newPageHref = await browser.eval(
`document.querySelector('style[data-n-href]').getAttribute('data-n-href')`
)
expect(newPrevSibling).toBe('VmVyY2Vs')
expect(newPageHref).toBeDefined()
expect(newPageHref).not.toBe(currentPageHref)
// Navigate to home:
await browser.waitForElementByCss('#link-index').click()
await checkGreenTitle(browser)
const newPrevSibling2 = await browser.eval(
`document.querySelector('style[data-n-href]').previousSibling.getAttribute('data-n-css')`
)
const newPageHref2 = await browser.eval(
`document.querySelector('style[data-n-href]').getAttribute('data-n-href')`
)
expect(newPrevSibling2).toBeTruthy()
expect(newPageHref2).toBeDefined()
expect(newPageHref2).toBe(currentPageHref)
} finally {
await browser.close()
}
})
it('should have correct color on index page (on nav from index)', async () => {
const browser = await webdriver(appPort, '/')
try {
await checkGreenTitle(browser)
await browser.waitForElementByCss('#link-other').click()
// Wait for navigation:
await browser.waitForElementByCss('#link-index')
await checkBlueTitle(browser)
// Navigate back to index:
await browser.waitForElementByCss('#link-index').click()
await checkGreenTitle(browser)
} finally {
await browser.close()
}
})
it('should have correct color on index page (on nav from other)', async () => {
const browser = await webdriver(appPort, '/other')
try {
await checkBlueTitle(browser)
await browser.waitForElementByCss('#link-index').click()
// Wait for navigation:
await browser.waitForElementByCss('#link-other')
await checkGreenTitle(browser)
// Navigate back to other:
await browser.waitForElementByCss('#link-other').click()
await checkBlueTitle(browser)
} finally {
await browser.close()
}
})
}
describe('Production Mode', () => {
beforeAll(async () => {
await remove(join(appDir, '.next'))
})
beforeAll(async () => {
await nextBuild(appDir, [], {})
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(async () => {
await killApp(app)
})
tests()
})
})
// https://github.com/vercel/next.js/issues/12445 // https://github.com/vercel/next.js/issues/12445
describe('CSS Modules Composes Ordering', () => { describe('CSS Modules Composes Ordering', () => {
const appDir = join(fixturesDir, 'composes-ordering') const appDir = join(fixturesDir, 'composes-ordering')
...@@ -1236,7 +1390,7 @@ describe('CSS Support', () => { ...@@ -1236,7 +1390,7 @@ describe('CSS Support', () => {
const newPageHref = await browser.eval( const newPageHref = await browser.eval(
`document.querySelector('style[data-n-href]').getAttribute('data-n-href')` `document.querySelector('style[data-n-href]').getAttribute('data-n-href')`
) )
expect(newPrevSibling).toBeTruthy() expect(newPrevSibling).toBe('')
expect(newPageHref).toBeDefined() expect(newPageHref).toBeDefined()
expect(newPageHref).not.toBe(currentPageHref) expect(newPageHref).not.toBe(currentPageHref)
...@@ -1250,7 +1404,7 @@ describe('CSS Support', () => { ...@@ -1250,7 +1404,7 @@ describe('CSS Support', () => {
const newPageHref2 = await browser.eval( const newPageHref2 = await browser.eval(
`document.querySelector('style[data-n-href]').getAttribute('data-n-href')` `document.querySelector('style[data-n-href]').getAttribute('data-n-href')`
) )
expect(newPrevSibling2).toBeTruthy() expect(newPrevSibling2).toBe('')
expect(newPageHref2).toBeDefined() expect(newPageHref2).toBeDefined()
expect(newPageHref2).toBe(currentPageHref) expect(newPageHref2).toBe(currentPageHref)
} finally { } finally {
......
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