Skip to content

Commit

Permalink
Check origins of Server Action requests (#56753)
Browse files Browse the repository at this point in the history
This check ensures that the `x-forwarded-host` (fallbacks to `host` if missing) header matches the request's `origin` header.
  • Loading branch information
shuding authored Oct 12, 2023
1 parent 0a6c60c commit e057c26
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions packages/next/src/server/app-render/action-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,49 @@ export async function handleAction({
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
res.setHeader(
'Cache-Control',
Expand Down

0 comments on commit e057c26

Please sign in to comment.