test(db): run the MCP and OAuth suites on the real database module

They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well. The OAuth service they drove by hand over a second ORM on the
SQLite handle is now the container's own, called in a request context.

The MCP audit cases wait for the mcp.tool_call row: the transport writes
it without awaiting it, so on Postgres it can land after the response.
This commit is contained in:
Maurice
2026-11-17 17:44:13 +01:00
parent 927fcab67f
commit 6e7336b8d7
6 changed files with 215 additions and 264 deletions
-3
View File
@@ -58,12 +58,9 @@
"tests/integration/legacy-upgrade-v205.test.ts": 1,
"tests/integration/legacy-upgrade-v242.test.ts": 1,
"tests/integration/legacy-upgrade-v244.test.ts": 1,
"tests/integration/mcp.test.ts": 1,
"tests/integration/memories-immich.test.ts": 1,
"tests/integration/memories-synology.test.ts": 1,
"tests/integration/memories-unified.test.ts": 1,
"tests/integration/oauth-authorize.test.ts": 1,
"tests/integration/oauth.test.ts": 1,
"tests/integration/plugins/boot-registry-order.test.ts": 1,
"tests/integration/plugins/plugin-runtime.test.ts": 1,
"tests/integration/scheduler-gate.test.ts": 1,
@@ -10,9 +10,6 @@
"tests/helpers/test-addons.ts": 1,
"tests/helpers/test-uow.ts": 3,
"tests/integration/dayReorder.test.ts": 3,
"tests/integration/mcp.test.ts": 2,
"tests/integration/oauth-authorize.test.ts": 2,
"tests/integration/oauth.test.ts": 2,
"tests/integration/plugins/boot-registry-order.test.ts": 7,
"tests/integration/plugins/plugin-runtime.task2-conversion.test.ts": 17,
"tests/integration/plugins/plugin-scheduler-sweep.test.ts": 5,
+120 -115
View File
@@ -7,30 +7,22 @@
*/
import { getMcpSafeUrl } from '../../src/app-config';
import { buildApp } from '../../src/bootstrap';
import { db as testDb } from '../../src/db/database';
import { SqliteEngine } from '../../src/db/engine/sqlite/sqlite-engine';
import { AuditLog } from '../../src/db/entities/AuditLog.entity';
import { McpTokens } from '../../src/db/entities/McpTokens.entity';
import { OauthClients } from '../../src/db/entities/OauthClients.entity';
import { OauthConsents } from '../../src/db/entities/OauthConsents.entity';
import { OauthTokens } from '../../src/db/entities/OauthTokens.entity';
import { Users } from '../../src/db/entities/Users.entity';
import { closeMcpSessions } from '../../src/mcp/index';
import { sessions } from '../../src/mcp/sessionManager';
import type { McpDynamicTool } from '../../src/nest-mcp';
import { AuditService } from '../../src/nest/audit/audit.service';
import { UnitOfWork } from '../../src/nest/database/unit-of-work';
import { CimdClientResolver } from '../../src/nest/oauth/oauth-cimd';
import { withRequestContext } from '../../src/nest/database/request-context';
import { OauthService } from '../../src/nest/oauth/oauth.service';
import { setPluginMcpToolSource } from '../../src/plugin-mcp-tools';
import { generateToken } from '../helpers/auth';
import { createUser } from '../helpers/factories';
import { createMcpToken } from '../helpers/factories';
import { countRows, deleteRows, findRow, findRows } from '../helpers/factories/rows';
import { setAddonEnabled } from '../helpers/factories/settings';
import { createTestAddonsService } from '../helpers/test-addons';
import { resetTestDb, resetRateLimits } from '../helpers/test-db';
import { createTestOrm, type TestOrm } from '../helpers/test-orm';
import { makeMcpToken } from '../helpers/factories/tokens';
import { makeUser } from '../helpers/factories/users';
import { resetDatabase } from '../helpers/reset-database';
import { resetRateLimits } from '../helpers/test-db';
import { MikroORM } from '@mikro-orm/core';
import type { INestApplication } from '@nestjs/common';
@@ -38,11 +30,6 @@ import type { Application } from 'express';
import request from 'supertest';
import { describe, it, expect, vi, beforeAll, beforeEach, afterEach, afterAll } from 'vitest';
vi.mock('../../src/db/database', async () => {
const { createSnapshotTestDb, buildDbMock } = await import('../helpers/db-mock');
return buildDbMock(createSnapshotTestDb());
});
let oauthSvc: OauthService;
/** Mint a trekoa_ access token for the user via a fresh OAuth client. */
@@ -51,17 +38,27 @@ async function mintOauthToken(
audience: string | null,
scopes: string[] = ['trips:read'],
): Promise<{ accessToken: string; clientId: string }> {
const created = await oauthSvc.createOAuthClient(
userId,
'MCP Test Client',
['https://client.example.com/cb'],
scopes,
const created = await withRequestContext(orm, () =>
oauthSvc.createOAuthClient(userId, 'MCP Test Client', ['https://client.example.com/cb'], scopes),
);
const clientId = (created.client as { client_id: string }).client_id;
const tokens = await oauthSvc.issueTokens(clientId, userId, scopes, null, audience);
const tokens = await withRequestContext(orm, () => oauthSvc.issueTokens(clientId, userId, scopes, null, audience));
return { accessToken: tokens.access_token, clientId };
}
/**
* The mcp.tool_call audit rows, once the first has landed. The transport
* writes the row without awaiting it (the registry cannot await its onInvoke
* seam), so on a database over the network it can land after the response.
*/
function toolCallAuditRows() {
return vi.waitFor(async () => {
const rows = await findRows(orm, AuditLog, { action: 'mcp.tool_call' });
if (rows.length === 0) throw new Error('no mcp.tool_call audit row yet');
return rows;
});
}
/** /mcp answers as SSE, so the JSON-RPC payload rides a `data:` line. */
function rpcResult(text: string): { tools?: Array<{ name: string; description?: string }> } {
const line = text.split('\n').find((l) => l.startsWith('data:'));
@@ -74,33 +71,23 @@ const EXPECTED_CHALLENGE = `Bearer realm="TREK MCP", resource_metadata="${getMcp
let nestApp: INestApplication;
let app: Application;
let t: TestOrm;
let orm: MikroORM;
beforeAll(async () => {
nestApp = await buildApp();
app = nestApp.getHttpAdapter().getInstance();
t = await createTestOrm(testDb);
oauthSvc = new OauthService(
t.repo(OauthClients),
t.repo(OauthTokens),
t.repo(OauthConsents),
await createTestAddonsService(testDb),
new AuditService(t.repo(AuditLog), t.repo(Users)),
new UnitOfWork(t.em, new SqliteEngine()),
nestApp.get(CimdClientResolver),
);
orm = nestApp.get(MikroORM);
oauthSvc = nestApp.get(OauthService);
});
beforeEach(async () => {
resetTestDb(testDb);
await resetDatabase(orm);
await resetRateLimits(nestApp);
});
afterAll(async () => {
closeMcpSessions();
await nestApp.close();
await t.close();
testDb.close();
});
describe('MCP authentication', () => {
@@ -126,11 +113,11 @@ describe('MCP authentication', () => {
describe('MCP session init', () => {
it('MCP-002 — POST /mcp with valid JWT passes auth check (may fail if addon disabled)', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const token = generateToken(user.id);
// Enable MCP addon in test DB
await setAddonEnabled(t, 'mcp', true);
await setAddonEnabled(orm, 'mcp', true);
const res = await request(app)
.post('/mcp')
@@ -147,10 +134,10 @@ describe('MCP session init', () => {
});
it('MCP-003 — DELETE /mcp with unknown session returns 404', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const token = generateToken(user.id);
await setAddonEnabled(t, 'mcp', true);
await setAddonEnabled(orm, 'mcp', true);
const res = await request(app)
.delete('/mcp')
@@ -160,7 +147,7 @@ describe('MCP session init', () => {
});
it('MCP-004 — POST /mcp with invalid JWT returns 401 (when addon enabled)', async () => {
await setAddonEnabled(t, 'mcp', true);
await setAddonEnabled(orm, 'mcp', true);
const res = await request(app)
.post('/mcp')
@@ -172,9 +159,9 @@ describe('MCP session init', () => {
describe('MCP API token auth', () => {
it('MCP-002 — POST /mcp with valid trek_ API token authenticates successfully', async () => {
const { user } = createUser(testDb);
const { rawToken } = createMcpToken(testDb, user.id);
await setAddonEnabled(t, 'mcp', true);
const { user } = await makeUser(orm);
const { rawToken } = await makeMcpToken(orm, user.id);
await setAddonEnabled(orm, 'mcp', true);
const res = await request(app)
.post('/mcp')
@@ -190,11 +177,14 @@ describe('MCP API token auth', () => {
});
it('MCP-002 — last_used_at is updated on token use', async () => {
const { user } = createUser(testDb);
const { rawToken, id: tokenId } = createMcpToken(testDb, user.id);
await setAddonEnabled(t, 'mcp', true);
const { user } = await makeUser(orm);
const {
rawToken,
token: { id: tokenId },
} = await makeMcpToken(orm, user.id);
await setAddonEnabled(orm, 'mcp', true);
const before = (await findRow(t, McpTokens, { id: tokenId }))?.last_used_at;
const before = (await findRow(orm, McpTokens, { id: tokenId }))?.last_used_at;
await request(app)
.post('/mcp')
@@ -207,13 +197,13 @@ describe('MCP API token auth', () => {
params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'test', version: '1' } },
});
const after = (await findRow(t, McpTokens, { id: tokenId }))?.last_used_at;
const after = (await findRow(orm, McpTokens, { id: tokenId }))?.last_used_at;
expect(after).not.toBeNull();
expect(after).not.toBe(before);
});
it('MCP — POST /mcp with unknown trek_ token returns 401', async () => {
await setAddonEnabled(t, 'mcp', true);
await setAddonEnabled(orm, 'mcp', true);
const res = await request(app)
.post('/mcp')
@@ -223,7 +213,7 @@ describe('MCP API token auth', () => {
});
it('MCP — POST /mcp with no Authorization header returns 401', async () => {
await setAddonEnabled(t, 'mcp', true);
await setAddonEnabled(orm, 'mcp', true);
const res = await request(app).post('/mcp').send({ jsonrpc: '2.0', method: 'initialize', id: 1 });
expect(res.status).toBe(401);
@@ -250,8 +240,8 @@ describe('MCP session management', () => {
}
it('MCP-003 — at the session cap, the coldest session is evicted rather than the request refused', async () => {
const { user } = createUser(testDb);
await setAddonEnabled(t, 'mcp', true);
const { user } = await makeUser(orm);
await setAddonEnabled(orm, 'mcp', true);
const sessionsForUser = () => [...sessions.values()].filter((s) => s.userId === user.id).length;
@@ -271,8 +261,8 @@ describe('MCP session management', () => {
});
it('MCP-006 — initializes that race past the cap check are trimmed when they register', async () => {
const { user } = createUser(testDb);
await setAddonEnabled(t, 'mcp', true);
const { user } = await makeUser(orm);
await setAddonEnabled(orm, 'mcp', true);
const sessionsForUser = () => [...sessions.values()].filter((s) => s.userId === user.id).length;
@@ -308,8 +298,8 @@ describe('MCP session management', () => {
});
it('MCP — session resumption with valid mcp-session-id', async () => {
const { user } = createUser(testDb);
await setAddonEnabled(t, 'mcp', true);
const { user } = await makeUser(orm);
await setAddonEnabled(orm, 'mcp', true);
const sessionId = await createSession(user.id);
const token = generateToken(user.id);
@@ -323,9 +313,9 @@ describe('MCP session management', () => {
});
it('MCP — session belongs to different user returns 403', async () => {
const { user: user1 } = createUser(testDb);
const { user: user2 } = createUser(testDb);
await setAddonEnabled(t, 'mcp', true);
const { user: user1 } = await makeUser(orm);
const { user: user2 } = await makeUser(orm);
await setAddonEnabled(orm, 'mcp', true);
const sessionId = await createSession(user1.id);
const token2 = generateToken(user2.id);
@@ -339,8 +329,8 @@ describe('MCP session management', () => {
});
it('MCP — a session-less non-initialize POST is rejected without registering a session', async () => {
const { user } = createUser(testDb);
await setAddonEnabled(t, 'mcp', true);
const { user } = await makeUser(orm);
await setAddonEnabled(orm, 'mcp', true);
const token = generateToken(user.id);
const before = sessions.size;
@@ -357,8 +347,8 @@ describe('MCP session management', () => {
});
it('MCP — initialize response exposes Mcp-Session-Id to browser-context clients', async () => {
const { user } = createUser(testDb);
await setAddonEnabled(t, 'mcp', true);
const { user } = await makeUser(orm);
await setAddonEnabled(orm, 'mcp', true);
const token = generateToken(user.id);
const res = await request(app)
@@ -381,8 +371,8 @@ describe('MCP session management', () => {
});
it('MCP — GET without mcp-session-id returns 400', async () => {
const { user } = createUser(testDb);
await setAddonEnabled(t, 'mcp', true);
const { user } = await makeUser(orm);
await setAddonEnabled(orm, 'mcp', true);
const token = generateToken(user.id);
const res = await request(app).get('/mcp').set('Authorization', `Bearer ${token}`);
@@ -409,7 +399,7 @@ describe('MCP transport parity pins (Nest-hosted /mcp)', () => {
}
beforeEach(async () => {
await setAddonEnabled(t, 'mcp', true);
await setAddonEnabled(orm, 'mcp', true);
});
// The source is process-level, so a test that installs one must not leak it
@@ -419,7 +409,7 @@ describe('MCP transport parity pins (Nest-hosted /mcp)', () => {
});
it('MCP-P01 — addon off answers 403 with the exact legacy body', async () => {
await setAddonEnabled(t, 'mcp', false);
await setAddonEnabled(orm, 'mcp', false);
const res = await request(app).post('/mcp').send(initBody);
expect(res.status).toBe(403);
expect(res.body).toEqual({ error: 'MCP is not enabled' });
@@ -440,7 +430,7 @@ describe('MCP transport parity pins (Nest-hosted /mcp)', () => {
});
it('MCP-P04 — a trekoa_ token with the wrong audience is rejected with a challenge', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const { accessToken } = await 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);
@@ -448,7 +438,7 @@ describe('MCP transport parity pins (Nest-hosted /mcp)', () => {
});
it('MCP-P05 — a trekoa_ token with the MCP audience authenticates', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const { accessToken } = await mintOauthToken(user.id, MCP_AUDIENCE);
const res = await request(app)
.post('/mcp')
@@ -460,7 +450,7 @@ describe('MCP transport parity pins (Nest-hosted /mcp)', () => {
});
it('MCP-P06 — resuming an unknown session answers the exact 404 body', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const res = await request(app)
.post('/mcp')
.set('Authorization', `Bearer ${generateToken(user.id)}`)
@@ -471,8 +461,8 @@ describe('MCP transport parity pins (Nest-hosted /mcp)', () => {
});
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 { user: owner } = await makeUser(orm);
const { user: intruder } = await makeUser(orm);
const sessionId = await createSession(generateToken(owner.id));
const res = await request(app)
@@ -486,7 +476,7 @@ describe('MCP transport parity pins (Nest-hosted /mcp)', () => {
});
it('MCP-P08 — a session created via JWT rejects resumption by an OAuth client', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const sessionId = await createSession(generateToken(user.id));
const { accessToken } = await mintOauthToken(user.id, MCP_AUDIENCE);
@@ -501,16 +491,22 @@ describe('MCP transport parity pins (Nest-hosted /mcp)', () => {
});
it('MCP-P08b — a narrower token cannot resume a session that was created with wider scopes', async () => {
const { user } = createUser(testDb);
const created = await oauthSvc.createOAuthClient(
user.id,
'Scope Test Client',
['https://client.example.com/cb'],
['trips:read', 'trips:write'],
const { user } = await makeUser(orm);
const created = await withRequestContext(orm, () =>
oauthSvc.createOAuthClient(
user.id,
'Scope Test Client',
['https://client.example.com/cb'],
['trips:read', 'trips:write'],
),
);
const clientId = (created.client as { client_id: string }).client_id;
const wide = await oauthSvc.issueTokens(clientId, user.id, ['trips:read', 'trips:write'], null, MCP_AUDIENCE);
const narrow = await oauthSvc.issueTokens(clientId, user.id, ['trips:read'], null, MCP_AUDIENCE);
const wide = await withRequestContext(orm, () =>
oauthSvc.issueTokens(clientId, user.id, ['trips:read', 'trips:write'], null, MCP_AUDIENCE),
);
const narrow = await withRequestContext(orm, () =>
oauthSvc.issueTokens(clientId, user.id, ['trips:read'], null, MCP_AUDIENCE),
);
const sessionId = await createSession(wide.access_token);
// The tool surface was registered from the wide set; resuming with the
@@ -526,16 +522,22 @@ describe('MCP transport parity pins (Nest-hosted /mcp)', () => {
});
it('MCP-P08c — the same scopes in a different order still resume', async () => {
const { user } = createUser(testDb);
const created = await oauthSvc.createOAuthClient(
user.id,
'Scope Order Client',
['https://client.example.com/cb'],
['trips:read', 'trips:write'],
const { user } = await makeUser(orm);
const created = await withRequestContext(orm, () =>
oauthSvc.createOAuthClient(
user.id,
'Scope Order Client',
['https://client.example.com/cb'],
['trips:read', 'trips:write'],
),
);
const clientId = (created.client as { client_id: string }).client_id;
const first = await oauthSvc.issueTokens(clientId, user.id, ['trips:read', 'trips:write'], null, MCP_AUDIENCE);
const reordered = await oauthSvc.issueTokens(clientId, user.id, ['trips:write', 'trips:read'], null, MCP_AUDIENCE);
const first = await withRequestContext(orm, () =>
oauthSvc.issueTokens(clientId, user.id, ['trips:read', 'trips:write'], null, MCP_AUDIENCE),
);
const reordered = await withRequestContext(orm, () =>
oauthSvc.issueTokens(clientId, user.id, ['trips:write', 'trips:read'], null, MCP_AUDIENCE),
);
const sessionId = await createSession(first.access_token);
const res = await request(app)
@@ -548,8 +550,8 @@ describe('MCP transport parity pins (Nest-hosted /mcp)', () => {
});
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 { user } = await makeUser(orm);
const { rawToken } = await makeMcpToken(orm, user.id);
const sessionId = await createSession(rawToken);
const callBody = { jsonrpc: '2.0', method: 'tools/call', id: 3, params: { name: 'list_trips', arguments: {} } };
@@ -573,10 +575,10 @@ describe('MCP transport parity pins (Nest-hosted /mcp)', () => {
});
it('MCP-P13 — an authorized tools/call writes exactly one mcp.tool_call audit row', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const { accessToken, clientId } = await mintOauthToken(user.id, MCP_AUDIENCE);
const sessionId = await createSession(accessToken);
await deleteRows(t, AuditLog, { action: 'mcp.tool_call' });
await deleteRows(orm, AuditLog, { action: 'mcp.tool_call' });
const call = await request(app)
.post('/mcp')
@@ -586,7 +588,7 @@ describe('MCP transport parity pins (Nest-hosted /mcp)', () => {
.send({ jsonrpc: '2.0', method: 'tools/call', id: 3, params: { name: 'list_trips', arguments: {} } });
expect(call.status).toBe(200);
const rows = await findRows(t, AuditLog, { action: 'mcp.tool_call' });
const rows = await toolCallAuditRows();
expect(rows).toHaveLength(1);
expect(rows[0].user_id).toBe(user.id);
expect(rows[0].resource).toBe('list_trips');
@@ -594,10 +596,10 @@ describe('MCP transport parity pins (Nest-hosted /mcp)', () => {
});
it('MCP-P14 — tools/list and resource reads write no mcp.tool_call rows', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const token = generateToken(user.id);
const sessionId = await createSession(token);
await deleteRows(t, AuditLog, { action: 'mcp.tool_call' });
await deleteRows(orm, AuditLog, { action: 'mcp.tool_call' });
const list = await request(app)
.post('/mcp')
@@ -615,7 +617,7 @@ describe('MCP transport parity pins (Nest-hosted /mcp)', () => {
.send({ jsonrpc: '2.0', method: 'resources/list', id: 3, params: {} });
expect(read.status).toBe(200);
expect(await countRows(t, AuditLog, { action: 'mcp.tool_call' })).toBe(0);
expect(await countRows(orm, AuditLog, { action: 'mcp.tool_call' })).toBe(0);
});
// ── plugin-contributed tools ──
@@ -635,7 +637,7 @@ describe('MCP transport parity pins (Nest-hosted /mcp)', () => {
});
it('MCP-P15 — a contributed tool colliding with a built-in never displaces it, and the session still serves', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
// list_trips is a real built-in; the contributor tries to take its name.
setPluginMcpToolSource(() => [
dynamicTool('list_trips', 'hijacked'),
@@ -665,7 +667,7 @@ describe('MCP transport parity pins (Nest-hosted /mcp)', () => {
});
it('MCP-P16 — a throwing tool source degrades the surface instead of the session', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
setPluginMcpToolSource(() => {
throw new Error('the plugin runtime is down');
});
@@ -687,11 +689,11 @@ describe('MCP transport parity pins (Nest-hosted /mcp)', () => {
});
it('MCP-P17 — a contributed tool call writes an mcp.tool_call audit row like any other', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
setPluginMcpToolSource(() => [dynamicTool('plugin_demo_echo', 'contributed')]);
const { accessToken, clientId } = await mintOauthToken(user.id, MCP_AUDIENCE, ['trips:read', 'plugins:use']);
const sessionId = await createSession(accessToken);
await deleteRows(t, AuditLog, { action: 'mcp.tool_call' });
await deleteRows(orm, AuditLog, { action: 'mcp.tool_call' });
const call = await request(app)
.post('/mcp')
@@ -703,7 +705,7 @@ describe('MCP transport parity pins (Nest-hosted /mcp)', () => {
// The audit seam is exactly why the source lives on McpAttachOptions rather
// than the host calling server.registerTool() itself.
const rows = await findRows(t, AuditLog, { action: 'mcp.tool_call' });
const rows = await toolCallAuditRows();
expect(rows).toHaveLength(1);
expect(rows[0].user_id).toBe(user.id);
expect(rows[0].resource).toBe('plugin_demo_echo');
@@ -711,7 +713,7 @@ describe('MCP transport parity pins (Nest-hosted /mcp)', () => {
});
it('MCP-P18 — a token without plugins:use is never shown a plugin tool', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
setPluginMcpToolSource(() => [dynamicTool('plugin_demo_echo', 'contributed')]);
// trips:read only. The declarative access marker on every contributed tool
// resolves through the same policy as a built-in's.
@@ -731,7 +733,7 @@ describe('MCP transport parity pins (Nest-hosted /mcp)', () => {
});
it('MCP-P10 — /mcp bodies stay raw: an initialize payload over the global 100kb cap succeeds', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const big = {
...initBody,
params: { ...initBody.params, clientInfo: { name: 'x'.repeat(150 * 1024), version: '1' } },
@@ -754,7 +756,7 @@ describe('MCP transport parity pins (Nest-hosted /mcp)', () => {
});
it('MCP-P12 — malformed JSON on /mcp gets the SDK JSON-RPC parse error, not body-parser 400', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const res = await request(app)
.post('/mcp')
.set('Authorization', `Bearer ${generateToken(user.id)}`)
@@ -769,8 +771,8 @@ describe('MCP transport parity pins (Nest-hosted /mcp)', () => {
describe('MCP rate limiting', () => {
it('MCP-005 — requests below limit succeed', async () => {
const { user } = createUser(testDb);
await setAddonEnabled(t, 'mcp', true);
const { user } = await makeUser(orm);
await setAddonEnabled(orm, 'mcp', true);
const token = generateToken(user.id);
// Set a very low rate limit via env for this test
@@ -825,10 +827,13 @@ describe('MCP bearer-token verification runs inside the HTTP request context (Pl
});
it('MCP-CTX-002: a repository read inside verifyMcpToken (the trek_ bearer-token branch) succeeds — the /mcp route already forks a request context before the auth step runs', async () => {
await setAddonEnabled(t, 'mcp', true);
const { user } = createUser(testDb);
const { rawToken, id: tokenId } = createMcpToken(testDb, user.id);
const before = (await findRow(t, McpTokens, { id: tokenId }))?.last_used_at;
await setAddonEnabled(orm, 'mcp', true);
const { user } = await makeUser(orm);
const {
rawToken,
token: { id: tokenId },
} = await makeMcpToken(orm, user.id);
const before = (await findRow(orm, McpTokens, { id: tokenId }))?.last_used_at;
expect(before).toBeNull();
const res = await request(app)
@@ -847,7 +852,7 @@ describe('MCP bearer-token verification runs inside the HTTP request context (Pl
// `findUserByHashAndKind` (TK13) then `touchLastUsedByHash` (TK14) —
// `last_used_at` moving is only possible if both reached the DB, which
// MCP-CTX-001 proves the ORM refuses outside a forked request context.
const after = (await findRow(t, McpTokens, { id: tokenId }))?.last_used_at;
const after = (await findRow(orm, McpTokens, { id: tokenId }))?.last_used_at;
expect(after).not.toBeNull();
expect(after).not.toBe(before);
});
@@ -9,23 +9,14 @@
* time under test here.
*/
import { buildApp } from '../../src/bootstrap';
import { db as testDb } from '../../src/db/database';
import { SqliteEngine } from '../../src/db/engine/sqlite/sqlite-engine';
import { Addons } from '../../src/db/entities/Addons.entity';
import { AuditLog } from '../../src/db/entities/AuditLog.entity';
import { OauthClients } from '../../src/db/entities/OauthClients.entity';
import { OauthConsents } from '../../src/db/entities/OauthConsents.entity';
import { OauthTokens } from '../../src/db/entities/OauthTokens.entity';
import { Users } from '../../src/db/entities/Users.entity';
import { AuditService } from '../../src/nest/audit/audit.service';
import { UnitOfWork } from '../../src/nest/database/unit-of-work';
import { CimdClientResolver } from '../../src/nest/oauth/oauth-cimd';
import { withRequestContext } from '../../src/nest/database/request-context';
import { OauthService } from '../../src/nest/oauth/oauth.service';
import { createUser } from '../helpers/factories';
import { upsertRow } from '../helpers/factories/rows';
import { createTestAddonsService } from '../helpers/test-addons';
import { resetTestDb, resetRateLimits } from '../helpers/test-db';
import { createTestOrm, type TestOrm } from '../helpers/test-orm';
import { makeUser } from '../helpers/factories/users';
import { resetDatabase } from '../helpers/reset-database';
import { resetRateLimits } from '../helpers/test-db';
import { MikroORM } from '@mikro-orm/core';
import type { INestApplication } from '@nestjs/common';
import crypto from 'crypto';
@@ -33,11 +24,6 @@ import type { Application } from 'express';
import request from 'supertest';
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
vi.mock('../../src/db/database', async () => {
const { createSnapshotTestDb, buildDbMock } = await import('../helpers/db-mock');
return buildDbMock(createSnapshotTestDb());
});
vi.mock('../../src/app-config', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../src/app-config')>();
return { ...actual, getMcpSafeUrl: () => 'https://trek.example.com' };
@@ -51,13 +37,13 @@ vi.mock('../../src/mcp/sessionManager', () => ({
// The consent controller writes pending codes through the container instance;
// the SDK-mounted authorize path reads them back. The map is module-scoped in
// oauth.pending-codes.ts, so a hand-built service instance shares it — the
// oauth.pending-codes.ts, so the container's service instance shares it — the
// same single-instance property the full auth-code loop below proves end-to-end.
let containerSideOauth: OauthService;
let nestApp: INestApplication;
let app: Application;
let t: TestOrm;
let orm: MikroORM;
function makePkce() {
const verifier = crypto.randomBytes(32).toString('base64url');
@@ -66,7 +52,7 @@ function makePkce() {
}
async function setMcpEnabled(enabled: boolean) {
await upsertRow(t, Addons, {
await upsertRow(orm, Addons, {
id: 'mcp',
name: 'MCP',
description: 'AI assistant integration',
@@ -90,28 +76,18 @@ async function registerClient(redirectUri = 'https://client.example.com/cb', sco
beforeAll(async () => {
nestApp = await buildApp();
app = nestApp.getHttpAdapter().getInstance();
t = await createTestOrm(testDb);
containerSideOauth = new OauthService(
t.repo(OauthClients),
t.repo(OauthTokens),
t.repo(OauthConsents),
await createTestAddonsService(testDb),
new AuditService(t.repo(AuditLog), t.repo(Users)),
new UnitOfWork(t.em, new SqliteEngine()),
nestApp.get(CimdClientResolver),
);
orm = nestApp.get(MikroORM);
containerSideOauth = nestApp.get(OauthService);
});
beforeEach(async () => {
resetTestDb(testDb);
await resetDatabase(orm);
await resetRateLimits(nestApp);
await setMcpEnabled(true);
});
afterAll(async () => {
await nestApp.close();
await t.close();
testDb.close();
});
describe('GET /oauth/authorize — SDK authorizationHandler over trekOAuthProvider', () => {
@@ -267,7 +243,7 @@ describe('GET /oauth/authorize — SDK authorizationHandler over trekOAuthProvid
});
it('AUTHZ-008 — full loop: register → authorize → consent-written code → token exchange', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const clientId = await registerClient();
const { verifier, challenge } = makePkce();
@@ -286,15 +262,17 @@ describe('GET /oauth/authorize — SDK authorizationHandler over trekOAuthProvid
// 2. the consent controller writes the code through the container
// singleton; the module-scoped pending-code map is what lets the
// SDK-side exchange see it.
const code = await containerSideOauth.createAuthCode({
clientId,
userId: user.id,
redirectUri: 'https://client.example.com/cb',
scopes: ['trips:read'],
resource: 'https://trek.example.com/mcp',
codeChallenge: challenge,
codeChallengeMethod: 'S256',
});
const code = await withRequestContext(orm, () =>
containerSideOauth.createAuthCode({
clientId,
userId: user.id,
redirectUri: 'https://client.example.com/cb',
scopes: ['trips:read'],
resource: 'https://trek.example.com/mcp',
codeChallenge: challenge,
codeChallengeMethod: 'S256',
}),
);
expect(code).toBeTruthy();
// 3. token exchange through the public token endpoint
+72 -95
View File
@@ -4,25 +4,17 @@
* and oauthApiRouter (/api/oauth/*).
*/
import { buildApp } from '../../src/bootstrap';
import { db as testDb } from '../../src/db/database';
import { SqliteEngine } from '../../src/db/engine/sqlite/sqlite-engine';
import { Addons } from '../../src/db/entities/Addons.entity';
import { AuditLog } from '../../src/db/entities/AuditLog.entity';
import { OauthClients } from '../../src/db/entities/OauthClients.entity';
import { OauthConsents } from '../../src/db/entities/OauthConsents.entity';
import { OauthTokens } from '../../src/db/entities/OauthTokens.entity';
import { Users } from '../../src/db/entities/Users.entity';
import { ALL_SCOPES } from '../../src/mcp/scopes';
import { AuditService } from '../../src/nest/audit/audit.service';
import { UnitOfWork } from '../../src/nest/database/unit-of-work';
import { CimdClientResolver } from '../../src/nest/oauth/oauth-cimd';
import { withRequestContext } from '../../src/nest/database/request-context';
import { OauthService } from '../../src/nest/oauth/oauth.service';
import { authCookie } from '../helpers/auth';
import { createUser } from '../helpers/factories';
import { updateRows, upsertRow } from '../helpers/factories/rows';
import { createTestAddonsService } from '../helpers/test-addons';
import { resetTestDb, resetRateLimits } from '../helpers/test-db';
import { createTestOrm, type TestOrm } from '../helpers/test-orm';
import { makeUser } from '../helpers/factories/users';
import { resetDatabase } from '../helpers/reset-database';
import { resetRateLimits } from '../helpers/test-db';
import { MikroORM } from '@mikro-orm/core';
import type { INestApplication } from '@nestjs/common';
import crypto from 'crypto';
@@ -30,11 +22,6 @@ import type { Application } from 'express';
import request from 'supertest';
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
vi.mock('../../src/db/database', async () => {
const { createSnapshotTestDb, buildDbMock } = await import('../helpers/db-mock');
return buildDbMock(createSnapshotTestDb());
});
vi.mock('../../src/app-config', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../src/app-config')>();
return { ...actual, getMcpSafeUrl: () => 'https://trek.example.com' };
@@ -55,15 +42,15 @@ let containerSideOauth: OauthService;
// Arrow wrappers rather than `.bind`: with `strictBindCallApply: false` a bound
// alias is typed `any`, which hides a missing `await` on the now-async methods.
const createAuthCode = (...args: Parameters<OauthService['createAuthCode']>) =>
containerSideOauth.createAuthCode(...args);
withRequestContext(orm, () => containerSideOauth.createAuthCode(...args));
const createOAuthClient = (...args: Parameters<OauthService['createOAuthClient']>) =>
containerSideOauth.createOAuthClient(...args);
withRequestContext(orm, () => containerSideOauth.createOAuthClient(...args));
const getUserByAccessToken = (...args: Parameters<OauthService['getUserByAccessToken']>) =>
containerSideOauth.getUserByAccessToken(...args);
withRequestContext(orm, () => containerSideOauth.getUserByAccessToken(...args));
let nestApp: INestApplication;
let app: Application;
let t: TestOrm;
let orm: MikroORM;
// PKCE helpers
function makePkce() {
@@ -77,7 +64,7 @@ function makePkce() {
// addons row, so driving the DB row keeps mcpEnabled() AND
// validateAuthorizeRequest()/token/revoke consistent from one source.
async function setMcpEnabled(enabled: boolean) {
await upsertRow(t, Addons, {
await upsertRow(orm, Addons, {
id: 'mcp',
name: 'MCP',
description: 'AI assistant integration',
@@ -91,28 +78,18 @@ async function setMcpEnabled(enabled: boolean) {
beforeAll(async () => {
nestApp = await buildApp();
app = nestApp.getHttpAdapter().getInstance();
t = await createTestOrm(testDb);
containerSideOauth = new OauthService(
t.repo(OauthClients),
t.repo(OauthTokens),
t.repo(OauthConsents),
await createTestAddonsService(testDb),
new AuditService(t.repo(AuditLog), t.repo(Users)),
new UnitOfWork(t.em, new SqliteEngine()),
nestApp.get(CimdClientResolver),
);
orm = nestApp.get(MikroORM);
containerSideOauth = nestApp.get(OauthService);
});
beforeEach(async () => {
resetTestDb(testDb);
await resetDatabase(orm);
await resetRateLimits(nestApp);
await setMcpEnabled(true);
});
afterAll(async () => {
await nestApp.close();
await t.close();
testDb.close();
});
// ─────────────────────────────────────────────────────────────────────────────
@@ -330,7 +307,7 @@ describe('POST /oauth/token — authorization_code grant', () => {
});
it('OAUTH-005 — invalid auth code returns 400 invalid_grant', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const clientResult = await createOAuthClient(user.id, 'TestApp', ['https://app.example.com/cb'], ['trips:read']);
const client = clientResult.client!;
@@ -347,7 +324,7 @@ describe('POST /oauth/token — authorization_code grant', () => {
});
it('OAUTH-006 — client_id mismatch returns 400 invalid_grant', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r1 = await createOAuthClient(user.id, 'App1', ['https://app1.example.com/cb'], ['trips:read']);
const r2 = await createOAuthClient(user.id, 'App2', ['https://app2.example.com/cb'], ['trips:read']);
const { verifier, challenge } = makePkce();
@@ -377,7 +354,7 @@ describe('POST /oauth/token — authorization_code grant', () => {
});
it('OAUTH-007 — redirect_uri mismatch returns 400 invalid_grant', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
const { verifier, challenge } = makePkce();
@@ -404,7 +381,7 @@ describe('POST /oauth/token — authorization_code grant', () => {
});
it('OAUTH-008 — wrong client_secret returns 401 invalid_client (timing-safe check)', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
const { verifier, challenge } = makePkce();
@@ -431,7 +408,7 @@ describe('POST /oauth/token — authorization_code grant', () => {
});
it('OAUTH-009 — PKCE failure returns 400 invalid_grant', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
const { challenge } = makePkce();
@@ -458,7 +435,7 @@ describe('POST /oauth/token — authorization_code grant', () => {
});
it('OAUTH-010 — happy path: exchange auth code for tokens', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
const { verifier, challenge } = makePkce();
@@ -503,7 +480,7 @@ describe('POST /oauth/token — refresh_token grant', () => {
});
it('OAUTH-012 — invalid refresh token returns 400 invalid_grant', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
const res = await request(app).post('/oauth/token').send({
@@ -517,7 +494,7 @@ describe('POST /oauth/token — refresh_token grant', () => {
});
it('OAUTH-013 — happy path: issue then refresh tokens', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
const { verifier, challenge } = makePkce();
@@ -582,7 +559,7 @@ describe('POST /oauth/revoke', () => {
});
it('OAUTH-016 — wrong client_secret returns 401 invalid_client', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
const res = await request(app)
@@ -593,7 +570,7 @@ describe('POST /oauth/revoke', () => {
});
it('OAUTH-017 — valid revoke returns 200 even for unknown token (RFC 7009)', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
const res = await request(app)
@@ -603,7 +580,7 @@ describe('POST /oauth/revoke', () => {
});
it('OAUTH-018 — happy path: issue token, revoke it, verify refresh no longer works', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
const { verifier, challenge } = makePkce();
@@ -665,7 +642,7 @@ describe('GET /api/oauth/authorize/validate', () => {
});
it('OAUTH-020 — returns 200 with valid:false for wrong response_type (authenticated)', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const { challenge } = makePkce();
const res = await request(app).get('/api/oauth/authorize/validate').set('Cookie', authCookie(user.id)).query({
response_type: 'token',
@@ -686,7 +663,7 @@ describe('GET /api/oauth/authorize/validate', () => {
// Before #2227 registration refused the URI outright; once it was accepted,
// this route still answered invalid_redirect_uri because it compared byte
// for byte while RFC 8252 §7.3 frees the port for loopback redirects.
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const { challenge } = makePkce();
const reg = await request(app)
.post('/oauth/register')
@@ -711,7 +688,7 @@ describe('GET /api/oauth/authorize/validate', () => {
});
it('OAUTH-2227E: the port is all that is free, so a different callback path is still refused', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const { challenge } = makePkce();
const reg = await request(app)
.post('/oauth/register')
@@ -746,7 +723,7 @@ describe('GET /api/oauth/authorize/validate', () => {
});
it('OAUTH-022 — returns 200 with valid:false for unknown client_id (authenticated)', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const { challenge } = makePkce();
const res = await request(app).get('/api/oauth/authorize/validate').set('Cookie', authCookie(user.id)).query({
response_type: 'code',
@@ -762,7 +739,7 @@ describe('GET /api/oauth/authorize/validate', () => {
});
it('OAUTH-023 — returns 200 with valid:false for mismatched redirect_uri (authenticated)', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
const { challenge } = makePkce();
@@ -780,7 +757,7 @@ describe('GET /api/oauth/authorize/validate', () => {
});
it('OAUTH-024 — returns 200 with valid:false for empty scope (authenticated)', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
const { challenge } = makePkce();
@@ -798,7 +775,7 @@ describe('GET /api/oauth/authorize/validate', () => {
});
it('OAUTH-025a — narrows scope to allowed intersection when client lacks some requested scopes (authenticated)', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
const { challenge } = makePkce();
@@ -817,7 +794,7 @@ describe('GET /api/oauth/authorize/validate', () => {
});
it('OAUTH-025b — returns 200 with valid:false when no requested scope is allowed (authenticated)', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
const { challenge } = makePkce();
@@ -835,7 +812,7 @@ describe('GET /api/oauth/authorize/validate', () => {
});
it('OAUTH-026 — unauthenticated valid request returns loginRequired=true (H3: minimal response, no client info)', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
const { challenge } = makePkce();
@@ -856,7 +833,7 @@ describe('GET /api/oauth/authorize/validate', () => {
});
it('OAUTH-027 — authenticated with no prior consent returns consentRequired=true with client details', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
const { challenge } = makePkce();
@@ -896,7 +873,7 @@ describe('POST /api/oauth/authorize', () => {
it('OAUTH-029 — 403 when MCP disabled', async () => {
await setMcpEnabled(false);
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const res = await request(app).post('/api/oauth/authorize').set('Cookie', authCookie(user.id)).send({
approved: true,
@@ -910,7 +887,7 @@ describe('POST /api/oauth/authorize', () => {
});
it('OAUTH-030 — user denied returns redirect with error=access_denied', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
const { challenge } = makePkce();
@@ -927,7 +904,7 @@ describe('POST /api/oauth/authorize', () => {
});
it('OAUTH-030b — a denial for an unregistered redirect_uri is refused, not redirected', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
const { challenge } = makePkce();
@@ -944,7 +921,7 @@ describe('POST /api/oauth/authorize', () => {
});
it('OAUTH-031 — invalid params returns 400', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const { challenge } = makePkce();
const res = await request(app).post('/api/oauth/authorize').set('Cookie', authCookie(user.id)).send({
@@ -959,7 +936,7 @@ describe('POST /api/oauth/authorize', () => {
});
it('OAUTH-032 — happy path: approve returns redirect with code', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
const { challenge } = makePkce();
@@ -985,14 +962,14 @@ describe('POST /api/oauth/authorize', () => {
describe('Client CRUD — /api/oauth/clients', () => {
it('OAUTH-033 — GET returns 403 when addon disabled', async () => {
await setMcpEnabled(false);
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const res = await request(app).get('/api/oauth/clients').set('Cookie', authCookie(user.id));
expect(res.status).toBe(403);
});
it('OAUTH-034 — GET returns 200 with clients list', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
await createOAuthClient(user.id, 'MyApp', ['https://app.example.com/cb'], ['trips:read']);
const res = await request(app).get('/api/oauth/clients').set('Cookie', authCookie(user.id));
@@ -1003,7 +980,7 @@ describe('Client CRUD — /api/oauth/clients', () => {
});
it('OAUTH-035 — POST creates client and returns 201 with client_secret', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const res = await request(app)
.post('/api/oauth/clients')
@@ -1018,7 +995,7 @@ describe('Client CRUD — /api/oauth/clients', () => {
it('OAUTH-036 — POST returns 403 when addon disabled', async () => {
await setMcpEnabled(false);
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const res = await request(app)
.post('/api/oauth/clients')
@@ -1028,7 +1005,7 @@ describe('Client CRUD — /api/oauth/clients', () => {
});
it('OAUTH-037 — POST /clients/:id/rotate rotates secret', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
const res = await request(app).post(`/api/oauth/clients/${r.client!.id}/rotate`).set('Cookie', authCookie(user.id));
@@ -1038,7 +1015,7 @@ describe('Client CRUD — /api/oauth/clients', () => {
});
it('OAUTH-038 — DELETE /clients/:id deletes client', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
const res = await request(app).delete(`/api/oauth/clients/${r.client!.id}`).set('Cookie', authCookie(user.id));
@@ -1047,7 +1024,7 @@ describe('Client CRUD — /api/oauth/clients', () => {
});
it('OAUTH-039 — DELETE /clients/:id returns 404 for non-existent', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const res = await request(app).delete('/api/oauth/clients/nonexistent-id').set('Cookie', authCookie(user.id));
expect(res.status).toBe(404);
@@ -1061,14 +1038,14 @@ describe('Client CRUD — /api/oauth/clients', () => {
describe('Sessions — /api/oauth/sessions', () => {
it('OAUTH-040 — GET returns 403 when addon disabled', async () => {
await setMcpEnabled(false);
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const res = await request(app).get('/api/oauth/sessions').set('Cookie', authCookie(user.id));
expect(res.status).toBe(403);
});
it('OAUTH-041 — GET returns 200 with sessions list', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const res = await request(app).get('/api/oauth/sessions').set('Cookie', authCookie(user.id));
expect(res.status).toBe(200);
@@ -1076,7 +1053,7 @@ describe('Sessions — /api/oauth/sessions', () => {
});
it('OAUTH-042 — DELETE /sessions/:id revokes session', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
const { verifier, challenge } = makePkce();
@@ -1110,14 +1087,14 @@ describe('Sessions — /api/oauth/sessions', () => {
});
it('OAUTH-043 — DELETE /sessions/:id returns 404 for non-existent', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const res = await request(app).delete('/api/oauth/sessions/99999').set('Cookie', authCookie(user.id));
expect(res.status).toBe(404);
});
it('OAUTH-043B — DELETE /sessions/abc (non-numeric id) returns the legacy 404, not a 500 (Plan 3b Task 4 controller addendum, per Task 2 review F1)', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const res = await request(app).delete('/api/oauth/sessions/abc').set('Cookie', authCookie(user.id));
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Session not found' });
@@ -1125,7 +1102,7 @@ describe('Sessions — /api/oauth/sessions', () => {
it('OAUTH-044 — DELETE /sessions/:id returns 403 when addon disabled', async () => {
await setMcpEnabled(false);
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const res = await request(app).delete('/api/oauth/sessions/1').set('Cookie', authCookie(user.id));
expect(res.status).toBe(403);
@@ -1166,7 +1143,7 @@ describe('M2 — 404 when MCP disabled on discovery + revoke endpoints', () => {
describe('H1 — PKCE format validation', () => {
it('OAUTH-SEC-004 — short code_challenge (<43 chars) rejected on /authorize/validate', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
const res = await request(app).get('/api/oauth/authorize/validate').set('Cookie', authCookie(user.id)).query({
response_type: 'code',
@@ -1182,7 +1159,7 @@ describe('H1 — PKCE format validation', () => {
});
it('OAUTH-SEC-005 — wrong code_verifier format rejected on /oauth/token (invalid_grant)', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
const { challenge } = makePkce();
@@ -1212,7 +1189,7 @@ describe('H1 — PKCE format validation', () => {
describe('H3 — Unauthenticated /authorize/validate returns minimal response', () => {
it('OAUTH-SEC-006 — invalid request by unauthenticated caller returns generic error (no oracle)', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
const { challenge } = makePkce();
@@ -1236,7 +1213,7 @@ describe('H3 — Unauthenticated /authorize/validate returns minimal response',
describe('H5 — All invalid_grant cases return identical response body', () => {
it('OAUTH-SEC-007 — expired/bad code, client_id mismatch, redirect_uri mismatch all return same body', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
const { verifier, challenge } = makePkce();
@@ -1290,7 +1267,7 @@ describe('H5 — All invalid_grant cases return identical response body', () =>
describe('M5 — Consent scope union (re-authorize adds to existing consent)', () => {
it('OAUTH-SEC-008 — second consent adds new scope without losing old scope', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read', 'places:read']);
const { challenge: ch1 } = makePkce();
const { challenge: ch2 } = makePkce();
@@ -1333,7 +1310,7 @@ describe('M5 — Consent scope union (re-authorize adds to existing consent)', (
describe('M7 — Cookie-only auth on privileged OAuth endpoints', () => {
it('OAUTH-SEC-009 — POST /api/oauth/authorize rejects Bearer JWT (no cookie)', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
// Use a valid JWT in Authorization header (no cookie) — must be rejected
const jwt = require('jsonwebtoken');
const token = jwt.sign({ id: user.id }, 'test-jwt-secret-for-trek-testing-only', { algorithm: 'HS256' });
@@ -1352,7 +1329,7 @@ describe('M7 — Cookie-only auth on privileged OAuth endpoints', () => {
it('OAUTH-SEC-010 — POST /api/oauth/clients rejects Bearer JWT (no cookie)', async () => {
const jwt = require('jsonwebtoken');
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const token = jwt.sign({ id: user.id }, 'test-jwt-secret-for-trek-testing-only', { algorithm: 'HS256' });
const res = await request(app)
@@ -1365,7 +1342,7 @@ describe('M7 — Cookie-only auth on privileged OAuth endpoints', () => {
it('OAUTH-SEC-011 — DELETE /api/oauth/sessions/:id rejects Bearer JWT (no cookie)', async () => {
const jwt = require('jsonwebtoken');
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const token = jwt.sign({ id: user.id }, 'test-jwt-secret-for-trek-testing-only', { algorithm: 'HS256' });
const res = await request(app).delete('/api/oauth/sessions/1').set('Authorization', `Bearer ${token}`);
@@ -1383,11 +1360,11 @@ describe('C3 — Refresh token replay detection', () => {
async function agePastGrace(rawRefreshToken: string) {
const hash = crypto.createHash('sha256').update(rawRefreshToken).digest('hex');
const old = new Date(Date.now() - 5 * 60 * 1000).toISOString().replace('T', ' ').slice(0, 19);
await updateRows(t, OauthTokens, { refresh_token_hash: hash }, { revoked_at: old });
await updateRows(orm, OauthTokens, { refresh_token_hash: hash }, { revoked_at: old });
}
it('OAUTH-SEC-012 — replaying a rotated (old) refresh token returns invalid_grant', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
const { verifier, challenge } = makePkce();
@@ -1435,7 +1412,7 @@ describe('C3 — Refresh token replay detection', () => {
});
it('OAUTH-SEC-012b — two clients refreshing the same token at once both keep working (#1007)', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
const { verifier, challenge } = makePkce();
@@ -1476,7 +1453,7 @@ describe('C3 — Refresh token replay detection', () => {
});
it('OAUTH-SEC-013 — replaying old token also invalidates the new chain', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
const { verifier, challenge } = makePkce();
@@ -1536,7 +1513,7 @@ describe('C3 — Refresh token replay detection', () => {
describe('POST /oauth/token — client_credentials grant', () => {
it('OAUTH-CC-001 — happy path: issues access token with no refresh_token', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'Machine', [], ['trips:read'], null, { allowsClientCredentials: true });
const res = await request(app).post('/oauth/token').send({
@@ -1554,7 +1531,7 @@ describe('POST /oauth/token — client_credentials grant', () => {
});
it('OAUTH-CC-002 — issued token resolves to the client owner user', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'Machine', [], ['trips:read'], null, { allowsClientCredentials: true });
const res = await request(app).post('/oauth/token').send({
@@ -1571,7 +1548,7 @@ describe('POST /oauth/token — client_credentials grant', () => {
});
it('OAUTH-CC-003 — wrong client_secret returns 401 invalid_client', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'Machine', [], ['trips:read'], null, { allowsClientCredentials: true });
const res = await request(app).post('/oauth/token').send({
@@ -1585,7 +1562,7 @@ describe('POST /oauth/token — client_credentials grant', () => {
});
it('OAUTH-CC-004 — missing client_secret returns 401 invalid_client', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'Machine', [], ['trips:read'], null, { allowsClientCredentials: true });
const res = await request(app).post('/oauth/token').send({
@@ -1598,7 +1575,7 @@ describe('POST /oauth/token — client_credentials grant', () => {
});
it('OAUTH-CC-005 — non-machine client returns 400 unauthorized_client', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'BrowserApp', ['https://app.example.com/cb'], ['trips:read']);
const res = await request(app).post('/oauth/token').send({
@@ -1612,7 +1589,7 @@ describe('POST /oauth/token — client_credentials grant', () => {
});
it('OAUTH-CC-006 — scope narrowing: requested subset is honoured', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'Machine', [], ['trips:read', 'places:read'], null, {
allowsClientCredentials: true,
});
@@ -1629,7 +1606,7 @@ describe('POST /oauth/token — client_credentials grant', () => {
});
it('OAUTH-CC-007 — scope outside allowed_scopes returns 400 invalid_scope', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'Machine', [], ['trips:read'], null, { allowsClientCredentials: true });
const res = await request(app).post('/oauth/token').send({
@@ -1644,7 +1621,7 @@ describe('POST /oauth/token — client_credentials grant', () => {
});
it('OAUTH-CC-008 — createOAuthClient with allowsClientCredentials succeeds without redirect URIs', async () => {
const { user } = createUser(testDb);
const { user } = await makeUser(orm);
const r = await createOAuthClient(user.id, 'Machine', [], ['trips:read'], null, { allowsClientCredentials: true });
expect(r.error).toBeUndefined();
@@ -4,12 +4,9 @@
"tests/integration/legacy-upgrade-v205.test.ts",
"tests/integration/legacy-upgrade-v242.test.ts",
"tests/integration/legacy-upgrade-v244.test.ts",
"tests/integration/mcp.test.ts",
"tests/integration/memories-immich.test.ts",
"tests/integration/memories-synology.test.ts",
"tests/integration/memories-unified.test.ts",
"tests/integration/oauth-authorize.test.ts",
"tests/integration/oauth.test.ts",
"tests/integration/scheduler-gate.test.ts",
"tests/integration/security.test.ts",
"tests/integration/settings.test.ts",