Unverified Commit a430936c authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

Strengthen _rsc cache-busting param (#92755)

This updates `_rsc` cache-busting param generation to use a stronger
digest so different RSC request variants are much less likely to produce
the same value.

It also updates the related request-validation and injected
resume/instant-test paths so they continue to generate and validate the
same `_rsc` values across client, server, and edge-reachable codepaths.
parent 8de4b600
...@@ -1793,7 +1793,9 @@ export async function handler( ...@@ -1793,7 +1793,9 @@ export async function handler(
const instantTestRequestId = const instantTestRequestId =
routeModule.isDev === true ? crypto.randomUUID() : null routeModule.isDev === true ? crypto.randomUUID() : null
body.pipeThrough( body.pipeThrough(
createInstantTestScriptInsertionTransformStream(instantTestRequestId) await createInstantTestScriptInsertionTransformStream(
instantTestRequestId
)
) )
return sendRenderResult({ return sendRenderResult({
req, req,
......
...@@ -532,7 +532,7 @@ export async function createFetch<T>( ...@@ -532,7 +532,7 @@ export async function createFetch<T>(
// search param to it. This should not leak outside of this function, so we // search param to it. This should not leak outside of this function, so we
// track them separately. // track them separately.
let fetchUrl = new URL(url) let fetchUrl = new URL(url)
setCacheBustingSearchParam(fetchUrl, headers) await setCacheBustingSearchParam(fetchUrl, headers)
let processed = fetch(fetchUrl, fetchOptions).then(processFetch) let processed = fetch(fetchUrl, fetchOptions).then(processFetch)
let fetchPromise = processed.then(({ response }) => response) let fetchPromise = processed.then(({ response }) => response)
...@@ -602,7 +602,7 @@ export async function createFetch<T>( ...@@ -602,7 +602,7 @@ export async function createFetch<T>(
// fetch again. // fetch again.
// TODO: We should abort the previous request. // TODO: We should abort the previous request.
fetchUrl = new URL(responseUrl) fetchUrl = new URL(responseUrl)
setCacheBustingSearchParam(fetchUrl, headers) await setCacheBustingSearchParam(fetchUrl, headers)
processed = fetch(fetchUrl, fetchOptions).then(processFetch) processed = fetch(fetchUrl, fetchOptions).then(processFetch)
fetchPromise = processed.then(({ response }) => response) fetchPromise = processed.then(({ response }) => response)
flightResponsePromise = shouldImmediatelyDecode flightResponsePromise = shouldImmediatelyDecode
......
import {
NEXT_ROUTER_PREFETCH_HEADER,
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
NEXT_ROUTER_STATE_TREE_HEADER,
NEXT_RSC_UNION_QUERY,
NEXT_URL,
} from '../app-router-headers'
import { setCacheBustingSearchParam } from './set-cache-busting-search-param'
import { computeLegacyCacheBustingSearchParam } from '../../../shared/lib/router/utils/cache-busting-search-param'
describe('setCacheBustingSearchParam', () => {
const originalCryptoDescriptor = Object.getOwnPropertyDescriptor(
globalThis,
'crypto'
)
afterEach(() => {
if (originalCryptoDescriptor) {
Object.defineProperty(globalThis, 'crypto', originalCryptoDescriptor)
}
})
it('falls back to the legacy hash when Web Crypto is unavailable', async () => {
Object.defineProperty(globalThis, 'crypto', {
configurable: true,
value: {},
})
const headers = {
[NEXT_ROUTER_PREFETCH_HEADER]: '1',
[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]: '/_tree',
[NEXT_ROUTER_STATE_TREE_HEADER]: '%5B%22%22%2C%7B%7D%5D',
[NEXT_URL]: '/pcsta0',
} as const
const url = new URL('https://example.com/')
await setCacheBustingSearchParam(url, headers)
expect(url.searchParams.get(NEXT_RSC_UNION_QUERY)).toBe(
computeLegacyCacheBustingSearchParam(
headers[NEXT_ROUTER_PREFETCH_HEADER],
headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER],
headers[NEXT_ROUTER_STATE_TREE_HEADER],
headers[NEXT_URL]
)
)
})
})
'use client' 'use client'
import { computeCacheBustingSearchParam } from '../../../shared/lib/router/utils/cache-busting-search-param' import {
computeCacheBustingSearchParam,
computeLegacyCacheBustingSearchParam,
} from '../../../shared/lib/router/utils/cache-busting-search-param'
import { import {
NEXT_ROUTER_PREFETCH_HEADER, NEXT_ROUTER_PREFETCH_HEADER,
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER, NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
...@@ -10,6 +13,26 @@ import { ...@@ -10,6 +13,26 @@ import {
} from '../app-router-headers' } from '../app-router-headers'
import type { RequestHeaders } from './fetch-server-response' import type { RequestHeaders } from './fetch-server-response'
async function computeClientCacheBustingSearchParam(
headers: RequestHeaders
): Promise<string> {
if (typeof globalThis.crypto?.subtle?.digest === 'function') {
return computeCacheBustingSearchParam(
headers[NEXT_ROUTER_PREFETCH_HEADER],
headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER],
headers[NEXT_ROUTER_STATE_TREE_HEADER],
headers[NEXT_URL]
)
}
return computeLegacyCacheBustingSearchParam(
headers[NEXT_ROUTER_PREFETCH_HEADER],
headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER],
headers[NEXT_ROUTER_STATE_TREE_HEADER],
headers[NEXT_URL]
)
}
/** /**
* Mutates the provided URL by adding a cache-busting search parameter for CDNs that don't * Mutates the provided URL by adding a cache-busting search parameter for CDNs that don't
* support custom headers. This helps avoid caching conflicts by making each request unique. * support custom headers. This helps avoid caching conflicts by making each request unique.
...@@ -21,21 +44,17 @@ import type { RequestHeaders } from './fetch-server-response' ...@@ -21,21 +44,17 @@ import type { RequestHeaders } from './fetch-server-response'
* URL before: https://example.com/path?query=1 * URL before: https://example.com/path?query=1
* URL after: https://example.com/path?query=1&_rsc=abc123 * URL after: https://example.com/path?query=1&_rsc=abc123
* *
* Note: This function mutates the input URL directly and does not return anything. * Note: This function mutates the input URL directly and resolves once the
* cache-busting value has been computed and applied.
* *
* TODO: Since we need to use a search param anyway, we could simplify by removing the custom * TODO: Since we need to use a search param anyway, we could simplify by removing the custom
* headers approach entirely and just use search params. * headers approach entirely and just use search params.
*/ */
export const setCacheBustingSearchParam = ( export const setCacheBustingSearchParam = async (
url: URL, url: URL,
headers: RequestHeaders headers: RequestHeaders
): void => { ): Promise<void> => {
const uniqueCacheKey = computeCacheBustingSearchParam( const uniqueCacheKey = await computeClientCacheBustingSearchParam(headers)
headers[NEXT_ROUTER_PREFETCH_HEADER],
headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER],
headers[NEXT_ROUTER_STATE_TREE_HEADER],
headers[NEXT_URL]
)
setCacheBustingSearchParamWithHash(url, uniqueCacheKey) setCacheBustingSearchParamWithHash(url, uniqueCacheKey)
} }
...@@ -50,7 +69,7 @@ export const setCacheBustingSearchParam = ( ...@@ -50,7 +69,7 @@ export const setCacheBustingSearchParam = (
* hash: "abc123" * hash: "abc123"
* URL after: https://example.com/path?query=1&_rsc=abc123 * URL after: https://example.com/path?query=1&_rsc=abc123
* *
* If the hash is null, we will set `_rsc` search param without a value. * If the hash is empty, we will set `_rsc` search param without a value.
* Like this: https://example.com/path?query=1&_rsc * Like this: https://example.com/path?query=1&_rsc
* *
* Note: This function mutates the input URL directly and does not return anything. * Note: This function mutates the input URL directly and does not return anything.
......
...@@ -68,11 +68,12 @@ import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.exte ...@@ -68,11 +68,12 @@ import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.exte
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import { executeRevalidates } from '../revalidation-utils' import { executeRevalidates } from '../revalidation-utils'
import { addRequestMeta, getRequestMeta } from '../request-meta' import { addRequestMeta, getRequestMeta } from '../request-meta'
import { setCacheBustingSearchParam } from '../../client/components/router-reducer/set-cache-busting-search-param' import { setCacheBustingSearchParamWithHash } from '../../client/components/router-reducer/set-cache-busting-search-param'
import { import {
ActionDidNotRevalidate, ActionDidNotRevalidate,
ActionDidRevalidateStaticAndDynamic, ActionDidRevalidateStaticAndDynamic,
} from '../../shared/lib/action-revalidation-kind' } from '../../shared/lib/action-revalidation-kind'
import { computeCacheBustingSearchParam } from '../../shared/lib/router/utils/cache-busting-search-param'
const INLINE_ACTION_PREFIX = '$$RSC_SERVER_ACTION_' const INLINE_ACTION_PREFIX = '$$RSC_SERVER_ACTION_'
...@@ -401,19 +402,15 @@ async function createRedirectRenderResult( ...@@ -401,19 +402,15 @@ async function createRedirectRenderResult(
forwardedHeaders.delete(ACTION_HEADER) forwardedHeaders.delete(ACTION_HEADER)
try { try {
setCacheBustingSearchParam(fetchUrl, { const cacheBustingSearchParam = await computeCacheBustingSearchParam(
[NEXT_ROUTER_PREFETCH_HEADER]: forwardedHeaders.get( forwardedHeaders.get(NEXT_ROUTER_PREFETCH_HEADER)
NEXT_ROUTER_PREFETCH_HEADER
)
? ('1' as const) ? ('1' as const)
: undefined, : undefined,
[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]: forwardedHeaders.get(NEXT_ROUTER_SEGMENT_PREFETCH_HEADER) ?? undefined,
forwardedHeaders.get(NEXT_ROUTER_SEGMENT_PREFETCH_HEADER) ?? forwardedHeaders.get(NEXT_ROUTER_STATE_TREE_HEADER) ?? undefined,
undefined, forwardedHeaders.get(NEXT_URL) ?? undefined
[NEXT_ROUTER_STATE_TREE_HEADER]: )
forwardedHeaders.get(NEXT_ROUTER_STATE_TREE_HEADER) ?? undefined, setCacheBustingSearchParamWithHash(fetchUrl, cacheBustingSearchParam)
[NEXT_URL]: forwardedHeaders.get(NEXT_URL) ?? undefined,
})
const response = await fetch(fetchUrl, { const response = await fetch(fetchUrl, {
method: 'GET', method: 'GET',
......
...@@ -145,7 +145,6 @@ import { shouldServeStreamingMetadata } from './lib/streaming-metadata' ...@@ -145,7 +145,6 @@ import { shouldServeStreamingMetadata } from './lib/streaming-metadata'
import { decodeQueryPathParameter } from './lib/decode-query-path-parameter' import { decodeQueryPathParameter } from './lib/decode-query-path-parameter'
import { NoFallbackError } from '../shared/lib/no-fallback-error.external' import { NoFallbackError } from '../shared/lib/no-fallback-error.external'
import { fixMojibake } from './lib/fix-mojibake' import { fixMojibake } from './lib/fix-mojibake'
import { computeCacheBustingSearchParam } from '../shared/lib/router/utils/cache-busting-search-param'
import { setCacheBustingSearchParamWithHash } from '../client/components/router-reducer/set-cache-busting-search-param' import { setCacheBustingSearchParamWithHash } from '../client/components/router-reducer/set-cache-busting-search-param'
import type { CacheControl } from './lib/cache-control' import type { CacheControl } from './lib/cache-control'
import type { PrerenderedRoute } from '../build/static-paths/types' import type { PrerenderedRoute } from '../build/static-paths/types'
...@@ -157,6 +156,10 @@ import { ...@@ -157,6 +156,10 @@ import {
getPostponedStateExceededErrorMessage, getPostponedStateExceededErrorMessage,
readBodyWithSizeLimit, readBodyWithSizeLimit,
} from './lib/postponed-request-body' } from './lib/postponed-request-body'
import {
computeCacheBustingSearchParam,
computeLegacyCacheBustingSearchParam,
} from '../shared/lib/router/utils/cache-busting-search-param'
export type FindComponentsResult< export type FindComponentsResult<
NextModule extends GenericComponentMod = GenericComponentMod, NextModule extends GenericComponentMod = GenericComponentMod,
...@@ -2080,7 +2083,7 @@ export default abstract class Server< ...@@ -2080,7 +2083,7 @@ export default abstract class Server<
headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] || headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] ||
getRequestMeta(req, 'segmentPrefetchRSCRequest') getRequestMeta(req, 'segmentPrefetchRSCRequest')
const expectedHash = computeCacheBustingSearchParam( const expectedHash = await computeCacheBustingSearchParam(
routerPrefetch, routerPrefetch,
segmentPrefetchRSCRequest, segmentPrefetchRSCRequest,
headers[NEXT_ROUTER_STATE_TREE_HEADER], headers[NEXT_ROUTER_STATE_TREE_HEADER],
...@@ -2092,10 +2095,24 @@ export default abstract class Server< ...@@ -2092,10 +2095,24 @@ export default abstract class Server<
NEXT_RSC_UNION_QUERY NEXT_RSC_UNION_QUERY
) )
if (expectedHash !== actualHash) { let matchesHash = expectedHash === actualHash
if (!matchesHash && actualHash !== null) {
// We'll fallback to checking the legacy hash format to support clients that do not have a secure context
matchesHash =
computeLegacyCacheBustingSearchParam(
routerPrefetch,
segmentPrefetchRSCRequest,
headers[NEXT_ROUTER_STATE_TREE_HEADER],
headers[NEXT_URL]
) === actualHash
}
if (!matchesHash) {
// The hash sent by the client does not match the expected value. // The hash sent by the client does not match the expected value.
// Redirect to the URL with the correct cache-busting search param. // Redirect to the URL with the correct cache-busting search param.
// This prevents cache poisoning attacks on CDNs that don't respect Vary headers. // This prevents cache poisoning attacks on CDNs that don't respect Vary headers.
// We continue to accept the legacy short hash for clients that still
// generate the 5-character `_rsc` form.
// Note: When no headers are present, expectedHash is empty string and client // Note: When no headers are present, expectedHash is empty string and client
// must send `_rsc` param, otherwise actualHash is null and hash check fails. // must send `_rsc` param, otherwise actualHash is null and hash check fails.
const url = new URL(req.url || '', 'http://localhost') const url = new URL(req.url || '', 'http://localhost')
......
...@@ -521,12 +521,11 @@ export function createHeadInsertionTransformStream( ...@@ -521,12 +521,11 @@ export function createHeadInsertionTransformStream(
}) })
} }
function createClientResumeScriptInsertionTransformStream(): TransformStream< async function createClientResumeScriptInsertionTransformStream(): Promise<
Uint8Array, TransformStream<Uint8Array, Uint8Array>
Uint8Array
> { > {
const segmentPath = '/_full' const segmentPath = '/_full'
const cacheBustingHeader = computeCacheBustingSearchParam( const cacheBustingHeader = await computeCacheBustingSearchParam(
'1', // headers[NEXT_ROUTER_PREFETCH_HEADER] '1', // headers[NEXT_ROUTER_PREFETCH_HEADER]
'/_full', // headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] '/_full', // headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]
undefined, // headers[NEXT_ROUTER_STATE_TREE_HEADER] undefined, // headers[NEXT_ROUTER_STATE_TREE_HEADER]
...@@ -586,9 +585,9 @@ function createClientResumeScriptInsertionTransformStream(): TransformStream< ...@@ -586,9 +585,9 @@ function createClientResumeScriptInsertionTransformStream(): TransformStream<
* element inside <head>. Used during instant navigation testing to set * element inside <head>. Used during instant navigation testing to set
* self.__next_instant_test before any async bootstrap scripts execute. * self.__next_instant_test before any async bootstrap scripts execute.
*/ */
export function createInstantTestScriptInsertionTransformStream( export async function createInstantTestScriptInsertionTransformStream(
requestId: string | null requestId: string | null
): TransformStream<Uint8Array, Uint8Array> { ): Promise<TransformStream<Uint8Array, Uint8Array>> {
// Kick off a fetch for the static RSC payload. This is the hydration // Kick off a fetch for the static RSC payload. This is the hydration
// source for the locked static shell — same as the __NEXT_CLIENT_RESUME // source for the locked static shell — same as the __NEXT_CLIENT_RESUME
// fetch used for fallback routes, but with NEXT_INSTANT_PREFETCH_HEADER // fetch used for fallback routes, but with NEXT_INSTANT_PREFETCH_HEADER
...@@ -598,7 +597,7 @@ export function createInstantTestScriptInsertionTransformStream( ...@@ -598,7 +597,7 @@ export function createInstantTestScriptInsertionTransformStream(
// as the feature flag (truthy = instant test mode). The client processes // as the feature flag (truthy = instant test mode). The client processes
// this as a fallback prerender payload for hydration. // this as a fallback prerender payload for hydration.
const segmentPath = '/_full' const segmentPath = '/_full'
const cacheBustingHeader = computeCacheBustingSearchParam( const cacheBustingHeader = await computeCacheBustingSearchParam(
'1', '1',
segmentPath, segmentPath,
undefined, undefined,
...@@ -1139,7 +1138,7 @@ export async function continueStaticFallbackPrerender( ...@@ -1139,7 +1138,7 @@ export async function continueStaticFallbackPrerender(
// Insert generated tags to head // Insert generated tags to head
createHeadInsertionTransformStream(getServerInsertedHTML), createHeadInsertionTransformStream(getServerInsertedHTML),
// Insert the client resume script into the head // Insert the client resume script into the head
createClientResumeScriptInsertionTransformStream(), await createClientResumeScriptInsertionTransformStream(),
// Transform metadata // Transform metadata
createMetadataTransformStream(getServerInsertedMetadata), createMetadataTransformStream(getServerInsertedMetadata),
// Insert the inlined data (Flight data, form state, etc.) stream into the HTML // Insert the inlined data (Flight data, form state, etc.) stream into the HTML
......
import { hexHash } from '../../hash' import { hexHash } from '../../hash'
export function computeCacheBustingSearchParam( const CACHE_BUSTING_SEARCH_PARAM_DIGEST_BYTES = 12
const textEncoder = new TextEncoder()
function encodeCacheBustingSearchParam(bytes: Uint8Array): string {
let binary = ''
for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i])
}
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
}
function normalizeCacheBustingInput(
value: string | string[] | undefined
): string {
if (value === undefined) {
return '0'
}
return Array.isArray(value) ? value.join(',') : value
}
function createCacheBustingSearchParamInput(
prefetchHeader: '1' | '2' | '0' | undefined, prefetchHeader: '1' | '2' | '0' | undefined,
segmentPrefetchHeader: string | string[] | undefined, segmentPrefetchHeader: string | string[] | undefined,
stateTreeHeader: string | string[] | undefined, stateTreeHeader: string | string[] | undefined,
nextUrlHeader: string | string[] | undefined nextUrlHeader: string | string[] | undefined
): string { ): string | null {
if ( if (
(prefetchHeader === undefined || prefetchHeader === '0') && (prefetchHeader === undefined || prefetchHeader === '0') &&
segmentPrefetchHeader === undefined && segmentPrefetchHeader === undefined &&
stateTreeHeader === undefined && stateTreeHeader === undefined &&
nextUrlHeader === undefined nextUrlHeader === undefined
) { ) {
return null
}
return [
prefetchHeader ?? '0',
normalizeCacheBustingInput(segmentPrefetchHeader),
normalizeCacheBustingInput(stateTreeHeader),
normalizeCacheBustingInput(nextUrlHeader),
].join(',')
}
async function computeCacheBustingSearchParamFromInput(
input: string
): Promise<string> {
// Truncate SHA-256 to 96 bits to keep `_rsc` compact
const digest = await globalThis.crypto.subtle.digest(
'SHA-256',
textEncoder.encode(input)
)
return encodeCacheBustingSearchParam(
new Uint8Array(digest).subarray(0, CACHE_BUSTING_SEARCH_PARAM_DIGEST_BYTES)
)
}
export async function computeCacheBustingSearchParam(
prefetchHeader: '1' | '2' | '0' | undefined,
segmentPrefetchHeader: string | string[] | undefined,
stateTreeHeader: string | string[] | undefined,
nextUrlHeader: string | string[] | undefined
): Promise<string> {
const input = createCacheBustingSearchParamInput(
prefetchHeader,
segmentPrefetchHeader,
stateTreeHeader,
nextUrlHeader
)
if (input === null) {
return '' return ''
} }
return hexHash(
[ return computeCacheBustingSearchParamFromInput(input)
prefetchHeader || '0', }
segmentPrefetchHeader || '0',
stateTreeHeader || '0', export function computeLegacyCacheBustingSearchParam(
nextUrlHeader || '0', prefetchHeader: '1' | '2' | '0' | undefined,
].join(',') segmentPrefetchHeader: string | string[] | undefined,
stateTreeHeader: string | string[] | undefined,
nextUrlHeader: string | string[] | undefined
): string {
const input = createCacheBustingSearchParamInput(
prefetchHeader,
segmentPrefetchHeader,
stateTreeHeader,
nextUrlHeader
) )
if (input === null) {
return ''
}
return hexHash(input)
} }
...@@ -223,14 +223,24 @@ describe('app dir - prefetching', () => { ...@@ -223,14 +223,24 @@ describe('app dir - prefetching', () => {
16, // PrefetchHint.IsRootLayout 16, // PrefetchHint.IsRootLayout
]) ])
) )
const response = await next.fetch(`/prefetch-auto/justputit?_rsc=dcqtr`, { const headers = {
headers: { rsc: '1',
rsc: '1', 'next-router-prefetch': '1',
'next-router-prefetch': '1', 'next-router-state-tree': stateTree,
'next-router-state-tree': stateTree, 'next-url': '/prefetch-auto/justputit',
'next-url': '/prefetch-auto/justputit', } as const
}, const cacheBustingParam = await computeCacheBustingSearchParam(
}) headers['next-router-prefetch'],
undefined,
headers['next-router-state-tree'],
headers['next-url']
)
const response = await next.fetch(
`/prefetch-auto/justputit?_rsc=${cacheBustingParam}`,
{
headers,
}
)
const prefetchResponse = await response.text() const prefetchResponse = await response.text()
expect(prefetchResponse).not.toContain('Page Data!') expect(prefetchResponse).not.toContain('Page Data!')
...@@ -267,7 +277,7 @@ describe('app dir - prefetching', () => { ...@@ -267,7 +277,7 @@ describe('app dir - prefetching', () => {
} }
const url = new URL('/prefetch-auto/justputit', 'http://localhost') const url = new URL('/prefetch-auto/justputit', 'http://localhost')
const cacheBustingParam = computeCacheBustingSearchParam( const cacheBustingParam = await computeCacheBustingSearchParam(
headers['next-router-prefetch'] ? '1' : '0', headers['next-router-prefetch'] ? '1' : '0',
undefined, undefined,
headers['next-router-state-tree'], headers['next-router-state-tree'],
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { computeCacheBustingSearchParam } from 'next/dist/shared/lib/router/utils/cache-busting-search-param' import {
computeCacheBustingSearchParam,
computeLegacyCacheBustingSearchParam,
} from 'next/dist/shared/lib/router/utils/cache-busting-search-param'
describe('app dir - validation', () => { describe('app dir - validation', () => {
const { next, skipped } = nextTestSetup({ const { next, skipped } = nextTestSetup({
...@@ -29,13 +32,13 @@ describe('app dir - validation', () => { ...@@ -29,13 +32,13 @@ describe('app dir - validation', () => {
const url2 = new URL('/', 'http://localhost') const url2 = new URL('/', 'http://localhost')
// Add cache busting search param for both requests // Add cache busting search param for both requests
const cacheBustingParam1 = computeCacheBustingSearchParam( const cacheBustingParam1 = await computeCacheBustingSearchParam(
undefined, undefined,
undefined, undefined,
stateTree1, stateTree1,
undefined undefined
) )
const cacheBustingParam2 = computeCacheBustingSearchParam( const cacheBustingParam2 = await computeCacheBustingSearchParam(
undefined, undefined,
undefined, undefined,
stateTree2, stateTree2,
...@@ -55,4 +58,51 @@ describe('app dir - validation', () => { ...@@ -55,4 +58,51 @@ describe('app dir - validation', () => {
const res2 = await next.fetch(url2.toString(), { headers: headers2 }) const res2 = await next.fetch(url2.toString(), { headers: headers2 })
expect(res2.status).toBe(200) expect(res2.status).toBe(200)
}) })
it('should generate distinct cache-busting params for known colliding RSC variants', async () => {
const stateTree = '%5B%22%22%2C%7B%7D%5D'
const fullRequestHash = await computeCacheBustingSearchParam(
undefined,
undefined,
stateTree,
undefined
)
const prefetchRequestHash = await computeCacheBustingSearchParam(
'1',
'/_tree',
stateTree,
'/pcsta0'
)
expect(fullRequestHash).toHaveLength(16)
expect(prefetchRequestHash).toHaveLength(16)
expect(fullRequestHash).not.toBe(prefetchRequestHash)
})
it('should accept legacy cache-busting params on plain HTTP requests', async () => {
const stateTree = '%5B%22%22%2C%7B%7D%5D'
const url = new URL('/', 'http://localhost')
const headers = {
rsc: '1',
'next-router-state-tree': stateTree,
}
url.searchParams.set(
'_rsc',
computeLegacyCacheBustingSearchParam(
undefined,
undefined,
stateTree,
undefined
)
)
const res = await next.fetch(url.toString(), {
headers,
redirect: 'manual',
})
expect(res.status).toBe(200)
})
}) })
...@@ -47,18 +47,18 @@ const pages: Page[] = [ ...@@ -47,18 +47,18 @@ const pages: Page[] = [
}, },
] ]
const addCacheBustingSearchParam = ( const addCacheBustingSearchParam = async (
pathname: string, pathname: string,
headers: Record<string, string | string[] | undefined> headers: Record<string, string | string[] | undefined>
) => { ) => {
const cacheKey = computeCacheBustingSearchParam( const cacheKey = await computeCacheBustingSearchParam(
headers['next-router-prefetch'] ? '1' : '0', headers['next-router-prefetch'] ? '1' : '0',
headers['next-router-segment-prefetch'], headers['next-router-segment-prefetch'],
headers['next-router-state-tree'], headers['next-router-state-tree'],
headers['next-url'] headers['next-url']
) )
if (cacheKey === null) { if (cacheKey.length === 0) {
return pathname return pathname
} }
...@@ -582,7 +582,7 @@ describe.skip('ppr-full', () => { ...@@ -582,7 +582,7 @@ describe.skip('ppr-full', () => {
rsc: '1', rsc: '1',
'next-router-prefetch': '1', 'next-router-prefetch': '1',
} }
const urlWithCacheBusting = addCacheBustingSearchParam( const urlWithCacheBusting = await addCacheBustingSearchParam(
pathname, pathname,
headers headers
) )
...@@ -619,7 +619,7 @@ describe.skip('ppr-full', () => { ...@@ -619,7 +619,7 @@ describe.skip('ppr-full', () => {
'next-router-prefetch': '1', 'next-router-prefetch': '1',
'X-Test-Input': unexpected, 'X-Test-Input': unexpected,
} }
const urlWithCacheBusting = addCacheBustingSearchParam( const urlWithCacheBusting = await addCacheBustingSearchParam(
pathname, pathname,
headers headers
) )
...@@ -639,7 +639,7 @@ describe.skip('ppr-full', () => { ...@@ -639,7 +639,7 @@ describe.skip('ppr-full', () => {
describe.each(pages)('for $pathname', ({ pathname, dynamic }) => { describe.each(pages)('for $pathname', ({ pathname, dynamic }) => {
it('should have correct headers', async () => { it('should have correct headers', async () => {
const headers = { rsc: '1' } const headers = { rsc: '1' }
const urlWithCacheBusting = addCacheBustingSearchParam( const urlWithCacheBusting = await addCacheBustingSearchParam(
pathname, pathname,
headers headers
) )
...@@ -671,7 +671,7 @@ describe.skip('ppr-full', () => { ...@@ -671,7 +671,7 @@ describe.skip('ppr-full', () => {
rsc: '1', rsc: '1',
'X-Test-Input': expected, 'X-Test-Input': expected,
} }
const urlWithCacheBusting = addCacheBustingSearchParam( const urlWithCacheBusting = await addCacheBustingSearchParam(
pathname, pathname,
headers headers
) )
...@@ -691,7 +691,7 @@ describe.skip('ppr-full', () => { ...@@ -691,7 +691,7 @@ describe.skip('ppr-full', () => {
rsc: '1', rsc: '1',
'X-Test-Input': unexpected, 'X-Test-Input': unexpected,
} }
const urlWithCacheBusting = addCacheBustingSearchParam( const urlWithCacheBusting = await addCacheBustingSearchParam(
pathname, pathname,
headers headers
) )
......
...@@ -30,7 +30,12 @@ describe('resume-data-cache', () => { ...@@ -30,7 +30,12 @@ describe('resume-data-cache', () => {
url.searchParams.set( url.searchParams.set(
'_rsc', '_rsc',
computeCacheBustingSearchParam('1', '/__PAGE__', undefined, undefined) await computeCacheBustingSearchParam(
'1',
'/__PAGE__',
undefined,
undefined
)
) )
const rsc = await next const rsc = await next
......
...@@ -476,7 +476,7 @@ describe('rewrite-headers', () => { ...@@ -476,7 +476,7 @@ describe('rewrite-headers', () => {
// Add cache busting param for RSC requests // Add cache busting param for RSC requests
if (headers.rsc === '1') { if (headers.rsc === '1') {
const cacheBustingParam = computeCacheBustingSearchParam( const cacheBustingParam = await computeCacheBustingSearchParam(
headers['next-router-prefetch'], headers['next-router-prefetch'],
headers['next-router-segment-prefetch'], headers['next-router-segment-prefetch'],
undefined, undefined,
......
...@@ -135,7 +135,7 @@ describe('middleware-static-rewrite', () => { ...@@ -135,7 +135,7 @@ describe('middleware-static-rewrite', () => {
it('should revalidate the overview page without replacing it with a 404', async () => { it('should revalidate the overview page without replacing it with a 404', async () => {
const url = new URL('/my-team', 'http://localhost') const url = new URL('/my-team', 'http://localhost')
const rsc = computeCacheBustingSearchParam( const rsc = await computeCacheBustingSearchParam(
'1', '1',
'/_head', '/_head',
undefined, undefined,
......
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