OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
test(runtime): coordinate credential-lock fixture owner lifetime (#1905)
jameshiester-oaied299f7532e9
diff --git a/sdk/typescript/scripts/fixtures/credential-lock.mjs b/sdk/typescript/scripts/fixtures/credential-lock.mjsindex 2f2a3b04b..d04218411 100644--- a/sdk/typescript/scripts/fixtures/credential-lock.mjs+++ b/sdk/typescript/scripts/fixtures/credential-lock.mjs@@ -1,5 +1,5 @@import assert from "node:assert/strict";-import { execFile, spawn } from "node:child_process";+import { spawn } from "node:child_process";import { once } from "node:events";import {lstat,@@ -12,7 +12,6 @@ import {} from "node:fs/promises";import { join } from "node:path";import { createInterface } from "node:readline";-import { promisify } from "node:util";const [runtimeUrl, directory, mode] = process.argv.slice(2);const {@@ -22,14 +21,18 @@ const {if (mode === "hold") {const release = await acquire(directory);+ const block = once(process.stdin, "data");process.stdout.write("locked\n");- await once(process.stdin, "data");+ await block;await new Promise((resolve) => process.stdout.write("blocked\n", resolve));// Stall the owner and any JavaScript heartbeat. Bound the wait so the holder// can exit if its parent dies.- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20_000);+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 120_000);await release();} else if (mode === "legacy") {+ const start = once(process.stdin, "data");+ process.stdout.write("ready\n");+ await start;const lock = join(directory, ".codex-security-scan.lock");const ownerPath = join(lock, "owner.json");const original = await lstat(lock);@@ -68,61 +71,97 @@ if (mode === "hold") {{stdio: ["pipe", "pipe", "pipe"],windowsHide: true,- timeout: 20_000,- killSignal: "SIGKILL",},);const exited = once(holder, "exit");+ const started = Date.now();+ let phase = "holder startup";+ let watchdogExpired = false;+ // The parent controls normal teardown. This is only an emergency bound, not+ // a holder lifetime that competes with slow process startup or ACL work.+ const watchdog = setTimeout(() => {+ watchdogExpired = true;+ holder.kill("SIGKILL");+ }, 90_000);let stderr = "";holder.stderr.setEncoding("utf8").on("data", (chunk) => {stderr += chunk;});const lines = createInterface({ input: holder.stdout });const output = lines[Symbol.asyncIterator]();+ const ownerExited = exited.then(([code, signal]) => {+ throw new Error(+ `Credential-lock holder exited during ${phase} after ${Date.now() - started}ms (code=${code}, signal=${signal}, watchdog=${watchdogExpired}): ${stderr}`,+ );+ });+ // Keep observing exits between awaits without an unhandled rejection.+ ownerExited.catch(() => {});+ const whileOwned = (operation) => Promise.race([operation, ownerExited]);async function expectOutput(expected) {- const line = await Promise.race([- output.next(),- exited.then(() => {- throw new Error(`Credential-lock holder exited early: ${stderr}`);- }),- ]);+ const line = await whileOwned(output.next());assert.equal(line.value, expected);}let release;+ let legacy;+ let legacyExited;+ let legacyLines;+ const controller = new AbortController();try {await expectOutput("locked");const activeOwner = await readFile(ownerPath, "utf8");const stale = new Date(Date.now() - 60_000);- await utimes(lock, stale, stale);- const legacy = await promisify(execFile)(+ phase = "legacy contender startup";+ legacy = spawn(process.execPath,[process.argv[1], runtimeUrl, home, "legacy"],- { timeout: 10_000, windowsHide: true },+ { stdio: ["pipe", "pipe", "pipe"], windowsHide: true },+ );+ legacyExited = once(legacy, "exit");+ let legacyStderr = "";+ legacy.stderr.setEncoding("utf8").on("data", (chunk) => {+ legacyStderr += chunk;+ });+ legacyLines = createInterface({ input: legacy.stdout });+ const legacyOutput = legacyLines[Symbol.asyncIterator]();+ assert.equal((await whileOwned(legacyOutput.next())).value, "ready");+ // Age the directory only once the contender has imported the runtime. A+ // heartbeat during slow startup must not invalidate its initial observation.+ await utimes(lock, stale, stale);+ phase = "legacy heartbeat observation";+ legacy.stdin.end("start\n");+ assert.equal(+ (await whileOwned(legacyOutput.next())).value,+ "legacy blocked",+ `Legacy contender failed: ${legacyStderr}`,);- assert.equal(legacy.stdout.trim(), "legacy blocked");+ assert.deepEqual(await whileOwned(legacyExited), [0, null], legacyStderr);assert.equal(await readFile(ownerPath, "utf8"), activeOwner);- holder.stdin.write("block\n");+ phase = "paused owner exclusion";+ holder.stdin.end("block\n");await expectOutput("blocked");const owner = JSON.parse(await readFile(ownerPath, "utf8"));await utimes(lock, stale, stale);- const controller = new AbortController();// Wait longer than the former five-second stale-heartbeat grace period.const timeout = setTimeout(() => controller.abort(), 6_000);try {- await assert.rejects(- async () => {- release = await acquire(home, controller.signal);- },- { name: "AbortError" },+ await whileOwned(+ assert.rejects(+ async () => {+ release = await acquire(home, controller.signal);+ },+ { name: "AbortError" },+ ),);} finally {clearTimeout(timeout);}assert.deepEqual(JSON.parse(await readFile(ownerPath, "utf8")), owner);+ phase = "intentional owner termination";+ clearTimeout(watchdog);holder.kill("SIGKILL");await exited;// Reuse a known live PID without relying on the OS to recycle one in a test.@@ -140,8 +179,13 @@ if (mode === "hold") {"Active owner protected from released clients; paused owner protected; crashed owner with reused PID recovered.",);} finally {+ clearTimeout(watchdog);+ controller.abort();+ legacy?.kill("SIGKILL");holder.kill("SIGKILL");await exited;+ await legacyExited;+ legacyLines?.close();lines.close();await release?.();}diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.tsindex 2f1cd5e98..aa4b2399f 100644--- a/sdk/typescript/tests-ts/runtime.test.ts+++ b/sdk/typescript/tests-ts/runtime.test.ts@@ -43,7 +43,7 @@ import { PassThrough } from "node:stream";import { createInterface } from "node:readline";import { setImmediate as nextTurn } from "node:timers/promises";import { promisify } from "node:util";-import { fileURLToPath } from "node:url";+import { fileURLToPath, pathToFileURL } from "node:url";import { afterEach, describe, expect, mock, spyOn, test } from "bun:test";import { strToU8, zipSync } from "fflate";import { build } from "esbuild";@@ -3323,9 +3323,88 @@ describe("runtime directories and plugin Python boundary", () => {new URL("../src/runtime.ts", import.meta.url).href,join(root, "state"),],- { timeout: 25_000, windowsHide: true },+ { timeout: 120_000, windowsHide: true },);- });+ }, 125_000);++ test("credential-lock fixture tolerates slow holder and legacy startup", async () => {+ const root = await temporaryDirectory();+ const runtime = join(root, "delayed-runtime.mjs");+ await writeFile(+ runtime,+ `export * from ${JSON.stringify(new URL("../src/runtime.ts", import.meta.url).href)};+ // Exceed the old holder lifetime and allow a heartbeat during legacy startup.+ const mode = process.argv[4];+ if (mode === "hold" || mode === "legacy") {+ await new Promise(resolve => setTimeout(resolve, mode === "hold" ? 21_000 : 6_000));+ }+ `,+ );+ await promisify(execFile)(+ process.execPath,+ [+ fileURLToPath(+ new URL("../scripts/fixtures/credential-lock.mjs", import.meta.url),+ ),+ pathToFileURL(runtime).href,+ join(root, "state"),+ ],+ { timeout: 120_000, windowsHide: true },+ );+ }, 125_000);++ test("credential-lock fixture diagnoses an owner exit during legacy startup", async () => {+ const root = await temporaryDirectory();+ const runtime = join(root, "exiting-runtime.mjs");+ const runtimeUrl = JSON.stringify(+ new URL("../src/runtime.ts", import.meta.url).href,+ );+ await writeFile(+ runtime,+ `export * from ${runtimeUrl};+ import { acquireCodexSecurityCredentialHomeLock as acquire } from ${runtimeUrl};+ import { existsSync } from "node:fs";+ import { writeFile } from "node:fs/promises";+ import { join } from "node:path";+ import { once } from "node:events";+ const exitMarker = join(process.argv[3], "exit-holder");+ export async function acquireCodexSecurityCredentialHomeLock(...args) {+ const release = await acquire(...args);+ if (process.argv[4] === "hold") {+ setInterval(() => {+ if (existsSync(exitMarker)) process.exit(23);+ }, 25);+ }+ return release;+ }+ if (process.argv[4] === "legacy") {+ // Coordinate an explicit exit: Windows reports external termination as+ // an exit code instead of a Unix signal.+ await writeFile(exitMarker, "exit");+ // Stay in startup until the parent notices the owner exit and cleans up.+ process.stdin.resume();+ await once(process.stdin, "end");+ }+ `,+ );+ await expect(+ promisify(execFile)(+ process.execPath,+ [+ fileURLToPath(+ new URL("../scripts/fixtures/credential-lock.mjs", import.meta.url),+ ),+ pathToFileURL(runtime).href,+ join(root, "state"),+ ],+ { timeout: 120_000, windowsHide: true },+ ),+ ).rejects.toMatchObject({+ stderr: expect.stringMatching(+ /Credential-lock holder exited during legacy contender startup.*code=23, signal=null, watchdog=false/,+ ),+ });+ }, 125_000);test("does not rewrite Windows credential ACLs while polling a held lock", async () => {const root = await temporaryDirectory();