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

Enforce `serverActions.bodySizeLimit` for Server Actions in Edge runtime (#96012)

https://github.com/vercel/next.js/security/advisories/GHSA-4c39-4ccg-62r3Co-authored-by: 's avatarDmitrii Troitskii <jsleitor@gmail.com>
Co-authored-by: 's avatarSushanth Tiruvaipati <puzzleverseai@gmail.com>
parent cfab3698
...@@ -779,6 +779,16 @@ export async function handleAction({ ...@@ -779,6 +779,16 @@ export async function handleAction({
let actionModId: string | number | undefined let actionModId: string | number | undefined
let boundActionArguments: unknown[] = [] let boundActionArguments: unknown[] = []
const defaultBodySizeLimit = '1 MB'
const bodySizeLimit =
serverActions?.bodySizeLimit ?? defaultBodySizeLimit
const bodySizeLimitBytes =
bodySizeLimit !== defaultBodySizeLimit
? (
require('next/dist/compiled/bytes') as typeof import('next/dist/compiled/bytes')
).parse(bodySizeLimit)
: 1024 * 1024 // 1 MB
if ( if (
// The type check here ensures that `req` is correctly typed, and the // The type check here ensures that `req` is correctly typed, and the
// environment variable check provides dead code elimination. // environment variable check provides dead code elimination.
...@@ -789,8 +799,6 @@ export async function handleAction({ ...@@ -789,8 +799,6 @@ export async function handleAction({
throw new Error('invariant: Missing request body.') throw new Error('invariant: Missing request body.')
} }
// TODO: add body limit
// Use react-server-dom-webpack/server // Use react-server-dom-webpack/server
const { const {
createTemporaryReferenceSet, createTemporaryReferenceSet,
...@@ -803,7 +811,42 @@ export async function handleAction({ ...@@ -803,7 +811,42 @@ export async function handleAction({
if (isMultipartAction) { if (isMultipartAction) {
// TODO-APP: Add streaming support // TODO-APP: Add streaming support
const formData = await req.request.formData() // Read the body stream with size tracking to enforce bodySizeLimitBytes.
// We cannot call req.request.formData() directly as that would bypass
// the body size limit entirely.
const edgeChunks: Uint8Array[] = []
let edgeBodySize = 0
const edgeReader = req.body.getReader()
while (true) {
const { done, value } = await edgeReader.read()
if (done) break
edgeBodySize += value.byteLength
if (edgeBodySize > bodySizeLimitBytes) {
const { ApiError } =
require('../api-utils') as typeof import('../api-utils')
throw new ApiError(
413,
`Body exceeded ${bodySizeLimit} limit.\n` +
`To configure the body size limit for Server Actions, see: https://nextjs.org/docs/app/api-reference/next-config-js/serverActions#bodysizelimit`
)
}
edgeChunks.push(value)
}
// Reconstruct a Blob from the buffered chunks and parse formData from it.
// Note: we must pass the original Content-Type as an explicit header
// rather than relying on the Blob's `type`. The Blob constructor
// normalizes `type` to ASCII lowercase per the File API spec, which
// would lowercase the multipart boundary parameter (e.g.
// `boundary=----WebKitFormBoundaryAbCdEf`). The body bytes contain the
// original mixed-case boundary delimiter, so a lowercased boundary
// would fail to match and `formData()` would throw. An explicit header
// on the Request takes precedence over the Blob's normalized type.
const edgeBodyBlob = new Blob(edgeChunks as BlobPart[])
const formData = await new Request('http://n/', {
method: 'POST',
headers: { 'content-type': req.headers['content-type'] ?? '' },
body: edgeBodyBlob,
}).formData()
if (isFetchAction) { if (isFetchAction) {
// A fetch action with a multipart body. // A fetch action with a multipart body.
...@@ -882,6 +925,7 @@ export async function handleAction({ ...@@ -882,6 +925,7 @@ export async function handleAction({
// which can happen for very simple JSON-like values that don't need multiple flight rows. // which can happen for very simple JSON-like values that don't need multiple flight rows.
const chunks: Buffer[] = [] const chunks: Buffer[] = []
let nonMultipartBodySize = 0
const reader = req.body.getReader() const reader = req.body.getReader()
while (true) { while (true) {
const { done, value } = await reader.read() const { done, value } = await reader.read()
...@@ -889,6 +933,16 @@ export async function handleAction({ ...@@ -889,6 +933,16 @@ export async function handleAction({
break break
} }
nonMultipartBodySize += value.byteLength
if (nonMultipartBodySize > bodySizeLimitBytes) {
const { ApiError } =
require('../api-utils') as typeof import('../api-utils')
throw new ApiError(
413,
`Body exceeded ${bodySizeLimit} limit.\n` +
`To configure the body size limit for Server Actions, see: https://nextjs.org/docs/app/api-reference/next-config-js/serverActions#bodysizelimit`
)
}
chunks.push(value) chunks.push(value)
} }
...@@ -931,16 +985,6 @@ export async function handleAction({ ...@@ -931,16 +985,6 @@ export async function handleAction({
? Readable.from(actionBodyFromMeta) ? Readable.from(actionBodyFromMeta)
: req.body : req.body
const defaultBodySizeLimit = '1 MB'
const bodySizeLimit =
serverActions?.bodySizeLimit ?? defaultBodySizeLimit
const bodySizeLimitBytes =
bodySizeLimit !== defaultBodySizeLimit
? (
require('next/dist/compiled/bytes') as typeof import('next/dist/compiled/bytes')
).parse(bodySizeLimit)
: 1024 * 1024 // 1 MB
let size = 0 let size = 0
const sizeLimitTransform = new Transform({ const sizeLimitTransform = new Transform({
transform(chunk, encoding, callback) { transform(chunk, encoding, callback) {
......
...@@ -249,6 +249,39 @@ describe('app-dir action size limit invalid config', () => { ...@@ -249,6 +249,39 @@ describe('app-dir action size limit invalid config', () => {
expect(logs).not.toContainEqual(expect.stringMatching(/^size = /)) expect(logs).not.toContainEqual(expect.stringMatching(/^size = /))
} }
}) })
it('should error for requests that exceed the size limit in Edge runtime', async () => {
const browser = await next.browser('/form-edge')
const requestTracker = createRequestTracker(browser)
const [, actionResponse] = await requestTracker.captureResponse(
() => browser.elementByCss('#size-3mb').click(),
{ request: { method: 'POST', pathname: '/form-edge' } }
)
expect(actionResponse.status()).toBe(500) // TODO: 413?
expect(
await actionResponse.request().headerValue('content-type')
).toStartWith('multipart/form-data')
// The error should have been returned to the client and thrown, triggering the nearest error boundary.
expect(await browser.elementByCss('#error').text()).toBe(
'Something went wrong!'
)
if (!isNextDeploy) {
await retry(() => {
expect(logs).toContainEqual(
expect.stringContaining('Error: Body exceeded 2mb limit')
)
expect(logs).toContainEqual(
expect.stringContaining(
'To configure the body size limit for Server Actions, see'
)
)
})
expect(logs).not.toContainEqual(expect.stringMatching(/^size = /))
}
})
}) })
}) })
......
'use client'
export default function Error() {
return (
<div>
<h2 id="error">Something went wrong!</h2>
</div>
)
}
import { accountForOverhead } from '../../account-for-overhead'
export const runtime = 'edge'
async function action(formData) {
'use server'
const payload = formData.get('payload').toString()
console.log('size =', payload.length)
}
export default function Page() {
return (
<>
<form action={action}>
<input
type="hidden"
name="payload"
value={'a'.repeat(accountForOverhead(1))}
/>
<button type="submit" id="size-1mb">
SUBMIT 1mb
</button>
</form>
<form action={action}>
<input
type="hidden"
name="payload"
value={'a'.repeat(accountForOverhead(2))}
/>
<button type="submit" id="size-2mb">
SUBMIT 2mb
</button>
</form>
<form action={action}>
<input
type="hidden"
name="payload"
value={'a'.repeat(accountForOverhead(3))}
/>
<button type="submit" id="size-3mb">
SUBMIT 3mb
</button>
</form>
</>
)
}
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