Skip to content

Commit 6c42d17

Browse files
committed
fix(codex): validate shim refresh transactions
1 parent ee4f88d commit 6c42d17

2 files changed

Lines changed: 116 additions & 16 deletions

File tree

‎src/codex/shim.ts‎

Lines changed: 42 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -46,11 +46,11 @@ group_file=$2
4646
wrapper=$3
4747
timeout_seconds=$4
4848
49-
"$wrapper" --version &
49+
/bin/sh "$wrapper" --version &
5050
launcher_pid=$!
5151
printf '%s\n' "$launcher_pid" > "$group_file"
5252
(
53-
/bin/sleep "$timeout_seconds"
53+
/bin/sleep "$timeout_seconds" || exit 0
5454
printf '%s\n' timeout > "$marker"
5555
kill -KILL -"$launcher_pid" 2>/dev/null || true
5656
) &
@@ -473,7 +473,9 @@ exec ${shQuote(realCodexPath)} "$@"
473473
`;
474474
}
475475

476-
function probeUnixShimInstall(wrapperPath: string): "descendants" | "recursive" | "timeout" | null {
476+
type UnixShimProbeResult = "cleanup" | "descendants" | "recursive" | "timeout" | null;
477+
478+
function probeUnixShimInstall(wrapperPath: string): UnixShimProbeResult {
477479
if (process.platform === "win32") return null;
478480
const env: NodeJS.ProcessEnv = { ...process.env, OCX_SHIM_BYPASS: "1" };
479481
delete env.OCX_SHIM_ACTIVE_PID;
@@ -498,7 +500,13 @@ function probeUnixShimInstall(wrapperPath: string): "descendants" | "recursive"
498500
const timedOut = (result.error as NodeJS.ErrnoException | undefined)?.code === "ETIMEDOUT";
499501
const marker = existsSync(markerPath) ? readFileSync(markerPath, "utf8").trim() : "";
500502
const groupId = existsSync(groupPath) ? Number.parseInt(readFileSync(groupPath, "utf8").trim(), 10) : 0;
501-
if ((timedOut || marker) && Number.isInteger(groupId) && groupId > 0) terminateUnixProcessGroup(groupId);
503+
if ((timedOut || marker) && Number.isInteger(groupId) && groupId > 0) {
504+
try {
505+
terminateUnixProcessGroup(groupId);
506+
} catch {
507+
return "cleanup";
508+
}
509+
}
502510
if (timedOut || marker === "timeout") return "timeout";
503511
if (marker === "descendants") return "descendants";
504512
if (result.status === CODEX_SHIM_REENTRY_EXIT_CODE && result.stderr.includes(CODEX_SHIM_REENTRY_DIAGNOSTIC)) {
@@ -514,6 +522,14 @@ function probeUnixShimInstall(wrapperPath: string): "descendants" | "recursive"
514522
}
515523
}
516524

525+
function probeUnixShimFiles(files: readonly ShimFileState[]): UnixShimProbeResult {
526+
if (process.platform === "win32") return null;
527+
return files
528+
.filter(file => !file.preserveOnly)
529+
.map(file => probeUnixShimInstall(file.wrapperPath))
530+
.find(result => result !== null) ?? null;
531+
}
532+
517533
function unixProcessGroupAlive(groupId: number): boolean {
518534
try {
519535
process.kill(-groupId, 0);
@@ -812,12 +828,20 @@ function refreshShimFile(file: ShimFileState): boolean {
812828
}
813829
if (existsSync(file.wrapperPath) && !isShim(file.wrapperPath)) {
814830
if (file.wrapperPath !== file.originalPath) return false;
815-
replaceOwnedBackup(file.wrapperPath, file.backupPath);
816-
writeShim(file.wrapperPath, file.realPath ?? file.backupPath);
817-
return true;
831+
const replacement = stableShimPathProbe(file.wrapperPath);
832+
if (!replacement) return false;
833+
return applyGuardedRefreshTransaction([{
834+
file,
835+
expectedReplacement: replacement.fingerprint,
836+
sourcePath: file.wrapperPath,
837+
}]);
818838
}
819839
if (!existsSync(file.wrapperPath) && existsSync(file.backupPath)) {
820840
writeShim(file.wrapperPath, file.realPath ?? file.backupPath);
841+
if (probeUnixShimFiles([file]) !== null) {
842+
if (existsSync(file.wrapperPath) && isShim(file.wrapperPath)) unlinkSync(file.wrapperPath);
843+
return false;
844+
}
821845
return true;
822846
}
823847
if (file.originalPath !== file.wrapperPath && existsSync(file.originalPath) && existsSync(file.wrapperPath) && isShim(file.wrapperPath)) {
@@ -1056,6 +1080,7 @@ function applyGuardedRefreshTransaction(
10561080
const journal: GuardedRefreshJournalEntry[] = [];
10571081
let applyError: Error | null = null;
10581082
let fingerprintMismatch = false;
1083+
let unsafeLauncher = false;
10591084
const transactionId = `${process.pid}-${++guardedRefreshTransactionId}`;
10601085

10611086
for (const [index, operation] of operations.entries()) {
@@ -1087,15 +1112,19 @@ function applyGuardedRefreshTransaction(
10871112
}
10881113
}
10891114

1090-
if (!fingerprintMismatch && !applyError && commitState) {
1115+
if (!fingerprintMismatch && !applyError) {
1116+
unsafeLauncher = probeUnixShimFiles(operations.map(operation => operation.file)) !== null;
1117+
}
1118+
1119+
if (!fingerprintMismatch && !applyError && !unsafeLauncher && commitState) {
10911120
try {
10921121
commitState();
10931122
} catch (error) {
10941123
applyError = error instanceof Error ? error : new Error(String(error));
10951124
}
10961125
}
10971126

1098-
if (fingerprintMismatch || applyError) {
1127+
if (fingerprintMismatch || applyError || unsafeLauncher) {
10991128
const rollbackErrors = rollbackGuardedRefresh(journal);
11001129
if (applyError || rollbackErrors.length > 0) {
11011130
throw new AggregateError(
@@ -1193,14 +1222,16 @@ function installCodexShimInternal(options: InstallCodexShimInternalOptions): { i
11931222
if (!target.preserveOnly) writeShim(target.wrapperPath, target.realPath ?? target.backupPath);
11941223
}
11951224
if (process.platform !== "win32") {
1196-
const unsafe = targets.map(target => probeUnixShimInstall(target.wrapperPath)).find(result => result !== null);
1225+
const unsafe = probeUnixShimFiles(targets);
11971226
if (unsafe) {
11981227
rollbackFreshShimInstall(targets);
11991228
const reason = unsafe === "recursive"
12001229
? "the saved launcher resolved back to the generated shim"
12011230
: unsafe === "timeout"
12021231
? `the saved launcher did not finish --version within ${CODEX_SHIM_INSTALL_PROBE_TIMEOUT_MS}ms`
1203-
: "the saved launcher left background descendants running after --version";
1232+
: unsafe === "descendants"
1233+
? "the saved launcher left background descendants running after --version"
1234+
: "the saved launcher's probe process group could not be terminated cleanly";
12041235
return {
12051236
installed: false,
12061237
message: `Refusing Codex autostart shim because ${reason}. The original launcher was restored; reinstall Codex as a concrete executable before enabling codexAutoStart.`,

‎tests/codex-shim.test.ts‎

Lines changed: 74 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,20 @@ import { autoRestoreCodexShim, buildUnixCodexShim, buildWindowsCodexShim, buildW
88
const SHIM_MARKER = "opencodex codex autostart shim";
99
const skipStabilityWait = () => {};
1010

11+
function processState(pid: number): string {
12+
return spawnSync("/bin/ps", ["-o", "stat=", "-p", String(pid)], { encoding: "utf8" }).stdout.trim();
13+
}
14+
15+
function expectProcessGroupMissing(groupId: number): void {
16+
let code: string | undefined;
17+
try {
18+
process.kill(-groupId, 0);
19+
} catch (error) {
20+
code = (error as NodeJS.ErrnoException).code;
21+
}
22+
expect(code).toBe("ESRCH");
23+
}
24+
1125
function withInstalledShim(run: (paths: {
1226
binDir: string;
1327
home: string;
@@ -23,7 +37,7 @@ function withInstalledShim(run: (paths: {
2337
? [join(binDir, "codex.cmd"), join(binDir, "codex.ps1"), join(binDir, "codex")]
2438
: [join(binDir, "codex")];
2539
try {
26-
process.env.PATH = binDir;
40+
process.env.PATH = `${binDir}:${oldPath ?? ""}`;
2741
process.env.OPENCODEX_HOME = home;
2842
for (const wrapper of wrappers) {
2943
writeFileSync(wrapper, process.platform === "win32" ? `real ${wrapper}\n` : "#!/bin/sh\necho real\n", "utf8");
@@ -307,20 +321,27 @@ exit 64
307321
const codexPath = join(binDir, "codex");
308322
const launcherPath = join(binDir, "dynamic-launcher");
309323
const childPidPath = join(home, "child-reentry.pid");
324+
const grandchildPidPath = join(home, "child-reentry-grandchild.pid");
325+
const groupIdPath = join(home, "child-reentry-group.pid");
310326
const original = `#!/bin/sh\nexec "${launcherPath}" "$@"\n`;
311327
try {
312328
process.env.PATH = `${binDir}:${oldPath ?? ""}`;
313329
process.env.OPENCODEX_HOME = home;
314330
writeFileSync(launcherPath, `#!/bin/sh
315331
if [ -n "$OCX_TEST_CHILD_REENTRY" ]; then
316-
/bin/sleep 30
332+
/bin/sleep 30 &
333+
grandchild=$!
334+
printf '%s\\n' "$grandchild" > "${grandchildPidPath}"
335+
wait "$grandchild"
317336
exec codex "$@"
318337
fi
319338
OCX_TEST_CHILD_REENTRY=1
320339
export OCX_TEST_CHILD_REENTRY
340+
printf '%s\\n' "$$" > "${groupIdPath}"
321341
codex "$@" &
322342
child=$!
323343
printf '%s\\n' "$child" > "${childPidPath}"
344+
while [ ! -f "${grandchildPidPath}" ]; do /bin/sleep 0.01; done
324345
exit 0
325346
`, "utf8");
326347
writeFileSync(codexPath, original, "utf8");
@@ -335,8 +356,13 @@ exit 0
335356
expect(existsSync(`${codexPath}.opencodex-real`)).toBe(false);
336357
expect(existsSync(join(home, "codex-shim.json"))).toBe(false);
337358
const childPid = Number.parseInt(readFileSync(childPidPath, "utf8").trim(), 10);
338-
const childState = spawnSync("/bin/ps", ["-o", "stat=", "-p", String(childPid)], { encoding: "utf8" }).stdout.trim();
359+
const grandchildPid = Number.parseInt(readFileSync(grandchildPidPath, "utf8").trim(), 10);
360+
const groupId = Number.parseInt(readFileSync(groupIdPath, "utf8").trim(), 10);
361+
expectProcessGroupMissing(groupId);
362+
const childState = processState(childPid);
363+
const grandchildState = processState(grandchildPid);
339364
expect(childState === "" || childState.startsWith("Z")).toBe(true);
365+
expect(grandchildState === "" || grandchildState.startsWith("Z")).toBe(true);
340366
} finally {
341367
if (oldPath === undefined) delete process.env.PATH;
342368
else process.env.PATH = oldPath;
@@ -382,8 +408,8 @@ wait "$child"
382408
const groupId = Number.parseInt(readFileSync(groupIdPath, "utf8").trim(), 10);
383409
expect(Number.isInteger(childPid)).toBe(true);
384410
expect(Number.isInteger(groupId)).toBe(true);
385-
expect(() => process.kill(-groupId, 0)).toThrow();
386-
const childState = spawnSync("/bin/ps", ["-o", "stat=", "-p", String(childPid)], { encoding: "utf8" }).stdout.trim();
411+
expectProcessGroupMissing(groupId);
412+
const childState = processState(childPid);
387413
expect(childState === "" || childState.startsWith("Z")).toBe(true);
388414
} finally {
389415
if (oldPath === undefined) delete process.env.PATH;
@@ -701,6 +727,49 @@ printf '%s\\n' child-codex
701727
});
702728
});
703729

730+
test("guarded auto-restore rejects a recursive replacement and restores both launcher generations", () => {
731+
if (process.platform === "win32") return;
732+
withInstalledShim(({ binDir, wrappers, backups, statePath }) => {
733+
const dynamicLauncher = join(binDir, "dynamic-codex-launcher");
734+
const replacement = `#!/bin/sh\nexec "${dynamicLauncher}" "$@"\n`;
735+
const oldBackup = readFileSync(backups[0]);
736+
const oldState = readFileSync(statePath);
737+
writeFileSync(dynamicLauncher, "#!/bin/sh\nexec codex \"$@\"\n", "utf8");
738+
writeFileSync(wrappers[0], replacement, "utf8");
739+
chmodSync(dynamicLauncher, 0o755);
740+
chmodSync(wrappers[0], 0o755);
741+
742+
const result = autoRestoreCodexShim({ enabled: () => true, stabilitySleep: skipStabilityWait });
743+
744+
expect(result.status).toBe("deferred");
745+
expect(readFileSync(wrappers[0], "utf8")).toBe(replacement);
746+
expect(readFileSync(backups[0])).toEqual(oldBackup);
747+
expect(readFileSync(statePath)).toEqual(oldState);
748+
});
749+
});
750+
751+
test("direct refresh rejects a recursive replacement without replacing the owned backup", () => {
752+
if (process.platform === "win32") return;
753+
withInstalledShim(({ binDir, wrappers, backups, statePath }) => {
754+
const dynamicLauncher = join(binDir, "dynamic-codex-launcher");
755+
const replacement = `#!/bin/sh\nexec "${dynamicLauncher}" "$@"\n`;
756+
const oldBackup = readFileSync(backups[0]);
757+
const oldState = readFileSync(statePath);
758+
writeFileSync(dynamicLauncher, "#!/bin/sh\nexec codex \"$@\"\n", "utf8");
759+
writeFileSync(wrappers[0], replacement, "utf8");
760+
chmodSync(dynamicLauncher, 0o755);
761+
chmodSync(wrappers[0], 0o755);
762+
763+
const result = installCodexShim();
764+
765+
expect(result.installed).toBe(false);
766+
expect(result.message).toContain("Refusing to overwrite existing backup");
767+
expect(readFileSync(wrappers[0], "utf8")).toBe(replacement);
768+
expect(readFileSync(backups[0])).toEqual(oldBackup);
769+
expect(readFileSync(statePath)).toEqual(oldState);
770+
});
771+
});
772+
704773
test("an aged lock held by a live restore owner is never reclaimed", async () => {
705774
const binDir = mkdtempSync(join(tmpdir(), "ocx-shim-concurrent-bin-"));
706775
const home = mkdtempSync(join(tmpdir(), "ocx-shim-concurrent-home-"));

0 commit comments

Comments
 (0)