Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 6 commits into from
Nov 13, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions packages/next/client/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -648,12 +648,19 @@ function doRender(input: RenderRouteInfo): Promise<any> {
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 }) => {
if (!currentHrefs.has(href)) {
const styleTag = document.createElement('style')
styleTag.setAttribute('data-n-href', href)
styleTag.setAttribute('media', 'x')

if (nonce) {
styleTag.setAttribute('nonce', nonce)
}

document.head.appendChild(styleTag)
styleTag.appendChild(document.createTextNode(text))
}
Expand Down
2 changes: 1 addition & 1 deletion packages/next/pages/_document.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -508,7 +508,7 @@ export class Head extends Component<
{process.env.__NEXT_OPTIMIZE_FONTS
? this.makeStylesheetInert(this.getCssLinks(files))
: this.getCssLinks(files)}
<noscript data-n-css />
<noscript data-n-css={this.props.nonce ?? ''} />
{!disableRuntimeJS && this.getPreloadDynamicChunks()}
{!disableRuntimeJS && this.getPreloadMainLinks(files)}
{this.context.isDevelopment && (
Expand Down
2 changes: 1 addition & 1 deletion test/integration/build-output/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ describe('Build Output', () => {
expect(parseFloat(err404FirstLoad) - 65).toBeLessThanOrEqual(0)
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)

if (_appSize.endsWith('kB')) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
module.exports = {
async headers() {
return [
{
source: '/(.*)',
headers: [
{
key: 'Content-Security-Policy',
value: `style-src 'self' 'nonce-VmVyY2Vs';`,
},
],
},
]
},
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
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>
)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
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>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.green {
font-size: 25px;
color: green;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
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>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.blue {
font-size: 25px;
color: blue;
}
158 changes: 156 additions & 2 deletions test/integration/css/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
describe('CSS Modules Composes Ordering', () => {
const appDir = join(fixturesDir, 'composes-ordering')
Expand Down Expand Up @@ -1236,7 +1390,7 @@ describe('CSS Support', () => {
const newPageHref = await browser.eval(
`document.querySelector('style[data-n-href]').getAttribute('data-n-href')`
)
expect(newPrevSibling).toBeTruthy()
expect(newPrevSibling).toBe('')
expect(newPageHref).toBeDefined()
expect(newPageHref).not.toBe(currentPageHref)

Expand All @@ -1250,7 +1404,7 @@ describe('CSS Support', () => {
const newPageHref2 = await browser.eval(
`document.querySelector('style[data-n-href]').getAttribute('data-n-href')`
)
expect(newPrevSibling2).toBeTruthy()
expect(newPrevSibling2).toBe('')
expect(newPageHref2).toBeDefined()
expect(newPageHref2).toBe(currentPageHref)
} finally {
Expand Down