From 0a9bd39aac4e1fccfd2d1a8a097d60b40d64c3e8 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 31 Aug 2025 12:35:35 +0200 Subject: [PATCH] Add CSRF middleware (#10051) ref OUT-Q325-03 --- app/components/primitives/Form.tsx | 19 ++++ app/hooks/useCsrfToken.ts | 30 +++++ app/scenes/Login/OAuthAuthorize.tsx | 5 +- .../Login/components/WorkspaceSetup.tsx | 4 +- app/utils/ApiClient.ts | 25 +++- server/errors.ts | 6 + server/middlewares/csrf.ts | 107 ++++++++++++++++++ server/models/ApiKey.ts | 2 +- server/models/helpers/AuthenticationHelper.ts | 59 ---------- server/models/oauth/OAuthAuthentication.ts | 2 +- server/routes/api/attachments/attachments.ts | 1 + server/routes/api/index.ts | 2 + server/routes/auth/index.ts | 2 + server/routes/oauth/index.ts | 2 + server/services/web.ts | 2 + server/storage/files/BaseStorage.ts | 3 + server/storage/files/LocalStorage.ts | 4 + server/storage/files/S3Storage.ts | 2 + server/utils/csrf.ts | 55 +++++++++ shared/constants.ts | 6 + .../helpers/AuthenticationHelper.test.ts | 0 shared/helpers/AuthenticationHelper.ts | 62 ++++++++++ 22 files changed, 335 insertions(+), 65 deletions(-) create mode 100644 app/components/primitives/Form.tsx create mode 100644 app/hooks/useCsrfToken.ts create mode 100644 server/middlewares/csrf.ts create mode 100644 server/utils/csrf.ts rename {server/models => shared}/helpers/AuthenticationHelper.test.ts (100%) create mode 100644 shared/helpers/AuthenticationHelper.ts diff --git a/app/components/primitives/Form.tsx b/app/components/primitives/Form.tsx new file mode 100644 index 0000000000..7b7cec6103 --- /dev/null +++ b/app/components/primitives/Form.tsx @@ -0,0 +1,19 @@ +import { CSRF } from "@shared/constants"; +import { useCsrfToken } from "~/hooks/useCsrfToken"; + +/** + * Form component that automatically includes a CSRF token as a hidden input field. + */ +export const Form = ({ + children, + ...props +}: React.FormHTMLAttributes) => { + const token = useCsrfToken(); + + return ( +
+ {token && } + {children} +
+ ); +}; diff --git a/app/hooks/useCsrfToken.ts b/app/hooks/useCsrfToken.ts new file mode 100644 index 0000000000..ce4a1b695f --- /dev/null +++ b/app/hooks/useCsrfToken.ts @@ -0,0 +1,30 @@ +import { CSRF } from "@shared/constants"; +import { useState, useEffect } from "react"; +import { getCookie } from "tiny-cookie"; + +/** + * React hook for accessing CSRF tokens in components + * + * @returns The CSRF token string or null if not found + */ +export function useCsrfToken() { + const [token, setToken] = useState(null); + + useEffect(() => { + const updateToken = () => { + const currentToken = getCookie(CSRF.cookieName); + + setToken(currentToken); + }; + + // Initial load + updateToken(); + + // Listen for cookie changes (when navigating or refreshing) + const interval = setInterval(updateToken, 1000); + + return () => clearInterval(interval); + }, []); + + return token; +} diff --git a/app/scenes/Login/OAuthAuthorize.tsx b/app/scenes/Login/OAuthAuthorize.tsx index 1acc7509b3..be390f4730 100644 --- a/app/scenes/Login/OAuthAuthorize.tsx +++ b/app/scenes/Login/OAuthAuthorize.tsx @@ -26,6 +26,7 @@ import { Background } from "./components/Background"; import { Centered } from "./components/Centered"; import { ConnectHeader } from "./components/ConnectHeader"; import { TeamSwitcher } from "./components/TeamSwitcher"; +import { Form } from "~/components/primitives/Form"; export default function OAuthAuthorize() { const team = useCurrentTeam({ rejectOnEmpty: false }); @@ -203,7 +204,7 @@ function Authorize() { ))} -
-
+ ); diff --git a/app/scenes/Login/components/WorkspaceSetup.tsx b/app/scenes/Login/components/WorkspaceSetup.tsx index dbda31f535..4c54770e65 100644 --- a/app/scenes/Login/components/WorkspaceSetup.tsx +++ b/app/scenes/Login/components/WorkspaceSetup.tsx @@ -12,15 +12,17 @@ import { detectLanguage } from "~/utils/language"; import { BackButton } from "./BackButton"; import { Background } from "./Background"; import { Centered } from "./Centered"; +import { Form } from "~/components/primitives/Form"; const WorkspaceSetup = ({ onBack }: { onBack?: () => void }) => { const { t } = useTranslation(); + return ( { + // Skip if not a potentially mutating method + if (["GET", "HEAD", "OPTIONS"].includes(ctx.method)) { + return false; + } + + // If not using cookie-based auth, skip CSRF protection + if (!ctx.cookies.get("accessToken")) { + return false; + } + + // For API routes, use AuthenticationHelper to determine if the operation is read-only + if (ctx.originalUrl.startsWith("/api/")) { + const canAccessWithReadOnly = AuthenticationHelper.canAccess(ctx.path, [ + Scope.Read, + ]); + + // If it can be accessed with read-only scope, it doesn't need CSRF protection + if (canAccessWithReadOnly) { + return false; + } + } + + // Protect all other mutating requests + return true; + }; + + return async function verifyCSRFTokenMiddleware(ctx: AppContext, next: Next) { + if (!shouldProtectRequest(ctx)) { + await next(); + return; + } + + // Get token from cookie + const cookieVal = ctx.cookies.get(CSRF.cookieName); + if (!cookieVal) { + throw CSRFError("CSRF token missing from cookie"); + } + + // Get token from header or form field depending on type + // Access the already-parsed body from koa-body middleware + const inputVal = + ctx.get(CSRF.headerName) || ctx.request.body?.[CSRF.fieldName]; + + if (!inputVal) { + throw CSRFError("CSRF token missing from request"); + } + + // Verify both tokens are valid HMAC-signed tokens + const { valid: cookieValid } = unbundleToken(cookieVal, env.SECRET_KEY); + const { valid: inputValid } = unbundleToken(inputVal, env.SECRET_KEY); + + if (!cookieValid || !inputValid) { + throw CSRFError("CSRF token invalid or malformed"); + } + + // Verify tokens match (double-submit check) + if (cookieVal !== inputVal) { + throw CSRFError("CSRF token mismatch"); + } + + await next(); + }; +} diff --git a/server/models/ApiKey.ts b/server/models/ApiKey.ts index 90c78742a4..b620373a74 100644 --- a/server/models/ApiKey.ts +++ b/server/models/ApiKey.ts @@ -21,7 +21,7 @@ import User from "./User"; import ParanoidModel from "./base/ParanoidModel"; import { SkipChangeset } from "./decorators/Changeset"; import Fix from "./decorators/Fix"; -import AuthenticationHelper from "./helpers/AuthenticationHelper"; +import AuthenticationHelper from "@shared/helpers/AuthenticationHelper"; import Length from "./validators/Length"; @Table({ tableName: "apiKeys", modelName: "apiKey" }) diff --git a/server/models/helpers/AuthenticationHelper.ts b/server/models/helpers/AuthenticationHelper.ts index 89e2d2ad13..e1f44efa28 100644 --- a/server/models/helpers/AuthenticationHelper.ts +++ b/server/models/helpers/AuthenticationHelper.ts @@ -1,28 +1,10 @@ /* oxlint-disable @typescript-eslint/no-var-requires */ import find from "lodash/find"; -import { Scope } from "@shared/types"; import env from "@server/env"; import Team from "@server/models/Team"; import { Hook, PluginManager } from "@server/utils/PluginManager"; export default class AuthenticationHelper { - /** - * The mapping of method names to their scopes, anything not listed here - * defaults to `Scope.Write`. - * - * - `documents.create` -> `Scope.Create` - * - `documents.list` -> `Scope.Read` - * - `documents.info` -> `Scope.Read` - */ - private static methodToScope = { - create: Scope.Create, - list: Scope.Read, - info: Scope.Read, - search: Scope.Read, - documents: Scope.Read, - export: Scope.Read, - }; - /** * Returns the enabled authentication provider configurations for the current * installation. @@ -70,45 +52,4 @@ export default class AuthenticationHelper { ); }); } - - /** - * Returns whether the given path can be accessed with any of the scopes. We - * support scopes in the formats of: - * - * - `/api/namespace.method` - * - `namespace:scope` - * - `scope` - * - * @param path The path to check - * @param scopes The scopes to check - * @returns True if the path can be accessed - */ - public static canAccess = (path: string, scopes: string[]) => { - // strip any query string, this is never used as part of scope matching - path = path.split("?")[0]; - - const resource = path.split("/").pop() ?? ""; - const [namespace, method] = resource.split("."); - - return scopes.some((scope) => { - const [scopeNamespace, scopeMethod] = scope.match(/[:\.]/g) - ? scope.replace("/api/", "").split(/[:\.]/g) - : ["*", scope]; - const isRouteScope = scope.startsWith("/api/"); - - if (isRouteScope) { - return ( - (namespace === scopeNamespace || scopeNamespace === "*") && - (method === scopeMethod || scopeMethod === "*") - ); - } - - return ( - (namespace === scopeNamespace || scopeNamespace === "*") && - (scopeMethod === Scope.Write || - this.methodToScope[method as keyof typeof this.methodToScope] === - scopeMethod) - ); - }); - }; } diff --git a/server/models/oauth/OAuthAuthentication.ts b/server/models/oauth/OAuthAuthentication.ts index 1b70a2af59..8d81d8b03a 100644 --- a/server/models/oauth/OAuthAuthentication.ts +++ b/server/models/oauth/OAuthAuthentication.ts @@ -20,7 +20,7 @@ import User from "@server/models/User"; import ParanoidModel from "@server/models/base/ParanoidModel"; import { SkipChangeset } from "@server/models/decorators/Changeset"; import Fix from "@server/models/decorators/Fix"; -import AuthenticationHelper from "@server/models/helpers/AuthenticationHelper"; +import AuthenticationHelper from "@shared/helpers/AuthenticationHelper"; import { hash } from "@server/utils/crypto"; import OAuthClient from "./OAuthClient"; diff --git a/server/routes/api/attachments/attachments.ts b/server/routes/api/attachments/attachments.ts index 3da6498e79..58da112080 100644 --- a/server/routes/api/attachments/attachments.ts +++ b/server/routes/api/attachments/attachments.ts @@ -135,6 +135,7 @@ router.post( }); const presignedPost = await FileStorage.getPresignedPost( + ctx, key, acl, maxUploadSize, diff --git a/server/routes/api/index.ts b/server/routes/api/index.ts index 51cd199c27..ddf769ca3c 100644 --- a/server/routes/api/index.ts +++ b/server/routes/api/index.ts @@ -6,6 +6,7 @@ import env from "@server/env"; import { NotFoundError } from "@server/errors"; import coalesceBody from "@server/middlewares/coaleseBody"; import requestTracer from "@server/middlewares/requestTracer"; +import { verifyCSRFToken } from "@server/middlewares/csrf"; import { AppState, AppContext } from "@server/types"; import { Hook, PluginManager } from "@server/utils/PluginManager"; import apiKeys from "./apiKeys"; @@ -67,6 +68,7 @@ api.use(requestTracer()); api.use(apiResponse()); api.use(apiErrorHandler()); api.use(editor()); +api.use(verifyCSRFToken()); // Register plugin API routes before others to allow for overrides PluginManager.getHooks(Hook.API).forEach((hook) => diff --git a/server/routes/auth/index.ts b/server/routes/auth/index.ts index 3f6233dbc0..552f5e5a22 100644 --- a/server/routes/auth/index.ts +++ b/server/routes/auth/index.ts @@ -9,6 +9,7 @@ import coalesceBody from "@server/middlewares/coaleseBody"; import { Collection, Team, View } from "@server/models"; import AuthenticationHelper from "@server/models/helpers/AuthenticationHelper"; import { AppState, AppContext, APIContext } from "@server/types"; +import { verifyCSRFToken } from "@server/middlewares/csrf"; const app = new Koa(); const router = new Router(); @@ -77,6 +78,7 @@ router.get("/redirect", authMiddleware(), async (ctx: APIContext) => { app.use(bodyParser()); app.use(coalesceBody()); +app.use(verifyCSRFToken()); app.use(router.routes()); export default app; diff --git a/server/routes/oauth/index.ts b/server/routes/oauth/index.ts index ed0b5f07e0..14c1eee6e2 100644 --- a/server/routes/oauth/index.ts +++ b/server/routes/oauth/index.ts @@ -16,6 +16,7 @@ import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { OAuthInterface } from "@server/utils/oauth/OAuthInterface"; import oauthErrorHandler from "./middlewares/oauthErrorHandler"; import * as T from "./schema"; +import { verifyCSRFToken } from "@server/middlewares/csrf"; const app = new Koa(); const router = new Router(); @@ -127,6 +128,7 @@ router.post( app.use(requestTracer()); app.use(oauthErrorHandler()); app.use(bodyParser()); +app.use(verifyCSRFToken()); app.use(router.routes()); export default app; diff --git a/server/services/web.ts b/server/services/web.ts index 6aa5ad23fb..463b7493a3 100644 --- a/server/services/web.ts +++ b/server/services/web.ts @@ -13,6 +13,7 @@ import env from "@server/env"; import Logger from "@server/logging/Logger"; import Metrics from "@server/logging/Metrics"; import csp from "@server/middlewares/csp"; +import { attachCSRFToken } from "@server/middlewares/csrf"; import ShutdownHelper, { ShutdownOrder } from "@server/utils/ShutdownHelper"; import { initI18n } from "@server/utils/i18n"; import routes from "../routes"; @@ -45,6 +46,7 @@ export default function init(app: Koa = new Koa(), server?: Server) { } app.use(compress()); + app.use(attachCSRFToken()); // Monitor server connections if (server) { diff --git a/server/storage/files/BaseStorage.ts b/server/storage/files/BaseStorage.ts index 17975c56da..e97dd6eed0 100644 --- a/server/storage/files/BaseStorage.ts +++ b/server/storage/files/BaseStorage.ts @@ -7,6 +7,7 @@ import { isBase64Url, isInternalUrl } from "@shared/utils/urls"; import env from "@server/env"; import Logger from "@server/logging/Logger"; import fetch, { chromeUserAgent, RequestInit } from "@server/utils/fetch"; +import { AppContext } from "@server/types"; export default abstract class BaseStorage { /** The default number of seconds until a signed URL expires. */ @@ -15,6 +16,7 @@ export default abstract class BaseStorage { /** * Returns a presigned post for uploading files to the storage provider. * + * @param ctx The request context * @param key The path to store the file at * @param acl The ACL to use * @param maxUploadSize The maximum upload size in bytes @@ -22,6 +24,7 @@ export default abstract class BaseStorage { * @returns The presigned post object to use on the client (TODO: Abstract away from S3) */ public abstract getPresignedPost( + ctx: AppContext, key: string, acl: string, maxUploadSize: number, diff --git a/server/storage/files/LocalStorage.ts b/server/storage/files/LocalStorage.ts index f34f915581..5a59fa0ca5 100644 --- a/server/storage/files/LocalStorage.ts +++ b/server/storage/files/LocalStorage.ts @@ -11,9 +11,12 @@ import env from "@server/env"; import { InternalError, ValidationError } from "@server/errors"; import Logger from "@server/logging/Logger"; import BaseStorage from "./BaseStorage"; +import { CSRF } from "@shared/constants"; +import { AppContext } from "@server/types"; export default class LocalStorage extends BaseStorage { public async getPresignedPost( + ctx: AppContext, key: string, acl: string, maxUploadSize: number, @@ -26,6 +29,7 @@ export default class LocalStorage extends BaseStorage { acl, maxUploadSize: String(maxUploadSize), contentType, + [CSRF.fieldName]: ctx.cookies.get(CSRF.cookieName) || "", }, }); } diff --git a/server/storage/files/S3Storage.ts b/server/storage/files/S3Storage.ts index beba39ab23..adc3e50a11 100644 --- a/server/storage/files/S3Storage.ts +++ b/server/storage/files/S3Storage.ts @@ -20,6 +20,7 @@ import tmp from "tmp"; import env from "@server/env"; import Logger from "@server/logging/Logger"; import BaseStorage from "./BaseStorage"; +import { AppContext } from "@server/types"; export default class S3Storage extends BaseStorage { constructor() { @@ -34,6 +35,7 @@ export default class S3Storage extends BaseStorage { } public async getPresignedPost( + _ctx: AppContext, key: string, acl: string, maxUploadSize: number, diff --git a/server/utils/csrf.ts b/server/utils/csrf.ts new file mode 100644 index 0000000000..bee25bbaf5 --- /dev/null +++ b/server/utils/csrf.ts @@ -0,0 +1,55 @@ +import { randomBytes, createHmac } from "crypto"; +import { safeEqual } from "./crypto"; + +/** + * Generates cryptographically secure random bytes + * + * @param size The number of bytes to generate + * @returns A buffer containing random bytes + */ +export const generateRawToken = (size: number): Buffer => randomBytes(size); + +/** + * Creates an HMAC-SHA256 signature for a token + * + * @param token The token to sign + * @param secret The secret key for signing + * @returns The HMAC signature as a hex string + */ +export const signToken = (token: Buffer, secret: string): string => + createHmac("sha256", secret).update(token).digest("hex"); + +/** + * Bundles a token with its HMAC signature + * + * @param token The raw token + * @param secret The secret key for signing + * @returns A string containing the token and signature separated by a dot + */ +export const bundleToken = (token: Buffer, secret: string): string => { + const sig = signToken(token, secret); + return `${token.toString("hex")}.${sig}`; +}; + +/** + * Unbundles and verifies a token with its HMAC signature + * + * @param bundled The bundled token string + * @param secret The secret key for verification + * @returns An object indicating validity and the raw token if valid + */ +export const unbundleToken = ( + bundled: string, + secret: string +): { valid: boolean; raw?: Buffer } => { + const [hex, sig] = bundled.split("."); + if (!hex || !sig) { + return { valid: false }; + } + + const token = Buffer.from(hex, "hex"); + const expected = signToken(token, secret); + + const valid = safeEqual(sig, expected); + return { valid, raw: valid ? token : undefined }; +}; diff --git a/shared/constants.ts b/shared/constants.ts index 8ebc461424..6c63f9c8bc 100644 --- a/shared/constants.ts +++ b/shared/constants.ts @@ -15,6 +15,12 @@ export const Pagination = { sidebarLimit: 10, }; +export const CSRF = { + cookieName: "csrfToken", + headerName: "x-csrf-token", + fieldName: "_csrf", +}; + export const TeamPreferenceDefaults: TeamPreferences = { [TeamPreference.SeamlessEdit]: true, [TeamPreference.ViewersCanExport]: true, diff --git a/server/models/helpers/AuthenticationHelper.test.ts b/shared/helpers/AuthenticationHelper.test.ts similarity index 100% rename from server/models/helpers/AuthenticationHelper.test.ts rename to shared/helpers/AuthenticationHelper.test.ts diff --git a/shared/helpers/AuthenticationHelper.ts b/shared/helpers/AuthenticationHelper.ts new file mode 100644 index 0000000000..72ef36beba --- /dev/null +++ b/shared/helpers/AuthenticationHelper.ts @@ -0,0 +1,62 @@ +import { Scope } from "../types"; + +export default class AuthenticationHelper { + /** + * The mapping of method names to their scopes, anything not listed here + * defaults to `Scope.Write`. + * + * - `documents.create` -> `Scope.Create` + * - `documents.list` -> `Scope.Read` + * - `documents.info` -> `Scope.Read` + */ + private static methodToScope = { + create: Scope.Create, + config: Scope.Read, + list: Scope.Read, + info: Scope.Read, + search: Scope.Read, + documents: Scope.Read, + export: Scope.Read, + }; + + /** + * Returns whether the given path can be accessed with any of the scopes. We + * support scopes in the formats of: + * + * - `/api/namespace.method` + * - `namespace:scope` + * - `scope` + * + * @param path The path to check + * @param scopes The scopes to check + * @returns True if the path can be accessed + */ + public static canAccess = (path: string, scopes: string[]) => { + // strip any query string, this is never used as part of scope matching + path = path.split("?")[0]; + + const resource = path.split("/").pop() ?? ""; + const [namespace, method] = resource.split("."); + + return scopes.some((scope) => { + const [scopeNamespace, scopeMethod] = scope.match(/[:\.]/g) + ? scope.replace("/api/", "").split(/[:\.]/g) + : ["*", scope]; + const isRouteScope = scope.startsWith("/api/"); + + if (isRouteScope) { + return ( + (namespace === scopeNamespace || scopeNamespace === "*") && + (method === scopeMethod || scopeMethod === "*") + ); + } + + return ( + (namespace === scopeNamespace || scopeNamespace === "*") && + (scopeMethod === Scope.Write || + this.methodToScope[method as keyof typeof this.methodToScope] === + scopeMethod) + ); + }); + }; +}