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

Block cross-site form POSTs by default #6510

Merged
merged 11 commits into from
Sep 1, 2022
Merged
5 changes: 5 additions & 0 deletions .changeset/strange-apples-vanish.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
---

[breaking] block cross-site form POSTs by default. disable with config.kit.csrf.checkOrigin
11 changes: 11 additions & 0 deletions documentation/docs/14-configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ const config = {
// ...
}
},
csrf: {
checkOrigin: true
},
env: {
dir: process.cwd(),
publicPrefix: 'PUBLIC_'
Expand Down Expand Up @@ -161,6 +164,14 @@ When pages are prerendered, the CSP header is added via a `<meta http-equiv>` ta

> Note that most [Svelte transitions](https://svelte.dev/tutorial/transition) work by creating an inline `<style>` element. If you use these in your app, you must either leave the `style-src` directive unspecified or add `unsafe-inline`.

### csrf

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` form submissions and verify that it matches the server's origin

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

### env

Environment variable configuration:
Expand Down
3 changes: 3 additions & 0 deletions packages/kit/src/core/config/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,9 @@ const get_defaults = (prefix = '') => ({
directives: directive_defaults,
reportOnly: directive_defaults
},
csrf: {
checkOrigin: true
},
endpointExtensions: undefined,
env: {
dir: process.cwd(),
Expand Down
4 changes: 4 additions & 0 deletions packages/kit/src/core/config/options.js
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,10 @@ const options = object(
reportOnly: directives
}),

csrf: object({
checkOrigin: boolean(true)
}),

// TODO: remove this for the 1.0 release
endpointExtensions: error(
(keypath) => `${keypath} has been renamed to config.kit.moduleExtensions`
Expand Down
3 changes: 3 additions & 0 deletions packages/kit/src/exports/vite/build/build_server.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@ export class Server {
constructor(manifest) {
this.options = {
csp: ${s(config.kit.csp)},
csrf: {
check_origin: ${s(config.kit.csrf.checkOrigin)},
},
dev: false,
get_stack: error => String(error), // for security
handle_error: (error, event) => {
Expand Down
3 changes: 3 additions & 0 deletions packages/kit/src/exports/vite/dev/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,9 @@ export async function dev(vite, vite_config, svelte_config, illegal_imports) {
request,
{
csp: svelte_config.kit.csp,
csrf: {
check_origin: svelte_config.kit.csrf.checkOrigin
},
dev: true,
get_stack: (error) => fix_stack_trace(error),
handle_error: (error, event) => {
Expand Down
15 changes: 15 additions & 0 deletions packages/kit/src/runtime/server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,21 @@ const default_transform = ({ html }) => html;
export async function respond(request, options, state) {
let url = new URL(request.url);

if (options.csrf.check_origin) {
const type = request.headers.get('content-type')?.split(';')[0];

const forbidden =
request.method === 'POST' &&
request.headers.get('origin') !== url.origin &&
(type === 'application/x-www-form-urlencoded' || type === 'multipart/form-data');
Conduitry marked this conversation as resolved.
Show resolved Hide resolved

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

const { parameter, allowed } = options.method_override;
const method_override = url.searchParams.get(parameter)?.toUpperCase();

Expand Down
4 changes: 4 additions & 0 deletions packages/kit/test/apps/basics/src/routes/csrf/+server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/** @type {import('./$types').RequestHandler} */
export function POST() {
return new Response(undefined, { status: 201 });
}
15 changes: 15 additions & 0 deletions packages/kit/test/apps/basics/test/server.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { expect } from '@playwright/test';
import { test } from '../../../utils.js';
import { fetch } from 'undici';
import { createHash, randomBytes } from 'node:crypto';

/** @typedef {import('@playwright/test').Response} Response */
Expand All @@ -22,6 +23,20 @@ test.describe('Content-Type', () => {
});
});

test.describe('CSRF', () => {
test('Blocks requests with incorrect origin', async ({ baseURL }) => {
const res = await fetch(`${baseURL}/csrf`, {
method: 'POST',
headers: {
'content-type': 'application/x-www-form-urlencoded'
}
});

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

Conduitry marked this conversation as resolved.
Show resolved Hide resolved
test.describe('Endpoints', () => {
test('HEAD with matching headers but without body', async ({ request }) => {
const url = '/endpoint-output/body';
Expand Down
3 changes: 3 additions & 0 deletions packages/kit/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,9 @@ export interface KitConfig {
directives?: CspDirectives;
reportOnly?: CspDirectives;
};
csrf?: {
checkOrigin?: boolean;
};
env?: {
dir?: string;
publicPrefix?: string;
Expand Down
3 changes: 3 additions & 0 deletions packages/kit/types/internal.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,9 @@ export type SSRNodeLoader = () => Promise<SSRNode>;

export interface SSROptions {
csp: ValidatedConfig['kit']['csp'];
csrf: {
check_origin: boolean;
};
dev: boolean;
get_stack: (error: Error) => string | undefined;
handle_error(error: Error & { frame?: string }, event: RequestEvent): void;
Expand Down