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(scans): resolve inventory and bulk tools outside selected sources (#2431)

Michael D'Angelo92585995e1f4
diff --git a/.gitattributes b/.gitattributes
index 414b1f9ba..a725e740c 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -11,6 +11,7 @@
*.yaml text eol=lf
*.yml text eol=lf
+plugins/codex-security/scripts/dispatch_inventory_tool text eol=lf
plugins/codex-security/scripts/launch_codex_security_mcp text eol=lf
# Bundled dependencies contain intentional whitespace in strings and comments.
diff --git a/plugins/codex-security/.mcp.json b/plugins/codex-security/.mcp.json
index f34c00d49..985fe3c5f 100644
--- a/plugins/codex-security/.mcp.json
+++ b/plugins/codex-security/.mcp.json
@@ -16,6 +16,7 @@
"CODEX_ELECTRON_RESOURCES_PATH",
"CODEX_MANAGED_PACKAGE_ROOT",
"CODEX_MCP_NODE_PATH",
+ "_CODEX_SECURITY_SDK_NODE_SEARCH_PATH",
"OPENAI_API_KEY",
"OPENROUTER_API_KEY",
"FIREWORKS_API_KEY",
diff --git a/plugins/codex-security/mcp-app/helpers-main.ts b/plugins/codex-security/mcp-app/helpers-main.ts
index 337e38f8d..1ecda7c7b 100644
--- a/plugins/codex-security/mcp-app/helpers-main.ts
+++ b/plugins/codex-security/mcp-app/helpers-main.ts
@@ -9,6 +9,8 @@ export {
readSealedScanFile,
requireSealedScanFile,
} from "./src/sealed-contract.js";
+import { withInventoryToolPaths } from "./src/helpers/inventory-git.js";
+export { inventoryToolPath } from "./src/helpers/inventory-git.js";
export { validateTrackingSource } from "./src/helpers/validate-tracking-source.js";
import { parseArgs } from "node:util";
import { isMainThread, parentPort, workerData } from "node:worker_threads";
@@ -105,9 +107,11 @@ function runHelper(): void {
command === "make-hosted-repo-scope-input" ||
command === "make-diff-rank-input"
) {
- void inventoryCommand(command, args).then((code) => {
- process.exitCode = code;
- });
+ void withInventoryToolPaths(() => inventoryCommand(command, args)).then(
+ (code) => {
+ process.exitCode = code;
+ },
+ );
} else if (command === "resolve-security-md") {
process.exitCode = resolveSecurityMdCommand(args, posixHome);
} else if (command === "normalize-candidates") {
diff --git a/plugins/codex-security/mcp-app/src/helpers/helper-files.ts b/plugins/codex-security/mcp-app/src/helpers/helper-files.ts
index dc9ce06d2..5949ac237 100644
--- a/plugins/codex-security/mcp-app/src/helpers/helper-files.ts
+++ b/plugins/codex-security/mcp-app/src/helpers/helper-files.ts
@@ -103,7 +103,11 @@ export function readFile(path: string | number, label?: string): Buffer {
}
}
-export function* readChunks(path: string, label?: string): Iterable<Buffer> {
+export function* readChunks(
+ path: string,
+ label?: string,
+ size = 64 * 1024,
+): Iterable<Buffer> {
if (process.platform === "win32") {
yield readFile(path, label);
return;
@@ -112,7 +116,7 @@ export function* readChunks(path: string, label?: string): Iterable<Buffer> {
try {
descriptor = openSync(encodePosixPath(path), "r");
while (true) {
- const chunk = Buffer.allocUnsafe(64 * 1024);
+ const chunk = Buffer.allocUnsafe(size);
const length = readSync(descriptor, chunk, 0, chunk.length, null);
if (length === 0) return;
yield chunk.subarray(0, length);
diff --git a/plugins/codex-security/mcp-app/src/helpers/inventory-git.ts b/plugins/codex-security/mcp-app/src/helpers/inventory-git.ts
index 3c233794f..7a26a75db 100644
--- a/plugins/codex-security/mcp-app/src/helpers/inventory-git.ts
+++ b/plugins/codex-security/mcp-app/src/helpers/inventory-git.ts
@@ -1,34 +1,51 @@
import {
environmentValue,
isMissingPathError,
+ readChunks,
resolvedPathText as canonical,
} from "./helper-files";
import {
spawn,
+ spawnSync,
type SpawnOptions,
type ChildProcessWithoutNullStreams,
} from "node:child_process";
import { randomUUID } from "node:crypto";
+import { AsyncLocalStorage } from "node:async_hooks";
+import {
+ lstatSync,
+ mkdirSync,
+ readdirSync,
+ readlinkSync,
+ rmSync,
+ symlinkSync,
+} from "node:fs";
import type { Writable } from "node:stream";
import {
basename,
dirname,
delimiter,
isAbsolute,
+ parse,
resolve,
sep,
} from "node:path";
import { createRequire } from "node:module";
-import { constants } from "node:os";
+import { constants, release, tmpdir } from "node:os";
import { spawnWindowsProcess } from "../../../native/windows-process.mjs";
import { nativeTarget } from "../../../native/platform.mjs";
-import { decodePosixBytes, encodePosixPath } from "./posix-path";
+import {
+ decodePosixBytes,
+ encodePosixPath,
+ resolvePosixPath,
+} from "./posix-path";
import { decodeUtf8 } from "./utf8";
import {
ancestors,
append,
executable,
exists,
+ fsPath,
inside,
linkedParent,
lstat,
@@ -69,15 +86,20 @@ function rawToolValue(value: string): boolean {
return (windows ? /[\ud800-\udfff]/u : /[\udc80-\udcff]/u).test(value);
}
-function selectedBundledRipgrep(candidate: string): boolean {
+function selectedBundledRipgrep(
+ candidate: string,
+ protectedRoot: string,
+): boolean {
const codex = environmentValue("CODEX_CLI_PATH");
if (!codex) return false;
try {
+ const binary = canonical(codex);
+ if (!isRepositoryPath(protectedRoot, binary)) return false;
return sameFile(
candidate,
append(
- append(dirname(dirname(canonical(codex))), "codex-path"),
- "rg.exe",
+ append(dirname(dirname(binary)), "codex-path"),
+ windows ? "rg.exe" : "rg",
),
);
} catch {
@@ -85,17 +107,395 @@ function selectedBundledRipgrep(candidate: string): boolean {
}
}
-function trustedTool(
+function protectedToolRoot(target: string): string {
+ let root = canonical(target);
+ for (const ancestor of ancestors(root))
+ if (exists(append(ancestor, ".git"))) root = ancestor;
+ return root;
+}
+
+function isRepositoryPath(root: string, path: string): boolean {
+ try {
+ inside(root, path);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+// The kernel can dispatch a shebang or the POSIX shell can interpret an
+// executable text file after ENOEXEC. Only skip inspection for native images.
+const nativeImageMagic = new Set(
+ process.platform === "darwin"
+ ? [
+ 0xfeedface,
+ 0xcefaedfe,
+ 0xfeedfacf,
+ 0xcffaedfe, // Mach-O
+ 0xcafebabe,
+ 0xbebafeca,
+ 0xcafebabf,
+ 0xbfbafeca, // universal binaries
+ ]
+ : [0x7f454c46],
+); // ELF
+
+// Linux reads BINPRM_BUF_SIZE bytes for exec. XNU uses IMG_SHSIZE and also
+// treats "#" as a shebang terminator. Arguments are left entirely to the OS.
+const macShebang = process.platform === "darwin";
+const legacyLinuxShebang =
+ process.platform === "linux" &&
+ /^(?:[0-4]\.|5\.0(?:\.|-|$))/u.test(release());
+const headerSize = macShebang ? 512 : 256;
+function toolHeader(path: string): "native" | "text" | string[] | undefined {
+ try {
+ for (const chunk of readChunks(path, undefined, headerSize)) {
+ if (chunk.length >= 4 && nativeImageMagic.has(chunk.readUInt32BE()))
+ return "native";
+ if (chunk[0] !== 35 || chunk[1] !== 33) return "text";
+ const line = chunk.subarray(2).toString("latin1");
+ if (macShebang && !/[#\n]/u.test(line)) return "text";
+ const pattern = macShebang
+ ? /^[ \t]*([^ \t#\n\0]+)/u
+ : /^[ \t]*([^ \t\n\0]+)/u;
+ const token = pattern.exec(line);
+ const names: string[] = [];
+ if (
+ token &&
+ (macShebang ||
+ chunk.length < headerSize ||
+ token[0].length < line.length)
+ )
+ names.push(token[1]!);
+ // Older Linux kernels could execute a name truncated at header byte 127.
+ // Check both spellings on those releases, including vendor backports.
+ if (legacyLinuxShebang && token && token[0].length > 125) {
+ const truncated = pattern.exec(line.slice(0, 125))?.[1];
+ if (truncated) names.push(truncated);
+ }
+ return names.length
+ ? names.map((name) => decodePosixBytes(Buffer.from(name, "latin1")))
+ : "text";
+ }
+ return "text";
+ } catch {
+ return undefined;
+ }
+}
+
+function interpreterCheck(
+ cwd: string,
+ allowsPath: (path: string) => boolean,
+ shared: boolean,
+ scripts?: Map<string, string>,
+) {
+ const checked = new Map<string, boolean>();
+ function allows(path: string, loader = false): boolean {
+ const prior = checked.get(path);
+ if (prior !== undefined) return prior;
+ if (!executable(path)) return true; // Leave missing loaders and EACCES to exec.
+ const header = toolHeader(path);
+ if (!header) return false;
+ if (typeof header === "string") {
+ if (loader) checked.set(path, true);
+ return true;
+ }
+ checked.set(path, true); // A cycle without a protected path is an OS launch error.
+ const safe = header.every((interpreter) => {
+ // A campaign's PATH is reused by children in different working directories.
+ if (shared && !isAbsolute(interpreter)) return false;
+ const file = isAbsolute(interpreter)
+ ? interpreter
+ : append(cwd, interpreter);
+ // XNU redirects once; Linux can chain interpreter scripts.
+ return allowsPath(file) && (macShebang || allows(file, true));
+ });
+ if (safe && header.length === 1 && isAbsolute(header[0]!))
+ scripts?.set(path, header[0]!);
+ checked.set(path, safe);
+ return safe;
+ }
+ return allows;
+}
+
+// libuv can return Win32 link targets using the extended drive or UNC spelling.
+function windowsLinkPath(path: string): string {
+ return path
+ .replace(/^\\\\[?.]\\UNC\\/iu, "\\\\")
+ .replace(/^\\\\[?.]\\(?=[a-z]:\\)/iu, "");
+}
+
+function linkTarget(path: string): string | undefined {
+ if (sep === "\\") {
+ let info: ReturnType<typeof lstat>;
+ try {
+ info = lstat(path);
+ } catch (error) {
+ // Only an absent entry may later materialize in an external directory.
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
+ throw error;
+ }
+ if (!("isNameSurrogate" in info) || !info.isNameSurrogate()) return;
+ // SDK source paths are UTF-8. An unreadable reparse target cannot be trusted.
+ if (!path.isWellFormed())
+ throw new Error("Cannot inspect this Windows link");
+ return windowsLinkPath(
+ decodeUtf8(readlinkSync(fsPath(path), { encoding: "buffer" })),
+ );
+ }
+ const name = encodePosixPath(path);
+ if (lstatSync(name, { throwIfNoEntry: false })?.isSymbolicLink())
+ return decodePosixBytes(readlinkSync(name, { encoding: "buffer" }));
+}
+
+function canonicalComponent(path: string): string {
+ return sep === "\\"
+ ? windowsLinkPath(canonical(path, false))
+ : decodePosixBytes(resolvePosixPath(encodePosixPath(path), false));
+}
+
+// A campaign can replace files in its checkouts after preparing the workers.
+// Check every component owned by the campaign, including intermediate links
+// whose current destination is an external executable.
+function campaignPathCheck(
+ isProtected: (path: string) => boolean,
+ cwd: string,
+) {
+ const resolved = new Map<string, string | null>();
+ function expand(directory: string, target: string): string | null {
+ // Win32 normalizes drive-relative and rooted names before filesystem
+ // lookup. POSIX processes ".." after following the preceding symlink.
+ const path =
+ sep === "\\" ? resolve(directory, windowsLinkPath(target)) : target;
+ const root = parse(path).root;
+ let parent =
+ root && sep === "\\" ? canonicalComponent(root) : root || directory;
+ for (const part of path.slice(root.length).split(sep)) {
+ if (!part || part === ".") continue;
+ if (part === "..") {
+ parent = dirname(parent);
+ continue;
+ }
+ if (isProtected(parent)) return null;
+ const child = append(parent, part);
+ if (!resolved.has(child)) {
+ resolved.set(child, null); // Detect symlink cycles while expanding.
+ const link = linkTarget(child);
+ // Filesystems may canonicalize case or DOS short names even without a link.
+ resolved.set(
+ child,
+ link === undefined ? canonicalComponent(child) : expand(parent, link),
+ );
+ }
+ const next = resolved.get(child);
+ if (!next) return null;
+ parent = next;
+ }
+ return parent;
+ }
+ return (path: string) => {
+ try {
+ const target = expand(cwd, path);
+ return target !== null && !isProtected(target);
+ } catch {
+ return false;
+ }
+ };
+}
+
+// Confirm the dispatcher starts through a link on the actual temporary mount.
+// The probe reaches only the system shell, before the operator directory is attached.
+function scriptDispatcher(
+ view: string,
+ origin: string,
+ allows: (path: string, link: boolean) => boolean,
+) {
+ const probe = append(view, "sh");
+ try {
+ const dispatcher = createRequire(import.meta.url).resolve(
+ "../scripts/dispatch_inventory_tool",
+ );
+ if (
+ !allows(dispatcher, true) ||
+ !allows("/bin/sh", true) ||
+ !executable(dispatcher)
+ )
+ return;
+ symlinkSync("/bin", fsPath(origin));
+ symlinkSync(dispatcher, fsPath(probe));
+ const args = ["-c", "exit 73"];
+ const options = { env: { PATH: "/dev/null" }, stdio: "ignore" } as const;
+ const env =
+ allows("/usr/bin/env", true) &&
+ spawnSync("/usr/bin/env", [probe, ...args], options).status === 73;
+ if (env || spawnSync(probe, args, options).status === 73)
+ return { dispatcher, env };
+ } catch {
+ // Older or non-executable installations still support direct tool links.
+ return;
+ } finally {
+ rmSync(fsPath(probe), { force: true });
+ rmSync(fsPath(origin), { force: true });
+ }
+}
+
+function scriptPathDirectory(
+ directory: string,
+ isProtected: (path: string) => boolean,
+ temporary: string[],
+ scripts: ReadonlyMap<string, string>,
+ allows: (path: string, link: boolean) => boolean,
+): string {
+ const entries = readdirSync(fsPath(directory), {
+ withFileTypes: true,
+ encoding: "buffer",
+ });
+ // Bun returns bare names for buffer-encoded directory entries.
+ const nameOf = (entry: (typeof entries)[number]) =>
+ decodePosixBytes(Buffer.isBuffer(entry) ? entry : entry.name);
+ const allowed = entries.filter((entry) => {
+ const path = append(directory, nameOf(entry));
+ const kind = Buffer.isBuffer(entry) ? lstat(path) : entry;
+ const link = kind.isSymbolicLink();
+ return (!link && !kind.isFile()) || allows(path, link);
+ });
+ if (allowed.length === entries.length) return directory;
+ // Keep safe neighbors in their original PATH position. env and the kernel
+ // then handle lookup, argument splitting and missing interpreters normally.
+ let copy: string | undefined;
+ for (const path of [tmpdir(), "/tmp"]) {
+ try {
+ const parent = canonical(path);
+ if (!parent.includes(delimiter) && !isProtected(parent)) {
+ const candidate = append(
+ parent,
+ `codex-security-tools-${randomUUID()}`,
+ );
+ mkdirSync(fsPath(candidate), { mode: 0o700 });
+ copy = candidate;
+ break;
+ }
+ } catch {
+ // Another external temporary directory may be usable.
+ }
+ }
+ if (!copy)
+ throw new Error("No external temporary directory for inventory tools");
+ temporary.push(copy);
+ const view = append(copy, "bin"),
+ origin = append(copy, "origin");
+ mkdirSync(fsPath(view), { mode: 0o700 });
+ const systems = new Map<string, string | undefined>();
+ const retained = allowed.map((entry) => {
+ const name = nameOf(entry);
+ const path = append(directory, name);
+ const loader = scripts.get(path);
+ // A forwarder would hide execvp's fallthrough for a missing kernel loader.
+ // Forward only scripts with a system interpreter whose launch we can prove.
+ if (loader && !systems.has(loader)) {
+ systems.set(
+ loader,
+ executable(loader)
+ ? ["/bin/sh", "/usr/bin/env"].find((system) =>
+ sameFile(loader, system),
+ )
+ : undefined,
+ );
+ }
+ return { name, path, interpreter: loader && systems.get(loader) };
+ });
+ const launch = retained.some((tool) => tool.interpreter)
+ ? scriptDispatcher(view, origin, allows)
+ : undefined;
+ if (launch) symlinkSync(fsPath(directory), fsPath(origin));
+ for (const tool of retained) {
+ const forward =
+ tool.interpreter === "/bin/sh" ||
+ (tool.interpreter === "/usr/bin/env" && launch?.env);
+ const target = launch && forward ? launch.dispatcher : tool.path;
+ symlinkSync(fsPath(target), fsPath(append(view, tool.name)));
+ }
+ return view;
+}
+
+export function inventoryToolPath(
+ path: string,
+ cwd: string,
+ roots: readonly string[],
+ mode: "native" | "script" | "campaign",
+) {
+ const temporary: string[] = [];
+ const key = (path: string) =>
+ sep === "\\" ? windowsLinkPath(path).toLowerCase() : path;
+ const boundaries = new Set(roots.map(key));
+ const isProtected = (entry: string) => {
+ for (const parent of ancestors(entry))
+ if (boundaries.has(key(parent))) return true;
+ return false;
+ };
+ const pathAllowed = campaignPathCheck(isProtected, cwd);
+ // Windows removes unsafe search entries in the SDK, before CreateProcess.
+ if (windows) return { path, allows: pathAllowed, cleanup() {} };
+ const scripts = new Map<string, string>();
+ const interpreterAllowed = interpreterCheck(
+ cwd,
+ pathAllowed,
+ mode === "campaign",
+ scripts,
+ );
+ const allows = (file: string) =>
+ pathAllowed(file) && interpreterAllowed(file);
+ const directories = path.split(delimiter).flatMap((entry) => {
+ try {
+ const lookup = isAbsolute(entry) ? entry : append(cwd, entry);
+ if (mode === "campaign" && !pathAllowed(lookup)) return [];
+ let directory = canonical(lookup);
+ if (isProtected(directory)) return [];
+ if (mode !== "native")
+ directory = scriptPathDirectory(
+ directory,
+ isProtected,
+ temporary,
+ scripts,
+ (file, link) => (link ? allows(file) : interpreterAllowed(file)),
+ );
+ // A directory containing ":" can be on PATH through an external alias.
+ if (directory.includes(delimiter))
+ return lookup.includes(delimiter) ||
+ isProtected(resolve(lookup)) ||
+ !pathAllowed(lookup)
+ ? []
+ : [lookup];
+ return [directory];
+ } catch {
+ return [];
+ }
+ });
+ // An empty POSIX PATH searches the current directory.
+ return {
+ path: directories.join(delimiter) || "/dev/null",
+ allows,
+ cleanup() {
+ for (const directory of temporary) {
+ try {
+ rmSync(fsPath(directory), { recursive: true, force: true });
+ } catch {
+ // Cleanup must not change the tool or campaign's exit status.
+ }
+ }
+ },
+ };
+}
+
+function* trustedTools(
name: "git" | "rg",
target: string,
+ protectedRoot: string,
rawWindowsLookup = false,
-): string | undefined {
- let protectedRoot = canonical(target);
- for (const ancestor of ancestors(protectedRoot))
- if (exists(append(ancestor, ".git"))) protectedRoot = ancestor;
+): Generator<string, undefined> {
const configured =
name === "git" ? environmentValue("CODEX_SECURITY_GIT") : undefined;
- if (configured === "") return undefined;
+ if (configured === "") return;
if (configured !== undefined && !isAbsolute(configured))
throw new Error(
"CODEX_SECURITY_GIT must name an absolute trusted executable.",
@@ -129,6 +529,14 @@ function trustedTool(
: [name];
return names.map((name) => append(directory, name));
});
+ const cwd = name === "git" ? process.cwd() : target;
+ const pathAllowed = campaignPathCheck(
+ (path) => isRepositoryPath(protectedRoot, path),
+ cwd,
+ );
+ const interpreterAllowed =
+ !windows && interpreterCheck(cwd, pathAllowed, false);
+ let lookupDenied = false;
for (const selected of candidates) {
const candidate =
name === "rg" &&
@@ -141,35 +549,47 @@ function trustedTool(
try {
invocation = append(canonical(dirname(candidate)), basename(candidate));
resolved = canonical(candidate);
- } catch {
+ } catch (error) {
+ if (
+ !windows &&
+ name === "rg" &&
+ !isRepositoryPath(protectedRoot, resolve(candidate))
+ ) {
+ const code = (error as NodeJS.ErrnoException).code;
+ if (code === "EACCES" || code === "EPERM") lookupDenied = true;
+ else if (code !== "ENOENT" && code !== "ENOTDIR") throw error;
+ }
continue;
}
if (
- !executable(resolved) ||
+ ((windows || name === "git") && !executable(resolved)) ||
(windows &&
(!/\.(exe|com)$/iu.test(candidate) || /\.(bat|cmd)$/iu.test(resolved)))
)
continue;
- const inRepository = [resolve(candidate), invocation, resolved].some(
- (path) => {
- try {
- inside(protectedRoot, path);
- return true;
- } catch {
- return false;
- }
- },
- );
- if (inRepository && !(name === "rg" && selectedBundledRipgrep(resolved))) {
+ // POSIX resolves each symlink before a following "..".
+ const inRepository =
+ [invocation, resolved].some((path) =>
+ isRepositoryPath(protectedRoot, path),
+ ) ||
+ (windows
+ ? isRepositoryPath(protectedRoot, resolve(candidate))
+ : !pathAllowed(candidate));
+ if (
+ (inRepository &&
+ !(name === "rg" && selectedBundledRipgrep(resolved, protectedRoot))) ||
+ (interpreterAllowed && !interpreterAllowed(resolved))
+ ) {
if (configured !== undefined)
throw new Error(
"CODEX_SECURITY_GIT must stay outside the protected repository.",
);
continue;
}
- return invocation;
+ yield inRepository ? resolved : invocation;
}
- return undefined;
+ if (lookupDenied)
+ throw Object.assign(new Error("spawn rg EACCES"), { code: "EACCES" });
}
function windowsToolPaths(searchPath: string): string[] {
@@ -190,13 +610,67 @@ function windowsToolPaths(searchPath: string): string[] {
return paths;
}
+type ToolOptions = SpawnOptions & {
+ cwd?: string;
+ stdio: ["ignore" | "pipe", "pipe", "pipe"];
+};
+
+const inventoryViews = new AsyncLocalStorage<
+ Map<string, ReturnType<typeof inventoryToolPath>>
+>();
+
+export async function withInventoryToolPaths<T>(
+ run: () => Promise<T>,
+): Promise<T> {
+ const views = new Map<string, ReturnType<typeof inventoryToolPath>>();
+ try {
+ return await inventoryViews.run(views, run);
+ } finally {
+ for (const view of views.values()) view.cleanup();
+ }
+}
+
+function spawnInventoryTool(
+ command: string,
+ args: string[],
+ options: ToolOptions,
+ inherited: Record<string, string>,
+ root: string,
+) {
+ if (windows || inherited.PATH === undefined)
+ return spawnTool(command, args, options, inherited);
+ const cwd = options.cwd ?? process.cwd();
+ const mode =
+ executable(command) && toolHeader(command) !== "native"
+ ? "script"
+ : "native";
+ const views = inventoryViews.getStore();
+ const key = JSON.stringify([root, cwd, inherited.PATH, mode]);
+ let view = views?.get(key);
+ if (!view) {
+ view = inventoryToolPath(inherited.PATH, cwd, [root], mode);
+ views?.set(key, view);
+ }
+ const PATH = view.path;
+ try {
+ const result = spawnTool(
+ command,
+ args,
+ { ...options, env: { ...(options.env ?? process.env), PATH } },
+ { ...inherited, PATH },
+ );
+ if (!views) result.child.once("close", view.cleanup);
+ return result;
+ } catch (error) {
+ if (!views) view.cleanup();
+ throw error;
+ }
+}
+
function spawnTool(
command: string,
args: string[],
- options: SpawnOptions & {
- cwd?: string;
- stdio: ["ignore" | "pipe", "pipe", "pipe"];
- },
+ options: ToolOptions,
inheritedEnvironment: Record<string, string>,
inputFd: 0 | 3 = 0,
) {
@@ -325,7 +799,8 @@ function inheritedToolPaths(additional: string[] = []): Record<string, string> {
}
function gitProcess(repo: string, args: string[]) {
- const command = trustedTool("git", repo);
+ const root = protectedToolRoot(repo);
+ const command = trustedTools("git", repo, root).next().value;
if (!command) return undefined;
const env: NodeJS.ProcessEnv = { ...process.env };
const inherited = inheritedToolPaths();
@@ -336,7 +811,7 @@ function gitProcess(repo: string, args: string[]) {
env.GIT_LITERAL_PATHSPECS = "1";
env.GIT_NO_LAZY_FETCH = "1";
env.GIT_ALLOW_PROTOCOL = "";
- return spawnTool(
+ return spawnInventoryTool(
command,
[
"-c",
@@ -349,6 +824,7 @@ function gitProcess(repo: string, args: string[]) {
],
{ env, stdio: ["pipe", "pipe", "pipe"] },
inherited,
+ root,
);
}
@@ -356,18 +832,43 @@ export async function runRipgrep(
args: string[],
repo: string,
): Promise<ToolResult> {
- if (!windows) return runTool("rg", args, repo);
+ const root = protectedToolRoot(repo);
const inherited = inheritedToolPaths([
"RIPGREP_CONFIG_PATH",
"CODEX_SECURITY_GIT",
]);
- const rawWindowsLookup = [repo, ...args, ...Object.values(inherited)].some(
- rawToolValue,
+ const rawWindowsLookup =
+ windows && [repo, ...args, ...Object.values(inherited)].some(rawToolValue);
+ let denied: unknown;
+ for (const command of trustedTools("rg", repo, root, rawWindowsLookup)) {
+ try {
+ return await collect(
+ spawnInventoryTool(
+ command,
+ args,
+ {
+ cwd: repo,
+ stdio: ["ignore", "pipe", "pipe"],
+ },
+ inherited,
+ root,
+ ),
+ );
+ } catch (error) {
+ // POSIX PATH lookup continues if a candidate cannot be executed, including
+ // a script whose interpreter is missing. Preserve actual tool exit statuses.
+ const code = (error as NodeJS.ErrnoException).code;
+ if (
+ windows ||
+ (code !== "ENOENT" && code !== "EACCES" && code !== "ENOTDIR")
+ )
+ throw error;
+ if (code === "EACCES") denied = error;
+ }
+ }
+ throw (
+ denied ?? Object.assign(new Error("spawn rg ENOENT"), { code: "ENOENT" })
);
- const command = trustedTool("rg", repo, rawWindowsLookup);
- if (!command)
- throw Object.assign(new Error("spawn rg ENOENT"), { code: "ENOENT" });
- return runTool(command, args, repo);
}
export async function runTool(
diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.ts b/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.ts
index adf48e7d4..2de694cdd 100644
--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.ts
+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.ts
@@ -1449,6 +1449,7 @@ async function testWorkerRuntimeSettings() {
"PYTHONIOENCODING",
"CODEX_SECURITY_PYTHON_COMMAND",
"PATH",
+ "_CODEX_SECURITY_SDK_NODE_SEARCH_PATH",
"HOME",
"NODE_OPTIONS",
"NODE_DEBUG",
@@ -2056,6 +2057,15 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,
path.join(fixture.root, `selected node ${index}`, "node"),
);
+ const scanGitEnvironments = settings.map((_, index) => {
+ const tools = path.join(fixture.root, `operator tools ${index}`);
+ return {
+ ...gitEnvironment,
+ PATH: [tools, gitEnvironment.PATH].join(path.delimiter),
+ CODEX_SECURITY_GIT: path.join(tools, "git"),
+ };
+ });
+
await Promise.all(
settings.map(async (_, index) => {
const directory = path.join(
@@ -2110,7 +2120,11 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,
await Promise.all(
executors.map((executor, index) => {
// Snapshot each scan environment independently.
+ Object.assign(process.env, scanGitEnvironments[index]);
process.env.CODEX_MCP_NODE_PATH = nodePaths[index];
+ process.env._CODEX_SECURITY_SDK_NODE_SEARCH_PATH = path.dirname(
+ nodePaths[index],
+ );
Object.assign(process.env, temporaryEnvironments[index]);
process.env.CODEX_SECURITY_STATE_DIR = path.join(
fixture.root,
@@ -2193,6 +2207,10 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,
workerConfigurations[index].parentSandbox.pluginReadRoot ??
path.join(fixture.root, "ambient-plugin"),
);
+ assert.equal(
+ workerLaunch.environment!._CODEX_SECURITY_SDK_NODE_SEARCH_PATH,
+ path.dirname(nodePaths[index]),
+ );
assert.equal(
workerLaunch.environment!.CODEX_SECURITY_CONFIG_PATH,
workerConfigurations[index].path,
@@ -2505,13 +2523,13 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,
assert.deepEqual(
invocation.gitEnvironment,
expectedGitEnvironment(
- gitEnvironment,
+ scanGitEnvironments[index],
nodePaths[index],
selectedProvider.environment,
),
);
for (const [name, value] of Object.entries({
- ...gitEnvironment,
+ ...scanGitEnvironments.at(-1),
CODEX_MCP_NODE_PATH: nodePaths.at(-1),
})) {
assert.equal(process.env[name], value);
@@ -2621,7 +2639,7 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,
assert.deepEqual(
preflight.gitEnvironment,
expectedGitEnvironment(
- gitEnvironment,
+ scanGitEnvironments[index],
nodePaths[index],
selectedProvider.environment,
),
diff --git a/plugins/codex-security/mcp-app/tests/test_mcp_app_smoke.ts b/plugins/codex-security/mcp-app/tests/test_mcp_app_smoke.ts
index 3eab22ffa..5e00db62d 100644
--- a/plugins/codex-security/mcp-app/tests/test_mcp_app_smoke.ts
+++ b/plugins/codex-security/mcp-app/tests/test_mcp_app_smoke.ts
@@ -87,6 +87,7 @@ assert.deepEqual(
"CODEX_ELECTRON_RESOURCES_PATH",
"CODEX_MANAGED_PACKAGE_ROOT",
"CODEX_MCP_NODE_PATH",
+ "_CODEX_SECURITY_SDK_NODE_SEARCH_PATH",
"OPENAI_API_KEY",
"OPENROUTER_API_KEY",
"FIREWORKS_API_KEY",
diff --git a/plugins/codex-security/mcp-app/tests/test_node_launcher.ts b/plugins/codex-security/mcp-app/tests/test_node_launcher.ts
index 2bc2b2f17..75d88bc58 100644
--- a/plugins/codex-security/mcp-app/tests/test_node_launcher.ts
+++ b/plugins/codex-security/mcp-app/tests/test_node_launcher.ts
@@ -52,21 +52,15 @@ async function fixture(
),
);
// Keep host-installed Node runtimes out of the simulated macOS runtime set.
- const tools = path.join(root, "shell-tools");
- await mkdir(tools);
- for (const name of ["dirname", "od", "tr"]) {
- const executable = spawnSync("/bin/sh", ["-c", `command -v ${name}`], {
- encoding: "utf8",
- }).stdout.trim();
- await symlink(executable, path.join(tools, name));
- }
+ const fallback = path.join(root, "fallback-bin");
+ await mkdir(fallback);
const source = await readFile(
path.join(sourcePluginRoot, "scripts", path.basename(launcher)),
"utf8",
);
await writeFile(
launcher,
- source.replace(/^PATH=.*$/m, `PATH="\${PATH}:"${shellQuote(tools)}`),
+ source.replace(/^ *PATH=.*$/m, ` PATH="\${PATH}:"${shellQuote(fallback)}`),
);
for (const entry of await readdir(path.join(pluginRoot, "mcp"), {
withFileTypes: true,
@@ -156,11 +150,14 @@ process.dlopen = function(module, filename, ...args) {
"CODEX_ELECTRON_RESOURCES_PATH",
"CODEX_CLI_PATH",
"CODEX_SECURITY_CONFIG_PATH",
+ "CODEX_SECURITY_PLUGIN_ROOT",
])
delete env[name];
return {
root,
repo,
+ fallback,
+ launcher,
addon,
managed,
ordinary,
@@ -192,6 +189,48 @@ process.dlopen = function(module, filename, ...args) {
};
}
+launcherTest("SDK launches preserve the supplied search path", async () => {
+ const { repo, fallback, launcher } = await fixture(false);
+ const node = path.join(fallback, "node");
+ await writeFile(
+ node,
+ `#!/bin/sh
+if [ "\${2:-}" = --helper ]; then
+ [ -n "$(command -p cat <&3)" ] || exit 1
+fi
+printf '%s' "$PATH"
+`,
+ { mode: 0o755 },
+ );
+ const run = (args: string[], env: NodeJS.ProcessEnv = {}) =>
+ spawnSync("/bin/sh", [launcher, ...args], {
+ env: { PATH: repo, HOME: repo, XDG_CACHE_HOME: repo, ...env },
+ encoding: "utf8",
+ });
+
+ const plugin = {
+ CODEX_SECURITY_PLUGIN_ROOT: path.dirname(path.dirname(launcher)),
+ };
+ for (const environment of [{}, plugin]) {
+ const standalone = run(["--stdio"], environment);
+ assert.equal(standalone.status, 0, standalone.stderr);
+ assert.equal(standalone.stdout, `${repo}:${fallback}`);
+ }
+
+ const sdk = { ...plugin, _CODEX_SECURITY_SDK_NODE_SEARCH_PATH: "" };
+ assert.equal(run(["--stdio"], sdk).status, 127);
+ for (const args of [["--stdio"], ["--helper", "probe"]]) {
+ for (const selection of [
+ { CODEX_MCP_NODE_PATH: node },
+ { _CODEX_SECURITY_SDK_NODE_SEARCH_PATH: fallback },
+ ]) {
+ const selected = run(args, { ...sdk, ...selection });
+ assert.equal(selected.status, 0, selected.stderr);
+ assert.equal(selected.stdout, repo);
+ }
+ }
+});
+
launcherTest(
"macOS helpers skip managed runtimes that reject the packaged addon",
async () => {
@@ -289,7 +328,7 @@ test(
fixtureLauncher,
source.replace(systemPaths, '"$FIXTURE_SYSTEM_NODE"'),
);
- const run = (candidate: string) =>
+ const run = (candidate: string, inspected?: string) =>
spawnSync("/bin/sh", [fixtureLauncher, "--helper", "database-info"], {
cwd: root,
encoding: "utf8",
@@ -300,6 +339,12 @@ test(
NODE_DEBUG: "module",
CODEX_BROWSER_USE_NODE_PATH: withoutSqlite,
FIXTURE_SYSTEM_NODE: candidate,
+ ...(inspected === undefined
+ ? {}
+ : {
+ CODEX_SECURITY_PLUGIN_ROOT: pluginRoot,
+ _CODEX_SECURITY_SDK_NODE_SEARCH_PATH: inspected,
+ }),
},
});
const linked = run(systemLink);
@@ -310,6 +355,12 @@ test(
const missing = run(path.join(root, "missing-node"));
assert.notEqual(missing.status, 0);
assert.match(missing.stderr, /node:sqlite/);
+ const excluded = run(systemLink, "");
+ assert.notEqual(excluded.status, 0);
+ assert.match(excluded.stderr, /node:sqlite/);
+ const selected = run(systemLink, path.dirname(systemLink));
+ assert.equal(selected.status, 0, selected.stderr);
+ assert.deepEqual(JSON.parse(selected.stdout), JSON.parse(linked.stdout));
assert.equal(existsSync(marker), false);
},
);
diff --git a/plugins/codex-security/plugin-files.json b/plugins/codex-security/plugin-files.json
index d8e79a683..d4db360be 100644
--- a/plugins/codex-security/plugin-files.json
+++ b/plugins/codex-security/plugin-files.json
@@ -69,6 +69,7 @@
"scripts/deep_scan_config.py",
"scripts/deep_scan_defaults.json",
"scripts/deep_scan_workbench.py",
+ "scripts/dispatch_inventory_tool",
"scripts/filesystem_identity.py",
"scripts/finalize_scan_contract.py",
"scripts/finding_preview.py",
diff --git a/plugins/codex-security/scripts/dispatch_inventory_tool b/plugins/codex-security/scripts/dispatch_inventory_tool
new file mode 100755
index 000000000..5c3c19789
--- /dev/null
+++ b/plugins/codex-security/scripts/dispatch_inventory_tool
@@ -0,0 +1,7 @@
+#!/bin/sh
+# The trailing slash preserves directory names ending in newlines through substitution.
+set -- "$(CDPATH= cd -P "${0%/*}/../origin" && printf '%s/' "${PWD%/}")${0##*/}" "$@"
+case "$1" in
+ /*) exec "$@" ;;
+ *) exit 126 ;;
+esac
diff --git a/plugins/codex-security/scripts/launch_codex_security_mcp b/plugins/codex-security/scripts/launch_codex_security_mcp
index d383d8758..539413e70 100755
--- a/plugins/codex-security/scripts/launch_codex_security_mcp
+++ b/plugins/codex-security/scripts/launch_codex_security_mcp
@@ -2,10 +2,13 @@
# Use LF line endings so POSIX can execute this script directly from Windows-built packages.
set -eu
-PATH="${PATH:-/usr/bin:/bin}:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin"
-export PATH
+# The SDK may have removed directories containing repository-owned executables.
+if [ -z "${_CODEX_SECURITY_SDK_NODE_SEARCH_PATH+x}" ]; then
+ PATH="${PATH:-/usr/bin:/bin}:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin"
+ export PATH
+fi
-launcher_dir=$(CDPATH= cd "$(dirname "$0")" && pwd)
+launcher_dir=$(CDPATH= cd "$(command -p dirname "$0")" && pwd)
server_path=$launcher_dir/../mcp/server.mjs
if [ "${1:-}" = "--helper" ]; then
server_path=$launcher_dir/../mcp/helpers.mjs
@@ -34,7 +37,7 @@ launch_node() {
trap 'forward_signal HUP 129' HUP
trap 'forward_signal INT 130' INT
trap 'forward_signal TERM 143' TERM
- printf '%s\000' "${HOME+x}" "${HOME-}" "$@" | od -An -v -tx1 | tr -d ' \n' | {
+ printf '%s\000' "${HOME+x}" "${HOME-}" "$@" | command -p od -An -v -tx1 | command -p tr -d ' \n' | {
# BusyBox ash requires a literal close redirection for a closed stdin.
if [ "$helper_stdin_open" = true ]; then
exec 0<&4
@@ -86,6 +89,12 @@ can_load_native() {
# This Linux runtime can still run helpers without SQLite. Prefer a system
# installation if available, without expanding discovery into the caller's PATH.
for system_candidate in /usr/local/bin/node /usr/bin/node /bin/node; do
+ if [ -n "${_CODEX_SECURITY_SDK_NODE_SEARCH_PATH+x}" ]; then
+ case ":$_CODEX_SECURITY_SDK_NODE_SEARCH_PATH:" in
+ *":${system_candidate%/*}:"*) ;;
+ *) continue ;;
+ esac
+ fi
if [ -x "$system_candidate" ] &&
_native_probe_output=$("$system_candidate" -e 'require("node:sqlite")' </dev/null 2>&1); then
selected_node=$system_candidate
@@ -106,8 +115,12 @@ do
fi
done
-remaining_path=$PATH
-while :; do
+remaining_path=${PATH-}
+if [ -n "${CODEX_SECURITY_PLUGIN_ROOT:-}" ] && [ -n "${_CODEX_SECURITY_SDK_NODE_SEARCH_PATH:-}" ]; then
+ # Only Node lookup uses the SDK-inspected fallback directories.
+ remaining_path=${remaining_path:+$remaining_path:}$_CODEX_SECURITY_SDK_NODE_SEARCH_PATH
+fi
+while [ -n "$remaining_path" ]; do
path_entry=${remaining_path%%:*}
node_path=${path_entry:-.}/node
if [ -x "$node_path" ] && can_load_native "$node_path"; then
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.md
index 570ec08d9..13a26ca76 100644
--- a/sdk/typescript/docs/cli.md
+++ b/sdk/typescript/docs/cli.md
@@ -1408,6 +1408,22 @@ including during recovery. Run post-scan prompts separately. A resumed scan also
limit and includes prior recorded usage in its cost estimate.
Bulk scans use clean shallow checkouts and support repository/path scopes.
+Bulk checkout, scan, and recovery processes select host tools outside every local
+source and campaign checkout. Inventory uses an external ripgrep executable or
+the copy shipped with the selected Codex installation.
+
+On POSIX, campaign processes and script-based inventory tools search readable
+tool directories. Launchers must be readable so their shebang interpreters can
+be checked. Use an absolute interpreter path for campaign scripts, including
+`#!/usr/bin/env sh`, because workers run in different directories. If a directory
+contains an ineligible executable, its other tools remain available through a
+temporary PATH. Scripts using the system `/bin/sh` or `/usr/bin/env` run from
+their installed location when the packaged dispatcher can start. Keep other
+prefix-sensitive tools, including Python virtual environments, in directories
+where every entry can be used. On Windows, the campaign omits a tool directory
+from the child PATH if its Git, ripgrep, or Node executable link passes through a
+selected source.
+
CSV scopes are literal paths relative to each checkout, including names such
as `~/src`.
Configured diff or working-tree scopes are rejected unless every affected row
diff --git a/sdk/typescript/package.json b/sdk/typescript/package.json
index 20dbcd6f1..9928a38d3 100644
--- a/sdk/typescript/package.json
+++ b/sdk/typescript/package.json
@@ -55,6 +55,7 @@
"publishConfig": {
"access": "public",
"executableFiles": [
+ "_bundled_plugin/scripts/dispatch_inventory_tool",
"_bundled_plugin/scripts/launch_codex_security_mcp"
]
},
diff --git a/sdk/typescript/scripts/check-package.mjs b/sdk/typescript/scripts/check-package.mjs
index ef10b6e31..04e677b21 100644
--- a/sdk/typescript/scripts/check-package.mjs
+++ b/sdk/typescript/scripts/check-package.mjs
@@ -198,6 +198,7 @@ const posixMcpLauncher =
"package/_bundled_plugin/scripts/launch_codex_security_mcp";
for (const [path, name] of [
["package/bin/codex-security.mjs", "CLI"],
+ ["package/_bundled_plugin/scripts/dispatch_inventory_tool", "inventory tool"],
[posixMcpLauncher, "MCP"],
]) {
const permissions =
diff --git a/sdk/typescript/scripts/package-dist-files.mjs b/sdk/typescript/scripts/package-dist-files.mjs
index 8b41b12c1..15b3f494a 100644
--- a/sdk/typescript/scripts/package-dist-files.mjs
+++ b/sdk/typescript/scripts/package-dist-files.mjs
@@ -10,6 +10,7 @@ const distModules = [
"artifact-export",
"auth",
"bulk-scan-discovery",
+ "bundled-plugin",
"cli",
"cli-argument",
"cli-daybreak",
diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.ts
index 56b041b50..5ea5b76a5 100644
--- a/sdk/typescript/src/api.ts
+++ b/sdk/typescript/src/api.ts
@@ -250,7 +250,10 @@ import {
} from "./version.js";
import { SCAN_MODES } from "./scan-modes.js";
import { readSavedScanLifecycle } from "./saved-scan-bootstrap.js";
-import { bundledCodexSdkEnvironment } from "./codex-sdk-environment.js";
+import {
+ bundledCodexSdkEnvironment,
+ definedEnvironment,
+} from "./codex-sdk-environment.js";
import {
canonicalConfigPath,
acquireCodexSecurityCredentialHomeLock,
@@ -275,6 +278,8 @@ import {
prepareCodexSecurityCredentialHome,
preserveCodexSecurityPluginRegistration,
pluginExecutionEnvironment,
+ SDK_NODE_SEARCH_PATH,
+ sdkNodeSearchPath,
environmentWithGit,
pluginMetadata,
planOutputArchive,
@@ -320,6 +325,7 @@ import {
} from "./targets.js";
import { startHeadDriftMonitor } from "./target-drift.js";
import {
+ campaignExecutable,
inspectTrustedExecutable,
isWithin,
type InspectedExecutable,
@@ -357,6 +363,7 @@ interface PreparedRuntime {
}
interface PreparedSession {
+ toolRoots: readonly string[];
pricingContext?: ScanPricingContext;
safetyIdentifier?: string;
runtime: PreparedRuntime;
@@ -2414,10 +2421,11 @@ export class CodexSecurity {
),
};
const hosted = this.#dependencies.hostedScan !== undefined;
- for (const root of [
+ session.toolRoots = [
(await gitMarkerRoot(repo, signal, "outermost")) ?? repo,
...(knowledgeBase?.protectedRoots ?? []),
- ]) {
+ ];
+ for (const root of session.toolRoots) {
git = await inspectTrustedExecutable("git", git.environment, root);
if (this.#dependencies.hostedScan !== undefined) {
// Match the hosted MCP launchers' PATH-based tool lookups.
@@ -4738,15 +4746,20 @@ export class CodexSecurity {
pluginVersion: session.runtime.plugin.version,
providerFamily: requestContext.metadata["codex_security_provider"],
});
+ const pluginPaths = {
+ ...runtimePaths,
+ [SDK_NODE_SEARCH_PATH]:
+ process.platform === "win32"
+ ? undefined
+ : await sdkNodeSearchPath(session.toolRoots),
+ };
const hosted = this.#dependencies.hostedScan;
if (hosted !== undefined) {
const workbench = this.#dependencies.runWorkbench ?? runWorkbench;
- const environment = {
- ...definedEnvironment(
- environmentWithGit(session.runtime.environment, git),
- ),
- ...runtimePaths,
- };
+ const environment = definedEnvironment({
+ ...environmentWithGit(session.runtime.environment, git),
+ ...pluginPaths,
+ });
const model = scanModelConfiguration(session.effectiveConfig);
return {
environment,
@@ -4878,7 +4891,7 @@ export class CodexSecurity {
),
...(providerEnvKey === undefined ? {} : { [providerEnvKey]: apiKey! }),
CODEX_HOME: runtime.codexHome,
- ...runtimePaths,
+ ...pluginPaths,
};
for (const name of Object.keys(environment)) {
if (name.toUpperCase() === SAFETY_IDENTIFIER_ENV)
@@ -4943,6 +4956,22 @@ export class CodexSecurity {
sdkEnvironment,
);
}
+ const executable = codexPathOverride ?? environment["CODEX_CLI_PATH"]!;
+ const campaign = campaignExecutable(executable, () =>
+ codexPathOverride === undefined
+ ? bundledCodexSdkEnvironment(executable, sdkEnvironment)
+ : sdkEnvironment,
+ );
+ if (campaign) {
+ const selected = await campaign;
+ // Pin the SDK launch so it cannot prepend its unfiltered bundled tools again.
+ codexPathOverride = selected.executable;
+ environment["CODEX_CLI_PATH"] = selected.executable;
+ sdkEnvironment = definedEnvironment({
+ ...selected.environment,
+ CODEX_CLI_PATH: selected.executable,
+ });
+ }
const codexOptions: CodexOptions & { nativeProfile?: string } = {
...(codexPathOverride === undefined
? {}
@@ -5022,6 +5051,7 @@ export class CodexSecurity {
signal,
});
return {
+ toolRoots: protectedRoots,
runtime,
runtimeHome,
effectiveConfig,
@@ -5237,6 +5267,7 @@ export class CodexSecurity {
return {
runtime,
safetyIdentifier: options.safetyIdentifier,
+ toolRoots: protectedRoots,
runtimeHome,
effectiveConfig,
preflightConfig,
@@ -7707,16 +7738,7 @@ function standaloneFindingForPrompt(finding: string | object): string {
return jsonForPrompt(finding);
}
-/** @internal */
-export function definedEnvironment(
- environment: ProcessEnvironment,
-): Record<string, string> {
- return Object.fromEntries(
- Object.entries(environment).filter(
- (entry): entry is [string, string] => entry[1] !== undefined,
- ),
- );
-}
+export { definedEnvironment };
function withoutCodexHome(
environment: ProcessEnvironment,
diff --git a/sdk/typescript/src/artifact-export.ts b/sdk/typescript/src/artifact-export.ts
index 24e8b761b..894fac53d 100644
--- a/sdk/typescript/src/artifact-export.ts
+++ b/sdk/typescript/src/artifact-export.ts
@@ -10,6 +10,7 @@ import type { JsonObject } from "./config.js";
import { resolveConfigPath } from "./config-path.js";
import { CodexSecurityError } from "./errors.js";
import { relativePathIsOutside as isOutsidePath } from "./targets.js";
+import { campaignCommandEnvironment } from "./trusted-executable.js";
import {
type PluginPythonOptions,
bundledPluginRoot,
@@ -162,7 +163,7 @@ export async function runArtifactHelper(
...args,
],
{
- env: environment,
+ env: (await campaignCommandEnvironment(environment)) ?? environment,
stdio: ["ignore", "pipe", "pipe"],
windowsHide: true,
signal: options.signal,
diff --git a/sdk/typescript/src/bundled-plugin.ts b/sdk/typescript/src/bundled-plugin.ts
new file mode 100644
index 000000000..2959f1228
--- /dev/null
+++ b/sdk/typescript/src/bundled-plugin.ts
@@ -0,0 +1,30 @@
+import { lstat, realpath } from "node:fs/promises";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { PluginBootstrapError } from "./errors.js";
+
+export function bundledPluginCandidates(moduleDirectory: string): string[] {
+ return [
+ resolve(moduleDirectory, "_bundled_plugin"),
+ resolve(moduleDirectory, "../_bundled_plugin"),
+ ];
+}
+
+export async function hasPluginManifest(root: string): Promise<boolean> {
+ return await lstat(join(root, ".codex-plugin", "plugin.json")).then(
+ (metadata) => metadata.isFile(),
+ () => false,
+ );
+}
+
+export async function bundledPluginRoot(): Promise<string> {
+ const moduleDirectory = dirname(fileURLToPath(import.meta.url));
+ for (const candidate of bundledPluginCandidates(moduleDirectory)) {
+ if (await hasPluginManifest(candidate)) {
+ return await realpath(candidate);
+ }
+ }
+ throw new PluginBootstrapError(
+ "The bundled Codex Security plugin is missing.",
+ );
+}
diff --git a/sdk/typescript/src/codex-sdk-environment.ts b/sdk/typescript/src/codex-sdk-environment.ts
index 714c4d661..46f50abb0 100644
--- a/sdk/typescript/src/codex-sdk-environment.ts
+++ b/sdk/typescript/src/codex-sdk-environment.ts
@@ -2,6 +2,36 @@ import { existsSync, readdirSync, realpathSync, statSync } from "node:fs";
import { createRequire } from "node:module";
import { delimiter, dirname, join } from "node:path";
import { PluginBootstrapError } from "./errors.js";
+import { campaignExecutable } from "./trusted-executable.js";
+
+export function definedEnvironment(
+ environment: Readonly<NodeJS.ProcessEnv>,
+): Record<string, string> {
+ return Object.fromEntries(
+ Object.entries(environment).filter(
+ (entry): entry is [string, string] => entry[1] !== undefined,
+ ),
+ );
+}
+
+/** Bind the native launch after the packaged SDK tools have been added to PATH. */
+export async function nativeCodexLaunch(
+ command: string,
+ inherited?: Record<string, string>,
+) {
+ const environment =
+ inherited && bundledCodexSdkEnvironment(command, inherited);
+ const campaign = campaignExecutable(command, environment ?? process.env);
+ if (!campaign) return { command, environment };
+ const selected = await campaign;
+ return {
+ command: selected.executable,
+ environment: definedEnvironment({
+ ...selected.environment,
+ CODEX_CLI_PATH: selected.executable,
+ }),
+ };
+}
export function bundledCodexSdkEnvironment(
command: string,
diff --git a/sdk/typescript/src/deep-scan.ts b/sdk/typescript/src/deep-scan.ts
index 1e171126d..6fcadbfdc 100644
--- a/sdk/typescript/src/deep-scan.ts
+++ b/sdk/typescript/src/deep-scan.ts
@@ -5,7 +5,7 @@ import { pathToFileURL } from "node:url";
import type { CodexOptions } from "@openai/codex-sdk";
import { parse } from "smol-toml";
import {
- bundledCodexSdkEnvironment,
+ nativeCodexLaunch,
resolveBundledCodexExecutable,
} from "./codex-sdk-environment.js";
import { CodexSecurityError } from "./errors.js";
@@ -105,6 +105,22 @@ function codeModeTable(value: JsonValue | undefined): JsonObject | undefined {
return isRecord(value) ? value : undefined;
}
+async function deepScanLaunch({
+ codexOptions,
+ preflightCommand: command,
+}: Pick<DirectDeepScanOptions, "codexOptions" | "preflightCommand">) {
+ const launch = await nativeCodexLaunch(command.command, {
+ ...codexOptions.env,
+ ...(codexOptions.apiKey === undefined
+ ? {}
+ : { CODEX_API_KEY: codexOptions.apiKey }),
+ });
+ return {
+ command: { ...command, command: launch.command },
+ environment: launch.environment!,
+ };
+}
+
/** Read the same native layers and CLI overrides as the parent before adding its tool. */
export async function readDeepScanParentConfig(
options: Pick<
@@ -115,19 +131,14 @@ export async function readDeepScanParentConfig(
pluginServers?: Record<string, unknown>;
},
): Promise<JsonObject | undefined> {
- const { codexOptions, preflightCommand: command } = options;
+ const { codexOptions } = options;
const config = codexOptions.config ?? {};
// The provider-profile launcher emits whole top-level tables instead.
const overrides =
codexOptions.nativeProfile === undefined
? sdkConfigFlags(config)
: (await nativeProfileClient()).profileConfigOverrides(config);
- const environment = bundledCodexSdkEnvironment(command.command, {
- ...codexOptions.env,
- ...(codexOptions.apiKey === undefined
- ? {}
- : { CODEX_API_KEY: codexOptions.apiKey }),
- });
+ const { command, environment } = await deepScanLaunch(options);
const configOverrides = [
...overrides,
...(codexOptions.configOverrides ?? []),
@@ -367,13 +378,7 @@ export async function* runDeepScan(
pathToFileURL(join(options.pluginRoot, "scripts", "codex_profile.mjs")).href
);
const configured = options.codexOptions;
- const command = options.preflightCommand;
- const environment = bundledCodexSdkEnvironment(command.command, {
- ...configured.env,
- ...(configured.apiKey === undefined
- ? {}
- : { CODEX_API_KEY: configured.apiKey }),
- });
+ const { command, environment } = await deepScanLaunch(options);
const session = (await withCodexPreflightLock(
environment,
options.signal,
diff --git a/sdk/typescript/src/multiscan.ts b/sdk/typescript/src/multiscan.ts
index 14efbf940..71ecd249f 100644
--- a/sdk/typescript/src/multiscan.ts
+++ b/sdk/typescript/src/multiscan.ts
@@ -57,6 +57,7 @@ import {
import {
DiffTarget,
gitOutput,
+ gitProtectionRoots,
nullIfMissingPath,
UNSUPPORTED_GIT_ENVIRONMENT,
resolveTargetPath,
@@ -69,7 +70,10 @@ import {
} from "./scan-settings.js";
import { workflowDigest } from "./finding-workflow.js";
import type { ScanResult } from "./result.js";
-import { resolveTrustedExecutable } from "./trusted-executable.js";
+import {
+ resolveTrustedExecutable,
+ withProtectedExecutableRoots,
+} from "./trusted-executable.js";
const execFile = promisify(execFileCallback);
const CHECKOUT_MARKER = ".git/codex-security-campaign-attempt";
@@ -202,7 +206,25 @@ export async function runMultiscan(
let pendingRoots: Promise<DocumentRoots> | undefined;
const documentRoots = () =>
(pendingRoots ??= bulkDocumentRoots(tasks, options.signal));
- const prompts = await resolveScanPrompts(options, documentRoots);
+ const requestedOutput = resolve(options.outputDir);
+ const localSources = [
+ ...new Set(tasks.map((task) => task.repository).filter(isAbsolute)),
+ ];
+ const worktrees = await Promise.all(
+ localSources.map((source) => gitProtectionRoots(source, options.signal)),
+ );
+ const executableRoots = (output: string) => [
+ ...localSources,
+ ...worktrees.flat(),
+ join(output, "checkouts"),
+ join(output, "recovery-checkouts"),
+ ];
+ const prompts = await resolveScanPrompts(options, () =>
+ withProtectedExecutableRoots(
+ executableRoots(requestedOutput),
+ documentRoots,
+ ),
+ );
const resolvedOptions: MultiscanOptions = {
...options,
...prompts,
@@ -222,7 +244,6 @@ export async function runMultiscan(
) {
throw new Error("Custom validation is not supported for Deep scans.");
}
- const requestedOutput = resolve(options.outputDir);
if (options.recoverScan !== undefined) {
const manifest = await lstat(join(requestedOutput, "manifest.json")).catch(
undefinedIfMissingFile,
@@ -247,12 +268,16 @@ export async function runMultiscan(
);
})());
try {
- const result = await runCampaign(
- resolvedOptions,
- tasks,
- output,
- resumePluginRoot,
- documentRoots,
+ const result = await withProtectedExecutableRoots(
+ executableRoots(output),
+ () =>
+ runCampaign(
+ resolvedOptions,
+ tasks,
+ output,
+ resumePluginRoot,
+ documentRoots,
+ ),
);
return (await realpath(requestedOutput).catch(() => undefined)) === output
? { ...result, resultsPath: join(requestedOutput, "results.jsonl") }
diff --git a/sdk/typescript/src/provider-profile.ts b/sdk/typescript/src/provider-profile.ts
index ad6eeadb2..06e37f306 100644
--- a/sdk/typescript/src/provider-profile.ts
+++ b/sdk/typescript/src/provider-profile.ts
@@ -16,7 +16,7 @@ import {
type JsonObject,
} from "./config.js";
import { isRecord } from "./record.js";
-import { bundledCodexSdkEnvironment } from "./codex-sdk-environment.js";
+import { nativeCodexLaunch } from "./codex-sdk-environment.js";
import {
bundledPluginRoot,
acquireCodexSecurityCredentialHomeLock,
@@ -185,17 +185,17 @@ export async function createProfileCodex(
profileName: string,
requestedPermissionProfile?: string,
): Promise<Codex> {
- const command =
- options.codexPathOverride ?? resolveCodexCommand(options.env).command;
+ const { command, environment } = await nativeCodexLaunch(
+ options.codexPathOverride ?? resolveCodexCommand(options.env).command,
+ options.env,
+ );
const client = await nativeProfileClient();
return client.createCodexProfileClient({
...options,
codexPathOverride: executablePathForSpawn(command),
profileName,
requestedPermissionProfile,
- ...(options.env === undefined
- ? {}
- : { env: bundledCodexSdkEnvironment(command, options.env) }),
+ env: environment,
}) as Codex;
}
@@ -215,17 +215,15 @@ export async function preflightReadOnlyProfileCodex(
`default_permissions=${JSON.stringify(permissionProfileId)}`,
`permissions.${permissionProfileId}=${inlineToml(expectedProfile)}`,
];
- const command =
- options.codexPathOverride ?? resolveCodexCommand(options.env).command;
+ const { command, environment: env } = await nativeCodexLaunch(
+ options.codexPathOverride ?? resolveCodexCommand(options.env).command,
+ options.env,
+ );
const client = await nativeProfileClient();
const providers = resolveCodexProfile(providerConfig)["model_providers"];
const definitions = isRecord(providers)
? (client.preflightProviderDefinitions(providers) as JsonObject)
: {};
- const env =
- options.env === undefined
- ? undefined
- : bundledCodexSdkEnvironment(command, options.env);
await withCodexPreflightLock(env, signal, async () => {
await preflight.preflightDeepScanWorkerPermissionProfile({
codexPath: executablePathForSpawn(command),
diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.ts
index a9a036bda..26a1353f8 100644
--- a/sdk/typescript/src/runtime.ts
+++ b/sdk/typescript/src/runtime.ts
@@ -6,6 +6,11 @@ import {
} from "./executable-path.js";
import { retryWindowsRename } from "./retry-windows-rename.js";
export { executablePathForSpawn } from "./executable-path.js";
+import { bundledPluginRoot, hasPluginManifest } from "./bundled-plugin.js";
+export {
+ bundledPluginCandidates,
+ bundledPluginRoot,
+} from "./bundled-plugin.js";
import {
PLUGIN_PYTHON_PROBE,
PLUGIN_PYTHON_PROBE_TIMEOUT_MS,
@@ -68,7 +73,6 @@ import {
sep,
win32,
} from "node:path";
-import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import type { Duplex } from "node:stream";
import { pipeline } from "node:stream/promises";
@@ -97,6 +101,8 @@ import {
} from "./config.js";
import { isRecord } from "./record.js";
import {
+ campaignExecutable,
+ inspectTrustedExecutable,
isWithin,
resolveTrustedExecutable,
type InspectedExecutable,
@@ -2174,25 +2180,6 @@ export async function runWorkbench(
return result as JsonObject;
}
-export function bundledPluginCandidates(moduleDirectory: string): string[] {
- return [
- resolve(moduleDirectory, "_bundled_plugin"),
- resolve(moduleDirectory, "../_bundled_plugin"),
- ];
-}
-
-export async function bundledPluginRoot(): Promise<string> {
- const moduleDirectory = dirname(fileURLToPath(import.meta.url));
- for (const candidate of bundledPluginCandidates(moduleDirectory)) {
- if (await hasPluginManifest(candidate)) {
- return await realpath(candidate);
- }
- }
- throw new PluginBootstrapError(
- "The bundled Codex Security plugin is missing.",
- );
-}
-
export async function resolveScanOutputPath(
outputDirectory: string,
validateTraversalLink?: (path: string) => void,
@@ -3414,6 +3401,30 @@ type PluginRuntimeProjection = {
files: Map<string, { contents: Buffer; mode?: number }>;
};
+// Private handoff to the staged SDK launcher and shell-invoked helpers.
+export const SDK_NODE_SEARCH_PATH = "_CODEX_SECURITY_SDK_NODE_SEARCH_PATH";
+
+export async function sdkNodeSearchPath(
+ roots: readonly string[],
+): Promise<string> {
+ let fallback = "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin";
+ const current = dirname(process.execPath);
+ if (
+ process.release.name === "node" &&
+ !process.versions["bun"] &&
+ !process.versions["electron"] &&
+ basename(process.execPath) === "node" &&
+ !current.includes(":")
+ )
+ fallback += `:${current}`;
+ const inspected = await inspectTrustedExecutable(
+ "node",
+ { PATH: fallback },
+ roots,
+ );
+ return inspected.environment["PATH"] ?? "";
+}
+
async function pluginRuntimeProjection(
root: string,
signal?: AbortSignal,
@@ -3454,7 +3465,7 @@ async function pluginRuntimeProjection(
'if [ -n "${CODEX_SECURITY_PLUGIN_ROOT:-}" ]; then\n' +
' exec "$CODEX_SECURITY_PLUGIN_ROOT/scripts/launch_codex_security_mcp" "$@"\n' +
"fi\n" +
- 'exec "$(dirname "$0")/launch_codex_security_mcp" "$@"\n',
+ 'exec "$(command -p dirname "$0")/launch_codex_security_mcp" "$@"\n',
),
mode: 0o755,
});
@@ -4280,10 +4291,10 @@ export function isDisconnectedChildStdin(
export async function runCodexCommand(
command: CodexCommand,
- args: readonly string[],
+ args: readonly string[] | ((executable: string) => readonly string[]),
environment: ProcessEnvironment,
input?: string | Uint8Array,
- signal?: AbortSignal,
+ launchSignal?: AbortSignal | (() => AbortSignal),
{
registrationHandshake = false,
stdinPrefix,
@@ -4294,17 +4305,23 @@ export async function runCodexCommand(
cwd?: string;
} = {},
): Promise<CodexCommandResult> {
+ const campaign = campaignExecutable(command.command, environment);
+ const selected = campaign && (await campaign);
+ const executable = selected?.executable ?? command.command;
+ const commandArgs = typeof args === "function" ? args(executable) : args;
+ const signal =
+ typeof launchSignal === "function" ? launchSignal() : launchSignal;
const cancellation = registrationHandshake
? new AbortController()
: undefined;
const abort = () => cancellation?.abort(signal?.reason);
const commandSignal = cancellation?.signal ?? signal;
const child = spawn(
- executablePathForSpawn(command.command),
- [...(command.args ?? []), ...args],
+ executablePathForSpawn(executable),
+ [...(command.args ?? []), ...commandArgs],
{
cwd,
- env: environment,
+ env: selected?.environment ?? environment,
stdio: registrationHandshake
? ["pipe", "pipe", "pipe", "pipe"]
: ["pipe", "pipe", "pipe"],
@@ -4387,8 +4404,14 @@ export async function probeCodexSandbox(
// This preflight covers the Unix sandbox backends.
if (process.platform === "win32") return;
// Reuse the resolved Codex executable instead of looking up a probe on PATH.
- const args = ["sandbox", "--", command.command, "--version"];
- const timeout = AbortSignal.timeout(SANDBOX_PROBE_TIMEOUT_MILLISECONDS);
+ const args = (executable: string) => [
+ "sandbox",
+ "--",
+ executable,
+ "--version",
+ ];
+ signal?.throwIfAborted();
+ let timeout: AbortSignal | undefined;
let detail: string;
try {
const result = await runCodexCommand(
@@ -4396,7 +4419,14 @@ export async function probeCodexSandbox(
args,
environment,
undefined,
- signal === undefined ? timeout : AbortSignal.any([signal, timeout]),
+ () => {
+ // Campaign tool selection happens before the sandbox process starts.
+ signal?.throwIfAborted();
+ timeout = AbortSignal.timeout(SANDBOX_PROBE_TIMEOUT_MILLISECONDS);
+ return signal === undefined
+ ? timeout
+ : AbortSignal.any([signal, timeout]);
+ },
);
if (result.success) return;
detail =
@@ -4405,7 +4435,7 @@ export async function probeCodexSandbox(
`Codex exited with status ${result.exitCode}.`;
} catch (error) {
signal?.throwIfAborted();
- if (timeout.aborted)
+ if (timeout?.aborted)
throw new SandboxUnavailableError(
`Codex sandbox probe timed out after ${SANDBOX_PROBE_TIMEOUT_MILLISECONDS / 1000} seconds.`,
{ cause: error },
@@ -4417,7 +4447,7 @@ export async function probeCodexSandbox(
? "\nOn Linux this usually means unprivileged user namespaces are restricted (kernel.apparmor_restrict_unprivileged_userns=1 on Ubuntu 24.04 and later), which Bubblewrap needs; inside the container image, use the AppArmor profile and Compose override from the SDK README."
: "";
throw new SandboxUnavailableError(
- `Codex could not run a command in its sandbox: ${detail}\nTo reproduce, run '${command.command} ${args.join(" ")}'.${guidance}`,
+ `Codex could not run a command in its sandbox: ${detail}\nTo reproduce, run '${command.command} ${args(command.command).join(" ")}'.${guidance}`,
);
}
@@ -4635,13 +4665,6 @@ export function isPythonPathCandidate(candidate: string): boolean {
return candidate.includes("/") || candidate.includes("\\");
}
-async function hasPluginManifest(root: string): Promise<boolean> {
- return await lstat(join(root, ".codex-plugin", "plugin.json")).then(
- (metadata) => metadata.isFile(),
- () => false,
- );
-}
-
/** @internal Compare filesystem identity without depending on path spelling. */
export function sameFile(left: string, right: string): Promise<boolean> {
// NTFS file IDs can exceed JavaScript's safe integer range.
diff --git a/sdk/typescript/src/targets.ts b/sdk/typescript/src/targets.ts
index a4b58cc7b..83f8b5da0 100644
--- a/sdk/typescript/src/targets.ts
+++ b/sdk/typescript/src/targets.ts
@@ -975,6 +975,19 @@ export async function gitOutput(
);
}
+function unavailableGitMarkerPath(
+ error: unknown,
+ search: "nearest" | "outermost",
+): boolean {
+ const { code } = error as NodeJS.ErrnoException;
+ return (
+ code === "ENOENT" ||
+ code === "ENOTDIR" ||
+ (search === "outermost" &&
+ ["EACCES", "EPERM", "ELOOP", "ENAMETOOLONG"].includes(code ?? ""))
+ );
+}
+
/** Bound repository-supplied document links to the selected checkout or directory. */
export async function documentSourceRoot(
repository: string,
@@ -991,7 +1004,7 @@ export async function gitMarkerRoot(
signal: AbortSignal | undefined,
search: "nearest" | "outermost",
): Promise<string | null> {
- let candidate = resolve(repository);
+ let candidate = resolveTargetPath(repository);
let current: string;
while (true) {
try {
@@ -1003,11 +1016,7 @@ export async function gitMarkerRoot(
} catch (error) {
// Stale or inaccessible descendants still belong to their accessible checkout ancestors.
throwIfAborted(signal);
- const code = (error as NodeJS.ErrnoException).code;
- if (
- search !== "outermost" ||
- !["ENOENT", "ENOTDIR", "EACCES", "EPERM", "ELOOP"].includes(code ?? "")
- )
+ if (search !== "outermost" || !unavailableGitMarkerPath(error, search))
throw error;
const parent = dirname(candidate);
if (parent === candidate) throw error;
@@ -1043,14 +1052,7 @@ async function walkGitMarkers(
root = current;
} catch (error) {
throwIfAborted(signal);
- const code = (error as NodeJS.ErrnoException).code;
- if (
- code !== "ENOENT" &&
- code !== "ENOTDIR" &&
- (search !== "outermost" ||
- !["EACCES", "EPERM", "ELOOP"].includes(code ?? ""))
- )
- throw error;
+ if (!unavailableGitMarkerPath(error, search)) throw error;
}
const parent = dirname(current);
if (parent === current) return root;
diff --git a/sdk/typescript/src/trusted-executable.ts b/sdk/typescript/src/trusted-executable.ts
index 8850515fa..b492327e9 100644
--- a/sdk/typescript/src/trusted-executable.ts
+++ b/sdk/typescript/src/trusted-executable.ts
@@ -1,4 +1,6 @@
+import { AsyncLocalStorage } from "node:async_hooks";
import { constants } from "node:fs";
+import { pathToFileURL } from "node:url";
import { access, realpath, stat } from "node:fs/promises";
import {
basename,
@@ -22,6 +24,100 @@ export interface InspectedExecutable {
environment: Record<string, string | undefined>;
}
+interface ToolPathView {
+ path: string;
+ cleanup(): void;
+ allows: (path: string) => boolean;
+}
+
+const campaignScope = new AsyncLocalStorage<{
+ roots: readonly string[];
+ views: Map<string, ToolPathView>;
+ project: (
+ path: string,
+ cwd: string,
+ roots: readonly string[],
+ mode: "campaign",
+ ) => ToolPathView;
+}>();
+
+function canonicalRoot(root: string): Promise<string> {
+ return realpath(root).catch(() => resolve(root));
+}
+
+async function campaignPathHelper() {
+ const { bundledPluginRoot } = await import("./bundled-plugin.js");
+ const path = join(await bundledPluginRoot(), "mcp/helpers.mjs");
+ const project = (await import(pathToFileURL(path).href)).default
+ .inventoryToolPath;
+ if (typeof project !== "function")
+ throw new Error("The bundled plugin is missing campaign tool lookup.");
+ return project;
+}
+
+/** Include every selected source when a campaign launches tools from a new checkout. */
+export async function withProtectedExecutableRoots<T>(
+ roots: readonly string[],
+ run: () => Promise<T>,
+): Promise<T> {
+ const canonical = await Promise.all(roots.map(canonicalRoot));
+ const scope = {
+ roots: [
+ ...new Set([...(campaignScope.getStore()?.roots ?? []), ...canonical]),
+ ],
+ views: new Map<string, ToolPathView>(),
+ project: await campaignPathHelper(),
+ };
+ try {
+ return await campaignScope.run(scope, run);
+ } finally {
+ for (const view of scope.views.values()) view.cleanup();
+ }
+}
+
+/** Bind an actual host launcher and its environment within this campaign. */
+export function campaignExecutable(
+ candidate: string,
+ environment:
+ Readonly<NodeJS.ProcessEnv> | (() => Readonly<NodeJS.ProcessEnv>),
+): Promise<TrustedExecutable> | undefined {
+ if (!campaignScope.getStore()) return;
+ const env = typeof environment === "function" ? environment() : environment;
+ return resolveTrustedExecutable(candidate, env, []).then(async (command) => {
+ if (!command)
+ throw new Error(
+ `Campaign executable is unavailable on a trusted PATH: ${candidate}`,
+ );
+ // Windows launchers inherit the same filtered PATH as checkout.
+ if (process.platform === "win32" && candidate !== "git")
+ command.environment = (
+ await inspectTrustedExecutable("git", command.environment, [])
+ ).environment;
+ return command;
+ });
+}
+
+/** Host launchers and the workbench inherit the same Git search path as checkout. */
+export function campaignCommandEnvironment(
+ environment: Record<string, string | undefined>,
+): Promise<Record<string, string | undefined>> | undefined {
+ if (!campaignScope.getStore()) return undefined;
+ return inspectTrustedExecutable("git", environment, []).then(
+ (command) => command.environment,
+ );
+}
+
+function searchPath(
+ environment: Readonly<NodeJS.ProcessEnv>,
+): string | undefined {
+ return (
+ environment["PATH"] ??
+ Object.entries(environment).find(
+ ([name, value]) => value !== undefined && name.toUpperCase() === "PATH",
+ )?.[1]
+ );
+}
+
export async function resolveTrustedExecutable(
candidate: string,
environment: Readonly<Record<string, string | undefined>>,
@@ -42,18 +138,27 @@ export async function inspectTrustedExecutable(
environment: Readonly<Record<string, string | undefined>>,
protectedRoot: string | readonly string[],
): Promise<InspectedExecutable> {
- const roots = await Promise.all(
+ const selectedRoots = await Promise.all(
(typeof protectedRoot === "string" ? [protectedRoot] : protectedRoot).map(
- (root) => realpath(root).catch(() => resolve(root)),
+ canonicalRoot,
),
);
+ const campaign = campaignScope.getStore();
+ const extra = campaign
+ ? selectedRoots.filter(
+ (root) => !campaign.roots.some((base) => isWithin(base, root)),
+ )
+ : selectedRoots;
+ const roots = campaign ? [...campaign.roots, ...extra] : selectedRoots;
const isProtected = (path: string) =>
roots.some((root) => isWithin(root, path));
const path =
- environment["PATH"] ??
- Object.entries(environment).find(
- ([name]) => name.toUpperCase() === "PATH",
- )?.[1];
+ searchPath(environment) ??
+ (campaign
+ ? process.platform === "win32"
+ ? searchPath(process.env)
+ : "/usr/bin:/bin"
+ : undefined);
const entries: string[] = [];
for (let entry of path?.split(delimiter) ?? []) {
if (
@@ -66,51 +171,78 @@ export async function inspectTrustedExecutable(
if (entry.length === 0) continue;
const canonical = await realpath(entry).catch(() => null);
if (canonical === null || isProtected(canonical)) continue;
- if (!entries.includes(canonical)) entries.push(canonical);
+ // A directory containing the separator can be on PATH through a safe alias.
+ // Keep that absolute spelling so joining the entries cannot split its name.
+ const directory = canonical.includes(delimiter)
+ ? isAbsolute(entry)
+ ? entry
+ : `${process.cwd()}${sep}${entry}`
+ : canonical;
+ if (
+ !directory.includes(delimiter) &&
+ !isProtected(directory) &&
+ !entries.includes(directory)
+ )
+ entries.push(directory);
+ }
+
+ let view: ToolPathView | undefined;
+ if (campaign) {
+ // Workers inherit this PATH across process boundaries. Keep the links until
+ // every row, including its pending child processes, has settled.
+ const path = entries.join(delimiter);
+ const cwd = process.cwd();
+ const key = JSON.stringify([cwd, extra, path]);
+ view = campaign.views.get(key);
+ if (!view) {
+ view = campaign.project(path || "/dev/null", cwd, roots, "campaign");
+ campaign.views.set(key, view);
+ }
}
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 }]
- : 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 candidates = pathLike
- ? extensions.map((extension) => ({
- entry: null,
- path:
- process.platform === "win32"
- ? resolve(`${candidate}${extension.suffix}`)
- : candidate,
- runnable: extension.runnable,
- }))
- : entries.flatMap((entry) =>
- extensions.map((extension) => ({
- entry,
- path: join(entry, `${candidate}${extension.suffix}`),
- runnable: extension.runnable,
- })),
- );
+ const windows = process.platform === "win32";
+ const suffixes =
+ !windows || /\.(?:exe|com)$/iu.test(candidate)
+ ? [""]
+ : pathLike
+ ? [extname(candidate) === "" ? ".exe" : ""]
+ : [".exe", ".com", ".bat", ".cmd", ""];
+ const primary = suffixes.map((suffix) => candidate + suffix);
+ // The Windows MCP launcher and inventory look up Node and ripgrep on this PATH.
+ const names =
+ campaign && windows && candidate === "git"
+ ? [...primary, "node.exe", "rg.exe", "rg.com"]
+ : primary;
+ const candidates = (pathLike ? [null] : entries).flatMap((entry) => {
+ // PATH lookup traverses links before "..". join() would collapse it first.
+ const directory = entry ?? "";
+ const prefix =
+ directory && !directory.endsWith(sep) ? directory + sep : directory;
+ return names.map((name) => ({
+ entry,
+ path: entry === null && windows ? resolve(name) : prefix + name,
+ runnable:
+ primary.includes(name) && (!windows || /\.(?:exe|com)$/iu.test(name)),
+ }));
+ });
const unsafeEntries = new Set<string>();
let executable: string | null = null;
for (const current of candidates) {
+ const crossesSource = view !== undefined && !view.allows(current.path);
+ if (!pathLike && crossesSource) {
+ if (current.entry !== null) unsafeEntries.add(current.entry);
+ continue;
+ }
const canonical = await realpath(current.path).catch(() => null);
if (canonical === null) continue;
- if (isProtected(canonical)) {
+ if (
+ isProtected(canonical) ||
+ (pathLike && view && crossesSource && !view.allows(canonical))
+ ) {
if (current.entry !== null) unsafeEntries.add(current.entry);
continue;
}
@@ -130,7 +262,10 @@ export async function inspectTrustedExecutable(
? join(await realpath(dirname(current.path)), basename(current.path))
: current.path;
executable ??=
- pathLike && (isProtected(current.path) || isProtected(invocationPath))
+ pathLike &&
+ (crossesSource ||
+ isProtected(current.path) ||
+ isProtected(invocationPath))
? canonical
: invocationPath;
} catch {
@@ -142,9 +277,14 @@ export async function inspectTrustedExecutable(
for (const name of Object.keys(sanitizedEnvironment)) {
if (name.toUpperCase() === "PATH") delete sanitizedEnvironment[name];
}
- sanitizedEnvironment["PATH"] = entries
- .filter((entry) => !unsafeEntries.has(entry))
- .join(delimiter);
+ const filteredPath =
+ (windows ? undefined : view?.path) ??
+ entries.filter((entry) => !unsafeEntries.has(entry)).join(delimiter);
+ // An empty POSIX PATH searches the current directory.
+ sanitizedEnvironment["PATH"] =
+ campaign && process.platform !== "win32" && !filteredPath
+ ? "/dev/null"
+ : filteredPath;
return { executable, environment: sanitizedEnvironment };
}
diff --git a/sdk/typescript/tests-ts/api-deep-scan-runtime-routing.test.ts b/sdk/typescript/tests-ts/api-deep-scan-runtime-routing.test.ts
index c19eee38b..28f9b2858 100644
--- a/sdk/typescript/tests-ts/api-deep-scan-runtime-routing.test.ts
+++ b/sdk/typescript/tests-ts/api-deep-scan-runtime-routing.test.ts
@@ -10,6 +10,7 @@ import {
type DirectDeepScanOptions,
} from "../src/deep-scan.js";
import { resolveCodexCommand } from "../src/runtime.js";
+import { withProtectedExecutableRoots } from "../src/trusted-executable.js";
import { PLUGIN_ROOT } from "./plugin-root.js";
import { TestClient } from "./support/api-client.js";
import {
@@ -456,6 +457,49 @@ test.each([
}
});
+test.skipIf(process.platform === "win32")(
+ "the native app-server filters packaged tool aliases added during a campaign",
+ async () => {
+ const home = await temporaryDirectory();
+ const source = join(home, "source");
+ const bin = join(home, "vendor", "bin");
+ const tools = join(home, "vendor", "codex-path");
+ await Promise.all(
+ [source, bin, tools].map((path) => mkdir(path, { recursive: true })),
+ );
+ const marker = join(home, "source-shell-ran");
+ await writeFile(
+ join(source, "sh"),
+ '#!/bin/sh\n: > "$SHELL_MARKER"\nexec /bin/sh "$@"\n',
+ { mode: 0o700 },
+ );
+ await symlink(join(source, "sh"), join(tools, "sh"));
+ const command = join(bin, "codex");
+ await writeFile(
+ command,
+ '#!/usr/bin/env sh\ncase "$*" in *--help*) printf " --cd <PATH>\\n" ;; *) exit 43 ;; esac\n',
+ { mode: 0o700 },
+ );
+ await withProtectedExecutableRoots([source], async () => {
+ await expect(
+ readDeepScanParentConfig({
+ codexOptions: {
+ env: {
+ PATH: "/usr/bin:/bin",
+ CODEX_HOME: home,
+ SHELL_MARKER: marker,
+ },
+ },
+ preflightCommand: { command },
+ scanDir: home,
+ signal: new AbortController().signal,
+ }),
+ ).rejects.toThrow(/configuration read completed with code 43/u);
+ });
+ await expect(readFile(marker)).rejects.toMatchObject({ code: "ENOENT" });
+ },
+);
+
// These stock routing tests disable plugins so a background marketplace fetch
// cannot hold the temporary Codex home open after the app-server exits.
test("stock Codex resolves ordered profile overrides and inherited transport policy in the scan", async () => {
diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.ts
index 273ccb12d..892090b51 100644
--- a/sdk/typescript/tests-ts/api.test.ts
+++ b/sdk/typescript/tests-ts/api.test.ts
@@ -86,6 +86,7 @@ import {
matchScanFindingsInternal,
} from "../src/scan-comparison.js";
import { normalizeTarget } from "../src/targets.js";
+import { withProtectedExecutableRoots } from "../src/trusted-executable.js";
import {
copyCompletedScan,
copyCredentialTestPlugin,
@@ -1267,6 +1268,7 @@ describe("CodexSecurity orchestration", () => {
const environment = {
OPENAI_API_KEY: "synthetic-openai-key",
[competingApiKey]: "synthetic-competing-provider-key",
+ CODEX_SECURITY_STATE_DIR: join(root, "state"),
[apiKey]: `synthetic-${provider}-key`,
};
const client = new TestClient(
@@ -18417,6 +18419,61 @@ if __name__ == "__main__":
}
});
+ test.skipIf(process.platform === "win32")(
+ "rejects campaign Codex launches through a selected source interpreter",
+ async () => {
+ const { root, repository, codexHome, scanDir } = await scanDirectories();
+ const interpreter = join(root, "interpreter");
+ await symlink("/bin/sh", join(repository, "shell"));
+ await symlink(join(repository, "shell"), interpreter);
+ const executable = join(root, "codex");
+ const marker = join(root, "launched");
+ await writeFile(
+ executable,
+ `#!${interpreter}\nprintf ran > "${marker}"\n`,
+ { mode: 0o700 },
+ );
+ const tools = join(root, "tools");
+ await mkdir(tools);
+ await symlink(Bun.which("git")!, join(tools, "git"));
+ const environment = {
+ OPENAI_API_KEY: "ambient-key",
+ CODEX_CLI_PATH: executable,
+ PATH: tools,
+ };
+ const createCodex = mock(completedCodex(root));
+ const client = TestClient.withDependencies({
+ ...scanRuntimeDependencies(codexHome, scanDir),
+ environment,
+ prepareRuntime: runtimePreparer(codexHome, () => ({
+ environment: { ...environment, CODEX_HOME: codexHome },
+ })),
+ createCodex,
+ });
+ try {
+ await withProtectedExecutableRoots([repository], async () => {
+ const refused = `trusted PATH: ${executable}`;
+ const timeout = spyOn(AbortSignal, "timeout");
+ try {
+ await expect(
+ runtime.probeCodexSandbox({ command: executable }, environment),
+ ).rejects.toThrow(refused);
+ expect(timeout).not.toHaveBeenCalled();
+ } finally {
+ timeout.mockRestore();
+ }
+ await expect(client.run(repository)).rejects.toThrow(refused);
+ });
+ expect(existsSync(marker)).toBe(false);
+ expect(createCodex).not.toHaveBeenCalled();
+ await runtime.probeCodexSandbox({ command: executable }, environment);
+ expect(existsSync(marker)).toBe(true);
+ } finally {
+ await client.close();
+ }
+ },
+ );
+
test.each(["native", "shim"])(
"uses one spawnable Codex executable for scans and nested workers (%s)",
async (kind) => {
@@ -18484,6 +18541,7 @@ if __name__ == "__main__":
"missing tools",
"non-directory tools",
"blank override",
+ "bulk campaign",
])("preserves default SDK bundled tools for %s", async (scenario) => {
const { root, repository, codexHome, scanDir } = await scanDirectories();
const executable = join(
@@ -18495,7 +18553,7 @@ if __name__ == "__main__":
);
const toolsDirectory = join(dirname(dirname(executable)), "codex-path");
const otherTools = join(root, "other tools");
- const pathEnvironment: Record<string, string> =
+ let pathEnvironment: Record<string, string> =
scenario === "no PATH"
? {}
: scenario === "mixed-case alias"
@@ -18514,7 +18572,10 @@ if __name__ == "__main__":
mkdir(otherTools),
mkdir(dirname(executable), { recursive: true }),
]);
- await writeFile(executable, "synthetic executable; never launched\n");
+ if (scenario === "bulk campaign") pathEnvironment = { PATH: otherTools };
+ await writeFile(executable, "synthetic executable; never launched\n", {
+ mode: 0o700,
+ });
const hasTools =
scenario !== "missing tools" && scenario !== "non-directory tools";
if (hasTools) await mkdir(toolsDirectory);
@@ -18540,12 +18601,20 @@ if __name__ == "__main__":
createCodex,
});
try {
- await client.run(repository);
+ if (scenario === "bulk campaign") {
+ await withProtectedExecutableRoots([repository], () =>
+ client.run(repository),
+ );
+ } else {
+ await client.run(repository);
+ }
const options = createCodex.mock.lastCall?.[0] ?? null;
expect(options?.codexPathOverride).toBe(
process.platform === "win32"
? win32.toNamespacedPath(executable)
- : undefined,
+ : scenario === "bulk campaign"
+ ? executable
+ : undefined,
);
expect(options?.env?.["CODEX_CLI_PATH"]).toBe(executable);
const pathValues = Object.fromEntries(
diff --git a/sdk/typescript/tests-ts/artifact-export.test.ts b/sdk/typescript/tests-ts/artifact-export.test.ts
index 69682f555..51c85aa6c 100644
--- a/sdk/typescript/tests-ts/artifact-export.test.ts
+++ b/sdk/typescript/tests-ts/artifact-export.test.ts
@@ -27,6 +27,7 @@ import {
writeThreatModel,
} from "../src/artifact-export.js";
import { PLUGIN_ROOT } from "./plugin-root.js";
+import { withProtectedExecutableRoots } from "../src/trusted-executable.js";
import { PYTHON } from "./support/security-policy.js";
const caseProbe = await mkdtemp(join(tmpdir(), "codex-security-case-probe-"));
@@ -203,6 +204,41 @@ describe("offline artifact export", () => {
},
);
+ test.skipIf(process.platform === "win32")(
+ "uses the campaign PATH when launching the artifact helper through a Python wrapper",
+ async () => {
+ const root = await mkdtemp(join(tmpdir(), "codex-security-export-"));
+ const source = join(root, "source");
+ const tools = join(root, "tools");
+ const python = join(tools, "python-wrapper");
+ const previous = process.env["PATH"];
+ try {
+ await mkdir(source);
+ await mkdir(tools);
+ await symlink(PYTHON, join(tools, "artifact-python"));
+ await writeFile(python, '#!/bin/sh\nexec artifact-python "$@"\n', {
+ mode: 0o700,
+ });
+ await writeFile(
+ join(source, "artifact-python"),
+ "#!/bin/sh\nexit 72\n",
+ {
+ mode: 0o700,
+ },
+ );
+ process.env["PATH"] = [source, tools, previous].join(delimiter);
+ const result = await withProtectedExecutableRoots([source], () =>
+ runArtifactHelper(["--help"], { pythonPath: python }),
+ );
+ expect(result.stdout).toContain("--describe-threat-model");
+ } finally {
+ if (previous === undefined) delete process.env["PATH"];
+ else process.env["PATH"] = previous;
+ await rm(root, { recursive: true, force: true });
+ }
+ },
+ );
+
test("exports with Python from the selected managed-runtime cache", async () => {
const root = await mkdtemp(join(tmpdir(), "codex-security-export-cache-"));
const environment = {
diff --git a/sdk/typescript/tests-ts/hosted-scan.test.ts b/sdk/typescript/tests-ts/hosted-scan.test.ts
index 5900b6f99..c9126c0ad 100644
--- a/sdk/typescript/tests-ts/hosted-scan.test.ts
+++ b/sdk/typescript/tests-ts/hosted-scan.test.ts
@@ -38,7 +38,11 @@ import {
import { main } from "../src/cli.js";
import { capture, dependencies } from "./cli-fixtures.js";
import { normalizeTarget } from "../src/targets.js";
-import { runWorkbench } from "../src/runtime.js";
+import {
+ runWorkbench,
+ SDK_NODE_SEARCH_PATH,
+ sdkNodeSearchPath,
+} from "../src/runtime.js";
import { readSavedScanLifecycle } from "../src/saved-scan-bootstrap.js";
import { useTestPython } from "./support/python.js";
import { git } from "./git-fixture.js";
@@ -509,6 +513,11 @@ test("hosted execution preserves inspected runtime tool paths", async () => {
for (const directory of executableAliases)
expect(paths).not.toContain(directory);
expect(paths).toContain(trustedTools);
+ expect(environment[SDK_NODE_SEARCH_PATH]).toBe(
+ process.platform === "win32"
+ ? undefined
+ : await sdkNodeSearchPath([input.repository]),
+ );
expect(isAbsolute(environment["CODEX_SECURITY_GIT"] ?? "")).toBe(true);
expect(isAbsolute(environment["PYTHON"] ?? "")).toBe(true);
} finally {
diff --git a/sdk/typescript/tests-ts/inventory-input.test.ts b/sdk/typescript/tests-ts/inventory-input.test.ts
index 0c811d0b0..80484a55d 100644
--- a/sdk/typescript/tests-ts/inventory-input.test.ts
+++ b/sdk/typescript/tests-ts/inventory-input.test.ts
@@ -29,9 +29,9 @@ const pathNameBytes =
process.platform === "darwin" ? Buffer.from("雪") : Buffer.from([0xff]);
afterEach(temporary.cleanup);
-function fixture() {
+function fixture(name = "repository") {
const root = temporary.create("codex-security-inventory-"),
- repo = join(root, "repository"),
+ repo = join(root, name),
out = join(root, "output");
mkdirSync(repo);
git(repo, "init", "-q");
@@ -242,7 +242,7 @@ require("node:module").syncBuiltinESMExports();
for (const command of ["generate-in-scope-files", "make-repo-scope-input"]) {
for (const rawWindowsHome of [false, true]) {
- test.skipIf(process.platform !== "win32")(
+ test.skipIf(rawWindowsHome && process.platform !== "win32")(
`${command} uses the selected project-local Codex ripgrep${rawWindowsHome ? " through the UTF-16 bridge" : ""}`,
() => {
const f = fixture();
@@ -260,17 +260,18 @@ for (const command of ["generate-in-scope-files", "make-repo-scope-input"]) {
f.repo,
"node_modules",
"@openai",
- `codex-win32-${process.arch}`,
+ `codex-${process.platform}-${process.arch}`,
"vendor",
"synthetic-target",
);
- const codex = join(runtime, "bin", "codex.exe");
+ const suffix = process.platform === "win32" ? ".exe" : "";
+ const codex = join(runtime, "bin", `codex${suffix}`);
const tools = join(runtime, "codex-path");
mkdirSync(dirname(codex), { recursive: true });
mkdirSync(tools);
copyFileSync(node, codex);
- copyFileSync(ripgrep!, join(tools, "rg.exe"));
- copyFileSync(node, join(f.repo, "rg.exe"));
+ copyFileSync(ripgrep!, join(tools, `rg${suffix}`));
+ copyFileSync(node, join(f.repo, `rg${suffix}`));
env[pathKey] = [f.repo, tools].join(delimiter);
env["CODEX_CLI_PATH"] = codex;
env["CODEX_SECURITY_GIT"] = "";
@@ -437,6 +438,28 @@ for (const command of ["generate-in-scope-files", "make-repo-scope-input"]) {
}
}
+test.skipIf(process.platform === "win32")(
+ "a separately selected Codex launcher does not supply ripgrep from the scan target",
+ () => {
+ const f = fixture("codex-path");
+ const launcher = join(f.root, "bin", "codex");
+ mkdirSync(dirname(launcher));
+ writeFileSync(launcher, "fixture", { mode: 0o700 });
+ writeFileSync(
+ join(f.repo, "rg"),
+ "#!/bin/sh\nprintf called > rg-ran\nexit 73\n",
+ { mode: 0o700 },
+ );
+ const result = f.run("generate-in-scope-files", ["--scope", "."], {
+ ...f.toolEnvironment,
+ PATH: [f.repo, f.toolEnvironment["PATH"]].join(delimiter),
+ CODEX_CLI_PATH: launcher,
+ });
+ expect(readdirSync(f.repo)).not.toContain("rg-ran");
+ expect(result.status, result.stderr).toBe(0);
+ },
+);
+
function runPathInventory(
f: ReturnType<typeof fixture>,
command: string,
@@ -470,7 +493,292 @@ function runPathInventory(
);
}
+test.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
+ "inventory reports access denied for an unsearchable ripgrep PATH directory",
+ () => {
+ const f = fixture();
+ const blocked = join(f.root, "blocked");
+ mkdirSync(blocked, { mode: 0o600 });
+ try {
+ f.write("scope/visible.py");
+ const result = runPathInventory(f, "generate-in-scope-files", {
+ ...f.toolEnvironment,
+ PATH: blocked,
+ CODEX_SECURITY_GIT: "",
+ });
+ expect(result.status).toBe(2);
+ expect(result.stderr).toContain("EACCES");
+ } finally {
+ chmodSync(blocked, 0o700);
+ }
+ },
+);
+
+test.skipIf(process.platform === "win32")(
+ "inventory selects a trusted shell for an executable text wrapper in a search-only directory",
+ () => {
+ const f = fixture();
+ f.write("scope/visible.py");
+ const checkoutShell = f.write(
+ "sh",
+ "#!/bin/sh\nprintf called > shim-ran\nexit 73\n",
+ );
+ chmodSync(checkoutShell, 0o700);
+ const directory = join(f.root, "search-only");
+ mkdirSync(directory);
+ symlinkSync(checkoutShell, join(directory, "sh"));
+ writeFileSync(
+ join(directory, "rg"),
+ `exec sh -c 'printf used > wrapper-ran; exec "$@"' sh "$INVENTORY_SEARCH" "$@"\n`,
+ { mode: 0o700 },
+ );
+ chmodSync(directory, 0o111);
+ try {
+ const result = runPathInventory(f, "generate-in-scope-files", {
+ ...f.toolEnvironment,
+ PATH: [directory, f.toolEnvironment["PATH"]].join(delimiter),
+ INVENTORY_SEARCH: Bun.which("rg", { PATH: f.toolEnvironment["PATH"] })!,
+ CODEX_SECURITY_GIT: "",
+ });
+ expect(readdirSync(f.repo)).not.toContain("shim-ran");
+ expect(readdirSync(f.repo)).toContain("wrapper-ran");
+ expect(result.status, result.stderr).toBe(0);
+ expect(readFileSync(f.out, "utf8")).toContain("scope/visible.py");
+ } finally {
+ chmodSync(directory, 0o700);
+ }
+ },
+);
+
+test.skipIf(process.platform === "win32")(
+ "inventory preserves a PATH helper's relative resource lookup in a directory with a checkout shim",
+ () => {
+ const f = fixture();
+ f.write("scope/visible.py");
+ const bin = join(f.root, "bin");
+ const lib = join(f.root, "lib");
+ mkdirSync(bin);
+ mkdirSync(lib);
+ const shim = f.write(
+ "shim",
+ "#!/bin/sh\nprintf used > shim-ran\nexit 73\n",
+ );
+ chmodSync(shim, 0o700);
+ symlinkSync(shim, join(bin, "checkout-shim"));
+ writeFileSync(
+ join(bin, "rg"),
+ '#!/bin/sh\nif command -v checkout-shim >/dev/null; then exec checkout-shim; fi\nexec inventory-helper "$@"\n',
+ { mode: 0o700 },
+ );
+ writeFileSync(
+ join(bin, "inventory-helper"),
+ '#!/bin/sh\ntest "$tool" = caller-value || exit 74\n. "${0%/*}/../lib/helper.sh"\n',
+ { mode: 0o700 },
+ );
+ writeFileSync(
+ join(lib, "helper.sh"),
+ 'printf used > helper-ran\nexec "$INVENTORY_SEARCH" "$@"\n',
+ );
+ const result = runPathInventory(f, "generate-in-scope-files", {
+ ...f.toolEnvironment,
+ PATH: bin,
+ tool: "caller-value",
+ TMPDIR: process.platform === "linux" ? "/dev/shm" : f.root,
+ INVENTORY_SEARCH: Bun.which("rg", { PATH: f.toolEnvironment["PATH"] })!,
+ CODEX_SECURITY_GIT: "",
+ });
+ expect(result.status, result.stderr).toBe(0);
+ expect(readFileSync(f.out, "utf8")).toBe("scope/visible.py\n");
+ expect(readdirSync(f.repo)).toContain("helper-ran");
+ expect(readdirSync(f.repo)).not.toContain("shim-ran");
+ },
+);
+
for (const command of ["generate-in-scope-files", "make-repo-scope-input"]) {
+ test.skipIf(process.platform === "win32")(
+ `${command} follows a PATH directory link before checking its parent for ripgrep`,
+ () => {
+ const f = fixture();
+ f.write("scope/visible.py");
+ const tools = join(f.root, "tools");
+ const unused = join(tools, "unused");
+ const external = join(tools, "repository");
+ mkdirSync(unused, { recursive: true });
+ mkdirSync(external);
+ const prefix = join(f.root, "prefix");
+ symlinkSync(unused, prefix, "dir");
+ writeFileSync(
+ join(external, "rg"),
+ '#!/bin/sh\nprintf used > wrapper-ran\nexec "$INVENTORY_SEARCH" "$@"\n',
+ { mode: 0o700 },
+ );
+ const result = runPathInventory(f, command, {
+ ...f.toolEnvironment,
+ PATH: `${prefix}/../repository`,
+ INVENTORY_SEARCH: Bun.which("rg", { PATH: f.toolEnvironment["PATH"] })!,
+ CODEX_SECURITY_GIT: "",
+ });
+ expect(result.status, result.stderr).toBe(0);
+ expect(readdirSync(f.repo)).toContain("wrapper-ran");
+ expect(readFileSync(f.out, "utf8")).toContain("scope/visible.py");
+ },
+ );
+ test.skipIf(process.platform === "win32")(
+ `${command} selects both ripgrep and its wrapper interpreter outside the checkout`,
+ () => {
+ const f = fixture();
+ f.write("scope/visible.py");
+ for (const name of ["rg", "sh"]) {
+ const shim = f.write(
+ name,
+ "#!/bin/sh\nprintf called > shim-ran\nexit 73\n",
+ );
+ chmodSync(shim, 0o700);
+ }
+ const tools = join(f.root, "operator:tools");
+ const alias = join(f.root, "tools");
+ mkdirSync(tools);
+ symlinkSync(tools, alias, "dir");
+ const interpreters = join(f.root, "interpreters");
+ mkdirSync(interpreters);
+ symlinkSync(join(f.repo, "sh"), join(interpreters, "sh"));
+ symlinkSync(join(f.repo, "sh"), join(interpreters, "final-sh"));
+ const checkoutRuntime = join(f.repo, "runtime");
+ copyFileSync(process.execPath, checkoutRuntime);
+ const loader = join(interpreters, "loader");
+ symlinkSync(checkoutRuntime, loader);
+ const scripts = join(f.root, "scripts");
+ mkdirSync(scripts);
+ writeFileSync(
+ join(scripts, "sh"),
+ `#!${loader}\nawait Bun.write("shim-ran", "used"); process.exit(73);\n`,
+ { mode: 0o700 },
+ );
+ const missing = join(f.root, "incomplete");
+ mkdirSync(missing);
+ symlinkSync(join(f.repo, "missing"), join(missing, "stale-helper"));
+ writeFileSync(join(missing, "sh"), "#!/missing-interpreter\n", {
+ mode: 0o700,
+ });
+ const shell = join(f.root, "operator's shell");
+ mkdirSync(shell);
+ const envAlias = join(f.root, "launch-env");
+ symlinkSync("/usr/bin/env", envAlias);
+ symlinkSync("/bin/sh", join(shell, "final-sh"));
+ writeFileSync(
+ join(shell, "sh"),
+ `#!${envAlias} final-sh\nexec /bin/sh "$@"\n`,
+ { mode: 0o700 },
+ );
+ const rg = Bun.which("rg", { PATH: f.toolEnvironment["PATH"] });
+ expect(rg).not.toBeNull();
+ // Keep this helper available even though its neighbor points into the checkout.
+ symlinkSync(rg!, join(interpreters, "inventory-search"));
+ // Neither of these aliases can supply this wrapper's interpreter.
+ symlinkSync(join(f.repo, "sh"), join(tools, "unrelated"));
+ symlinkSync(f.write("guide.md", "Ordinary document."), join(tools, "sh"));
+ const split =
+ command === "make-repo-scope-input" &&
+ spawnSync("/usr/bin/env", ["-S", "sh -c 'exit 0'"]).status === 0;
+ writeFileSync(
+ join(tools, "rg"),
+ `#!${split ? envAlias : "/usr/bin/env"} ${split ? "-S 'sh' -e" : "sh"}\nprintf used > wrapper-ran\nexec inventory-search "$@"\n`,
+ { mode: 0o700 },
+ );
+ const result = runPathInventory(f, command, {
+ ...f.toolEnvironment,
+ TMPDIR: f.root,
+ PATH: [
+ "",
+ ".",
+ missing,
+ scripts,
+ interpreters,
+ shell,
+ alias,
+ f.toolEnvironment["PATH"],
+ ].join(delimiter),
+ CODEX_SECURITY_GIT: "",
+ });
+ expect(
+ readdirSync(f.root).filter((entry) =>
+ entry.startsWith("codex-security-tools-"),
+ ),
+ ).toEqual([]);
+ expect(readdirSync(f.repo)).not.toContain("shim-ran");
+ expect(readdirSync(f.repo)).toContain("wrapper-ran");
+ expect(result.status, result.stderr).toBe(0);
+ expect(readFileSync(f.out, "utf8")).toContain("scope/visible.py");
+ },
+ );
+ test.skipIf(process.platform === "win32")(
+ `${command} preserves a failed tool lookup outside the checkout`,
+ () => {
+ const f = fixture();
+ f.write("scope/visible.py");
+ f.write(".ignore", "ignored.py\n");
+ const cycle = join(f.root, "cycle");
+ symlinkSync(cycle, cycle);
+ const result = runPathInventory(f, command, {
+ ...f.toolEnvironment,
+ PATH: [cycle, f.toolEnvironment["PATH"]].join(delimiter),
+ CODEX_SECURITY_GIT: "",
+ });
+ expect(result.status).not.toBe(0);
+ },
+ );
+ for (const nested of [false, true]) {
+ // Linux can execute a script as another script's shebang interpreter.
+ test.skipIf(
+ process.platform === "win32" || (nested && process.platform !== "linux"),
+ )(
+ `${command} checks ${nested ? "nested " : ""}absolute ripgrep interpreters before launch`,
+ () => {
+ const f = fixture();
+ f.write("scope/visible.py");
+ const checkoutRuntime = join(f.repo, "runtime");
+ copyFileSync(process.execPath, checkoutRuntime);
+ const directories = ["first", "fallback"].map((name) => {
+ const directory = join(f.root, name);
+ mkdirSync(directory);
+ const shell = join(directory, "sh");
+ symlinkSync(name === "first" ? checkoutRuntime : "/bin/sh", shell);
+ const recordUnsafeLaunch =
+ 'await Bun.write("first-ran", "used"); process.exit(73);';
+ const interpreter = nested ? join(directory, "interpreter") : shell;
+ if (nested) {
+ const dispatch =
+ name === "first" ? recordUnsafeLaunch : 'exec /bin/sh "$@"';
+ writeFileSync(interpreter, `#!${shell}\n${dispatch}\n`, {
+ mode: 0o700,
+ });
+ }
+ const script =
+ name === "first"
+ ? recordUnsafeLaunch
+ : 'printf used > fallback-ran\nexec "$INVENTORY_SEARCH" "$@"';
+ writeFileSync(
+ join(directory, "rg"),
+ `#!${interpreter}\n${script}\n`,
+ { mode: 0o700 },
+ );
+ return directory;
+ });
+ const result = runPathInventory(f, command, {
+ ...f.toolEnvironment,
+ PATH: directories.join(delimiter),
+ INVENTORY_SEARCH: Bun.which("rg", {
+ PATH: f.toolEnvironment["PATH"],
+ })!,
+ CODEX_SECURITY_GIT: "",
+ });
+ expect(readdirSync(f.repo)).not.toContain("first-ran");
+ expect(readdirSync(f.repo)).toContain("fallback-ran");
+ expect(result.status, result.stderr).toBe(0);
+ expect(readFileSync(f.out, "utf8")).toContain("scope/visible.py");
+ },
+ );
+ }
test.skipIf(process.platform === "win32")(
`${command} continues PATH lookup after a missing ripgrep interpreter`,
() => {
@@ -484,9 +792,18 @@ for (const command of ["generate-in-scope-files", "make-repo-scope-input"]) {
`#!${join(f.root, "missing-interpreter")}\n`,
{ mode: 0o700 },
);
+ const shim = f.write("helper", "#!/bin/sh\nexit 73\n");
+ chmodSync(shim, 0o700);
+ symlinkSync(shim, join(first, "helper"));
+ env["TMPDIR"] = f.root;
env["PATH"] = `${first}${delimiter}${env["PATH"] ?? ""}`;
env["CODEX_SECURITY_GIT"] = "";
const result = runPathInventory(f, command, env);
+ expect(
+ readdirSync(f.root).filter((entry) =>
+ entry.startsWith("codex-security-tools-"),
+ ),
+ ).toEqual([]);
expect(result.status, result.stderr).toBe(0);
const output = readFileSync(f.out, "utf8");
expect(
diff --git a/sdk/typescript/tests-ts/multiscan-checkout.test.ts b/sdk/typescript/tests-ts/multiscan-checkout.test.ts
index 7cda5af79..411ebdabb 100644
--- a/sdk/typescript/tests-ts/multiscan-checkout.test.ts
+++ b/sdk/typescript/tests-ts/multiscan-checkout.test.ts
@@ -1,6 +1,5 @@
-import { gitText } from "./support/shell.js";
+import { gitText, nodeCommand } from "./support/shell.js";
import { parseJsonLines } from "./support/json.js";
-import { execFileSync } from "node:child_process";
import {
access,
appendFile,
@@ -18,12 +17,14 @@ import {
} from "node:fs/promises";
import * as filesystem from "node:fs/promises";
import { hostname } from "node:os";
-import { dirname, join } from "node:path";
+import { delimiter, dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { afterEach, describe, expect, spyOn, test, mock } from "bun:test";
import { buildGitHubCredentialArgs, runMultiscan } from "../src/multiscan.js";
import { resolveTrustedExecutable } from "../src/trusted-executable.js";
-import { normalizeTarget } from "../src/targets.js";
+import { gitOutput, normalizeTarget } from "../src/targets.js";
+import { probeCodexSandbox, runCodexCommand } from "../src/runtime.js";
+import { PLUGIN_ROOT } from "./plugin-root.js";
import { runTestInSubprocess } from "./support/test-subprocess.js";
import { rejecting } from "./support/errors.js";
import {
@@ -148,6 +149,30 @@ describe("multiscan", () => {
expect(summary).toMatchObject({ total: 1, completed: 1, failed: 0 });
});
+ testPosix(
+ "continues the campaign when local Git sources cannot be resolved",
+ async () => {
+ const { paths, source } = await repositoryFixture("valid");
+ const cycle = join(paths.root, "cycle");
+ await symlink(cycle, cycle);
+ const invalid = [
+ cycle,
+ join(paths.root, "missing"),
+ join(source.path, "src", "app.ts", "child"),
+ ];
+ await appendFile(
+ paths.input,
+ invalid
+ .map((path, i) => `invalid-${i},${path},${source.revision}\n`)
+ .join(""),
+ );
+ const summary = await runMultiscan(
+ options(paths, client(completeRun), { maxAttempts: 1 }),
+ );
+ expect(summary).toMatchObject({ completed: 1, failed: invalid.length });
+ },
+ );
+
test("materializes the pinned commit, applies row options, and removes its checkout", async () => {
const paths = await fixture();
const source = await repository(paths.root, "payments");
@@ -1095,6 +1120,72 @@ describe("multiscan", () => {
},
);
+ testPosix(
+ "bootstrap launchers and inventory helpers use the campaign's selected tool path",
+ async () => {
+ const { paths, source } = await repositoryFixture("source");
+ const install = join(paths.root, "tool:installation");
+ const tools = join(paths.root, "tools");
+ await mkdir(install);
+ await symlink(install, tools, "dir");
+ await symlink(nodeCommand().command, join(tools, "node"));
+ const launcher = join(tools, "codex");
+ await writeFile(launcher, "#!/usr/bin/env node\nprocess.exit(0);\n", {
+ mode: 0o700,
+ });
+ const aliases = [];
+ for (const name of ["node", "rg"]) {
+ const alias = join(paths.root, `${name}-aliases`);
+ await mkdir(alias);
+ await writeFile(join(source.path, name), "#!/bin/sh\nexit 73\n", {
+ mode: 0o700,
+ });
+ await symlink(join(source.path, name), join(alias, name));
+ aliases.push(alias);
+ }
+ await writeFile(
+ join(tools, "rg"),
+ "#!/bin/sh\nprintf './src/app.ts\\0'\n",
+ {
+ mode: 0o700,
+ },
+ );
+ const environment = {
+ PATH: [source.path, ...aliases, tools].join(delimiter),
+ };
+ const inventory = join(paths.root, "inventory.txt");
+ const summary = await runMultiscan(
+ options(
+ paths,
+ client(async (checkout, settings) => {
+ await probeCodexSandbox({ command: launcher }, environment);
+ const result = await runCodexCommand(
+ { command: join(tools, "node") },
+ [
+ join(PLUGIN_ROOT, "mcp", "helpers.mjs"),
+ "generate-in-scope-files",
+ "--repo",
+ checkout,
+ "--scope",
+ ".",
+ "--out",
+ inventory,
+ ],
+ environment,
+ );
+ expect(result.success, result.stderr).toBe(true);
+ return completeRun(checkout, settings);
+ }),
+ { maxAttempts: 1 },
+ ),
+ );
+ expect((await results(summary.resultsPath))[0]).toMatchObject({
+ status: "completed",
+ });
+ expect(await readFile(inventory, "utf8")).toBe("./src/app.ts\n");
+ },
+ );
+
test("ignores repository-local Git shims while preserving credential configuration", async () => {
if (
runTestInSubprocess(
@@ -1103,15 +1194,55 @@ describe("multiscan", () => {
)
)
return;
- const { paths } = await repositoryFixture("private");
- const shimDirectory = join(paths.root, "node_modules", ".bin");
- const leakedCredential = join(paths.root, "leaked-credential");
- await mkdir(shimDirectory, { recursive: true });
+ const paths = await fixture();
+ const first = await repository(paths.root, "first");
+ const second = await repository(paths.root, "second");
await writeFile(
- join(shimDirectory, "git"),
- `#!/bin/sh\nprintf '%s' "$GIT_CONFIG_VALUE_0" > "${leakedCredential}"\nexit 1\n`,
- { mode: 0o700 },
+ paths.input,
+ `id,repository,revision\nfirst,${first.path},${first.revision}\nsecond,${join(second.path, ".git")},${second.revision}\n`,
+ );
+ const shimDirectories = [first.path, second.path].map((root) =>
+ join(root, "node_modules", ".bin"),
);
+ const shimMarker = join(paths.root, "shim-ran");
+ const interpreterMarker = join(paths.root, "source-interpreter-ran");
+ const gitMarker = join(paths.root, "operator-git-ran");
+ for (const directory of shimDirectories) {
+ await mkdir(directory, { recursive: true });
+ await writeFile(
+ join(directory, process.platform === "win32" ? "git.exe" : "git"),
+ `#!/bin/sh\nprintf called > "${shimMarker}"\nexit 1\n`,
+ { mode: 0o700 },
+ );
+ }
+ if (process.platform !== "win32") {
+ const operatorBin = join(paths.root, "operator-bin");
+ await mkdir(operatorBin);
+ await writeFile(
+ join(second.path, "sh"),
+ `#!/bin/sh\nprintf called > "${shimMarker}"\nexec /bin/sh "$@"\n`,
+ { mode: 0o700 },
+ );
+ await symlink(join(second.path, "sh"), join(operatorBin, "sh"));
+ const wrapperBin = join(paths.root, "wrapper-bin");
+ await mkdir(wrapperBin);
+ const sourceInterpreter = join(second.path, "interpreter");
+ await symlink("/bin/sh", sourceInterpreter);
+ const interpreterAlias = join(operatorBin, "interpreter");
+ await symlink(sourceInterpreter, interpreterAlias);
+ const hostGit = Bun.which("git")!.replaceAll("'", "'\\''");
+ await writeFile(
+ join(wrapperBin, "git"),
+ `#!${interpreterAlias}\nprintf called > "${interpreterMarker}"\nexec '${hostGit}' "$@"\n`,
+ { mode: 0o700 },
+ );
+ await writeFile(
+ join(operatorBin, "git"),
+ `#!/usr/bin/env sh\nprintf called > "${gitMarker}"\nexec '${hostGit}' "$@"\n`,
+ { mode: 0o700 },
+ );
+ shimDirectories.push(wrapperBin, operatorBin);
+ }
const previousDirectory = process.cwd();
const environment = new Map(
[
@@ -1123,9 +1254,10 @@ describe("multiscan", () => {
);
try {
- process.chdir(paths.root);
- process.env["PATH"] =
- `${shimDirectory}${process.platform === "win32" ? ";" : ":"}${environment.get("PATH") ?? ""}`;
+ process.chdir(first.path);
+ process.env["PATH"] = [...shimDirectories, environment.get("PATH")].join(
+ delimiter,
+ );
process.env["GIT_CONFIG_COUNT"] = "1";
process.env["GIT_CONFIG_KEY_0"] = "multiscan.credential";
process.env["GIT_CONFIG_VALUE_0"] = "SYNTHETIC_GIT_CREDENTIAL";
@@ -1134,31 +1266,23 @@ describe("multiscan", () => {
options(
paths,
client(async (checkout, scanOptions = {}) => {
- const trustedGit = await resolveTrustedExecutable(
- "git",
- { ...process.env, PATH: environment.get("PATH") ?? "" },
- paths.root,
- );
- if (trustedGit === null) {
- throw new Error("Git is not available on a trusted PATH.");
- }
- const credential = execFileSync(
- trustedGit.executable,
- ["-C", checkout, "config", "--get", "multiscan.credential"],
- {
- encoding: "utf8",
- env: trustedGit.environment,
- stdio: ["ignore", "pipe", "pipe"],
- },
- ).trim();
+ const credential = await gitOutput(checkout, [
+ "config",
+ "--get",
+ "multiscan.credential",
+ ]);
expect(credential).toBe("SYNTHETIC_GIT_CREDENTIAL");
return await completedScan(scanOptions.outputDir!);
}),
),
);
- expect(summary).toMatchObject({ completed: 1, failed: 0 });
- await expect(access(leakedCredential)).rejects.toThrow();
+ await expect(access(shimMarker)).rejects.toThrow();
+ if (process.platform !== "win32") {
+ await expect(access(interpreterMarker)).rejects.toThrow();
+ await access(gitMarker);
+ }
+ expect(summary).toMatchObject({ completed: 2, failed: 0 });
} finally {
process.chdir(previousDirectory);
for (const [name, value] of environment) {
diff --git a/sdk/typescript/tests-ts/multiscan.test.ts b/sdk/typescript/tests-ts/multiscan.test.ts
index cb354c6f0..2c73ff69c 100644
--- a/sdk/typescript/tests-ts/multiscan.test.ts
+++ b/sdk/typescript/tests-ts/multiscan.test.ts
@@ -11,7 +11,7 @@ import {
writeFile,
} from "node:fs/promises";
import * as filesystem from "node:fs/promises";
-import { dirname, join } from "node:path";
+import { delimiter, dirname, join } from "node:path";
import { afterEach, describe, expect, spyOn, test, mock } from "bun:test";
import { main } from "../src/cli.js";
import { ScanCostLimitExceededError } from "../src/errors.js";
@@ -154,6 +154,56 @@ second,${source.path},${source.revision}
]);
});
+ const linkedPromptGit =
+ "excludes every selected repository from Git lookup for linked bulk prompts";
+ test(linkedPromptGit, async () => {
+ if (runTestInSubprocess(import.meta.path, linkedPromptGit)) return;
+ const { paths, source } = await repositoryFixture("first");
+ const second = await repository(paths.root, "second");
+ await writeFile(
+ paths.input,
+ `id,repository,revision\nfirst,${source.path},${source.revision}\nsecond,${second.path},${second.revision}\n`,
+ );
+ await writeFile(join(paths.root, "prompt.md"), "External prompt.");
+ const docs = join(source.path, "docs");
+ await symlink(paths.root, docs, "junction");
+ const marker = join(paths.root, "untrusted-git-ran");
+ const hostGit = Bun.which("git")!;
+ const shim = join(
+ second.path,
+ process.platform === "win32" ? "git.exe" : "git",
+ );
+ await writeFile(
+ shim,
+ '#!/bin/sh\necho called > "$SHIM_MARKER"\nexec "$HOST_GIT" "$@"\n',
+ { mode: 0o700 },
+ );
+ process.env["SHIM_MARKER"] = marker;
+ process.env["HOST_GIT"] = hostGit;
+ process.env["PATH"] = [second.path, process.env["PATH"]].join(delimiter);
+ await expect(
+ runMultiscan(
+ options(paths, client(completeRun), {
+ scanPromptFile: join(docs, "prompt.md"),
+ }),
+ ),
+ ).rejects.toThrow("repository directory links");
+ expect(await Bun.file(marker).exists()).toBe(false);
+ const internal = join(source.path, "internal");
+ await mkdir(internal);
+ await writeFile(join(internal, "prompt.md"), "Internal prompt.");
+ const alias = join(source.path, "alias");
+ await symlink(internal, alias, "junction");
+ const security = client(async (_checkout, scan = {}) => {
+ expect(scan.scanPrompt).toBe("Internal prompt.");
+ return await completedScan(scan.outputDir!);
+ });
+ const result = await runMultiscan(
+ options(paths, security, { scanPromptFile: join(alias, "prompt.md") }),
+ );
+ expect(result).toMatchObject({ completed: 2, failed: 0 });
+ });
+
test("checks linked bulk documents against the selected Git layout", async () => {
const { paths, source } = await repositoryFixture("source");
const settings = options(paths, client(completeRun), { maxAttempts: 1 });
diff --git a/sdk/typescript/tests-ts/package-tar-listing.test.ts b/sdk/typescript/tests-ts/package-tar-listing.test.ts
index 6bedf900a..39ff8c55b 100644
--- a/sdk/typescript/tests-ts/package-tar-listing.test.ts
+++ b/sdk/typescript/tests-ts/package-tar-listing.test.ts
@@ -42,7 +42,10 @@ const execFileAsync = promisify(execFile);
const pluginContract = {
externalOwnedExact: [".codex-plugin/plugin.json"],
- shippedExact: ["scripts/launch_codex_security_mcp"],
+ shippedExact: [
+ "scripts/dispatch_inventory_tool",
+ "scripts/launch_codex_security_mcp",
+ ],
};
function paxExtension(attributes: Record<string, string>, type = 0x78): Buffer {
@@ -76,6 +79,7 @@ function packageTar({
} = {}): Buffer {
const executablePaths = [
"package/bin/codex-security.mjs",
+ "package/_bundled_plugin/scripts/dispatch_inventory_tool",
"package/_bundled_plugin/scripts/launch_codex_security_mcp",
];
const paths = [
diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.ts
index 08ba802ab..de54ebf32 100644
--- a/sdk/typescript/tests-ts/runtime.test.ts
+++ b/sdk/typescript/tests-ts/runtime.test.ts
@@ -108,6 +108,7 @@ import {
logoutCredentialHome,
setCodexSecurityCredentialLogout,
streamWindowsCredentialAclDescriptors,
+ sdkNodeSearchPath,
windowsCredentialAncestorAclScript,
} from "../src/runtime.js";
import { inspectTrustedExecutable } from "../src/trusted-executable.js";
@@ -1002,6 +1003,8 @@ describe("plugin runtime preparation", () => {
await mkdir(join(selected, "mcp"));
await writeFile(join(home, "config.toml"), "[features]\nplugins=true\n");
const declaredRoot = interpreter.endsWith("with root");
+ const declaresNodeSearchPath = interpreter.startsWith("shell");
+ const nodeSearchPath = join(root, "fallback node");
const argumentsAfterEntry = [
"--stdio",
"synthetic ! % & argument",
@@ -1016,6 +1019,9 @@ describe("plugin runtime preparation", () => {
env_vars: [
"CODEX_HOME",
"CODEX_MCP_NODE_PATH",
+ ...(declaresNodeSearchPath
+ ? ["_CODEX_SECURITY_SDK_NODE_SEARCH_PATH"]
+ : []),
...(declaredRoot ? ["CODEX_SECURITY_PLUGIN_ROOT"] : []),
],
startup_timeout_sec: 20,
@@ -1047,7 +1053,7 @@ for await (const line of createInterface({ input: process.stdin })) {
const result = request.method === "initialize"
? { protocolVersion: request.params.protocolVersion, capabilities: { tools: {} }, serverInfo: { name: "synthetic-launcher", version: "1" } }
: request.method === "tools/list"
- ? { tools: [{ name: "probe", description: "Reports test launcher details.", _meta: { launch: { pluginRoot, repository: process.env.CODEX_SECURITY_REPOSITORY, ambient: process.env.SYNTHETIC_UNDECLARED_VALUE, args: process.argv.slice(2), execArgv: process.execArgv, cwd: process.cwd(), entry: process.argv[1] } }, inputSchema: { type: "object", properties: {} } }] }
+ ? { tools: [{ name: "probe", description: "Reports test launcher details.", _meta: { launch: { pluginRoot, repository: process.env.CODEX_SECURITY_REPOSITORY, ambient: process.env.SYNTHETIC_UNDECLARED_VALUE, args: process.argv.slice(2), execArgv: process.execArgv, cwd: process.cwd(), entry: process.argv[1], nodeSearchPath: process.env._CODEX_SECURITY_SDK_NODE_SEARCH_PATH } }, inputSchema: { type: "object", properties: {} } }] }
: request.method === "resources/list" ? { resources: [] }
: request.method === "resources/templates/list" ? { resourceTemplates: [] }
: {};
@@ -1104,6 +1110,7 @@ for await (const line of createInterface({ input: process.stdin })) {
SystemRoot: process.env["SystemRoot"],
PATHEXT: process.env["PATHEXT"],
CODEX_MCP_NODE_PATH: process.execPath,
+ _CODEX_SECURITY_SDK_NODE_SEARCH_PATH: nodeSearchPath,
};
const command = resolveCodexCommand({});
const installed = await bootstrapPlugin(home, selected, {
@@ -1222,6 +1229,9 @@ for await (const line of createInterface({ input: process.stdin })) {
tools: { probe: { description: expect.any(String) } },
});
const details = server.tools.probe._meta.launch;
+ expect(details.nodeSearchPath).toBe(
+ declaresNodeSearchPath ? nodeSearchPath : undefined,
+ );
expect(details.pluginRoot).toBe(await realpath(pluginRoot));
expect(details.repository).toBe(
join(root, pluginRoot === second ? "second source" : "first source"),
@@ -3197,6 +3207,18 @@ for await (const line of createInterface({ input: process.stdin })) {
},
);
+ test.skipIf(process.platform === "win32")(
+ "filters SDK Node fallback directories against the scan source",
+ async () => {
+ const systemBin = await realpath("/usr/bin");
+ expect((await sdkNodeSearchPath([])).split(":")).toContain(systemBin);
+ expect((await sdkNodeSearchPath([systemBin])).split(":")).not.toContain(
+ systemBin,
+ );
+ expect(await sdkNodeSearchPath(["/"])).toBe("");
+ },
+ );
+
test("replaces unspawnable Windows Codex shims with the bundled executable", () => {
const fallback = resolveCodexCommand({});
diff --git a/sdk/typescript/tests-ts/sandbox-probe.test.ts b/sdk/typescript/tests-ts/sandbox-probe.test.ts
index 578a1cdd8..73437a6fc 100644
--- a/sdk/typescript/tests-ts/sandbox-probe.test.ts
+++ b/sdk/typescript/tests-ts/sandbox-probe.test.ts
@@ -1,8 +1,9 @@
-import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
+import { chmod, mkdir, readFile, symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { afterEach, describe, expect, test, spyOn } from "bun:test";
import { SandboxUnavailableError } from "../src/index.js";
import { probeCodexSandbox } from "../src/runtime.js";
+import { withProtectedExecutableRoots } from "../src/trusted-executable.js";
import { TestClient } from "./support/api-client.js";
import { createApiTestFixtures } from "./support/temporary-directories.js";
@@ -112,9 +113,8 @@ describe("Codex sandbox probe", () => {
await expect(
probeCodexSandbox({ command }, environment),
).resolves.toBeUndefined();
- expect(await readFile(`${command}.args`, "utf8")).toBe(
- ["sandbox", "--", command, "--version", ""].join("\n"),
- );
+ const args = ["sandbox", "--", command, "--version", ""].join("\n");
+ expect(await readFile(`${command}.args`, "utf8")).toBe(args);
expect(await readFile(`${command}.environment`, "utf8")).toBe(
[
environment.PATH,
@@ -123,6 +123,14 @@ describe("Codex sandbox probe", () => {
"",
].join("\n"),
);
+ const source = join(root, "repository");
+ await mkdir(source);
+ const alias = join(source, "codex");
+ await symlink(command, alias);
+ await withProtectedExecutableRoots([source], () =>
+ probeCodexSandbox({ command: alias }, environment),
+ );
+ expect(await readFile(`${command}.args`, "utf8")).toBe(args + args);
},
);
@@ -142,6 +150,27 @@ describe("Codex sandbox probe", () => {
},
);
+ test.skipIf(process.platform === "win32")(
+ "does not launch a probe canceled during campaign tool selection",
+ async () => {
+ const tools = await temporaryDirectory();
+ const command = await syntheticCodex(tools, 0);
+ const controller = new AbortController();
+ const source = await temporaryDirectory();
+ await withProtectedExecutableRoots([source], async () => {
+ using timeout = spyOn(AbortSignal, "timeout");
+ const probe = probeCodexSandbox(
+ { command },
+ { PATH: tools },
+ controller.signal,
+ );
+ controller.abort(new Error("scan canceled"));
+ await expect(probe).rejects.toBe(controller.signal.reason);
+ expect(timeout).not.toHaveBeenCalled();
+ });
+ },
+ );
+
test.skipIf(process.platform === "win32")(
"reports an executable that cannot be started",
async () => {
diff --git a/sdk/typescript/tests-ts/scan-comparison.test.ts b/sdk/typescript/tests-ts/scan-comparison.test.ts
index 72a9736a5..caf8e918b 100644
--- a/sdk/typescript/tests-ts/scan-comparison.test.ts
+++ b/sdk/typescript/tests-ts/scan-comparison.test.ts
@@ -489,7 +489,8 @@ describe("semantic scan comparison", () => {
runtimeCommands,
"runCodexCommand",
).mockImplementation((...args) => {
- if (args[1].includes("mcp")) startupCommands.push(args[0]);
+ if (Array.isArray(args[1]) && args[1].includes("mcp"))
+ startupCommands.push(args[0]);
return runNativeCommand(...args);
});
const before = finding("before");
diff --git a/sdk/typescript/tests-ts/scan-resume.test.ts b/sdk/typescript/tests-ts/scan-resume.test.ts
index 0c4992384..f620bd856 100644
--- a/sdk/typescript/tests-ts/scan-resume.test.ts
+++ b/sdk/typescript/tests-ts/scan-resume.test.ts
@@ -15,9 +15,10 @@ import {
rename,
rm,
stat,
+ symlink,
writeFile,
} from "node:fs/promises";
-import { dirname, join } from "node:path";
+import { delimiter, dirname, join } from "node:path";
import { afterEach, expect, spyOn, test } from "bun:test";
import { parse as parseToml } from "smol-toml";
import { strToU8, zipSync } from "fflate";
@@ -1512,6 +1513,23 @@ test.each([
postScanPrompt: "Run these exact saved post-scan instructions.\n",
};
const f = await interruptedScan("deep", bulk, settings, true);
+ const sourceTools = join(f.root, "source", "bin");
+ const operatorTools = await temporaryDirectory();
+ await mkdir(sourceTools, { recursive: true });
+ const gitMarker = join(f.root, "git-ran");
+ const searchPaths = [sourceTools, operatorTools];
+ if (bulk && process.platform !== "win32") {
+ const sourceGit = join(sourceTools, "git");
+ await writeFile(
+ sourceGit,
+ `#!/bin/sh\nprintf called > "${gitMarker}"\nexit 72\n`,
+ { mode: 0o700 },
+ );
+ const aliases = await temporaryDirectory();
+ await symlink(sourceGit, join(aliases, "git"));
+ searchPaths.unshift(aliases);
+ }
+ f.environment.PATH = [...searchPaths, f.environment.PATH].join(delimiter);
f.environment.OPENAI_API_KEY = "synthetic-resume-key";
const ambientHome = join(f.root, "ambient-codex-home");
f.environment.CODEX_HOME = ambientHome;
@@ -1531,6 +1549,9 @@ test.each([
: ["scans", "resume", f.scanId, "--json"],
resumeDependencies(f, (options) => {
expect(options.config).toMatchObject(selected);
+ const workerPath = options.env?.["PATH"]?.split(delimiter);
+ expect(workerPath).toContain(operatorTools);
+ expect(workerPath?.includes(sourceTools)).toBe(!bulk);
expect(options.env?.["CODEX_SAFETY_IDENTIFIER"]).toBe(
settings.safetyIdentifier,
);
@@ -1613,6 +1634,7 @@ test.each([
};
}),
);
+ expect(await Bun.file(gitMarker).exists()).toBe(false);
expect(code, stderr.text()).toBe(0);
expect(prompts, stderr.text()).toHaveLength(2);
expect(prompts[1]).toBe(settings.postScanPrompt);
diff --git a/sdk/typescript/tests-ts/targets.test.ts b/sdk/typescript/tests-ts/targets.test.ts
index e2f0d4d49..2e96502f2 100644
--- a/sdk/typescript/tests-ts/targets.test.ts
+++ b/sdk/typescript/tests-ts/targets.test.ts
@@ -1044,3 +1044,20 @@ test("executable protection retains lexical and canonical checkout roots", async
expect.arrayContaining([lexical, canonical]),
);
});
+
+test("executable protection follows native parent traversal before finding Git roots", async () => {
+ const stored = await repository("stored");
+ const physical = await repository("physical");
+ const link = join(stored, "child");
+ await symlink(
+ join(physical, "src"),
+ link,
+ process.platform === "win32" ? "junction" : "dir",
+ );
+ const expected = process.platform === "win32" ? [stored] : [physical, stored];
+ for (const suffix of [".git", "missing/child"]) {
+ expect((await gitProtectionRoots(`${link}/../${suffix}`)).sort()).toEqual(
+ expected.toSorted(),
+ );
+ }
+});
diff --git a/sdk/typescript/tests-ts/trusted-executable.test.ts b/sdk/typescript/tests-ts/trusted-executable.test.ts
index fa7a4039b..9ae614470 100644
--- a/sdk/typescript/tests-ts/trusted-executable.test.ts
+++ b/sdk/typescript/tests-ts/trusted-executable.test.ts
@@ -1,13 +1,27 @@
import { spawnSync } from "node:child_process";
-import { chmod, mkdir, realpath, symlink, writeFile } from "node:fs/promises";
+import { existsSync } from "node:fs";
+import {
+ chmod,
+ lstat,
+ mkdir,
+ realpath,
+ symlink,
+ unlink,
+ writeFile,
+} from "node:fs/promises";
import { basename, delimiter, dirname, join, relative } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { afterEach, describe, expect, test } from "bun:test";
import {
inspectTrustedExecutable,
resolveTrustedExecutable,
+ withProtectedExecutableRoots,
} from "../src/trusted-executable.js";
+import { bundledCodexSdkEnvironment } from "../src/codex-sdk-environment.js";
+import { resolveCodexCommand } from "../src/runtime.js";
+import { PLUGIN_ROOT } from "./plugin-root.js";
import { PYTHON } from "./support/security-policy.js";
+import { nodeCommand } from "./support/shell.js";
import { createApiTestFixtures } from "./support/temporary-directories.js";
const { temporaryDirectory, cleanup } = createApiTestFixtures(
@@ -20,23 +34,29 @@ async function resolveWindowsExecutable(
candidate: string,
path: string,
protectedRoot: string,
+ campaign = false,
): ReturnType<typeof resolveTrustedExecutable> {
if (process.platform === "win32") {
- return await resolveTrustedExecutable(
- candidate,
- { Path: path, KEEP: "ok" },
- protectedRoot,
- );
+ const run = () =>
+ resolveTrustedExecutable(
+ candidate,
+ { Path: path, KEEP: "ok" },
+ protectedRoot,
+ );
+ return campaign
+ ? withProtectedExecutableRoots([protectedRoot], run)
+ : run();
}
const script = `
Object.defineProperty(process, "platform", { value: "win32" });
- const { resolveTrustedExecutable } = await import(process.argv[1]);
- console.log(JSON.stringify(await resolveTrustedExecutable(
+ const { resolveTrustedExecutable, withProtectedExecutableRoots } = await import(process.argv[1]);
+ const run = () => resolveTrustedExecutable(
process.argv[2],
{ Path: process.argv[3], KEEP: "ok" },
process.argv[4],
- )));
+ );
+ console.log(JSON.stringify(await (process.argv[5] === "campaign" ? withProtectedExecutableRoots([process.argv[4]], run) : run())));
`;
const result = spawnSync(
process.execPath,
@@ -47,6 +67,7 @@ async function resolveWindowsExecutable(
candidate,
path,
protectedRoot,
+ campaign ? "campaign" : "",
],
{ encoding: "utf8" },
);
@@ -57,6 +78,69 @@ async function resolveWindowsExecutable(
}
describe("trusted executable resolution", () => {
+ test("keeps executable search boundaries isolated between concurrent campaigns", async () => {
+ const first = await temporaryDirectory();
+ const second = await temporaryDirectory();
+ const environment = { PATH: [first, second].join(delimiter) };
+ const inspectPath = async () =>
+ (await inspectTrustedExecutable("git", environment, [])).environment[
+ "PATH"
+ ];
+ expect(
+ await Promise.all([
+ withProtectedExecutableRoots([first], inspectPath),
+ withProtectedExecutableRoots([second], inspectPath),
+ inspectPath(),
+ ]),
+ ).toEqual([second, first, environment.PATH]);
+ });
+
+ test.skipIf(process.platform === "win32")(
+ "campaigns isolate links into checkouts that materialize later",
+ async () => {
+ const first = await temporaryDirectory(),
+ second = await temporaryDirectory(),
+ tools = await temporaryDirectory();
+ const alternate = join(dirname(first), basename(first).toUpperCase());
+ const firstAlias = existsSync(alternate) ? alternate : first;
+ for (const [name, directory] of [
+ ["first", firstAlias],
+ ["second", second],
+ ] as const)
+ await symlink(join(directory, "tool"), join(tools, name));
+ // One checkout starts missing, the other replaces a link to a trusted tool.
+ await symlink("/bin/sh", join(first, "tool"));
+ await symlink(join(firstAlias, "tool"), join(tools, "git"));
+ const environments = await Promise.all(
+ [first, second].map((root) =>
+ withProtectedExecutableRoots([root], async () => {
+ const input = { PATH: tools };
+ const command = await inspectTrustedExecutable("git", input, []);
+ const path = command.environment["PATH"]!;
+ if (root === first) {
+ expect(command.executable).toBeNull();
+ await unlink(join(root, "tool"));
+ }
+ await writeFile(join(root, "tool"), "#!/bin/sh\nexit 73\n", {
+ mode: 0o700,
+ });
+ const selected = root === first ? "first" : "second";
+ expect(
+ spawnSync(selected, [], { env: { PATH: path } }).error,
+ ).toMatchObject({ code: "ENOENT" });
+ const neighbor = root === first ? "second" : "first";
+ expect((await lstat(join(path, neighbor))).isSymbolicLink()).toBe(
+ true,
+ );
+ return path;
+ }),
+ ),
+ );
+ expect(environments[0]).not.toBe(environments[1]);
+ for (const path of environments) expect(existsSync(path)).toBe(false);
+ },
+ );
+
test("accepts safe relative PATH entries without trusting repository links", async () => {
const root = await temporaryDirectory();
const repository = join(root, "repository");
@@ -97,7 +181,11 @@ describe("trusted executable resolution", () => {
const root = await temporaryDirectory();
const repository = join(root, "repository");
const repositoryTools = join(repository, "tools");
- const linkedExecutable = join(root, "linked-executable");
+ const windows = process.platform === "win32";
+ const linkedExecutable = join(
+ root,
+ windows ? "linked-executable" : "tool:installation",
+ );
const safe = join(root, "safe");
const executable = process.platform === "win32" ? "git.exe" : "git";
await Promise.all([
@@ -105,26 +193,40 @@ describe("trusted executable resolution", () => {
mkdir(linkedExecutable),
mkdir(safe),
]);
- await writeFile(join(repositoryTools, executable), "untrusted executable");
+ await writeFile(join(repositoryTools, executable), "#!/bin/sh\nexit 72\n", {
+ mode: 0o700,
+ });
await symlink(
join(repositoryTools, executable),
join(linkedExecutable, executable),
"file",
);
- await expect(
- inspectTrustedExecutable(
- "git",
- {
- PATH: [linkedExecutable, safe].join(delimiter),
- KEEP: "ok",
- },
- repository,
- ),
- ).resolves.toEqual({
+ let entry = linkedExecutable;
+ if (!windows) {
+ const alias = join(root, "current");
+ const version = join(linkedExecutable, "version");
+ await mkdir(version);
+ await symlink(version, alias);
+ entry = alias + "/..";
+ }
+ const result = await inspectTrustedExecutable(
+ "git",
+ { PATH: [entry, safe].join(delimiter), KEEP: "ok" },
+ repository,
+ );
+ expect(result).toEqual({
executable: null,
environment: { KEEP: "ok", PATH: safe },
});
+ if (!windows) {
+ await writeFile(join(safe, executable), "#!/bin/sh\nexit 0\n", {
+ mode: 0o700,
+ });
+ expect(
+ spawnSync("/usr/bin/env", ["git"], { env: result.environment }).status,
+ ).toBe(0);
+ }
});
test.skipIf(process.platform === "win32")(
@@ -452,6 +554,89 @@ describe("trusted executable resolution", () => {
);
});
+ test.each(["direct", "relay", "linked parent"])(
+ "Windows campaign children exclude %s tool links through a selected source",
+ async (route) => {
+ const root = await temporaryDirectory();
+ const source = join(root, "source"),
+ aliases = join(root, "aliases"),
+ pending = join(root, "pending"),
+ nodeAliases = join(root, "node-aliases"),
+ tools = join(root, "tools");
+ await Promise.all(
+ [source, aliases, pending, nodeAliases, tools].map((path) =>
+ mkdir(path),
+ ),
+ );
+ const alternate = join(root, "SOURCE");
+ const spelling = existsSync(alternate) ? alternate : source;
+ const via = route === "direct" ? spelling : join(root, "via");
+ if (route === "linked parent") await symlink(spelling, via, "junction");
+ if (route === "relay") {
+ await mkdir(via);
+ for (const name of ["git.exe", "rg.exe", "node.exe"])
+ await symlink(join(spelling, name), join(via, name), "file");
+ }
+ const node = nodeCommand().command;
+ await symlink(node, join(tools, "git.exe"), "file");
+ await symlink(node, join(tools, "node.exe"), "file");
+ await symlink(node, join(source, "git.exe"), "file");
+ await writeFile(join(source, "node.exe"), "checkout-owned executable");
+ await symlink(
+ join(via, "node.exe"),
+ join(nodeAliases, "node.exe"),
+ "file",
+ );
+ await symlink(join(via, "git.exe"), join(aliases, "git.exe"), "file");
+ await symlink(join(via, "rg.exe"), join(pending, "rg.com"), "file");
+ if (process.platform !== "win32")
+ await symlink(join(pending, "rg.com"), join(pending, "rg"));
+ const command = await resolveWindowsExecutable(
+ "git",
+ [pending, aliases, nodeAliases, tools].join(delimiter),
+ source,
+ true,
+ );
+ expect(command).toEqual({
+ executable: join(tools, "git.exe"),
+ environment: { KEEP: "ok", PATH: tools },
+ });
+ await unlink(join(source, "git.exe"));
+ for (const name of ["git.exe", "rg.exe"])
+ await writeFile(join(source, name), "checkout-owned executable");
+ const environment = bundledCodexSdkEnvironment(
+ resolveCodexCommand({}).command,
+ {
+ PATH: process.env["PATH"] ?? "",
+ },
+ );
+ await symlink(
+ Bun.which("rg", { PATH: environment["PATH"] })!,
+ join(tools, process.platform === "win32" ? "rg.exe" : "rg"),
+ "file",
+ );
+ const checkout = join(root, "checkout");
+ await mkdir(checkout);
+ await writeFile(join(checkout, "visible.ts"), "");
+ const inventory = spawnSync(
+ "node.exe",
+ [
+ join(PLUGIN_ROOT, "mcp", "helpers.mjs"),
+ "generate-in-scope-files",
+ "--repo",
+ checkout,
+ "--scope",
+ ".",
+ "--out",
+ join(root, "inventory.txt"),
+ ],
+ { env: command!.environment, encoding: "utf8" },
+ );
+ expect(inventory.status, inventory.stderr).toBe(0);
+ expect(inventory.stdout).toContain("Recorded 1 in-scope files.");
+ },
+ );
+
test("removes PATH entries containing repository-linked Windows shims", async () => {
const root = await temporaryDirectory();
const repository = join(root, "repository");