refactor(server): serve /mcp from a Nest controller; delete auth, audit, addons and oauth bridges

This commit is contained in:
jubnl
2026-08-11 23:01:19 +02:00
parent fac442086f
commit 954a3ca0a7
23 changed files with 861 additions and 638 deletions
+184
View File
@@ -55,6 +55,26 @@ import { generateToken } from '../helpers/auth';
import { createMcpToken } from '../helpers/factories';
import { closeMcpSessions } from '../../src/mcp/index';
import { sessions } from '../../src/mcp/sessionManager';
import { getMcpSafeUrl } from '../../src/app-config';
import { OauthService } from '../../src/nest/oauth/oauth.service';
import { DatabaseService } from '../../src/nest/database/database.service';
import { AddonsService } from '../../src/nest/addons/addons.service';
import { AuditService } from '../../src/nest/audit/audit.service';
const oauthDbs = new DatabaseService(testDb);
const oauthSvc = new OauthService(oauthDbs, new AddonsService(oauthDbs), new AuditService(oauthDbs));
/** Mint a trekoa_ access token for the user via a fresh OAuth client. */
function mintOauthToken(userId: number, audience: string | null): { accessToken: string; clientId: string } {
const created = oauthSvc.createOAuthClient(userId, 'MCP Test Client', ['https://client.example.com/cb'], ['trips:read']);
const clientId = (created.client as { client_id: string }).client_id;
const tokens = oauthSvc.issueTokens(clientId, userId, ['trips:read'], null, audience);
return { accessToken: tokens.access_token, clientId };
}
const MCP_AUDIENCE = `${getMcpSafeUrl().replace(/\/+$/, '')}/mcp`;
const EXPECTED_CHALLENGE =
`Bearer realm="TREK MCP", resource_metadata="${getMcpSafeUrl().replace(/\/+$/, '')}/.well-known/oauth-protected-resource/mcp", error="invalid_token"`;
let nestApp: INestApplication;
let app: Application;
@@ -311,6 +331,170 @@ describe('MCP session management', () => {
});
});
describe('MCP transport parity pins (Nest-hosted /mcp)', () => {
const initBody = { jsonrpc: '2.0', method: 'initialize', id: 1, params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'test', version: '1' } } };
async function createSession(token: string): Promise<string> {
const res = await request(app)
.post('/mcp')
.set('Authorization', `Bearer ${token}`)
.set('Accept', 'application/json, text/event-stream')
.send(initBody);
expect(res.status).toBe(200);
return res.headers['mcp-session-id'] as string;
}
beforeEach(() => {
testDb.prepare("UPDATE addons SET enabled = 1 WHERE id = 'mcp'").run();
});
it('MCP-P01 — addon off answers 403 with the exact legacy body', async () => {
testDb.prepare("UPDATE addons SET enabled = 0 WHERE id = 'mcp'").run();
const res = await request(app).post('/mcp').send(initBody);
expect(res.status).toBe(403);
expect(res.body).toEqual({ error: 'MCP is not enabled' });
});
it('MCP-P02 — missing/invalid auth carries the exact WWW-Authenticate challenge', async () => {
const res = await request(app).post('/mcp').send(initBody);
expect(res.status).toBe(401);
expect(res.body).toEqual({ error: 'Access token required' });
expect(res.headers['www-authenticate']).toBe(EXPECTED_CHALLENGE);
});
it('MCP-P03 — a non-Bearer scheme and a schemeless token are both rejected', async () => {
for (const header of ['Basic dXNlcjpwdw==', 'just-a-token']) {
const res = await request(app).post('/mcp').set('Authorization', header).send(initBody);
expect(res.status, header).toBe(401);
}
});
it('MCP-P04 — a trekoa_ token with the wrong audience is rejected with a challenge', async () => {
const { user } = createUser(testDb);
const { accessToken } = mintOauthToken(user.id, 'https://other.example.com/api');
const res = await request(app)
.post('/mcp')
.set('Authorization', `Bearer ${accessToken}`)
.send(initBody);
expect(res.status).toBe(401);
expect(res.headers['www-authenticate']).toBe(EXPECTED_CHALLENGE);
});
it('MCP-P05 — a trekoa_ token with the MCP audience authenticates', async () => {
const { user } = createUser(testDb);
const { accessToken } = mintOauthToken(user.id, MCP_AUDIENCE);
const res = await request(app)
.post('/mcp')
.set('Authorization', `Bearer ${accessToken}`)
.set('Accept', 'application/json, text/event-stream')
.send(initBody);
expect(res.status).toBe(200);
expect(res.headers['mcp-session-id']).toBeTruthy();
});
it('MCP-P06 — resuming an unknown session answers the exact 404 body', async () => {
const { user } = createUser(testDb);
const res = await request(app)
.post('/mcp')
.set('Authorization', `Bearer ${generateToken(user.id)}`)
.set('mcp-session-id', 'no-such-session')
.send({ jsonrpc: '2.0', method: 'tools/list', id: 2 });
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Session not found' });
});
it("MCP-P07 — another user's session answers 403 with the challenge and exact body", async () => {
const { user: owner } = createUser(testDb);
const { user: intruder } = createUser(testDb);
const sessionId = await createSession(generateToken(owner.id));
const res = await request(app)
.post('/mcp')
.set('Authorization', `Bearer ${generateToken(intruder.id)}`)
.set('mcp-session-id', sessionId)
.send({ jsonrpc: '2.0', method: 'tools/list', id: 2 });
expect(res.status).toBe(403);
expect(res.body).toEqual({ error: 'Session belongs to a different user' });
expect(res.headers['www-authenticate']).toBe(EXPECTED_CHALLENGE);
});
it('MCP-P08 — a session created via JWT rejects resumption by an OAuth client', async () => {
const { user } = createUser(testDb);
const sessionId = await createSession(generateToken(user.id));
const { accessToken } = mintOauthToken(user.id, MCP_AUDIENCE);
const res = await request(app)
.post('/mcp')
.set('Authorization', `Bearer ${accessToken}`)
.set('mcp-session-id', sessionId)
.send({ jsonrpc: '2.0', method: 'tools/list', id: 2 });
expect(res.status).toBe(403);
expect(res.body).toEqual({ error: 'Session was created with a different OAuth client' });
expect(res.headers['www-authenticate']).toBe(EXPECTED_CHALLENGE);
});
it('MCP-P09 — a static-token session carries the deprecation notice on the first tool call only', async () => {
const { user } = createUser(testDb);
const { rawToken } = createMcpToken(testDb, user.id);
const sessionId = await createSession(rawToken);
const callBody = { jsonrpc: '2.0', method: 'tools/call', id: 3, params: { name: 'list_trips', arguments: {} } };
const first = await request(app)
.post('/mcp')
.set('Authorization', `Bearer ${rawToken}`)
.set('mcp-session-id', sessionId)
.set('Accept', 'application/json, text/event-stream')
.send(callBody);
expect(first.status).toBe(200);
expect(first.text).toContain('Deprecated authentication');
const second = await request(app)
.post('/mcp')
.set('Authorization', `Bearer ${rawToken}`)
.set('mcp-session-id', sessionId)
.set('Accept', 'application/json, text/event-stream')
.send({ ...callBody, id: 4 });
expect(second.status).toBe(200);
expect(second.text).not.toContain('Deprecated authentication');
});
it('MCP-P10 — /mcp bodies stay raw: an initialize payload over the global 100kb cap succeeds', async () => {
const { user } = createUser(testDb);
const big = {
...initBody,
params: { ...initBody.params, clientInfo: { name: 'x'.repeat(150 * 1024), version: '1' } },
};
const res = await request(app)
.post('/mcp')
.set('Authorization', `Bearer ${generateToken(user.id)}`)
.set('Accept', 'application/json, text/event-stream')
.send(big);
expect(res.status).toBe(200);
expect(res.headers['mcp-session-id']).toBeTruthy();
});
it('MCP-P11 — the global 100kb JSON cap still guards every other route', async () => {
const res = await request(app)
.post('/api/auth/login')
.set('Content-Type', 'application/json')
.send(JSON.stringify({ username: 'x'.repeat(150 * 1024), password: 'y' }));
expect(res.status).toBe(413);
});
it('MCP-P12 — malformed JSON on /mcp gets the SDK JSON-RPC parse error, not body-parser 400', async () => {
const { user } = createUser(testDb);
const res = await request(app)
.post('/mcp')
.set('Authorization', `Bearer ${generateToken(user.id)}`)
.set('Accept', 'application/json, text/event-stream')
.set('Content-Type', 'application/json')
.send('{ this is not json');
expect(res.status).toBe(400);
expect(res.body.jsonrpc).toBe('2.0');
expect(res.body.error.code).toBe(-32700);
});
});
describe('MCP rate limiting', () => {
it('MCP-005 — requests below limit succeed', async () => {
const { user } = createUser(testDb);