diff --git a/src/__tests__/AuthMiddleware.test.ts b/src/__tests__/AuthMiddleware.test.ts new file mode 100644 index 00000000..980f397d --- /dev/null +++ b/src/__tests__/AuthMiddleware.test.ts @@ -0,0 +1,96 @@ +/** + * #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.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"); + + 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("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"); + 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..b574af4e 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; } /** @@ -100,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; }