From b510b0a777229a058bec8e03cd26b22a894abb05 Mon Sep 17 00:00:00 2001 From: Quorafind Date: Sun, 29 Nov 2026 10:23:24 +0800 Subject: [PATCH 1/2] fix(mcp): compare the MCP auth token in constant time validateRequest compared the bearer token with ===, which returns at the first differing character, so response times could reveal how much of a guessed token is right (CWE-208). Compare with a loop whose time depends only on the lengths. It is plain JavaScript, so nothing pulls in Node's crypto module. Refs #575. --- src/__tests__/AuthMiddleware.test.ts | 57 ++++++++++++++++++++++++++++ src/mcp/auth/AuthMiddleware.ts | 18 ++++++++- 2 files changed, 74 insertions(+), 1 deletion(-) create mode 100644 src/__tests__/AuthMiddleware.test.ts diff --git a/src/__tests__/AuthMiddleware.test.ts b/src/__tests__/AuthMiddleware.test.ts new file mode 100644 index 00000000..9047961d --- /dev/null +++ b/src/__tests__/AuthMiddleware.test.ts @@ -0,0 +1,57 @@ +/** + * #575: the MCP server must compare bearer tokens in constant time. + */ +import type { IncomingMessage } from "http"; +import { AuthMiddleware } from "@/mcp/auth/AuthMiddleware"; + +function request(authorization?: string): IncomingMessage { + return { headers: { authorization } } as unknown as IncomingMessage; +} + +describe("AuthMiddleware.constantTimeEquals", () => { + it("accepts equal strings", () => { + expect(AuthMiddleware.constantTimeEquals("abc123", "abc123")).toBe(true); + expect(AuthMiddleware.constantTimeEquals("", "")).toBe(true); + }); + + it("rejects strings that differ anywhere", () => { + expect(AuthMiddleware.constantTimeEquals("xbc123", "abc123")).toBe(false); + expect(AuthMiddleware.constantTimeEquals("abc12x", "abc123")).toBe(false); + }); + + it("rejects prefixes and extensions of the token", () => { + expect(AuthMiddleware.constantTimeEquals("abc", "abc123")).toBe(false); + expect(AuthMiddleware.constantTimeEquals("abc1234", "abc123")).toBe(false); + expect(AuthMiddleware.constantTimeEquals("", "abc123")).toBe(false); + }); + + it("does not treat a missing character as a NUL character", () => { + expect(AuthMiddleware.constantTimeEquals("abc\0", "abc")).toBe(false); + }); +}); + +describe("AuthMiddleware.validateRequest", () => { + const auth = new AuthMiddleware("secret-token"); + + it("accepts the right bearer token, with or without an app id", () => { + expect(auth.validateRequest(request("Bearer secret-token"))).toBe(true); + expect(auth.validateRequest(request("Bearer secret-token+my-app"))).toBe( + true, + ); + }); + + it("rejects wrong, partial or missing tokens", () => { + expect(auth.validateRequest(request("Bearer secret-tokem"))).toBe(false); + expect(auth.validateRequest(request("Bearer secret"))).toBe(false); + expect(auth.validateRequest(request("Bearer "))).toBe(false); + expect(auth.validateRequest(request("Basic secret-token"))).toBe(false); + expect(auth.validateRequest(request())).toBe(false); + }); + + it("checks against the updated token", () => { + const updated = new AuthMiddleware("old-token"); + updated.updateToken("new-token"); + expect(updated.validateRequest(request("Bearer new-token"))).toBe(true); + expect(updated.validateRequest(request("Bearer old-token"))).toBe(false); + }); +}); diff --git a/src/mcp/auth/AuthMiddleware.ts b/src/mcp/auth/AuthMiddleware.ts index 7c79ef55..660cf874 100644 --- a/src/mcp/auth/AuthMiddleware.ts +++ b/src/mcp/auth/AuthMiddleware.ts @@ -19,7 +19,23 @@ export class AuthMiddleware { if (!parsed) { return false; } - return parsed.token === this.authToken; + return AuthMiddleware.constantTimeEquals(parsed.token, this.authToken); + } + + /** + * Compare two strings in time that depends only on their lengths, not on + * the position of the first differing character. A plain `===` returns as + * soon as a character differs, so response times would reveal how much of a + * guessed token is right (CWE-208). + */ + static constantTimeEquals(a: string, b: string): boolean { + const length = Math.max(a.length, b.length); + let diff = a.length ^ b.length; + for (let i = 0; i < length; i++) { + // charCodeAt past the end is NaN; `| 0` turns it into 0. + diff |= (a.charCodeAt(i) | 0) ^ (b.charCodeAt(i) | 0); + } + return diff === 0; } /** From c82c988f1d1cc545eda3ff56f840d6f5c4a84ed5 Mon Sep 17 00:00:00 2001 From: Quorafind Date: Sun, 29 Nov 2026 10:23:49 +0800 Subject: [PATCH 2/2] fix(mcp): generate MCP auth tokens with crypto.getRandomValues generateToken picked characters with Math.random, whose output is predictable and not meant for secrets (CWE-338). Draw bytes from the Web Crypto random number generator instead, and skip bytes that would bias the character choice. Web Crypto is available on desktop and mobile, so no Node module is needed. --- src/__tests__/AuthMiddleware.test.ts | 39 ++++++++++++++++++++++++++++ src/mcp/auth/AuthMiddleware.ts | 16 +++++++++--- 2 files changed, 52 insertions(+), 3 deletions(-) diff --git a/src/__tests__/AuthMiddleware.test.ts b/src/__tests__/AuthMiddleware.test.ts index 9047961d..980f397d 100644 --- a/src/__tests__/AuthMiddleware.test.ts +++ b/src/__tests__/AuthMiddleware.test.ts @@ -30,6 +30,34 @@ describe("AuthMiddleware.constantTimeEquals", () => { }); }); +describe("AuthMiddleware.generateToken", () => { + it("returns 32 alphanumeric characters", () => { + for (let i = 0; i < 50; i++) { + expect(AuthMiddleware.generateToken()).toMatch(/^[A-Za-z0-9]{32}$/); + } + }); + + it("uses the Web Crypto random number generator, not Math.random", () => { + const getRandomValues = jest.spyOn(window.crypto, "getRandomValues"); + const mathRandom = jest.spyOn(Math, "random"); + try { + AuthMiddleware.generateToken(); + expect(getRandomValues).toHaveBeenCalled(); + expect(mathRandom).not.toHaveBeenCalled(); + } finally { + getRandomValues.mockRestore(); + mathRandom.mockRestore(); + } + }); + + it("does not repeat tokens", () => { + const tokens = new Set( + Array.from({ length: 200 }, () => AuthMiddleware.generateToken()), + ); + expect(tokens.size).toBe(200); + }); +}); + describe("AuthMiddleware.validateRequest", () => { const auth = new AuthMiddleware("secret-token"); @@ -48,6 +76,17 @@ describe("AuthMiddleware.validateRequest", () => { expect(auth.validateRequest(request())).toBe(false); }); + it("rejects a token of the right length with one wrong character", () => { + const token = AuthMiddleware.generateToken(); + const last = token.endsWith("A") ? "B" : "A"; + const almost = token.slice(0, -1) + last; + const generated = new AuthMiddleware(token); + expect(generated.validateRequest(request(`Bearer ${token}`))).toBe(true); + expect(generated.validateRequest(request(`Bearer ${almost}`))).toBe( + false, + ); + }); + it("checks against the updated token", () => { const updated = new AuthMiddleware("old-token"); updated.updateToken("new-token"); diff --git a/src/mcp/auth/AuthMiddleware.ts b/src/mcp/auth/AuthMiddleware.ts index 660cf874..b574af4e 100644 --- a/src/mcp/auth/AuthMiddleware.ts +++ b/src/mcp/auth/AuthMiddleware.ts @@ -116,14 +116,24 @@ export class AuthMiddleware { } /** - * Generate a random token + * Generate a random 32-character alphanumeric token from the Web Crypto + * random number generator (Math.random is predictable). */ static generateToken(): string { const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + const tokenLength = 32; + // Skip bytes at or above the largest multiple of chars.length (248), + // so that every character is equally likely. + const limit = 256 - (256 % chars.length); let token = ""; - for (let i = 0; i < 32; i++) { - token += chars.charAt(Math.floor(Math.random() * chars.length)); + while (token.length < tokenLength) { + const bytes = window.crypto.getRandomValues(new Uint8Array(64)); + for (const byte of bytes) { + if (byte < limit && token.length < tokenLength) { + token += chars[byte % chars.length]; + } + } } return token; }