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
fix(runtime): release inherited command pipes after cancellation (#1705)
Michael D'Angelo2415a64e5c47
diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.tsindex 8c00ad150..4cdcef575 100644--- a/sdk/typescript/src/runtime.ts+++ b/sdk/typescript/src/runtime.ts@@ -3142,6 +3142,7 @@ export async function runCodexCommand(): Promise<CodexCommandResult> {const cancellation = archiveHandshake ? new AbortController() : undefined;const abort = () => cancellation?.abort(signal?.reason);+ const commandSignal = cancellation?.signal ?? signal;let awaitingArchive = archiveHandshake;const child = spawn(executablePathForSpawn(command.command),@@ -3150,7 +3151,7 @@ export async function runCodexCommand(env: environment,stdio: ["pipe", "pipe", "pipe"],windowsHide: true,- signal: cancellation?.signal ?? signal,+ signal: commandSignal,},);let stdout = "";@@ -3191,6 +3192,17 @@ export async function runCodexCommand(: reject(processError),);});+ const releaseCanceledPipes = () => {+ if (!commandSignal?.aborted) return;+ if (child.exitCode === null && child.signalCode === null) return;+ child.stdin.destroy();+ child.stdout.destroy();+ child.stderr.destroy();+ };+ commandSignal?.addEventListener("abort", releaseCanceledPipes, {+ once: true,+ });+ child.once("exit", releaseCanceledPipes);if (archiveHandshake) {signal?.addEventListener("abort", abort, { once: true });if (signal?.aborted) abort();@@ -3202,6 +3214,8 @@ export async function runCodexCommand(return await completion;} finally {if (archiveHandshake) signal?.removeEventListener("abort", abort);+ commandSignal?.removeEventListener("abort", releaseCanceledPipes);+ child.removeListener("exit", releaseCanceledPipes);}}diff --git a/sdk/typescript/tests-ts/codex-process-cancellation.test.ts b/sdk/typescript/tests-ts/codex-process-cancellation.test.tsindex 48d9c81e8..d49377bbc 100644--- a/sdk/typescript/tests-ts/codex-process-cancellation.test.ts+++ b/sdk/typescript/tests-ts/codex-process-cancellation.test.ts@@ -3,18 +3,20 @@ import {type ChildProcessWithoutNullStreams,type SpawnOptions,} from "node:child_process";+import * as childProcess from "node:child_process";import { getEventListeners } from "node:events";import { existsSync } from "node:fs";-import { mkdir, writeFile } from "node:fs/promises";+import { mkdir, readFile, writeFile } from "node:fs/promises";import { join } from "node:path";import {setImmediate as nextTurn,setTimeout as delay,} from "node:timers/promises";import { fileURLToPath } from "node:url";-import { afterEach, expect, test } from "bun:test";+import { afterEach, expect, spyOn, test } from "bun:test";import { CodexReviewRunner } from "../src/deduplication/codex-review.js";import { sendFeedback } from "../src/feedback.js";+import { runCodexCommand } from "../src/runtime.js";import { nodeCommand } from "./support/shell.js";import { createApiTestFixtures } from "./support/temporary-directories.js";@@ -25,6 +27,144 @@ const fixture = fileURLToPath();const node = nodeCommand().command;+for (const mode of [+ "command-success",+ "command-failure",+ "command-active",+ "command-late",+ "archive-pending",+ "archive-committed",+]) {+ test(`command settles inherited pipes: ${mode}`, async () => {+ const root = await temporaryDirectory();+ const release = join(root, "release");+ const controller = new AbortController();+ const deadline = new AbortController();+ const bounded = <T>(operation: Promise<T>): Promise<T> =>+ Promise.race([+ operation,+ delay(5000, undefined, { signal: deadline.signal }).then(() => {+ throw new Error("Command did not settle before holder release");+ }),+ ]);+ const until = async (ready: () => boolean) => {+ while (!ready()) await delay(10, undefined, { signal: deadline.signal });+ };+ const alive = (pid: number) => {+ try {+ process.kill(pid, 0);+ return true;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ESRCH") return false;+ throw error;+ }+ };+ const exited = Promise.withResolvers<void>();+ const originalSpawn = childProcess.spawn;+ const observer = spyOn(childProcess, "spawn").mockImplementation(((+ ...args: Parameters<typeof originalSpawn>+ ) => {+ const child = originalSpawn(...args);+ child.once("exit", () => exited.resolve());+ return child;+ }) as typeof originalSpawn);+ let operation: ReturnType<typeof runCodexCommand>;+ try {+ operation = runCodexCommand(+ { command: node },+ [fixture, mode, release],+ {+ PATH: process.env["PATH"],+ SystemRoot: process.env["SystemRoot"],+ },+ undefined,+ controller.signal,+ mode.startsWith("archive-"),+ );+ } finally {+ observer.mockRestore();+ }+ let settled = false;+ const result = operation.then(+ (value) => {+ settled = true;+ return { value, error: undefined };+ },+ (error: unknown) => {+ settled = true;+ return { value: undefined, error };+ },+ );+ let parentPid: number | undefined;+ let holderPid: number | undefined;+ let parentExited = false;+ try {+ await bounded(+ Promise.race([+ until(() => existsSync(`${release}.ready`)),+ result.then((outcome) => {+ throw outcome.error ?? new Error("Fixture did not start");+ }),+ ]),+ );+ ({ parentPid, holderPid } = JSON.parse(+ await readFile(`${release}.ready`, "utf8"),+ ) as { parentPid: number; holderPid: number });+ if (mode === "command-active" || mode === "archive-pending") {+ expect(alive(parentPid)).toBe(true);+ controller.abort({ mode });+ }+ // OS PID disappearance can precede delivery of the child exit event.+ await bounded(exited.promise);+ parentExited = true;+ if (mode === "command-success" || mode === "command-failure")+ controller.abort({ mode });+ if (mode === "command-late" || mode === "archive-committed") {+ if (mode === "archive-committed") controller.abort({ mode });+ await nextTurn();+ expect(settled).toBe(false);+ await writeFile(release, "released");+ }+ const outcome = await bounded(result);+ if (mode === "command-active" || mode === "archive-pending") {+ expect(outcome.error).toMatchObject({ name: "AbortError" });+ } else {+ expect(outcome.error).toBeUndefined();+ expect(outcome.value).toMatchObject({+ success: mode !== "command-failure",+ exitCode: mode === "command-failure" ? 7 : 0,+ stdout: mode === "archive-committed" ? "committed\n" : "",+ });+ if (mode === "command-late" || mode === "archive-committed") {+ expect(outcome.value!.stderr).toContain("initial diagnostic");+ expect(outcome.value!.stderr).toContain("late café 日本語 😀");+ }+ }+ expect(getEventListeners(controller.signal, "abort")).toHaveLength(0);+ } finally {+ await writeFile(release, "released");+ controller.abort();+ if (parentPid !== undefined && !parentExited && alive(parentPid))+ process.kill(parentPid, "SIGKILL");+ try {+ await bounded(result);+ if (holderPid !== undefined)+ await bounded(until(() => existsSync(`${release}.done`)));+ } finally {+ if (holderPid !== undefined && !existsSync(`${release}.done`)) {+ try {+ process.kill(holderPid, "SIGKILL");+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error;+ }+ await bounded(result);+ }+ deadline.abort();+ }+ }+ });+}+for (const surface of ["review", "feedback"] as const) {for (const mode of ["abandoned",diff --git a/sdk/typescript/tests-ts/fixtures/inherited-codex-pipes.mjs b/sdk/typescript/tests-ts/fixtures/inherited-codex-pipes.mjsindex 3b893ee73..49aaf4949 100644--- a/sdk/typescript/tests-ts/fixtures/inherited-codex-pipes.mjs+++ b/sdk/typescript/tests-ts/fixtures/inherited-codex-pipes.mjs@@ -1,5 +1,5 @@import { spawn } from "node:child_process";-import { existsSync, writeFileSync } from "node:fs";+import { existsSync, renameSync, writeFileSync } from "node:fs";import { dirname } from "node:path";import { createInterface } from "node:readline";import { fileURLToPath } from "node:url";@@ -14,7 +14,7 @@ if (role === "holder") {const interval = setInterval(() => {if (!existsSync(release)) return;clearInterval(interval);- if (mode !== "late") finish();+ if (!["late", "command-late", "archive-committed"].includes(mode)) finish();const diagnostic = Buffer.from("late café 日本語 😀\n");process.stderr.write(diagnostic.subarray(0, 9), () => {setImmediate(() => {@@ -34,6 +34,33 @@ if (role === "holder") {},);await new Promise((resolve) => holder.once("message", resolve));+ if (mode.startsWith("command-") || mode.startsWith("archive-")) {+ writeFileSync(+ `${release}.ready.tmp`,+ JSON.stringify({ parentPid: process.pid, holderPid: holder.pid }),+ );+ renameSync(`${release}.ready.tmp`, `${release}.ready`);+ if (mode === "command-active" || mode === "archive-pending") {+ setInterval(() => {}, 1000);+ await new Promise(() => {});+ }+ if (mode === "archive-committed") {+ const lines = createInterface({ input: process.stdin });+ let receivedInput = false;+ for await (const _line of lines) {+ if (receivedInput) break;+ receivedInput = true;+ process.stdout.write("codex-security-archive-ready\n");+ }+ await new Promise((resolve) =>+ process.stdout.write("committed\n", resolve),+ );+ }+ await new Promise((resolve) =>+ process.stderr.write("initial diagnostic\n", resolve),+ );+ process.exit(mode === "command-failure" ? 7 : 0);+ }process.on("SIGTERM", () => {if (mode === "active") process.send("ignored-term");else process.exit(0);