Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check origins of Server Action requests #56753

Merged
merged 5 commits into from
Oct 12, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading