File size: 8,423 Bytes
35743bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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 { SignJWT } from "jose";

const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-api-auth-"));
process.env.DATA_DIR = TEST_DATA_DIR;
process.env.API_KEY_SECRET = "test-api-key-secret";

const core = await import("../../src/lib/db/core.ts");
const localDb = await import("../../src/lib/localDb.ts");
const apiKeysDb = await import("../../src/lib/db/apiKeys.ts");
const apiAuth = await import("../../src/shared/utils/apiAuth.ts");

const ORIGINAL_JWT_SECRET = process.env.JWT_SECRET;
const ORIGINAL_INITIAL_PASSWORD = process.env.INITIAL_PASSWORD;

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

function makeCookieRequest(token: string) {
  return {
    cookies: {
      get(name: string) {
        return name === "auth_token" && token ? { value: token } : undefined;
      },
    },
    headers: new Headers(),
  };
}

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

test.after(() => {
  core.resetDbInstance();
  apiKeysDb.resetApiKeyState();
  fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });

  if (ORIGINAL_JWT_SECRET === undefined) {
    delete process.env.JWT_SECRET;
  } else {
    process.env.JWT_SECRET = ORIGINAL_JWT_SECRET;
  }

  if (ORIGINAL_INITIAL_PASSWORD === undefined) {
    delete process.env.INITIAL_PASSWORD;
  } else {
    process.env.INITIAL_PASSWORD = ORIGINAL_INITIAL_PASSWORD;
  }
});

test("isPublicRoute recognizes allowed API prefixes", () => {
  assert.equal(apiAuth.isPublicRoute("/api/auth/login"), true);
  assert.equal(apiAuth.isPublicRoute("/api/v1/chat/completions"), true);
  assert.equal(apiAuth.isPublicRoute("/api/sync/bundle"), true);
  assert.equal(apiAuth.isPublicRoute("/api/monitoring/health", "GET"), true);
  assert.equal(apiAuth.isPublicRoute("/api/monitoring/health", "DELETE"), false);
  assert.equal(apiAuth.isPublicRoute("/api/settings"), false);
});

test("verifyAuth accepts a valid JWT session cookie", async () => {
  process.env.JWT_SECRET = "jwt-secret-for-tests";
  const secret = new TextEncoder().encode(process.env.JWT_SECRET);
  const token = await new SignJWT({ authenticated: true })
    .setProtectedHeader({ alg: "HS256" })
    .setIssuedAt()
    .setExpirationTime("1h")
    .sign(secret);

  const result = await apiAuth.verifyAuth(makeCookieRequest(token));

  assert.equal(result, null);
});

test("verifyAuth falls back to bearer API key validation after a bad JWT", async () => {
  process.env.JWT_SECRET = "jwt-secret-for-tests";
  const key = await apiKeysDb.createApiKey("integration", "machine1234567890");
  const request = {
    cookies: {
      get() {
        return { value: "definitely-not-a-valid-jwt" };
      },
    },
    headers: new Headers({ authorization: `Bearer ${key.key}` }),
    url: "https://example.com/api/v1/models",
  };

  const result = await apiAuth.verifyAuth(request);

  assert.equal(result, null);
});

test("verifyAuth rejects bearer API keys on management routes", async () => {
  const key = await apiKeysDb.createApiKey("integration", "machine1234567890");
  const result = await apiAuth.verifyAuth({
    cookies: {
      get() {
        return undefined;
      },
    },
    headers: new Headers({ authorization: `Bearer ${key.key}` }),
    url: "https://example.com/api/providers",
  });

  assert.equal(result, "Invalid management token");
});

test("verifyAuth rejects requests without valid credentials", async () => {
  const result = await apiAuth.verifyAuth({
    cookies: {
      get() {
        return undefined;
      },
    },
    headers: new Headers({ authorization: "Bearer sk-invalid" }),
    url: "https://example.com/api/v1/models",
  });

  assert.equal(result, "Authentication required");
});

test("isAuthenticated accepts bearer API keys on client-facing routes", async () => {
  const key = await apiKeysDb.createApiKey("integration", "machine1234567890");
  const request = new Request("https://example.com/api/v1/models", {
    headers: { authorization: `Bearer ${key.key}` },
  });

  const result = await apiAuth.isAuthenticated(request);

  assert.equal(result, true);
});

test("isAuthenticated rejects bearer API keys on management routes", async () => {
  process.env.INITIAL_PASSWORD = "bootstrap-password";
  await localDb.updateSettings({ requireLogin: true, password: "" });

  const key = await apiKeysDb.createApiKey("integration", "machine1234567890");
  const request = new Request("https://example.com/api/providers", {
    headers: { authorization: `Bearer ${key.key}` },
  });

  const result = await apiAuth.isAuthenticated(request);

  assert.equal(result, false);
});

test("monitoring health reset route requires dashboard authentication", async () => {
  process.env.INITIAL_PASSWORD = "bootstrap-password";
  await localDb.updateSettings({ requireLogin: true, password: "" });

  const healthRoute = await import("../../src/app/api/monitoring/health/route.ts");
  const response = await healthRoute.DELETE(
    new Request("https://example.com/api/monitoring/health", { method: "DELETE" })
  );

  assert.equal(response.status, 401);
});

test("isAuthenticated returns false when auth is required without valid credentials", async () => {
  // Force requireLogin to be active
  process.env.INITIAL_PASSWORD = "bootstrap-password";
  await localDb.updateSettings({ requireLogin: true, password: "" });

  const request = new Request("https://example.com/api/providers");

  const result = await apiAuth.isAuthenticated(request);

  assert.equal(result, false);
});

test("isAuthRequired is disabled when requireLogin is false", async () => {
  await localDb.updateSettings({ requireLogin: false });

  const result = await apiAuth.isAuthRequired();

  assert.equal(result, false);
});

test("isAuthRequired is disabled while no password exists", async () => {
  await localDb.updateSettings({ requireLogin: true, password: "" });

  const result = await apiAuth.isAuthRequired();

  assert.equal(result, false);
});

test("isAuthRequired keeps fresh bootstrap open only on loopback", async () => {
  await localDb.updateSettings({ requireLogin: true, password: "" });

  assert.equal(await apiAuth.isAuthRequired(new Request("http://localhost/api/providers")), false);
  assert.equal(await apiAuth.isAuthRequired(new Request("http://127.0.0.1/api/providers")), false);
  assert.equal(
    await apiAuth.isAuthRequired(new Request("https://example.com/api/providers")),
    true
  );
});

test("isAuthenticated rejects remote management bootstrap without a configured password", async () => {
  await localDb.updateSettings({ requireLogin: true, password: "" });

  const request = new Request("https://example.com/api/providers");

  assert.equal(await apiAuth.isAuthenticated(request), false);
});

test("isAuthRequired stays enabled when a password exists", async () => {
  await localDb.updateSettings({ requireLogin: true, password: "hashed-password" });

  const result = await apiAuth.isAuthRequired();

  assert.equal(result, true);
});

test("isAuthRequired stays enabled when INITIAL_PASSWORD is present", async () => {
  process.env.INITIAL_PASSWORD = "bootstrap-password";
  await localDb.updateSettings({ requireLogin: true, password: "" });

  const result = await apiAuth.isAuthRequired();

  assert.equal(result, true);

  delete process.env.INITIAL_PASSWORD;
});

test("getApiKeyMetadata recognizes OMNIROUTE_API_KEY environment variable", async () => {
  const envKey = "sk-test-env-key-" + Date.now();
  process.env.OMNIROUTE_API_KEY = envKey;

  const metadata = await apiKeysDb.getApiKeyMetadata(envKey);

  assert.ok(metadata);
  assert.equal(metadata.id, "env-key");
  assert.equal(metadata.name, "Environment Key");

  delete process.env.OMNIROUTE_API_KEY;
});

test("getApiKeyMetadata recognizes ROUTER_API_KEY environment variable", async () => {
  const envKey = "sk-test-router-key-" + Date.now();
  process.env.ROUTER_API_KEY = envKey;

  const metadata = await apiKeysDb.getApiKeyMetadata(envKey);

  assert.ok(metadata);
  assert.equal(metadata.id, "env-key");

  delete process.env.ROUTER_API_KEY;
});