Skip to content

Commit 94a4447

Browse files
committed
fix(codex): guard refresh recovery exchange races
1 parent 75f7c07 commit 94a4447

2 files changed

Lines changed: 70 additions & 18 deletions

File tree

‎src/codex/native-main-refresh-publication.ts‎

Lines changed: 31 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import type { NativeProfileContext } from "./native-profile-store";
77

88
const JOURNAL = ".opencodex-native-main-refresh.json";
99
const TRANSACTION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
10+
let beforeRecoveryReplaceForTests: (() => void) | null = null;
1011

1112
type Journal = {
1213
version: 1;
@@ -90,6 +91,22 @@ function cleanup(context: NativeProfileContext, journal: Journal): void {
9091
}
9192
}
9293

94+
function settlePreparedReplacement(
95+
context: NativeProfileContext,
96+
journal: Journal,
97+
displacedPath: string,
98+
rollbackPath: string,
99+
): void {
100+
const displaced = readExact(displacedPath);
101+
if (!displaced) throw new NativeMainRefreshPublicationError();
102+
if (digest(displaced) !== journal.expectedSha256) {
103+
restoreFilePreservingTarget(displacedPath, journal.targetPath, rollbackPath);
104+
const restored = readExact(journal.targetPath);
105+
if (!restored || !restored.equals(displaced)) throw new NativeMainRefreshPublicationError();
106+
}
107+
cleanup(context, journal);
108+
}
109+
93110
/** Recover only a transaction whose exact hashes prove one deterministic outcome. */
94111
export function recoverNativeMainRefreshPublication(context: NativeProfileContext): void {
95112
const path = journalPath(context);
@@ -103,31 +120,24 @@ export function recoverNativeMainRefreshPublication(context: NativeProfileContex
103120
const stagedBytes = readExact(staged);
104121
const displacedPath = process.platform === "win32" ? previous : staged;
105122
const rollbackPath = process.platform === "win32" ? staged : previous;
106-
const displacedBytes = readExact(displacedPath);
107123
if (!canonical) throw new NativeMainRefreshPublicationError();
108124
if (digest(canonical) === journal.expectedSha256 && stagedBytes && digest(stagedBytes) === journal.replacementSha256) {
109125
try {
126+
const hook = beforeRecoveryReplaceForTests;
127+
beforeRecoveryReplaceForTests = null;
128+
hook?.();
110129
replaceFilePreservingTarget(staged, journal.targetPath, previous);
111-
cleanup(context, { ...journal, phase: "replaced" });
130+
settlePreparedReplacement(context, journal, displacedPath, rollbackPath);
112131
} catch (cause) {
113132
throw new NativeMainRefreshPublicationError({ cause });
114133
}
115134
return;
116135
}
117136
if (digest(canonical) === journal.replacementSha256) {
118137
if (journal.phase === "prepared") {
119-
if (!displacedBytes) throw new NativeMainRefreshPublicationError();
120-
if (digest(displacedBytes) !== journal.expectedSha256) {
121-
try {
122-
restoreFilePreservingTarget(displacedPath, journal.targetPath, rollbackPath);
123-
const restored = readExact(journal.targetPath);
124-
if (!restored || !restored.equals(displacedBytes)) throw new NativeMainRefreshPublicationError();
125-
cleanup(context, journal);
126-
} catch (cause) {
127-
throw new NativeMainRefreshPublicationError({ cause });
128-
}
129-
return;
130-
}
138+
try { settlePreparedReplacement(context, journal, displacedPath, rollbackPath); }
139+
catch (cause) { throw new NativeMainRefreshPublicationError({ cause }); }
140+
return;
131141
}
132142
try { cleanup(context, journal); } catch (cause) { throw new NativeMainRefreshPublicationError({ cause }); }
133143
return;
@@ -169,12 +179,12 @@ export function publishNativeMainRefresh(
169179
if (!displaced || digest(displaced) !== journal.expectedSha256) {
170180
const canonical = readExact(targetPath);
171181
if (canonical && digest(canonical) === journal.replacementSha256) {
172-
restoreFilePreservingTarget(
182+
settlePreparedReplacement(
183+
context,
184+
journal,
173185
process.platform === "win32" ? previous : staged,
174-
targetPath,
175186
process.platform === "win32" ? staged : previous,
176187
);
177-
cleanup(context, journal);
178188
}
179189
throw new NativeMainRefreshPublicationError();
180190
}
@@ -194,3 +204,7 @@ export function publishNativeMainRefresh(
194204
export function nativeMainRefreshJournalBasename(): string {
195205
return basename(JOURNAL);
196206
}
207+
208+
export function setNativeMainBeforeRecoveryReplaceHookForTests(hook: (() => void) | null): void {
209+
beforeRecoveryReplaceForTests = hook;
210+
}

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

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,10 @@ import {
2222
MainAccountTokenRefreshError,
2323
setMainAuthJsonBeforeRenameHookForTests,
2424
} from "../src/codex/main-account";
25-
import { recoverNativeMainRefreshPublication } from "../src/codex/native-main-refresh-publication";
25+
import {
26+
recoverNativeMainRefreshPublication,
27+
setNativeMainBeforeRecoveryReplaceHookForTests,
28+
} from "../src/codex/native-main-refresh-publication";
2629
import { resolveNativeProfileContext } from "../src/codex/native-profile-store";
2730

2831
let home: string;
@@ -54,6 +57,7 @@ beforeEach(() => {
5457

5558
afterEach(() => {
5659
setMainAuthJsonBeforeRenameHookForTests(null);
60+
setNativeMainBeforeRecoveryReplaceHookForTests(null);
5761
if (previousCodexHome === undefined) delete process.env.CODEX_HOME;
5862
else process.env.CODEX_HOME = previousCodexHome;
5963
rmSync(home, { recursive: true, force: true });
@@ -545,6 +549,40 @@ describe("native main token refresh", () => {
545549
expect(existsSync(previousPath)).toBe(false);
546550
});
547551

552+
test("preserves an external write that races a prepared recovery exchange", () => {
553+
const authPath = join(home, "auth.json");
554+
const transactionId = "11111111-1111-4111-8111-111111111111";
555+
const stagedBasename = `.opencodex-native-main-refresh.${transactionId}.new`;
556+
const previousBasename = `.opencodex-native-main-refresh.${transactionId}.previous`;
557+
const stagedPath = join(home, stagedBasename);
558+
const previousPath = join(home, previousBasename);
559+
const journalPath = join(home, ".opencodex-native-main-refresh.json");
560+
const original = JSON.stringify({ tokens: { access_token: "old-access", refresh_token: "old-refresh" } });
561+
const replacement = JSON.stringify({ tokens: { access_token: "new-access", refresh_token: "new-refresh" } });
562+
const external = JSON.stringify({ tokens: { access_token: "external-access", refresh_token: "external-refresh" } });
563+
const digest = (value: string) => createHash("sha256").update(value).digest("hex");
564+
writeFileSync(authPath, original);
565+
writeFileSync(stagedPath, replacement);
566+
writeFileSync(journalPath, JSON.stringify({
567+
version: 1,
568+
transactionId,
569+
targetPath: authPath,
570+
stagedBasename,
571+
previousBasename,
572+
phase: "prepared",
573+
expectedSha256: digest(original),
574+
replacementSha256: digest(replacement),
575+
}));
576+
setNativeMainBeforeRecoveryReplaceHookForTests(() => writeFileSync(authPath, external));
577+
578+
recoverNativeMainRefreshPublication(resolveNativeProfileContext());
579+
580+
expect(readFileSync(authPath, "utf8")).toBe(external);
581+
expect(existsSync(journalPath)).toBe(false);
582+
expect(existsSync(stagedPath)).toBe(false);
583+
expect(existsSync(previousPath)).toBe(false);
584+
});
585+
548586
test("retains an unprovable prepared replacement without a displaced artifact", () => {
549587
const authPath = join(home, "auth.json");
550588
const transactionId = "11111111-1111-4111-8111-111111111111";

0 commit comments

Comments
 (0)