diff --git a/.changeset/quiet-mcp-guards.md b/.changeset/quiet-mcp-guards.md new file mode 100644 index 000000000..5daf0b93b --- /dev/null +++ b/.changeset/quiet-mcp-guards.md @@ -0,0 +1,9 @@ +--- +"@voltagent/server-core": patch +--- + +fix(server-core): require authentication for MCP execution routes under legacy `auth` + +The legacy auth policy protected agent, tool, and workflow execution but left the MCP execution routes open, so an MCP client could call exposed tools, agents, and workflows without a token. `PROTECTED_ROUTES` now includes the MCP Streamable HTTP route (`/mcp/:serverId/mcp`), the SSE connection and message routes (`GET /mcp/:serverId/sse`, `POST /mcp/:serverId/messages`), MCP tool invocation, reading a single MCP prompt or resource, and the logging level route. MCP discovery is unchanged: `GET /mcp/servers`, `GET /mcp/servers/:serverId` and `GET /mcp/servers/:serverId/tools` stay public, and the prompt, resource and resource template lists stay public in the default mode (with `defaultPrivate: true` they require auth, as before). Apps that relied on unauthenticated MCP access can opt back in with `publicRoutes`. `requiresAuth()` also matches a path with a trailing slash and a `HEAD` request the same way as the route without the slash and its `GET`, so those spellings no longer reach protected handlers without a token. + +Fixes #1493 diff --git a/packages/server-core/src/auth/defaults.spec.ts b/packages/server-core/src/auth/defaults.spec.ts index 97ce41f90..13e479f39 100644 --- a/packages/server-core/src/auth/defaults.spec.ts +++ b/packages/server-core/src/auth/defaults.spec.ts @@ -119,6 +119,41 @@ describe("Auth Defaults", () => { expect(requiresAuth("POST", "/workflows/test/executions/exec-789/cancel")).toBe(true); }); + it("should require auth for MCP transport endpoints", () => { + expect(requiresAuth("POST", "/mcp/my-server/mcp")).toBe(true); + expect(requiresAuth("GET", "/mcp/my-server/mcp")).toBe(true); + expect(requiresAuth("DELETE", "/mcp/my-server/mcp")).toBe(true); + expect(requiresAuth("GET", "/mcp/my-server/sse")).toBe(true); + expect(requiresAuth("POST", "/mcp/my-server/messages")).toBe(true); + }); + + it("should require auth for MCP tool invocation and logging control", () => { + expect(requiresAuth("POST", "/mcp/servers/my-server/tools/search")).toBe(true); + expect(requiresAuth("POST", "/mcp/my-server/tools/search/invoke")).toBe(true); + expect(requiresAuth("POST", "/mcp/servers/my-server/logging/level")).toBe(true); + expect(requiresAuth("POST", "/mcp/my-server/logging/level")).toBe(true); + }); + + it("should require auth for reading MCP prompts and resources", () => { + expect(requiresAuth("GET", "/mcp/servers/my-server/prompts/greet")).toBe(true); + expect(requiresAuth("GET", "/mcp/my-server/prompts/greet")).toBe(true); + expect(requiresAuth("GET", "/mcp/servers/my-server/resources/contents")).toBe(true); + expect(requiresAuth("GET", "/mcp/my-server/resources/read")).toBe(true); + }); + + it("should keep MCP prompt and resource listings public", () => { + expect(requiresAuth("GET", "/mcp/servers/my-server/prompts")).toBe(false); + expect(requiresAuth("GET", "/mcp/servers/my-server/resources")).toBe(false); + expect(requiresAuth("GET", "/mcp/servers/my-server/resource-templates")).toBe(false); + }); + + it("should keep MCP discovery public while protecting MCP execution", () => { + expect(requiresAuth("GET", "/mcp/servers")).toBe(false); + expect(requiresAuth("GET", "/mcp/servers/my-server")).toBe(false); + expect(requiresAuth("GET", "/mcp/servers/my-server/tools")).toBe(false); + expect(requiresAuth("POST", "/mcp/my-server/mcp")).toBe(true); + }); + it("should require auth for all observability endpoints via wildcard", () => { expect(requiresAuth("GET", "/observability/traces")).toBe(true); expect(requiresAuth("GET", "/observability/spans/abc-123")).toBe(true); @@ -193,6 +228,13 @@ describe("Auth Defaults", () => { expect(requiresAuth("POST", "/agents/test/text", publicRoutes)).toBe(false); }); + + it("should allow making MCP transport routes public via publicRoutes", () => { + const publicRoutes = ["/mcp/:serverId/mcp"]; + + expect(requiresAuth("POST", "/mcp/my-server/mcp", publicRoutes)).toBe(false); + expect(requiresAuth("POST", "/mcp/my-server/messages", publicRoutes)).toBe(true); + }); }); }); @@ -219,6 +261,22 @@ describe("Auth Defaults", () => { }); }); + describe("MCP Routes (Opt-Out Mode)", () => { + it("should keep MCP discovery public and protect MCP execution with defaultPrivate", () => { + expect(requiresAuth("GET", "/mcp/servers", undefined, true)).toBe(false); + expect(requiresAuth("GET", "/mcp/servers/my-server/tools", undefined, true)).toBe(false); + expect(requiresAuth("POST", "/mcp/my-server/mcp", undefined, true)).toBe(true); + }); + + it("should require auth for MCP prompt and resource lists with defaultPrivate", () => { + expect(requiresAuth("GET", "/mcp/servers/my-server/prompts", undefined, true)).toBe(true); + expect(requiresAuth("GET", "/mcp/servers/my-server/resources", undefined, true)).toBe(true); + expect( + requiresAuth("GET", "/mcp/servers/my-server/resource-templates", undefined, true), + ).toBe(true); + }); + }); + describe("Custom Routes (Opt-Out Mode) - Main Feature", () => { it("should require auth for custom routes when defaultPrivate is true", () => { // This is the NEW behavior - custom routes are protected by default @@ -364,6 +422,34 @@ describe("Auth Defaults", () => { expect(requiresAuth("POST", "/webhooks/stripe-test", publicRoutes)).toBe(false); expect(requiresAuth("GET", "/api/data-export", publicRoutes)).toBe(false); }); + + it("should match trailing-slash paths like the route without the slash", () => { + expect(requiresAuth("POST", "/mcp/my-server/tools/search/invoke/")).toBe(true); + expect(requiresAuth("GET", "/mcp/my-server/resources/read/")).toBe(true); + expect(requiresAuth("GET", "/mcp/my-server/prompts/greet/")).toBe(true); + expect(requiresAuth("POST", "/agents/test/text/")).toBe(true); + expect(requiresAuth("GET", "/mcp/servers/")).toBe(false); + expect(requiresAuth("GET", "/")).toBe(false); + expect(requiresAuth("GET", "/api/custom/", ["GET /api/custom"], true)).toBe(false); + }); + + it("should treat HEAD like GET", () => { + expect(requiresAuth("HEAD", "/mcp/servers/my-server/prompts/greet")).toBe(true); + expect(requiresAuth("HEAD", "/mcp/my-server/resources/read")).toBe(true); + expect(requiresAuth("HEAD", "/mcp/my-server/sse")).toBe(true); + expect(requiresAuth("head", "/mcp/my-server/sse")).toBe(true); + expect(requiresAuth("HEAD", "/mcp/servers")).toBe(false); + expect(requiresAuth("HEAD", "/api/data", ["GET /api/data"], true)).toBe(false); + }); + + it("should keep publicRoutes written with HEAD or a trailing slash", () => { + expect(requiresAuth("HEAD", "/health", ["HEAD /health"], true)).toBe(false); + expect(requiresAuth("GET", "/health", ["HEAD /health"], true)).toBe(true); + expect(requiresAuth("POST", "/webhooks/stripe/", ["POST /webhooks/stripe/"], true)).toBe( + false, + ); + expect(requiresAuth("POST", "/webhooks/stripe", ["POST /webhooks/stripe/"], true)).toBe(true); + }); }); describe("Constants Validation", () => { diff --git a/packages/server-core/src/auth/defaults.ts b/packages/server-core/src/auth/defaults.ts index 3dc005d58..be95dfd04 100644 --- a/packages/server-core/src/auth/defaults.ts +++ b/packages/server-core/src/auth/defaults.ts @@ -122,6 +122,23 @@ export const PROTECTED_ROUTES = [ "POST /workflows/:id/executions/:executionId/replay", // Replay execution from historical step "POST /workflows/:id/executions/:executionId/cancel", // Cancel execution + // ======================================== + // MCP EXECUTION (Tools, Agents, Workflows, Prompts, Resources) + // Not listed here: discovery. Server list/details and tool lists are in DEFAULT_LEGACY_PUBLIC_ROUTES; + // prompt, resource and resource template lists stay public unless defaultPrivate is true + // ======================================== + "/mcp/:serverId/mcp", // Streamable HTTP transport (GET/POST/DELETE) + "GET /mcp/:serverId/sse", // SSE transport connection + "POST /mcp/:serverId/messages", // SSE transport messages + "POST /mcp/servers/:serverId/tools/:toolName", // Invoke MCP tool (Hono) + "POST /mcp/:serverId/tools/:toolName/invoke", // Invoke MCP tool (Elysia) + "POST /mcp/servers/:serverId/logging/level", // Set MCP logging level (Hono) + "POST /mcp/:serverId/logging/level", // Set MCP logging level (Elysia) + "GET /mcp/servers/:serverId/prompts/:promptName", // Get MCP prompt (Hono) + "GET /mcp/:serverId/prompts/:promptName", // Get MCP prompt (Elysia) + "GET /mcp/servers/:serverId/resources/contents", // Read MCP resource (Hono) + "GET /mcp/:serverId/resources/read", // Read MCP resource (Elysia) + // ======================================== // MEMORY (User Data) // ======================================== @@ -232,17 +249,28 @@ export function requiresAuth( publicRoutes?: string[], defaultPrivate?: boolean, ): boolean { + // HEAD is served by GET handlers, and a trailing slash can reach the same handler + // (Elysia's default non-strict routing), so match both against the canonical route + const upperMethod = method.toUpperCase(); + const normalizedMethod = upperMethod === "HEAD" ? "GET" : upperMethod; + const normalizedPath = path.replace(/\/+$/, "") || "/"; + // Routes written with HEAD or a trailing slash keep matching the request as sent + const methodMatches = (routeMethod: string) => + routeMethod === upperMethod || routeMethod === normalizedMethod; + const routePathMatches = (routePath: string) => + pathMatches(path, routePath) || pathMatches(normalizedPath, routePath); + // Check if it's a default public route for (const publicRoute of DEFAULT_LEGACY_PUBLIC_ROUTES) { if (publicRoute.includes(" ")) { // Route with method specified const [routeMethod, routePath] = publicRoute.split(" "); - if (method.toUpperCase() === routeMethod && pathMatches(path, routePath)) { + if (methodMatches(routeMethod) && routePathMatches(routePath)) { return false; // Public route, no auth required } } else { // Route without method (any method) - if (pathMatches(path, publicRoute)) { + if (routePathMatches(publicRoute)) { return false; // Public route, no auth required } } @@ -254,12 +282,12 @@ export function requiresAuth( if (publicRoute.includes(" ")) { // Route with method specified const [routeMethod, routePath] = publicRoute.split(" "); - if (method.toUpperCase() === routeMethod && pathMatches(path, routePath)) { + if (methodMatches(routeMethod) && routePathMatches(routePath)) { return false; // Public route, no auth required } } else { // Route without method (any method) - if (pathMatches(path, publicRoute)) { + if (routePathMatches(publicRoute)) { return false; // Public route, no auth required } } @@ -271,12 +299,12 @@ export function requiresAuth( if (protectedRoute.includes(" ")) { // Route with method specified const [routeMethod, routePath] = protectedRoute.split(" "); - if (method.toUpperCase() === routeMethod && pathMatches(path, routePath)) { + if (methodMatches(routeMethod) && routePathMatches(routePath)) { return true; // Protected route, auth required } } else { // Route without method (any method) - if (pathMatches(path, protectedRoute)) { + if (routePathMatches(protectedRoute)) { return true; // Protected route, auth required } } diff --git a/packages/server-elysia/src/auth/middleware.spec.ts b/packages/server-elysia/src/auth/middleware.spec.ts index 795e55985..cdc16319f 100644 --- a/packages/server-elysia/src/auth/middleware.spec.ts +++ b/packages/server-elysia/src/auth/middleware.spec.ts @@ -426,6 +426,93 @@ describe("Auth Middleware - conversationId & Options Preservation", () => { expect(json.error).toBe("Authentication required"); }); + it("should return 401 for MCP prompt and resource reads when token is missing", async () => { + const app = new Elysia() + .state("authenticatedUser", null as any) + .onBeforeHandle(createAuthMiddleware(mockAuthProvider)) + .get("/mcp/:serverId/prompts/:promptName", () => ({ success: true })) + .get("/mcp/:serverId/resources/read", () => ({ success: true })); + + for (const path of ["/mcp/test-server/prompts/greet", "/mcp/test-server/resources/read"]) { + const res = await app.handle(new Request(`http://localhost:3000${path}`)); + + expect(res.status).toBe(401); + const json = await res.json(); + expect(json.error).toBe("Authentication required"); + } + }); + + it("should return 401 for MCP tool invocation when token is missing", async () => { + const app = new Elysia() + .state("authenticatedUser", null as any) + .onBeforeHandle(createAuthMiddleware(mockAuthProvider)) + .post("/mcp/:serverId/tools/:toolName/invoke", () => ({ success: true })) + .post("/mcp/:serverId/logging/level", () => ({ success: true })); + + for (const path of [ + "/mcp/test-server/tools/search/invoke", + "/mcp/test-server/logging/level", + ]) { + const res = await app.handle( + new Request(`http://localhost:3000${path}`, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({}), + }), + ); + + expect(res.status).toBe(401); + const json = await res.json(); + expect(json.error).toBe("Authentication required"); + } + }); + + it("should return 401 for trailing-slash MCP tool invocation when token is missing", async () => { + const app = new Elysia() + .state("authenticatedUser", null as any) + .onBeforeHandle(createAuthMiddleware(mockAuthProvider)) + .post("/mcp/:serverId/tools/:toolName/invoke", () => ({ success: true })); + + const res = await app.handle( + new Request("http://localhost:3000/mcp/test-server/tools/search/invoke/", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({}), + }), + ); + + expect(res.status).toBe(401); + }); + + it("should let authenticated requests reach MCP tool invocation", async () => { + const app = new Elysia() + .state("authenticatedUser", null as any) + .onBeforeHandle(createAuthMiddleware(mockAuthProvider)) + .post("/mcp/:serverId/tools/:toolName/invoke", () => ({ success: true })); + + for (const path of [ + "/mcp/test-server/tools/search/invoke", + "/mcp/test-server/tools/search/invoke/", + ]) { + const res = await app.handle( + new Request(`http://localhost:3000${path}`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer valid-token", + }, + body: JSON.stringify({}), + }), + ); + + expect(res.status).toBe(200); + const json = await res.json(); + expect(json.success).toBe(true); + } + }); + it("should return 401 when token is invalid", async () => { mockAuthProvider.defaultPrivate = true; diff --git a/packages/server-hono/src/auth/middleware.spec.ts b/packages/server-hono/src/auth/middleware.spec.ts index 5179bd473..1b2845605 100644 --- a/packages/server-hono/src/auth/middleware.spec.ts +++ b/packages/server-hono/src/auth/middleware.spec.ts @@ -429,6 +429,38 @@ describe("Auth Middleware - conversationId & Options Preservation", () => { expect(json.error).toBe("Authentication required"); }); + it("should return 401 for MCP execution routes when token is missing", async () => { + const middleware = createAuthMiddleware(mockAuthProvider); + const routes: Array<[string, string]> = [ + ["/mcp/test-server/mcp", "POST"], + ["/mcp/test-server/sse", "GET"], + ["/mcp/test-server/messages", "POST"], + ["/mcp/servers/test-server/tools/search", "POST"], + ["/mcp/servers/test-server/logging/level", "POST"], + ["/mcp/servers/test-server/prompts/greet", "GET"], + ["/mcp/servers/test-server/resources/contents", "GET"], + ]; + + for (const [path, method] of routes) { + mockContext = createMockContext(path, method, {}); + const response = await middleware(mockContext as Context, mockNext); + + expect(response?.status).toBe(401); + } + + expect(mockNext).not.toHaveBeenCalled(); + }); + + it("should let authenticated requests reach MCP execution routes", async () => { + mockContext = createMockContext("/mcp/test-server/mcp", "POST", {}, "valid-token"); + + const middleware = createAuthMiddleware(mockAuthProvider); + await middleware(mockContext as Context, mockNext); + + expect(mockAuthProvider.verifyToken).toHaveBeenCalled(); + expect(mockNext).toHaveBeenCalled(); + }); + it("should return 401 when token is invalid", async () => { mockContext = createMockContext( "/agents/test-agent/text", diff --git a/website/docs/api/authentication.md b/website/docs/api/authentication.md index 27b7c9383..1e59e8b27 100644 --- a/website/docs/api/authentication.md +++ b/website/docs/api/authentication.md @@ -611,7 +611,7 @@ if (process.env.NODE_ENV === "production") { Legacy auth uses two default lists: - **DEFAULT_LEGACY_PUBLIC_ROUTES** (alias `DEFAULT_PUBLIC_ROUTES`): management, docs, discovery -- **PROTECTED_ROUTES**: execution, tool execution, observability, updates +- **PROTECTED_ROUTES**: execution, tool execution, MCP execution (transports, tool invocation, prompt and resource reads, logging level), observability, updates When `auth` is enabled: @@ -626,6 +626,7 @@ If you need `/agents`, `/workflows`, `/doc`, or `/ui` protected, use **authNext* | Endpoint Type | Legacy Auth (Default) | Legacy Auth (defaultPrivate: true) | | --------------------------------- | --------------------- | ---------------------------------- | | Execution (`POST /agents/*/text`) | Protected | Protected | +| MCP execution (`/mcp/*/mcp`) | Protected | Protected | | Management (`GET /agents`) | Public | Public | | Docs (`/doc`, `/ui`) | Public | Public | | Custom routes | Public | Protected |