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

fix(python): preserve explicit virtualenv launchers (#227)

Dipesh Babu9edded5f776f
diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.mjs b/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.mjs
index 8c1a757db..bdd14b1f0 100644
--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.mjs
+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.mjs
@@ -98,7 +98,7 @@ const deniedWorkerPermissionProfile = {
try {
testCodeModeFrameDiagnosticBoundaries();
await testOpenAiCredentialsReachWorker();
- await testWorkerReasoningSummaries();
+ await testWorkerRuntimeSettings();
if (process.platform !== "win32") {
await testMissingParentSandboxFailsBeforeWorkerLaunch();
await testDisallowedWorkerProfileFailsBeforeWorkerLaunch();
@@ -1102,7 +1102,7 @@ async function testOpenAiCredentialsReachWorker() {
}
}
-async function testWorkerReasoningSummaries() {
+async function testWorkerRuntimeSettings() {
const cases = [
["", undefined],
['model_reasoning_summary = "none"\n', "none"],
@@ -1118,6 +1118,7 @@ async function testWorkerReasoningSummaries() {
];
const saved = Object.fromEntries(
[
+ "PYTHON",
"CODEX_CLI_PATH",
"CODEX_SECURITY_CONFIG_PATH",
"CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH",
@@ -1131,6 +1132,14 @@ async function testWorkerReasoningSummaries() {
delete process.env.CODEX_API_KEY;
for (const [configuration, expected] of cases) {
const fixture = await fakeCodexFixture(deniedWorkerPermissionProfile);
+ const python = path.join(fixture.root, "selected venv", "bin", "python");
+ const helperPython = path.join(
+ fixture.root,
+ "helper venv",
+ "bin",
+ "python",
+ );
+ process.env.PYTHON = python;
const configPath = path.join(fixture.root, "active scan config.toml");
const promptPath = path.join(fixture.root, "prompt.md");
await writeFile(configPath, configuration);
@@ -1155,6 +1164,13 @@ async function testWorkerReasoningSummaries() {
model: "fixture-model",
reasoningEffort: "xhigh",
parentSandbox: trustedParentSandboxWithDenials,
+ artifactContext: {
+ pluginRoot: fixture.root,
+ scanRoot: fixture.root,
+ repoRoot: fixture.root,
+ scanId: "fixture-scan",
+ pythonCommand: helperPython,
+ },
});
// A running coordinator retains its settings if the source file changes.
for (const kind of ["discovery", "dedup"]) {
@@ -1165,6 +1181,15 @@ async function testWorkerReasoningSummaries() {
workingDirectory: fixture.root,
subagents: 0,
resumeThreadId,
+ artifactContext: {
+ root: fixture.root,
+ layout: kind === "dedup" ? "reducer" : "worker",
+ ...(kind === "dedup"
+ ? {
+ deepReducer: { scanRoot: fixture.root, claimedWorkers: [] },
+ }
+ : {}),
+ },
signal: new AbortController().signal,
});
const invocation = JSON.parse(
@@ -1190,6 +1215,14 @@ async function testWorkerReasoningSummaries() {
true,
);
assert.equal(invocation.configPath, configPath);
+ assert.equal(invocation.python, python);
+ assert.equal(
+ invocation.argv.includes(
+ `mcp_servers.cs_artifacts.env.CODEX_SECURITY_PYTHON_COMMAND=${JSON.stringify(helperPython)}`,
+ ),
+ true,
+ );
+ assert.equal(process.env.PYTHON, python);
assert.equal(
invocation.deepConfigPath,
process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH,
@@ -2147,7 +2180,7 @@ async function fakeCodexFixture(
"for await (const chunk of process.stdin) stdin += chunk;",
"const openaiAuthentication = stdin.includes('CAPTURE_SYNTHETIC_OPENAI_AUTH') ? { OPENAI_API_KEY: process.env.OPENAI_API_KEY, CODEX_API_KEY: process.env.CODEX_API_KEY } : undefined;",
"const bedrockAuthentication = stdin.includes('CAPTURE_SYNTHETIC_BEDROCK_AUTH') ? Object.fromEntries(JSON.parse(process.env.FAKE_CODEX_BEDROCK_ENV_KEYS).map((name) => [name, process.env[name]])) : undefined;",
- "writeFileSync(process.env.FAKE_CODEX_MARKER, JSON.stringify({ argv: process.argv.slice(2), stdin, cwd: process.cwd(), codexHome: process.env.CODEX_HOME, configPath: process.env.CODEX_SECURITY_CONFIG_PATH, deepConfigPath: process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH, originator: process.env.CODEX_INTERNAL_ORIGINATOR_OVERRIDE, ...(stdin.includes('COMPLETE_THEN_HANG') ? { pid: process.pid } : {}), ...(openaiAuthentication ? { openaiAuthentication } : {}), ...(bedrockAuthentication ? { bedrockAuthentication } : {}) }));",
+ "writeFileSync(process.env.FAKE_CODEX_MARKER, JSON.stringify({ argv: process.argv.slice(2), stdin, cwd: process.cwd(), codexHome: process.env.CODEX_HOME, configPath: process.env.CODEX_SECURITY_CONFIG_PATH, deepConfigPath: process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH, python: process.env.PYTHON, originator: process.env.CODEX_INTERNAL_ORIGINATOR_OVERRIDE, ...(stdin.includes('COMPLETE_THEN_HANG') ? { pid: process.pid } : {}), ...(openaiAuthentication ? { openaiAuthentication } : {}), ...(bedrockAuthentication ? { bedrockAuthentication } : {}) }));",
"if (stdin.includes('COMPLETE_THEN_HANG')) process.on('SIGTERM', () => setTimeout(() => process.exit(0), 100));",
"if (stdin.includes('THREAD_START_CONFIG_ERROR')) { console.error('Error: thread/start: thread/start failed: agents.max_threads cannot be set when features.multi_agent_v2 is enabled (code -32600)'); process.exit(1); }",
"if (stdin.includes('CONFIG_ERROR')) { console.error('failed to load configuration: invalid value'); process.exit(2); }",
diff --git a/sdk/typescript/src/trusted-executable.ts b/sdk/typescript/src/trusted-executable.ts
index 2e410484d..e13034b0c 100644
--- a/sdk/typescript/src/trusted-executable.ts
+++ b/sdk/typescript/src/trusted-executable.ts
@@ -1,7 +1,9 @@
import { constants } from "node:fs";
import { access, realpath, stat } from "node:fs/promises";
import {
+ basename,
delimiter,
+ dirname,
extname,
isAbsolute,
join,
@@ -92,7 +94,16 @@ export async function resolveTrustedExecutable(
process.platform === "win32" ? constants.F_OK : constants.X_OK,
);
if (!(await stat(canonical)).isFile()) continue;
- executable ??= pathLike ? canonical : current.path;
+ // Keep explicit virtualenv launchers, but resolve repository-local aliases
+ // to the trusted target instead of invoking them from the repository.
+ const invocationPath = pathLike
+ ? join(await realpath(dirname(current.path)), basename(current.path))
+ : current.path;
+ executable ??=
+ pathLike &&
+ (isWithin(root, current.path) || isWithin(root, invocationPath))
+ ? canonical
+ : invocationPath;
} catch {
continue;
}
diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.ts
index 02552e655..abf83278e 100644
--- a/sdk/typescript/tests-ts/runtime.test.ts
+++ b/sdk/typescript/tests-ts/runtime.test.ts
@@ -23,6 +23,7 @@ import {
import * as fsPromises from "node:fs/promises";
import { homedir, tmpdir } from "node:os";
import {
+ basename,
delimiter,
dirname,
isAbsolute,
@@ -5831,21 +5832,27 @@ describe("runtime directories and plugin Python boundary", () => {
});
test("resolves inherited Python names case-insensitively", async () => {
- const interpreter =
+ const discovered =
Bun.which("python3") ?? Bun.which("python") ?? Bun.which("py");
- expect(interpreter).not.toBeNull();
+ expect(discovered).not.toBeNull();
+ const interpreter = join(
+ await realpath(dirname(discovered!)),
+ basename(discovered!),
+ );
+ const repository = await temporaryDirectory();
expect(
await resolvePluginPython({
+ protectedRoot: repository,
environment: {
PATH: "",
- Python: interpreter!,
+ Python: interpreter,
...(process.env["SystemRoot"] === undefined
? {}
: { SystemRoot: process.env["SystemRoot"] }),
},
}),
- ).toBe(await realpath(interpreter!));
+ ).toBe(interpreter);
});
test.skipIf(process.platform !== "win32")(
@@ -5947,6 +5954,38 @@ describe("runtime directories and plugin Python boundary", () => {
).rejects.toThrow(PluginPythonUnavailableError);
});
+ testPosix("preserves an explicit virtualenv Python launcher", async () => {
+ const root = await temporaryDirectory();
+ const repository = join(root, "repository");
+ const systemBin = join(root, "system", "bin");
+ const virtualenvBin = join(root, "venv", "bin");
+ const systemPython = join(systemBin, "python3");
+ const virtualenvPython = join(virtualenvBin, "python");
+ await Promise.all([
+ mkdir(repository),
+ mkdir(systemBin, { recursive: true }),
+ mkdir(virtualenvBin, { recursive: true }),
+ ]);
+ await writeFile(
+ systemPython,
+ '#!/bin/sh\ncase "$0" in */venv/bin/python) ;; *) exit 1 ;; esac\nprintf "codex-security-python-ok\\n"\n',
+ );
+ await chmod(systemPython, 0o700);
+ await symlink(systemPython, virtualenvPython);
+ const aliasedBin = join(root, "venv-bin-alias");
+ await symlink(virtualenvBin, aliasedBin, "dir");
+
+ for (const candidate of [virtualenvPython, join(aliasedBin, "python")]) {
+ await expect(
+ resolvePluginPython({
+ configuredPath: candidate,
+ environment: { PATH: "" },
+ protectedRoot: repository,
+ }),
+ ).resolves.toBe(virtualenvPython);
+ }
+ });
+
test.skipIf(process.platform !== "win32")(
"uses a configured Windows Python path without the executable suffix",
async () => {
@@ -6024,9 +6063,13 @@ describe("runtime directories and plugin Python boundary", () => {
const root = await temporaryDirectory();
const repository = join(root, "repository");
const marker = join(root, "sitecustomize-executed");
- const interpreter = Bun.which("python3");
- expect(interpreter).not.toBeNull();
- if (interpreter === null) return;
+ const discovered = Bun.which("python3");
+ expect(discovered).not.toBeNull();
+ if (discovered === null) return;
+ const interpreter = join(
+ await realpath(dirname(discovered)),
+ basename(discovered),
+ );
await mkdir(repository);
await writeFile(
@@ -6047,7 +6090,7 @@ describe("runtime directories and plugin Python boundary", () => {
environment,
protectedRoot: repository,
}),
- ).toBe(await realpath(interpreter));
+ ).toBe(interpreter);
expect(existsSync(marker)).toBe(false);
},
);
diff --git a/sdk/typescript/tests-ts/trusted-executable.test.ts b/sdk/typescript/tests-ts/trusted-executable.test.ts
index fb6a8f6d9..6c895b059 100644
--- a/sdk/typescript/tests-ts/trusted-executable.test.ts
+++ b/sdk/typescript/tests-ts/trusted-executable.test.ts
@@ -173,6 +173,42 @@ describe("trusted executable resolution", () => {
},
);
+ test.skipIf(process.platform === "win32")(
+ "canonicalizes aliased parents before preserving explicit launchers",
+ async () => {
+ const root = await temporaryDirectory();
+ const repository = join(root, "repository");
+ const repositoryBin = join(repository, "bin");
+ const aliasedBin = join(root, "repository-bin-alias");
+ const externalBin = join(repository, "external-bin");
+ const repositoryAlias = join(root, "repository-alias");
+ const trusted = join(root, "trusted");
+ const wrapper = join(trusted, "python3");
+ const launcher = join(repositoryBin, "python");
+ await Promise.all([
+ mkdir(repositoryBin, { recursive: true }),
+ mkdir(trusted),
+ ]);
+ await writeFile(wrapper, "#!/bin/sh\nexit 0\n");
+ await chmod(wrapper, 0o700);
+ await symlink(wrapper, launcher);
+ await symlink(repositoryBin, aliasedBin, "dir");
+ await symlink(trusted, externalBin, "dir");
+ await symlink(repository, repositoryAlias, "dir");
+
+ for (const candidate of [
+ launcher,
+ join(aliasedBin, "python"),
+ join(externalBin, "python3"),
+ join(repositoryAlias, "external-bin", "python3"),
+ ]) {
+ await expect(
+ resolveTrustedExecutable(candidate, { PATH: "" }, repository),
+ ).resolves.toEqual({ executable: wrapper, environment: { PATH: "" } });
+ }
+ },
+ );
+
test("selects runnable Windows executables ahead of extensionless and batch files", async () => {
const root = await temporaryDirectory();
const repository = join(root, "repository");