Skip to content

Commit 01b4ea3

Browse files
committed
fix(codex): abort contended native-main refresh claims
1 parent a6014b9 commit 01b4ea3

3 files changed

Lines changed: 116 additions & 38 deletions

File tree

‎src/codex/main-account.ts‎

Lines changed: 31 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -206,39 +206,41 @@ async function resolveMainAccountToken(
206206
// primitive and no FFI. Order is claim (machine-wide) then fingerprint lock
207207
// (per-grant), never the reverse: two processes holding different fingerprint
208208
// locks and then reaching for the same claim would deadlock.
209-
return withNativeMainExclusiveClaim(resolveNativeProfileContext(), () =>
210-
withCodexRefreshFileLock(lockKey, signal, async () => {
211-
const locked = readMainAuthJsonCredential();
212-
if (!locked) throw new MainAuthJsonChangedDuringRefreshError();
213-
if (!locked.refreshToken
214-
|| refreshGrantFingerprintForToken(locked.refreshToken) !== lockKey) {
209+
return withNativeMainExclusiveClaim(
210+
resolveNativeProfileContext(),
211+
() => withCodexRefreshFileLock(lockKey, signal, async () => {
212+
const locked = readMainAuthJsonCredential();
213+
if (!locked) throw new MainAuthJsonChangedDuringRefreshError();
214+
if (!locked.refreshToken
215+
|| refreshGrantFingerprintForToken(locked.refreshToken) !== lockKey) {
216+
if (locked.accessToken !== rejectedAccessToken
217+
&& mainAccessTokenFresh(locked.accessToken, Date.now(), 0)) {
218+
return { accessToken: locked.accessToken!, chatgptAccountId: locked.chatgptAccountId };
219+
}
220+
throw new MainAuthJsonChangedDuringRefreshError();
221+
}
215222
if (locked.accessToken !== rejectedAccessToken
216-
&& mainAccessTokenFresh(locked.accessToken, Date.now(), 0)) {
223+
&& mainAccessTokenFresh(locked.accessToken, Date.now(), MAIN_TOKEN_REFRESH_SKEW_MS)) {
217224
return { accessToken: locked.accessToken!, chatgptAccountId: locked.chatgptAccountId };
218225
}
219-
throw new MainAuthJsonChangedDuringRefreshError();
220-
}
221-
if (locked.accessToken !== rejectedAccessToken
222-
&& mainAccessTokenFresh(locked.accessToken, Date.now(), MAIN_TOKEN_REFRESH_SKEW_MS)) {
223-
return { accessToken: locked.accessToken!, chatgptAccountId: locked.chatgptAccountId };
224-
}
225-
const refresh = dependencies.refreshToken
226-
?? ((refreshToken: string, options: { signal: AbortSignal }) => refreshChatGPTToken(refreshToken, options));
227-
let refreshed: OAuthCredentials;
228-
try {
229-
refreshed = await refresh(locked.refreshToken, { signal });
230-
} catch (cause) {
231-
const message = cause instanceof Error ? cause.message.toLowerCase() : "";
232-
const reason = /invalid_grant|invalidated|revoked|expired/.test(message)
233-
? "reauth" as const
234-
: "transient" as const;
235-
throw new MainAccountTokenRefreshError(reason, { cause });
236-
}
237-
const result = persistRefreshedMainAuthJson(locked, refreshed);
238-
clearAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID);
239-
return result;
226+
const refresh = dependencies.refreshToken
227+
?? ((refreshToken: string, options: { signal: AbortSignal }) => refreshChatGPTToken(refreshToken, options));
228+
let refreshed: OAuthCredentials;
229+
try {
230+
refreshed = await refresh(locked.refreshToken, { signal });
231+
} catch (cause) {
232+
const message = cause instanceof Error ? cause.message.toLowerCase() : "";
233+
const reason = /invalid_grant|invalidated|revoked|expired/.test(message)
234+
? "reauth" as const
235+
: "transient" as const;
236+
throw new MainAccountTokenRefreshError(reason, { cause });
237+
}
238+
const result = persistRefreshedMainAuthJson(locked, refreshed);
239+
clearAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID);
240+
return result;
240241
}),
241-
{ waitMs: 30_000 });
242+
{ waitMs: 30_000, signal },
243+
);
242244
}
243245

244246
/** Refresh the CLI-owned native credential before upstream I/O and publish it atomically. */

‎src/codex/native-main-claim.ts‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ export const NATIVE_MAIN_CLAIM_DB = ".opencodex-native-main.claim.sqlite";
1717
export interface NativeMainClaimOptions {
1818
waitMs?: number;
1919
pollMs?: number;
20+
signal?: AbortSignal;
2021
hardenPath?: (path: string) => Promise<void>;
2122
platform?: NodeJS.Platform;
2223
env?: NodeJS.ProcessEnv;
@@ -121,6 +122,22 @@ function releaseClaim(database: Database | undefined, file: StableLockFile | und
121122
try { file?.close(); } catch { /* operation already completed */ }
122123
}
123124

125+
function waitForClaimRetry(ms: number, signal?: AbortSignal): Promise<void> {
126+
if (!signal) return Bun.sleep(ms);
127+
if (signal.aborted) return Promise.reject(signal.reason);
128+
return new Promise((resolve, reject) => {
129+
const timer = setTimeout(() => {
130+
signal.removeEventListener("abort", onAbort);
131+
resolve();
132+
}, ms);
133+
const onAbort = () => {
134+
clearTimeout(timer);
135+
reject(signal.reason);
136+
};
137+
signal.addEventListener("abort", onAbort, { once: true });
138+
});
139+
}
140+
124141
export async function withNativeMainSharedClaim<T>(
125142
context: NativeProfileContext,
126143
operation: () => Promise<T>,
@@ -151,9 +168,11 @@ export async function withNativeMainExclusiveClaim<T>(
151168
operation: () => Promise<T>,
152169
options: NativeMainClaimOptions = {},
153170
): Promise<T> {
171+
const signal = options.signal;
154172
const deadline = Date.now() + Math.max(0, options.waitMs ?? 0);
155173
const pollMs = Math.max(1, options.pollMs ?? 50);
156174
for (;;) {
175+
if (signal?.aborted) throw signal.reason;
157176
let database: Database | undefined;
158177
let file: StableLockFile | undefined;
159178
try {
@@ -162,14 +181,16 @@ export async function withNativeMainExclusiveClaim<T>(
162181
assertStableLockFile(nativeMainClaimPath(context), file);
163182
} catch (error) {
164183
releaseClaim(database, file);
184+
if (signal?.aborted) throw signal.reason;
165185
const mapped = mapClaimSetupError(error, "Native-main credentials are in use.");
166186
if (mapped.code === "NATIVE_MAIN_CLAIM_BUSY" && Date.now() < deadline) {
167-
await Bun.sleep(Math.min(pollMs, Math.max(1, deadline - Date.now())));
187+
await waitForClaimRetry(Math.min(pollMs, Math.max(1, deadline - Date.now())), signal);
168188
continue;
169189
}
170190
throw mapped;
171191
}
172192
try {
193+
if (signal?.aborted) throw signal.reason;
173194
return await operation();
174195
} finally {
175196
releaseClaim(database, file);

‎tests/codex-main-account-refresh.test.ts‎

Lines changed: 63 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -145,9 +145,9 @@ describe("native main token refresh", () => {
145145
const homeA = mkdtempSync(join(tmpdir(), "ocx-home-a-"));
146146
const homeB = mkdtempSync(join(tmpdir(), "ocx-home-b-"));
147147
const previousOcxHome = process.env.OPENCODEX_HOME;
148-
// Overlap is observed, not assumed: each refresh records when it entered and
149-
// left, so a serialized pair reads enter/leave/enter and a concurrent one
150-
// reads enter/enter.
148+
// The first refresh records its entry and exit. A concurrent second refresh would
149+
// add enter:b before the first release; the serialized follower instead rereads
150+
// fresh credentials and does not refresh the now-rotated grant itself.
151151
const order: string[] = [];
152152
let release: (() => void) | undefined;
153153
const firstEntered = Promise.withResolvers<void>();
@@ -160,8 +160,8 @@ describe("native main token refresh", () => {
160160
}
161161
order.push(`leave:${label}`);
162162
return {
163-
accessToken: `fresh-${label}`,
164-
refreshToken: `rotated-${label}`,
163+
access: `fresh-${label}`,
164+
refresh: `rotated-${label}`,
165165
expires: Date.now() + 3_600_000,
166166
accountId: "account-main",
167167
};
@@ -176,13 +176,12 @@ describe("native main token refresh", () => {
176176
// this entered immediately; now it waits on the shared claim.
177177
process.env.OPENCODEX_HOME = homeB;
178178
const second = getValidMainAccountToken({ refreshToken: refreshFor("b", false) });
179-
await Bun.sleep(50);
180179
expect(order).toEqual(["enter:a"]);
181180

182181
release?.();
183182
await first;
184-
await second.catch(() => null);
185-
expect(order.slice(0, 3)).toEqual(["enter:a", "leave:a", "enter:b"]);
183+
await second;
184+
expect(order).toEqual(["enter:a", "leave:a"]);
186185
} finally {
187186
release?.();
188187
if (previousOcxHome === undefined) delete process.env.OPENCODEX_HOME;
@@ -191,4 +190,60 @@ describe("native main token refresh", () => {
191190
rmSync(homeB, { recursive: true, force: true });
192191
}
193192
});
193+
194+
test("aborts a contended native-main refresh before it retries", async () => {
195+
const authPath = join(home, "auth.json");
196+
writeFileSync(authPath, JSON.stringify({
197+
tokens: { access_token: expiredJwt(), refresh_token: "old-refresh", account_id: "account-main" },
198+
}));
199+
200+
const homeA = mkdtempSync(join(tmpdir(), "ocx-home-a-"));
201+
const homeB = mkdtempSync(join(tmpdir(), "ocx-home-b-"));
202+
const previousOcxHome = process.env.OPENCODEX_HOME;
203+
const firstEntered = Promise.withResolvers<void>();
204+
const releaseFirst = Promise.withResolvers<void>();
205+
const abort = new AbortController();
206+
const abortReason = new Error("refresh cancelled while native-main claim was busy");
207+
let secondRefreshStarted = false;
208+
209+
try {
210+
process.env.OPENCODEX_HOME = homeA;
211+
const first = getValidMainAccountToken({
212+
refreshToken: async () => {
213+
firstEntered.resolve();
214+
await releaseFirst.promise;
215+
return {
216+
access: "fresh-a",
217+
refresh: "rotated-a",
218+
expires: Date.now() + 3_600_000,
219+
accountId: "account-main",
220+
};
221+
},
222+
});
223+
await firstEntered.promise;
224+
225+
// The first refresh holds the CODEX_HOME claim. Cancellation must release the
226+
// second caller from that wait instead of letting it refresh after the holder exits.
227+
process.env.OPENCODEX_HOME = homeB;
228+
const second = getValidMainAccountToken({
229+
signal: abort.signal,
230+
refreshToken: async () => {
231+
secondRefreshStarted = true;
232+
throw new Error("must not refresh after cancellation");
233+
},
234+
});
235+
abort.abort(abortReason);
236+
releaseFirst.resolve();
237+
238+
await expect(second).rejects.toBe(abortReason);
239+
await expect(first).resolves.toEqual({ accessToken: "fresh-a", chatgptAccountId: "account-main" });
240+
expect(secondRefreshStarted).toBe(false);
241+
} finally {
242+
releaseFirst.resolve();
243+
if (previousOcxHome === undefined) delete process.env.OPENCODEX_HOME;
244+
else process.env.OPENCODEX_HOME = previousOcxHome;
245+
rmSync(homeA, { recursive: true, force: true });
246+
rmSync(homeB, { recursive: true, force: true });
247+
}
248+
});
194249
});

0 commit comments

Comments
 (0)