Unverified Commit 1c1550ca authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

tests: Assert dpl query string in all tests for Turbopack (#90592)

Enable skew protection for all start-mode tests when Turbopack is enabled (i.e. not dev). This works by setting `NEXT_DEPLOYMENT_ID` in the test infra

- When running the tests, `packages/next/src/server/lib/router-utils/resolve-routes.ts` now validates that all static asset requests have the correct `?dpl=...` query param value, and returns a 404 if missing.
- It can be disabled with `disableAutoSkewProtection: true` in the test options
- There were various tests that were asserting URLs and were missing the optional `?dpl` at the end.
   - `next.getDeploymentIdQuery()` can be used to get the `?dpl=dpl_123912js` string (or an empty string)
   - `next.getAssetQuery()` currently behaves like `getDeploymentIdQuery`, but will switch to prefer the immutable static token in #88607
parent e027b6c2
...@@ -474,6 +474,27 @@ export function getResolveRoutes( ...@@ -474,6 +474,27 @@ export function getResolveRoutes(
if (output.locale) { if (output.locale) {
addRequestMeta(req, 'locale', output.locale) addRequestMeta(req, 'locale', output.locale)
} }
if (
process.env.__NEXT_TEST_MODE &&
process.env.IS_TURBOPACK_TEST &&
output.type === 'nextStaticFolder' &&
config.deploymentId
) {
const expectedToken = config.deploymentId
if (parsedUrl.query.dpl !== expectedToken) {
console.error(
`Invalid dpl query param: ${req.url}, expected: ${expectedToken}`
)
return {
finished: true,
parsedUrl,
resHeaders,
matchedOutput: null,
}
}
}
return { return {
parsedUrl, parsedUrl,
resHeaders, resHeaders,
......
...@@ -700,9 +700,26 @@ export default class NextNodeServer extends BaseServer< ...@@ -700,9 +700,26 @@ export default class NextNodeServer extends BaseServer<
return return
} }
const { isAbsolute, href } = paramsResult let { href } = paramsResult
const imageUpstream = isAbsolute if (
process.env.__NEXT_TEST_MODE &&
process.env.IS_TURBOPACK_TEST &&
!paramsResult.isAbsolute
) {
// Forward the dpl query param from the original /_next/image request to the
// internal static file request so that the static file validation in
// resolve-routes.ts can verify it.
const dpl =
typeof req.url === 'string'
? new URL(req.url, 'http://n').searchParams.get('dpl')
: undefined
if (dpl) {
href += `${href.includes('?') ? '&' : '?'}dpl=${dpl}`
}
}
const imageUpstream = paramsResult.isAbsolute
? await fetchExternalImage( ? await fetchExternalImage(
href, href,
this.nextConfig.images.dangerouslyAllowLocalIP, this.nextConfig.images.dangerouslyAllowLocalIP,
......
...@@ -210,6 +210,7 @@ export function runTests({ ...@@ -210,6 +210,7 @@ export function runTests({
files: join(__dirname, '..'), files: join(__dirname, '..'),
skipDeployment: true, skipDeployment: true,
skipStart: true, skipStart: true,
disableAutoSkewProtection: true,
}) })
if (skipped) { if (skipped) {
return return
......
...@@ -52,6 +52,7 @@ if (!(globalThis as any).isNextStart) { ...@@ -52,6 +52,7 @@ if (!(globalThis as any).isNextStart) {
/- Local:/, /- Local:/,
{ {
...process.env, ...process.env,
...next.env,
PORT: appPort.toString(), PORT: appPort.toString(),
}, },
undefined, undefined,
......
...@@ -69,6 +69,7 @@ if (!(globalThis as any).isNextStart) { ...@@ -69,6 +69,7 @@ if (!(globalThis as any).isNextStart) {
/- Local:/, /- Local:/,
{ {
...process.env, ...process.env,
...next.env,
PORT: appPort.toString(), PORT: appPort.toString(),
}, },
undefined, undefined,
......
...@@ -73,6 +73,7 @@ if (!(globalThis as any).isNextStart) { ...@@ -73,6 +73,7 @@ if (!(globalThis as any).isNextStart) {
/- Local:/, /- Local:/,
{ {
...process.env, ...process.env,
...next.env,
PORT: appPort.toString(), PORT: appPort.toString(),
}, },
undefined, undefined,
......
...@@ -61,7 +61,7 @@ for (const type of ['with-mdx-rs', 'without-mdx-rs']) { ...@@ -61,7 +61,7 @@ for (const type of ['with-mdx-rs', 'without-mdx-rs']) {
it('should work with next/image', async () => { it('should work with next/image', async () => {
const $ = await next.render$('/image') const $ = await next.render$('/image')
expect($('img').attr('src')).toBe( expect($('img').attr('src')).toBe(
'/_next/image?url=%2Ftest.jpg&w=384&q=75' `/_next/image?url=%2Ftest.jpg&w=384&q=75${next.getDeploymentIdQuery(true)}`
) )
}) })
......
import { join } from 'path' import { join } from 'path'
import { findPort, check } from 'next-test-utils' import { findPort, retry } from 'next-test-utils'
import https from 'https' import https from 'https'
import httpProxy from 'http-proxy' import httpProxy from 'http-proxy'
import fs from 'fs' import fs from 'fs'
...@@ -77,32 +77,21 @@ describe('next-image-proxy', () => { ...@@ -77,32 +77,21 @@ describe('next-image-proxy', () => {
}) })
const local = await browser.elementByCss('#app-page').getAttribute('src') const local = await browser.elementByCss('#app-page').getAttribute('src')
expect(local.replace(/test\.[0-9a-f]{8,}\.png/g, 'test.HASH.png')).toEqual(
if (process.env.IS_TURBOPACK_TEST) { `/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Ftest.HASH.png&w=828&q=90${next.getAssetQuery(true)}`
expect(local).toMatchInlineSnapshot(
`"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Ftest.c5ae911e.png&w=828&q=90"`
)
} else {
expect(local).toMatchInlineSnapshot(
`"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Ftest.3f1a293b.png&w=828&q=90"`
) )
}
const remote = await browser const remote = await browser
.elementByCss('#remote-app-page') .elementByCss('#remote-app-page')
.getAttribute('src') .getAttribute('src')
if (process.env.IS_TURBOPACK_TEST) { expect(remote).toEqual(
expect(remote).toMatchInlineSnapshot( `/_next/image?url=https%3A%2F%2Fimage-optimization-test.vercel.app%2Ftest.jpg&w=640&q=90`
`"/_next/image?url=https%3A%2F%2Fimage-optimization-test.vercel.app%2Ftest.jpg&w=640&q=90"`
) )
} else {
expect(remote).toMatchInlineSnapshot(
`"/_next/image?url=https%3A%2F%2Fimage-optimization-test.vercel.app%2Ftest.jpg&w=640&q=90"`
)
}
const expected = JSON.stringify({ fulfilledCount: 4, failCount: 0 }) await retry(() => {
await check(() => JSON.stringify({ fulfilledCount, failCount }), expected) expect(fulfilledCount).toBe(4)
expect(failCount).toBe(0)
})
await browser.close() await browser.close()
}) })
......
...@@ -75,8 +75,8 @@ describe('node-worker-threads', () => { ...@@ -75,8 +75,8 @@ describe('node-worker-threads', () => {
/\/_next\/static.*\/test-image\.[a-f0-9]+\.png/ /\/_next\/static.*\/test-image\.[a-f0-9]+\.png/
) )
if (!isNextDev) { if (!isNextDev) {
expect(next.deploymentId).toMatch(/.+/) expect(next.assetToken).toMatch(/.+/)
expect(url.searchParams.get('dpl')).toBe(next.deploymentId) expect(url.searchParams.get('dpl')).toBe(next.assetToken)
} }
// Now fetch the PNG URL from the client to verify it's accessible // Now fetch the PNG URL from the client to verify it's accessible
......
...@@ -65,6 +65,7 @@ describe('segment cache (deployment skew)', () => { ...@@ -65,6 +65,7 @@ describe('segment cache (deployment skew)', () => {
// rely on skew protection when deployed // rely on skew protection when deployed
NEXT_DEPLOYMENT_ID: isNextDeploy ? undefined : 'test-deployment-id', NEXT_DEPLOYMENT_ID: isNextDeploy ? undefined : 'test-deployment-id',
}, },
disableAutoSkewProtection: true,
}) })
// Deployment skew is hard to properly e2e deploy test, so this just checks for the header. // Deployment skew is hard to properly e2e deploy test, so this just checks for the header.
......
...@@ -22,7 +22,10 @@ describe('segment cache (output: "export")', () => { ...@@ -22,7 +22,10 @@ describe('segment cache (output: "export")', () => {
beforeAll(async () => { beforeAll(async () => {
const appDir = __dirname const appDir = __dirname
await nextBuild(appDir, undefined, { cwd: appDir }) await nextBuild(appDir, undefined, {
cwd: appDir,
disableAutoSkewProtection: true,
})
port = await findPort() port = await findPort()
server.listen(port) server.listen(port)
}) })
......
...@@ -8,6 +8,7 @@ describe('app dir - workers', () => { ...@@ -8,6 +8,7 @@ describe('app dir - workers', () => {
env: { env: {
NEXT_DEPLOYMENT_ID: isNextStart ? 'test-deployment-id' : undefined, NEXT_DEPLOYMENT_ID: isNextStart ? 'test-deployment-id' : undefined,
}, },
disableAutoSkewProtection: true,
}) })
function beforePageLoad(page: Page) { function beforePageLoad(page: Page) {
...@@ -17,7 +18,7 @@ describe('app dir - workers', () => { ...@@ -17,7 +18,7 @@ describe('app dir - workers', () => {
const url = request.url() const url = request.url()
if (url.includes('/_next/')) { if (url.includes('/_next/')) {
let parsed = new URL(url, next.url) let parsed = new URL(url, next.url)
expect(parsed.searchParams.get('dpl')).toBe(next.deploymentId) expect(parsed.searchParams.get('dpl')).toBe(next.assetToken)
} }
}) })
} }
......
...@@ -89,13 +89,11 @@ describe('Document and App - Rendering via HTTP', () => { ...@@ -89,13 +89,11 @@ describe('Document and App - Rendering via HTTP', () => {
}) })
$('link[rel=preload]').each((index, element) => { $('link[rel=preload]').each((index, element) => {
const href = $(element).attr('href') const href = $(element).attr('href')
expect(href.match(/\?/g)).toHaveLength(1) expect(href).toMatch(/^[^?]+\?ts=\d+$/)
expect(href).toMatch(/\?ts=/)
}) })
$('script[src]').each((index, element) => { $('script[src]').each((index, element) => {
const src = $(element).attr('src') const src = $(element).attr('src')
expect(src.match(/\?/g)).toHaveLength(1) expect(src).toMatch(/^[^?]+\?ts=\d+$/)
expect(src).toMatch(/\?ts=/)
}) })
}) })
} }
......
...@@ -9,7 +9,7 @@ describe('invalid-static-asset-404-app-asset-prefix', () => { ...@@ -9,7 +9,7 @@ describe('invalid-static-asset-404-app-asset-prefix', () => {
}) })
it('should return correct output with status 200 on valid asset path', async () => { it('should return correct output with status 200 on valid asset path', async () => {
const buildManifestPath = `/assets/_next/static/${next.buildId}/_buildManifest.js` const buildManifestPath = `/assets/_next/static/${next.buildId}/_buildManifest.js${next.getDeploymentIdQuery()}`
const res = await next.fetch(buildManifestPath) const res = await next.fetch(buildManifestPath)
expect(res.status).toBe(200) expect(res.status).toBe(200)
......
...@@ -9,7 +9,7 @@ describe('invalid-static-asset-404-app-base-path', () => { ...@@ -9,7 +9,7 @@ describe('invalid-static-asset-404-app-base-path', () => {
}) })
it('should return correct output with status 200 on valid asset path', async () => { it('should return correct output with status 200 on valid asset path', async () => {
const buildManifestPath = `/base/_next/static/${next.buildId}/_buildManifest.js` const buildManifestPath = `/base/_next/static/${next.buildId}/_buildManifest.js${next.getDeploymentIdQuery()}`
const res = await next.fetch(buildManifestPath) const res = await next.fetch(buildManifestPath)
expect(res.status).toBe(200) expect(res.status).toBe(200)
......
...@@ -6,7 +6,7 @@ describe('invalid-static-asset-404-app', () => { ...@@ -6,7 +6,7 @@ describe('invalid-static-asset-404-app', () => {
}) })
it('should return correct output with status 200 on valid asset path', async () => { it('should return correct output with status 200 on valid asset path', async () => {
const buildManifestPath = `/_next/static/${next.buildId}/_buildManifest.js` const buildManifestPath = `/_next/static/${next.buildId}/_buildManifest.js${next.getDeploymentIdQuery()}`
const res = await next.fetch(buildManifestPath) const res = await next.fetch(buildManifestPath)
expect(res.status).toBe(200) expect(res.status).toBe(200)
......
...@@ -9,7 +9,7 @@ describe('invalid-static-asset-404-pages-asset-prefix', () => { ...@@ -9,7 +9,7 @@ describe('invalid-static-asset-404-pages-asset-prefix', () => {
}) })
it('should return correct output with status 200 on valid asset path', async () => { it('should return correct output with status 200 on valid asset path', async () => {
const buildManifestPath = `/assets/_next/static/${next.buildId}/_buildManifest.js` const buildManifestPath = `/assets/_next/static/${next.buildId}/_buildManifest.js${next.getDeploymentIdQuery()}`
const res = await next.fetch(buildManifestPath) const res = await next.fetch(buildManifestPath)
expect(res.status).toBe(200) expect(res.status).toBe(200)
......
...@@ -9,7 +9,7 @@ describe('invalid-static-asset-404-pages-base-path', () => { ...@@ -9,7 +9,7 @@ describe('invalid-static-asset-404-pages-base-path', () => {
}) })
it('should return correct output with status 200 on valid asset path', async () => { it('should return correct output with status 200 on valid asset path', async () => {
const buildManifestPath = `/base/_next/static/${next.buildId}/_buildManifest.js` const buildManifestPath = `/base/_next/static/${next.buildId}/_buildManifest.js${next.getDeploymentIdQuery()}`
const res = await next.fetch(buildManifestPath) const res = await next.fetch(buildManifestPath)
expect(res.status).toBe(200) expect(res.status).toBe(200)
......
...@@ -6,7 +6,7 @@ describe('invalid-static-asset-404-pages', () => { ...@@ -6,7 +6,7 @@ describe('invalid-static-asset-404-pages', () => {
}) })
it('should return correct output with status 200 on valid asset path', async () => { it('should return correct output with status 200 on valid asset path', async () => {
const buildManifestPath = `/_next/static/${next.buildId}/_buildManifest.js` const buildManifestPath = `/_next/static/${next.buildId}/_buildManifest.js${next.getDeploymentIdQuery()}`
const res = await next.fetch(buildManifestPath) const res = await next.fetch(buildManifestPath)
expect(res.status).toBe(200) expect(res.status).toBe(200)
......
...@@ -76,7 +76,7 @@ describe('Middleware custom matchers with root', () => { ...@@ -76,7 +76,7 @@ describe('Middleware custom matchers with root', () => {
it('should not match', async () => { it('should not match', async () => {
const res = await next.fetch( const res = await next.fetch(
`/_next/static/${next.buildId}/_buildManifest.js` `/_next/static/${next.buildId}/_buildManifest.js${next.getDeploymentIdQuery()}`
) )
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(res.headers.get('x-from-middleware')).toBeFalsy() expect(res.headers.get('x-from-middleware')).toBeFalsy()
......
...@@ -125,6 +125,7 @@ describe('pages ssg data deployment skew - hard navigate when a new deployment o ...@@ -125,6 +125,7 @@ describe('pages ssg data deployment skew - hard navigate when a new deployment o
NEXT_DEPLOYMENT_ID: NEXT_DEPLOYMENT_ID1, NEXT_DEPLOYMENT_ID: NEXT_DEPLOYMENT_ID1,
OUTPUT_MODE, OUTPUT_MODE,
}, },
disableAutoSkewProtection: true,
}) })
let appPort1 = await findPort() let appPort1 = await findPort()
apps.push( apps.push(
...@@ -134,6 +135,7 @@ describe('pages ssg data deployment skew - hard navigate when a new deployment o ...@@ -134,6 +135,7 @@ describe('pages ssg data deployment skew - hard navigate when a new deployment o
NEXT_DEPLOYMENT_ID: NEXT_DEPLOYMENT_ID1, NEXT_DEPLOYMENT_ID: NEXT_DEPLOYMENT_ID1,
OUTPUT_MODE, OUTPUT_MODE,
}, },
disableAutoSkewProtection: true,
}) })
) )
...@@ -142,6 +144,7 @@ describe('pages ssg data deployment skew - hard navigate when a new deployment o ...@@ -142,6 +144,7 @@ describe('pages ssg data deployment skew - hard navigate when a new deployment o
DIST_DIR: '2', DIST_DIR: '2',
NEXT_DEPLOYMENT_ID: NEXT_DEPLOYMENT_ID2, NEXT_DEPLOYMENT_ID: NEXT_DEPLOYMENT_ID2,
}, },
disableAutoSkewProtection: true,
}) })
let appPort2 = await findPort() let appPort2 = await findPort()
apps.push( apps.push(
...@@ -150,6 +153,7 @@ describe('pages ssg data deployment skew - hard navigate when a new deployment o ...@@ -150,6 +153,7 @@ describe('pages ssg data deployment skew - hard navigate when a new deployment o
DIST_DIR: '2', DIST_DIR: '2',
NEXT_DEPLOYMENT_ID: NEXT_DEPLOYMENT_ID2, NEXT_DEPLOYMENT_ID: NEXT_DEPLOYMENT_ID2,
}, },
disableAutoSkewProtection: true,
}) })
) )
......
...@@ -102,6 +102,7 @@ if (isNextProd) { ...@@ -102,6 +102,7 @@ if (isNextProd) {
/Listening/, /Listening/,
{ {
...process.env, ...process.env,
...next.env,
PORT: appPort, PORT: appPort,
}, },
undefined, undefined,
......
...@@ -47,6 +47,7 @@ if (!(globalThis as any).isNextStart) { ...@@ -47,6 +47,7 @@ if (!(globalThis as any).isNextStart) {
/- Local:/, /- Local:/,
{ {
...process.env, ...process.env,
...next.env,
PORT: appPort.toString(), PORT: appPort.toString(),
}, },
undefined, undefined,
......
...@@ -16,6 +16,9 @@ describe(`Handle new URL asset references`, () => { ...@@ -16,6 +16,9 @@ describe(`Handle new URL asset references`, () => {
env: { env: {
// rely on skew protection when deployed // rely on skew protection when deployed
NEXT_DEPLOYMENT_ID: isNextStart ? 'test-deployment-id' : undefined, NEXT_DEPLOYMENT_ID: isNextStart ? 'test-deployment-id' : undefined,
VERCEL_IMMUTABLE_DEPLOYMENT_ID: isNextStart
? 'test-immutable-tkn-7890'
: undefined,
}, },
skipDeployment: true, skipDeployment: true,
}) })
...@@ -40,7 +43,7 @@ describe(`Handle new URL asset references`, () => { ...@@ -40,7 +43,7 @@ describe(`Handle new URL asset references`, () => {
if (isNextDev || !isTurbopack) { if (isNextDev || !isTurbopack) {
expectedToken = undefined expectedToken = undefined
} else { } else {
expectedToken = next.deploymentId expectedToken = next.assetToken
if (!expectedToken) { if (!expectedToken) {
throw new Error('Missing deployment id') throw new Error('Missing deployment id')
} }
......
...@@ -5,7 +5,9 @@ export default async function handler(req, res) { ...@@ -5,7 +5,9 @@ export default async function handler(req, res) {
const proxy = httpProxy.createProxy({ const proxy = httpProxy.createProxy({
target: `http://127.0.0.1:${port}/${ target: `http://127.0.0.1:${port}/${
req.query.buildId req.query.buildId
? `_next/static/${req.query.buildId}/_ssgManifest.js` ? process.env.NEXT_DEPLOYMENT_ID
? `_next/static/${req.query.buildId}/_ssgManifest.js?dpl=${process.env.NEXT_DEPLOYMENT_ID}`
: `_next/static/${req.query.buildId}/_ssgManifest.js`
: `user` : `user`
}`, }`,
ignorePath: true, ignorePath: true,
......
...@@ -37,7 +37,7 @@ function runTests() { ...@@ -37,7 +37,7 @@ function runTests() {
it('should inline critical CSS', async () => { it('should inline critical CSS', async () => {
const html = await renderViaHTTP(appPort, '/') const html = await renderViaHTTP(appPort, '/')
expect(html).toMatch( expect(html).toMatch(
/<link rel="stylesheet" href="\/_next\/static\/.*\.css" .*>/ /<link rel="stylesheet" href="\/_next\/static\/.*\.css(\?dpl=.*)?" .*>/
) )
expect(html).toMatch(/body{/) expect(html).toMatch(/body{/)
}) })
...@@ -45,7 +45,7 @@ function runTests() { ...@@ -45,7 +45,7 @@ function runTests() {
it('should inline critical CSS (dynamic)', async () => { it('should inline critical CSS (dynamic)', async () => {
const html = await renderViaHTTP(appPort, '/another') const html = await renderViaHTTP(appPort, '/another')
expect(html).toMatch( expect(html).toMatch(
/<link rel="stylesheet" href="\/_next\/static\/.*\.css" .*>/ /<link rel="stylesheet" href="\/_next\/static\/.*\.css(\?dpl=.*)?" .*>/
) )
expect(html).toMatch(/body{/) expect(html).toMatch(/body{/)
}) })
...@@ -70,9 +70,12 @@ describe('CSS optimization for SSR apps', () => { ...@@ -70,9 +70,12 @@ describe('CSS optimization for SSR apps', () => {
if (fs.pathExistsSync(join(appDir, '.next'))) { if (fs.pathExistsSync(join(appDir, '.next'))) {
await fs.remove(join(appDir, '.next')) await fs.remove(join(appDir, '.next'))
} }
await nextBuild(appDir) // TODO optimizeCss is broken when ?dpl is added to CSS URLs
await nextBuild(appDir, undefined, { disableAutoSkewProtection: true })
appPort = await findPort() appPort = await findPort()
app = await nextStart(appDir, appPort) app = await nextStart(appDir, appPort, {
disableAutoSkewProtection: true,
})
}) })
afterAll(async () => { afterAll(async () => {
await killApp(app) await killApp(app)
......
...@@ -2653,12 +2653,15 @@ describe('Custom routes', () => { ...@@ -2653,12 +2653,15 @@ describe('Custom routes', () => {
{ {
stdout: true, stdout: true,
stderr: true, stderr: true,
disableAutoSkewProtection: true,
} }
) )
stdout = buildStdout stdout = buildStdout
stderr = buildStderr stderr = buildStderr
appPort = await findPort() appPort = await findPort()
app = await nextStart(appDir, appPort) app = await nextStart(appDir, appPort, {
disableAutoSkewProtection: true,
})
buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8') buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8')
}) })
afterAll(() => killApp(app)) afterAll(() => killApp(app))
......
...@@ -1582,8 +1582,6 @@ function runTests({ dev }) { ...@@ -1582,8 +1582,6 @@ function runTests({ dev }) {
} }
} }
const nextConfig = join(appDir, 'next.config.js')
describe('Dynamic Routing', () => { describe('Dynamic Routing', () => {
if (process.env.__MIDDLEWARE_TEST) { if (process.env.__MIDDLEWARE_TEST) {
const middlewarePath = join(__dirname, '../middleware.js') const middlewarePath = join(__dirname, '../middleware.js')
...@@ -1606,8 +1604,6 @@ describe('Dynamic Routing', () => { ...@@ -1606,8 +1604,6 @@ describe('Dynamic Routing', () => {
'development mode', 'development mode',
() => { () => {
beforeAll(async () => { beforeAll(async () => {
await fs.remove(nextConfig)
appPort = await findPort() appPort = await findPort()
app = await launchApp(appDir, appPort) app = await launchApp(appDir, appPort)
buildId = 'development' buildId = 'development'
...@@ -1621,13 +1617,15 @@ describe('Dynamic Routing', () => { ...@@ -1621,13 +1617,15 @@ describe('Dynamic Routing', () => {
'production mode', 'production mode',
() => { () => {
beforeAll(async () => { beforeAll(async () => {
await fs.remove(nextConfig) await nextBuild(appDir, undefined, {
disableAutoSkewProtection: true,
await nextBuild(appDir) })
buildId = await fs.readFile(buildIdPath, 'utf8') buildId = await fs.readFile(buildIdPath, 'utf8')
appPort = await findPort() appPort = await findPort()
app = await nextStart(appDir, appPort) app = await nextStart(appDir, appPort, {
disableAutoSkewProtection: true,
})
}) })
afterAll(() => killApp(app)) afterAll(() => killApp(app))
......
...@@ -13,6 +13,7 @@ import { ...@@ -13,6 +13,7 @@ import {
waitFor, waitFor,
normalizeRegEx, normalizeRegEx,
check, check,
getDeploymentId,
} from 'next-test-utils' } from 'next-test-utils'
const domainLocales = ['go', 'go-BE', 'do', 'do-BE'] const domainLocales = ['go', 'go-BE', 'do', 'do-BE']
...@@ -61,16 +62,22 @@ export function runTests(ctx) { ...@@ -61,16 +62,22 @@ export function runTests(ctx) {
cwd: join(ctx.appDir, '.next/static'), cwd: join(ctx.appDir, '.next/static'),
}) })
const deploymentDpl = getDeploymentId(ctx.appDir, ctx.isDev)
// Only use a subset of the locales to speed up the test // Only use a subset of the locales to speed up the test
for (const locale of [ for (const locale of [
...nonDomainLocales.slice(0, 2), ...nonDomainLocales.slice(0, 2),
...domainLocales.slice(0, 2), ...domainLocales.slice(0, 2),
]) { ]) {
for (const asset of assets) { for (const asset of assets) {
const dpl = asset.includes(ctx.buildId)
? deploymentDpl.getDeploymentIdQuery()
: deploymentDpl.getAssetQuery()
// _next/static asset // _next/static asset
const res = await fetchViaHTTP( const res = await fetchViaHTTP(
ctx.appPort, ctx.appPort,
`${ctx.basePath || ''}/${locale}/_next/static/${encodeURI(asset)}`, `${ctx.basePath || ''}/${locale}/_next/static/${encodeURI(asset)}${dpl}`,
undefined, undefined,
{ redirect: 'manual' } { redirect: 'manual' }
) )
......
...@@ -8,6 +8,7 @@ import { ...@@ -8,6 +8,7 @@ import {
fetchViaHTTP, fetchViaHTTP,
File, File,
findPort, findPort,
getDeploymentId,
getDistDir, getDistDir,
killApp, killApp,
launchApp, launchApp,
...@@ -1522,10 +1523,14 @@ export function runTests(ctx: RunTestsCtx) { ...@@ -1522,10 +1523,14 @@ export function runTests(ctx: RunTestsCtx) {
.readdirSync(join(ctx.appDir, '.next/static/media')) .readdirSync(join(ctx.appDir, '.next/static/media'))
.find((f) => /^test\.[0-9a-f]+\.jpg$/.test(f)) .find((f) => /^test\.[0-9a-f]+\.jpg$/.test(f))
expect(filename).toBeString() expect(filename).toBeString()
const query = { const query: Record<string, string> = {
url: `/_next/static/media/${filename}`, url: `/_next/static/media/${filename}`,
w: ctx.w, w: String(ctx.w),
q: ctx.q, q: String(ctx.q),
}
const assetToken = getDeploymentId(ctx.appDir, false).assetToken
if (assetToken) {
query.dpl = assetToken
} }
const opts = { headers: { accept: 'image/webp' } } const opts = { headers: { accept: 'image/webp' } }
......
...@@ -11,6 +11,7 @@ import { ...@@ -11,6 +11,7 @@ import {
nextBuild, nextBuild,
nextStart, nextStart,
waitFor, waitFor,
getDeploymentId,
} from 'next-test-utils' } from 'next-test-utils'
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
import { join } from 'path' import { join } from 'path'
...@@ -58,7 +59,12 @@ function getRatio(width, height) { ...@@ -58,7 +59,12 @@ function getRatio(width, height) {
return height / width return height / width
} }
function runTests(mode) { function runTests(mode: 'dev' | 'server') {
let dpl: string
beforeAll(() => {
dpl = getDeploymentId(appDir, mode === 'dev').getDeploymentIdQuery(true)
})
it('should load the images', async () => { it('should load the images', async () => {
let browser = await webdriver(appPort, '/docs') let browser = await webdriver(appPort, '/docs')
try { try {
...@@ -75,7 +81,7 @@ function runTests(mode) { ...@@ -75,7 +81,7 @@ function runTests(mode) {
}, /result-correct/) }, /result-correct/)
expect(await getImageUrls(browser)).toContain( expect(await getImageUrls(browser)).toContain(
`http://localhost:${appPort}/docs/_next/image?url=%2Fdocs%2Ftest.jpg&w=828&q=75` `http://localhost:${appPort}/docs/_next/image?url=%2Fdocs%2Ftest.jpg&w=828&q=75${dpl}`
) )
} finally { } finally {
await browser.close() await browser.close()
...@@ -127,10 +133,10 @@ function runTests(mode) { ...@@ -127,10 +133,10 @@ function runTests(mode) {
const delta = 250 const delta = 250
const id = 'fixed1' const id = 'fixed1'
expect(await getSrc(browser, id)).toBe( expect(await getSrc(browser, id)).toBe(
'/docs/_next/image?url=%2Fdocs%2Fwide.png&w=3840&q=75' `/docs/_next/image?url=%2Fdocs%2Fwide.png&w=3840&q=75${dpl}`
) )
expect(await browser.elementById(id).getAttribute('srcset')).toBe( expect(await browser.elementById(id).getAttribute('srcset')).toBe(
'/docs/_next/image?url=%2Fdocs%2Fwide.png&w=1200&q=75 1x, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=3840&q=75 2x' `/docs/_next/image?url=%2Fdocs%2Fwide.png&w=1200&q=75${dpl} 1x, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=3840&q=75${dpl} 2x`
) )
expect(await browser.elementById(id).getAttribute('sizes')).toBeFalsy() expect(await browser.elementById(id).getAttribute('sizes')).toBeFalsy()
await browser.setDimensions({ await browser.setDimensions({
...@@ -160,12 +166,12 @@ function runTests(mode) { ...@@ -160,12 +166,12 @@ function runTests(mode) {
await check(async () => { await check(async () => {
expect(await getSrc(browser, id)).toBe( expect(await getSrc(browser, id)).toBe(
'/docs/_next/image?url=%2Fdocs%2Fwide.png&w=3840&q=75' `/docs/_next/image?url=%2Fdocs%2Fwide.png&w=3840&q=75${dpl}`
) )
return 'success' return 'success'
}, 'success') }, 'success')
expect(await browser.elementById(id).getAttribute('srcset')).toBe( expect(await browser.elementById(id).getAttribute('srcset')).toBe(
'/docs/_next/image?url=%2Fdocs%2Fwide.png&w=1200&q=75 1x, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=3840&q=75 2x' `/docs/_next/image?url=%2Fdocs%2Fwide.png&w=1200&q=75${dpl} 1x, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=3840&q=75${dpl} 2x`
) )
expect(await browser.elementById(id).getAttribute('sizes')).toBeFalsy() expect(await browser.elementById(id).getAttribute('sizes')).toBeFalsy()
await browser.setDimensions({ await browser.setDimensions({
...@@ -201,12 +207,12 @@ function runTests(mode) { ...@@ -201,12 +207,12 @@ function runTests(mode) {
await check(async () => { await check(async () => {
expect(await getSrc(browser, id)).toBe( expect(await getSrc(browser, id)).toBe(
'/docs/_next/image?url=%2Fdocs%2Fwide.png&w=3840&q=75' `/docs/_next/image?url=%2Fdocs%2Fwide.png&w=3840&q=75${dpl}`
) )
return 'success' return 'success'
}, 'success') }, 'success')
expect(await browser.elementById(id).getAttribute('srcset')).toBe( expect(await browser.elementById(id).getAttribute('srcset')).toBe(
'/docs/_next/image?url=%2Fdocs%2Fwide.png&w=640&q=75 640w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=750&q=75 750w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=828&q=75 828w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=1080&q=75 1080w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=1200&q=75 1200w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=1920&q=75 1920w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=2048&q=75 2048w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=3840&q=75 3840w' `/docs/_next/image?url=%2Fdocs%2Fwide.png&w=640&q=75${dpl} 640w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=750&q=75${dpl} 750w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=828&q=75${dpl} 828w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=1080&q=75${dpl} 1080w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=1200&q=75${dpl} 1200w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=1920&q=75${dpl} 1920w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=2048&q=75${dpl} 2048w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=3840&q=75${dpl} 3840w`
) )
expect(await browser.elementById(id).getAttribute('sizes')).toBe('100vw') expect(await browser.elementById(id).getAttribute('sizes')).toBe('100vw')
await browser.setDimensions({ await browser.setDimensions({
...@@ -242,12 +248,12 @@ function runTests(mode) { ...@@ -242,12 +248,12 @@ function runTests(mode) {
await check(async () => { await check(async () => {
expect(await getSrc(browser, id)).toBe( expect(await getSrc(browser, id)).toBe(
'/docs/_next/image?url=%2Fdocs%2Fwide.png&w=3840&q=75' `/docs/_next/image?url=%2Fdocs%2Fwide.png&w=3840&q=75${dpl}`
) )
return 'success' return 'success'
}, 'success') }, 'success')
expect(await browser.elementById(id).getAttribute('srcset')).toBe( expect(await browser.elementById(id).getAttribute('srcset')).toBe(
'/docs/_next/image?url=%2Fdocs%2Fwide.png&w=640&q=75 640w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=750&q=75 750w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=828&q=75 828w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=1080&q=75 1080w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=1200&q=75 1200w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=1920&q=75 1920w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=2048&q=75 2048w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=3840&q=75 3840w' `/docs/_next/image?url=%2Fdocs%2Fwide.png&w=640&q=75${dpl} 640w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=750&q=75${dpl} 750w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=828&q=75${dpl} 828w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=1080&q=75${dpl} 1080w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=1200&q=75${dpl} 1200w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=1920&q=75${dpl} 1920w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=2048&q=75${dpl} 2048w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=3840&q=75${dpl} 3840w`
) )
expect(await browser.elementById(id).getAttribute('sizes')).toBe('100vw') expect(await browser.elementById(id).getAttribute('sizes')).toBe('100vw')
await browser.setDimensions({ await browser.setDimensions({
...@@ -283,12 +289,12 @@ function runTests(mode) { ...@@ -283,12 +289,12 @@ function runTests(mode) {
await check(async () => { await check(async () => {
expect(await getSrc(browser, id)).toBe( expect(await getSrc(browser, id)).toBe(
'/docs/_next/image?url=%2Fdocs%2Fwide.png&w=3840&q=75' `/docs/_next/image?url=%2Fdocs%2Fwide.png&w=3840&q=75${dpl}`
) )
return 'success' return 'success'
}, 'success') }, 'success')
expect(await browser.elementById(id).getAttribute('srcset')).toBe( expect(await browser.elementById(id).getAttribute('srcset')).toBe(
'/docs/_next/image?url=%2Fdocs%2Fwide.png&w=640&q=75 640w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=750&q=75 750w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=828&q=75 828w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=1080&q=75 1080w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=1200&q=75 1200w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=1920&q=75 1920w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=2048&q=75 2048w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=3840&q=75 3840w' `/docs/_next/image?url=%2Fdocs%2Fwide.png&w=640&q=75${dpl} 640w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=750&q=75${dpl} 750w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=828&q=75${dpl} 828w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=1080&q=75${dpl} 1080w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=1200&q=75${dpl} 1200w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=1920&q=75${dpl} 1920w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=2048&q=75${dpl} 2048w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=3840&q=75${dpl} 3840w`
) )
expect(await browser.elementById(id).getAttribute('sizes')).toBe('100vw') expect(await browser.elementById(id).getAttribute('sizes')).toBe('100vw')
expect(await getComputed(browser, id, 'width')).toBe(width) expect(await getComputed(browser, id, 'width')).toBe(width)
...@@ -334,12 +340,12 @@ function runTests(mode) { ...@@ -334,12 +340,12 @@ function runTests(mode) {
await check(async () => { await check(async () => {
expect(await getSrc(browser, id)).toBe( expect(await getSrc(browser, id)).toBe(
'/docs/_next/image?url=%2Fdocs%2Fwide.png&w=3840&q=75' `/docs/_next/image?url=%2Fdocs%2Fwide.png&w=3840&q=75${dpl}`
) )
return 'success' return 'success'
}, 'success') }, 'success')
expect(await browser.elementById(id).getAttribute('srcset')).toBe( expect(await browser.elementById(id).getAttribute('srcset')).toBe(
'/docs/_next/image?url=%2Fdocs%2Fwide.png&w=32&q=75 32w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=48&q=75 48w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=64&q=75 64w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=96&q=75 96w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=128&q=75 128w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=256&q=75 256w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=384&q=75 384w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=640&q=75 640w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=750&q=75 750w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=828&q=75 828w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=1080&q=75 1080w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=1200&q=75 1200w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=1920&q=75 1920w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=2048&q=75 2048w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=3840&q=75 3840w' `/docs/_next/image?url=%2Fdocs%2Fwide.png&w=32&q=75${dpl} 32w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=48&q=75${dpl} 48w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=64&q=75${dpl} 64w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=96&q=75${dpl} 96w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=128&q=75${dpl} 128w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=256&q=75${dpl} 256w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=384&q=75${dpl} 384w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=640&q=75${dpl} 640w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=750&q=75${dpl} 750w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=828&q=75${dpl} 828w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=1080&q=75${dpl} 1080w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=1200&q=75${dpl} 1200w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=1920&q=75${dpl} 1920w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=2048&q=75${dpl} 2048w, /docs/_next/image?url=%2Fdocs%2Fwide.png&w=3840&q=75${dpl} 3840w`
) )
expect(await browser.elementById(id).getAttribute('sizes')).toBe( expect(await browser.elementById(id).getAttribute('sizes')).toBe(
'(max-width: 2048px) 1200px, 3840px' '(max-width: 2048px) 1200px, 3840px'
......
...@@ -2,12 +2,13 @@ ...@@ -2,12 +2,13 @@
import { join } from 'path' import { join } from 'path'
import { import {
check,
findPort, findPort,
getDeploymentId,
killApp, killApp,
launchApp, launchApp,
nextBuild, nextBuild,
nextStart, nextStart,
retry,
} from 'next-test-utils' } from 'next-test-utils'
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
...@@ -15,10 +16,13 @@ const appDir = join(__dirname, '../') ...@@ -15,10 +16,13 @@ const appDir = join(__dirname, '../')
let appPort let appPort
let app let app
function runTests() { function runTests(mode: 'dev' | 'server') {
it('should not optimize any image', async () => { it('should not optimize any image', async () => {
const browser = await webdriver(appPort, '/') const browser = await webdriver(appPort, '/')
const dpl = getDeploymentId(appDir, mode === 'dev').getDeploymentIdQuery()
const assetDpl = getDeploymentId(appDir, mode === 'dev').getAssetQuery()
expect( expect(
await browser.elementById('internal-image').getAttribute('src') await browser.elementById('internal-image').getAttribute('src')
).toMatch('data:') ).toMatch('data:')
...@@ -29,7 +33,7 @@ function runTests() { ...@@ -29,7 +33,7 @@ function runTests() {
await browser.elementById('external-image').getAttribute('src') await browser.elementById('external-image').getAttribute('src')
).toMatch('data:') ).toMatch('data:')
expect(await browser.elementById('eager-image').getAttribute('src')).toBe( expect(await browser.elementById('eager-image').getAttribute('src')).toBe(
'/test.webp' `/test.webp${dpl}`
) )
expect( expect(
...@@ -45,42 +49,55 @@ function runTests() { ...@@ -45,42 +49,55 @@ function runTests() {
await browser.elementById('eager-image').getAttribute('srcset') await browser.elementById('eager-image').getAttribute('srcset')
).toBeNull() ).toBeNull()
await check(async () => { await retry(async () => {
await browser.eval( await browser.eval(
`window.scrollTo(0, 0); document.getElementById("external-image").scrollIntoView()` `window.scrollTo(0, 0); document.getElementById("external-image").scrollIntoView()`
) )
return browser.eval( expect(
await browser.eval(
`document.getElementById("external-image").currentSrc` `document.getElementById("external-image").currentSrc`
) )
}, 'https://image-optimization-test.vercel.app/test.jpg') ).toBe('https://image-optimization-test.vercel.app/test.jpg')
})
await check(async () => { await retry(async () => {
await browser.eval( await browser.eval(
`window.scrollTo(0, 0); document.getElementById("internal-image").scrollIntoView()` `window.scrollTo(0, 0); document.getElementById("internal-image").scrollIntoView()`
) )
return browser.elementById('internal-image').getAttribute('src') expect(
}, '/test.png') await browser.elementById('internal-image').getAttribute('src')
).toBe(`/test.png${dpl}`)
})
await check(async () => { await retry(async () => {
await browser.eval( await browser.eval(
`window.scrollTo(0, 0); document.getElementById("static-image").scrollIntoView()` `window.scrollTo(0, 0); document.getElementById("static-image").scrollIntoView()`
) )
return browser.elementById('static-image').getAttribute('src') expect(
}, /test(.*)jpg/) (await browser.elementById('static-image').getAttribute('src')).replace(
/test\.[a-z0-9]+\.jpg/,
'test.HASH.jpg'
)
).toMatch('/_next/static/media/test.HASH.jpg' + assetDpl)
})
await check(async () => { await retry(async () => {
await browser.eval( await browser.eval(
`window.scrollTo(0, 0); document.getElementById("external-image").scrollIntoView()` `window.scrollTo(0, 0); document.getElementById("external-image").scrollIntoView()`
) )
return browser.elementById('external-image').getAttribute('src') expect(
}, 'https://image-optimization-test.vercel.app/test.jpg') await browser.elementById('external-image').getAttribute('src')
).toBe('https://image-optimization-test.vercel.app/test.jpg')
})
await check(async () => { await retry(async () => {
await browser.eval( await browser.eval(
`window.scrollTo(0, 0); document.getElementById("eager-image").scrollIntoView()` `window.scrollTo(0, 0); document.getElementById("eager-image").scrollIntoView()`
) )
return browser.elementById('eager-image').getAttribute('src') expect(await browser.elementById('eager-image').getAttribute('src')).toBe(
}, '/test.webp') `/test.webp${dpl}`
)
})
expect( expect(
await browser.elementById('internal-image').getAttribute('srcset') await browser.elementById('internal-image').getAttribute('srcset')
...@@ -109,7 +126,7 @@ describe('Unoptimized Image Tests', () => { ...@@ -109,7 +126,7 @@ describe('Unoptimized Image Tests', () => {
await killApp(app) await killApp(app)
}) })
runTests() runTests('dev')
} }
) )
;(process.env.TURBOPACK_DEV ? describe.skip : describe)( ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
...@@ -124,7 +141,7 @@ describe('Unoptimized Image Tests', () => { ...@@ -124,7 +141,7 @@ describe('Unoptimized Image Tests', () => {
await killApp(app) await killApp(app)
}) })
runTests() runTests('server')
} }
) )
}) })
...@@ -11,6 +11,7 @@ import { ...@@ -11,6 +11,7 @@ import {
nextBuild, nextBuild,
nextStart, nextStart,
waitFor, waitFor,
getDeploymentId,
} from 'next-test-utils' } from 'next-test-utils'
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
import { join } from 'path' import { join } from 'path'
...@@ -50,7 +51,7 @@ function getRatio(width, height) { ...@@ -50,7 +51,7 @@ function getRatio(width, height) {
return height / width return height / width
} }
function runTests(mode) { function runTests(mode: 'dev' | 'server') {
it('should load the images', async () => { it('should load the images', async () => {
let browser let browser
try { try {
...@@ -69,7 +70,7 @@ function runTests(mode) { ...@@ -69,7 +70,7 @@ function runTests(mode) {
}, /result-correct/) }, /result-correct/)
expect(await getImageUrls(browser)).toContain( expect(await getImageUrls(browser)).toContain(
`http://localhost:${appPort}/docs/_next/image?url=%2Fdocs%2Ftest.jpg&w=828&q=75` `http://localhost:${appPort}/docs/_next/image?url=%2Fdocs%2Ftest.jpg&w=828&q=75${getDeploymentId(appDir, mode === 'dev').getDeploymentIdQuery(true)}`
) )
} finally { } finally {
if (browser) { if (browser) {
......
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
import { import {
fetchViaHTTP, fetchViaHTTP,
findPort, findPort,
getDeploymentId,
killApp, killApp,
launchApp, launchApp,
nextBuild, nextBuild,
...@@ -16,25 +17,32 @@ const appDir = join(__dirname, '../') ...@@ -16,25 +17,32 @@ const appDir = join(__dirname, '../')
let appPort let appPort
let app let app
const runTests = () => { const runTests = (mode: 'dev' | 'server') => {
let dpl: string
let assetDpl: string
beforeAll(() => {
dpl = getDeploymentId(appDir, mode === 'dev').getDeploymentIdQuery(true)
assetDpl = getDeploymentId(appDir, mode === 'dev').getAssetQuery(true)
})
it('should correctly load image src from import', async () => { it('should correctly load image src from import', async () => {
expect.assertions(3)
const browser = await webdriver(appPort, '/prefix/') const browser = await webdriver(appPort, '/prefix/')
const img = await browser.elementById('import-img') const img = await browser.elementById('import-img')
const src = await img.getAttribute('src') const src = await img.getAttribute('src')
expect(src).toMatch( expect(stripTestHash(src)).toBe(
/\/prefix\/_next\/image\/\?url=%2Fprefix%2F_next%2Fstatic%2Fmedia%2Ftest\.(.*)\.jpg&w=828&q=75/ `/prefix/_next/image/?url=%2Fprefix%2F_next%2Fstatic%2Fmedia%2Ftest.HASH.jpg&w=828&q=75${assetDpl}`
) )
const res = await fetchViaHTTP(appPort, src) const res = await fetchViaHTTP(appPort, src)
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toBe('image/jpeg') expect(res.headers.get('content-type')).toBe('image/jpeg')
}) })
it('should correctly load image src from string', async () => { it('should correctly load image src from string', async () => {
expect.assertions(3)
const browser = await webdriver(appPort, '/prefix/') const browser = await webdriver(appPort, '/prefix/')
const img = await browser.elementById('string-img') const img = await browser.elementById('string-img')
const src = await img.getAttribute('src') const src = await img.getAttribute('src')
expect(src).toBe('/prefix/_next/image/?url=%2Fprefix%2Ftest.jpg&w=640&q=75') expect(src).toBe(
`/prefix/_next/image/?url=%2Fprefix%2Ftest.jpg&w=640&q=75${dpl}`
)
const res = await fetchViaHTTP(appPort, src) const res = await fetchViaHTTP(appPort, src)
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toBe('image/jpeg') expect(res.headers.get('content-type')).toBe('image/jpeg')
...@@ -51,7 +59,7 @@ describe('Image Component basePath + trailingSlash Tests', () => { ...@@ -51,7 +59,7 @@ describe('Image Component basePath + trailingSlash Tests', () => {
}) })
afterAll(() => killApp(app)) afterAll(() => killApp(app))
runTests() runTests('dev')
} }
) )
;(process.env.TURBOPACK_DEV ? describe.skip : describe)( ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
...@@ -64,7 +72,11 @@ describe('Image Component basePath + trailingSlash Tests', () => { ...@@ -64,7 +72,11 @@ describe('Image Component basePath + trailingSlash Tests', () => {
}) })
afterAll(() => killApp(app)) afterAll(() => killApp(app))
runTests() runTests('server')
} }
) )
}) })
function stripTestHash(text: string) {
return text.replace(/test\.[0-9a-f]{8,}\.(png|jpe?g)/g, 'test.HASH.$1')
}
...@@ -20,9 +20,11 @@ describe('Production Config Usage', () => { ...@@ -20,9 +20,11 @@ describe('Production Config Usage', () => {
'production mode', 'production mode',
() => { () => {
beforeAll(async () => { beforeAll(async () => {
await nextBuild(appDir) await nextBuild(appDir, undefined, { disableAutoSkewProtection: true })
appPort = await findPort() appPort = await findPort()
app = await nextStart(appDir, appPort) app = await nextStart(appDir, appPort, {
disableAutoSkewProtection: true,
})
}) })
afterAll(() => killApp(app)) afterAll(() => killApp(app))
......
...@@ -54,6 +54,7 @@ export interface NextInstanceOpts { ...@@ -54,6 +54,7 @@ export interface NextInstanceOpts {
serverReadyPattern?: RegExp serverReadyPattern?: RegExp
patchFileDelay?: number patchFileDelay?: number
startServerTimeout?: number startServerTimeout?: number
disableAutoSkewProtection?: boolean
} }
/** /**
...@@ -641,8 +642,18 @@ export class NextInstance { ...@@ -641,8 +642,18 @@ export class NextInstance {
return undefined return undefined
} }
public get deploymentIdQuery(): string { public getDeploymentIdQuery(ampersand: boolean = false): string | undefined {
return this.deploymentId ? `?dpl=${this.deploymentId}` : '' const prefix = ampersand ? '&' : '?'
return this.deploymentId ? `${prefix}dpl=${this.deploymentId}` : ''
}
public get assetToken(): string | undefined {
return this.deploymentId
}
public getAssetQuery(ampersand: boolean = false): string | undefined {
const prefix = ampersand ? '&' : '?'
return this.assetToken ? `${prefix}dpl=${this.assetToken}` : ''
} }
public get cliOutput(): string { public get cliOutput(): string {
......
import path from 'path' import path from 'path'
import fs from 'fs-extra' import fs from 'fs-extra'
import { NextInstance } from './base' import { NextInstance, type NextInstanceOpts } from './base'
import spawn from 'cross-spawn' import spawn from 'cross-spawn'
import { Span } from 'next/dist/trace' import { Span } from 'next/dist/trace'
import stripAnsi from 'strip-ansi' import stripAnsi from 'strip-ansi'
import { quote as shellQuote } from 'shell-quote' import { quote as shellQuote } from 'shell-quote'
import { shouldUseTurbopack } from 'next-test-utils'
export class NextStartInstance extends NextInstance { export class NextStartInstance extends NextInstance {
private _buildId: string private _buildId: string
...@@ -13,6 +14,14 @@ export class NextStartInstance extends NextInstance { ...@@ -13,6 +14,14 @@ export class NextStartInstance extends NextInstance {
private _prerenderFinishedTimeMS: number | null = null private _prerenderFinishedTimeMS: number | null = null
constructor(opts: NextInstanceOpts) {
super(opts)
if (!opts.disableAutoSkewProtection && shouldUseTurbopack()) {
this.env.NEXT_DEPLOYMENT_ID = 'test-dpl-id-1234'
}
}
public get buildId() { public get buildId() {
return this._buildId return this._buildId
} }
......
...@@ -265,6 +265,7 @@ export interface NextOptions { ...@@ -265,6 +265,7 @@ export interface NextOptions {
stderr?: true | 'log' stderr?: true | 'log'
stdout?: true | 'log' stdout?: true | 'log'
ignoreFail?: boolean ignoreFail?: boolean
disableAutoSkewProtection?: boolean
onStdout?: (data: any) => void onStdout?: (data: any) => void
onStderr?: (data: any) => void onStderr?: (data: any) => void
...@@ -283,7 +284,7 @@ export function runNextCommand( ...@@ -283,7 +284,7 @@ export function runNextCommand(
const nextBin = path.join(nextDir, 'dist/bin/next') const nextBin = path.join(nextDir, 'dist/bin/next')
const cwd = options.cwd || nextDir const cwd = options.cwd || nextDir
// Let Next.js decide the environment // Let Next.js decide the environment
const env = { const env: NodeJS.ProcessEnv = {
...process.env, ...process.env,
// @ts-ignore packages/next/types/global.d.ts should allow undefined NODE_ENV // @ts-ignore packages/next/types/global.d.ts should allow undefined NODE_ENV
NODE_ENV: undefined as NodeJS.ProcessEnv['NODE_ENV'], NODE_ENV: undefined as NodeJS.ProcessEnv['NODE_ENV'],
...@@ -390,6 +391,7 @@ export interface NextDevOptions { ...@@ -390,6 +391,7 @@ export interface NextDevOptions {
bootupMarker?: RegExp bootupMarker?: RegExp
nextStart?: boolean nextStart?: boolean
turbo?: boolean turbo?: boolean
disableAutoSkewProtection?: boolean
stderr?: false stderr?: false
stdout?: false stdout?: false
...@@ -517,6 +519,11 @@ export function nextBuild( ...@@ -517,6 +519,11 @@ export function nextBuild(
args: string[] = [], args: string[] = [],
opts: NextOptions = {} opts: NextOptions = {}
) { ) {
if (!opts.disableAutoSkewProtection && shouldUseTurbopack() && !opts.env) {
opts.env ??= {}
opts.env.NEXT_DEPLOYMENT_ID = 'test-dpl-id-1234'
}
return runNextCommand(['build', dir, ...args], opts) return runNextCommand(['build', dir, ...args], opts)
} }
...@@ -539,6 +546,11 @@ export function nextStart( ...@@ -539,6 +546,11 @@ export function nextStart(
port: string | number, port: string | number,
opts: NextDevOptions = {} opts: NextDevOptions = {}
) { ) {
if (!opts.disableAutoSkewProtection && shouldUseTurbopack() && !opts.env) {
opts.env ??= {}
opts.env.NEXT_DEPLOYMENT_ID = 'test-dpl-id-1234'
}
return runNextCommandDev( return runNextCommandDev(
['start', '-p', port as string, '--hostname', '::', dir], ['start', '-p', port as string, '--hostname', '::', dir],
undefined, undefined,
...@@ -2040,3 +2052,36 @@ export function getClientReferenceManifest( ...@@ -2040,3 +2052,36 @@ export function getClientReferenceManifest(
export const getCacheHeader = (curRes: Response) => export const getCacheHeader = (curRes: Response) =>
// favor generic header // favor generic header
curRes.headers.get('x-nextjs-cache') || curRes.headers.get('x-vercel-cache') curRes.headers.get('x-nextjs-cache') || curRes.headers.get('x-vercel-cache')
export function getDeploymentId(appDir: string, isDev: boolean) {
let requiredServerFiles
if (!isDev) {
// File isn't written in dev, but it might still exist because it was created by a prior
// production build.
try {
requiredServerFiles = JSON.parse(
readFileSync(
path.join(appDir, getDistDir(), 'required-server-files.json'),
'utf8'
)
)
} catch {}
}
const deploymentId: string | undefined =
requiredServerFiles?.config?.deploymentId
const immutableAssetToken: string | undefined =
requiredServerFiles?.config?.experimental?.immutableAssetToken
const assetToken: string | undefined = immutableAssetToken || deploymentId
return {
deploymentId,
getDeploymentIdQuery(ampersand = false) {
return deploymentId ? `${ampersand ? '&' : '?'}dpl=${deploymentId}` : ''
},
assetToken,
getAssetQuery(ampersand = false) {
return assetToken ? `${ampersand ? '&' : '?'}dpl=${assetToken}` : ''
},
}
}
import { nextTestSetup } from 'e2e-utils' import { isNextStart, nextTestSetup } from 'e2e-utils'
describe('css-url-deployment-id', () => { describe('css-url-deployment-id', () => {
const deploymentId = 'test-deployment-id'
const { next } = nextTestSetup({ const { next } = nextTestSetup({
files: __dirname, files: __dirname,
skipDeployment: true, skipDeployment: true,
dependencies: { sass: '1.54.0' }, dependencies: { sass: '1.54.0' },
env: {
NEXT_DEPLOYMENT_ID: isNextStart ? 'test-deployment-id' : undefined,
VERCEL_IMMUTABLE_DEPLOYMENT_ID: isNextStart
? 'imm-deployment-id'
: undefined,
},
disableAutoSkewProtection: true,
}) })
it('should include dpl query in CSS url() references for images and fonts', async () => { it('should include dpl query in CSS url() references for images and fonts', async () => {
...@@ -57,7 +62,7 @@ describe('css-url-deployment-id', () => { ...@@ -57,7 +62,7 @@ describe('css-url-deployment-id', () => {
expect(assetUrls.length).toBeGreaterThanOrEqual(1) expect(assetUrls.length).toBeGreaterThanOrEqual(1)
for (const assetUrl of assetUrls) { for (const assetUrl of assetUrls) {
expect(assetUrl).toContain('dpl=' + deploymentId) expect(assetUrl).toContain('dpl=' + next.assetToken)
} }
}) })
...@@ -98,7 +103,7 @@ describe('css-url-deployment-id', () => { ...@@ -98,7 +103,7 @@ describe('css-url-deployment-id', () => {
expect(imageUrls.length).toBeGreaterThanOrEqual(1) expect(imageUrls.length).toBeGreaterThanOrEqual(1)
for (const imageUrl of imageUrls) { for (const imageUrl of imageUrls) {
expect(imageUrl).toContain('dpl=' + deploymentId) expect(imageUrl).toContain('dpl=' + next.assetToken)
} }
// Find font references from CSS modules // Find font references from CSS modules
...@@ -106,7 +111,7 @@ describe('css-url-deployment-id', () => { ...@@ -106,7 +111,7 @@ describe('css-url-deployment-id', () => {
expect(fontUrls.length).toBeGreaterThanOrEqual(1) expect(fontUrls.length).toBeGreaterThanOrEqual(1)
for (const fontUrl of fontUrls) { for (const fontUrl of fontUrls) {
expect(fontUrl).toContain('dpl=' + deploymentId) expect(fontUrl).toContain('dpl=' + next.assetToken)
} }
}) })
}) })
/** @type {import('next').NextConfig} */
module.exports = {
deploymentId: 'test-deployment-id',
}
...@@ -10,6 +10,7 @@ describe('deployment-id-handling disabled', () => { ...@@ -10,6 +10,7 @@ describe('deployment-id-handling disabled', () => {
COOKIE_SKEW: '1', COOKIE_SKEW: '1',
NEXT_DEPLOYMENT_ID: 'thankyounext', NEXT_DEPLOYMENT_ID: 'thankyounext',
}, },
disableAutoSkewProtection: true,
}) })
it('should set set-cookie header correctly', async () => { it('should set set-cookie header correctly', async () => {
......
...@@ -18,6 +18,7 @@ describe.each([ ...@@ -18,6 +18,7 @@ describe.each([
? '1' ? '1'
: undefined, : undefined,
}, },
disableAutoSkewProtection: true,
}) })
it.each([ it.each([
...@@ -170,6 +171,7 @@ describe('deployment-id-handling disabled', () => { ...@@ -170,6 +171,7 @@ describe('deployment-id-handling disabled', () => {
const deploymentId = Date.now() + '' const deploymentId = Date.now() + ''
const { next } = nextTestSetup({ const { next } = nextTestSetup({
files: join(__dirname, 'app'), files: join(__dirname, 'app'),
disableAutoSkewProtection: true,
}) })
it.each([ it.each([
{ urlPath: '/' }, { urlPath: '/' },
......
...@@ -207,6 +207,7 @@ const FILES = { ...@@ -207,6 +207,7 @@ const FILES = {
}, },
skipStart: true, skipStart: true,
skipDeployment: true, skipDeployment: true,
disableAutoSkewProtection: true,
}) })
it('should produce identical build outputs even when changing deployment id', async () => { it('should produce identical build outputs even when changing deployment id', async () => {
...@@ -240,6 +241,7 @@ const FILES = { ...@@ -240,6 +241,7 @@ const FILES = {
: undefined, : undefined,
skipStart: true, skipStart: true,
skipDeployment: true, skipDeployment: true,
disableAutoSkewProtection: true,
}) })
it('should produce identical build outputs even when changing deployment id', async () => { it('should produce identical build outputs even when changing deployment id', async () => {
......
...@@ -538,7 +538,7 @@ describe('Production Usage', () => { ...@@ -538,7 +538,7 @@ describe('Production Usage', () => {
for (const file of files) { for (const file of files) {
const res = await fetchViaHTTP( const res = await fetchViaHTTP(
`http://localhost:${next.appPort}`, `http://localhost:${next.appPort}`,
`/_next/${encodeURI(file)}`, `/_next/${encodeURI(file)}${next.getAssetQuery()}`,
undefined, undefined,
{ {
method: 'GET', method: 'GET',
...@@ -561,7 +561,7 @@ describe('Production Usage', () => { ...@@ -561,7 +561,7 @@ describe('Production Usage', () => {
for (const file of files) { for (const file of files) {
const res = await fetchViaHTTP( const res = await fetchViaHTTP(
`http://localhost:${next.appPort}`, `http://localhost:${next.appPort}`,
`/_next/${encodeURI(file)}`, `/_next/${encodeURI(file)}${next.getAssetQuery()}`,
undefined, undefined,
{ {
method: 'GET', method: 'GET',
...@@ -635,7 +635,10 @@ describe('Production Usage', () => { ...@@ -635,7 +635,10 @@ describe('Production Usage', () => {
const responses = await Promise.all( const responses = await Promise.all(
[...resources].map((resource) => [...resources].map((resource) =>
fetchViaHTTP(url, join('/_next', encodeURI(resource))) fetchViaHTTP(
url,
`/_next/${encodeURI(resource)}${next.getAssetQuery()}`
)
) )
) )
......
...@@ -307,6 +307,8 @@ describe('Prerender prefetch', () => { ...@@ -307,6 +307,8 @@ describe('Prerender prefetch', () => {
// See https://github.com/vercel/next.js/pull/70674 for context. // See https://github.com/vercel/next.js/pull/70674 for context.
NEXT_PRIVATE_CDN_CONSUMED_SWR_CACHE_CONTROL: '1', NEXT_PRIVATE_CDN_CONSUMED_SWR_CACHE_CONTROL: '1',
}, },
// relies on changing build id
disableAutoSkewProtection: true,
}) })
}) })
afterAll(() => next.destroy()) afterAll(() => next.destroy())
...@@ -333,6 +335,8 @@ describe('Prerender prefetch', () => { ...@@ -333,6 +335,8 @@ describe('Prerender prefetch', () => {
// See https://github.com/vercel/next.js/pull/70674 for context. // See https://github.com/vercel/next.js/pull/70674 for context.
NEXT_PRIVATE_CDN_CONSUMED_SWR_CACHE_CONTROL: '1', NEXT_PRIVATE_CDN_CONSUMED_SWR_CACHE_CONTROL: '1',
}, },
// relies on changing build id
disableAutoSkewProtection: true,
}) })
}) })
afterAll(() => next.destroy()) afterAll(() => next.destroy())
......
...@@ -50,6 +50,7 @@ describe('standalone mode: ipv6 hostname', () => { ...@@ -50,6 +50,7 @@ describe('standalone mode: ipv6 hostname', () => {
/- Local:/, /- Local:/,
{ {
...process.env, ...process.env,
...next.env,
HOSTNAME: '::', HOSTNAME: '::',
PORT: appPort, PORT: appPort,
}, },
......
import { createNext } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { NextInstance } from 'e2e-utils'
import { renderViaHTTP } from 'next-test-utils'
describe('standalone mode and optimizeCss', () => { describe('standalone mode and optimizeCss', () => {
let next: NextInstance const { next } = nextTestSetup({
beforeAll(async () => {
next = await createNext({
files: { files: {
'pages/index.js': ` 'pages/index.js': `
import styles from './index.module.css' import styles from './index.module.css'
...@@ -31,12 +26,12 @@ describe('standalone mode and optimizeCss', () => { ...@@ -31,12 +26,12 @@ describe('standalone mode and optimizeCss', () => {
dependencies: { dependencies: {
critters: '0.0.16', critters: '0.0.16',
}, },
// TODO optimizeCss is broken when ?dpl is added to CSS URLs
disableAutoSkewProtection: true,
}) })
})
afterAll(() => next.destroy())
it('should work', async () => { it('should work', async () => {
const html = await renderViaHTTP(next.url, '/') const html = await next.render('/')
expect(html).toContain('hello world') expect(html).toContain('hello world')
expect(html).toContain('background:orange') expect(html).toContain('background:orange')
}) })
......
...@@ -84,6 +84,7 @@ describe('required server files app router', () => { ...@@ -84,6 +84,7 @@ describe('required server files app router', () => {
/- Local:/, /- Local:/,
{ {
...process.env, ...process.env,
...next.env,
PORT: `${appPort}`, PORT: `${appPort}`,
}, },
undefined, undefined,
......
...@@ -118,6 +118,7 @@ describe('required server files i18n', () => { ...@@ -118,6 +118,7 @@ describe('required server files i18n', () => {
/- Local:/, /- Local:/,
{ {
...process.env, ...process.env,
...next.env,
PORT: `${appPort}`, PORT: `${appPort}`,
}, },
undefined, undefined,
......
...@@ -104,6 +104,7 @@ describe.skip('required server files app router', () => { ...@@ -104,6 +104,7 @@ describe.skip('required server files app router', () => {
/- Local:/, /- Local:/,
{ {
...process.env, ...process.env,
...next.env,
__NEXT_TEST_MODE: 'e2e', __NEXT_TEST_MODE: 'e2e',
PORT: `${appPort}`, PORT: `${appPort}`,
NEXT_PRIVATE_DEBUG_CACHE: '1', NEXT_PRIVATE_DEBUG_CACHE: '1',
......
...@@ -145,6 +145,7 @@ describe('required server files', () => { ...@@ -145,6 +145,7 @@ describe('required server files', () => {
/- Local:/, /- Local:/,
{ {
...process.env, ...process.env,
...next.env,
ENV_FROM_HOST: 'FOOBAR', ENV_FROM_HOST: 'FOOBAR',
PORT: `${appPort}`, PORT: `${appPort}`,
}, },
......
...@@ -68,6 +68,7 @@ describe('minimal-mode-response-cache', () => { ...@@ -68,6 +68,7 @@ describe('minimal-mode-response-cache', () => {
/- Local:/, /- Local:/,
{ {
...process.env, ...process.env,
...next.env,
HOSTNAME: '', HOSTNAME: '',
PORT: port.toString(), PORT: port.toString(),
}, },
......
...@@ -23,6 +23,7 @@ describe('standalone mode: runtimeServerDeploymentId', () => { ...@@ -23,6 +23,7 @@ describe('standalone mode: runtimeServerDeploymentId', () => {
NEXT_DEPLOYMENT_ID: MY_DEPLOYMENT_ID, NEXT_DEPLOYMENT_ID: MY_DEPLOYMENT_ID,
}, },
skipStart: true, skipStart: true,
disableAutoSkewProtection: true,
}) })
let { exitCode } = await next.build() let { exitCode } = await next.build()
// eslint-disable-next-line jest/no-standalone-expect // eslint-disable-next-line jest/no-standalone-expect
...@@ -47,6 +48,7 @@ describe('standalone mode: runtimeServerDeploymentId', () => { ...@@ -47,6 +48,7 @@ describe('standalone mode: runtimeServerDeploymentId', () => {
/- Local:/, /- Local:/,
{ {
...process.env, ...process.env,
...next.env,
HOSTNAME: '::', HOSTNAME: '::',
PORT: appPort, PORT: appPort,
NEXT_DEPLOYMENT_ID: MY_DEPLOYMENT_ID, NEXT_DEPLOYMENT_ID: MY_DEPLOYMENT_ID,
......
...@@ -28,7 +28,7 @@ describe('type-module', () => { ...@@ -28,7 +28,7 @@ describe('type-module', () => {
const server = await initNextServerScript( const server = await initNextServerScript(
serverFile, serverFile,
/- Local:/, /- Local:/,
{ ...process.env, PORT: appPort.toString() }, { ...process.env, ...next.env, PORT: appPort.toString() },
undefined, undefined,
{ cwd: next.testDir } { cwd: next.testDir }
) )
......
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