mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 17:41:51 +00:00
refactor(server): serve /mcp from a Nest controller; delete auth, audit, addons and oauth bridges
This commit is contained in:
@@ -14,7 +14,6 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
|
||||
import { Client } from '@modelcontextprotocol/sdk/client/index';
|
||||
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory';
|
||||
import { registerTools } from '../../src/mcp/tools';
|
||||
import { setMcpRegistry } from '../../src/mcp/registry-handoff';
|
||||
import { createMcpTestRegistry } from './mcp-test-controllers';
|
||||
|
||||
export interface McpHarness {
|
||||
@@ -48,12 +47,11 @@ export async function createMcpHarness(options: McpHarnessOptions): Promise<McpH
|
||||
const server = new McpServer({ name: 'trek-test', version: '1.0.0' });
|
||||
|
||||
if (withTools) {
|
||||
// In production bootstrap.ts hands the Nest-discovered registry to
|
||||
// registerTools after app.init(); the harness has no Nest app, so it
|
||||
// In production the transport service passes its injected
|
||||
// McpRegistryService to registerTools; the harness has no Nest app, so it
|
||||
// builds the same registry by hand (see mcp-test-controllers.ts).
|
||||
// registerTools' own ctx construction stays exercised.
|
||||
setMcpRegistry(createMcpTestRegistry());
|
||||
registerTools(server, userId, scopes ?? null, isStaticToken, getDeprecationNotice);
|
||||
registerTools(createMcpTestRegistry(), server, userId, scopes ?? null, isStaticToken, getDeprecationNotice);
|
||||
}
|
||||
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
/**
|
||||
* addons.bridge delegation — one case per bridged export (the permissions
|
||||
* bridge-test precedent). The bridge constructs a module-level AddonsService
|
||||
* over the reinitialize-proof db Proxy, so a real in-memory SQLite exercises
|
||||
* the byte-identical SQL relocated from services/adminService (`admin-1`).
|
||||
* The bag-tracking/collab polarity quirks are pinned on the service itself
|
||||
* (addons.service.test.ts) — those reads are no longer bridged.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeAll } from 'vitest';
|
||||
|
||||
// ── DB setup ──────────────────────────────────────────────────────────────────
|
||||
// The db/database mock builds a real in-memory SQLite; the test body reaches it
|
||||
// straight through the mocked `db` export (no hoisted require needed).
|
||||
|
||||
vi.mock('../../../src/db/database', async () => {
|
||||
const { default: Database } = await import('better-sqlite3');
|
||||
const db = new Database(':memory:');
|
||||
db.exec('PRAGMA journal_mode = WAL');
|
||||
db.exec('PRAGMA foreign_keys = ON');
|
||||
db.exec('PRAGMA busy_timeout = 5000');
|
||||
return { db, closeDb: () => {}, reinitialize: () => {} };
|
||||
});
|
||||
|
||||
import { db as testDb } from '../../../src/db/database';
|
||||
import { createTables } from '../../../src/db/schema';
|
||||
import { runMigrations } from '../../../src/db/migrations';
|
||||
import { isAddonEnabled } from '../../../src/nest/addons/addons.bridge';
|
||||
|
||||
beforeAll(() => {
|
||||
createTables(testDb);
|
||||
runMigrations(testDb);
|
||||
});
|
||||
|
||||
describe('addons.bridge', () => {
|
||||
it('isAddonEnabled reflects the addons row and is false for an unknown id', () => {
|
||||
testDb
|
||||
.prepare("INSERT OR REPLACE INTO addons (id, name, type, icon, enabled, sort_order) VALUES ('test-addon', 'Test', 'page', 'star', 1, 99)")
|
||||
.run();
|
||||
expect(isAddonEnabled('test-addon')).toBe(true);
|
||||
testDb.prepare('UPDATE addons SET enabled = 0 WHERE id = ?').run('test-addon');
|
||||
expect(isAddonEnabled('test-addon')).toBe(false);
|
||||
expect(isAddonEnabled('no-such-addon')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -42,7 +42,6 @@ import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import { AuditService } from '../../../src/nest/audit/audit.service';
|
||||
import { getClientIp } from '../../../src/nest/audit/client-ip';
|
||||
import { logInfo, logDebug, logError } from '../../../src/nest/audit/audit-log.logger';
|
||||
import { writeAudit as bridgeWriteAudit, getClientIp as bridgeGetClientIp } from '../../../src/nest/audit/audit.bridge';
|
||||
|
||||
const svc = new AuditService(new DatabaseService(testDb));
|
||||
|
||||
@@ -180,17 +179,3 @@ describe('writeAudit', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ── audit.bridge delegation ───────────────────────────────────────────────────
|
||||
|
||||
describe('audit.bridge delegation', () => {
|
||||
it('AUDIT-SVC-015: writeAudit writes a real row through the module-level instance', () => {
|
||||
seedUser(1, 'a@b.c');
|
||||
bridgeWriteAudit({ userId: 1, action: 'user.login', ip: '5.5.5.5' });
|
||||
const row = testDb.prepare('SELECT user_id, action, ip FROM audit_log').get();
|
||||
expect(row).toEqual({ user_id: 1, action: 'user.login', ip: '5.5.5.5' });
|
||||
});
|
||||
|
||||
it('AUDIT-SVC-016: getClientIp is the same pure helper', () => {
|
||||
expect(bridgeGetClientIp).toBe(getClientIp);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -67,7 +67,6 @@ import { resetTestDb } from '../../helpers/test-db';
|
||||
import { createUser, createAdmin, createInviteToken, createTrip, createPlace, createReservation } from '../../helpers/factories';
|
||||
import { AuthService } from '../../../src/nest/auth/auth.service';
|
||||
import { TokenService } from '../../../src/nest/tokens/token.service';
|
||||
import * as authBridge from '../../../src/nest/auth/auth.bridge';
|
||||
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
|
||||
import { BudgetService } from '../../../src/nest/budget/budget.service';
|
||||
import { ExchangeRatesService } from '../../../src/nest/budget/exchange-rates.service';
|
||||
@@ -928,23 +927,24 @@ describe('auth quirk fixes', () => {
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// auth.bridge.ts delegation (coverage gate: one case per bridge export)
|
||||
// MCP-token verification round-trips (was the auth.bridge delegation block;
|
||||
// the MCP transport now injects TokenService/AuthService directly)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('auth.bridge delegation', () => {
|
||||
describe('MCP token verification round-trips', () => {
|
||||
it('AUTH-BR-002: verifyMcpToken resolves a freshly created token to its user', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = tokens.createMcpToken(user.id, 'bridge-case');
|
||||
const raw = (created.token as { raw_token: string }).raw_token;
|
||||
const resolved = authBridge.verifyMcpToken(raw);
|
||||
const resolved = tokens.verifyMcpToken(raw);
|
||||
expect(resolved?.id).toBe(user.id);
|
||||
expect(authBridge.verifyMcpToken('trek_no_such_token')).toBeNull();
|
||||
expect(tokens.verifyMcpToken('trek_no_such_token')).toBeNull();
|
||||
});
|
||||
|
||||
it('AUTH-BR-003: verifyJwtToken round-trips a service-minted token through the pv gate', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const token = svc.generateToken({ id: user.id });
|
||||
expect(authBridge.verifyJwtToken(token)?.id).toBe(user.id);
|
||||
expect(authBridge.verifyJwtToken('not-a-jwt')).toBeNull();
|
||||
expect(svc.verifyJwtToken(token)?.id).toBe(user.id);
|
||||
expect(svc.verifyJwtToken('not-a-jwt')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
|
||||
const h = vi.hoisted(() => ({
|
||||
getMcpSafeUrl: vi.fn(() => 'https://trek.example.test'),
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/app-config', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../../src/app-config')>();
|
||||
return { ...actual, getMcpSafeUrl: h.getMcpSafeUrl };
|
||||
});
|
||||
vi.mock('../../../src/db/database', () => ({ db: {}, closeDb: () => {}, reinitialize: () => {} }));
|
||||
|
||||
import {
|
||||
McpTransportService,
|
||||
armSseKeepalive,
|
||||
countSessionsForUser,
|
||||
jsonRpcError,
|
||||
setAuthChallenge,
|
||||
} from '../../../src/nest/mcp-transport/mcp-transport.service';
|
||||
import { McpTransportController } from '../../../src/nest/mcp-transport/mcp-transport.controller';
|
||||
import { sessions } from '../../../src/mcp/sessionManager';
|
||||
import { KEEPALIVE_MS } from '../../../src/mcp';
|
||||
import type { AuthService } from '../../../src/nest/auth/auth.service';
|
||||
import type { TokenService } from '../../../src/nest/tokens/token.service';
|
||||
import type { OauthService } from '../../../src/nest/oauth/oauth.service';
|
||||
import type { AddonsService } from '../../../src/nest/addons/addons.service';
|
||||
import type { McpRegistryService } from '@trek/nest-mcp';
|
||||
import { IS_PUBLIC } from '../../../src/nest/auth/public.decorator';
|
||||
|
||||
const user = { id: 7, username: 'u', email: 'u@example.com', role: 'user' as const };
|
||||
|
||||
function makeService(overrides: {
|
||||
auth?: Partial<Record<'verifyJwtToken', unknown>>;
|
||||
tokens?: Partial<Record<'verifyMcpToken', unknown>>;
|
||||
oauth?: Partial<Record<'getUserByAccessToken', unknown>>;
|
||||
addons?: Partial<Record<'isAddonEnabled', unknown>>;
|
||||
} = {}) {
|
||||
const auth = { verifyJwtToken: vi.fn(() => null), ...overrides.auth } as unknown as AuthService;
|
||||
const tokens = { verifyMcpToken: vi.fn(() => null), ...overrides.tokens } as unknown as TokenService;
|
||||
const oauth = { getUserByAccessToken: vi.fn(() => null), ...overrides.oauth } as unknown as OauthService;
|
||||
const addons = { isAddonEnabled: vi.fn(() => true), ...overrides.addons } as unknown as AddonsService;
|
||||
const registry = { attach: vi.fn() } as unknown as McpRegistryService;
|
||||
return { svc: new McpTransportService(auth, tokens, oauth, addons, registry), auth, tokens, oauth, addons };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
h.getMcpSafeUrl.mockReturnValue('https://trek.example.test');
|
||||
});
|
||||
|
||||
describe('jsonRpcError', () => {
|
||||
it('MCPT-001: shapes a valid JSON-RPC 2.0 error frame', () => {
|
||||
expect(jsonRpcError('nope')).toEqual({ jsonrpc: '2.0', error: { code: -32000, message: 'nope' }, id: null });
|
||||
expect(jsonRpcError('custom', -32601)).toEqual({ jsonrpc: '2.0', error: { code: -32601, message: 'custom' }, id: null });
|
||||
});
|
||||
});
|
||||
|
||||
describe('setAuthChallenge', () => {
|
||||
it('MCPT-002: writes the RFC 9728 path-suffixed challenge with the given error code', () => {
|
||||
const res = { set: vi.fn() };
|
||||
setAuthChallenge(res as never);
|
||||
expect(res.set).toHaveBeenCalledWith(
|
||||
'WWW-Authenticate',
|
||||
'Bearer realm="TREK MCP", resource_metadata="https://trek.example.test/.well-known/oauth-protected-resource/mcp", error="invalid_token"',
|
||||
);
|
||||
setAuthChallenge(res as never, 'insufficient_scope');
|
||||
expect(res.set).toHaveBeenLastCalledWith('WWW-Authenticate', expect.stringContaining('error="insufficient_scope"'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('countSessionsForUser', () => {
|
||||
afterEach(() => sessions.clear());
|
||||
|
||||
it('MCPT-003: counts only live sessions belonging to the user', () => {
|
||||
const now = Date.now();
|
||||
const fake = (userId: number, lastActivity: number) =>
|
||||
({ userId, lastActivity, server: {}, transport: {}, scopes: null, clientId: null, isStaticToken: false }) as never;
|
||||
sessions.set('a', fake(7, now));
|
||||
sessions.set('b', fake(7, now - 1));
|
||||
sessions.set('c', fake(8, now));
|
||||
sessions.set('d', fake(7, 0)); // long expired
|
||||
expect(countSessionsForUser(7)).toBe(2);
|
||||
expect(countSessionsForUser(9)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('armSseKeepalive', () => {
|
||||
beforeEach(() => vi.useFakeTimers());
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
function makeRes(contentType: string) {
|
||||
return {
|
||||
headersSent: true,
|
||||
writableEnded: false,
|
||||
destroyed: false,
|
||||
getHeader: vi.fn(() => contentType),
|
||||
write: vi.fn(),
|
||||
once: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
it('MCPT-004: pings an open event stream and touches the session', () => {
|
||||
const res = makeRes('text/event-stream');
|
||||
const touch = vi.fn();
|
||||
armSseKeepalive(res as never, touch);
|
||||
vi.advanceTimersByTime(KEEPALIVE_MS + 5);
|
||||
expect(res.write).toHaveBeenCalledWith(': keepalive\n\n');
|
||||
expect(touch).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('MCPT-005: stops as soon as the response is not an open event stream', () => {
|
||||
const res = makeRes('application/json');
|
||||
armSseKeepalive(res as never, vi.fn());
|
||||
vi.advanceTimersByTime(KEEPALIVE_MS + 5);
|
||||
expect(res.write).not.toHaveBeenCalled();
|
||||
// Timer cleared: a second window writes nothing either.
|
||||
vi.advanceTimersByTime(KEEPALIVE_MS + 5);
|
||||
expect(res.write).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('MCPT-006: waits for headers before judging the stream', () => {
|
||||
const res = makeRes('text/event-stream');
|
||||
res.headersSent = false;
|
||||
armSseKeepalive(res as never, vi.fn());
|
||||
vi.advanceTimersByTime(KEEPALIVE_MS + 5);
|
||||
expect(res.write).not.toHaveBeenCalled();
|
||||
res.headersSent = true;
|
||||
vi.advanceTimersByTime(KEEPALIVE_MS + 5);
|
||||
expect(res.write).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('MCPT-007: clears its interval when the response closes', () => {
|
||||
const res = makeRes('text/event-stream');
|
||||
armSseKeepalive(res as never);
|
||||
expect(res.once).toHaveBeenCalledWith('close', expect.any(Function));
|
||||
});
|
||||
});
|
||||
|
||||
describe('McpTransportService.verifyToken', () => {
|
||||
it('MCPT-010: rejects a missing header, a schemeless token, and non-Bearer schemes', () => {
|
||||
const { svc } = makeService();
|
||||
expect(svc.verifyToken(undefined)).toBeNull();
|
||||
expect(svc.verifyToken('token-without-scheme')).toBeNull();
|
||||
expect(svc.verifyToken('Basic dXNlcjpwdw==')).toBeNull();
|
||||
expect(svc.verifyToken('Bearer ')).toBeNull();
|
||||
});
|
||||
|
||||
it('MCPT-011: trekoa_ tokens resolve through OauthService and enforce the RFC 8707 audience', () => {
|
||||
const info = { user, scopes: ['trips:read'], clientId: 'cid-1', audience: 'https://trek.example.test/mcp' };
|
||||
const { svc, oauth } = makeService({ oauth: { getUserByAccessToken: vi.fn(() => info) } });
|
||||
expect(svc.verifyToken('Bearer trekoa_x')).toEqual({
|
||||
user, scopes: ['trips:read'], clientId: 'cid-1', isStaticToken: false,
|
||||
});
|
||||
expect(oauth.getUserByAccessToken).toHaveBeenCalledWith('trekoa_x');
|
||||
|
||||
const wrongAudience = makeService({
|
||||
oauth: { getUserByAccessToken: vi.fn(() => ({ ...info, audience: 'https://other.example.com' })) },
|
||||
});
|
||||
expect(wrongAudience.svc.verifyToken('Bearer trekoa_x')).toBeNull();
|
||||
|
||||
const unknown = makeService();
|
||||
expect(unknown.svc.verifyToken('Bearer trekoa_dead')).toBeNull();
|
||||
});
|
||||
|
||||
it('MCPT-012: trek_ static tokens resolve through TokenService with full access + notice flag', () => {
|
||||
const { svc, tokens } = makeService({ tokens: { verifyMcpToken: vi.fn(() => user) } });
|
||||
expect(svc.verifyToken('Bearer trek_x')).toEqual({ user, scopes: null, clientId: null, isStaticToken: true });
|
||||
expect(tokens.verifyMcpToken).toHaveBeenCalledWith('trek_x');
|
||||
expect(makeService().svc.verifyToken('Bearer trek_dead')).toBeNull();
|
||||
});
|
||||
|
||||
it('MCPT-013: everything else falls back to the JWT path', () => {
|
||||
const { svc, auth } = makeService({ auth: { verifyJwtToken: vi.fn(() => user) } });
|
||||
expect(svc.verifyToken('Bearer some.jwt.token')).toEqual({ user, scopes: null, clientId: null, isStaticToken: false });
|
||||
expect(auth.verifyJwtToken).toHaveBeenCalledWith('some.jwt.token');
|
||||
expect(makeService().svc.verifyToken('Bearer not-a-jwt')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('McpTransportController', () => {
|
||||
it('MCPT-020: is a @Public controller on the /mcp path with the three transport verbs', () => {
|
||||
expect(Reflect.getMetadata('path', McpTransportController)).toBe('mcp');
|
||||
expect(Reflect.getMetadata(IS_PUBLIC, McpTransportController)).toBeTruthy();
|
||||
for (const method of ['post', 'get', 'delete'] as const) {
|
||||
expect(typeof McpTransportController.prototype[method]).toBe('function');
|
||||
}
|
||||
});
|
||||
|
||||
it('MCPT-021: every verb passes straight through to the service', async () => {
|
||||
const handle = vi.fn(async () => {});
|
||||
const ctrl = new McpTransportController({ handle } as unknown as McpTransportService);
|
||||
const req = {} as never;
|
||||
const res = {} as never;
|
||||
await ctrl.post(req, res);
|
||||
await ctrl.get(req, res);
|
||||
await ctrl.delete(req, res);
|
||||
expect(handle).toHaveBeenCalledTimes(3);
|
||||
expect(handle).toHaveBeenCalledWith(req, res);
|
||||
});
|
||||
});
|
||||
@@ -64,7 +64,6 @@ import { AuditService } from '../../../src/nest/audit/audit.service';
|
||||
import type { AddonsService } from '../../../src/nest/addons/addons.service';
|
||||
import { getMcpSafeUrl } from '../../../src/app-config';
|
||||
import { ADDON_IDS } from '../../../src/addons';
|
||||
import * as bridge from '../../../src/nest/oauth/oauth.bridge';
|
||||
import { MAX_PENDING_CODES, sweepPendingCodes } from '../../../src/nest/oauth/oauth.pending-codes';
|
||||
|
||||
const dbs = new DatabaseService(testDb);
|
||||
@@ -1110,20 +1109,7 @@ describe('branches the legacy suite could not reach', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('oauth.bridge delegation', () => {
|
||||
// The bridge is down to its one surviving export — what the MCP transport's
|
||||
// token verification reaches outside the container. The SDK provider paths
|
||||
// that used to be bridged live behind the container now (oauth-sdk.provider).
|
||||
it('verifies a container-issued token through the bridge instance', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = makeClient(user.id);
|
||||
const clientId = (created.client as { client_id: string }).client_id;
|
||||
|
||||
const tokens = issueTokens(clientId, user.id, ['trips:read']);
|
||||
|
||||
expect(bridge.getUserByAccessToken(tokens.access_token)?.user.id).toBe(user.id);
|
||||
});
|
||||
|
||||
describe('module-scoped OAuth state', () => {
|
||||
it('shares the pending-code map across service instances', () => {
|
||||
// The load-bearing invariant: the consent controller writes the code through
|
||||
// the DI singleton, the SDK exchange path reads it back. The map is module-
|
||||
|
||||
@@ -6,13 +6,10 @@ const h = vi.hoisted(() => ({
|
||||
verifyJwtAndLoadUser: vi.fn(),
|
||||
dbPrepare: vi.fn(),
|
||||
existsSync: vi.fn(),
|
||||
// Tagged handler so we can identify which route registration received it.
|
||||
mcpHandler: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/nest/auth/jwt-verify', () => ({ verifyJwtAndLoadUser: h.verifyJwtAndLoadUser }));
|
||||
vi.mock('../../../src/db/database', () => ({ db: { prepare: h.dbPrepare } }));
|
||||
vi.mock('../../../src/mcp', () => ({ mcpHandler: h.mcpHandler }));
|
||||
|
||||
vi.mock('node:fs', async (orig) => {
|
||||
const real = (await orig()) as Record<string, unknown>;
|
||||
@@ -21,7 +18,6 @@ vi.mock('node:fs', async (orig) => {
|
||||
|
||||
import {
|
||||
applyPlatformUploads,
|
||||
applyPlatformTransport,
|
||||
applyPlatformSpa,
|
||||
applyPlatformStatic,
|
||||
} from '../../../src/nest/platform/platform.routes';
|
||||
@@ -202,21 +198,6 @@ describe('applyPlatformUploads', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('applyPlatformTransport', () => {
|
||||
function build() {
|
||||
const { app, calls } = fakeApp();
|
||||
applyPlatformTransport(app);
|
||||
return calls;
|
||||
}
|
||||
|
||||
it('mounts the MCP handler on POST/GET/DELETE /mcp', () => {
|
||||
const calls = build();
|
||||
expect(calls.find((c) => c.method === 'post' && c.path === '/mcp')!.handlers[0]).toBe(h.mcpHandler);
|
||||
expect(calls.find((c) => c.method === 'get' && c.path === '/mcp')!.handlers[0]).toBe(h.mcpHandler);
|
||||
expect(calls.find((c) => c.method === 'delete' && c.path === '/mcp')!.handlers[0]).toBe(h.mcpHandler);
|
||||
});
|
||||
});
|
||||
|
||||
describe('applyPlatformStatic', () => {
|
||||
const original = process.env.NODE_ENV;
|
||||
afterEach(() => { process.env.NODE_ENV = original; });
|
||||
|
||||
Reference in New Issue
Block a user