fix: Keep existing CSRF token across concurrent requests (#14411)

* fix: Keep existing CSRF token across concurrent requests

* fix: Compare byte length in safeEqual so malformed input cannot throw
This commit is contained in:
Tom Moor authored and GitHub committed 2026-10-29 18:47:54 -04:00
1 parent 5e880ca835
commit 3fafd2a7ea
7 files changed
+111 -3

No files matched your search

+75
View File
@@ -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();
}
});
});
+9 -1
View File
@@ -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);
+2
View File
@@ -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,
+2
View File
@@ -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<AppState, AppContext>();
@@ -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),
+2
View File
@@ -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;
+5 -2
View File
@@ -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);
}
/**
+16
View File
@@ -25,6 +25,22 @@ export const getTokenFromCookie = (
ctx: Pick<Context, "cookies" | "request">
): 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<Context, "cookies" | "request">
): void => {
ctx.cookies.set(getCookieName(ctx), null, {
httpOnly: false,
sameSite: "lax",
secure: ctx.request.secure,
});
};
/**
* Generates cryptographically secure random bytes
*