Skip to content

Commit 96726a1

Browse files
committed
test(gui): cover stale concurrent 401 token clear race
1 parent 92e9677 commit 96726a1

1 file changed

Lines changed: 58 additions & 0 deletions

File tree

‎gui/tests/api-auth-memory.test.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,64 @@ test("concurrent 401s share one token prompt and all retry with the stored token
177177
expect([...new Set(statuses)]).toEqual([200]);
178178
});
179179

180+
test("stale concurrent 401 does not clear a token refreshed by another request", async () => {
181+
// Codex/CodeRabbit race: request A prompts and stores T2; request B still holding stale T1
182+
// must not wipe T2 (clearTokenIfCurrent) before its re-read / shared gate join.
183+
let promptCalls = 0;
184+
let acceptV1 = true;
185+
const release401: Array<() => void> = [];
186+
const mockFetch = (async (_input: RequestInfo | URL, init?: RequestInit) => {
187+
const headers = new Headers(init?.headers);
188+
const key = headers.get("X-OpenCodex-API-Key");
189+
if (key === "token-v2") return new Response("{}", { status: 200 });
190+
if (acceptV1 && key === "token-v1") return new Response("{}", { status: 200 });
191+
if (key === "token-v1") {
192+
await new Promise<void>((resolve) => {
193+
release401.push(resolve);
194+
});
195+
return new Response("unauthorized", { status: 401 });
196+
}
197+
return new Response("unauthorized", { status: 401 });
198+
}) as typeof fetch;
199+
window.prompt = () => {
200+
promptCalls += 1;
201+
return "token-v1";
202+
};
203+
await installMockAuthFetch(mockFetch);
204+
expect((await fetch("/api/config")).status).toBe(200);
205+
expect(promptCalls).toBe(1);
206+
207+
acceptV1 = false;
208+
promptCalls = 0;
209+
window.prompt = () => {
210+
promptCalls += 1;
211+
return "token-v2";
212+
};
213+
214+
const pending = [fetch("/api/config"), fetch("/api/providers")].map((p) => p.then((r) => r.status));
215+
for (let i = 0; i < 20 && release401.length < 2; i += 1) {
216+
await Promise.resolve();
217+
}
218+
expect(release401.length).toBe(2);
219+
220+
for (let i = 0; i < 2; i += 1) {
221+
const done = pending[i]!;
222+
let settled = false;
223+
void done.then(() => {
224+
settled = true;
225+
});
226+
release401.shift()!();
227+
for (let spin = 0; spin < 50 && !settled; spin += 1) {
228+
await Promise.resolve();
229+
}
230+
expect(settled).toBe(true);
231+
}
232+
233+
const statuses = await Promise.all(pending);
234+
expect(promptCalls).toBe(1);
235+
expect([...new Set(statuses)]).toEqual([200]);
236+
});
237+
180238
test("canceling the token prompt once does not reopen it for the rest of the 401 fan-out", async () => {
181239
let promptCalls = 0;
182240
const release401: Array<() => void> = [];

0 commit comments

Comments
 (0)