From aa117b49aa21726486860c2dcbf38eb160f55779 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 17:49:24 +0000 Subject: [PATCH] fix: return 404 instead of 401 for terminated sessions The spec requires HTTP 404 for a request that carries a terminated session ID, so the client knows to re-initialize. A 401 made clients retry auth with a token that was still valid. Another user's session gets the same 404, so the response does not reveal which session IDs are live. Co-authored-by: fweinberger --- docs/session-ownership.md | 1 + .../mcp/handlers/shttp.integration.test.ts | 63 +++++++++++++++++-- src/modules/mcp/handlers/shttp.ts | 6 +- 3 files changed, 62 insertions(+), 8 deletions(-) diff --git a/docs/session-ownership.md b/docs/session-ownership.md index 9ff82e7..6117535 100644 --- a/docs/session-ownership.md +++ b/docs/session-ownership.md @@ -75,6 +75,7 @@ When an MCP server starts handling a session, it subscribes to the channel. When - **Ownership persistence**: Survives across requests and server restarts - **Token-based validation**: User ID extracted from validated OAuth token - **Access control**: All operations (GET, POST, DELETE) validate ownership +- **Uniform 404**: On `/mcp`, terminated, unknown and other users' sessions all get the same HTTP 404 response, which tells the client to start a new session ## Implementation diff --git a/src/modules/mcp/handlers/shttp.integration.test.ts b/src/modules/mcp/handlers/shttp.integration.test.ts index d3f9154..eb25425 100644 --- a/src/modules/mcp/handlers/shttp.integration.test.ts +++ b/src/modules/mcp/handlers/shttp.integration.test.ts @@ -19,6 +19,12 @@ interface MCPInitResponse { }; } +const SESSION_NOT_FOUND = { + jsonrpc: '2.0', + id: null, + error: { code: -32001, message: 'Session not found' } +}; + describe('Streamable HTTP Handler Integration Tests', () => { let mockRedis: MockRedisClient; let mockReq: Partial; @@ -346,7 +352,52 @@ describe('Streamable HTTP Handler Integration Tests', () => { } }); - it('should return 401 for DELETE request with wrong user', async () => { + it.each(['POST', 'GET', 'DELETE'])('should return 404 for %s request after the session is terminated', async (method) => { + mockReq.body = { + jsonrpc: '2.0', + id: 'init-1', + method: 'initialize', + params: { + protocolVersion: '2024-11-05', + capabilities: {}, + clientInfo: { name: 'test-client', version: '1.0.0' } + } + }; + mockReq.auth = { + clientId: 'test-client-123', + token: 'test-token', + scopes: ['mcp'], + extra: { userId: 'test-user-123' } + } as AuthInfo; + + await handleStreamableHTTP(mockReq as Request, mockRes as Response); + await new Promise(resolve => setTimeout(resolve, 100)); + + const sessionId = getSessionIdFromTest(); + expect(sessionId).toBeDefined(); + + await triggerResponseCleanup(); + // Same path as the inactivity timeout and DELETE + await shutdownSession(sessionId!); + await new Promise(resolve => setTimeout(resolve, 50)); + jest.clearAllMocks(); + + mockReq.method = method; + mockReq.headers = { + ...mockReq.headers, + 'mcp-session-id': sessionId + }; + mockReq.body = method === 'POST' + ? { jsonrpc: '2.0', id: 'req-1', method: 'tools/list', params: {} } + : {}; + + await handleStreamableHTTP(mockReq as Request, mockRes as Response); + + expect(mockRes.status).toHaveBeenCalledWith(404); + expect(mockRes.json).toHaveBeenCalledWith(SESSION_NOT_FOUND); + }); + + it('should return 404 for DELETE request with wrong user', async () => { // First, create a session as user1 const initRequest: JSONRPCMessage = { jsonrpc: '2.0', @@ -426,8 +477,9 @@ describe('Streamable HTTP Handler Integration Tests', () => { await handleStreamableHTTP(mockReq as Request, mockRes as Response); - // Should return 401 for unauthorized access to another user's session - expect(mockRes.status).toHaveBeenCalledWith(401); + // Another user's session is reported as not found + expect(mockRes.status).toHaveBeenCalledWith(404); + expect(mockRes.json).toHaveBeenCalledWith(SESSION_NOT_FOUND); // shutdown the session if (sessionId) { @@ -537,8 +589,9 @@ describe('Streamable HTTP Handler Integration Tests', () => { await handleStreamableHTTP(mockReq as Request, mockRes as Response); - // Should return 401 for unauthorized access to another user's session - expect(mockRes.status).toHaveBeenCalledWith(401); + // Another user's session is reported as not found + expect(mockRes.status).toHaveBeenCalledWith(404); + expect(mockRes.json).toHaveBeenCalledWith(SESSION_NOT_FOUND); // Clean up the MCP server by sending DELETE request if (actualSessionId) { diff --git a/src/modules/mcp/handlers/shttp.ts b/src/modules/mcp/handlers/shttp.ts index 6f4c11f..6b69ea4 100644 --- a/src/modules/mcp/handlers/shttp.ts +++ b/src/modules/mcp/handlers/shttp.ts @@ -78,7 +78,7 @@ export async function handleStreamableHTTP(req: Request, res: Response) { const isGetRequest = req.method === 'GET'; - // incorrect session for the authed user, return 401 + // terminated, unknown or another user's session: 404 tells the client to re-initialize if (sessionId) { if (!(await isSessionOwnedBy(sessionId, userId))) { logger.warning('Session ownership mismatch', { @@ -86,12 +86,12 @@ export async function handleStreamableHTTP(req: Request, res: Response) { userId, requestMethod: req.method }); - res.status(401).json({ + res.status(404).json({ "jsonrpc": "2.0", "id": null, "error": { "code": -32001, - "message": "Session not found or access denied" + "message": "Session not found" } }); return;