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(windows): make executable discovery robust (#493)
faizan-oai99c85613b0c4
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex 298bfccac..15d18a147 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -460,7 +460,8 @@ shims such as `codex.cmd` automatically use the bundled Codex executableinstead.Interpreter discovery uses `--python` or `pythonPath` first, then `PYTHON`,-the managed Codex runtime, and finally `python3` or `python` from `PATH`.+the managed Codex runtime, and finally `python3` or `python` from `PATH` (`py`+is also supported on Windows).`CODEX_SECURITY_STATE_DIR` takes precedence over `CODEX_HOME`; keep bothstate and result paths outside the scanned repository.diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.tsindex 13c41f2c2..e370454bc 100644--- a/sdk/typescript/src/runtime.ts+++ b/sdk/typescript/src/runtime.ts@@ -2207,7 +2207,7 @@ export async function resolvePluginPython(}for (const candidate of process.platform === "win32"- ? ["python", "python3"]+ ? ["python", "python3", "py"]: ["python3", "python"]) {const resolved = await usablePython(candidate,@@ -2219,7 +2219,7 @@ export async function resolvePluginPython(}throw new PluginPythonUnavailableError("The bundled Codex Security plugin requires Python 3.10 or later (Python 3.10 also requires tomli), but no usable interpreter was found. " +- "Set pythonPath, --python, or PYTHON, install the Codex managed runtime, or add python3/python to PATH.",+ "Set pythonPath, --python, or PYTHON, install the Codex managed runtime, or add python3/python (py on Windows) to PATH.",);}diff --git a/sdk/typescript/src/trusted-executable.ts b/sdk/typescript/src/trusted-executable.tsindex 5a0729cf0..aa0cac47f 100644--- a/sdk/typescript/src/trusted-executable.ts+++ b/sdk/typescript/src/trusted-executable.ts@@ -1,6 +1,14 @@import { constants } from "node:fs";import { access, realpath, stat } from "node:fs/promises";-import { delimiter, isAbsolute, join, relative, resolve, sep } from "node:path";+import {+ delimiter,+ extname,+ isAbsolute,+ join,+ relative,+ resolve,+ sep,+} from "node:path";export interface TrustedExecutable {executable: string;@@ -19,29 +27,46 @@ export async function resolveTrustedExecutable(([name]) => name.toUpperCase() === "PATH",)?.[1];const entries: string[] = [];- for (const entry of path?.split(delimiter) ?? []) {+ for (let entry of path?.split(delimiter) ?? []) {+ if (+ process.platform === "win32" &&+ entry.startsWith('"') &&+ entry.endsWith('"')+ ) {+ entry = entry.slice(1, -1);+ }if (entry.length === 0) continue;const canonical = await realpath(entry).catch(() => null);if (canonical === null || isWithin(root, canonical)) continue;if (!entries.includes(canonical)) entries.push(canonical);}+ const pathLike = candidate.includes("/") || candidate.includes("\\");// execFile cannot launch batch files, but their symlink targets still affect PATH trust.+ // CreateProcess appends .exe to an extensionless explicit path, so inspect the file that+ // will actually run instead of rejecting an otherwise valid Windows configuration.const extensions =process.platform === "win32"? /\.(?:exe|com)$/iu.test(candidate)? [{ suffix: "", runnable: true }]- : [- { suffix: ".exe", runnable: true },- { suffix: ".com", runnable: true },- { suffix: ".bat", runnable: false },- { suffix: ".cmd", runnable: false },- { suffix: "", runnable: false },- ]+ : pathLike+ ? extname(candidate) === ""+ ? [{ suffix: ".exe", runnable: true }]+ : [{ suffix: "", runnable: false }]+ : [+ { suffix: ".exe", runnable: true },+ { suffix: ".com", runnable: true },+ { suffix: ".bat", runnable: false },+ { suffix: ".cmd", runnable: false },+ { suffix: "", runnable: false },+ ]: [{ suffix: "", runnable: true }];- const pathLike = candidate.includes("/") || candidate.includes("\\");const candidates = pathLike- ? [{ entry: null, path: resolve(candidate), runnable: true }]+ ? extensions.map((extension) => ({+ entry: null,+ path: resolve(`${candidate}${extension.suffix}`),+ runnable: extension.runnable,+ })): entries.flatMap((entry) =>extensions.map((extension) => ({entry,diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.tsindex 16280e70e..c46a8f9b3 100644--- a/sdk/typescript/tests-ts/runtime.test.ts+++ b/sdk/typescript/tests-ts/runtime.test.ts@@ -4774,6 +4774,77 @@ describe("runtime directories and plugin Python boundary", () => {).rejects.toThrow(PluginPythonUnavailableError);});+ test.skipIf(process.platform !== "win32")(+ "uses a configured Windows Python path without the executable suffix",+ async () => {+ const discovered = Bun.which("python3") ?? Bun.which("python");+ expect(discovered).not.toBeNull();+ if (discovered === null) return;+ const python = await realpath(discovered);+ const extensionless = python.replace(/\.exe$/iu, "");+ expect(extensionless).not.toBe(python);++ await expect(+ resolvePluginPython({+ configuredPath: extensionless,+ environment: {+ PATH: "",+ ...(process.env["SystemRoot"] === undefined+ ? {}+ : { SystemRoot: process.env["SystemRoot"] }),+ },+ }),+ ).resolves.toBe(python);+ },+ );++ test.skipIf(process.platform !== "win32")(+ "discovers Python through the standard Windows py launcher",+ async () => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ const installedPython = process.env["PYTHON"] ?? Bun.which("python");+ expect(installedPython).not.toBeNull();+ if (installedPython === null) return;+ await mkdir(repository);+ const launcher = join(root, "py.exe");+ await copyFile(installedPython, launcher);+ const installation = dirname(installedPython);+ for (const entry of await readdir(installation, {+ withFileTypes: true,+ })) {+ if (entry.isFile() && entry.name.toLowerCase().endsWith(".dll")) {+ await copyFile(+ join(installation, entry.name),+ join(root, entry.name),+ );+ }+ }+ await writeFile(+ join(root, "pyvenv.cfg"),+ `home = ${installation}\ninclude-system-site-packages = false\n`,+ );++ await expect(+ resolvePluginPython({+ environment: {+ PATH: root,+ PATHEXT: ".EXE",+ ...(process.env["SystemRoot"] === undefined+ ? {}+ : { SystemRoot: process.env["SystemRoot"] }),+ ...(process.env["WINDIR"] === undefined+ ? {}+ : { WINDIR: process.env["WINDIR"] }),+ },+ homeDirectory: root,+ managedRuntimeRoots: [],+ protectedRoot: repository,+ }),+ ).resolves.toBe(await realpath(launcher));+ },+ );+testPosix("does not load repository-controlled Python startup code",async () => {diff --git a/sdk/typescript/tests-ts/trusted-executable.test.ts b/sdk/typescript/tests-ts/trusted-executable.test.tsindex f1e06baac..8c74d8e5a 100644--- a/sdk/typescript/tests-ts/trusted-executable.test.ts+++ b/sdk/typescript/tests-ts/trusted-executable.test.ts@@ -225,6 +225,35 @@ describe("trusted executable resolution", () => {).toBeNull();});+ test("resolves extensionless explicit Windows executable paths", async () => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ const trusted = join(root, "trusted");+ await Promise.all([mkdir(repository), mkdir(trusted)]);+ await Promise.all([+ writeFile(join(trusted, "python.exe"), "python executable"),+ writeFile(join(trusted, "python.cmd"), "batch"),+ ]);++ expect(+ await resolveWindowsExecutable(+ join(trusted, "python"),+ trusted,+ repository,+ ),+ ).toEqual({+ executable: await realpath(join(trusted, "python.exe")),+ environment: { KEEP: "ok", PATH: trusted },+ });+ expect(+ await resolveWindowsExecutable(+ join(trusted, "python.cmd"),+ trusted,+ repository,+ ),+ ).toBeNull();+ });+test("removes PATH entries containing repository-linked Windows shims", async () => {const root = await temporaryDirectory();const repository = join(root, "repository");@@ -295,4 +324,30 @@ describe("trusted executable resolution", () => {});},);++ test.skipIf(process.platform !== "win32")(+ "resolves executables from quoted Windows PATH entries",+ async () => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ const unsafe = join(repository, "tools");+ const trusted = join(root, "trusted tools");+ await Promise.all([mkdir(unsafe, { recursive: true }), mkdir(trusted)]);+ await Promise.all([+ writeFile(join(unsafe, "git.exe"), "untrusted executable"),+ writeFile(join(trusted, "git.exe"), "executable"),+ ]);++ await expect(+ resolveTrustedExecutable(+ "git",+ { Path: [`"${unsafe}"`, `"${trusted}"`].join(delimiter), KEEP: "ok" },+ repository,+ ),+ ).resolves.toEqual({+ executable: join(trusted, "git.exe"),+ environment: { KEEP: "ok", PATH: trusted },+ });+ },+ );});