Skip to content

Block cross-site form POSTs by default #6510

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

Merged
merged 11 commits into from
Sep 1, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
4 changes: 2 additions & 2 deletions documentation/docs/14-configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,9 +168,9 @@ When pages are prerendered, the CSP header is added via a `<meta http-equiv>` ta

Protection against [cross-site request forgery](https://owasp.org/www-community/attacks/csrf) attacks:

- `checkOrigin` — if `true`, SvelteKit will check the incoming `origin` header for `POST` requests and verify that it matches the server's origin
- `checkOrigin` — if `true`, SvelteKit will check the incoming `origin` header for `POST` form submissions and verify that it matches the server's origin

To allow people to make `POST` requests to your app from other origins, you will need to disable this option. Be careful!
To allow people to make `POST` form submissions to your app from other origins, you will need to disable this option. Be careful!

### env

Expand Down
19 changes: 13 additions & 6 deletions packages/kit/src/runtime/server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,19 @@ const default_transform = ({ html }) => html;
export async function respond(request, options, state) {
let url = new URL(request.url);

if (
options.csrf.check_origin &&
request.method === 'POST' &&
request.headers.get('origin') !== url.origin
) {
return new Response(`Cross-site ${request.method} requests are forbidden`, { status: 403 });
if (options.csrf.check_origin) {
const type = request.headers.get('content-type');

const forbidden =
request.method === 'POST' &&
request.headers.get('origin') !== url.origin &&
(type === 'application/x-www-form-urlencoded' || type === 'multipart/form-data');

if (forbidden) {
return new Response(`Cross-site ${request.method} form submissions are forbidden`, {
status: 403
});
}
}

const { parameter, allowed } = options.method_override;
Expand Down
2 changes: 1 addition & 1 deletion packages/kit/test/apps/basics/test/server.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ test.describe('CSRF', () => {
});

expect(res.status).toBe(403);
expect(await res.text()).toBe('Cross-site POST requests are forbidden');
expect(await res.text()).toBe('Cross-site POST form submissions are forbidden');
});
});

Expand Down