Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix: address #503 review (dir-mode + retry/strip coverage + version p…
…ins)

- runtime/runtime-observability.ts: re-assert dir 0o700 via fs.chmod after
  mkdir — mkdir's mode is a no-op on a pre-existing multi-auth dir, so the
  upgrade path kept old (possibly permissive) perms. POSIX-only, best-effort.
- Bump .codex-plugin/plugin.json + AGENTS.md to 2.1.13-beta.3 (plugin-manifest
  test asserts manifest version == package version; the beta.3 bump left them
  stale).

Tests:
- local-bridge + runtime-rotation-proxy: assert inbound `proxy-authorization`
  (alongside cookie) is stripped on the outbound request, so a refactor dropping
  the delete is caught.
- quota-cache: read-retry (EACCES) + rename-retry (ENOTEMPTY) + last-write-wins
  queue-ordering regressions, pinning the widened retry taxonomy.
- runtime-observability-dir-mode (new, POSIX-only): pre-create CODEX_MULTI_AUTH_DIR
  world-writable, persist a snapshot, assert the dir becomes owner-only — proves
  the chmod-after-mkdir hardening on the upgrade path.
- runtime-observability test fs-mock now exposes chmod.

typecheck + lint + audit:ci clean; full suite 4249 passed / 2 skipped.
  • Loading branch information
ndycode committed Jun 2, 2026
commit 4f0eefce1b977cf66afc195c3f35ff2c169c80fa
2 changes: 1 addition & 1 deletion .codex-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "codex-multi-auth",
"version": "2.1.13-beta.2",
"version": "2.1.13-beta.3",
"description": "Install and operate codex-multi-auth for the official @openai/codex CLI with multi-account OAuth rotation, switching, health checks, and recovery tools.",
"interface": {
"composerIcon": "./assets/codex-multi-auth-icon.svg"
Expand Down
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
Generated: 2026-04-25
Commit: a87e005
Branch: main
Package version: 2.1.13-beta.2
Package version: 2.1.13-beta.3

## OVERVIEW

Expand Down
7 changes: 7 additions & 0 deletions lib/runtime/runtime-observability.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,13 @@ async function writeSnapshot(snapshot: RuntimeObservabilitySnapshot): Promise<vo
// keep it owner-only on POSIX like the other sensitive writers (logger,
// local-client-tokens). mode is a no-op on win32 (ACL-based).
await fs.mkdir(dir, { recursive: true, mode: 0o700 });
// mkdir's mode only applies to a freshly-created dir; an upgrade path with a
// pre-existing multi-auth dir keeps its old (possibly permissive) perms, so
// re-assert 0o700 on POSIX. Best-effort: a concurrent wrapper may race the
// chmod, and win32 ignores POSIX modes.
if (process.platform !== "win32") {
await fs.chmod(dir, 0o700).catch(() => undefined);
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
let lastError: unknown = null;
for (let attempt = 0; attempt < 3; attempt += 1) {
const tempPath = `${path}.${process.pid}.${Date.now()}.${attempt}.tmp`;
Expand Down
2 changes: 2 additions & 0 deletions test/local-bridge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,7 @@ describe("local bridge", () => {
authorization: "Bearer inbound-client-token",
"x-api-key": "inbound-secret-key",
cookie: "session=inbound-cookie-secret",
"proxy-authorization": "Basic inbound-proxy-cred",
},
});

Expand All @@ -327,5 +328,6 @@ describe("local bridge", () => {
expect(headers.get("authorization")).toBeNull();
expect(headers.get("x-api-key")).toBeNull();
expect(headers.get("cookie")).toBeNull();
expect(headers.get("proxy-authorization")).toBeNull();
});
});
113 changes: 113 additions & 0 deletions test/quota-cache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -430,4 +430,117 @@ describe("quota cache", () => {
vi.doUnmock("../lib/logger.js");
}
});

it("retries transient EACCES while loading cache", async () => {
const { loadQuotaCache, getQuotaCachePath } =
await import("../lib/quota-cache.js");
await fs.writeFile(
getQuotaCachePath(),
JSON.stringify({
version: 1,
byAccountId: {
acc_1: {
updatedAt: Date.now(),
status: 200,
model: "gpt-5-codex",
primary: { usedPercent: 12 },
secondary: { usedPercent: 7 },
},
},
byEmail: {},
}),
"utf8",
);

const realRead = fs.readFile.bind(fs);
let attempts = 0;
const readSpy = vi.spyOn(fs, "readFile");
readSpy.mockImplementation(async (...args) => {
if (String(args[0]) === getQuotaCachePath()) {
attempts += 1;
if (attempts === 1) {
const error = new Error("permission denied") as NodeJS.ErrnoException;
error.code = "EACCES";
throw error;
}
}
return realRead(...args);
});

try {
const loaded = await loadQuotaCache();
expect(loaded.byAccountId.acc_1?.model).toBe("gpt-5-codex");
expect(attempts).toBeGreaterThan(1);
} finally {
readSpy.mockRestore();
}
});

it("retries atomic rename on transient ENOTEMPTY errors", async () => {
const { saveQuotaCache, loadQuotaCache } =
await import("../lib/quota-cache.js");
const realRename = fs.rename.bind(fs);
let attempts = 0;
const renameSpy = vi.spyOn(fs, "rename");
renameSpy.mockImplementation(async (...args) => {
attempts += 1;
if (attempts === 1) {
const error = new Error("dir not empty") as NodeJS.ErrnoException;
error.code = "ENOTEMPTY";
throw error;
}
return realRename(...args);
});

try {
await saveQuotaCache({
byAccountId: {
acc_1: {
updatedAt: Date.now(),
status: 200,
model: "gpt-5-codex",
primary: { usedPercent: 40, windowMinutes: 300 },
secondary: { usedPercent: 20, windowMinutes: 10080 },
},
},
byEmail: {},
});
const loaded = await loadQuotaCache();
expect(loaded.byAccountId.acc_1?.model).toBe("gpt-5-codex");
expect(attempts).toBeGreaterThan(1);
} finally {
renameSpy.mockRestore();
}
});

it("serializes concurrent saves so the last write wins", async () => {
const { saveQuotaCache, loadQuotaCache, getQuotaCachePath } =
await import("../lib/quota-cache.js");

const makePayload = (usedPercent: number) => ({
byAccountId: {
acc_1: {
updatedAt: Date.now(),
status: 200,
model: "gpt-5-codex",
planType: "plus",
primary: { usedPercent, windowMinutes: 300 },
secondary: { usedPercent: 5, windowMinutes: 10080 },
},
},
byEmail: {},
});

// Fire two writes back-to-back without awaiting the first; the internal
// quotaCacheWriteQueue serializes them so the second (last) call wins and
// the file is never left torn/interleaved.
const first = saveQuotaCache(makePayload(11));
const second = saveQuotaCache(makePayload(99));
await Promise.all([first, second]);

const raw = await fs.readFile(getQuotaCachePath(), "utf8");
expect(() => JSON.parse(raw)).not.toThrow();
const loaded = await loadQuotaCache();
expect(loaded.byAccountId.acc_1?.primary.usedPercent).toBe(99);
});
});
96 changes: 96 additions & 0 deletions test/runtime-observability-dir-mode.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
Comment thread
ndycode marked this conversation as resolved.
Resolved
import { promises as fs, rmSync, statSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { sleep } from "../lib/utils.js";

// Windows-safe recursive remove with EBUSY/EPERM backoff, mirroring the
// removeDirectoryWithRetry helper in codex-bin-wrapper.test.ts. A bare fs.rm
// can flake on Windows when an antivirus/indexer briefly locks the just-written
// snapshot file.
function isRetriableFsError(error: unknown): boolean {
if (!error || typeof error !== "object" || !("code" in error)) {
return false;
}
const { code } = error as { code?: unknown };
return code === "EBUSY" || code === "EPERM";
}

async function removeDirectoryWithRetry(dir: string): Promise<void> {
const backoffMs = [20, 60, 120];
let lastError: unknown;
for (let attempt = 0; attempt <= backoffMs.length; attempt += 1) {
try {
rmSync(dir, { recursive: true, force: true });
return;
} catch (error) {
lastError = error;
if (!isRetriableFsError(error) || attempt === backoffMs.length) {
break;
}
await sleep(backoffMs[attempt]);
}
}
throw lastError;
}
Comment thread
ndycode marked this conversation as resolved.
Resolved

describe("runtime observability snapshot dir hardening", () => {
let tempRoot: string;
let snapshotDir: string;
let originalDir: string | undefined;
let originalVitest: string | undefined;

beforeEach(async () => {
originalDir = process.env.CODEX_MULTI_AUTH_DIR;
originalVitest = process.env.VITEST;
tempRoot = await fs.mkdtemp(join(tmpdir(), "codex-obs-dirmode-"));
// Pin the multi-auth dir to a deterministic temp subdir; getCodexMultiAuthDir
// returns CODEX_MULTI_AUTH_DIR verbatim when set.
snapshotDir = join(tempRoot, "multi-auth");
process.env.CODEX_MULTI_AUTH_DIR = snapshotDir;
// PERSIST_RUNTIME_SNAPSHOT is computed at module load as VITEST !== "true",
// so blank it before the dynamic import to enable on-disk persistence.
process.env.VITEST = "";
vi.resetModules();
});

afterEach(async () => {
if (originalDir === undefined) {
delete process.env.CODEX_MULTI_AUTH_DIR;
} else {
process.env.CODEX_MULTI_AUTH_DIR = originalDir;
}
if (originalVitest === undefined) {
delete process.env.VITEST;
} else {
process.env.VITEST = originalVitest;
}
await removeDirectoryWithRetry(tempRoot);
});

it.skipIf(process.platform === "win32")(
"re-asserts owner-only (0o700) dir mode on a pre-existing permissive dir",
async () => {
// Upgrade path: the multi-auth dir already exists with permissive perms,
// so mkdir({ mode: 0o700 }) is a no-op and only the explicit chmod can
// tighten it.
await fs.mkdir(snapshotDir, { recursive: true });
await fs.chmod(snapshotDir, 0o777);
expect(statSync(snapshotDir).mode & 0o777).toBe(0o777);

const mod = await import("../lib/runtime/runtime-observability.js");
mod.mutateRuntimeObservabilitySnapshot((snapshot) => {
snapshot.responsesRequests = 1;
});

const snapshotPath = join(snapshotDir, "runtime-observability.json");
await vi.waitFor(() => {
expect(statSync(snapshotPath).isFile()).toBe(true);
});

// chmod runs before the snapshot file is written, so the dir is tightened
// by the time the file exists.
expect(statSync(snapshotDir).mode & 0o777).toBe(0o700);
},
);
});
2 changes: 2 additions & 0 deletions test/runtime-observability.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const writeFileMock = vi.fn(async () => undefined);
const renameMock = vi.fn(async () => undefined);
const unlinkMock = vi.fn(async () => undefined);
const mkdirMock = vi.fn(async () => undefined);
const chmodMock = vi.fn(async () => undefined);
vi.mock("node:fs", () => ({
existsSync: vi.fn(() => true),
readFileSync: readFileSyncMock,
Expand All @@ -15,6 +16,7 @@ vi.mock("node:fs", () => ({
rename: renameMock,
unlink: unlinkMock,
mkdir: mkdirMock,
chmod: chmodMock,
},
}));

Expand Down
2 changes: 2 additions & 0 deletions test/runtime-rotation-proxy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1121,6 +1121,7 @@ describe("runtime rotation proxy", () => {
connection: "close",
"x-custom-trace": "trace-1",
cookie: "session=inbound-cookie-secret",
"proxy-authorization": "Basic inbound-proxy-cred",
},
)
).text();
Expand All @@ -1133,6 +1134,7 @@ describe("runtime rotation proxy", () => {
expect(calls[0]?.headers.get("x-api-key")).toBeNull();
// Inbound client credentials must never ride upstream with the managed token.
expect(calls[0]?.headers.get("cookie")).toBeNull();
expect(calls[0]?.headers.get("proxy-authorization")).toBeNull();
});
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

it("strips expect before forwarding to fetch", async () => {
Expand Down