forked from lidge-jun/opencodex
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi-auth-memory.test.ts
More file actions
312 lines (283 loc) · 11 KB
/
Copy pathapi-auth-memory.test.ts
File metadata and controls
312 lines (283 loc) · 11 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
import { afterEach, beforeEach, expect, test } from "bun:test";
import { Window } from "happy-dom";
import { installApiAuthFetch, resetApiAuthFetchForTests } from "../src/api";
const LEGACY_TOKEN_KEY = "opencodex-api-token";
const globals = ["document", "window", "navigator", "sessionStorage", "fetch"] as const;
let previousGlobals: Record<(typeof globals)[number], unknown>;
let testWindow: Window;
let originalPrompt: typeof window.prompt;
beforeEach(() => {
previousGlobals = Object.fromEntries(globals.map((key) => [key, Reflect.get(globalThis, key)])) as typeof previousGlobals;
testWindow = new Window({ url: "http://localhost/" });
Object.defineProperties(globalThis, {
document: { configurable: true, value: testWindow.document },
window: { configurable: true, value: testWindow },
navigator: { configurable: true, value: testWindow.navigator },
sessionStorage: { configurable: true, value: testWindow.sessionStorage },
fetch: { configurable: true, value: testWindow.fetch.bind(testWindow) },
});
originalPrompt = window.prompt;
resetApiAuthFetchForTests();
sessionStorage.clear();
});
afterEach(() => {
window.prompt = originalPrompt;
resetApiAuthFetchForTests();
testWindow.close();
for (const key of globals) {
Object.defineProperty(globalThis, key, { configurable: true, value: previousGlobals[key] });
}
});
async function installMockAuthFetch(handler: typeof fetch): Promise<void> {
Object.defineProperty(globalThis, "fetch", { configurable: true, value: handler });
Object.defineProperty(window, "fetch", { configurable: true, value: handler });
installApiAuthFetch();
// installApiAuthFetch replaces window.fetch — keep globalThis in sync for bare `fetch()`.
Object.defineProperty(globalThis, "fetch", { configurable: true, value: window.fetch });
}
test("installApiAuthFetch deletes legacy sessionStorage token without reading it", () => {
sessionStorage.setItem(LEGACY_TOKEN_KEY, "legacy-secret");
let getItemCalls = 0;
const storage = sessionStorage;
const originalGetItem = storage.getItem.bind(storage);
storage.getItem = ((key: string) => {
getItemCalls += 1;
return originalGetItem(key);
}) as typeof storage.getItem;
try {
installApiAuthFetch();
expect(getItemCalls).toBe(0);
expect(originalGetItem(LEGACY_TOKEN_KEY)).toBeNull();
} finally {
storage.getItem = originalGetItem;
}
});
test("prompted API tokens stay memory-only and are not written to sessionStorage", async () => {
sessionStorage.setItem(LEGACY_TOKEN_KEY, "legacy-secret");
let authorized = false;
const mockFetch = (async (_input: RequestInfo | URL, init?: RequestInit) => {
const headers = new Headers(init?.headers);
if (headers.get("X-OpenCodex-API-Key") === "fresh-token") {
authorized = true;
return new Response("{}", { status: 200 });
}
return new Response("unauthorized", { status: 401 });
}) as typeof fetch;
window.prompt = () => "fresh-token";
await installMockAuthFetch(mockFetch);
const res = await fetch("/api/config");
expect(res.status).toBe(200);
expect(authorized).toBe(true);
expect(sessionStorage.getItem(LEGACY_TOKEN_KEY)).toBeNull();
expect(sessionStorage.length).toBe(0);
});
test("cross-origin /api/* requests do not receive the API key or token prompt", async () => {
let promptCalls = 0;
let phase: "seed" | "cross" = "seed";
const seenHeaders: Array<string | null> = [];
const stateful = (async (_input: RequestInfo | URL, init?: RequestInit) => {
const headers = new Headers(init?.headers);
seenHeaders.push(headers.get("X-OpenCodex-API-Key"));
if (phase === "seed") {
if (headers.get("X-OpenCodex-API-Key") === "local-token") return new Response("{}", { status: 200 });
return new Response("unauthorized", { status: 401 });
}
return new Response("unauthorized", { status: 401 });
}) as typeof fetch;
window.prompt = () => {
promptCalls += 1;
return "local-token";
};
await installMockAuthFetch(stateful);
expect((await fetch("/api/config")).status).toBe(200);
expect(promptCalls).toBe(1);
phase = "cross";
const beforeCrossPrompts = promptCalls;
seenHeaders.length = 0;
const cross = await fetch("https://evil.example/api/config");
expect(cross.status).toBe(401);
expect(seenHeaders).toEqual([null]);
expect(promptCalls).toBe(beforeCrossPrompts);
});
test("concurrent 401s share one token prompt and all retry with the stored token", async () => {
// Repro for #647: many /api/* requests start without a token (dashboard fan-out).
// Delivering 401s one-by-one after each auth cycle finishes matches the browser case where
// window.prompt blocks the main thread: each continuation still holds a captured null token
// and must reuse the in-memory token from an earlier request instead of prompting again.
let promptCalls = 0;
const release401: Array<() => void> = [];
const mockFetch = (async (_input: RequestInfo | URL, init?: RequestInit) => {
const headers = new Headers(init?.headers);
if (headers.get("X-OpenCodex-API-Key") === "shared-token") {
return new Response("{}", { status: 200 });
}
await new Promise<void>((resolve) => {
release401.push(resolve);
});
return new Response("unauthorized", { status: 401 });
}) as typeof fetch;
window.prompt = () => {
promptCalls += 1;
return "shared-token";
};
await installMockAuthFetch(mockFetch);
const endpoints = [
"/api/config",
"/api/providers",
"/api/models",
"/api/selected-models",
"/api/disabled-models",
"/api/effort-caps",
"/api/sidecar-settings",
"/api/injection-model",
"/api/v2",
"/api/keys",
"/api/provider-presets",
"/api/key-providers",
"/api/oauth/providers",
"/api/codex-auth/accounts",
];
const pending = endpoints.map((path) => fetch(path).then((r) => r.status));
// Let every request reach the 401 gate before any response is delivered.
for (let i = 0; i < 20 && release401.length < endpoints.length; i += 1) {
await Promise.resolve();
}
expect(release401.length).toBe(endpoints.length);
for (let i = 0; i < endpoints.length; i += 1) {
const done = pending[i]!;
let settled = false;
void done.then(() => {
settled = true;
});
release401.shift()!();
for (let spin = 0; spin < 50 && !settled; spin += 1) {
await Promise.resolve();
}
expect(settled).toBe(true);
}
const statuses = await Promise.all(pending);
expect(promptCalls).toBe(1);
expect([...new Set(statuses)]).toEqual([200]);
});
test("stale concurrent 401 does not clear a token refreshed by another request", async () => {
// Codex/CodeRabbit race: request A prompts and stores T2; request B still holding stale T1
// must not wipe T2 (clearTokenIfCurrent) before its re-read / shared gate join.
let promptCalls = 0;
let acceptV1 = true;
const release401: Array<() => void> = [];
const mockFetch = (async (_input: RequestInfo | URL, init?: RequestInit) => {
const headers = new Headers(init?.headers);
const key = headers.get("X-OpenCodex-API-Key");
if (key === "token-v2") return new Response("{}", { status: 200 });
if (acceptV1 && key === "token-v1") return new Response("{}", { status: 200 });
if (key === "token-v1") {
await new Promise<void>((resolve) => {
release401.push(resolve);
});
return new Response("unauthorized", { status: 401 });
}
return new Response("unauthorized", { status: 401 });
}) as typeof fetch;
window.prompt = () => {
promptCalls += 1;
return "token-v1";
};
await installMockAuthFetch(mockFetch);
expect((await fetch("/api/config")).status).toBe(200);
expect(promptCalls).toBe(1);
acceptV1 = false;
promptCalls = 0;
window.prompt = () => {
promptCalls += 1;
return "token-v2";
};
const pending = [fetch("/api/config"), fetch("/api/providers")].map((p) => p.then((r) => r.status));
for (let i = 0; i < 20 && release401.length < 2; i += 1) {
await Promise.resolve();
}
expect(release401.length).toBe(2);
for (let i = 0; i < 2; i += 1) {
const done = pending[i]!;
let settled = false;
void done.then(() => {
settled = true;
});
release401.shift()!();
for (let spin = 0; spin < 50 && !settled; spin += 1) {
await Promise.resolve();
}
expect(settled).toBe(true);
}
const statuses = await Promise.all(pending);
expect(promptCalls).toBe(1);
expect([...new Set(statuses)]).toEqual([200]);
});
test("canceling the token prompt once does not reopen it for the rest of the 401 fan-out", async () => {
let promptCalls = 0;
const release401: Array<() => void> = [];
const mockFetch = (async (_input: RequestInfo | URL, init?: RequestInit) => {
const headers = new Headers(init?.headers);
if (headers.get("X-OpenCodex-API-Key")) {
return new Response("{}", { status: 200 });
}
await new Promise<void>((resolve) => {
release401.push(resolve);
});
return new Response("unauthorized", { status: 401 });
}) as typeof fetch;
window.prompt = () => {
promptCalls += 1;
return null;
};
await installMockAuthFetch(mockFetch);
const endpoints = ["/api/config", "/api/providers", "/api/models", "/api/keys"];
const pending = endpoints.map((path) => fetch(path).then((r) => r.status));
for (let i = 0; i < 20 && release401.length < endpoints.length; i += 1) {
await Promise.resolve();
}
expect(release401.length).toBe(endpoints.length);
for (let i = 0; i < endpoints.length; i += 1) {
const done = pending[i]!;
let settled = false;
void done.then(() => {
settled = true;
});
release401.shift()!();
for (let spin = 0; spin < 50 && !settled; spin += 1) {
await Promise.resolve();
}
expect(settled).toBe(true);
}
const statuses = await Promise.all(pending);
expect(promptCalls).toBe(1);
expect([...new Set(statuses)]).toEqual([401]);
});
test("data-plane requests never receive the management token or prompt", async () => {
let promptCalls = 0;
let phase: "seed" | "cross" = "seed";
const seenHeaders: Array<string | null> = [];
const stateful = (async (_input: RequestInfo | URL, init?: RequestInit) => {
const headers = new Headers(init?.headers);
seenHeaders.push(headers.get("X-OpenCodex-API-Key"));
if (phase === "seed") {
if (headers.get("X-OpenCodex-API-Key") === "local-token") return new Response("{}", { status: 200 });
return new Response("unauthorized", { status: 401 });
}
return new Response("unauthorized", { status: 401 });
}) as typeof fetch;
window.prompt = () => {
promptCalls += 1;
return "local-token";
};
await installMockAuthFetch(stateful);
expect((await fetch("/v1/models")).status).toBe(401);
expect(seenHeaders).toEqual([null]);
expect(promptCalls).toBe(0);
phase = "cross";
const beforeCrossPrompts = promptCalls;
seenHeaders.length = 0;
const cross = await fetch("https://evil.example/v1/models");
expect(cross.status).toBe(401);
expect(seenHeaders).toEqual([null]);
expect(promptCalls).toBe(beforeCrossPrompts);
});