Repository navigation
Expand file tree
/
Copy pathtoken.test.ts
More file actions
431 lines (396 loc) · 18.1 KB
/
Copy pathtoken.test.ts
File metadata and controls
431 lines (396 loc) · 18.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
/**
* GET and POST /api/mcp/token (#246): the MCP channel's status for the signed-in user, and a token
* minted for that user's own role, answered once and stored nowhere. The session is a real signed
* cookie read through a replaced next/headers, so getSession and verifyJWT run as they do in the app.
*/
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, mock, spyOn, test } from "bun:test";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { SignJWT } from "jose";
let cookieStore: Record<string, { value: string } | undefined> = {};
let requestHeaders = new Headers();
mock.module("next/headers", () => ({
cookies: async () => ({ get: (name: string) => cookieStore[name] }),
headers: async () => requestHeaders,
}));
const { GET, POST } = await import("@/app/api/mcp/token/route");
const mcpRoute = await import("@/app/api/mcp/route");
const { getSession, signJWT, verifyJWT } = await import("@/lib/auth");
const { getJwtSecret } = await import("@/lib/config/auth-env");
const { clearRateLimitState } = await import("@/lib/api/rate-limit");
const { logger } = await import("@/lib/logger");
const { verifyMcpToken } = await import("@/lib/mcp/token");
const { resetCache } = await import("@/lib/seed");
const fixtures = await import("../../helpers/mcp-fixtures");
const harness = await import("../../helpers/mcp-harness");
const { useMcpChannel } = await import("../../helpers/mcp-token");
const bearerProvider = await import("../../helpers/oidc-bearer-provider");
const { resetBearerKeys } = await import("@/lib/oidc-bearer");
const dir = mkdtempSync(join(tmpdir(), "libredb-mcp-token-route-"));
const NOT_ISSUED = "MCP tokens cannot be issued on this server";
const AUDIT_FAILED = "The token was not issued because its audit record could not be written.";
const SEED_UNREADABLE =
"The seed connection file could not be read, so the connections an MCP token reaches are unknown; the server log names the cause";
let restoreChannel: () => void = () => {};
async function signIn(username: string, role: "admin" | "user", claimRoles?: string[]): Promise<void> {
cookieStore = {
"auth-token": {
value: await signJWT({ username, role, ...(claimRoles ? { claimRoles } : {}) }),
},
};
}
async function signInSecondsAgo(seconds: number): Promise<void> {
const issuedAt = Math.floor(Date.now() / 1000) - seconds;
const token = await new SignJWT({ username: "bob", role: "admin" })
.setProtectedHeader({ alg: "HS256" })
.setIssuedAt(issuedAt)
.setExpirationTime(issuedAt + 86_400)
.sign(getJwtSecret());
cookieStore = { "auth-token": { value: token } };
}
const RECENT_SIGN_IN_REQUIRED =
"Sign in again to create a token: a token can only be created within 10 minutes of signing in.";
const mintRequest = (headers: Record<string, string> = {}) =>
new Request("http://localhost:3000/api/mcp/token", {
method: "POST",
headers: { "content-type": "application/json", ...headers },
});
beforeAll(() => {
fixtures.pinMcpTestEnvironment();
fixtures.createSqliteFile(join(dir, "shop.db"), ["CREATE TABLE users (id INTEGER PRIMARY KEY)"]);
});
beforeEach(() => {
clearRateLimitState();
cookieStore = {};
requestHeaders = new Headers();
restoreChannel = useMcpChannel();
fixtures.writeSeedFile(dir, [
{ id: "everyone", type: "sqlite", database: join(dir, "shop.db"), roles: ["*"] },
{ id: "admins", type: "sqlite", database: join(dir, "shop.db"), roles: ["admin"] },
{ id: "silent", type: "sqlite", database: join(dir, "shop.db"), mcp: null },
]);
});
afterEach(async () => {
restoreChannel();
delete process.env.RATE_LIMIT_QUERY_MAX;
await fixtures.resetMcpTestState();
});
afterAll(() => {
rmSync(dir, { recursive: true, force: true });
});
describe("GET /api/mcp/token", () => {
test("answers 401 without a session", async () => {
expect((await GET()).status).toBe(401);
});
test("answers a ready channel and the opted-in connections the user's role reaches", async () => {
await signIn("bob", "user");
const response = await GET();
expect(response.status).toBe(200);
expect(await response.json()).toEqual({
state: "ready",
problems: [],
url: harness.MCP_TEST_URL,
tokenTtlDays: 30,
visibleConnections: 1,
});
});
test("counts the admin-only connection for an admin", async () => {
await signIn("alice", "admin");
expect((await (await GET()).json()).visibleConnections).toBe(2);
});
test("answers zero for a role no opted-in connection admits, which the screen explains", async () => {
fixtures.writeSeedFile(dir, [
{ id: "admins", type: "sqlite", database: join(dir, "shop.db"), roles: ["admin"] },
{ id: "silent", type: "sqlite", database: join(dir, "shop.db"), mcp: null },
]);
await signIn("bob", "user");
expect((await (await GET()).json()).visibleConnections).toBe(0);
});
test("names everything enabling it needs when it is off", async () => {
restoreChannel();
restoreChannel = useMcpChannel({ enabled: null, url: null, label: null });
await signIn("alice", "admin");
expect(await (await GET()).json()).toEqual({
state: "off",
problems: [
"LIBREDB_MCP_ENABLED is off: set it to true, on or 1 to enable MCP",
"LIBREDB_MCP_URL is not set: set it to the address clients use, such as https://studio.example.com/api/mcp",
"LIBREDB_MCP_TOKEN_LABEL is not set: set it to any value, and change it to revoke every MCP token at once",
],
url: null,
tokenTtlDays: 30,
visibleConnections: 2,
});
});
test("answers null connections, with a problem, when the seed file cannot be read", async () => {
const file = join(dir, "broken.json");
writeFileSync(file, "{ not json");
process.env.SEED_CONFIG_PATH = file;
resetCache();
const errorLog = spyOn(logger, "error").mockImplementation(() => {});
try {
await signIn("alice", "admin");
const body = await (await GET()).json();
expect(body.visibleConnections).toBeNull();
expect(body.problems).toContain(SEED_UNREADABLE);
} finally {
errorLog.mockRestore();
}
});
test("is never metered", async () => {
process.env.RATE_LIMIT_QUERY_MAX = "1";
await signIn("alice", "admin");
for (let i = 0; i < 3; i += 1) expect((await GET()).status).toBe(200);
expect((await POST(mintRequest())).status).toBe(200);
});
});
describe("a token signed with JWT_SECRET that is not a session", () => {
test("the OIDC state cookie is refused by GET and POST, and reads nothing", async () => {
cookieStore = {
"auth-token": {
value: await new SignJWT({ code_verifier: "verifier", state: "state", nonce: "nonce" })
.setProtectedHeader({ alg: "HS256" })
.setIssuedAt()
.setExpirationTime("5m")
.sign(getJwtSecret()),
},
};
const status = await GET();
expect(status.status).toBe(401);
expect(await status.json()).toEqual({ error: "Authentication required", code: "AUTH_REQUIRED" });
const mint = await POST(mintRequest());
expect(mint.status).toBe(401);
expect(await mint.json()).toEqual({ error: "Authentication required", code: "AUTH_REQUIRED" });
});
test.each([
["an empty user name", { username: "", role: "admin" }],
["a role that is neither admin nor user", { username: "bob", role: "owner" }],
])("a payload with %s is refused by both", async (_name, payload) => {
cookieStore = {
"auth-token": {
value: await new SignJWT(payload)
.setProtectedHeader({ alg: "HS256" })
.setIssuedAt()
.setExpirationTime("1h")
.sign(getJwtSecret()),
},
};
expect((await GET()).status).toBe(401);
expect((await POST(mintRequest())).status).toBe(401);
});
});
describe("a URL that carries credentials", () => {
test("is named by its rule in both answers, and no part of it is repeated", async () => {
restoreChannel();
// Built from parts with a password generated at run time, so the file holds no credential for a secret scanner to flag.
const credentialed = new URL("https://studio.example/api/mcp");
credentialed.username = "someone";
credentialed.password = crypto.randomUUID();
restoreChannel = useMcpChannel({ url: credentialed.href });
await signIn("alice", "admin");
for (const response of [await GET(), await POST(mintRequest())]) {
const text = await response.text();
expect(JSON.parse(text).problems).toContain("LIBREDB_MCP_URL must not carry a user name or password");
for (const part of ["someone", credentialed.password, "studio.example"]) expect(text).not.toContain(part);
}
});
});
describe("POST /api/mcp/token", () => {
test("answers guardRoute's 401 without a session", async () => {
const response = await POST(mintRequest());
expect(response.status).toBe(401);
expect(await response.json()).toEqual({ error: "Authentication required", code: "AUTH_REQUIRED" });
});
test("mints for the session's user and role, once, with no-store, verifiable only under the MCP key", async () => {
await signIn("bob", "user");
const response = await POST(mintRequest());
expect(response.status).toBe(200);
expect(response.headers.get("cache-control")).toBe("no-store");
const body = (await response.json()) as { token: string; expiresAt: string; url: string };
expect(Object.keys(body).sort()).toEqual(["expiresAt", "token", "url"]);
expect(body.url).toBe(harness.MCP_TEST_URL);
expect(await verifyMcpToken(body.token)).toMatchObject({ sub: "bob", role: "user" });
expect(new Date(body.expiresAt).getTime()).toBeGreaterThan(Date.now() + 29 * 86_400_000);
expect(await verifyJWT(body.token)).toBeNull();
cookieStore = { "auth-token": { value: body.token } };
expect(await getSession()).toBeNull();
await signIn("bob", "user");
expect(await (await GET()).text()).not.toContain(body.token);
});
test("an MCP bearer authenticates nothing here", async () => {
await signIn("alice", "admin");
const { token } = (await (await POST(mintRequest())).json()) as { token: string };
cookieStore = {};
expect((await POST(mintRequest({ authorization: `Bearer ${token}` }))).status).toBe(401);
});
// An access token is refreshed every few minutes, so its iat always looks like a fresh sign-in, and the native client
// that holds it never signed in to Studio at all (src/lib/oidc-bearer.ts).
test("a bearer access token cannot mint, and nothing is signed", async () => {
const fetchSpy = bearerProvider.stubIdentityProvider();
bearerProvider.useBearerEnv();
resetBearerKeys();
try {
requestHeaders = new Headers({ authorization: `Bearer ${await bearerProvider.signBearer()}` });
const response = await POST(mintRequest());
expect(response.status).toBe(403);
expect(response.headers.get("cache-control")).toBe("no-store");
expect(await response.json()).toEqual({
error: "A token can only be created from a browser session: sign in to Studio and create it there.",
});
} finally {
bearerProvider.restoreBearerEnv();
fetchSpy.mockRestore();
}
});
test("a user-role token lists only what that role reaches, and an admin's the admin-only connection too", async () => {
for (const [username, role, ids] of [
["bob", "user", ["seed:everyone"]],
["alice", "admin", ["seed:everyone", "seed:admins"]],
] as const) {
await signIn(username, role);
const { token } = (await (await POST(mintRequest())).json()) as { token: string };
const session = await harness.connectClient(harness.routeServe(mcpRoute), { token });
try {
const result = await session.client.callTool({ name: "list_connections", arguments: {} });
expect(
(result.structuredContent as { connections: Array<{ id: string }> }).connections.map((entry) => entry.id),
).toEqual([...ids]);
} finally {
await session.close();
}
}
});
test("a session with claimRoles mints a token carrying claimRoles that reaches custom role connections", async () => {
const origProvider = process.env.NEXT_PUBLIC_AUTH_PROVIDER;
const origPrefix = process.env.OIDC_ROLE_PREFIX;
process.env.NEXT_PUBLIC_AUTH_PROVIDER = "oidc";
process.env.OIDC_ROLE_PREFIX = "team-";
try {
fixtures.writeSeedFile(dir, [
{ id: "everyone", type: "sqlite", database: join(dir, "shop.db"), roles: ["*"], mcp: true },
{ id: "billing", type: "sqlite", database: join(dir, "shop.db"), roles: ["team-billing"], mcp: true },
{ id: "analytics", type: "sqlite", database: join(dir, "shop.db"), roles: ["team-analytics"], mcp: true },
]);
await signIn("carol", "user", ["team-billing"]);
const { token } = (await (await POST(mintRequest())).json()) as { token: string };
const session = await harness.connectClient(harness.routeServe(mcpRoute), { token });
try {
const result = await session.client.callTool({ name: "list_connections", arguments: {} });
const ids = (result.structuredContent as { connections: Array<{ id: string }> }).connections.map((c) => c.id);
expect(ids).toEqual(["seed:everyone", "seed:billing"]);
} finally {
await session.close();
}
} finally {
if (origProvider !== undefined) process.env.NEXT_PUBLIC_AUTH_PROVIDER = origProvider;
else delete process.env.NEXT_PUBLIC_AUTH_PROVIDER;
if (origPrefix !== undefined) process.env.OIDC_ROLE_PREFIX = origPrefix;
else delete process.env.OIDC_ROLE_PREFIX;
}
});
test.each([
["off", { enabled: null }, "LIBREDB_MCP_ENABLED is off"],
["without a label", { label: null }, "LIBREDB_MCP_TOKEN_LABEL is not set"],
["without a URL", { url: null }, "LIBREDB_MCP_URL is not set"],
[
"with a URL that does not end in /api/mcp",
{ url: "https://mcp-host.test/api/mcp/" },
"LIBREDB_MCP_URL must end in /api/mcp",
],
["with a lifetime of 0", { ttlDays: "0" }, "LIBREDB_MCP_TOKEN_TTL_DAYS must be a whole number"],
["with a lifetime of 366", { ttlDays: "366" }, "LIBREDB_MCP_TOKEN_TTL_DAYS must be a whole number"],
["with a lifetime of abc", { ttlDays: "abc" }, "LIBREDB_MCP_TOKEN_TTL_DAYS must be a whole number"],
] as const)(
"answers 409 naming the problem when the channel is %s, and signs nothing",
async (_name, overrides, problem) => {
restoreChannel();
restoreChannel = useMcpChannel(overrides);
await signIn("alice", "admin");
const signs = spyOn(SignJWT.prototype, "sign");
try {
const response = await POST(mintRequest());
expect(response.status).toBe(409);
const body = (await response.json()) as { error: string; problems: string[] };
expect(body.error).toBe(NOT_ISSUED);
expect(body.problems.some((text) => text.startsWith(problem))).toBe(true);
expect(signs).not.toHaveBeenCalled();
} finally {
signs.mockRestore();
}
},
);
test("refuses a session signed more than ten minutes ago and signs nothing, so a rotated label is not re-minted on an old session", async () => {
await signInSecondsAgo(601);
const signs = spyOn(SignJWT.prototype, "sign");
const sink = spyOn(console, "log").mockImplementation(() => {});
try {
const response = await POST(mintRequest());
expect(response.status).toBe(403);
expect(response.headers.get("cache-control")).toBe("no-store");
expect(await response.json()).toEqual({ error: RECENT_SIGN_IN_REQUIRED });
expect(signs).not.toHaveBeenCalled();
const lines = sink.mock.calls.map(([line]) => JSON.parse(String(line)) as Record<string, unknown>);
expect(lines.filter((line) => line.event === "mcp_operation")).toEqual([]);
} finally {
signs.mockRestore();
sink.mockRestore();
}
});
test("mints on a session signed nine minutes ago", async () => {
await signInSecondsAgo(540);
const response = await POST(mintRequest());
expect(response.status).toBe(200);
expect(await verifyMcpToken(((await response.json()) as { token: string }).token)).toMatchObject({ sub: "bob" });
});
test("refuses a session that carries no issue time", async () => {
cookieStore = {
"auth-token": {
value: await new SignJWT({ username: "bob", role: "admin" })
.setProtectedHeader({ alg: "HS256" })
.setExpirationTime("1h")
.sign(getJwtSecret()),
},
};
const response = await POST(mintRequest());
expect(response.status).toBe(403);
expect(await response.json()).toEqual({ error: RECENT_SIGN_IN_REQUIRED });
});
test("spends one slot of the query budget", async () => {
process.env.RATE_LIMIT_QUERY_MAX = "1";
await signIn("alice", "admin");
expect((await POST(mintRequest())).status).toBe(200);
expect((await POST(mintRequest())).status).toBe(429);
});
test("writes one mint_token event for the session's user", async () => {
await signIn("alice", "admin");
const sink = spyOn(console, "log").mockImplementation(() => {});
try {
await POST(mintRequest());
const lines = sink.mock.calls.map(([line]) => JSON.parse(String(line)) as Record<string, unknown>);
expect(lines.filter((line) => line.event === "mcp_operation")).toEqual([
expect.objectContaining({ action: "mint_token", route: "mcp/token", actor: "alice", outcome: "success" }),
]);
} finally {
sink.mockRestore();
}
});
test("answers 500 and signs nothing when that event cannot be written, so the record comes first", async () => {
await signIn("alice", "admin");
const signs = spyOn(SignJWT.prototype, "sign");
const sink = spyOn(console, "log").mockImplementation(() => {
throw new Error("audit sink unavailable");
});
const errorLog = spyOn(logger, "error").mockImplementation(() => {});
try {
const response = await POST(mintRequest());
expect(response.status).toBe(500);
expect(await response.json()).toEqual({ error: AUDIT_FAILED });
expect(signs).not.toHaveBeenCalled();
} finally {
signs.mockRestore();
sink.mockRestore();
errorLog.mockRestore();
}
});
});