Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(mcp): don't let abandoned responses lock out a valid token
Elian Doran0e103ce0315a
diff --git a/apps/server/src/routes/mcp.spec.ts b/apps/server/src/routes/mcp.spec.tsindex 85bfe8f1f8..0ce56e9fb4 100644--- a/apps/server/src/routes/mcp.spec.ts+++ b/apps/server/src/routes/mcp.spec.ts@@ -1,6 +1,10 @@-import { describe, expect, it } from "vitest";+import { options as optionService } from "@triliumnext/core";+import express from "express";+import supertest from "supertest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { resolveMcpAccess } from "./mcp.js";+import etapiTokenService from "../services/etapi_tokens.js";+import { createMcpRateLimiter, resolveMcpAccess } from "./mcp.js";describe("resolveMcpAccess", () => {it("denies everything with 403 while MCP is disabled, token or not", () => {@@ -20,3 +24,86 @@ describe("resolveMcpAccess", () => {expect(decision.type === "deny" && decision.error).toContain("Options > ETAPI");});});++describe("createMcpRateLimiter", () => {+ // The limiter reads both halves of the access decision to tell a failed authentication+ // from anything else, so both singletons are stubbed rather than a live becca booted.+ beforeEach(() => vi.spyOn(optionService, "getOptionOrNull").mockReturnValue("true"));+ afterEach(() => vi.restoreAllMocks());++ it("never spends the budget on an authenticated client, even when its responses are abandoned", async () => {+ // The leak this guards against: an MCP client drops its standing GET stream on every+ // reconnect, so the response never reaches `finish`. A limiter that counts the hit up+ // front and refunds it on `finish` never refunds these, and locks the valid token out+ // once 10 have piled up.+ vi.spyOn(etapiTokenService, "isValidAuthHeader").mockReturnValue(true);+ const { app, handled } = buildApp((_req, res) => res.socket?.destroy());++ const statuses = await sendRepeatedly(app, 15);++ expect(handled()).toBe(15);+ expect(statuses).toEqual(Array(15).fill(ABORTED));+ });++ it("caps failed authentications and keeps rejecting past the limit", async () => {+ vi.spyOn(etapiTokenService, "isValidAuthHeader").mockReturnValue(false);+ const { app, handled } = buildApp((_req, res) => { res.status(401).json({ error: "nope" }); });++ const statuses = await sendRepeatedly(app, 12);++ expect(handled()).toBe(10); // the configured max+ expect(statuses).toEqual([...Array(10).fill(401), 429, 429]);+ });++ it("does not spend the budget while MCP is disabled, since nothing there is an attempt at the credential", async () => {+ vi.spyOn(optionService, "getOptionOrNull").mockReturnValue("false");+ vi.spyOn(etapiTokenService, "isValidAuthHeader").mockReturnValue(false);+ const { app } = buildApp((_req, res) => { res.status(403).json({ error: "off" }); });++ const statuses = await sendRepeatedly(app, 12);++ expect(statuses).toEqual(Array(12).fill(403));+ });+});++const ABORTED = "aborted";++/** An app whose only route counts how many requests made it past the limiter. */+function buildApp(handler: express.RequestHandler) {+ let handled = 0;++ const app = express();+ app.get("/mcp", createMcpRateLimiter(), (req, res, next) => {+ handled++;+ handler(req, res, next);+ });++ return { app, handled: () => handled };+}++async function sendRepeatedly(app: express.Application, count: number) {+ const statuses: (number | typeof ABORTED)[] = [];++ // Sequentially: the limiter's budget is spent in request order, which is what's asserted.+ for (let i = 0; i < count; i++) {+ statuses.push(await sendAndTolerateAbort(app));+ }++ return statuses;+}++/**+ * A destroyed socket surfaces to the client as ECONNRESET rather than as a response — the+ * point of the first test — so that one rejection is an expected outcome. Anything else is+ * a broken test, and is rethrown rather than quietly recorded as an abort.+ */+async function sendAndTolerateAbort(app: express.Application): Promise<number | typeof ABORTED> {+ try {+ return (await supertest(app).get("/mcp")).status;+ } catch (e) {+ if ((e as NodeJS.ErrnoException)?.code !== "ECONNRESET") {+ throw e;+ }+ return ABORTED;+ }+}diff --git a/apps/server/src/routes/mcp.ts b/apps/server/src/routes/mcp.tsindex 74451ad9b2..5084626e03 100644--- a/apps/server/src/routes/mcp.ts+++ b/apps/server/src/routes/mcp.ts@@ -17,21 +17,7 @@ import etapiTokenService from "../services/etapi_tokens.js";import { createMcpServer } from "../services/mcp/mcp_server.js";export function register(app: express.Application) {- // Token guessing is unbounded once the endpoint is reachable off-loopback, so cap- // failed authentications per IP. Mirrors the login limiter.- //- // Only a 401 counts. `skipSuccessfulRequests` alone would spend the budget on every- // 4xx/5xx — a 403 while MCP is disabled, a transport-level 406/415, a 500 — none of- // which is an attempt at the credential. Since the limiter necessarily runs ahead of- // mcpGuard, letting those count would let an unauthenticated caller exhaust the budget- // deliberately and lock out a valid token for the whole window. The budget is per-IP,- // and a Docker port mapping or a reverse proxy collapses every client onto one address.- const mcpRateLimiter = rateLimit({- windowMs: 15 * 60 * 1000,- max: 10,- skipSuccessfulRequests: true,- requestWasSuccessful: (_req, res) => res.statusCode !== 401- });+ const mcpRateLimiter = createMcpRateLimiter();app.post("/mcp", mcpRateLimiter, mcpGuard, handleMcpRequest);app.get("/mcp", mcpRateLimiter, mcpGuard, handleMcpRequest);@@ -40,6 +26,50 @@ export function register(app: express.Application) {getLog().info("MCP server registered at /mcp (ETAPI token required)");}+/**+ * Caps failed authentications per IP — token guessing is unbounded once the endpoint is+ * reachable off-loopback. Mirrors the login limiter.+ *+ * A request costs budget only if it is one the guard behind this would answer 401 to, and+ * the cost is never refunded: `skip` decides before anything is recorded. The refund route+ * that express-rate-limit offers for the same goal — `skipSuccessfulRequests`, which+ * records the hit up front and gives it back from a `res.on("finish")` handler — cannot be+ * used here, because a response that never finishes never gets its hit back. Abandoned+ * responses are routine on this endpoint: an MCP client drops its standing `GET /mcp` event+ * stream on every reconnect, and cancels in-flight tool calls on timeout or user interrupt.+ * Ten of those inside the window — a handful of agent restarts — and the limiter answers+ * 429 to a perfectly valid token for the rest of it, which reads to the user as the MCP+ * connection dropping.+ *+ * A 401 always completes, so nothing is abandoned on the path that does spend budget.+ *+ * The corollary is that a valid token is served even from an address that has exhausted its+ * budget. That is the intent, not a hole: the budget is per-IP, and a Docker port mapping,+ * a NAT or a reverse proxy collapses every client onto one address, so anything else lets+ * one bad client lock out the one that actually holds a credential. Guessing is still+ * throttled — that is what the budget is for — and throttling a request that already+ * presents the right token protects nothing.+ */+export function createMcpRateLimiter() {+ return rateLimit({+ windowMs: 15 * 60 * 1000,+ max: 10,+ skip: (req) => {+ const decision = readMcpAccess(req);+ return decision.type !== "deny" || decision.status !== 401;+ }+ });+}++function readMcpAccess(req: express.Request): McpAccessDecision {+ return resolveMcpAccess({+ mcpEnabled: optionService.getOptionOrNull("mcpEnabled") === "true",+ // Only the Authorization header authenticates — never a session cookie. A cookie would+ // make `/mcp` CSRF-able by any page the logged-in user visits, with full tool access.+ hasValidToken: etapiTokenService.isValidAuthHeader(req.headers.authorization)+ });+}+export type McpAccessDecision =| { type: "allow" }| { type: "deny"; status: number; error: string };@@ -82,12 +112,7 @@ export function resolveMcpAccess(opts: {}function mcpGuard(req: express.Request, res: express.Response, next: express.NextFunction) {- const decision = resolveMcpAccess({- mcpEnabled: optionService.getOptionOrNull("mcpEnabled") === "true",- // Only the Authorization header authenticates — never a session cookie. A cookie would- // make `/mcp` CSRF-able by any page the logged-in user visits, with full tool access.- hasValidToken: etapiTokenService.isValidAuthHeader(req.headers.authorization)- });+ const decision = readMcpAccess(req);if (decision.type === "deny") {res.status(decision.status).json({ error: decision.error });diff --git a/apps/server/src/routes/transport.spec.ts b/apps/server/src/routes/transport.spec.tsindex df3f6b8c2d..1177ec8c90 100644--- a/apps/server/src/routes/transport.spec.ts+++ b/apps/server/src/routes/transport.spec.ts@@ -265,11 +265,12 @@ describe("Route transport & middleware", () => {cls.init(() => optionService.setOption("mcpEnabled", "true"));- // Nothing above was an authentication failure, so a valid token must still be- // served. If every 4xx/5xx counts, this is a 429 — and since the limiter runs- // ahead of the guard, an unauthenticated caller can spend the budget on purpose- // and lock out a legitimate client, or everyone sharing a NAT or Docker bridge- // address, for fifteen minutes.+ // Nothing above was an authentication failure, so none of it may cost budget —+ // and a valid token is skipped by the limiter outright in any case. If either+ // rule slips, this is a 429: the limiter runs ahead of the guard, so an+ // unauthenticated caller could otherwise spend the budget on purpose and lock+ // out a legitimate client, or everyone sharing a NAT or Docker bridge address,+ // for fifteen minutes.const res = await mcpPostFrom("203.0.113.1").set("Authorization", `Bearer ${authToken}`).send(initializeRequest);@@ -285,12 +286,20 @@ describe("Route transport & middleware", () => {}// Repeated bad tokens are what the limiter exists for: once the budget is gone- // the IP is cut off, valid token or not. Guards against "fixing" the above by+ // the guessing stops being answered. Guards against "fixing" the above by// dropping the limiter.+ await mcpPostFrom("203.0.113.2")+ .set("Authorization", "Bearer still_not_a_real_token")+ .send(initializeRequest)+ .expect(429);++ // The client that does hold a token is served throughout: it never spends+ // budget, so it cannot be locked out by someone else's guessing from the same+ // address — which is everyone, behind a NAT, a Docker bridge or a proxy.const res = await mcpPostFrom("203.0.113.2").set("Authorization", `Bearer ${authToken}`).send(initializeRequest);- expect(res.status).toBe(429);+ expect(res.status).toBe(200);});});});