Unverified Commit bd9214f9 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

[lts-active] Fix draft mode leaks through cross-request `'use cache'` deduplication (#205)

Co-authored-by: 's avatarHendrik Liebau <mail@hendrik-liebau.de>
parent 8db4a627
...@@ -251,6 +251,7 @@ export async function handler( ...@@ -251,6 +251,7 @@ export async function handler(
}, },
cacheComponents: Boolean(nextConfig.cacheComponents), cacheComponents: Boolean(nextConfig.cacheComponents),
validationLevel: nextConfig.experimental.instantInsights.validationLevel, validationLevel: nextConfig.experimental.instantInsights.validationLevel,
isDraftMode,
supportsDynamicResponse, supportsDynamicResponse,
incrementalCache, incrementalCache,
hmrRefreshHash: getRequestMeta(req, 'hmrRefreshHash'), hmrRefreshHash: getRequestMeta(req, 'hmrRefreshHash'),
......
...@@ -2900,7 +2900,14 @@ export async function cache( ...@@ -2900,7 +2900,14 @@ export async function cache(
// headers, so concurrent requests with identical request data should share // headers, so concurrent requests with identical request data should share
// a fill too; that request-scoped `cacheHandlerKey` keeps requests with // a fill too; that request-scoped `cacheHandlerKey` keeps requests with
// different cookies or headers in separate entries. // different cookies or headers in separate entries.
const skipCrossRequestDedupe = isPrivate && !process.env.__NEXT_DEV_SERVER //
// Draft mode requests are skipped as well, in both directions. A fill that
// runs with draft mode enabled can contain unpublished content, so it must
// not be registered for other requests to join. And a draft mode request
// must not join a pending public fill, because it would be served the
// published content instead of the draft.
const skipCrossRequestDedupe =
(isPrivate && !process.env.__NEXT_DEV_SERVER) || workStore.isDraftMode
try { try {
// The loop handles cross-request root param mismatches: when a // The loop handles cross-request root param mismatches: when a
......
import { draftMode } from 'next/headers'
export async function GET() {
const draft = await draftMode()
draft.enable()
return new Response('draft mode enabled')
}
import { draftMode } from 'next/headers'
import { setTimeout } from 'timers/promises'
export async function getContent(key) {
'use cache'
const { isEnabled } = await draftMode()
// Simulate I/O latency so that a concurrent request overlaps the pending
// fill.
await setTimeout(3000)
return isEnabled ? 'DRAFT-SECRET' : 'PUBLIC'
}
import { ReactNode, Suspense } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>
<Suspense>{children}</Suspense>
</body>
</html>
)
}
import { connection } from 'next/server'
import { getContent } from '../get-content'
export default async function Page({ searchParams }: PageProps<'/page'>) {
await connection()
const { key = 'default' } = await searchParams
const content = await getContent(key)
return <p id="content">{content}</p>
}
import { connection, NextRequest } from 'next/server'
import { getContent } from '../get-content'
export async function GET(request: NextRequest) {
await connection()
const key = new URL(request.url).searchParams.get('key') ?? 'default'
const content = await getContent(key)
return Response.json({ content })
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
useCache: true,
},
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
const DRAFT_CONTENT = 'DRAFT-SECRET'
const PUBLIC_CONTENT = 'PUBLIC'
type FetchContent = (key: string, cookie?: string) => Promise<string>
describe('use-cache-draft-mode-isolation', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
// Cross-request dedup shares pending cache fills within one server
// process. In deploy mode, concurrent requests could hit different
// lambdas, so this test cannot exercise the sharing.
skipDeployment: true,
})
if (skipped) {
return
}
async function getDraftModeCookie(): Promise<string> {
const response = await next.fetch('/enable-draft')
const setCookie = response.headers.get('set-cookie')
if (!setCookie) {
throw new Error('Expected /enable-draft to set a draft mode cookie.')
}
return setCookie.split(';')[0]
}
// Each test uses a distinct key so that every test gets its own cache entry,
// independent of what earlier tests populated.
async function fetchRoute(key: string, cookie?: string): Promise<string> {
const response = await next.fetch(
`/route-handler?key=${key}`,
cookie ? { headers: { cookie } } : undefined
)
const body = await response.json()
return body.content as string
}
async function fetchPage(key: string, cookie?: string): Promise<string> {
const response = await next.fetch(
`/page?key=${key}`,
cookie ? { headers: { cookie } } : undefined
)
const html = await response.text()
return html.includes(DRAFT_CONTENT) ? DRAFT_CONTENT : PUBLIC_CONTENT
}
// The editor's draft mode request leads, and a public request overlaps the
// pending fill. The public request must not join the editor's fill, i.e. it
// must never receive the editor's unpublished content.
async function expectDraftFillNotSharedWithPublicRequest(
fetchContent: FetchContent,
key: string
): Promise<void> {
const draftCookie = await getDraftModeCookie()
// The cached function takes 3s, so the 500ms offset lands the public
// request well inside the editor's pending window.
const editorPromise = fetchContent(key, draftCookie)
await new Promise((resolve) => setTimeout(resolve, 500))
const publicContent = await fetchContent(key)
const editorContent = await editorPromise
// Sanity check: the editor must see draft content, otherwise the test
// itself is broken (e.g. draft mode not readable in "use cache").
expect(editorContent).toBe(DRAFT_CONTENT)
expect(publicContent).toBe(PUBLIC_CONTENT)
}
// The public request leads, and the editor's draft mode request overlaps the
// pending fill. The editor must not join the public fill, i.e. it must
// produce its own draft content.
async function expectPublicFillNotSharedWithDraftRequest(
fetchContent: FetchContent,
key: string
): Promise<void> {
const draftCookie = await getDraftModeCookie()
const publicPromise = fetchContent(key)
await new Promise((resolve) => setTimeout(resolve, 500))
const editorContent = await fetchContent(key, draftCookie)
const publicContent = await publicPromise
expect(publicContent).toBe(PUBLIC_CONTENT)
expect(editorContent).toBe(DRAFT_CONTENT)
}
it('does not expose a pending draft fill to a concurrent public request', async () => {
await expectDraftFillNotSharedWithPublicRequest(fetchRoute, 'route-cold')
})
it('does not expose a pending draft fill to a concurrent public request despite a fresh public entry', async () => {
const key = 'route-warm'
// Populate the public entry first. The cross-request pending map is
// consulted before the memory cache, so a fresh public entry cannot be what
// protects the public request.
expect(await fetchRoute(key)).toBe(PUBLIC_CONTENT)
await expectDraftFillNotSharedWithPublicRequest(fetchRoute, key)
})
it('does not serve a pending public fill to a concurrent draft mode request', async () => {
await expectPublicFillNotSharedWithDraftRequest(fetchRoute, 'route-reverse')
})
it('page: does not expose a pending draft fill to a concurrent public request', async () => {
await expectDraftFillNotSharedWithPublicRequest(fetchPage, 'page-cold')
})
it('page: does not serve a pending public fill to a concurrent draft mode request', async () => {
await expectPublicFillNotSharedWithDraftRequest(fetchPage, 'page-reverse')
})
})
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