Skip to content

Commit a6014b9

Browse files
committed
fix(codex): serialize native-main refresh on the CODEX_HOME claim
Reimplements #3000 (author @MarcTCruz) for the #2999 lock-scope half. The refresh lock is keyed on the grant fingerprint and lives under OPENCODEX_HOME (src/codex/account-store.ts:420-422, via getConfigDir). The file it protects is auth.json under CODEX_HOME, which every OpenCodex install on the machine shares regardless of its own home. Two proxies with distinct OPENCODEX_HOMEs therefore took two unrelated locks and refreshed the one credential concurrently; the loser published its rotated grant over the winner's and the provider then rejected it. The outer lock is now withNativeMainExclusiveClaim on resolveNativeProfileContext(), which is the CODEX_HOME coordination the other native-main paths already use (.opencodex-native-main.claim.sqlite). No new primitive, no FFI. Why not #3000's approach: it introduces src/lib/atomic-file-preserving-replace.ts, which dlopens libc.so.6 / libSystem.B.dylib / kernel32.dll for renameat2 / renamex_np / ReplaceFileW and throws "No rename fallback is safe" on anything else. musl names its libc libc.so, not libc.so.6, so publication would crash on Alpine. It also throws MainAccountTokenRefreshError("transient") on an aborted signal BEFORE persistRefreshedMainAuthJson, so a late cancel discards a grant the provider has already rotated -- the only live refresh token, dropped. The existing check-then-rename guard is left as it is: atomicWriteFile with assertMainAuthJsonSnapshotUnchanged in both beforeRename and validateBeforeRename refuses rather than overwrites, and the covering test (refuses to overwrite an external auth writer after refresh) already passes. Lock order is claim (machine-wide) then fingerprint lock (per-grant), never the reverse: two processes holding different fingerprint locks and then reaching for the same claim would deadlock. Mutation-checked: dropping the claim wrapper fails exactly the new test (3 pass / 1 fail), restored to 4/0. Closes #2999.
1 parent 6123be3 commit a6014b9

2 files changed

Lines changed: 88 additions & 2 deletions

File tree

‎src/codex/main-account.ts‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ import { resolveCodexHomeDir } from "./home";
1919
import { assertNotRealCodexHomeUnderTest } from "../lib/test-home-guard";
2020
import { clearAccountNeedsReauth } from "./account-runtime-state";
2121
import { advanceCodexCredentialMutationEpoch } from "./credential-mutation-epoch";
22+
import { withNativeMainExclusiveClaim } from "./native-main-claim";
23+
import { resolveNativeProfileContext } from "./native-profile-store";
2224

2325
export { MAIN_CODEX_ACCOUNT_ID } from "./account-id";
2426

@@ -191,7 +193,21 @@ async function resolveMainAccountToken(
191193
? AbortSignal.any([dependencies.signal, AbortSignal.timeout(30_000)])
192194
: AbortSignal.timeout(30_000);
193195
const lockKey = refreshGrantFingerprintForToken(initial.refreshToken);
194-
return withCodexRefreshFileLock(lockKey, signal, async () => {
196+
// Two locks, because they guard two different things that live in two different
197+
// homes. `withCodexRefreshFileLock` is keyed on the grant fingerprint and lives
198+
// under OPENCODEX_HOME; it serializes refreshes of the SAME grant within one
199+
// install. The file being rewritten is `auth.json` under CODEX_HOME, which every
200+
// OpenCodex install on the machine shares no matter what its own home is -- so two
201+
// proxies with distinct OPENCODEX_HOMEs took two unrelated fingerprint locks and
202+
// refreshed the one credential concurrently (#2999).
203+
//
204+
// The outer claim is the CODEX_HOME coordination the other native-main paths
205+
// already use (`.opencodex-native-main.claim.sqlite`), so this needs no new
206+
// primitive and no FFI. Order is claim (machine-wide) then fingerprint lock
207+
// (per-grant), never the reverse: two processes holding different fingerprint
208+
// locks and then reaching for the same claim would deadlock.
209+
return withNativeMainExclusiveClaim(resolveNativeProfileContext(), () =>
210+
withCodexRefreshFileLock(lockKey, signal, async () => {
195211
const locked = readMainAuthJsonCredential();
196212
if (!locked) throw new MainAuthJsonChangedDuringRefreshError();
197213
if (!locked.refreshToken
@@ -221,7 +237,8 @@ async function resolveMainAccountToken(
221237
const result = persistRefreshedMainAuthJson(locked, refreshed);
222238
clearAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID);
223239
return result;
224-
});
240+
}),
241+
{ waitMs: 30_000 });
225242
}
226243

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

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

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,4 +122,73 @@ describe("native main token refresh", () => {
122122
expect(readFileSync(authPath)).toEqual(original);
123123
expect(readdirSync(home).filter(name => name.includes(".tmp"))).toEqual([]);
124124
});
125+
126+
/**
127+
* #2999: the refresh lock is keyed on the grant fingerprint and lives under
128+
* OPENCODEX_HOME, but the file it protects is `auth.json` under CODEX_HOME, which
129+
* every install on the machine shares. Two proxies with different OPENCODEX_HOMEs
130+
* therefore took two unrelated locks and refreshed the one credential at once, so
131+
* the loser's rotated grant was published over the winner's and then rejected by
132+
* the provider.
133+
*
134+
* The claim this now takes lives in CODEX_HOME, so it is the same lock for both.
135+
* Driven through the real `getValidMainAccountToken` with OPENCODEX_HOME actually
136+
* swapped between the two calls: asserting on the claim primitive directly would
137+
* pass even if `main-account.ts` never took it.
138+
*/
139+
test("two OPENCODEX_HOMEs serialize on the one CODEX_HOME credential", async () => {
140+
const authPath = join(home, "auth.json");
141+
writeFileSync(authPath, JSON.stringify({
142+
tokens: { access_token: expiredJwt(), refresh_token: "old-refresh", account_id: "account-main" },
143+
}));
144+
145+
const homeA = mkdtempSync(join(tmpdir(), "ocx-home-a-"));
146+
const homeB = mkdtempSync(join(tmpdir(), "ocx-home-b-"));
147+
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.
151+
const order: string[] = [];
152+
let release: (() => void) | undefined;
153+
const firstEntered = Promise.withResolvers<void>();
154+
155+
const refreshFor = (label: string, gate: boolean) => async () => {
156+
order.push(`enter:${label}`);
157+
if (gate) {
158+
firstEntered.resolve();
159+
await new Promise<void>(resolve => { release = resolve; });
160+
}
161+
order.push(`leave:${label}`);
162+
return {
163+
accessToken: `fresh-${label}`,
164+
refreshToken: `rotated-${label}`,
165+
expires: Date.now() + 3_600_000,
166+
accountId: "account-main",
167+
};
168+
};
169+
170+
try {
171+
process.env.OPENCODEX_HOME = homeA;
172+
const first = getValidMainAccountToken({ refreshToken: refreshFor("a", true) });
173+
await firstEntered.promise;
174+
175+
// Second install, different OPENCODEX_HOME, same CODEX_HOME. Before the fix
176+
// this entered immediately; now it waits on the shared claim.
177+
process.env.OPENCODEX_HOME = homeB;
178+
const second = getValidMainAccountToken({ refreshToken: refreshFor("b", false) });
179+
await Bun.sleep(50);
180+
expect(order).toEqual(["enter:a"]);
181+
182+
release?.();
183+
await first;
184+
await second.catch(() => null);
185+
expect(order.slice(0, 3)).toEqual(["enter:a", "leave:a", "enter:b"]);
186+
} finally {
187+
release?.();
188+
if (previousOcxHome === undefined) delete process.env.OPENCODEX_HOME;
189+
else process.env.OPENCODEX_HOME = previousOcxHome;
190+
rmSync(homeA, { recursive: true, force: true });
191+
rmSync(homeB, { recursive: true, force: true });
192+
}
193+
});
125194
});

0 commit comments

Comments
 (0)