Skip to content

OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security

chore(codex-security): sync public projection

mldangelo-oai5d8cd485d4c3
diff --git a/sdk/typescript/tests-ts/auth.test.ts b/sdk/typescript/tests-ts/auth.test.ts
index 214c50bcf..5e95da2f5 100644
--- a/sdk/typescript/tests-ts/auth.test.ts
+++ b/sdk/typescript/tests-ts/auth.test.ts
@@ -1,7 +1,8 @@
import { ChildProcess } from "node:child_process";
-import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { setTimeout as delay } from "node:timers/promises";
import { afterEach, describe, expect, spyOn, test } from "bun:test";
import {
accountStatus,
@@ -137,7 +138,7 @@ describe("Codex authentication process boundary", () => {
);
const handle = new CodexLoginHandle(
- { command: "node", prefixArgs: [script] },
+ { command: process.execPath, prefixArgs: [script] },
["login"],
process.env,
() => {},
@@ -221,7 +222,7 @@ grandchild.once("error", (error) => {
);
const handle = new CodexLoginHandle(
- { command: "node", prefixArgs: [script] },
+ { command: process.execPath, prefixArgs: [script] },
["login"],
process.env,
() => {},
@@ -240,15 +241,61 @@ grandchild.once("error", (error) => {
async () => {
const root = await mkdtemp(join(tmpdir(), "codex-security-auth-pipes-"));
temporaryDirectories.push(root);
+ const ready = join(root, "grandchild-ready");
+ const release = join(root, "release-grandchild");
const script = join(root, "login-pipes.mjs");
+ const grandchildScript = `
+import { existsSync, writeFileSync } from "node:fs";
+
+const ready = process.argv[1];
+const release = process.argv[2];
+const timeout = setTimeout(() => process.exit(1), 10_000);
+const watcher = setInterval(() => {
+ if (!existsSync(release)) return;
+ clearInterval(watcher);
+ clearTimeout(timeout);
+ process.exit(0);
+}, 25);
+writeFileSync(ready, String(process.pid));
+`;
await writeFile(
script,
- 'process.stdout.write("ready\\n", () => process.exit(0));\n',
+ `
+import { spawn } from "node:child_process";
+import { existsSync } from "node:fs";
+
+const grandchild = spawn(
+ process.execPath,
+ ["-e", ${JSON.stringify(grandchildScript)}, ${JSON.stringify(ready)}, ${JSON.stringify(release)}],
+ {
+ stdio: ["ignore", "inherit", "inherit"],
+ windowsHide: true,
+ detached: true,
+ },
+);
+const readyTimeout = setTimeout(() => {
+ clearInterval(readyWatcher);
+ grandchild.kill();
+ console.error("Timed out waiting for the Windows login grandchild.");
+ process.exit(1);
+}, 10_000);
+const readyWatcher = setInterval(() => {
+ if (!existsSync(${JSON.stringify(ready)})) return;
+ clearInterval(readyWatcher);
+ clearTimeout(readyTimeout);
+ process.stdout.write("ready\\n", (error) => process.exit(error ? 1 : 0));
+}, 25);
+grandchild.once("error", (error) => {
+ clearInterval(readyWatcher);
+ clearTimeout(readyTimeout);
+ console.error(error.message);
+ process.exit(1);
+});
+`,
);
const originalOnce = ChildProcess.prototype.once;
let loginChild: ChildProcess | undefined;
- let releaseClose: (() => void) | undefined;
const processObserver = spyOn(ChildProcess.prototype, "once");
processObserver.mockImplementation(function (
this: ChildProcess,
@@ -256,22 +303,13 @@ grandchild.once("error", (error) => {
listener: (...eventArguments: never[]) => void,
) {
if (event === "exit") loginChild = this;
- if (event === "close") {
- return Reflect.apply(originalOnce, this, [
- event,
- (...eventArguments: unknown[]) => {
- releaseClose = () =>
- Reflect.apply(listener, this, eventArguments);
- },
- ]);
- }
return Reflect.apply(originalOnce, this, [event, listener]);
});
let handle: CodexLoginHandle;
try {
handle = new CodexLoginHandle(
- { command: "node", prefixArgs: [script] },
+ { command: process.execPath, prefixArgs: [script] },
["login"],
process.env,
() => {},
@@ -280,8 +318,32 @@ grandchild.once("error", (error) => {
processObserver.mockRestore();
}
+ const readMarker = async (path: string): Promise<string> => {
+ const deadline = Date.now() + 5_000;
+ while (true) {
+ try {
+ return await readFile(path, "utf8");
+ } catch (error) {
+ if (
+ !(error instanceof Error) ||
+ !("code" in error) ||
+ error.code !== "ENOENT" ||
+ Date.now() >= deadline
+ ) {
+ throw error;
+ }
+ await delay(25);
+ }
+ }
+ };
+
+ let grandchildPid: number | undefined;
try {
- const startedAt = Date.now();
+ const readyMarker = await readMarker(ready);
+ expect(readyMarker).toMatch(/^\d+$/u);
+ grandchildPid = Number(readyMarker);
+ expect(Number.isSafeInteger(grandchildPid)).toBe(true);
+ expect(grandchildPid).toBeGreaterThan(0);
const timeout = AbortSignal.timeout(5_000);
const completion = Promise.race([
handle.wait(),
@@ -297,12 +359,33 @@ grandchild.once("error", (error) => {
success: true,
exitCode: 0,
});
- expect(Date.now() - startedAt).toBeGreaterThanOrEqual(900);
- expect(releaseClose).toBeFunction();
expect(loginChild?.stdout?.destroyed).toBe(true);
expect(loginChild?.stderr?.destroyed).toBe(true);
} finally {
- releaseClose?.();
+ await writeFile(release, "released");
+ if (grandchildPid !== undefined) {
+ const deadline = Date.now() + 5_000;
+ while (true) {
+ try {
+ process.kill(grandchildPid, 0);
+ } catch (error) {
+ if (
+ error instanceof Error &&
+ "code" in error &&
+ error.code === "ESRCH"
+ ) {
+ break;
+ }
+ throw error;
+ }
+ if (Date.now() >= deadline) {
+ throw new Error(
+ "The Windows login grandchild did not exit after pipe cleanup.",
+ );
+ }
+ await delay(25);
+ }
+ }
}
},
);
diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.ts
index eec9467ec..4b6e3860d 100644
--- a/sdk/typescript/tests-ts/runtime.test.ts
+++ b/sdk/typescript/tests-ts/runtime.test.ts
@@ -1,6 +1,7 @@
import { existsSync, renameSync, symlinkSync } from "node:fs";
import {
chmod,
+ copyFile,
lstat,
mkdir,
mkdtemp,
@@ -169,6 +170,151 @@ describe("plugin runtime preparation", () => {
).toBeDefined();
});
+ testPosix(
+ "preserves literal POSIX candidate paths in the bundled plugin",
+ async () => {
+ const root = await temporaryDirectory();
+ await mkdir(join(root, "source"));
+ const cases = [
+ { path: "source\\candidate.py", contents: "literal candidate\n" },
+ { path: " leading.py", contents: "leading whitespace\n" },
+ { path: "trailing.py ", contents: "trailing whitespace\n" },
+ { path: " ", contents: "single whitespace filename\n" },
+ { path: " ", contents: "multiple whitespace filename\n" },
+ { path: "C:candidate.py", contents: "literal colon\n" },
+ { path: "carriage\rreturn.py", contents: "literal carriage return\n" },
+ { path: "vertical\vtab.py", contents: "literal vertical tab\n" },
+ { path: "form\ffeed.py", contents: "literal form feed\n" },
+ { path: "next\u0085line.py", contents: "literal next line\n" },
+ {
+ path: "unicode\u2028separator.py",
+ contents: "literal line separator\n",
+ },
+ {
+ path: "paragraph\u2029separator.py",
+ contents: "literal paragraph separator\n",
+ },
+ ];
+ await Promise.all([
+ ...cases.map((item) => writeFile(join(root, item.path), item.contents)),
+ writeFile(join(root, "source", "candidate.py"), "wrong candidate\n"),
+ writeFile(join(root, "leading.py"), "wrong leading candidate\n"),
+ writeFile(join(root, "trailing.py"), "wrong trailing candidate\n"),
+ ]);
+ const scopePath = join(root, "in-scope-files.txt");
+ await writeFile(
+ scopePath,
+ `${cases.map((item) => item.path).join("\n")}\n`,
+ );
+
+ const python = Bun.which("python3") ?? Bun.which("python");
+ expect(python).not.toBeNull();
+ const sourcePlugin = await bundledPluginRoot();
+ const projector = new URL(
+ "../scripts/project-plugin.mjs",
+ import.meta.url,
+ );
+ const publicManifest = new URL(
+ "../public-repo/sdk/typescript/plugin.public.json",
+ import.meta.url,
+ );
+ let bundledPlugin = sourcePlugin;
+ if (existsSync(projector) && existsSync(publicManifest)) {
+ const packageRoot = join(root, "package");
+ const isolatedProjector = join(
+ packageRoot,
+ "scripts",
+ "project-plugin.mjs",
+ );
+ const isolatedManifest = join(
+ packageRoot,
+ "public-repo",
+ "sdk",
+ "typescript",
+ "plugin.public.json",
+ );
+ await Promise.all([
+ mkdir(dirname(isolatedProjector), { recursive: true }),
+ mkdir(dirname(isolatedManifest), { recursive: true }),
+ ]);
+ await Promise.all([
+ copyFile(projector, isolatedProjector),
+ copyFile(publicManifest, isolatedManifest),
+ ]);
+ const projection = Bun.spawnSync(
+ [process.execPath, isolatedProjector],
+ {
+ cwd: packageRoot,
+ env: {
+ ...process.env,
+ CODEX_SECURITY_PLUGIN_ROOT: sourcePlugin,
+ },
+ stdout: "pipe",
+ stderr: "pipe",
+ },
+ );
+ expect(new TextDecoder().decode(projection.stderr)).toBe("");
+ expect(projection.exitCode).toBe(0);
+ bundledPlugin = join(packageRoot, "_bundled_plugin");
+ }
+ const normalizer = join(
+ bundledPlugin,
+ "scripts",
+ "normalize_candidates.py",
+ );
+ expect(await readFile(normalizer, "utf8")).toBe(
+ await readFile(
+ join(sourcePlugin, "scripts", "normalize_candidates.py"),
+ "utf8",
+ ),
+ );
+ const result = Bun.spawnSync([
+ python!,
+ "-I",
+ "-B",
+ "-c",
+ [
+ "import json, pathlib, runpy, sys",
+ "module = runpy.run_path(sys.argv[1])",
+ "root = pathlib.Path(sys.argv[2])",
+ "scope = module['read_scope'](pathlib.Path(sys.argv[3]), root)",
+ "finalizer = runpy.run_path(sys.argv[5])",
+ "results = []",
+ "for value in json.loads(sys.argv[4]):",
+ " path, source = module['relative_file'](value, root)",
+ " candidate = {'cwe_ids': ['CWE-89'], 'locations': [{'path': value, 'start_line': 1, 'role': 'entrypoint'}], 'summary': 'Test finding', 'evidence': 'Test evidence'}",
+ " try:",
+ " normalized = module['normalize_candidate'](candidate, root, scope, {})",
+ " location = normalized['locations'][0]",
+ " finalizer['_validate_location']({'path': location['path'], 'startLine': location['start_line'], 'endLine': location['end_line'], 'role': location['role']}, 'candidate.locations[0]')",
+ " except ValueError:",
+ " contract_valid = False",
+ " else:",
+ " contract_valid = True",
+ " results.append({'path': path, 'contents': source.read_text(encoding='utf-8'), 'inScope': path in scope, 'contractValid': contract_valid})",
+ "print(json.dumps(results))",
+ ].join("\n"),
+ normalizer,
+ root,
+ scopePath,
+ JSON.stringify(cases.map((item) => item.path)),
+ join(bundledPlugin, "scripts", "finalize_scan_contract.py"),
+ ]);
+
+ expect(result.exitCode).toBe(0);
+ expect(JSON.parse(new TextDecoder().decode(result.stdout))).toEqual(
+ cases.map((item) => ({
+ ...item,
+ inScope: true,
+ contractValid:
+ item.path.trim().length > 0 &&
+ !item.path.includes("\\") &&
+ !item.path.includes(":"),
+ })),
+ );
+ },
+ );
+
test("uses a configured plugin directory directly", async () => {
const root = await temporaryDirectory();
const ambientHome = join(root, ".codex", "plugins", "cache");