feat: add CSRF middleware (#3018)
Co-authored-by: Marvin Hagemeister <marvin@deno.com>
This commit is contained in:
co-authored by
Marvin Hagemeister
parent
3ad3e6ecf3
commit
a988dc37e1
@@ -0,0 +1,113 @@
|
|||||||
|
import type { Context } from "../context.ts";
|
||||||
|
import { HttpError } from "../error.ts";
|
||||||
|
import type { Middleware } from "./mod.ts";
|
||||||
|
|
||||||
|
/** Options for {@linkcode csrf}. **/
|
||||||
|
// deno-lint-ignore no-explicit-any
|
||||||
|
export interface CsrfOptions<State = any> {
|
||||||
|
/**
|
||||||
|
* origin - Specifies the allowed origin(s) for requests.
|
||||||
|
* - string: A single allowed origin.
|
||||||
|
* - string[]: static allowed origins.
|
||||||
|
* - function: A function to determine if an origin is allowed.
|
||||||
|
*/
|
||||||
|
origin?:
|
||||||
|
| string
|
||||||
|
| string[]
|
||||||
|
| ((origin: string, context: Context<State>) => boolean);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CSRF Protection Middleware for Fresh.
|
||||||
|
*
|
||||||
|
* @param options Options for the CSRF protection middleware.
|
||||||
|
* @returns The middleware handler function.
|
||||||
|
*
|
||||||
|
* @example Basic usage (with defaults)
|
||||||
|
* ```ts
|
||||||
|
* const app = new App<State>()
|
||||||
|
*
|
||||||
|
* app.use(csrf())
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @example Specifying static origins
|
||||||
|
* ```ts
|
||||||
|
* app.use(csrf({ origin: 'https://myapp.example.com' }))
|
||||||
|
*
|
||||||
|
* // string[]
|
||||||
|
* app.use(
|
||||||
|
* csrf({
|
||||||
|
* origin: ['https://myapp.example.com', 'http://development.myapp.example.com'],
|
||||||
|
* })
|
||||||
|
* )
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @example Specifying more complex origins
|
||||||
|
* ```ts
|
||||||
|
* app.use(
|
||||||
|
* '*',
|
||||||
|
* csrf({
|
||||||
|
* origin: (origin) => ['https://myapp.example.com', 'http://development.myapp.example.com'].includes(origin),
|
||||||
|
* })
|
||||||
|
* )
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export function csrf<State>(
|
||||||
|
options?: CsrfOptions,
|
||||||
|
): Middleware<State> {
|
||||||
|
const isAllowedOrigin = (
|
||||||
|
origin: string | null,
|
||||||
|
ctx: Context<State>,
|
||||||
|
) => {
|
||||||
|
if (origin === null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const optsOrigin = options?.origin;
|
||||||
|
|
||||||
|
if (!optsOrigin) {
|
||||||
|
return origin === ctx.url.origin;
|
||||||
|
}
|
||||||
|
if (typeof optsOrigin === "string") {
|
||||||
|
return origin === optsOrigin;
|
||||||
|
}
|
||||||
|
if (typeof optsOrigin === "function") {
|
||||||
|
return optsOrigin(origin, ctx);
|
||||||
|
}
|
||||||
|
return Array.isArray(optsOrigin) && optsOrigin.includes(origin);
|
||||||
|
};
|
||||||
|
|
||||||
|
return async (ctx) => {
|
||||||
|
const { method, headers } = ctx.req;
|
||||||
|
|
||||||
|
// Safe methods
|
||||||
|
if (method === "GET" || method === "HEAD" || method === "OPTIONS") {
|
||||||
|
return await ctx.next();
|
||||||
|
}
|
||||||
|
|
||||||
|
const secFetchSite = headers.get("Sec-Fetch-Site");
|
||||||
|
const origin = headers.get("origin");
|
||||||
|
|
||||||
|
if (secFetchSite !== null) {
|
||||||
|
if (
|
||||||
|
secFetchSite === "same-origin" || secFetchSite === "none" ||
|
||||||
|
isAllowedOrigin(origin, ctx)
|
||||||
|
) {
|
||||||
|
return await ctx.next();
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new HttpError(403);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Neither `Sec-Fetch-Site` or `Origin` is set
|
||||||
|
if (origin === null) {
|
||||||
|
return await ctx.next();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isAllowedOrigin(origin, ctx)) {
|
||||||
|
return await ctx.next();
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new HttpError(403);
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
import { App } from "../app.ts";
|
||||||
|
import type { Method } from "../router.ts";
|
||||||
|
import { csrf, type CsrfOptions } from "./csrf.ts";
|
||||||
|
import { expect } from "@std/expect";
|
||||||
|
|
||||||
|
function testHandler<T>(
|
||||||
|
options?: CsrfOptions<T>,
|
||||||
|
): (request: Request) => Promise<Response> {
|
||||||
|
return new App<T>()
|
||||||
|
.use(csrf(options))
|
||||||
|
.all("/", () => new Response("hello"))
|
||||||
|
.handler();
|
||||||
|
}
|
||||||
|
|
||||||
|
function createTests(trusted: CsrfOptions["origin"]) {
|
||||||
|
return async function runTest(
|
||||||
|
method: Method,
|
||||||
|
expected: 200 | 403,
|
||||||
|
test: {
|
||||||
|
secFetchSite?: "cross-site" | "same-origin" | "same-site" | "none";
|
||||||
|
origin?: string;
|
||||||
|
} = {},
|
||||||
|
) {
|
||||||
|
const handler = testHandler({ origin: trusted });
|
||||||
|
|
||||||
|
const headers = new Headers();
|
||||||
|
if (test.secFetchSite) headers.append("Sec-Fetch-Site", test.secFetchSite);
|
||||||
|
if (test.origin) {
|
||||||
|
headers.append("Origin", test.origin);
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await handler(
|
||||||
|
new Request("https://example.com", { method, headers }),
|
||||||
|
);
|
||||||
|
await res.body?.cancel();
|
||||||
|
expect(res.status).toEqual(expected);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
Deno.test("CSRF - allow GET/HEAD/OPTIONS", async () => {
|
||||||
|
const runTest = createTests("https://example.com");
|
||||||
|
|
||||||
|
await runTest("GET", 200);
|
||||||
|
await runTest("HEAD", 200);
|
||||||
|
await runTest("OPTIONS", 200);
|
||||||
|
});
|
||||||
|
|
||||||
|
Deno.test("CSRF - Sec-Fetch-Site", async () => {
|
||||||
|
const runTest = createTests("https://example.com");
|
||||||
|
|
||||||
|
await runTest("POST", 200, { secFetchSite: "same-origin" });
|
||||||
|
await runTest("POST", 200, { secFetchSite: "none" });
|
||||||
|
await runTest("POST", 403, { secFetchSite: "cross-site" });
|
||||||
|
await runTest("POST", 403, { secFetchSite: "same-site" });
|
||||||
|
|
||||||
|
await runTest("POST", 200);
|
||||||
|
await runTest("POST", 200, { origin: "https://example.com" });
|
||||||
|
await runTest("POST", 403, { origin: "https://attacker.example.com" });
|
||||||
|
await runTest("POST", 403, { origin: "null" });
|
||||||
|
|
||||||
|
await runTest("GET", 200, { secFetchSite: "cross-site" });
|
||||||
|
await runTest("HEAD", 200, { secFetchSite: "cross-site" });
|
||||||
|
await runTest("OPTIONS", 200, { secFetchSite: "cross-site" });
|
||||||
|
await runTest("PUT", 403, { secFetchSite: "cross-site" });
|
||||||
|
});
|
||||||
|
|
||||||
|
Deno.test("CSRF - cross origin", async () => {
|
||||||
|
const runTest = createTests("https://trusted.example.com");
|
||||||
|
|
||||||
|
await runTest("POST", 200, { origin: "https://trusted.example.com" });
|
||||||
|
await runTest("POST", 200, {
|
||||||
|
origin: "https://trusted.example.com",
|
||||||
|
secFetchSite: "cross-site",
|
||||||
|
});
|
||||||
|
|
||||||
|
await runTest("POST", 403, { origin: "https://attacker.example.com" });
|
||||||
|
await runTest("POST", 403, {
|
||||||
|
origin: "https://attacker.example.com",
|
||||||
|
secFetchSite: "cross-site",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
Deno.test("CSRF - array origin", async () => {
|
||||||
|
const runTest = createTests(
|
||||||
|
["https://example.com", "https://trusted.example.com"],
|
||||||
|
);
|
||||||
|
|
||||||
|
await runTest("POST", 200, { origin: "https://trusted.example.com" });
|
||||||
|
await runTest("POST", 200, { origin: "https://example.com" });
|
||||||
|
await runTest("POST", 403, { origin: "https://foo.example.com" });
|
||||||
|
});
|
||||||
|
|
||||||
|
Deno.test("CSRF - function origin", async () => {
|
||||||
|
const runTest = createTests(
|
||||||
|
(origin) => origin === "https://example.com",
|
||||||
|
);
|
||||||
|
|
||||||
|
await runTest("POST", 200, { origin: "https://example.com" });
|
||||||
|
await runTest("POST", 403, { origin: "https://trusted.example.com" });
|
||||||
|
await runTest("POST", 403, { origin: "https://foo.example.com" });
|
||||||
|
});
|
||||||
@@ -11,6 +11,7 @@ export {
|
|||||||
export type { LayoutConfig, Lazy, MaybeLazy, RouteConfig } from "./types.ts";
|
export type { LayoutConfig, Lazy, MaybeLazy, RouteConfig } from "./types.ts";
|
||||||
export type { Middleware, MiddlewareFn } from "./middlewares/mod.ts";
|
export type { Middleware, MiddlewareFn } from "./middlewares/mod.ts";
|
||||||
export { staticFiles } from "./middlewares/static_files.ts";
|
export { staticFiles } from "./middlewares/static_files.ts";
|
||||||
|
export { csrf, type CsrfOptions } from "./middlewares/csrf.ts";
|
||||||
export { cors, type CORSOptions } from "./middlewares/cors.ts";
|
export { cors, type CORSOptions } from "./middlewares/cors.ts";
|
||||||
export type { FreshConfig, ResolvedFreshConfig } from "./config.ts";
|
export type { FreshConfig, ResolvedFreshConfig } from "./config.ts";
|
||||||
export type { Context, FreshContext, Island } from "./context.ts";
|
export type { Context, FreshContext, Island } from "./context.ts";
|
||||||
|
|||||||
Reference in New Issue
Block a user