Skip to content
Draft
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
1 change: 1 addition & 0 deletions docs/session-ownership.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
63 changes: 58 additions & 5 deletions src/modules/mcp/handlers/shttp.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Request>;
Expand Down Expand Up @@ -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',
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand Down
6 changes: 3 additions & 3 deletions src/modules/mcp/handlers/shttp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,20 +78,20 @@ 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', {
sessionId,
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;
Expand Down
Loading