Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
mcp: fix auth (#2659)
Thibault Le Ouay00da67be4e96
diff --git a/apps/server/src/routes/mcp/handler.test.ts b/apps/server/src/routes/mcp/handler.test.tsindex b6660edd9..949d0c3fa 100644--- a/apps/server/src/routes/mcp/handler.test.ts+++ b/apps/server/src/routes/mcp/handler.test.ts@@ -2,6 +2,7 @@ import { sentry } from "@hono/sentry";import { Events } from "@openstatus/analytics";import { db, desc, eq } from "@openstatus/db";import { auditLog, page, statusReport } from "@openstatus/db/src/schema";+import { resourceMetadataUrl } from "@openstatus/services/oauth";import { SEEDED_WORKSPACE_TEAM_ID } from "@openstatus/services/test/fixtures";import type { MockFn } from "@openstatus/test-utils";import { expect } from "@std/expect";@@ -16,6 +17,7 @@ import { Hono } from "hono";import { requestId } from "hono/request-id";import { handleError } from "../../libs/errors";+import { oauthConfigFromEnv } from "../oauth/config";import { mcpRoute } from "./index";/**@@ -78,34 +80,28 @@ async function readJsonRpc(}describe("MCP transport", () => {- test("serves the public documents without a key", async () => {+ test("a request without a key is a 401 that starts OAuth discovery", async () => {const app = makeApp();- const res = await app.fetch(jsonRpc({ method: "resources/list" }, false));- expect(res.status).toBe(200);- const body = await readJsonRpc(res);- const resources = (body.result as { resources: { uri: string }[] })- .resources;- expect(resources.length).toBeGreaterThan(0);- });-- test("registers no tools without a key", async () => {- const app = makeApp();- const res = await app.fetch(jsonRpc({ method: "tools/list" }, false));- // No tool handler is registered on the anonymous server, so the method- // itself is absent — an empty tool list would still be a workspace-shaped- // response to an unauthenticated caller.- const body = await readJsonRpc(res);- expect(body.result).toBeUndefined();- expect(body.error?.code).toBe(-32601);+ const res = await app.fetch(jsonRpc({ method: "initialize" }, false));+ expect(res.status).toBe(401);+ // RFC 9728: the challenge points at the protected-resource metadata, which+ // is how an MCP client finds the authorization server. Without it the+ // client has a dead endpoint rather than a protected one.+ const challenge = res.headers.get("WWW-Authenticate") ?? "";+ expect(challenge.startsWith("Bearer ")).toBe(true);+ expect(challenge).toContain(+ `resource_metadata="${resourceMetadataUrl(oauthConfigFromEnv().issuer)}"`,+ );});- test("a present but empty key is a 401, not the public surface", async () => {+ test("a present but empty key is a 401 too", async () => {const app = makeApp();const res = await app.fetch(jsonRpc({ method: "resources/list" }, ""));expect(res.status).toBe(401);+ expect(res.headers.get("WWW-Authenticate")).toBeTruthy();});- test("resources/list is also served to an authenticated key", async () => {+ test("resources/list serves the public documents to an authenticated key", async () => {const app = makeApp();const res = await app.fetch(jsonRpc({ method: "resources/list" }));expect(res.status).toBe(200);@@ -282,23 +278,14 @@ describe("MCP transport — analytics", () => {expect(event?.authenticated).toBe(true);});- test("an anonymous call is tracked without a profile", async () => {+ test("a rejected request is not tracked", async () => {const app = makeApp();await app.fetch(jsonRpc({ method: "resources/list" }, false));await flushTracking();- const identify = analyticsSpies.setupAnalytics.mock.calls[0]?.[0] as Record<- string,- unknown- >;- expect(identify?.userId).toBeUndefined();-- const event = analyticsSpies.track.mock.calls[0]?.[0] as Record<- string,- unknown- >;- expect(event?.method).toBe("resources/list");- expect(event?.authenticated).toBe(false);+ // `authMiddleware` throws before the handler runs, so unauthenticated+ // traffic never reaches the tracker: the event counts real MCP calls.+ expect(analyticsSpies.track.mock.calls.length).toBe(0);});});diff --git a/apps/server/src/routes/mcp/index.ts b/apps/server/src/routes/mcp/index.tsindex 75209302c..f8104a88a 100644--- a/apps/server/src/routes/mcp/index.ts+++ b/apps/server/src/routes/mcp/index.ts@@ -4,14 +4,14 @@ import { Events, setupAnalytics } from "@openstatus/analytics";import type { Workspace } from "@openstatus/db/src/schema";import { resourceMetadataUrl } from "@openstatus/services/oauth";import { Hono } from "hono";-import type { Context, Next } from "hono";+import type { Context } from "hono";import { handleError } from "../../libs/errors";import { authMiddleware } from "../../libs/middlewares/auth";import type { Variables } from "../../types";import { oauthConfigFromEnv } from "../oauth/config";import { toServiceCtx } from "./adapter";-import { createMcpServer, createPublicMcpServer } from "./server";+import { createMcpServer } from "./server";const logger = getLogger("api-server");@@ -33,31 +33,16 @@ mcpRoute.onError((err, c) => {});/**- * An MCP client `initialize`s before it has a credential, and a handshake that- * 401s reads as an unreachable server rather than a protected one. A missing- * key drops the request to the public surface (documents only, no tools); a- * key that is present but invalid is still a 401, so a misconfigured client- * gets told so instead of silently losing its workspace.+ * `/mcp` is an OAuth protected resource (RFC 9728), so every request needs a+ * credential and one without gets a 401 carrying `WWW-Authenticate`.+ *+ * That 401 is not a failure mode, it is the discovery mechanism: an MCP client+ * `initialize`s without a credential precisely so the challenge tells it where+ * the authorization server lives. Answering the handshake anonymously instead+ * leaves such a client permanently connected but unauthenticated — it never+ * learns OAuth is on offer, and never sees a tool.*/-async function optionalAuthMiddleware(- c: Context<{ Variables: Variables }, "/*">,- next: Next,-) {- // `=== undefined` rather than a truthiness check: a client that sends the- // header with an empty value is misconfigured, not anonymous, and should be- // told so instead of silently dropping to the public surface.- // A bearer token is a credential too; it must be validated, never treated- // as anonymous.- if (- c.req.header("x-openstatus-key") === undefined &&- c.req.header("authorization") === undefined- ) {- return next();- }- return authMiddleware(c, next);-}--mcpRoute.use("*", optionalAuthMiddleware);+mcpRoute.use("*", authMiddleware);/*** The JSON-RPC calls carried by a request body, as OpenPanel event properties.@@ -87,25 +72,23 @@ function rpcCalls(body: unknown): Record<string, unknown>[] {* Emitted before execution: this measures calls, not successes, so a tool that* throws still shows up in the volume.*- * Authenticated requests reuse the `api_<workspaceId>` profile the RPC tracking- * interceptor writes to — one identity per workspace across both programmatic- * surfaces, with the `mcp` channel telling them apart. Anonymous requests (an- * `initialize` before the client has a credential, or a public `resources/read`)- * carry no profile: `setupAnalytics` skips `identify` without a `userId` and the- * event still lands, marked `authenticated: false`.+ * Requests reuse the `api_<workspaceId>` profile the RPC tracking interceptor+ * writes to — one identity per workspace across both programmatic surfaces,+ * with the `mcp` channel telling them apart. Requests rejected by+ * `authMiddleware` never reach here, so this counts authenticated traffic only.*/function trackMcpRequest(c: Context<{ Variables: Variables }, "/*">,- workspace: Workspace | undefined,+ workspace: Workspace,body: unknown,) {const calls = rpcCalls(body);if (calls.length === 0) return;setupAnalytics({- userId: workspace ? `api_${workspace.id}` : undefined,- workspaceId: workspace ? `${workspace.id}` : undefined,- plan: workspace?.plan,+ userId: `api_${workspace.id}`,+ workspaceId: `${workspace.id}`,+ plan: workspace.plan,location: c.req.header("x-forwarded-for"),userAgent: c.req.header("user-agent"),})@@ -115,7 +98,7 @@ function trackMcpRequest(analytics.track({...Events.McpRequest,...call,- authenticated: workspace !== undefined,+ authenticated: true,}),),),@@ -136,9 +119,8 @@ function trackMcpRequest(* surface as HTTP 401, which is correct.*/mcpRoute.all("/", async (c) => {- // Anonymous requests reach here with `workspace` unset, which `Variables`- // (shared with the authenticated V1 surface) cannot express.- const workspace = c.get("workspace") as Workspace | undefined;+ // `authMiddleware` ran on every path into this handler, so both are set.+ const workspace = c.get("workspace");const requestId = c.get("requestId");// Pre-parse the JSON-RPC body so we can mirror the request `id` on@@ -170,11 +152,9 @@ mcpRoute.all("/", async (c) => {// NOT call `server.close()` in a `finally` — closing tears down the// SSE stream before Hono finishes writing the body, sending an// empty response to the client.- const server = workspace- ? createMcpServer(- toServiceCtx({ workspace, apiKey: c.get("apiKey"), requestId }),- )- : createPublicMcpServer();+ const server = createMcpServer(+ toServiceCtx({ workspace, apiKey: c.get("apiKey"), requestId }),+ );const transport = new StreamableHTTPTransport();try {await server.connect(transport);diff --git a/apps/server/src/routes/mcp/resources.test.ts b/apps/server/src/routes/mcp/resources.test.tsindex 39b5e6e56..0ab60331b 100644--- a/apps/server/src/routes/mcp/resources.test.ts+++ b/apps/server/src/routes/mcp/resources.test.ts@@ -1,10 +1,12 @@import { Client } from "@modelcontextprotocol/sdk/client/index.js";import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";+import type { Workspace } from "@openstatus/db/src/schema";import { expect } from "@std/expect";import { afterEach, describe, test } from "@std/testing/bdd";+import { toServiceCtx } from "./adapter";import { PUBLIC_RESOURCES, readPublicResource } from "./resources";-import { createPublicMcpServer } from "./server";+import { createMcpServer } from "./server";const realFetch = globalThis.fetch;@@ -87,9 +89,27 @@ describe("public MCP resources", () => {});});-/** Connect a client to the anonymous server the route actually builds. */-async function connectPublicServer() {- const server = createPublicMcpServer();+/**+ * Connect a client to the server the route actually builds. The public+ * documents live on the authenticated server — `/mcp` has no anonymous+ * surface, so there is no other server to connect to. `limits` is real+ * because tool registration reads it (`registerAuditTools` gates on+ * `audit-log`); the rest of the workspace is never touched by a+ * `resources/*` call.+ */+async function connectServer() {+ const server = createMcpServer(+ toServiceCtx({+ workspace: {+ id: 1,+ slug: "ws",+ name: "ws",+ limits: {},+ } as unknown as Workspace,+ apiKey: { id: "k1", scopes: ["*"] },+ requestId: "req-resources",+ }),+ );const client = new Client({ name: "probe", version: "test" });const [clientTransport, serverTransport] =InMemoryTransport.createLinkedPair();@@ -100,13 +120,12 @@ async function connectPublicServer() {return { client, close: () => client.close() };}-describe("anonymous MCP surface", () => {+describe("public MCP documents over the transport", () => {test("advertises the resources capability on initialize", async () => {stubFetch(() => Promise.resolve(new Response("# doc")));- const { client, close } = await connectPublicServer();+ const { client, close } = await connectServer();try {expect(client.getServerCapabilities()?.resources).toBeDefined();- expect(client.getServerCapabilities()?.tools).toBeUndefined();} finally {await close();}@@ -114,7 +133,7 @@ describe("anonymous MCP surface", () => {test("resources/list returns every public document", async () => {stubFetch(() => Promise.resolve(new Response("# doc")));- const { client, close } = await connectPublicServer();+ const { client, close } = await connectServer();try {const { resources } = await client.listResources();expect(resources.map((r) => r.uri).sort()).toEqual(@@ -132,7 +151,7 @@ describe("anonymous MCP surface", () => {test("resources/read returns a non-empty body for each", async () => {stubFetch(() => Promise.resolve(new Response("# doc")));- const { client, close } = await connectPublicServer();+ const { client, close } = await connectServer();try {for (const resource of PUBLIC_RESOURCES) {const result = await client.readResource({ uri: resource.uri });@@ -142,14 +161,4 @@ describe("anonymous MCP surface", () => {await close();}});-- test("exposes no tools without a key", async () => {- stubFetch(() => Promise.resolve(new Response("# doc")));- const { client, close } = await connectPublicServer();- try {- await expect(client.listTools()).rejects.toThrow();- } finally {- await close();- }- });});diff --git a/apps/server/src/routes/mcp/resources.ts b/apps/server/src/routes/mcp/resources.tsindex 7e680ce50..2fe15d119 100644--- a/apps/server/src/routes/mcp/resources.ts+++ b/apps/server/src/routes/mcp/resources.ts@@ -85,11 +85,6 @@ export async function readPublicResource(};}-/**- * Registered on every server, authenticated or not: they carry no workspace- * data, and they are what an anonymous client reads to learn how to- * authenticate.- */export function registerPublicResources(server: McpServer): void {for (const resource of PUBLIC_RESOURCES) {server.registerResource(diff --git a/apps/server/src/routes/mcp/server.ts b/apps/server/src/routes/mcp/server.tsindex f7c4140e2..309591776 100644--- a/apps/server/src/routes/mcp/server.ts+++ b/apps/server/src/routes/mcp/server.ts@@ -37,19 +37,3 @@ export function createMcpServer(ctx: ServiceContext): McpServer {registerAuditTools(server, ctx);return server;}--/**- * Server for a request that carried no `x-openstatus-key`. MCP clients- * `initialize` before they have a credential, and an endpoint that refuses the- * handshake reads as unreachable rather than as protected. No tool is- * registered, so `tools/list` and `tools/call` are absent — not empty — and- * nothing workspace-scoped is reachable without a key.- */-export function createPublicMcpServer(): McpServer {- const server = new McpServer({- name: "openstatus",- version: packageJson.version,- });- registerPublicResources(server);- return server;-}diff --git a/apps/server/src/routes/oauth/oauth.test.ts b/apps/server/src/routes/oauth/oauth.test.tsindex 45ccbc84b..31766b8c0 100644--- a/apps/server/src/routes/oauth/oauth.test.ts+++ b/apps/server/src/routes/oauth/oauth.test.ts@@ -464,12 +464,15 @@ describe("POST /oauth/revoke", () => {});describe("bearer tokens on the resource surfaces", () => {- test("/mcp without any credential falls to the public surface", async () => {- // Anonymous requests are served the public documents; OAuth discovery- // therefore starts from the 401 an invalid or empty credential produces.+ test("/mcp without any credential is the 401 that starts discovery", async () => {+ // `/mcp` is a protected resource with no anonymous surface: a client that+ // `initialize`s before it holds a token is told where the authorization+ // server is rather than being handed a credential-less session.const res = await mcp();- expect(res.status).toBe(200);- expect(await toolNames(res)).toEqual([]);+ expect(res.status).toBe(401);+ expect(res.headers.get("www-authenticate")).toBe(+ `Bearer resource_metadata="${config.issuer}/.well-known/oauth-protected-resource/mcp"`,+ );});test("/mcp with an empty Authorization header is a 401 carrying WWW-Authenticate", async () => {