Skip to content

Commit 5fa8d1c

Browse files
fix: bind HTTP sessions to bearer principal, 404 unknown session ids
Address review findings on the streamable HTTP transport: - F2: store req.principal with each session at initialize; POST/GET/DELETE carrying another principal's session id now get a bare 403 {"error":"forbidden"} with no MCP protocol details leaked. A rejected DELETE cannot tear down someone else's session. - F3: a present-but-unknown Mcp-Session-Id returns 404; 400 is kept only for missing session ids on non-initialize requests, matching the MCP streamable HTTP contract. - F4: npm test invokes node --test via a shell-expanded file list so it works on Node 18/20 (no --test glob support there). Note: the suggested `node --test test` was adjusted to `node --test test/*.test.js` — since Node 21 positional --test args are globs, a bare directory matches itself and crashes with MODULE_NOT_FOUND (nodejs/node#64555), which would break npm test on every current Node. The unquoted glob is expanded by sh into literal paths that every supported Node accepts. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
1 parent 1506244 commit 5fa8d1c

3 files changed

Lines changed: 75 additions & 14 deletions

File tree

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
},
1010
"scripts": {
1111
"start": "node yourls-mcp.js",
12-
"test": "node --test \"test/*.test.js\""
12+
"test": "node --test test/*.test.js"
1313
},
1414
"publishConfig": {
1515
"access": "public"

‎src/http.js‎

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ function sendJsonRpcError(res, status, message) {
2727
* @param {Function} options.createMcpServer - Factory returning a fresh McpServer per session
2828
* @param {Map<string, string>} [options.tokens] - Bearer token to principal map
2929
* @param {boolean} [options.allowUnauthenticated=false] - Dev-only auth bypass
30-
* @returns {{app: object, httpServer: object, transports: Map, close: Function}}
30+
* @returns {{app: object, httpServer: object, transports: Map<string, {transport: object, principal: string}>, close: Function}}
3131
*/
3232
export function startHttpServer({
3333
port = 3133,
@@ -50,13 +50,22 @@ export function startHttpServer({
5050
const sessionId = req.headers['mcp-session-id'];
5151
let transport;
5252

53-
if (sessionId && transports.has(sessionId)) {
54-
transport = transports.get(sessionId);
55-
} else if (!sessionId && isInitializeRequest(req.body)) {
53+
if (sessionId) {
54+
const session = transports.get(sessionId);
55+
if (!session) {
56+
sendJsonRpcError(res, 404, 'Not Found: unknown session ID');
57+
return;
58+
}
59+
if (session.principal !== req.principal) {
60+
res.status(403).json({ error: 'forbidden' });
61+
return;
62+
}
63+
transport = session.transport;
64+
} else if (isInitializeRequest(req.body)) {
5665
transport = new StreamableHTTPServerTransport({
5766
sessionIdGenerator: () => randomUUID(),
5867
onsessioninitialized: (sid) => {
59-
transports.set(sid, transport);
68+
transports.set(sid, { transport, principal: req.principal });
6069
}
6170
});
6271

@@ -82,12 +91,20 @@ export function startHttpServer({
8291

8392
const handleSessionRequest = async (req, res) => {
8493
const sessionId = req.headers['mcp-session-id'];
85-
const transport = sessionId ? transports.get(sessionId) : undefined;
86-
if (!transport) {
87-
sendJsonRpcError(res, 400, 'Bad Request: invalid or missing session ID');
94+
if (!sessionId) {
95+
sendJsonRpcError(res, 400, 'Bad Request: missing session ID');
8896
return;
8997
}
90-
await transport.handleRequest(req, res);
98+
const session = transports.get(sessionId);
99+
if (!session) {
100+
sendJsonRpcError(res, 404, 'Not Found: unknown session ID');
101+
return;
102+
}
103+
if (session.principal !== req.principal) {
104+
res.status(403).json({ error: 'forbidden' });
105+
return;
106+
}
107+
await session.transport.handleRequest(req, res);
91108
};
92109

93110
app.get('/mcp', requireAuth, handleSessionRequest);

‎test/http.test.js‎

Lines changed: 48 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,11 @@ import { buildMcpServer, createServer } from '../src/index.js';
88
import { loadBearerTokens } from '../src/bearer.js';
99

1010
const TOKEN = 'test-token-for-http-suite';
11+
const TOKEN_B = 'second-token-for-http-suite';
1112

1213
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'yourls-mcp-http-'));
1314
const tokensFile = path.join(tmpDir, 'tokens.json');
14-
fs.writeFileSync(tokensFile, JSON.stringify({ [TOKEN]: 'team-bot' }));
15+
fs.writeFileSync(tokensFile, JSON.stringify({ [TOKEN]: 'team-bot', [TOKEN_B]: 'other-bot' }));
1516

1617
function mockYourlsClient() {
1718
return {
@@ -37,8 +38,8 @@ function parseSseMessages(text) {
3738
.map(line => JSON.parse(line.slice('data:'.length).trim()));
3839
}
3940

40-
const mcpHeaders = (sessionId) => ({
41-
Authorization: `Bearer ${TOKEN}`,
41+
const mcpHeaders = (sessionId, token = TOKEN) => ({
42+
Authorization: `Bearer ${token}`,
4243
'Content-Type': 'application/json',
4344
Accept: 'application/json, text/event-stream',
4445
...(sessionId ? { 'Mcp-Session-Id': sessionId } : {})
@@ -156,6 +157,27 @@ test('POST /mcp non-initialize request without session returns 400', async () =>
156157
assert.equal(res.status, 400);
157158
});
158159

160+
test('GET and DELETE /mcp without a session id return 400', async () => {
161+
for (const method of ['GET', 'DELETE']) {
162+
const res = await fetch(`${base}/mcp`, { method, headers: mcpHeaders() });
163+
assert.equal(res.status, 400, method);
164+
}
165+
});
166+
167+
test('requests with an unknown session id return 404', async () => {
168+
for (const method of ['GET', 'DELETE']) {
169+
const res = await fetch(`${base}/mcp`, { method, headers: mcpHeaders('no-such-session') });
170+
assert.equal(res.status, 404, method);
171+
}
172+
173+
const res = await fetch(`${base}/mcp`, {
174+
method: 'POST',
175+
headers: mcpHeaders('no-such-session'),
176+
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' })
177+
});
178+
assert.equal(res.status, 404);
179+
});
180+
159181
test('initialize + tools/list returns exactly the allowlisted tools', async () => {
160182
const sessionId = await initializeSession(base);
161183
const { result } = await rpc(base, sessionId, 'tools/list');
@@ -190,6 +212,28 @@ test('tools/call shorten_url succeeds for a free kebab-case keyword', async () =
190212
assert.equal(body.shorturl, 'https://s.example/acme-corp-annual');
191213
});
192214

215+
test('session is bound to the bearer principal that created it', async () => {
216+
const sessionId = await initializeSession(base);
217+
218+
const res = await fetch(`${base}/mcp`, {
219+
method: 'POST',
220+
headers: mcpHeaders(sessionId, TOKEN_B),
221+
body: JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'tools/list' })
222+
});
223+
assert.equal(res.status, 403);
224+
assert.deepEqual(await res.json(), { error: 'forbidden' });
225+
226+
for (const method of ['GET', 'DELETE']) {
227+
const denied = await fetch(`${base}/mcp`, { method, headers: mcpHeaders(sessionId, TOKEN_B) });
228+
assert.equal(denied.status, 403, method);
229+
assert.deepEqual(await denied.json(), { error: 'forbidden' });
230+
}
231+
232+
// The forbidden DELETE must not have torn the session down
233+
const { result } = await rpc(base, sessionId, 'tools/list');
234+
assert.ok(result, 'session must still be usable by its owner');
235+
});
236+
193237
test('tools/call for a non-registered tool fails', async () => {
194238
const sessionId = await initializeSession(base);
195239
const res = await fetch(`${base}/mcp`, {
@@ -215,7 +259,7 @@ test('DELETE /mcp tears down the session', async () => {
215259
headers: mcpHeaders(sessionId),
216260
body: JSON.stringify({ jsonrpc: '2.0', id: 4, method: 'tools/list' })
217261
});
218-
assert.equal(res.status, 400);
262+
assert.equal(res.status, 404);
219263
});
220264

221265
test('createServer http mode is a hard startup error without bearer tokens', () => {

0 commit comments

Comments
 (0)