diff --git a/server/middlewares/csrf.test.ts b/server/middlewares/csrf.test.ts new file mode 100644 index 0000000000..478e7c8c1c --- /dev/null +++ b/server/middlewares/csrf.test.ts @@ -0,0 +1,75 @@ +import Koa from "koa"; +import { CSRF } from "@shared/constants"; +import env from "@server/env"; +import TestServer from "@server/test/TestServer"; +import { + bundleToken, + clearCSRFCookie, + generateRawToken, +} from "@server/utils/csrf"; +import { attachCSRFToken } from "./csrf"; + +async function getSetCookie(cookie?: string) { + const app = new Koa(); + app.use(attachCSRFToken()); + app.use((ctx) => { + ctx.body = "ok"; + }); + + const server = new TestServer(app); + try { + const res = await server.get("/", { + headers: cookie ? { Cookie: cookie } : {}, + }); + return res.headers.get("set-cookie") ?? ""; + } finally { + server.close(); + } +} + +describe("attachCSRFToken", () => { + it("should set a token when no cookie is present", async () => { + const setCookie = await getSetCookie(); + expect(setCookie).toContain(`${CSRF.cookieName}=`); + }); + + it("should keep a valid existing token", async () => { + const token = bundleToken(generateRawToken(16), env.SECRET_KEY); + const setCookie = await getSetCookie(`${CSRF.cookieName}=${token}`); + expect(setCookie).toEqual(""); + }); + + it("should replace a malformed existing token", async () => { + const token = `${generateRawToken(16).toString("hex")}.${"é".repeat(64)}`; + const setCookie = await getSetCookie(`${CSRF.cookieName}=${token}`); + expect(setCookie).toContain(`${CSRF.cookieName}=`); + expect(setCookie).not.toContain(token); + }); + + it("should replace an invalid existing token", async () => { + const token = bundleToken(generateRawToken(16), "wrong-secret"); + const setCookie = await getSetCookie(`${CSRF.cookieName}=${token}`); + expect(setCookie).toContain(`${CSRF.cookieName}=`); + expect(setCookie).not.toContain(token); + }); +}); + +describe("clearCSRFCookie", () => { + it("should expire the cookie so a fresh token is minted next request", async () => { + const app = new Koa(); + app.use((ctx) => { + clearCSRFCookie(ctx); + ctx.body = "ok"; + }); + + const server = new TestServer(app); + try { + const res = await server.get("/"); + const setCookie = res.headers.get("set-cookie") ?? ""; + expect(setCookie).toContain(`${CSRF.cookieName}=;`); + expect(setCookie).toContain("expires=Thu, 01 Jan 1970"); + } finally { + server.close(); + } + }); +}); diff --git a/server/middlewares/csrf.ts b/server/middlewares/csrf.ts index 39a114b486..97b4a956a7 100644 --- a/server/middlewares/csrf.ts +++ b/server/middlewares/csrf.ts @@ -16,12 +16,20 @@ import { CSRFError } from "@server/errors"; import { parseAuthentication } from "./authentication"; /** - * Middleware that generates and attaches CSRF tokens for safe methods + * Middleware that generates and attaches CSRF tokens for safe methods. An + * existing valid token is kept, so that concurrent requests do not replace the + * cookie while a mutating request is in flight. */ export function attachCSRFToken() { return async function attachCSRFTokenMiddleware(ctx: AppContext, next: Next) { // Only attach tokens for safe methods that don't mutate state if (["GET", "HEAD", "OPTIONS"].includes(ctx.method)) { + const existing = getTokenFromCookie(ctx); + if (existing && unbundleToken(existing, env.SECRET_KEY).valid) { + await next(); + return; + } + const raw = generateRawToken(16); const bundled = bundleToken(raw, env.SECRET_KEY); diff --git a/server/routes/api/auth/auth.ts b/server/routes/api/auth/auth.ts index 8eec3bffe3..0d0571de17 100644 --- a/server/routes/api/auth/auth.ts +++ b/server/routes/api/auth/auth.ts @@ -21,6 +21,7 @@ import ValidateSSOAccessTask from "@server/queues/tasks/ValidateSSOAccessTask"; import type { APIContext } from "@server/types"; import { AuthenticationType } from "@server/types"; import { getSessionsInCookie } from "@server/utils/authentication"; +import { clearCSRFCookie } from "@server/utils/csrf"; import RateLimiter from "@server/utils/RateLimiter"; import type * as T from "./schema"; @@ -207,6 +208,7 @@ router.post( sameSite: "lax", expires: subMinutes(new Date(), 1), }); + clearCSRFCookie(ctx); ctx.body = { success: true, diff --git a/server/routes/auth/index.ts b/server/routes/auth/index.ts index 1012eb59d6..089badbad3 100644 --- a/server/routes/auth/index.ts +++ b/server/routes/auth/index.ts @@ -11,6 +11,7 @@ import AuthenticationHelper from "@server/models/helpers/AuthenticationHelper"; import type { AppState, AppContext, APIContext } from "@server/types"; import { AuthenticationType } from "@server/types"; import { verifyCSRFToken } from "@server/middlewares/csrf"; +import { clearCSRFCookie } from "@server/utils/csrf"; import { getJWTPayload } from "@server/utils/jwt"; const app = new Koa(); @@ -56,6 +57,7 @@ router.get( sameSite: "lax", expires, }); + clearCSRFCookie(ctx); const [team, collection, view] = await Promise.all([ Team.findByPk(user.teamId), Collection.findFirstCollectionForUser(user), diff --git a/server/utils/authentication.ts b/server/utils/authentication.ts index 5e0b99e608..4b12729c0a 100644 --- a/server/utils/authentication.ts +++ b/server/utils/authentication.ts @@ -11,6 +11,7 @@ import Logger from "@server/logging/Logger"; import { Event, Collection, Team, View } from "@server/models"; import type { APIContext, AuthenticationResult } from "@server/types"; import { AuthenticationType } from "@server/types"; +import { clearCSRFCookie } from "./csrf"; /** * Parse and return the details from the "sessions" cookie in the request, if @@ -188,6 +189,7 @@ export async function signIn( sameSite: "lax", expires, }); + clearCSRFCookie(ctx); const defaultCollectionId = team.defaultCollectionId; diff --git a/server/utils/crypto.ts b/server/utils/crypto.ts index 4be6947c3c..8e5387994a 100644 --- a/server/utils/crypto.ts +++ b/server/utils/crypto.ts @@ -11,11 +11,14 @@ export function safeEqual(a?: string | null, b?: string | null) { if (!a || !b) { return false; } - if (a.length !== b.length) { + + const bufA = Buffer.from(a); + const bufB = Buffer.from(b); + if (bufA.length !== bufB.length) { return false; } - return crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b)); + return crypto.timingSafeEqual(bufA, bufB); } /** diff --git a/server/utils/csrf.ts b/server/utils/csrf.ts index d9f9d66175..2d32117085 100644 --- a/server/utils/csrf.ts +++ b/server/utils/csrf.ts @@ -25,6 +25,22 @@ export const getTokenFromCookie = ( ctx: Pick ): string | undefined => ctx.cookies.get(getCookieName(ctx)); +/** + * Expires the CSRF cookie so that the next safe request mints a fresh token. + * Call this when the session changes hands, such as on sign in and sign out. + * + * @param ctx the request context. + */ +export const clearCSRFCookie = ( + ctx: Pick +): void => { + ctx.cookies.set(getCookieName(ctx), null, { + httpOnly: false, + sameSite: "lax", + secure: ctx.request.secure, + }); +}; + /** * Generates cryptographically secure random bytes *