Unverified Commit 5f03a712 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Move SRI test into separate suite (#56015)

Moves the experimental.sri config test into a separate test suite.

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->
parent e3a28051
import { createNextDescribe } from 'e2e-utils' import { createNextDescribe } from 'e2e-utils'
import crypto from 'crypto'
import { check, getRedboxHeader, hasRedbox, waitFor } from 'next-test-utils' import { check, getRedboxHeader, hasRedbox, waitFor } from 'next-test-utils'
import cheerio from 'cheerio' import cheerio from 'cheerio'
import stripAnsi from 'strip-ansi' import stripAnsi from 'strip-ansi'
...@@ -1329,160 +1328,6 @@ createNextDescribe( ...@@ -1329,160 +1328,6 @@ createNextDescribe(
}) })
}) })
}) })
;(isDev || isNextDeploy ? describe.skip : describe)(
'Subresource Integrity',
() => {
function fetchWithPolicy(policy: string | null) {
return next.fetch('/dashboard', {
headers: policy
? {
'Content-Security-Policy': policy,
}
: {},
})
}
async function renderWithPolicy(policy: string | null) {
const res = await fetchWithPolicy(policy)
expect(res.ok).toBe(true)
const html = await res.text()
return cheerio.load(html)
}
it('does not include nonce when not enabled', async () => {
const policies = [
`script-src 'nonce-'`, // invalid nonce
'style-src "nonce-cmFuZG9tCg=="', // no script or default src
'', // empty string
]
for (const policy of policies) {
const $ = await renderWithPolicy(policy)
// Find all the script tags without src attributes and with nonce
// attributes.
const elements = $('script[nonce]:not([src])')
// Expect there to be none.
expect(elements.length).toBe(0)
}
})
it('includes a nonce value with inline scripts when Content-Security-Policy header is defined', async () => {
// A random nonce value, base64 encoded.
const nonce = 'cmFuZG9tCg=='
// Validate all the cases where we could parse the nonce.
const policies = [
`script-src 'nonce-${nonce}'`, // base case
` script-src 'nonce-${nonce}' `, // extra space added around sources and directive
`style-src 'self'; script-src 'nonce-${nonce}'`, // extra directives
`script-src 'self' 'nonce-${nonce}' 'nonce-othernonce'`, // extra nonces
`default-src 'nonce-othernonce'; script-src 'nonce-${nonce}';`, // script and then fallback case
`default-src 'nonce-${nonce}'`, // fallback case
]
for (const policy of policies) {
const $ = await renderWithPolicy(policy)
// Find all the script tags without src attributes.
const elements = $('script:not([src])')
// Expect there to be at least 1 script tag without a src attribute.
expect(elements.length).toBeGreaterThan(0)
// Expect all inline scripts to have the nonce value.
elements.each((i, el) => {
expect(el.attribs['nonce']).toBe(nonce)
})
}
})
it('includes a nonce value with bootstrap scripts when Content-Security-Policy header is defined', async () => {
// A random nonce value, base64 encoded.
const nonce = 'cmFuZG9tCg=='
// Validate all the cases where we could parse the nonce.
const policies = [
`script-src 'nonce-${nonce}'`, // base case
` script-src 'nonce-${nonce}' `, // extra space added around sources and directive
`style-src 'self'; script-src 'nonce-${nonce}'`, // extra directives
`script-src 'self' 'nonce-${nonce}' 'nonce-othernonce'`, // extra nonces
`default-src 'nonce-othernonce'; script-src 'nonce-${nonce}';`, // script and then fallback case
`default-src 'nonce-${nonce}'`, // fallback case
]
for (const policy of policies) {
const $ = await renderWithPolicy(policy)
// Find all the script tags without src attributes.
const elements = $('script[src]')
// Expect there to be at least 2 script tag with a src attribute.
// The main chunk and the webpack runtime.
expect(elements.length).toBeGreaterThan(1)
// Expect all inline scripts to have the nonce value.
elements.each((i, el) => {
expect(el.attribs['nonce']).toBe(nonce)
})
}
})
it('includes an integrity attribute on scripts', async () => {
const $ = await next.render$('/dashboard')
// Find all the script tags with src attributes.
const elements = $('script[src]')
// Expect there to be at least 1 script tag with a src attribute.
expect(elements.length).toBeGreaterThan(0)
// Collect all the scripts with integrity hashes so we can verify them.
const files: [string, string][] = []
// For each of these attributes, ensure that there's an integrity
// attribute and starts with the correct integrity hash prefix.
elements.each((i, el) => {
const integrity = el.attribs['integrity']
expect(integrity).toBeDefined()
expect(integrity).toStartWith('sha256-')
const src = el.attribs['src']
expect(src).toBeDefined()
files.push([src, integrity])
})
// For each script tag, ensure that the integrity attribute is the
// correct hash of the script tag.
for (const [src, integrity] of files) {
const res = await next.fetch(src)
expect(res.status).toBe(200)
const content = await res.text()
const hash = crypto
.createHash('sha256')
.update(content)
.digest()
.toString('base64')
expect(integrity).toEndWith(hash)
}
})
it('throws when escape characters are included in nonce', async () => {
const res = await fetchWithPolicy(
`script-src 'nonce-"><script></script>"'`
)
expect(res.status).toBe(500)
})
}
)
describe('template component', () => { describe('template component', () => {
it('should render the template that holds state in a client component and reset on navigation', async () => { it('should render the template that holds state in a client component and reset on navigation', async () => {
......
module.exports = { module.exports = {
experimental: { experimental: {
clientRouterFilterRedirects: true, clientRouterFilterRedirects: true,
sri: {
algorithm: 'sha256',
},
webpackBuildWorker: true, webpackBuildWorker: true,
}, },
// output: 'standalone', // output: 'standalone',
......
'use client'
import styles from './client-comp.module.css'
import { useEffect, useState } from 'react'
export default function ClientComp() {
const [state, setState] = useState({})
useEffect(() => {
setState({ test: 'HELLOOOO' })
}, [])
return (
<>
<p className={styles.client}>Hello</p>
{state.test}
</>
)
}
import './style.css'
import './global.css'
export default function DashboardLayout(props) {
return (
<div className="dangerous-text">
<h1 className="green">Dashboard</h1>
{props.children}
</div>
)
}
export const preferredRegion = 'iad1'
import ClientComp from './client-comp-client'
export default function DashboardPage(props) {
if (typeof WebSocket === 'undefined') {
throw new Error('missing WebSocket constructor!!')
}
return (
<>
<p id="from-dashboard" className="p">
hello from app/dashboard
</p>
<p className="bold">BOLD</p>
<p className="green">this is green</p>
<ClientComp />
</>
)
}
export const runtime = 'edge'
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello world</p>
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
sri: {
algorithm: 'sha256',
},
},
}
module.exports = nextConfig
import { createNextDescribe } from 'e2e-utils'
import crypto from 'crypto'
import path from 'path'
import cheerio from 'cheerio'
createNextDescribe(
'Subresource Integrity',
{
files: path.join(__dirname, 'fixture'),
},
({ next }) => {
function fetchWithPolicy(policy: string | null) {
return next.fetch('/dashboard', {
headers: policy
? {
'Content-Security-Policy': policy,
}
: {},
})
}
async function renderWithPolicy(policy: string | null) {
const res = await fetchWithPolicy(policy)
expect(res.ok).toBe(true)
const html = await res.text()
return cheerio.load(html)
}
it('does not include nonce when not enabled', async () => {
const policies = [
`script-src 'nonce-'`, // invalid nonce
'style-src "nonce-cmFuZG9tCg=="', // no script or default src
'', // empty string
]
for (const policy of policies) {
const $ = await renderWithPolicy(policy)
// Find all the script tags without src attributes and with nonce
// attributes.
const elements = $('script[nonce]:not([src])')
// Expect there to be none.
expect(elements.length).toBe(0)
}
})
it('includes a nonce value with inline scripts when Content-Security-Policy header is defined', async () => {
// A random nonce value, base64 encoded.
const nonce = 'cmFuZG9tCg=='
// Validate all the cases where we could parse the nonce.
const policies = [
`script-src 'nonce-${nonce}'`, // base case
` script-src 'nonce-${nonce}' `, // extra space added around sources and directive
`style-src 'self'; script-src 'nonce-${nonce}'`, // extra directives
`script-src 'self' 'nonce-${nonce}' 'nonce-othernonce'`, // extra nonces
`default-src 'nonce-othernonce'; script-src 'nonce-${nonce}';`, // script and then fallback case
`default-src 'nonce-${nonce}'`, // fallback case
]
for (const policy of policies) {
const $ = await renderWithPolicy(policy)
// Find all the script tags without src attributes.
const elements = $('script:not([src])')
// Expect there to be at least 1 script tag without a src attribute.
expect(elements.length).toBeGreaterThan(0)
// Expect all inline scripts to have the nonce value.
elements.each((i, el) => {
expect(el.attribs['nonce']).toBe(nonce)
})
}
})
it('includes a nonce value with bootstrap scripts when Content-Security-Policy header is defined', async () => {
// A random nonce value, base64 encoded.
const nonce = 'cmFuZG9tCg=='
// Validate all the cases where we could parse the nonce.
const policies = [
`script-src 'nonce-${nonce}'`, // base case
` script-src 'nonce-${nonce}' `, // extra space added around sources and directive
`style-src 'self'; script-src 'nonce-${nonce}'`, // extra directives
`script-src 'self' 'nonce-${nonce}' 'nonce-othernonce'`, // extra nonces
`default-src 'nonce-othernonce'; script-src 'nonce-${nonce}';`, // script and then fallback case
`default-src 'nonce-${nonce}'`, // fallback case
]
for (const policy of policies) {
const $ = await renderWithPolicy(policy)
// Find all the script tags without src attributes.
const elements = $('script[src]')
// Expect there to be at least 2 script tag with a src attribute.
// The main chunk and the webpack runtime.
expect(elements.length).toBeGreaterThan(1)
// Expect all inline scripts to have the nonce value.
elements.each((i, el) => {
expect(el.attribs['nonce']).toBe(nonce)
})
}
})
it('includes an integrity attribute on scripts', async () => {
const $ = await next.render$('/dashboard')
// Find all the script tags with src attributes.
const elements = $('script[src]')
// Expect there to be at least 1 script tag with a src attribute.
expect(elements.length).toBeGreaterThan(0)
// Collect all the scripts with integrity hashes so we can verify them.
const files: [string, string][] = []
// For each of these attributes, ensure that there's an integrity
// attribute and starts with the correct integrity hash prefix.
elements.each((i, el) => {
const integrity = el.attribs['integrity']
if (!integrity) {
console.log({ el })
}
expect(integrity).toBeDefined()
expect(integrity).toStartWith('sha256-')
const src = el.attribs['src']
expect(src).toBeDefined()
files.push([src, integrity])
})
// For each script tag, ensure that the integrity attribute is the
// correct hash of the script tag.
for (const [src, integrity] of files) {
const res = await next.fetch(src)
expect(res.status).toBe(200)
const content = await res.text()
const hash = crypto
.createHash('sha256')
.update(content)
.digest()
.toString('base64')
expect(integrity).toEndWith(hash)
}
})
it('throws when escape characters are included in nonce', async () => {
const res = await fetchWithPolicy(
`script-src 'nonce-"><script></script>"'`
)
expect(res.status).toBe(500)
})
}
)
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