OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
fix(native): preserve Windows process launch behavior (#1601)
Michael D'Angelo84a76e16db8b
diff --git a/plugins/codex-security/native/README.md b/plugins/codex-security/native/README.mdindex f618eddff..0aca51ebe 100644--- a/plugins/codex-security/native/README.md+++ b/plugins/codex-security/native/README.md@@ -39,9 +39,13 @@ Four additional operations preserve Windows strings at the Node boundary. `windoWindows process arguments and working directories can also contain unpaired UTF-16 units. `windows-process.mts` runs a private Node subprocess shim that passes those values as bytes to `runWindowsProcess`; ordinary invocations still use Node directly. The native call inherits stdin, stdout, stderr, and the shim's environment. The shim joins a kill-on-close Job Object before starting the child and retains its handle until process exit. Descendants inherit membership, so terminating the shim also closes the child's streams. Startup errors return through Node IPC, separately from command stderr and exit status. The Windows proof checks raw arguments and working directories, binary stream forwarding, environment inheritance, exit status, startup errors, and termination cleanup. The file adapter's `readChunks` callback supports bounded reads and closes the handle when a consumer stops or throws.-Target `NODE_OPTIONS`, `NODE_DEBUG`, and `NODE_EXTRA_CA_CERTS` values travel through the same environment override payload instead of affecting the private shim's startup. This preserves relative preloads and certificate paths in the target's working directory and keeps shim diagnostics out of the target's stderr. The one-command shim restores target environment overrides before lookup and changes to the target directory before launching it, so relative executable paths and `PATH` entries use that directory. Bare executable names also check that directory before Rust's `PATH` lookup, honoring the Windows current-directory search setting. The effective `PATH` is explicit in the target command, so its entries precede the shim's executable directory and Rust's parent-PATH fallback uses the same exact value. Early cancellation skips the IPC handoff and its cancellation-induced transport errors.+Target `NODE_OPTIONS`, `NODE_DEBUG`, `NODE_DEBUG_NATIVE`, `NODE_EXTRA_CA_CERTS`, and `NODE_V8_COVERAGE` values travel through the same environment override payload instead of affecting the private shim's startup. This preserves relative preloads, certificate paths, and coverage directories in the target's working directory and keeps shim diagnostics out of the target's stderr. Node's automatic forwarding of parent coverage settings is preserved for the target. The one-command shim restores target environment overrides before lookup and changes to the target directory before launching it, so relative executable paths and `PATH` entries use that directory. Bare executable names check that directory when the Windows current-directory search setting permits it, then search each `PATH` directory in order. Early cancellation skips the IPC handoff and its cancellation-induced transport errors.-Explicitly selected `.com` paths use `CreateProcessW` with that exact application name, because Rust's `Command` otherwise prefers an existing `.com.exe` sibling. This branch preserves UTF-16 arguments with CRT quoting, duplicates the shim's standard handles for inheritance, and uses the same restored environment, job lifetime, and error reporting. Other executables continue to use `Command`.+Every selected image uses `CreateProcessW` with that exact application name, because Rust's `Command` otherwise searches different extensions and can prefer a sibling such as `.bin.exe` over the selected `.bin`. The originally requested executable spelling remains `argv[0]`. The launcher preserves UTF-16 arguments with CRT quoting, duplicates the shim's standard handles for inheritance, and uses the same restored environment, job lifetime, and error reporting.++Selected `.cmd` and `.bat` files are rejected with Windows error 87 before launch, including Node's case-insensitive extension handling with trailing dots and whitespace. Win32 can otherwise dispatch batch files through a command interpreter whose argument rules differ from CRT quoting. The check follows image selection, preserving missing-file errors and `.com`/`.exe` sibling selection. The proof uses harmless echo metacharacters to check that batch contents and argument commands never execute.++Explicit paths and names searched through `PATH` try the given name first when it has an extension, followed by `.com` and `.exe`, matching Node's lookup. Candidate checks inspect Windows entry attributes without following file symlinks and skip directories, including directory symlinks. A dangling first file candidate therefore reports its launch failure instead of selecting a later image. The Windows proof compares image selection and `argv[0]` with ordinary Node spawning, including PATH-only `.com` files, extension collisions, quoted PATH entries, symlink candidates, and names with a trailing dot, while preserving the caller's working directory.Build on Windows after compiling the TypeScript tools, then run:diff --git a/plugins/codex-security/native/proof-process-windows.mts b/plugins/codex-security/native/proof-process-windows.mtsindex d9975e2e1..4c1e5ac15 100644--- a/plugins/codex-security/native/proof-process-windows.mts+++ b/plugins/codex-security/native/proof-process-windows.mts@@ -1,12 +1,20 @@import assert from "node:assert/strict";+import { spawn } from "node:child_process";import { once } from "node:events";-import { copyFileSync, mkdirSync, readFileSync } from "node:fs";+import {+ copyFileSync,+ mkdirSync,+ readFileSync,+ readdirSync,+ symlinkSync,+} from "node:fs";import { join, win32 } from "node:path";import { setTimeout as delay } from "node:timers/promises";import { rootCertificates } from "node:tls";import { binaryPath } from "./binding.mjs";import { loadWindowsBinding } from "./windows-binding.mjs";import { widePath, windowsFileSystem } from "./windows-files.mjs";+import { windowsFlags as flags } from "./windows-flags.mjs";import { spawnWindowsProcess } from "./windows-process.mjs";async function processExit(@@ -23,6 +31,7 @@ async function processExit(export async function processProof(root: string,+ symlinks: boolean,): Promise<Record<string, boolean>> {const native = loadWindowsBinding(),files = windowsFileSystem(native);@@ -43,7 +52,7 @@ export async function processProof(`space ${"\\".repeat(count)}`,]),];- const script = `const fs=require('node:fs'), native=require(${JSON.stringify(binaryPath)}); const args=native.windowsArguments().slice(3).map(value=>value.toString('utf16le')); const cwd=native.windowsAbsolutePath(Buffer.from('.', 'utf16le')).value.toString('utf16le'); process.stderr.write(JSON.stringify({args,cwd,executable:process.execPath,setting:process.env.INVENTORY_PROCESS_FIXTURE,rawSetting:native.windowsEnvironment(Buffer.from("INVENTORY_PROCESS_RAW", "utf16le")).toString("utf16le")})); process.stdout.write(fs.readFileSync(0)); process.exitCode=23;`;+ const script = `const fs=require('node:fs'), native=require(${JSON.stringify(binaryPath)}); const argv=native.windowsArguments().map(value=>value.toString('utf16le')); const args=argv.slice(3); const cwd=native.windowsAbsolutePath(Buffer.from('.', 'utf16le')).value.toString('utf16le'); process.stderr.write(JSON.stringify({args,argv0:argv[0],cwd,executable:process.execPath,setting:process.env.INVENTORY_PROCESS_FIXTURE,rawSetting:native.windowsEnvironment(Buffer.from("INVENTORY_PROCESS_RAW", "utf16le")).toString("utf16le")})); process.stdout.write(fs.readFileSync(0)); process.exitCode=23;`;const child = spawnWindowsProcess(binaryPath,process.execPath,@@ -69,6 +78,7 @@ export async function processProof(assert.deepEqual(Buffer.concat(stdout), bytes);const result = JSON.parse(Buffer.concat(stderr).toString("utf8"));assert.deepEqual(result.args, arguments_);+ assert.equal(result.argv0, process.execPath);assert.equal(result.cwd.toLowerCase(), cwd.toLowerCase());assert.equal(result.setting, "inherited");assert.equal(result.rawSetting, "raw-\udfff");@@ -88,7 +98,25 @@ export async function processProof(),);for (const [executable, directory, path, selected] of [- ["process-probe", cwd, "..\\relative-tools", "process-probe.exe"],+ ["process-probe", cwd, "..\\relative-tools", "process-probe.com"],+ [+ "..\\relative-tools\\process-probe",+ cwd,+ join(root, "absent-tools"),+ "process-probe.com",+ ],+ [+ "..\\relative-tools\\process-probe.",+ cwd,+ join(root, "absent-tools"),+ "process-probe.com",+ ],+ [+ join(tools, "process-probe"),+ cwd,+ join(root, "absent-tools"),+ "process-probe.com",+ ],["..\\relative-tools\\process-probe.exe",cwd,@@ -143,6 +171,7 @@ export async function processProof(assert.deepEqual(Buffer.concat(output), bytes);assert.deepEqual(JSON.parse(Buffer.concat(errors).toString()), {args: arguments_,+ argv0: executable,cwd: directory,executable: join(tools, selected),setting: "relative target",@@ -151,6 +180,299 @@ export async function processProof(assert.equal(process.cwd(), callerCwd);}+ copyFileSync(process.execPath, join(tools, "process-probe.bin"));+ copyFileSync(process.execPath, join(tools, "process-probe.bin.exe"));+ const firstTools = join(root, "first-tools"),+ quotedTools = join(root, "quoted;tools");+ mkdirSync(firstTools);+ mkdirSync(quotedTools);+ copyFileSync(process.execPath, join(firstTools, "process-probe.exe"));+ copyFileSync(process.execPath, join(quotedTools, "process-probe.com"));+ const selectionArgs = [+ "-e",+ "process.stdout.write(JSON.stringify({executable:process.execPath,argv0:process.argv0}))",+ ];+ for (const [executable, path, expected] of [+ [+ "process-probe",+ `"${quotedTools}"`,+ join(quotedTools, "process-probe.com"),+ ],+ [+ "process-probe",+ `'${quotedTools}'`,+ join(quotedTools, "process-probe.com"),+ ],+ [+ "process-probe",+ `${firstTools};${tools}`,+ join(firstTools, "process-probe.exe"),+ ],+ ["process-probe.com", tools, join(tools, "process-probe.com")],+ ["process-probe.exe", tools, join(tools, "process-probe.exe")],+ ["process-probe.", tools, join(tools, "process-probe.com")],+ ["process-probe.bin", tools, join(tools, "process-probe.bin")],+ ...["com", "exe"].map(+ (extension) =>+ [+ `\\\\.\\${join(tools, `process-probe.${extension}`)}\\unused\\..`,+ firstTools,+ `\\\\.\\${join(tools, `process-probe.${extension}`)}`,+ ] as const,+ ),+ [+ ".\\relative-tools\\process-probe.exe",+ firstTools,+ join(tools, "process-probe.exe"),+ ],+ [+ ".\\relative-tools\\process-probe.bin",+ firstTools,+ join(tools, "process-probe.bin"),+ ],+ [+ join(tools, "process-probe.bin"),+ firstTools,+ join(tools, "process-probe.bin"),+ ],+ ] as const) {+ for (const mode of ["node", "native"] as const) {+ const options = {+ cwd: root,+ env: { ...relativeEnvironment, PATH: path },+ stdio: ["ignore", "pipe", "pipe"] as ["ignore", "pipe", "pipe"],+ };+ const selected =+ mode === "node"+ ? spawn(executable, selectionArgs, options)+ : spawnWindowsProcess(+ binaryPath,+ executable,+ selectionArgs,+ options,+ );+ const output: Buffer[] = [],+ diagnostics: Buffer[] = [];+ selected.stdout!.on("data", (chunk: Buffer) => output.push(chunk));+ selected.stderr!.on("data", (chunk: Buffer) => diagnostics.push(chunk));+ assert.deepEqual(+ await processExit(+ selected,+ `${mode} selection ${JSON.stringify(executable)}`,+ ),+ [0, null],+ );+ const actual = JSON.parse(Buffer.concat(output).toString());+ // Node can retain dot components in its reported module filename.+ assert.deepEqual(+ { ...actual, executable: win32.normalize(actual.executable) },+ { executable: expected, argv0: executable },+ `${mode} selection ${JSON.stringify(executable)}`,+ );+ assert.equal(Buffer.concat(diagnostics).toString(), "");+ }+ }++ for (const kind of [+ "directory",+ ...(symlinks ? ["dangling-file", "dangling-directory"] : []),+ ]) {+ const first = join(root, `${kind}-tools`);+ mkdirSync(first);+ const candidate = join(first, "process-probe.exe");+ if (kind === "directory") mkdirSync(candidate);+ else+ symlinkSync(+ join(first, "missing"),+ candidate,+ kind === "dangling-file" ? "file" : "dir",+ );+ for (const mode of ["node", "native"] as const) {+ const options = {+ cwd: root,+ env: { ...relativeEnvironment, PATH: `${first};${tools}` },+ stdio: ["ignore", "pipe", "pipe"] as ["ignore", "pipe", "pipe"],+ };+ const selected =+ mode === "node"+ ? spawn("process-probe", selectionArgs, options)+ : spawnWindowsProcess(+ binaryPath,+ "process-probe",+ selectionArgs,+ options,+ );+ const output: Buffer[] = [],+ diagnostics: Buffer[] = [];+ const errors: Error[] = [];+ selected.stdout!.on("data", (chunk: Buffer) => output.push(chunk));+ selected.stderr!.on("data", (chunk: Buffer) => diagnostics.push(chunk));+ selected.on("error", (error) => errors.push(error));+ const status = await new Promise<number | null>((resolve) =>+ selected.once("close", (code) => resolve(code)),+ );+ if (kind === "dangling-file") {+ assert.equal(+ errors.length,+ 1,+ `${mode} must report the first candidate's launch failure`,+ );+ assert.equal(+ Buffer.concat(output).length,+ 0,+ "a later PATH image must not run",+ );+ } else {+ assert.deepEqual(errors, []);+ assert.equal(status, 0);+ assert.deepEqual(JSON.parse(Buffer.concat(output).toString()), {+ executable: join(tools, "process-probe.com"),+ argv0: "process-probe",+ });+ }+ assert.equal(Buffer.concat(diagnostics).length, 0);+ }+ }++ const batchTools = join(root, "batch-tools");+ mkdirSync(batchTools);+ const batchArguments = [+ "value&echo.BATCH_METACHAR",+ 'value"&echo.BATCH_QUOTE',+ ];+ const batchOptions = {+ cwd: root,+ env: { ...relativeEnvironment, PATH: batchTools },+ stdio: ["ignore", "pipe", "pipe"] as ["ignore", "pipe", "pipe"],+ };+ async function startupFailure(+ executable: string,+ expectedErrors: number[],+ args = batchArguments,+ ) {+ const child = spawnWindowsProcess(+ binaryPath,+ executable,+ args,+ batchOptions,+ );+ const errors: NodeJS.ErrnoException[] = [];+ const stdout: Buffer[] = [],+ stderr: Buffer[] = [];+ child.on("error", (error) => errors.push(error));+ child.stdout!.on("data", (chunk: Buffer) => stdout.push(chunk));+ child.stderr!.on("data", (chunk: Buffer) => stderr.push(chunk));+ const status = await new Promise<number | null>((resolve) =>+ child.once("close", (code) => resolve(code)),+ );+ assert.equal(status, 127);+ assert.equal(errors.length, 1);+ assert.equal(errors[0]!.code, "WINDOWS_PROCESS_ERROR");+ assert(+ expectedErrors.includes(errors[0]!.errno!),+ `${executable}: ${errors[0]!.message}`,+ );+ assert(errors[0]!.message.length > 0);+ assert.equal(+ Buffer.concat(stdout).length,+ 0,+ "neither the batch nor a metacharacter command may run",+ );+ assert.equal(Buffer.concat(stderr).length, 0);+ }+ for (const extension of ["cmd", "bat"] as const) {+ const batch = join(batchTools, `blocked.${extension}`);+ const selected = `${batch}.${extension === "cmd" ? "com" : "exe"}`;+ copyFileSync(process.execPath, selected);+ files.writeFile(+ widePath(batch),+ Buffer.from("@echo off\r\necho BATCH_BODY\r\n"),+ );+ for (const executable of [+ batch,+ `.\\batch-tools\\blocked.${extension}`,+ `blocked.${extension}`,+ join(batchTools, `blocked.${extension.toUpperCase()}`),+ `${batch}. `,+ `${batch}\\.`,+ `${batch}\\unused\\..`,+ `\\\\.\\${batch}`,+ `\\\\.\\${batch}\\.`,+ `\\\\.\\${batch}\\unused\\..`,+ win32.toNamespacedPath(batch),+ ])+ await startupFailure(executable, [87]);+ // Verbatim paths do not resolve the dot segments through a regular file.+ await startupFailure(`${win32.toNamespacedPath(batch)}\\unused\\..`, [2]);+ files.unlink(widePath(batch));+ // Classify the selected image, allowing the existing .com/.exe fallback.+ const image = spawnWindowsProcess(+ binaryPath,+ `blocked.${extension}`,+ selectionArgs,+ batchOptions,+ );+ const output: Buffer[] = [],+ diagnostics: Buffer[] = [];+ image.stdout!.on("data", (chunk: Buffer) => output.push(chunk));+ image.stderr!.on("data", (chunk: Buffer) => diagnostics.push(chunk));+ assert.deepEqual(+ await processExit(image, `batch-name ${extension} image fallback`),+ [0, null],+ );+ assert.deepEqual(JSON.parse(Buffer.concat(output).toString()), {+ executable: selected,+ argv0: `blocked.${extension}`,+ });+ assert.equal(Buffer.concat(diagnostics).length, 0);+ }+ await startupFailure(join(batchTools, "missing.cmd"), [2]);+ const lockedExecutable = join(batchTools, "locked.exe");+ copyFileSync(process.execPath, lockedExecutable);+ const locked = native.openWindowsFile(+ widePath(win32.toNamespacedPath(lockedExecutable)),+ flags.GENERIC_READ,+ 0,+ flags.OPEN_EXISTING,+ flags.FILE_ATTRIBUTE_NORMAL,+ );+ assert.equal(locked.error, 0);+ assert(locked.handle);+ try {+ await startupFailure(lockedExecutable, [5, 32], selectionArgs);+ } finally {+ assert.equal(locked.handle.close(), 0);+ }++ const inheritedPath = process.env["PATH"];+ try {+ process.env["PATH"] = tools;+ const inherited = spawnWindowsProcess(+ binaryPath,+ "process-probe",+ selectionArgs,+ {+ cwd: root,+ env: relativeEnvironment,+ stdio: ["ignore", "pipe", "pipe"],+ },+ );+ const output: Buffer[] = [];+ inherited.stdout!.on("data", (chunk: Buffer) => output.push(chunk));+ inherited.stderr!.resume();+ assert.deepEqual(+ await processExit(inherited, "omitted PATH inherits caller value"),+ [0, null],+ );+ assert.deepEqual(JSON.parse(Buffer.concat(output).toString()), {+ executable: join(tools, "process-probe.com"),+ argv0: "process-probe",+ });+ } finally {+ if (inheritedPath === undefined) delete process.env["PATH"];+ else process.env["PATH"] = inheritedPath;+ }+const executableBytes = readFileSync(process.execPath);const rawTools = join(root, "path-tools-\ud800"),replacementTools = join(root, "path-tools-�");@@ -238,7 +560,7 @@ export async function processProof(executable,["-e",- `const native=require(${JSON.stringify(binaryPath)}); process.stdout.write(JSON.stringify({selected:process.execPath.endsWith('.com'),args:native.windowsArguments().slice(3).map(value=>value.toString('utf16le'))}));`,+ `const native=require(${JSON.stringify(binaryPath)}); const argv=native.windowsArguments().map(value=>value.toString('utf16le')); process.stdout.write(JSON.stringify({selected:process.execPath.endsWith('.com'),argv0:argv[0],args:argv.slice(3)}));`,...arguments_,],{ cwd, stdio: ["ignore", "pipe", "pipe"] },@@ -256,16 +578,18 @@ export async function processProof();assert.deepEqual(JSON.parse(Buffer.concat(output).toString()), {selected: true,+ argv0: executable,args: arguments_,});assert.equal(Buffer.concat(errors).toString(), "");}- const shimTools = join(root, "shim-tools");+ const shimTools = join(root, "shim-tools"),+ absentTools = join(root, "absent-tools");mkdirSync(shimTools);copyFileSync(process.execPath, join(shimTools, "node.exe"));copyFileSync(process.execPath, join(shimTools, "process-probe.exe"));- for (const overridePath of [undefined, tools]) {+ for (const overridePath of [undefined, tools, absentTools]) {const originalNode = process.execPath;let selectedChild: ReturnType<typeof spawnWindowsProcess>;try {@@ -295,18 +619,35 @@ export async function processProof(errors: Buffer[] = [];selectedChild.stdout!.on("data", (data: Buffer) => output.push(data));selectedChild.stderr!.on("data", (data: Buffer) => errors.push(data));- assert.deepEqual(- await processExit(- selectedChild,- `PATH collision (override=${overridePath !== undefined})`,- ),- [0, null],- );- assert.deepEqual(JSON.parse(Buffer.concat(output).toString()), {- executable: join(tools, "process-probe.exe"),- path: tools,- setting: "selected target",- });+ if (overridePath === absentTools) {+ const errors: NodeJS.ErrnoException[] = [];+ selectedChild.on("error", (error) => errors.push(error));+ await new Promise<void>((resolve) =>+ selectedChild.once("close", () => resolve()),+ );+ assert.deepEqual(+ errors.map((error) => error.code),+ ["WINDOWS_PROCESS_ERROR"],+ );+ assert.equal(+ Buffer.concat(output).length,+ 0,+ "missing PATH tool must not resolve beside the shim",+ );+ } else {+ assert.deepEqual(+ await processExit(+ selectedChild,+ `PATH collision (override=${overridePath !== undefined})`,+ ),+ [0, null],+ );+ assert.deepEqual(JSON.parse(Buffer.concat(output).toString()), {+ executable: join(tools, "process-probe.com"),+ path: tools,+ setting: "selected target",+ });+ }assert.equal(Buffer.concat(errors).toString(), "");}@@ -333,25 +674,28 @@ export async function processProof();assert.equal(searchErrors.length, 1);- for (const [key, override] of [- ["NODE_DEBUG", undefined],- ["Node_Debug", undefined],- ["NODE_DEBUG", "module,net"],+ for (const [key, value, override] of [+ ["NODE_DEBUG", "module", undefined],+ ["Node_Debug", "module", undefined],+ ["NODE_DEBUG", "module", "module,net"],+ ["NODE_DEBUG_NATIVE", "code_cache", undefined],+ ["Node_Debug_Native", "code_cache", undefined],+ ["NODE_DEBUG_NATIVE", "code_cache", "async_wrap"],] as const) {const env = Object.fromEntries(Object.entries(process.env).filter(- ([name]) => name.toUpperCase() !== "NODE_DEBUG",+ ([name]) => name.toUpperCase() !== key.toUpperCase(),),);- env["node_debug"] = "ignored duplicate";- env[key] = "module";+ env[key.toLowerCase()] = "ignored duplicate";+ env[key] = value;const snapshot = { ...env };const debugChild = spawnWindowsProcess(binaryPath,process.env["ComSpec"]!,- ["/d", "/c", "echo %NODE_DEBUG%"],+ ["/d", "/c", `echo %${key}%`],{ cwd, env, stdio: ["ignore", "pipe", "pipe"] },- override === undefined ? {} : { Node_Debug: override },+ override === undefined ? {} : { [key.toLowerCase()]: override },);const output: Buffer[] = [],errors: Buffer[] = [];@@ -361,14 +705,68 @@ export async function processProof(0,null,]);- assert.equal(- Buffer.concat(output).toString().trim(),- override ?? "module",- );+ assert.equal(Buffer.concat(output).toString().trim(), override ?? value);assert.equal(Buffer.concat(errors).toString(), "");assert.deepEqual(env, snapshot);}+ for (const [index, scenario] of [+ { key: "NODE_V8_COVERAGE", value: "coverage" },+ { key: "Node_V8_Coverage", value: "coverage" },+ { key: "NODE_V8_COVERAGE", value: "ignored", override: "coverage" },+ { inherited: "coverage" },+ ].entries()) {+ const caller = join(root, `coverage-caller-${index}`),+ target = join(caller, "target");+ mkdirSync(target, { recursive: true });+ // A separate caller keeps both correct and misplaced coverage inside the fixture.+ const coverageChild = spawn(+ process.execPath,+ [+ "--input-type=module",+ "-e",+ `import assert from 'node:assert/strict';+import { spawnWindowsProcess } from ${JSON.stringify(new URL("./windows-process.mjs", import.meta.url).href)};+const scenario = ${JSON.stringify(scenario)};+const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => name.toUpperCase() !== 'NODE_V8_COVERAGE'));+if (scenario.key) env[scenario.key] = scenario.value;+if (scenario.inherited) process.env.NODE_V8_COVERAGE = scenario.inherited;+const snapshot = { ...env };+const child = spawnWindowsProcess(${JSON.stringify(binaryPath)}, process.execPath,+ ['-e', 'process.stdout.write(process.env.NODE_V8_COVERAGE)'],+ { cwd: ${JSON.stringify(target)}, env, stdio: ['ignore', 'pipe', 'pipe'] },+ scenario.override === undefined ? {} : { Node_V8_Coverage: scenario.override });+assert.deepEqual(env, snapshot);+child.stdout.pipe(process.stdout);+child.stderr.pipe(process.stderr);+child.on('error', error => { process.stderr.write(String(error)); process.exitCode = 1; });+child.once('close', code => { process.exitCode = code ?? 1; });`,+ ],+ {+ cwd: caller,+ env: { ...process.env, NODE_V8_COVERAGE: undefined },+ stdio: ["ignore", "pipe", "pipe"],+ },+ );+ const output: Buffer[] = [],+ diagnostics: Buffer[] = [];+ coverageChild.stdout!.on("data", (chunk: Buffer) => output.push(chunk));+ coverageChild.stderr!.on("data", (chunk: Buffer) =>+ diagnostics.push(chunk),+ );+ assert.deepEqual(+ await processExit(coverageChild, `target coverage ${index}`),+ [0, null],+ );+ assert.equal(Buffer.concat(output).toString(), join(target, "coverage"));+ assert.equal(Buffer.concat(diagnostics).toString(), "");+ assert.deepEqual(readdirSync(caller), ["target"]);+ const reports = readdirSync(join(target, "coverage"));+ assert.equal(reports.length, 1, "only the target writes coverage");+ assert.match(reports[0]!, /^coverage-.*\.json$/u);+ assert.equal(process.cwd(), callerCwd);+ }+files.writeFile(widePath(join(root, "target-certificates.pem")),Buffer.from(rootCertificates[0]!),@@ -595,12 +993,22 @@ export async function processProof(relativeExecutableAndPathUseTargetCwd: true,bareExecutableUsesTargetCwd: true,explicitComSelectionAndArgumentQuoting: true,+ pathAndExplicitImageSelectionMatchNode: true,+ originalArgv0Preserved: true,+ executableSymlinkSelectionMatchesNode: symlinks,+ executableDirectoryCandidatesSkipped: true,+ batchImagesRejectedWithoutInterpretingArguments: true,+ batchNamedExecutableFallbackPreserved: true,+ missingAndLockedImageDiagnosticsPreserved: true,+ omittedPathInheritsCallerValue: true,longAndNamespacedRawComPaths: true,inheritedAndOverriddenPathPrecedeShimDirectory: true,rawPathDoesNotFallBackToReplacementTool: true,disabledCurrentDirectorySearchPreserved: true,inheritedSettingsAndBinaryStreams: true,targetDebugSettingsWithoutShimDiagnostics: true,+ targetNativeDebugSettingsWithoutShimDiagnostics: true,+ targetCoverageUsesTargetCwdWithoutShimCoverage: true,targetCertificatesWithoutShimDiagnostics: true,inheritedModuleModeForTarget: true,targetPreloadsAndOverrides: true,diff --git a/plugins/codex-security/native/proof-windows.mts b/plugins/codex-security/native/proof-windows.mtsindex 0171591b6..d0399c7c4 100644--- a/plugins/codex-security/native/proof-windows.mts+++ b/plugins/codex-security/native/proof-windows.mts@@ -383,6 +383,9 @@ const root = realpathSync.native();let proofError: unknown;try {+ const handles = handleProof(root);+ const privateDirectories = privateDirectoryProof(root, native);+ const wideProcessAndPaths = wideProcessProof(root);console.log(JSON.stringify({@@ -390,10 +393,15 @@ try {platform: process.platform,architecture: process.arch,nodeApi: 8,- handles: handleProof(root),- privateDirectories: privateDirectoryProof(root, native),- wideProcessAndPaths: wideProcessProof(root),- childProcesses: await processProof(root),+ handles,+ privateDirectories,+ wideProcessAndPaths,+ childProcesses: await processProof(+ root,+ wideProcessAndPaths[+ "cachedSymlinkTagsIncludingDanglingDirectories"+ ] === true,+ ),garbageCollectionClosesHandle: await ownershipProof(root),fixture: basename(root),},diff --git a/plugins/codex-security/native/src/windows.rs b/plugins/codex-security/native/src/windows.rsindex 48527e288..7c3e63592 100644--- a/plugins/codex-security/native/src/windows.rs+++ b/plugins/codex-security/native/src/windows.rs@@ -14,7 +14,8 @@ use std::{};use windows_sys::Win32::{Foundation::{- GetLastError, LocalFree, SetLastError, ERROR_INVALID_HANDLE, HANDLE, INVALID_HANDLE_VALUE,+ GetLastError, LocalFree, SetLastError, ERROR_FILE_NOT_FOUND, ERROR_INVALID_HANDLE,+ ERROR_INVALID_PARAMETER, HANDLE, INVALID_HANDLE_VALUE,},Security::{Authorization::{@@ -121,9 +122,9 @@ pub struct WindowsProcessResult {pub status: i32,}-fn windows_command_line(executable: &OsStr, arguments: &[OsString]) -> Vec<u16> {+fn windows_command_line(argv0: &OsStr, arguments: &[OsString]) -> Vec<u16> {let mut line = vec![b'"' as u16];- line.extend(executable.encode_wide());+ line.extend(argv0.encode_wide());line.push(b'"' as u16);for argument in arguments {line.push(b' ' as u16);@@ -172,7 +173,8 @@ fn windows_application_path(executable: &OsStr) -> io::Result<Vec<u16>> {bytes.starts_with(br"\\?\") || bytes.starts_with(br"\\.\") || bytes.starts_with(br"\??\")};let terminated = |path: &OsStr| path.encode_wide().chain([0]).collect::<Vec<_>>();- if namespaced(executable) {+ // DOS-device paths still need Win32 normalization; only verbatim paths skip it.+ if namespaced(executable) && !executable.as_encoded_bytes().starts_with(br"\\.\") {return Ok(terminated(executable));}// Resolve lexically, without canonicalizing the selected file or changing argv.@@ -182,7 +184,7 @@ fn windows_application_path(executable: &OsStr) -> io::Result<Vec<u16>> {}let units = absolute.as_os_str().encode_wide().collect::<Vec<_>>();if units.len() < MAX_PATH as usize {- return Ok(terminated(executable));+ return Ok(terminated(absolute.as_os_str()));}// CreateProcessW needs a namespace for an ordinary long application path.let (prefix, tail) = if units.starts_with(&[b'\\' as u16; 2]) {@@ -197,7 +199,100 @@ fn windows_application_path(executable: &OsStr) -> io::Result<Vec<u16>> {.collect())}-fn run_exact_com_process(executable: &OsStr, arguments: &[OsString]) -> io::Result<i32> {+fn windows_search_paths(paths: &OsStr) -> Vec<OsString> {+ let units = paths.encode_wide().collect::<Vec<_>>();+ let mut remaining = units.as_slice();+ let mut directories = Vec::new();+ while !remaining.is_empty() {+ // Like Node, a leading quote protects separators until its closing quote.+ let quoted = matches!(remaining[0], 34 | 39);+ let start = if quoted {+ remaining[1..]+ .iter()+ .position(|&unit| unit == remaining[0])+ .map_or(remaining.len(), |index| index + 1)+ } else {+ 0+ };+ let end = remaining[start..]+ .iter()+ .position(|&unit| unit == b';' as u16)+ .map_or(remaining.len(), |index| start + index);+ let mut directory = &remaining[..end];+ remaining = remaining.get(end + 1..).unwrap_or_default();+ if directory.is_empty() {+ continue;+ }+ if quoted {+ directory = &directory[1..];+ }+ if matches!(directory.last(), Some(34 | 39)) {+ directory = &directory[..directory.len() - 1];+ }+ directories.push(OsString::from_wide(directory));+ }+ directories+}++fn resolve_windows_executable(executable: &OsStr) -> io::Result<OsString> {+ use std::path::Path;+ use windows_sys::Win32::System::Environment::NeedCurrentDirectoryForExePathW;++ let missing = || io::Error::from_raw_os_error(ERROR_FILE_NOT_FOUND as i32);+ if executable.is_empty() || executable == "." {+ return Err(missing());+ }+ let filename = Path::new(executable).file_name();+ let has_directory = filename != Some(executable);+ let bytes = filename.unwrap_or(executable).as_encoded_bytes();+ let has_extension = bytes+ .iter()+ .position(|&byte| byte == b'.')+ .is_some_and(|index| index + 1 < bytes.len());+ let mut candidates = Vec::new();+ if has_extension {+ candidates.push(executable.to_os_string());+ }+ for extension in ["com", "exe"] {+ let mut candidate = executable.to_os_string();+ if bytes.last() != Some(&b'.') {+ candidate.push(".");+ }+ candidate.push(extension);+ candidates.push(candidate);+ }+ let cwd = std::env::current_dir()?;+ let find = |directory: &Path| {+ candidates+ .iter()+ .map(|candidate| directory.join(candidate))+ .find_map(|path| {+ let path = windows_application_path(path.as_os_str()).ok()?;+ // Select, classify and launch the same path without following file symlinks.+ let attributes = unsafe { GetFileAttributesW(path.as_ptr()) };+ (attributes != INVALID_FILE_ATTRIBUTES+ && attributes & FILE_ATTRIBUTE_DIRECTORY == 0)+ .then(|| OsString::from_wide(&path[..path.len() - 1]))+ })+ };+ if has_directory || unsafe { NeedCurrentDirectoryForExePathW([0_u16].as_ptr()) } != 0 {+ if let Some(path) = find(&cwd) {+ return Ok(path);+ }+ }+ if !has_directory {+ if let Some(paths) = std::env::var_os("PATH") {+ for directory in windows_search_paths(&paths) {+ if let Some(path) = find(&cwd.join(directory)) {+ return Ok(path);+ }+ }+ }+ }+ Err(missing())+}++fn run_exact_process(executable: &OsStr, argv0: &OsStr, arguments: &[OsString]) -> io::Result<i32> {use windows_sys::Win32::{Foundation::{DuplicateHandle, DUPLICATE_SAME_ACCESS, WAIT_OBJECT_0},System::Threading::{@@ -248,7 +343,7 @@ fn run_exact_com_process(executable: &OsStr, arguments: &[OsString]) -> io::Resu.as_ref().map_or(null_mut(), AsRawHandle::as_raw_handle);let mut process: PROCESS_INFORMATION = unsafe { std::mem::zeroed() };- let mut command_line = windows_command_line(executable, arguments);+ let mut command_line = windows_command_line(argv0, arguments);if unsafe {CreateProcessW(application.as_ptr(),@@ -279,6 +374,17 @@ fn run_exact_com_process(executable: &OsStr, arguments: &[OsString]) -> io::ResuOk(exit_code as i32)}+fn windows_batch_file(executable: &OsStr) -> bool {+ let bytes = executable.as_encoded_bytes();+ // Node recognizes batch extensions after trailing dots and ASCII whitespace.+ let end = bytes+ .iter()+ .rposition(|byte| !matches!(byte, b'.' | b' ' | b'\t' | b'\n' | b'\r' | 11 | 12))+ .map_or(0, |index| index + 1);+ let extension = &bytes[end.saturating_sub(4)..end];+ extension.eq_ignore_ascii_case(b".cmd") || extension.eq_ignore_ascii_case(b".bat")+}+/// Run only inside the Node subprocess shim: blocking here keeps pipe ownership in that process.#[napi]pub fn run_windows_process(@@ -287,8 +393,6 @@ pub fn run_windows_process(cwd: Option<Buffer>,environment: Option<Vec<WindowsEnvironmentValue>>,) -> napi::Result<WindowsProcessResult> {- use std::process::{Command, Stdio};-let executable = os_string(executable)?;let arguments = arguments.into_iter()@@ -301,22 +405,19 @@ pub fn run_windows_process(.map(|entry| Ok((os_string(entry.name)?, os_string(entry.value)?))).collect::<napi::Result<Vec<_>>>()?;fn run(- mut executable: OsString,+ executable: OsString,arguments: Vec<OsString>,cwd: Option<OsString>,environment: Vec<(OsString, OsString)>,) -> io::Result<i32> {- use std::path::Path;- use windows_sys::Win32::System::Environment::{- NeedCurrentDirectoryForExePathW, SetEnvironmentVariableW,- };+ use windows_sys::Win32::System::Environment::SetEnvironmentVariableW;use windows_sys::Win32::System::JobObjects::{AssignProcessToJobObject, CreateJobObjectW, JobObjectExtendedLimitInformation,SetInformationJobObject, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,};// Restore target settings inside the one-command shim after Node startup.- // Lookup must use the exact environment, including Rust's parent-PATH fallback.+ // Lookup and the target must use the same exact environment.for (name, value) in environment {let name = name.encode_wide().chain([0]).collect::<Vec<_>>();let value = value.encode_wide().chain([0]).collect::<Vec<_>>();@@ -329,33 +430,10 @@ pub fn run_windows_process(if let Some(directory) = cwd {std::env::set_current_dir(directory)?;}- // Rust searches PATH but omits Node's current-directory lookup for bare names.- if Path::new(&executable).file_name() == Some(executable.as_os_str())- && unsafe { NeedCurrentDirectoryForExePathW([0_u16].as_ptr()) } != 0- {- let bytes = executable.as_encoded_bytes();- let has_extension = bytes- .iter()- .position(|&byte| byte == b'.')- .is_some_and(|index| index + 1 < bytes.len());- let mut candidates = Vec::new();- if has_extension {- candidates.push(executable.clone());- }- for extension in ["com", "exe"] {- let mut candidate = executable.clone();- if bytes.last() != Some(&b'.') {- candidate.push(".");- }- candidate.push(extension);- candidates.push(candidate);- }- if let Some(candidate) = candidates- .into_iter()- .find(|path| Path::new(path).is_file())- {- executable = std::env::current_dir()?.join(candidate).into_os_string();- }+ let application = resolve_windows_executable(&executable)?;+ // CreateProcessW can dispatch batch files through a shell without CRT escaping.+ if windows_batch_file(&application) {+ return Err(io::Error::from_raw_os_error(ERROR_INVALID_PARAMETER as i32));}let raw_job = unsafe { CreateJobObjectW(null(), null()) };if raw_job.is_null() {@@ -382,27 +460,8 @@ pub fn run_windows_process(// process exit, so descendants inherit membership before they can run.// Closing the handle on return would terminate the shim before reporting status.std::mem::forget(job);- // Rust otherwise prefers a sibling .com.exe over an explicitly selected .com.- let path = Path::new(&executable);- let bytes = executable.as_encoded_bytes();- if path.file_name() != Some(executable.as_os_str())- && bytes[bytes.len().saturating_sub(4)..].eq_ignore_ascii_case(b".com")- {- return run_exact_com_process(&executable, &arguments);- }- let mut command = Command::new(executable);- // Explicit PATH is searched before the shim's executable and system directories.- if let Some(path) = std::env::var_os("PATH") {- command.env("PATH", path);- }- command.args(arguments);- Ok(command- .stdin(Stdio::inherit())- .stdout(Stdio::inherit())- .stderr(Stdio::inherit())- .status()?- .code()- .unwrap_or(1))+ // Launch the selected image without Rust performing another extension search.+ run_exact_process(&application, &executable, &arguments)}match run(executable, arguments, cwd, environment) {Ok(status) => Ok(WindowsProcessResult {diff --git a/plugins/codex-security/native/windows-process.mts b/plugins/codex-security/native/windows-process.mtsindex 3f343e4e3..eeb7efdf0 100644--- a/plugins/codex-security/native/windows-process.mts+++ b/plugins/codex-security/native/windows-process.mts@@ -33,9 +33,22 @@ export function spawnWindowsProcess(const inherited = options.env ?? process.env;const env: NodeJS.ProcessEnv = Object.create(null);for (const name in inherited) env[name] = inherited[name];- // Target preloads, diagnostics, and certificates must not affect the private shim.+ // Node forwards parent coverage even when an explicit env omits it.+ const coverage = process.env["NODE_V8_COVERAGE"];+ if (+ coverage &&+ (!options.env || !Object.hasOwn(options.env, "NODE_V8_COVERAGE"))+ )+ env["NODE_V8_COVERAGE"] = coverage;+ // Target startup settings must not affect the private shim.const targetEnvironment: Record<string, string> = {};- for (const key of ["NODE_OPTIONS", "NODE_DEBUG", "NODE_EXTRA_CA_CERTS"]) {+ for (const key of [+ "NODE_OPTIONS",+ "NODE_DEBUG",+ "NODE_DEBUG_NATIVE",+ "NODE_EXTRA_CA_CERTS",+ "NODE_V8_COVERAGE",+ ]) {// Windows keeps the first lexicographic spelling of a duplicated env key.const names = Object.keys(env).filter((name) => name.toUpperCase() === key)@@ -45,6 +58,8 @@ export function spawnWindowsProcess(targetEnvironment[name] = env[name];for (const name of names) delete env[name];}+ // An own undefined entry prevents Node from forwarding coverage to the shim again.+ env["NODE_V8_COVERAGE"] = undefined;Object.assign(targetEnvironment, environment);const payload = {binary,