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(
const instantTestRequestId =
routeModule.isDev === true ? crypto.randomUUID() : null
body.pipeThrough(
createInstantTestScriptInsertionTransformStream(instantTestRequestId)
await createInstantTestScriptInsertionTransformStream(
instantTestRequestId
)
)
return sendRenderResult({
req,
......
......@@ -532,7 +532,7 @@ export async function createFetch<T>(
// search param to it. This should not leak outside of this function, so we
// track them separately.
let fetchUrl = new URL(url)
setCacheBustingSearchParam(fetchUrl, headers)
await setCacheBustingSearchParam(fetchUrl, headers)
let processed = fetch(fetchUrl, fetchOptions).then(processFetch)
let fetchPromise = processed.then(({ response }) => response)
......@@ -602,7 +602,7 @@ export async function createFetch<T>(
// fetch again.
// TODO: We should abort the previous request.
fetchUrl = new URL(responseUrl)
setCacheBustingSearchParam(fetchUrl, headers)
await setCacheBustingSearchParam(fetchUrl, headers)
processed = fetch(fetchUrl, fetchOptions).then(processFetch)
fetchPromise = processed.then(({ response }) => response)
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'
import { computeCacheBustingSearchParam } from '../../../shared/lib/router/utils/cache-busting-search-param'
import {
computeCacheBustingSearchParam,
computeLegacyCacheBustingSearchParam,
} from '../../../shared/lib/router/utils/cache-busting-search-param'
import {
NEXT_ROUTER_PREFETCH_HEADER,
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
......@@ -10,6 +13,26 @@ import {
} from '../app-router-headers'
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
* support custom headers. This helps avoid caching conflicts by making each request unique.
......@@ -21,21 +44,17 @@ import type { RequestHeaders } from './fetch-server-response'
* URL before: https://example.com/path?query=1
* 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
* headers approach entirely and just use search params.
*/
export const setCacheBustingSearchParam = (
export const setCacheBustingSearchParam = async (
url: URL,
headers: RequestHeaders
): void => {
const uniqueCacheKey = computeCacheBustingSearchParam(
headers[NEXT_ROUTER_PREFETCH_HEADER],
headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER],
headers[NEXT_ROUTER_STATE_TREE_HEADER],
headers[NEXT_URL]
)
): Promise<void> => {
const uniqueCacheKey = await computeClientCacheBustingSearchParam(headers)
setCacheBustingSearchParamWithHash(url, uniqueCacheKey)
}
......@@ -50,7 +69,7 @@ export const setCacheBustingSearchParam = (
* hash: "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
*
* 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
import { InvariantError } from '../../shared/lib/invariant-error'
import { executeRevalidates } from '../revalidation-utils'
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 {
ActionDidNotRevalidate,
ActionDidRevalidateStaticAndDynamic,
} from '../../shared/lib/action-revalidation-kind'
import { computeCacheBustingSearchParam } from '../../shared/lib/router/utils/cache-busting-search-param'
const INLINE_ACTION_PREFIX = '$$RSC_SERVER_ACTION_'
......@@ -401,19 +402,15 @@ async function createRedirectRenderResult(
forwardedHeaders.delete(ACTION_HEADER)
try {
setCacheBustingSearchParam(fetchUrl, {
[NEXT_ROUTER_PREFETCH_HEADER]: forwardedHeaders.get(
NEXT_ROUTER_PREFETCH_HEADER
)
const cacheBustingSearchParam = await computeCacheBustingSearchParam(
forwardedHeaders.get(NEXT_ROUTER_PREFETCH_HEADER)
? ('1' as const)
: undefined,
[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]:
forwardedHeaders.get(NEXT_ROUTER_SEGMENT_PREFETCH_HEADER) ??
undefined,
[NEXT_ROUTER_STATE_TREE_HEADER]:
forwardedHeaders.get(NEXT_ROUTER_STATE_TREE_HEADER) ?? undefined,
[NEXT_URL]: forwardedHeaders.get(NEXT_URL) ?? undefined,
})
forwardedHeaders.get(NEXT_ROUTER_SEGMENT_PREFETCH_HEADER) ?? undefined,
forwardedHeaders.get(NEXT_ROUTER_STATE_TREE_HEADER) ?? undefined,
forwardedHeaders.get(NEXT_URL) ?? undefined
)
setCacheBustingSearchParamWithHash(fetchUrl, cacheBustingSearchParam)
const response = await fetch(fetchUrl, {
method: 'GET',
......
......@@ -145,7 +145,6 @@ import { shouldServeStreamingMetadata } from './lib/streaming-metadata'
import { decodeQueryPathParameter } from './lib/decode-query-path-parameter'
import { NoFallbackError } from '../shared/lib/no-fallback-error.external'
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 type { CacheControl } from './lib/cache-control'
import type { PrerenderedRoute } from '../build/static-paths/types'
......@@ -157,6 +156,10 @@ import {
getPostponedStateExceededErrorMessage,
readBodyWithSizeLimit,
} from './lib/postponed-request-body'
import {
computeCacheBustingSearchParam,
computeLegacyCacheBustingSearchParam,
} from '../shared/lib/router/utils/cache-busting-search-param'
export type FindComponentsResult<
NextModule extends GenericComponentMod = GenericComponentMod,
......@@ -2080,7 +2083,7 @@ export default abstract class Server<
headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] ||
getRequestMeta(req, 'segmentPrefetchRSCRequest')
const expectedHash = computeCacheBustingSearchParam(
const expectedHash = await computeCacheBustingSearchParam(
routerPrefetch,
segmentPrefetchRSCRequest,
headers[NEXT_ROUTER_STATE_TREE_HEADER],
......@@ -2092,10 +2095,24 @@ export default abstract class Server<
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.
// Redirect to the URL with the correct cache-busting search param.
// 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
// must send `_rsc` param, otherwise actualHash is null and hash check fails.
const url = new URL(req.url || '', 'http://localhost')
......
......@@ -521,12 +521,11 @@ export function createHeadInsertionTransformStream(
})
}
function createClientResumeScriptInsertionTransformStream(): TransformStream<
Uint8Array,
Uint8Array
async function createClientResumeScriptInsertionTransformStream(): Promise<
TransformStream<Uint8Array, Uint8Array>
> {
const segmentPath = '/_full'
const cacheBustingHeader = computeCacheBustingSearchParam(
const cacheBustingHeader = await computeCacheBustingSearchParam(
'1', // headers[NEXT_ROUTER_PREFETCH_HEADER]
'/_full', // headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]
undefined, // headers[NEXT_ROUTER_STATE_TREE_HEADER]
......@@ -586,9 +585,9 @@ function createClientResumeScriptInsertionTransformStream(): TransformStream<
* element inside <head>. Used during instant navigation testing to set
* self.__next_instant_test before any async bootstrap scripts execute.
*/
export function createInstantTestScriptInsertionTransformStream(
export async function createInstantTestScriptInsertionTransformStream(
requestId: string | null
): TransformStream<Uint8Array, Uint8Array> {
): Promise<TransformStream<Uint8Array, Uint8Array>> {
// 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
// fetch used for fallback routes, but with NEXT_INSTANT_PREFETCH_HEADER
......@@ -598,7 +597,7 @@ export function createInstantTestScriptInsertionTransformStream(
// as the feature flag (truthy = instant test mode). The client processes
// this as a fallback prerender payload for hydration.
const segmentPath = '/_full'
const cacheBustingHeader = computeCacheBustingSearchParam(
const cacheBustingHeader = await computeCacheBustingSearchParam(
'1',
segmentPath,
undefined,
......@@ -1139,7 +1138,7 @@ export async function continueStaticFallbackPrerender(
// Insert generated tags to head
createHeadInsertionTransformStream(getServerInsertedHTML),
// Insert the client resume script into the head
createClientResumeScriptInsertionTransformStream(),
await createClientResumeScriptInsertionTransformStream(),
// Transform metadata
createMetadataTransformStream(getServerInsertedMetadata),
// Insert the inlined data (Flight data, form state, etc.) stream into the HTML
......
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,
segmentPrefetchHeader: string | string[] | undefined,
stateTreeHeader: string | string[] | undefined,
nextUrlHeader: string | string[] | undefined
): string {
): string | null {
if (
(prefetchHeader === undefined || prefetchHeader === '0') &&
segmentPrefetchHeader === undefined &&
stateTreeHeader === 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 hexHash(
[
prefetchHeader || '0',
segmentPrefetchHeader || '0',
stateTreeHeader || '0',
nextUrlHeader || '0',
].join(',')
return computeCacheBustingSearchParamFromInput(input)
}
export function computeLegacyCacheBustingSearchParam(
prefetchHeader: '1' | '2' | '0' | undefined,
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', () => {
16, // PrefetchHint.IsRootLayout
])
)
const response = await next.fetch(`/prefetch-auto/justputit?_rsc=dcqtr`, {
headers: {
rsc: '1',
'next-router-prefetch': '1',
'next-router-state-tree': stateTree,
'next-url': '/prefetch-auto/justputit',
},
})
const headers = {
rsc: '1',
'next-router-prefetch': '1',
'next-router-state-tree': stateTree,
'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()
expect(prefetchResponse).not.toContain('Page Data!')
......@@ -267,7 +277,7 @@ describe('app dir - prefetching', () => {
}
const url = new URL('/prefetch-auto/justputit', 'http://localhost')
const cacheBustingParam = computeCacheBustingSearchParam(
const cacheBustingParam = await computeCacheBustingSearchParam(
headers['next-router-prefetch'] ? '1' : '0',
undefined,
headers['next-router-state-tree'],
......
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', () => {
const { next, skipped } = nextTestSetup({
......@@ -29,13 +32,13 @@ describe('app dir - validation', () => {
const url2 = new URL('/', 'http://localhost')
// Add cache busting search param for both requests
const cacheBustingParam1 = computeCacheBustingSearchParam(
const cacheBustingParam1 = await computeCacheBustingSearchParam(
undefined,
undefined,
stateTree1,
undefined
)
const cacheBustingParam2 = computeCacheBustingSearchParam(
const cacheBustingParam2 = await computeCacheBustingSearchParam(
undefined,
undefined,
stateTree2,
......@@ -55,4 +58,51 @@ describe('app dir - validation', () => {
const res2 = await next.fetch(url2.toString(), { headers: headers2 })
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[] = [
},
]
const addCacheBustingSearchParam = (
const addCacheBustingSearchParam = async (
pathname: string,
headers: Record<string, string | string[] | undefined>
) => {
const cacheKey = computeCacheBustingSearchParam(
const cacheKey = await computeCacheBustingSearchParam(
headers['next-router-prefetch'] ? '1' : '0',
headers['next-router-segment-prefetch'],
headers['next-router-state-tree'],
headers['next-url']
)
if (cacheKey === null) {
if (cacheKey.length === 0) {
return pathname
}
......@@ -582,7 +582,7 @@ describe.skip('ppr-full', () => {
rsc: '1',
'next-router-prefetch': '1',
}
const urlWithCacheBusting = addCacheBustingSearchParam(
const urlWithCacheBusting = await addCacheBustingSearchParam(
pathname,
headers
)
......@@ -619,7 +619,7 @@ describe.skip('ppr-full', () => {
'next-router-prefetch': '1',
'X-Test-Input': unexpected,
}
const urlWithCacheBusting = addCacheBustingSearchParam(
const urlWithCacheBusting = await addCacheBustingSearchParam(
pathname,
headers
)
......@@ -639,7 +639,7 @@ describe.skip('ppr-full', () => {
describe.each(pages)('for $pathname', ({ pathname, dynamic }) => {
it('should have correct headers', async () => {
const headers = { rsc: '1' }
const urlWithCacheBusting = addCacheBustingSearchParam(
const urlWithCacheBusting = await addCacheBustingSearchParam(
pathname,
headers
)
......@@ -671,7 +671,7 @@ describe.skip('ppr-full', () => {
rsc: '1',
'X-Test-Input': expected,
}
const urlWithCacheBusting = addCacheBustingSearchParam(
const urlWithCacheBusting = await addCacheBustingSearchParam(
pathname,
headers
)
......@@ -691,7 +691,7 @@ describe.skip('ppr-full', () => {
rsc: '1',
'X-Test-Input': unexpected,
}
const urlWithCacheBusting = addCacheBustingSearchParam(
const urlWithCacheBusting = await addCacheBustingSearchParam(
pathname,
headers
)
......
......@@ -30,7 +30,12 @@ describe('resume-data-cache', () => {
url.searchParams.set(
'_rsc',
computeCacheBustingSearchParam('1', '/__PAGE__', undefined, undefined)
await computeCacheBustingSearchParam(
'1',
'/__PAGE__',
undefined,
undefined
)
)
const rsc = await next
......
......@@ -476,7 +476,7 @@ describe('rewrite-headers', () => {
// Add cache busting param for RSC requests
if (headers.rsc === '1') {
const cacheBustingParam = computeCacheBustingSearchParam(
const cacheBustingParam = await computeCacheBustingSearchParam(
headers['next-router-prefetch'],
headers['next-router-segment-prefetch'],
undefined,
......
......@@ -135,7 +135,7 @@ describe('middleware-static-rewrite', () => {
it('should revalidate the overview page without replacing it with a 404', async () => {
const url = new URL('/my-team', 'http://localhost')
const rsc = computeCacheBustingSearchParam(
const rsc = await computeCacheBustingSearchParam(
'1',
'/_head',
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