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
 
 
 
 
 
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { makeManagementSessionRequest } from "../helpers/managementSession.ts";

const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-api-keys-route-"));
process.env.DATA_DIR = TEST_DATA_DIR;
process.env.API_KEY_SECRET = "test-api-key-secret";
process.env.CLOUD_URL = "http://cloud.example";

const core = await import("../../src/lib/db/core.ts");
const apiKeysDb = await import("../../src/lib/db/apiKeys.ts");
const localDb = await import("../../src/lib/localDb.ts");
const compliance = await import("../../src/lib/compliance/index.ts");
const listRoute = await import("../../src/app/api/keys/route.ts");
const keyRoute = await import("../../src/app/api/keys/[id]/route.ts");
const revealRoute = await import("../../src/app/api/keys/[id]/reveal/route.ts");

const MACHINE_ID = "1234567890abcdef";

async function resetStorage() {
  delete process.env.ALLOW_API_KEY_REVEAL;
  delete process.env.INITIAL_PASSWORD;
  core.resetDbInstance();
  apiKeysDb.resetApiKeyState();
  fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
  fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
}

async function enableManagementAuth() {
  process.env.INITIAL_PASSWORD = "bootstrap-password";
  await localDb.updateSettings({ requireLogin: true, password: "" });
}

async function createManagementKey() {
  return apiKeysDb.createApiKey("management", MACHINE_ID);
}

function makeRequest(
  url: string | URL,
  { method = "GET", token, body }: { method?: string; token?: string; body?: unknown } = {}
) {
  const headers = new Headers();
  if (token) {
    headers.set("authorization", `Bearer ${token}`);
  }
  if (body !== undefined) {
    headers.set("content-type", "application/json");
  }

  return new Request(url, {
    method,
    headers,
    body: body === undefined ? undefined : JSON.stringify(body),
  });
}

test.beforeEach(async () => {
  await resetStorage();
});

test.after(async () => {
  await resetStorage();
  fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
});

test("API keys routes require management auth when login protection is enabled", async () => {
  await enableManagementAuth();

  const unauthenticated = await listRoute.GET(new Request("http://localhost/api/keys"));
  const invalidToken = await listRoute.GET(
    new Request("http://localhost/api/keys", {
      headers: { authorization: "Bearer sk-invalid" },
    })
  );

  const unauthenticatedBody = (await unauthenticated.json()) as any;
  const invalidTokenBody = (await invalidToken.json()) as any;

  assert.equal(unauthenticated.status, 401);
  assert.equal(unauthenticatedBody.error.message, "Authentication required");
  assert.equal(invalidToken.status, 403);
  assert.equal(invalidTokenBody.error.message, "Invalid management token");
});

test("API keys POST also requires management auth when login protection is enabled", async () => {
  await enableManagementAuth();

  const unauthenticated = await listRoute.POST(
    makeRequest("http://localhost/api/keys", {
      method: "POST",
      body: { name: "Blocked Create" },
    })
  );
  const invalidToken = await listRoute.POST(
    makeRequest("http://localhost/api/keys", {
      method: "POST",
      token: "sk-invalid",
      body: { name: "Blocked Create" },
    })
  );

  const unauthenticatedBody = (await unauthenticated.json()) as any;
  const invalidTokenBody = (await invalidToken.json()) as any;

  assert.equal(unauthenticated.status, 401);
  assert.equal(unauthenticatedBody.error.message, "Authentication required");
  assert.equal(invalidToken.status, 403);
  assert.equal(invalidTokenBody.error.message, "Invalid management token");
});

test("POST /api/keys creates a key, preserves special characters, and persists noLog", async () => {
  await enableManagementAuth();
  await createManagementKey();
  const response = await listRoute.POST(
    await makeManagementSessionRequest("http://localhost/api/keys", {
      method: "POST",
      body: { name: "Key / Prod #1", noLog: true },
    })
  );
  const body = (await response.json()) as any;
  const stored = await apiKeysDb.getApiKeyById(body.id);

  assert.equal(response.status, 201);
  assert.equal(body.name, "Key / Prod #1");
  assert.equal(body.noLog, true);
  assert.match(body.key, /^sk-[a-z0-9-]+/i);
  assert.equal(stored?.noLog, true);
  assert.equal(compliance.isNoLog(body.id), true);
});

test("POST /api/keys validates missing and oversized names", async () => {
  await enableManagementAuth();
  await createManagementKey();

  const missingName = await listRoute.POST(
    await makeManagementSessionRequest("http://localhost/api/keys", {
      method: "POST",
      body: {},
    })
  );
  const oversizedName = await listRoute.POST(
    await makeManagementSessionRequest("http://localhost/api/keys", {
      method: "POST",
      body: { name: "x".repeat(201) },
    })
  );

  assert.equal(missingName.status, 400);
  assert.equal(oversizedName.status, 400);
});

test("POST /api/keys returns a server error for malformed JSON payloads", async () => {
  await enableManagementAuth();
  await createManagementKey();

  const response = await listRoute.POST(
    await makeManagementSessionRequest("http://localhost/api/keys", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: "{",
    })
  );
  const body = (await response.json()) as any;

  assert.equal(response.status, 500);
  assert.equal(body.error, "Failed to create key");
});

test("GET /api/keys lists masked keys with pagination and GET /api/keys/[id] stays masked", async () => {
  await enableManagementAuth();
  await createManagementKey();
  const createdA = await apiKeysDb.createApiKey("Alpha", MACHINE_ID);
  const createdB = await apiKeysDb.createApiKey("Beta", MACHINE_ID);

  const listResponse = await listRoute.GET(
    await makeManagementSessionRequest("http://localhost/api/keys?limit=1&offset=1")
  );
  const getResponse = await keyRoute.GET(
    await makeManagementSessionRequest(`http://localhost/api/keys/${createdB.id}`),
    { params: Promise.resolve({ id: createdB.id }) }
  );

  const listBody = (await listResponse.json()) as any;
  const getBody = (await getResponse.json()) as any;

  assert.equal(listResponse.status, 200);
  assert.equal(listBody.total, 3);
  assert.equal(listBody.keys.length, 1);
  assert.equal(listBody.keys[0].id, createdA.id);
  assert.notEqual(listBody.keys[0].key, createdA.key);
  assert.match(listBody.keys[0].key, /\*{4}/);

  assert.equal(getResponse.status, 200);
  assert.equal(getBody.id, createdB.id);
  assert.notEqual(getBody.key, createdB.key);
  assert.match(getBody.key, /\*{4}/);
});

test("GET /api/keys falls back to default pagination for invalid query params", async () => {
  await enableManagementAuth();
  await createManagementKey();
  await apiKeysDb.createApiKey("Alpha", MACHINE_ID);
  await apiKeysDb.createApiKey("Beta", MACHINE_ID);

  const response = await listRoute.GET(
    await makeManagementSessionRequest("http://localhost/api/keys?limit=0&offset=-25")
  );
  const body = (await response.json()) as any;

  assert.equal(response.status, 200);
  assert.equal(body.total, 3);
  assert.equal(body.keys.length, 3);
  assert.equal(body.keys[0].name, "management");
});

test("GET /api/keys treats non-numeric pagination params as defaults", async () => {
  await enableManagementAuth();
  await createManagementKey();
  await apiKeysDb.createApiKey("Alpha", MACHINE_ID);
  await apiKeysDb.createApiKey("Beta", MACHINE_ID);

  const response = await listRoute.GET(
    await makeManagementSessionRequest("http://localhost/api/keys?limit=abc&offset=xyz")
  );
  const body = (await response.json()) as any;

  assert.equal(response.status, 200);
  assert.equal(body.total, 3);
  assert.equal(body.keys.length, 3);
  assert.deepEqual(
    body.keys.map((entry) => entry.name),
    ["management", "Alpha", "Beta"]
  );
});

test("GET /api/keys uses default pagination when query params are absent and reports reveal support", async () => {
  await enableManagementAuth();
  process.env.ALLOW_API_KEY_REVEAL = "true";
  const authKey = await createManagementKey();
  const createdA = await apiKeysDb.createApiKey("Alpha", MACHINE_ID);
  const createdB = await apiKeysDb.createApiKey("Beta", MACHINE_ID);

  const response = await listRoute.GET(
    await makeManagementSessionRequest("http://localhost/api/keys")
  );
  const body = (await response.json()) as any;

  assert.equal(response.status, 200);
  assert.equal(body.total, 3);
  assert.equal(body.allowKeyReveal, true);
  assert.equal(body.keys.length, 3);
  assert.deepEqual(
    body.keys.map((entry) => entry.id).sort(),
    [authKey.id, createdA.id, createdB.id].sort()
  );
  assert.ok(body.keys.every((entry) => entry.key !== undefined && entry.key !== ""));
});

test("POST /api/keys triggers cloud sync when cloud mode is enabled", async () => {
  await enableManagementAuth();
  await localDb.updateSettings({ cloudEnabled: true });
  await createManagementKey();
  const originalFetch = globalThis.fetch;
  const calls = [];
  globalThis.fetch = async (url, options = {}) => {
    calls.push({ url, options });
    return Response.json({ changes: { apiKeys: 1 } });
  };

  try {
    const response = await listRoute.POST(
      await makeManagementSessionRequest("http://localhost/api/keys", {
        method: "POST",
        body: { name: "Cloud Synced Key" },
      })
    );
    const body = (await response.json()) as any;
    const syncPayload = JSON.parse(calls[0].options.body);

    assert.equal(response.status, 201);
    assert.equal(body.name, "Cloud Synced Key");
    assert.equal(calls.length, 1);
    assert.match(String(calls[0].url), /^http:\/\/cloud\.example\/sync\//);
    assert.ok(Array.isArray(syncPayload.providers));
    assert.ok(Array.isArray(syncPayload.apiKeys));
  } finally {
    globalThis.fetch = originalFetch;
  }
});

test("GET /api/keys returns 500 when the key store throws unexpectedly", async () => {
  await apiKeysDb.createApiKey("Alpha", MACHINE_ID);

  const db = core.getDbInstance();
  const originalPrepare = db.prepare.bind(db);
  const originalLog = console.log;
  const originalError = console.error;

  db.prepare = (sql) => {
    if (String(sql).includes("FROM api_keys")) {
      throw new Error("api keys offline");
    }
    return originalPrepare(sql);
  };
  apiKeysDb.resetApiKeyState();
  // Suppress Pino structured log output during test
  console.log = () => {};
  console.error = () => {};

  try {
    const response = await listRoute.GET(new Request("http://localhost/api/keys"));
    const body = (await response.json()) as any;

    assert.equal(response.status, 500);
    assert.equal(body.error, "Failed to fetch keys");
  } finally {
    db.prepare = originalPrepare;
    apiKeysDb.resetApiKeyState();
    console.log = originalLog;
    console.error = originalError;
  }
});

test("POST /api/keys still succeeds when cloud sync fails after creation", async () => {
  await enableManagementAuth();
  await localDb.updateSettings({ cloudEnabled: true });
  await createManagementKey();
  const originalFetch = globalThis.fetch;
  let syncAttempts = 0;

  globalThis.fetch = async () => {
    syncAttempts += 1;
    throw new Error("cloud sync offline");
  };

  try {
    const response = await listRoute.POST(
      await makeManagementSessionRequest("http://localhost/api/keys", {
        method: "POST",
        body: { name: "Cloud Failure Tolerated" },
      })
    );
    const body = (await response.json()) as any;
    const stored = await apiKeysDb.getApiKeyById(body.id);

    assert.equal(response.status, 201);
    assert.equal(body.name, "Cloud Failure Tolerated");
    assert.equal(syncAttempts, 1);
    assert.equal(stored?.name, "Cloud Failure Tolerated");
  } finally {
    globalThis.fetch = originalFetch;
  }
});

test("GET /api/keys/[id] returns 404 for an unknown key and reveal is gated by the feature flag", async () => {
  await enableManagementAuth();
  await createManagementKey();
  const created = await apiKeysDb.createApiKey("Reveal Target", MACHINE_ID);

  const missingResponse = await keyRoute.GET(
    await makeManagementSessionRequest("http://localhost/api/keys/missing"),
    { params: Promise.resolve({ id: "missing" }) }
  );
  const revealDisabled = await revealRoute.GET(
    await makeManagementSessionRequest(`http://localhost/api/keys/${created.id}/reveal`),
    { params: Promise.resolve({ id: created.id }) }
  );

  process.env.ALLOW_API_KEY_REVEAL = "true";
  const revealEnabled = await revealRoute.GET(
    await makeManagementSessionRequest(`http://localhost/api/keys/${created.id}/reveal`),
    { params: Promise.resolve({ id: created.id }) }
  );

  const missingBody = (await missingResponse.json()) as any;
  const revealDisabledBody = (await revealDisabled.json()) as any;
  const revealEnabledBody = (await revealEnabled.json()) as any;

  assert.equal(missingResponse.status, 404);
  assert.equal(missingBody.error, "Key not found");
  assert.equal(revealDisabled.status, 403);
  assert.equal(revealDisabledBody.error, "API key reveal is disabled");
  assert.equal(revealEnabled.status, 200);
  assert.equal(revealEnabledBody.key, created.key);
});

test("PATCH /api/keys/[id] updates permissions and rejects invalid payloads", async () => {
  await enableManagementAuth();
  await createManagementKey();
  const created = await apiKeysDb.createApiKey("Mutable", MACHINE_ID);
  const patchResponse = await keyRoute.PATCH(
    await makeManagementSessionRequest(`http://localhost/api/keys/${created.id}`, {
      method: "PATCH",
      body: {
        noLog: true,
        allowedModels: ["gpt-4.1-mini"],
        allowedConnections: [],
        isActive: false,
        maxSessions: 2,
      },
    }),
    { params: Promise.resolve({ id: created.id }) }
  );
  const invalidJsonResponse = await keyRoute.PATCH(
    await makeManagementSessionRequest(`http://localhost/api/keys/${created.id}`, {
      method: "PATCH",
      headers: { "content-type": "application/json" },
      body: "{",
    }),
    { params: Promise.resolve({ id: created.id }) }
  );
  const missingKeyResponse = await keyRoute.PATCH(
    await makeManagementSessionRequest("http://localhost/api/keys/missing", {
      method: "PATCH",
      body: { noLog: false },
    }),
    { params: Promise.resolve({ id: "missing" }) }
  );

  const patchBody = (await patchResponse.json()) as any;
  const invalidJsonBody = (await invalidJsonResponse.json()) as any;
  const missingKeyBody = (await missingKeyResponse.json()) as any;
  const updated = await apiKeysDb.getApiKeyById(created.id);

  assert.equal(patchResponse.status, 200);
  assert.equal(patchBody.noLog, true);
  assert.equal(patchBody.isActive, false);
  assert.equal(patchBody.maxSessions, 2);
  assert.deepEqual(updated?.allowedModels, ["gpt-4.1-mini"]);
  assert.equal(updated?.noLog, true);
  assert.equal(updated?.isActive, false);
  assert.equal(invalidJsonResponse.status, 400);
  assert.equal(invalidJsonBody.error.message, "Invalid request");
  assert.equal(missingKeyResponse.status, 404);
  assert.equal(missingKeyBody.error, "Key not found");
});

test("PATCH /api/keys/[id] renames a key and rejects invalid names", async () => {
  await enableManagementAuth();
  await createManagementKey();
  const created = await apiKeysDb.createApiKey("Original Name", MACHINE_ID);

  // Valid rename
  const renameResponse = await keyRoute.PATCH(
    await makeManagementSessionRequest(`http://localhost/api/keys/${created.id}`, {
      method: "PATCH",
      body: { name: "Renamed Key" },
    }),
    { params: Promise.resolve({ id: created.id }) }
  );
  const renameBody = (await renameResponse.json()) as any;
  const renamed = await apiKeysDb.getApiKeyById(created.id);

  assert.equal(renameResponse.status, 200);
  assert.equal(renameBody.name, "Renamed Key");
  assert.equal(renamed?.name, "Renamed Key");

  // Empty name should be rejected by Zod schema (min(1))
  const emptyNameResponse = await keyRoute.PATCH(
    await makeManagementSessionRequest(`http://localhost/api/keys/${created.id}`, {
      method: "PATCH",
      body: { name: "   " },
    }),
    { params: Promise.resolve({ id: created.id }) }
  );
  assert.equal(emptyNameResponse.status, 400);

  // Name too long should be rejected (max 200)
  const longNameResponse = await keyRoute.PATCH(
    await makeManagementSessionRequest(`http://localhost/api/keys/${created.id}`, {
      method: "PATCH",
      body: { name: "x".repeat(201) },
    }),
    { params: Promise.resolve({ id: created.id }) }
  );
  assert.equal(longNameResponse.status, 400);
});

test("DELETE /api/keys/[id] removes keys and reports missing resources", async () => {
  await enableManagementAuth();
  await createManagementKey();
  const created = await apiKeysDb.createApiKey("Disposable", MACHINE_ID);

  const deleteResponse = await keyRoute.DELETE(
    await makeManagementSessionRequest(`http://localhost/api/keys/${created.id}`, {
      method: "DELETE",
    }),
    { params: Promise.resolve({ id: created.id }) }
  );
  const missingDeleteResponse = await keyRoute.DELETE(
    await makeManagementSessionRequest("http://localhost/api/keys/missing", {
      method: "DELETE",
    }),
    { params: Promise.resolve({ id: "missing" }) }
  );

  const deleteBody = (await deleteResponse.json()) as any;
  const missingDeleteBody = (await missingDeleteResponse.json()) as any;

  assert.equal(deleteResponse.status, 200);
  assert.equal(deleteBody.message, "Key deleted successfully");
  assert.equal(await apiKeysDb.getApiKeyById(created.id), null);
  assert.equal(missingDeleteResponse.status, 404);
  assert.equal(missingDeleteBody.error, "Key not found");
});