Unverified Commit f1c11203 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

[backport] Fix double-encoding of URL pathname parts in client param parsing (#93506)

Backports:

- #93491
parent 2d08397b
......@@ -49,6 +49,24 @@ export function getRenderedPathname(
.pathname) as NormalizedPathname
}
// Pathname parts come from `URL.pathname.split('/')`, so they are already
// in the encoded form the URL parser produces. The server-side equivalent
// (`get-dynamic-param.ts`) starts from a decoded param value and applies
// `encodeURIComponent` once. The two encodings are not the same — for
// example, the URL parser leaves `,` and `:` untouched while
// `encodeURIComponent` percent-encodes them. To produce the same canonical
// form on the client (and avoid double-encoding `%xx` sequences such as
// `%2F` → `%252F`), we decode the URL part first and re-encode it.
function canonicalizeURLPart(part: string): string {
try {
return encodeURIComponent(decodeURIComponent(part))
} catch {
// `decodeURIComponent` throws on malformed sequences. Fall back to the
// already-encoded form rather than failing the navigation.
return part
}
}
export function parseDynamicParamFromURLPart(
paramType: DynamicParamTypesShort,
pathnameParts: Array<string>,
......@@ -61,7 +79,7 @@ export function parseDynamicParamFromURLPart(
// Catchalls receive all the remaining URL parts. If there are no
// remaining pathname parts, return an empty array.
return partIndex < pathnameParts.length
? pathnameParts.slice(partIndex).map((s) => encodeURIComponent(s))
? pathnameParts.slice(partIndex).map((s) => canonicalizeURLPart(s))
: []
}
// Catchall intercepted
......@@ -73,10 +91,10 @@ export function parseDynamicParamFromURLPart(
return partIndex < pathnameParts.length
? pathnameParts.slice(partIndex).map((s, i) => {
if (i === 0) {
return encodeURIComponent(s.slice(prefix))
return canonicalizeURLPart(s.slice(prefix))
}
return encodeURIComponent(s)
return canonicalizeURLPart(s)
})
: []
}
......@@ -85,7 +103,7 @@ export function parseDynamicParamFromURLPart(
// Optional catchalls receive all the remaining URL parts, unless this is
// the end of the pathname, in which case they return null.
return partIndex < pathnameParts.length
? pathnameParts.slice(partIndex).map((s) => encodeURIComponent(s))
? pathnameParts.slice(partIndex).map((s) => canonicalizeURLPart(s))
: null
}
// Dynamic
......@@ -100,7 +118,7 @@ export function parseDynamicParamFromURLPart(
// recovery options.
return ''
}
return encodeURIComponent(pathnameParts[partIndex])
return canonicalizeURLPart(pathnameParts[partIndex])
}
// Dynamic intercepted
case 'di(..)(..)':
......@@ -119,7 +137,7 @@ export function parseDynamicParamFromURLPart(
return ''
}
return encodeURIComponent(pathnameParts[partIndex].slice(prefix))
return canonicalizeURLPart(pathnameParts[partIndex].slice(prefix))
}
default:
paramType satisfies never
......
import { Suspense } from 'react'
type Params = { slug: string }
async function PageContent({ params }: { params: Promise<Params> }) {
const { slug } = await params
return <div data-slug-page>{`slug=${slug}`}</div>
}
export default function SlugPage({ params }: { params: Promise<Params> }) {
return (
<Suspense fallback={<div data-page-loading>Loading…</div>}>
<PageContent params={params} />
</Suspense>
)
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { connection } from 'next/server'
import { Suspense } from 'react'
import { LinkAccordion } from '../components/link-accordion'
// `connection()` ensures the hub is dynamically rendered.
async function HubContent() {
await connection()
return <div id="hub-content">Hub</div>
}
export default function HubPage() {
return (
<div id="hub">
<Suspense fallback={<div data-loading>Loading…</div>}>
<HubContent />
</Suspense>
<ul>
<li>
<LinkAccordion href="/foo">unencoded</LinkAccordion>
</li>
<li>
<LinkAccordion href="/foo%2Fbar">encoded slash</LinkAccordion>
</li>
</ul>
</div>
)
}
'use client'
import Link from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
href,
prefetch,
children,
}: {
href: string
prefetch?: boolean
children: React.ReactNode
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch}>
{children}
</Link>
) : (
<>{children} (link is hidden)</>
)}
</>
)
}
import { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright'
import { createRouterAct } from 'router-act'
/**
* When a dynamic param contains a percent-encoded forward slash (`%2F`), the
* client double-encodes the URL part when deriving its segment cache key, while
* the server encodes the decoded value once. The resulting segment mismatch
* causes the navigation reducer to invalidate the entire route cache, so any
* later prefetch for the same URL re-fetches the route tree
* (`next-router-segment-prefetch: /_tree`).
*
* The fixture is intentionally fully dynamic (no `generateStaticParams`): a
* statically prerendered file is served from the CDN without the `%2F`
* round-trip the bug depends on.
*/
describe('segment cache - encoded slash params', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
if (isNextDev) {
test('prefetching is disabled in dev mode', () => {})
return
}
describe.each([
{ label: 'unencoded param', href: '/foo' },
{ label: 'encoded slash in param', href: '/foo%2Fbar' },
])('$label', ({ href }) => {
it('back navigation does not refetch the route tree', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
act = createRouterAct(p)
},
})
// Reveal the link — wait for the prefetch to settle.
await act(async () => {
const toggle = await browser.elementByCss(
`input[data-link-accordion="${href}"]`
)
await toggle.click()
})
// Click through. The prefetched data should satisfy this nav.
const link = await browser.elementByCss(`a[href="${href}"]`)
await act(async () => {
await link.click()
})
await browser.elementByCss('[data-slug-page]')
// Browser back to the home page, then ensure the link is revealed. The
// route tree cache already has an entry for the URL — the re-prefetch on
// Link mount must not fire any requests. With the encoded-slash bug, the
// cache lookup misses and a `next-router-segment-prefetch: /_tree`
// request goes out.
await act(async () => {
await browser.back()
await browser.elementById('hub')
// BFCache restoration of `useState` is browser-dependent. If the Link
// isn't in the DOM (checkbox unchecked), click the toggle to reveal it.
const linkSelector = `a[href="${href}"]`
if (!(await browser.hasElementByCssSelector(linkSelector))) {
const toggle = await browser.elementByCss(
`input[data-link-accordion="${href}"]`
)
await toggle.click()
}
await browser.elementByCss(linkSelector)
}, 'no-requests')
})
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
}
module.exports = nextConfig
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