Unverified Commit e057c263 authored by Shu Ding's avatar Shu Ding Committed by GitHub

Check origins of Server Action requests (#56753)

This check ensures that the `x-forwarded-host` (fallbacks to `host` if missing) header matches the request's `origin` header.
parent 0a6c60ce
...@@ -286,6 +286,49 @@ export async function handleAction({ ...@@ -286,6 +286,49 @@ export async function handleAction({
return return
} }
const originHostname =
typeof req.headers['origin'] === 'string'
? new URL(req.headers['origin']).host
: undefined
const host = req.headers['x-forwarded-host'] || req.headers['host']
// This is to prevent CSRF attacks. If `x-forwarded-host` is set, we need to
// ensure that the request is coming from the same host.
if (!originHostname) {
// This might be an old browser that doesn't send `host` header. We ignore
// this case.
console.warn(
'Missing `origin` header from a forwarded Server Actions request.'
)
} else if (!host || originHostname !== host) {
// This is an attack. We should not proceed the action.
console.error(
'`x-forwarded-host` and `host` headers do not match `origin` header from a forwarded Server Actions request. Aborting the action.'
)
const error = new Error('Invalid Server Actions request.')
if (isFetchAction) {
res.statusCode = 500
await Promise.all(staticGenerationStore.pendingRevalidates || [])
const promise = Promise.reject(error)
try {
await promise
} catch {}
return {
type: 'done',
result: await generateFlight(ctx, {
actionResult: promise,
// if the page was not revalidated, we can skip the rendering the flight tree
skipFlight: !staticGenerationStore.pathWasRevalidated,
}),
}
}
throw error
}
// ensure we avoid caching server actions unexpectedly // ensure we avoid caching server actions unexpectedly
res.setHeader( res.setHeader(
'Cache-Control', 'Cache-Control',
......
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