Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 96 additions & 0 deletions src/__tests__/AuthMiddleware.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
34 changes: 30 additions & 4 deletions src/mcp/auth/AuthMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand Down Expand Up @@ -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;
}
Expand Down
Loading