Skip to content

Commit

Permalink
fix middleware cookie initialization (#65820)
Browse files Browse the repository at this point in the history
When we provide the `set-cookie` string in `x-middleware-set-cookie`, we
need to ensure that multiple values are properly delimited.

We also make sure the cookies that get passed into `RequestCookies`
aren't in `ResponseCookie` form, to prevent something like `Path=/` from
being part of `cookies()`.

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

Closes NEXT-
Fixes #

-->
  • Loading branch information
ztanner authored and lubieowoce committed Sep 2, 2024
1 parent d99d229 commit 196f629
Show file tree
Hide file tree
Showing 6 changed files with 33 additions and 20 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ import {
RequestCookiesAdapter,
type ReadonlyRequestCookies,
} from '../web/spec-extension/adapters/request-cookies'
import type { ResponseCookies } from '../web/spec-extension/cookies'
import { RequestCookies } from '../web/spec-extension/cookies'
import { ResponseCookies, RequestCookies } from '../web/spec-extension/cookies'
import { DraftModeProvider } from './draft-mode-provider'
import { splitCookiesString } from '../web/utils'

function getHeaders(headers: Headers | IncomingHttpHeaders): ReadonlyHeaders {
const cleaned = HeadersAdapter.from(headers)
Expand All @@ -30,13 +30,6 @@ function getHeaders(headers: Headers | IncomingHttpHeaders): ReadonlyHeaders {
return HeadersAdapter.seal(cleaned)
}

function getCookies(
headers: Headers | IncomingHttpHeaders
): ReadonlyRequestCookies {
const cookies = new RequestCookies(HeadersAdapter.from(headers))
return RequestCookiesAdapter.seal(cookies)
}

function getMutableCookies(
headers: Headers | IncomingHttpHeaders,
onUpdateCookies?: (cookies: string[]) => void
Expand Down Expand Up @@ -103,24 +96,32 @@ export const RequestAsyncStorageWrapper: AsyncStorageWrapper<
if (!cache.cookies) {
// if middleware is setting cookie(s), then include those in
// the initial cached cookies so they can be read in render
let combinedCookies
const requestCookies = new RequestCookies(
HeadersAdapter.from(req.headers)
)

if (
'x-middleware-set-cookie' in req.headers &&
typeof req.headers['x-middleware-set-cookie'] === 'string'
) {
combinedCookies = `${req.headers.cookie}; ${req.headers['x-middleware-set-cookie']}`
const setCookieValue = req.headers['x-middleware-set-cookie']
const responseHeaders = new Headers()

for (const cookie of splitCookiesString(setCookieValue)) {
responseHeaders.append('set-cookie', cookie)
}

const responseCookies = new ResponseCookies(responseHeaders)

// Transfer cookies from ResponseCookies to RequestCookies
for (const cookie of responseCookies.getAll()) {
requestCookies.set(cookie.name, cookie.value ?? '')
}
}

// Seal the cookies object that'll freeze out any methods that could
// mutate the underlying data.
cache.cookies = getCookies(
combinedCookies
? {
...req.headers,
cookie: combinedCookies,
}
: req.headers
)
cache.cookies = RequestCookiesAdapter.seal(requestCookies)
}

return cache.cookies
Expand Down
1 change: 1 addition & 0 deletions packages/next/src/server/web/spec-extension/cookies.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export {
RequestCookies,
ResponseCookies,
stringifyCookie,
} from 'next/dist/compiled/@edge-runtime/cookies'
9 changes: 8 additions & 1 deletion packages/next/src/server/web/spec-extension/response.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { stringifyCookie } from '../../web/spec-extension/cookies'
import type { I18NConfig } from '../../config-shared'
import { NextURL } from '../next-url'
import { toNodeOutgoingHttpHeaders, validateURL } from '../utils'
Expand Down Expand Up @@ -55,7 +56,13 @@ export class NextResponse<Body = unknown> extends Response {
const newHeaders = new Headers(headers)

if (result instanceof ResponseCookies) {
headers.set('x-middleware-set-cookie', result.toString())
headers.set(
'x-middleware-set-cookie',
result
.getAll()
.map((cookie) => stringifyCookie(cookie))
.join(',')
)
}

handleMiddlewareField(init, newHeaders)
Expand Down
2 changes: 2 additions & 0 deletions test/e2e/app-dir/app-middleware/app-middleware.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,10 +140,12 @@ createNextDescribe(

const initialRandom1 = await browser.elementById('rsc-cookie-1').text()
const initialRandom2 = await browser.elementById('rsc-cookie-2').text()
const totalCookies = await browser.elementById('total-cookies').text()

// cookies were set in middleware, assert they are present and match the Math.random() pattern
expect(initialRandom1).toMatch(/Cookie 1: \d+\.\d+/)
expect(initialRandom2).toMatch(/Cookie 2: \d+\.\d+/)
expect(totalCookies).toBe('Total Cookie Length: 2')

await browser.refresh()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export default function Page() {
<div>
<p id="rsc-cookie-1">Cookie 1: {rscCookie1}</p>
<p id="rsc-cookie-2">Cookie 2: {rscCookie2}</p>
<p id="total-cookies">Total Cookie Length: {cookies().size}</p>
</div>
)
}
1 change: 1 addition & 0 deletions test/e2e/app-dir/app-middleware/app/rsc-cookies/page.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export default function Page() {
<div>
<p id="rsc-cookie-1">Cookie 1: {rscCookie1}</p>
<p id="rsc-cookie-2">Cookie 2: {rscCookie2}</p>
<p id="total-cookies">Total Cookie Length: {cookies().size}</p>
<Link href="/rsc-cookies-delete">To Delete Cookies Route</Link>
</div>
)
Expand Down

0 comments on commit 196f629

Please sign in to comment.