Unverified Commit 64fbcb60 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Make `instant()` resilient to a leaked navigation-testing cookie (#95375)

The Instant Navigation Testing helper threw `An instant() scope is
already active` whenever it found the `next-instant-navigation-testing`
cookie set at acquire time. Because Playwright reuses one browser
context across every test in a file, a cookie left behind by an earlier
scope poisoned the shared jar and made every following `instant()` call
fail fast, cascading through the suite.

The cookie can outlive its scope: under the lock, each MPA page load
asynchronously re-writes it via `cookieStore`, and that write can land
right after the scope's release deletes it but before the client
observes the deletion, resurrecting a captured-state entry that the
change handler then ignores.

Nesting is now tracked in-process, keyed on the browser context, rather
than inferred from cookie presence. The context is the right granularity
because the instant cookie is context-scoped: concurrent scopes on the
same context share one cookie and conflict, while scopes on separate
contexts or browsers are independent and must both run. On acquire we
clear any stale cookie instead of throwing, and the release re-reads and
re-deletes until the cookie stays gone, defeating the resurrection race.
New tests cover recovery from a leaked cookie and concurrent scopes
across separate contexts.


---

<sub>Stack created with <a
href="https://github.com/github/gh-stack">GitHub Stacks CLI</a> • <a
href="https://gh.io/stacks-feedback">Give Feedback 💬</a></sub>
parent a26a1d64
...@@ -29,6 +29,23 @@ interface PlaywrightPage { ...@@ -29,6 +29,23 @@ interface PlaywrightPage {
const INSTANT_COOKIE = 'next-instant-navigation-testing' const INSTANT_COOKIE = 'next-instant-navigation-testing'
// Browser contexts that currently have an instant() scope executing. The
// instant cookie is scoped to the browser context, so the context is the
// natural granularity for the scope: two concurrent instant() calls on the same
// context share one cookie and genuinely conflict, whereas calls on different
// contexts (or different browsers) are independent and must not. Keying on the
// context object preserves that isolation while giving a race-free nesting
// signal.
//
// We track this in-process rather than inferring nesting from the cookie's
// presence: a locked page asynchronously re-writes the instant cookie on every
// MPA load (see navigation-testing-lock.ts), and that write can land right
// after a prior scope's release deletes it, resurrecting the cookie once the
// scope has already ended. Treating such a leftover as an active scope would
// turn a benign residue into a cascading failure across every later test that
// shares the browser context.
const contextsWithActiveScope = new WeakSet<PlaywrightBrowserContext>()
/** /**
* Runs a function with instant navigation enabled. Within this scope, * Runs a function with instant navigation enabled. Within this scope,
* navigations render the prefetched UI immediately and wait for the * navigations render the prefetched UI immediately and wait for the
...@@ -55,10 +72,8 @@ export async function instant<T>( ...@@ -55,10 +72,8 @@ export async function instant<T>(
fn: () => Promise<T>, fn: () => Promise<T>,
options?: { baseURL?: string } options?: { baseURL?: string }
): Promise<T> { ): Promise<T> {
// Check for nested instant() calls. The cookie is scoped to the browser const context = page.context()
// context, so we can detect nesting by checking if it's already set. if (contextsWithActiveScope.has(context)) {
const existingCookies = await page.context().cookies()
if (existingCookies.some((c) => c.name === INSTANT_COOKIE)) {
throw new Error( throw new Error(
'An instant() scope is already active. Nesting instant() ' + 'An instant() scope is already active. Nesting instant() ' +
'calls is not supported. Did you forget to await the ' + 'calls is not supported. Did you forget to await the ' +
...@@ -66,56 +81,86 @@ export async function instant<T>( ...@@ -66,56 +81,86 @@ export async function instant<T>(
) )
} }
// Acquire the lock by setting the cookie via the browser context. This // Resolve the cookie's scope before touching any browser state, so misuse on
// ensures the cookie is present even on the very first navigation. // a fresh page (no baseURL and no prior navigation) fails with the
// The cookie triggers the CookieStore change event in // descriptive error from resolveURL rather than half-entering a scope.
// navigation-testing-lock.ts, which acquires the in-memory navigation lock.
const { hostname } = new URL(resolveURL(page, options)) const { hostname } = new URL(resolveURL(page, options))
await step('Acquire Instant Lock', () =>
page.context().addCookies([ contextsWithActiveScope.add(context)
{
name: INSTANT_COOKIE,
value: JSON.stringify([0, `p${Math.random()}`]),
domain: hostname,
path: '/',
},
])
)
try { try {
return await fn() // A completed prior scope on this context can leave the cookie behind (its
// client-side release races an in-flight captured-cookie write from a
// locked MPA page load; see the note above). No scope is active for this
// context, so a present cookie is always stale here — clear it before
// acquiring so a completed prior scope never blocks this one.
await releaseInstantCookie(context)
// Acquire the lock by setting the cookie via the browser context. This
// ensures the cookie is present even on the very first navigation. The
// cookie triggers the CookieStore change event in
// navigation-testing-lock.ts, which acquires the in-memory navigation lock.
await step('Acquire Instant Lock', () =>
context.addCookies([
{
name: INSTANT_COOKIE,
value: JSON.stringify([0, `p${Math.random()}`]),
domain: hostname,
path: '/',
},
])
)
try {
return await fn()
} finally {
await step('Release Instant Lock', () => releaseInstantCookie(context))
}
} finally { } finally {
// Release the lock by expiring the instant cookie, leaving every other contextsWithActiveScope.delete(context)
// cookie untouched. }
// }
// We must NOT use `context.clearCookies({ name: INSTANT_COOKIE })` here.
// Playwright implements a filtered `clearCookies` by clearing the ENTIRE /**
// cookie jar and then re-adding the cookies that don't match the filter. * Deletes the instant cookie, leaving every other cookie untouched.
// That briefly removes the application's own cookies too. Next.js reacts *
// to the instant cookie's deletion by immediately re-rendering, and if * We must NOT use `context.clearCookies({ name: INSTANT_COOKIE })` here.
// that render's request races the empty window it observes none of the * Playwright implements a filtered `clearCookies` by clearing the ENTIRE cookie
// app's cookies (e.g. a navigated page renders as if no cookies were set). * jar and then re-adding the cookies that don't match the filter. That briefly
// * removes the application's own cookies too. Next.js reacts to the instant
// Instead we read the instant cookie's stored entries (Next.js may have * cookie's deletion by immediately re-rendering, and if that render's request
// updated the value, e.g. from [0] to [1,null], but preserves the domain * races the empty window it observes none of the app's cookies (e.g. a
// and path) and re-add each with a past expiry, which deletes only those * navigated page renders as if no cookies were set).
// entries without disturbing the rest of the jar. *
await step('Release Instant Lock', async () => { * Instead we read the instant cookie's stored entries (Next.js may have updated
const instantCookies = (await page.context().cookies()).filter( * the value, e.g. from [0] to [1,null], but preserves the domain and path) and
(cookie) => cookie.name === INSTANT_COOKIE * re-add each with a past expiry, which deletes only those entries without
) * disturbing the rest of the jar.
if (instantCookies.length > 0) { *
await page.context().addCookies( * A locked MPA page load can asynchronously re-write (resurrect) the cookie
instantCookies.map((cookie) => ({ * just after we delete it: the client only stops writing once it observes the
name: cookie.name, * deletion, an event that races the pending write. We therefore re-read and
value: cookie.value, * re-delete until the cookie stays gone, bounded so a cookie that some other
domain: cookie.domain, * actor keeps re-setting can't loop forever.
path: cookie.path, */
// A past expiry (Unix epoch seconds) deletes the cookie. async function releaseInstantCookie(
expires: 1, context: PlaywrightBrowserContext
})) ): Promise<void> {
) for (let attempt = 0; attempt < 5; attempt++) {
} const instantCookies = (await context.cookies()).filter(
}) (cookie) => cookie.name === INSTANT_COOKIE
)
if (instantCookies.length === 0) {
return
}
await context.addCookies(
instantCookies.map((cookie) => ({
name: cookie.name,
value: cookie.value,
domain: cookie.domain,
path: cookie.path,
// A past expiry (Unix epoch seconds) deletes the cookie.
expires: 1,
}))
)
} }
} }
......
...@@ -216,6 +216,82 @@ describe('instant-navigation-testing-api', () => { ...@@ -216,6 +216,82 @@ describe('instant-navigation-testing-api', () => {
}) })
}) })
it('recovers from a stale instant cookie left by a prior scope', async () => {
const page = await openPage(next, '/')
// Simulate a cookie leaked by a previous instant() scope. A locked MPA page
// load re-writes the cookie asynchronously and can resurrect it right after
// a prior scope's release deletes it, leaving a captured-state entry in the
// shared browser context. Because the context is reused across tests, a new
// instant() call must treat that residue as stale (clearing it) rather than
// reporting an active scope, or every following test would cascade-fail.
const { hostname } = new URL(next.url)
await page.context().addCookies([
{
name: 'next-instant-navigation-testing',
value: JSON.stringify([1, 'c-stale', null]),
domain: hostname,
path: '/',
},
])
let ranCallback = false
await instant(page, async () => {
ranCallback = true
await page.click('#link-to-target')
const loadingShell = page.locator('[data-testid="loading-shell"]')
await loadingShell.waitFor({ state: 'visible' })
})
expect(ranCallback).toBe(true)
// After exiting the scope the cookie is gone again, so a normal navigation
// is not locked and dynamic content streams in.
const dynamicContent = page.locator('[data-testid="dynamic-content"]')
await dynamicContent.waitFor({ state: 'visible' })
})
it('allows concurrent instant scopes across separate browser contexts', async () => {
const page = await openPage(next, '/')
// A second, independent browser context. Its cookie jar and its page's
// navigation lock are separate from the first context's, so a concurrent
// instant() scope here must not be reported as already active against the
// first. This guards against tracking the active scope per-process instead
// of per-context.
const browser = page.context().browser()
if (!browser) {
throw new Error('Expected the page context to expose a browser instance')
}
const otherContext = await browser.newContext()
try {
const otherPage = await otherContext.newPage()
await otherPage.goto(next.url)
let ranFirst = false
let ranSecond = false
await Promise.all([
instant(page, async () => {
ranFirst = true
await page.click('#link-to-target')
await page
.locator('[data-testid="loading-shell"]')
.waitFor({ state: 'visible' })
}),
instant(otherPage, async () => {
ranSecond = true
await otherPage.click('#link-to-target')
await otherPage
.locator('[data-testid="loading-shell"]')
.waitFor({ state: 'visible' })
}),
])
expect(ranFirst).toBe(true)
expect(ranSecond).toBe(true)
} finally {
await otherContext.close()
}
})
it('renders shell on page reload', async () => { it('renders shell on page reload', async () => {
const page = await openPage(next, '/target-page') const page = await openPage(next, '/target-page')
......
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