From e588bcd7fdc0263b74f2972eebd0b68964b8e686 Mon Sep 17 00:00:00 2001 From: Michael D'Angelo Date: Mon, 9 Nov 2026 22:32:37 -0800 Subject: [PATCH 01/28] fix(sdk): register local marketplaces in Codex homes containing a hash (#2547) --- sdk/typescript/src/runtime.ts | 46 +++++++++++++------ .../codex-process-cancellation.test.ts | 2 +- sdk/typescript/tests-ts/runtime.test.ts | 19 ++++++++ 3 files changed, 52 insertions(+), 15 deletions(-) diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.ts index 301b5ebb1..5d0752907 100644 --- a/sdk/typescript/src/runtime.ts +++ b/sdk/typescript/src/runtime.ts @@ -2042,11 +2042,13 @@ export async function runWorkbench( ) : input, signal, - registrationHandshake, - // Frame Python arguments on stdin to preserve NUL and long diagnostics. - native - ? undefined - : `${JSON.stringify(arguments_.map((argument) => argument.toWellFormed()))}\n`, + { + registrationHandshake, + // Frame Python arguments on stdin to preserve NUL and long diagnostics. + stdinPrefix: native + ? undefined + : `${JSON.stringify(arguments_.map((argument) => argument.toWellFormed()))}\n`, + }, ); if (!result.success) { throw new Error( @@ -3822,8 +3824,15 @@ export async function runCodexCommand( environment: ProcessEnvironment, input?: string | Uint8Array, signal?: AbortSignal, - registrationHandshake = false, - stdinPrefix?: string, + { + registrationHandshake = false, + stdinPrefix, + cwd, + }: { + registrationHandshake?: boolean; + stdinPrefix?: string; + cwd?: string; + } = {}, ): Promise { const cancellation = registrationHandshake ? new AbortController() @@ -3834,6 +3843,7 @@ export async function runCodexCommand( executablePathForSpawn(command.command), [...(command.args ?? []), ...args], { + cwd, env: environment, stdio: registrationHandshake ? ["pipe", "pipe", "pipe", "pipe"] @@ -3967,13 +3977,21 @@ async function runPluginCommand( signal?: AbortSignal, ): Promise { try { - const { success, exitCode, stdout, stderr } = await runCodexCommand( - command, - args, - environment, - undefined, - signal, - ); + const run = (argv: readonly string[], cwd?: string) => + runCodexCommand(command, argv, environment, undefined, signal, { cwd }); + let result = await run(args); + const source = args[1] === "marketplace" ? args[3] : undefined; + if ( + result.exitCode === 1 && + source?.includes("#") && + result.stderr + .split(/\r?\n/u) + .includes("Error: --ref is only supported for git marketplace sources") + ) { + // Native Codex parsed a literal hash in the local path as a Git ref. + result = await run(["plugin", "marketplace", "add", "."], source); + } + const { success, exitCode, stdout, stderr } = result; if (!success) { const detail = stderr.trim() || diff --git a/sdk/typescript/tests-ts/codex-process-cancellation.test.ts b/sdk/typescript/tests-ts/codex-process-cancellation.test.ts index 2702bff76..5bb4420f7 100644 --- a/sdk/typescript/tests-ts/codex-process-cancellation.test.ts +++ b/sdk/typescript/tests-ts/codex-process-cancellation.test.ts @@ -125,7 +125,7 @@ for (const mode of [ }, undefined, controller.signal, - mode.startsWith("archive-"), + { registrationHandshake: mode.startsWith("archive-") }, ); } finally { observer.mockRestore(); diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.ts index 1a2b66263..d69e6ad17 100644 --- a/sdk/typescript/tests-ts/runtime.test.ts +++ b/sdk/typescript/tests-ts/runtime.test.ts @@ -907,6 +907,25 @@ describe("plugin runtime preparation", () => { ).toBeDefined(); }); + test("installs a local marketplace when the Codex home contains a literal hash", async () => { + const root = await temporaryDirectory(); + const home = join(root, "codex #team"); + const source = await bundledPluginRoot(); + const installed = await bootstrapPlugin(home, source, { + environment: { + HOME: root, + USERPROFILE: root, + PATH: process.env["PATH"], + SystemRoot: process.env["SystemRoot"], + }, + }); + + const manifest = join(".codex-plugin", "plugin.json"); + expect( + await readFile(join(installed.installedRoot, manifest), "utf8"), + ).toBe(await readFile(join(source, manifest), "utf8")); + }); + test("keeps local marketplace failures separate from installer failures", async () => { const root = await temporaryDirectory(); const selected = await plugin(root); From 9161e1adbccf7f971c2a225f0c13faac21846b1a Mon Sep 17 00:00:00 2001 From: Michael D'Angelo Date: Mon, 9 Nov 2026 22:52:19 -0800 Subject: [PATCH 02/28] fix(sdk): preserve whitespace in POSIX state directory overrides (#2548) --- sdk/typescript/src/runtime.ts | 6 +++++- sdk/typescript/tests-ts/runtime.test.ts | 13 +++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.ts index 5d0752907..7d6ae9731 100644 --- a/sdk/typescript/src/runtime.ts +++ b/sdk/typescript/src/runtime.ts @@ -244,7 +244,11 @@ function environmentValue( export function codexSecurityStateDirectory( environment: ProcessEnvironment = process.env, ): string { - const configured = environmentValue(environment, "CODEX_SECURITY_STATE_DIR"); + const configured = environmentValue( + environment, + "CODEX_SECURITY_STATE_DIR", + process.platform !== "win32", + ); const path = configured !== undefined ? resolve(expandHome(configured, environment)) diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.ts index d69e6ad17..7fb339293 100644 --- a/sdk/typescript/tests-ts/runtime.test.ts +++ b/sdk/typescript/tests-ts/runtime.test.ts @@ -5856,6 +5856,19 @@ describe("runtime directories and plugin Python boundary", () => { }, ); + test.skipIf(process.platform === "win32")( + "preserves trailing whitespace in an explicit POSIX state directory", + async () => { + const root = await temporaryDirectory(); + for (const suffix of [" ", "\u00a0"]) { + const state = join(root, `explicit-state${suffix}`); + expect( + codexSecurityStateDirectory({ CODEX_SECURITY_STATE_DIR: state }), + ).toBe(state); + } + }, + ); + test("derives persistent state from the ambient home or explicit override", async () => { const root = await temporaryDirectory(); expect(codexSecurityStateDirectory({ CODEX_HOME: root })).toBe( From 9792d360be927a07c7963e879cc42cc806214581 Mon Sep 17 00:00:00 2001 From: Michael D'Angelo Date: Mon, 9 Nov 2026 22:54:33 -0800 Subject: [PATCH 03/28] fix(container): record the Wolfi Canvas 1.1.0 source and Skia notice (#2549) --- docker/wolfi/build-inputs.json | 2 +- docker/wolfi/payload/native-sources.json | 1 + docker/wolfi/payload/notices/SKIA-LICENSE | 29 +++++++++++++++++++++++ docker/wolfi/payload/notices/sources.json | 4 ++++ 4 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 docker/wolfi/payload/notices/SKIA-LICENSE diff --git a/docker/wolfi/build-inputs.json b/docker/wolfi/build-inputs.json index 9bca3a944..d333f2e95 100644 --- a/docker/wolfi/build-inputs.json +++ b/docker/wolfi/build-inputs.json @@ -3,7 +3,7 @@ "wolfi_key_sha256": "f0031424cf46f7db780ce63a45f0fd6aa6f85f601e6bb3b7a91fe3d4d5b7d2cc", "repository": "https://packages.wolfi.dev/os", "local_package": "codex-security=0.7.0-r1", - "payload_sha256": "db42f7b5b4d0bfc79975e38778ece88d02d31887a262f8a5c0e5bdfdbbe3563d", + "payload_sha256": "3e8c94eb8ff8ff4d041722d133e059aeffd9084a73fc63a1f3b1670e879c9ab9", "image_revision": 0, "snapshots": { "builder": { diff --git a/docker/wolfi/payload/native-sources.json b/docker/wolfi/payload/native-sources.json index d21a05dfb..1e9bdc331 100644 --- a/docker/wolfi/payload/native-sources.json +++ b/docker/wolfi/payload/native-sources.json @@ -3,6 +3,7 @@ "@openai/codex@0.165.0-linux-x64": "https://github.com/openai/codex/tree/360319d8dee62d87e2d59fc0c21805d79519cfed", "@napi-rs/canvas-linux-x64-gnu@1.0.10": "https://github.com/Brooooooklyn/canvas/tree/7d19abed029287e7c26b14eaa6e67d560a37d853", "@napi-rs/canvas-linux-x64-gnu@1.0.13": "https://github.com/Brooooooklyn/canvas/tree/00a115d9903647f116daf86eccd2c6ba36128371", + "@napi-rs/canvas-linux-x64-gnu@1.1.0": "https://github.com/Brooooooklyn/canvas/tree/5246bbf5573fdf53b5672a4d096d4d8fa660a406", "@openai/codex@0.166.0-linux-x64": "https://github.com/openai/codex/tree/6ff1e1ca3b30fc8b914720681fcf5fe62e95f856", "@openai/codex@0.167.0-linux-x64": "https://github.com/openai/codex/tree/086ccc833bc9cf01024ad2dd6af7dbd421b6bf9a" } diff --git a/docker/wolfi/payload/notices/SKIA-LICENSE b/docker/wolfi/payload/notices/SKIA-LICENSE new file mode 100644 index 000000000..e32636d56 --- /dev/null +++ b/docker/wolfi/payload/notices/SKIA-LICENSE @@ -0,0 +1,29 @@ +Copyright (c) 2011 Google Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + + * Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/docker/wolfi/payload/notices/sources.json b/docker/wolfi/payload/notices/sources.json index 1acac77d0..ac2defb2f 100644 --- a/docker/wolfi/payload/notices/sources.json +++ b/docker/wolfi/payload/notices/sources.json @@ -23,6 +23,10 @@ "source": "https://raw.githubusercontent.com/scalar/scalar/71c72fbc1c3860ac741812617057141db2033fcd/LICENSE", "sha256": "380cd0a6ad700e1f821f2a509f0dd9ff835041cee2d43daf5dedc1adb2bcc620" }, + "SKIA-LICENSE": { + "source": "https://raw.githubusercontent.com/google/skia/b94213a11b3a2edadfae89f0c57a7f4ab72772c9/LICENSE", + "sha256": "5f787c1dee3c56547f09ccc2906ab5f5293c4d8dd6c8654e573216c38e908dbd" + }, "YOGA-LICENSE": { "source": "https://raw.githubusercontent.com/react/yoga/042f5013152eb81c1552dec945b88f7b95ca350f/LICENSE", "sha256": "52412d7bc7ce4157ea628bbaacb8829e0a9cb3c58f57f99176126bc8cf2bfc85" From cd47bb2b98ab3676a4d2b5389f1f64000c171ea0 Mon Sep 17 00:00:00 2001 From: Michael D'Angelo Date: Mon, 9 Nov 2026 23:40:46 -0800 Subject: [PATCH 04/28] fix(plugin): preserve trailing whitespace in POSIX scan roots (#2552) --- .../mcp-app/src/workbench-client.ts | 8 +++- .../mcp-app/tests/test_artifact_storage.ts | 39 +++++++++++++------ .../tests/test_deep_scan_stdio_lifecycle.ts | 5 ++- .../references/artifact-storage.md | 2 +- 4 files changed, 39 insertions(+), 15 deletions(-) diff --git a/plugins/codex-security/mcp-app/src/workbench-client.ts b/plugins/codex-security/mcp-app/src/workbench-client.ts index 983d87f58..cb509af73 100644 --- a/plugins/codex-security/mcp-app/src/workbench-client.ts +++ b/plugins/codex-security/mcp-app/src/workbench-client.ts @@ -10,7 +10,13 @@ import { import { WORKBENCH_PYTHON } from "./server/workbench-process.js"; const execFileAsync = promisify(execFile); -const CONFIGURED_SCAN_ROOT = process.env.CODEX_SECURITY_SCAN_ROOT?.trim(); +const configuredScanRoot = process.env.CODEX_SECURITY_SCAN_ROOT; +// A padded absolute or home-relative override must keep its original base. +const CONFIGURED_SCAN_ROOT = + process.platform !== "win32" && + configuredScanRoot?.trimStart() === configuredScanRoot + ? configuredScanRoot + : configuredScanRoot?.trim(); export const PLUGIN_ROOT = process.env.CODEX_SECURITY_PLUGIN_ROOT || resolve(__dirname, ".."); diff --git a/plugins/codex-security/mcp-app/tests/test_artifact_storage.ts b/plugins/codex-security/mcp-app/tests/test_artifact_storage.ts index 6d545cd5a..b40255ec4 100644 --- a/plugins/codex-security/mcp-app/tests/test_artifact_storage.ts +++ b/plugins/codex-security/mcp-app/tests/test_artifact_storage.ts @@ -365,18 +365,33 @@ try { content, ); - await client.close(); - client = await connect({ - CODEX_SECURITY_SCAN_ROOT: path.join(stateAlias, "missing", "scans"), - }); - const relocated = await save({ - targetPath: repository, - storage: "persistent", - }); - assert.ok( - relocated.directory.startsWith( - path.join(stateRoot, "missing", "scans") + path.sep, - ), + const rootName = process.platform === "win32" ? "scans" : "scans "; + for (const [configured, expected] of [ + [ + path.join(stateAlias, "missing", rootName), + path.join(stateRoot, "missing", rootName), + ], + [ + ` ${path.join(stateAlias, "padded", "scans")} `, + path.join(stateRoot, "padded", "scans"), + ], + ]) { + await client.close(); + client = await connect({ CODEX_SECURITY_SCAN_ROOT: configured }); + const relocated = await save({ + targetPath: repository, + storage: "persistent", + }); + assert.ok(relocated.directory.startsWith(expected + path.sep)); + } + if (process.platform !== "win32") + await assert.rejects(stat(path.join(stateRoot, "missing", "scans")), { + code: "ENOENT", + }); + assert.equal( + (await read({ ...identity, storage: "persistent", path: relativePath })) + .content, + content, ); const linkedScanRoot = path.join(fixture, "linked-scans"); diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_stdio_lifecycle.ts b/plugins/codex-security/mcp-app/tests/test_deep_scan_stdio_lifecycle.ts index 759ec571b..6476ba7fc 100644 --- a/plugins/codex-security/mcp-app/tests/test_deep_scan_stdio_lifecycle.ts +++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_stdio_lifecycle.ts @@ -56,6 +56,7 @@ async function testDeepScanStdioLifecycle() { const failedTargetPath = path.join(fixtureRoot, "failed-target"); const expiredTargetPath = path.join(fixtureRoot, "expired-target"); const stateDir = path.join(fixtureRoot, "state]"); + const scanRoot = path.join(await realpath(fixtureRoot), "scans "); const codexHome = path.join(fixtureRoot, "codex [home]"); const installedPluginRoot = path.join(codexHome, "plugins", "installed"); const runtimeConfigPath = path.join(fixtureRoot, "active-config.toml"); @@ -192,7 +193,7 @@ service_tier = "ultrafast" CODEX_HOME: codexHome, CODEX_SECURITY_CONFIG_PATH: runtimeConfigPath, CODEX_SECURITY_PLUGIN_ROOT: pluginRoot, - CODEX_SECURITY_SCAN_ROOT: path.join(fixtureRoot, "scans"), + CODEX_SECURITY_SCAN_ROOT: scanRoot, CODEX_SECURITY_STATE_DIR: stateDir, PYTHON: pythonWrapperPath, CODEX_SECURITY_PYTHON_COMMAND: pythonWrapperPath, @@ -343,6 +344,7 @@ service_tier = "ultrafast" assert.match(startedWorker.stdin, /record_codex_security_scan_draft/); const startedState = await getDeepScan({ environment, scanId, threadId }); assert.equal(startedState.config.maxTimeHours, 0.5); + assert.ok(startedState.scanDir.startsWith(scanRoot + path.sep)); await rm(projectConfigPath); const startedArtifactRoot = startedState.workers.find( (worker: PersistedDeepScanWorker) => worker.kind === "discovery", @@ -774,6 +776,7 @@ service_tier = "ultrafast" ); const resumedScan = started.structuredContent.workspace.results; const resumedScanId = resumedScan.scanId; + assert.ok(resumedScan.scanDir.startsWith(scanRoot + path.sep)); await chmod(resumedScan.scanDir, 0o755); const handoffClaimToken = randomUUID(); for (const [id, name, arguments_] of [ diff --git a/plugins/codex-security/references/artifact-storage.md b/plugins/codex-security/references/artifact-storage.md index 5c6401505..7a013be8d 100644 --- a/plugins/codex-security/references/artifact-storage.md +++ b/plugins/codex-security/references/artifact-storage.md @@ -22,7 +22,7 @@ Select `storage` explicitly: - `persistent`: retained documents/evidence under the authoritative scan directory or standalone collection. The default root is `$CODEX_SECURITY_STATE_DIR/scans`, or `$CODEX_HOME/state/plugins/codex-security/scans` when no state override is set; `CODEX_HOME` defaults to `~/.codex`. The existing `CODEX_SECURITY_SCAN_ROOT` override still takes precedence for plugin-created output. The workbench state directory must be writable; set `CODEX_SECURITY_STATE_DIR` explicitly on hosts with an unwritable default. Preserve an existing scan's saved path, including older temporary paths. - `temporary`: disposable staging and execution output in a context-specific OS temporary directory. Standalone temporary saves and reads do not create or require the persistent collection. It is not part of the completed result and must not be referenced from canonical findings or coverage. It can disappear independently of retained files. -Relative storage overrides resolve from the plugin directory, matching the workbench, regardless of the MCP launch directory. +Relative storage overrides resolve from the plugin directory, matching the workbench, regardless of the MCP launch directory. On POSIX, `CODEX_SECURITY_SCAN_ROOT` preserves trailing whitespace. A value with leading padding is trimmed. Use an absolute path or a `./` prefix for a relative directory name that begins with whitespace. Omit `path`, `content` and `sourcePath` to prepare the selected directory. Use the returned `directory`; never construct or guess the physical path. A save with a file requires `path` plus exactly one of `content` or `sourcePath`. From a0fedec4cad849eac39c443e1e427c87ab29e55e Mon Sep 17 00:00:00 2001 From: Michael D'Angelo Date: Tue, 10 Nov 2026 00:14:26 -0800 Subject: [PATCH 05/28] fix(runtime): honor literal POSIX executable override paths (#2551) * fix(runtime): honor literal POSIX executable override paths * fix(runtime): retain the lookup origin of padded executable paths * fix(runtime): keep bare executable overrides on their original lookup path --- .../mcp-app/src/deep-scan/executor.ts | 27 +++----- .../mcp-app/src/executable-path.ts | 36 ++++++++++ .../mcp-app/src/python_command.ts | 22 ++++-- .../mcp-app/src/workbench-client.ts | 4 +- .../tests/deep_scan_executable_cases.ts | 32 ++++++++- .../mcp-app/tests/test_python_command.ts | 48 ++++++++++++- sdk/typescript/docs/cli.md | 4 ++ sdk/typescript/src/executable-path.ts | 36 ++++++++++ sdk/typescript/src/runtime.ts | 32 +++++++-- sdk/typescript/tests-ts/runtime.test.ts | 67 +++++++++++++++++++ 10 files changed, 278 insertions(+), 30 deletions(-) diff --git a/plugins/codex-security/mcp-app/src/deep-scan/executor.ts b/plugins/codex-security/mcp-app/src/deep-scan/executor.ts index 07df96f20..7686d9f66 100644 --- a/plugins/codex-security/mcp-app/src/deep-scan/executor.ts +++ b/plugins/codex-security/mcp-app/src/deep-scan/executor.ts @@ -1,8 +1,6 @@ import { randomUUID } from "node:crypto"; import { - accessSync, type BigIntStats, - constants as fsConstants, existsSync, promises as fs, readdirSync, @@ -33,7 +31,11 @@ import { profileConfigOverrides, } from "../../../scripts/codex_profile.mjs"; import { DEEP_SCAN_SETTINGS } from "../deep-scan-settings.js"; -import { executablePathForSpawn } from "../executable-path.js"; +import { + configuredExecutableValue, + executablePathForSpawn, + isExecutableFile, +} from "../executable-path.js"; import { writePrivateFile } from "./artifacts.js"; import { workerTokenUsage } from "./usage-receipt.js"; import { @@ -1053,11 +1055,12 @@ export function resolveCodexPath( originalCwd: string = process.cwd(), ): string { const searchPath = searchPathForPlatform(env, platform); - const configured = environmentVariable( - env, - "CODEX_CLI_PATH", + const configured = configuredExecutableValue( + environmentVariable(env, "CODEX_CLI_PATH", platform), platform, - )?.trim(); + (value) => + isExecutableFile(absoluteCodexPath(value, platform, originalCwd)), + ); if (configured && (platform !== "win32" || !isWindowsAppsPath(configured))) { if (isBareCommandName(configured)) { const executableName = @@ -1256,16 +1259,6 @@ function resolveWindowsCachedBinary( return selected?.path; } -function isExecutableFile(value: string): boolean { - try { - if (!statSync(value).isFile()) return false; - accessSync(value, fsConstants.X_OK); - return true; - } catch { - return false; - } -} - function absoluteCodexPath( value: string, platform: NodeJS.Platform, diff --git a/plugins/codex-security/mcp-app/src/executable-path.ts b/plugins/codex-security/mcp-app/src/executable-path.ts index 11eeeec04..5733ebb2b 100644 --- a/plugins/codex-security/mcp-app/src/executable-path.ts +++ b/plugins/codex-security/mcp-app/src/executable-path.ts @@ -1,3 +1,4 @@ +import { accessSync, constants, statSync } from "node:fs"; import { win32 } from "node:path"; export function executablePathForSpawn(command: string): string { @@ -9,3 +10,38 @@ export function executablePathForSpawn(command: string): string { ? command : win32.toNamespacedPath(command); } + +export function isExecutableFile(value: string): boolean { + try { + if (!statSync(value).isFile()) return false; + accessSync(value, constants.X_OK); + return true; + } catch { + return false; + } +} + +export function isExplicitPathWithTrailingWhitespace( + value: string, + platform: NodeJS.Platform, +): boolean { + // Bare names keep their usual PATH precedence. Leading padding can change the path's root. + return ( + platform !== "win32" && + value.includes("/") && + value.trimStart() === value && + value.trimEnd() !== value + ); +} + +export function configuredExecutableValue( + value: string | undefined, + platform: NodeJS.Platform, + literalIsExecutable: (value: string) => boolean, +): string | undefined { + return value && + isExplicitPathWithTrailingWhitespace(value, platform) && + literalIsExecutable(value) + ? value + : value?.trim(); +} diff --git a/plugins/codex-security/mcp-app/src/python_command.ts b/plugins/codex-security/mcp-app/src/python_command.ts index db7675598..c3eaae412 100644 --- a/plugins/codex-security/mcp-app/src/python_command.ts +++ b/plugins/codex-security/mcp-app/src/python_command.ts @@ -2,6 +2,10 @@ import { spawn } from "node:child_process"; import { constants, promises as fs } from "node:fs"; import { homedir } from "node:os"; import path from "node:path"; +import { + configuredExecutableValue, + isExecutableFile, +} from "./executable-path.ts"; type PythonPlatform = NodeJS.Platform; @@ -11,6 +15,7 @@ interface ResolvePythonCommandOptions { homeDirectory?: string; isUsableExecutable?: (candidate: string) => Promise; platform?: PythonPlatform; + workingDirectory?: string; } const MISSING_PYTHON_HELPER_MESSAGE = @@ -29,12 +34,19 @@ export async function resolvePythonCommand( ) { return process.env.CODEX_SECURITY_PYTHON_COMMAND; } - const configuredPython = options.configuredPython ?? process.env.PYTHON; - if (configuredPython?.trim()) { - return configuredPython.trim(); - } - const platform = options.platform ?? process.platform; + const configuredPython = configuredExecutableValue( + options.configuredPython ?? process.env.PYTHON, + platform, + (value) => + isExecutableFile( + value.startsWith("/") + ? value + : `${options.workingDirectory ?? process.cwd()}/${value}`, + ), + ); + if (configuredPython) return configuredPython; + const pathImplementation = platform === "win32" ? path.win32 : path.posix; const systemPython = platform === "win32" ? "python" : "python3"; let cacheDirectory = options.cacheDirectory ?? process.env.XDG_CACHE_HOME; diff --git a/plugins/codex-security/mcp-app/src/workbench-client.ts b/plugins/codex-security/mcp-app/src/workbench-client.ts index cb509af73..96a46f5d6 100644 --- a/plugins/codex-security/mcp-app/src/workbench-client.ts +++ b/plugins/codex-security/mcp-app/src/workbench-client.ts @@ -41,7 +41,9 @@ export async function runWorkbench( ): Promise { let pythonCommand: string | undefined; try { - pythonCommand = await resolvePythonCommand(); + pythonCommand = await resolvePythonCommand({ + workingDirectory: PLUGIN_ROOT, + }); return await executeWorkbench(pythonCommand, args, input, options); } catch (error) { const launchError = pythonCommand diff --git a/plugins/codex-security/mcp-app/tests/deep_scan_executable_cases.ts b/plugins/codex-security/mcp-app/tests/deep_scan_executable_cases.ts index 5f0baf339..6e4f4cf85 100644 --- a/plugins/codex-security/mcp-app/tests/deep_scan_executable_cases.ts +++ b/plugins/codex-security/mcp-app/tests/deep_scan_executable_cases.ts @@ -7,6 +7,7 @@ import { realpath, rename, rm, + symlink, writeFile, } from "node:fs/promises"; import { syncBuiltinESMExports } from "node:module"; @@ -177,6 +178,35 @@ export async function testExecutorExecutablePinning({ () => new CodexSdkWorkerExecutor({ parentSandbox }), ); try { + const configuredPaths = fixtures.map((fixture) => fixture.executablePath); + if (process.platform !== "win32") { + const alias = path.join( + fixtures[0]!.root, + "codex with trailing space ", + ); + await symlink(fixtures[0]!.executablePath, alias); + configuredPaths[0] = alias; + const other = fixtures[1]!.executablePath; + const bare = path.basename(other) + " "; + await symlink( + fixtures[0]!.executablePath, + path.join(fixtures[0]!.root, bare), + ); + assert.equal( + resolveCodexPath( + { + PATH: [path.dirname(other), fixtures[0]!.root].join( + path.delimiter, + ), + CODEX_CLI_PATH: bare, + }, + process.platform, + process.arch, + fixtures[0]!.root, + ), + other, + ); + } for (const fixture of fixtures) { await writeFile( path.join(fixture.root, "prompt.md"), @@ -188,7 +218,7 @@ export async function testExecutorExecutablePinning({ await Promise.all( fixtures.map((fixture, index) => { process.env.CODEX_CLI_PATH = - fixtures[firstLaunch ? index : 1 - index]!.executablePath; + configuredPaths[firstLaunch ? index : 1 - index]!; process.env.FAKE_CODEX_MARKER = fixture.markerPath; return runTurn( executors[index]!, diff --git a/plugins/codex-security/mcp-app/tests/test_python_command.ts b/plugins/codex-security/mcp-app/tests/test_python_command.ts index 990c8e5eb..4af57cf6e 100644 --- a/plugins/codex-security/mcp-app/tests/test_python_command.ts +++ b/plugins/codex-security/mcp-app/tests/test_python_command.ts @@ -177,8 +177,54 @@ try { ); const resolvedPython = process.platform === "win32" ? process.execPath : `${fileCandidate} `; - if (process.platform !== "win32") + if (process.platform !== "win32") { await symlink(process.execPath, resolvedPython); + assert.equal( + await resolvePythonCommand({ configuredPython: resolvedPython }), + resolvedPython, + ); + assert.equal( + await resolvePythonCommand({ + configuredPython: "./python3 ", + workingDirectory: executableFixtureRoot, + }), + "./python3 ", + ); + const paddedAbsolute = ` ${fileCandidate} `; + const shadow = path.join(executableFixtureRoot, paddedAbsolute); + await mkdir(path.dirname(shadow), { recursive: true }); + await symlink(process.execPath, shadow); + assert.equal( + await resolvePythonCommand({ + configuredPython: paddedAbsolute, + workingDirectory: executableFixtureRoot, + }), + fileCandidate, + ); + const trusted = path.join(executableFixtureRoot, "tools"); + await mkdir(trusted); + await writeFile( + path.join(trusted, "python3"), + "#!/bin/sh\n/bin/cat >/dev/null\nprintf trusted", + { + mode: 0o700, + }, + ); + const previousPath = process.env.PATH; + try { + process.env.PATH = [trusted, executableFixtureRoot].join(path.delimiter); + const command = await resolvePythonCommand({ + configuredPython: "python3 ", + }); + assert.equal( + await runPythonWithInput(command, [], "", "fixture"), + "trusted", + ); + } finally { + if (previousPath === undefined) delete process.env.PATH; + else process.env.PATH = previousPath; + } + } process.env.PYTHON = ` ${fileCandidate} `; process.env.CODEX_SECURITY_PYTHON_COMMAND = resolvedPython; assert.equal(await resolvePythonCommand(), resolvedPython); diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.md index 4e0c4d594..c233e6882 100644 --- a/sdk/typescript/docs/cli.md +++ b/sdk/typescript/docs/cli.md @@ -1113,6 +1113,10 @@ Python lookup: `--python` on commands that expose interpreter selection or SDK `pythonPath`, then `PYTHON`, the managed runtime, and `python3` or `python` on `PATH` (`py` also works on Windows). `CODEX_SECURITY_STATE_DIR` overrides `CODEX_HOME` for storage. +On POSIX, `CODEX_CLI_PATH` and `PYTHON` preserve trailing whitespace in an +explicit path that selects an executable. Use an absolute path or a `./` +prefix for filenames beginning or ending in whitespace. Bare command names +are trimmed before lookup. ### Troubleshooting diff --git a/sdk/typescript/src/executable-path.ts b/sdk/typescript/src/executable-path.ts index 6bd72d108..83c525a73 100644 --- a/sdk/typescript/src/executable-path.ts +++ b/sdk/typescript/src/executable-path.ts @@ -1,4 +1,5 @@ /* Generated from plugin executable-path.ts. Run `pnpm generate:models`. */ +import { accessSync, constants, statSync } from "node:fs"; import { win32 } from "node:path"; export function executablePathForSpawn(command: string): string { @@ -10,3 +11,38 @@ export function executablePathForSpawn(command: string): string { ? command : win32.toNamespacedPath(command); } + +export function isExecutableFile(value: string): boolean { + try { + if (!statSync(value).isFile()) return false; + accessSync(value, constants.X_OK); + return true; + } catch { + return false; + } +} + +export function isExplicitPathWithTrailingWhitespace( + value: string, + platform: NodeJS.Platform, +): boolean { + // Bare names keep their usual PATH precedence. Leading padding can change the path's root. + return ( + platform !== "win32" && + value.includes("/") && + value.trimStart() === value && + value.trimEnd() !== value + ); +} + +export function configuredExecutableValue( + value: string | undefined, + platform: NodeJS.Platform, + literalIsExecutable: (value: string) => boolean, +): string | undefined { + return value && + isExplicitPathWithTrailingWhitespace(value, platform) && + literalIsExecutable(value) + ? value + : value?.trim(); +} diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.ts index 7d6ae9731..67092898b 100644 --- a/sdk/typescript/src/runtime.ts +++ b/sdk/typescript/src/runtime.ts @@ -1,4 +1,9 @@ -import { executablePathForSpawn } from "./executable-path.js"; +import { + configuredExecutableValue, + executablePathForSpawn, + isExplicitPathWithTrailingWhitespace, + isExecutableFile, +} from "./executable-path.js"; import { retryWindowsRename } from "./retry-windows-rename.js"; export { executablePathForSpawn } from "./executable-path.js"; import { @@ -3202,7 +3207,11 @@ async function pluginRuntimeProjection( export function resolveCodexCommand( environment: ProcessEnvironment = process.env, ): CodexCommand { - const configured = environmentValue(environment, "CODEX_CLI_PATH"); + const configured = configuredExecutableValue( + environmentValue(environment, "CODEX_CLI_PATH", true), + process.platform, + (value) => isExecutableFile(expandHomeForLookup(value, environment)), + ); const expanded = configured === undefined ? undefined @@ -3683,13 +3692,26 @@ export async function resolvePluginPython( options.signal, ); } - const inherited = environmentValue(environment, "PYTHON"); + const inherited = environmentValue(environment, "PYTHON", true); if (inherited) { + const roots = isPythonPathCandidate(inherited) + ? protectedRoot + : discoveryRoots; + // Check an explicit literal path with the same repository protections as the launch. + const candidate = + isExplicitPathWithTrailingWhitespace(inherited, process.platform) && + (await resolveTrustedExecutable( + expandHomeForLookup(inherited, environment), + environment, + roots, + )) + ? inherited + : inherited.trim(); return await requirePython( - inherited, + candidate, "PYTHON", environment, - isPythonPathCandidate(inherited) ? protectedRoot : discoveryRoots, + roots, options.signal, ); } diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.ts index 7fb339293..00686838d 100644 --- a/sdk/typescript/tests-ts/runtime.test.ts +++ b/sdk/typescript/tests-ts/runtime.test.ts @@ -6966,6 +6966,73 @@ describe("runtime directories and plugin Python boundary", () => { } }); + testPosix( + "preserves literal executable override names and accepts padding", + async () => { + const tools = await realpath(await temporaryDirectory()); + const repository = await temporaryDirectory(); + const interpreter = pythonWithLauncher(); + expect(interpreter).not.toBeNull(); + const ordinary = join(tools, "tool"); + const literal = ordinary + " "; + await symlink(interpreter!, ordinary); + await symlink(interpreter!, literal); + + for (const [configured, expected] of [ + [literal, literal], + [` ${ordinary} `, ordinary], + ] as const) { + expect( + resolveCodexCommand({ CODEX_CLI_PATH: configured }).command, + ).toBe(expected); + await expect( + resolvePluginPython({ + environment: { PYTHON: configured, PATH: tools }, + protectedRoot: repository, + }), + ).resolves.toBe(expected); + } + await expect( + resolvePluginPython({ + environment: { PYTHON: "tool ", PATH: tools }, + protectedRoot: repository, + }), + ).resolves.toBe(ordinary); + + const paddedAbsolute = ` ${ordinary} `; + const shadow = join(repository, paddedAbsolute); + await mkdir(dirname(shadow), { recursive: true }); + await writeFile(shadow, "#!/bin/sh\nexit 93\n", { mode: 0o700 }); + const runtime = new URL("../src/runtime.ts", import.meta.url).href; + const child = spawnSync( + process.execPath, + [ + "-e", + `import { resolveCodexCommand } from ${JSON.stringify(runtime)}; + import { spawnSync } from "node:child_process"; + const { command } = resolveCodexCommand(); + process.exit(spawnSync(command, ["-I", "-c", "pass"]).status ?? 1);`, + ], + { + cwd: repository, + env: { ...process.env, CODEX_CLI_PATH: paddedAbsolute }, + }, + ); + expect(child.status).toBe(0); + + await rm(literal); + expect(resolveCodexCommand({ CODEX_CLI_PATH: literal }).command).toBe( + ordinary, + ); + await expect( + resolvePluginPython({ + environment: { PYTHON: literal, PATH: tools }, + protectedRoot: repository, + }), + ).resolves.toBe(ordinary); + }, + ); + test("resolves inherited Python names case-insensitively", async () => { const discovered = pythonWithLauncher(); expect(discovered).not.toBeNull(); From 1c4431b36e6f5a597b4007353f6154a76e5ad5cd Mon Sep 17 00:00:00 2001 From: Michael D'Angelo Date: Tue, 10 Nov 2026 00:58:45 -0800 Subject: [PATCH 06/28] fix(workbench): preserve explicit usage database paths (#2556) * fix(workbench): preserve explicit usage database paths * test(workbench): close usage fixtures before renaming them * test(workbench): use supported database names on each host --- .../scripts/workbench_scan_usage.py | 6 +-- .../tests/test_workbench_scan_usage.py | 43 ++++++++++++++++++- 2 files changed, 45 insertions(+), 4 deletions(-) diff --git a/plugins/codex-security/scripts/workbench_scan_usage.py b/plugins/codex-security/scripts/workbench_scan_usage.py index 5af54fef4..f06df3788 100644 --- a/plugins/codex-security/scripts/workbench_scan_usage.py +++ b/plugins/codex-security/scripts/workbench_scan_usage.py @@ -607,9 +607,9 @@ def _scan_worker_directories( def _codex_state_database() -> Path | None: - configured_database = os.environ.get("CODEX_STATE_DB", "").strip() - if configured_database: - path = Path(configured_database).expanduser() + configured_database = os.environ.get("CODEX_STATE_DB", "") + if configured_database.strip(): + path = Path(os.path.expanduser(configured_database)) return path.resolve() if path.is_file() and os.access(path, os.R_OK) else None configured_home = os.environ.get("CODEX_HOME", "") diff --git a/plugins/codex-security/tests/test_workbench_scan_usage.py b/plugins/codex-security/tests/test_workbench_scan_usage.py index 3e51d5f2a..bf85a47d8 100644 --- a/plugins/codex-security/tests/test_workbench_scan_usage.py +++ b/plugins/codex-security/tests/test_workbench_scan_usage.py @@ -9,6 +9,7 @@ import subprocess import sys import tempfile import uuid +from contextlib import closing from dataclasses import dataclass, replace from datetime import datetime, timedelta from pathlib import Path @@ -328,7 +329,7 @@ def _state_graph( ) -> None: sqlite_home = Path(environment["CODEX_SQLITE_HOME"]) sqlite_home.mkdir(parents=True, exist_ok=True) - with sqlite3.connect(sqlite_home / "state_5.sqlite") as connection: + with closing(sqlite3.connect(sqlite_home / "state_5.sqlite")) as connection, connection: connection.execute( "CREATE TABLE threads " "(id TEXT PRIMARY KEY, rollout_path TEXT NOT NULL, cwd TEXT, created_at INTEGER)" @@ -1307,6 +1308,46 @@ def test_usage_finds_state_database_in_configured_home( assert scan_usage._codex_state_database() == database.resolve() +@pytest.mark.cross_platform +@pytest.mark.parametrize( + "spelling", + ["leading-relative", "trailing-absolute"] + + ([] if sys.platform == "win32" else ["literal-tilde"]), +) +def test_completion_reads_the_literal_usage_database( + tmp_path: Path, spelling: str, monkeypatch: pytest.MonkeyPatch +) -> None: + fixture = _start_scan(tmp_path) + counted = fixture.started_at + timedelta(microseconds=1) + fixture.write_parent_rollout([_token_event(counted, 18, 2)]) + original = Path(fixture.environment["CODEX_SQLITE_HOME"]) / "state_5.sqlite" + selected = ( + tmp_path + / { + "leading-relative": " usage.sqlite", + "trailing-absolute": "usage.sqlite\N{NO-BREAK SPACE}" + if sys.platform == "win32" + else "usage.sqlite ", + "literal-tilde": "~synthetic-usage.sqlite", + }[spelling] + ) + original.rename(selected) + + neighbor = tmp_path / "neighbor" + neighbor.mkdir() + other_rollout = _rollout(neighbor, "scan-parent", [_token_event(counted, 96, 2)]) + _state_graph(fixture.environment, {"scan-parent": other_rollout}, []) + original.rename(tmp_path / "usage.sqlite") + monkeypatch.chdir(tmp_path) + fixture.environment["CODEX_STATE_DB"] = ( + str(selected) if spelling == "trailing-absolute" else selected.name + ) + + usage = _complete_scan(fixture)["scan"]["usage"] + assert usage["coverage"] == "complete" + assert usage["totalTokens"] == 20 + + def test_completion_reports_unavailable_without_fabricating_zero(tmp_path: Path) -> None: fixture = _start_scan(tmp_path) usage = _complete_scan(fixture)["scan"]["usage"] From 337dd60c96237802a7cdc870034b65e892dafa20 Mon Sep 17 00:00:00 2001 From: Michael D'Angelo Date: Tue, 10 Nov 2026 01:19:23 -0800 Subject: [PATCH 07/28] fix(windows): grant scan workers explicit source read access (#2545) * fix(windows): configure explicit read access to scan sources * fix(windows): preserve source reads through MCP launch * test(mcp): expect repository environment forwarding --------- Co-authored-by: Codex --- plugins/codex-security/.mcp.json | 1 + .../mcp-app/src/deep-scan/executor.ts | 2 + .../mcp-app/src/deep-scan/parent-sandbox.ts | 32 +++-- .../mcp-app/tests/test_deep_scan_executor.ts | 6 + .../tests/test_deep_scan_parent_sandbox.ts | 29 +++++ .../mcp-app/tests/test_mcp_app_smoke.ts | 1 + sdk/typescript/src/api.ts | 23 +++- sdk/typescript/src/runtime.ts | 15 +-- sdk/typescript/tests-ts/api-policy.test.ts | 8 ++ .../tests-ts/api-runtime-storage.test.ts | 4 + .../tests-ts/api-validation.test.ts | 3 + .../runtime-mcp-source-environment.test.ts | 122 ++++++++++++++++++ sdk/typescript/tests-ts/runtime.test.ts | 28 ++-- 13 files changed, 245 insertions(+), 29 deletions(-) create mode 100644 sdk/typescript/tests-ts/runtime-mcp-source-environment.test.ts diff --git a/plugins/codex-security/.mcp.json b/plugins/codex-security/.mcp.json index ca6334d1f..f34c00d49 100644 --- a/plugins/codex-security/.mcp.json +++ b/plugins/codex-security/.mcp.json @@ -48,6 +48,7 @@ "CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH", "CODEX_SECURITY_SCAN_DIR", "CODEX_SECURITY_PLUGIN_ROOT", + "CODEX_SECURITY_REPOSITORY", "CODEX_SECURITY_SCAN_ROOT", "CODEX_SECURITY_STATE_DIR", "CODEX_SECURITY_SURFACE", diff --git a/plugins/codex-security/mcp-app/src/deep-scan/executor.ts b/plugins/codex-security/mcp-app/src/deep-scan/executor.ts index 7686d9f66..d212d18e9 100644 --- a/plugins/codex-security/mcp-app/src/deep-scan/executor.ts +++ b/plugins/codex-security/mcp-app/src/deep-scan/executor.ts @@ -612,6 +612,8 @@ function workerPermissionProfile( ]); if (sandbox.pluginReadRoot !== undefined) filesystem.set(sandbox.pluginReadRoot, { ".": "read" }); + if (sandbox.sourceReadRoot !== undefined) + filesystem.set(sandbox.sourceReadRoot, { ".": "read" }); for (const path of [...sandbox.filesystemDenies, ...literalDenies]) filesystem.set(path, "deny"); const pointDenies = literalDenies.filter((path) => /[*?[\]]/u.test(path)); diff --git a/plugins/codex-security/mcp-app/src/deep-scan/parent-sandbox.ts b/plugins/codex-security/mcp-app/src/deep-scan/parent-sandbox.ts index 21e30a2c7..f4d065ac5 100644 --- a/plugins/codex-security/mcp-app/src/deep-scan/parent-sandbox.ts +++ b/plugins/codex-security/mcp-app/src/deep-scan/parent-sandbox.ts @@ -15,6 +15,8 @@ export type DeepWorkerParentSandbox = { readonly literalFilesystemDenies?: readonly string[]; /** Windows needs the parent's named read root for the selected plugin. */ readonly pluginReadRoot?: string; + /** Preserve the selected source's named read root for Windows ACL setup. */ + readonly sourceReadRoot?: string; readonly globScanMaxDepth?: number; }; @@ -24,6 +26,9 @@ export function resolveDeepWorkerParentSandbox( pluginRoot = process.platform === "win32" ? process.env.CODEX_SECURITY_PLUGIN_ROOT : undefined, + sourceRoot = process.platform === "win32" + ? process.env.CODEX_SECURITY_REPOSITORY + : undefined, ): DeepWorkerParentSandbox { const state = trustedSandboxState(extra); @@ -57,6 +62,7 @@ export function resolveDeepWorkerParentSandbox( const filesystemDenies: string[] = []; const literalFilesystemDenies: string[] = []; let pluginReadRoot: string | undefined; + let sourceReadRoot: string | undefined; for (const value of filesystem.entries) { const entry = record(value); if (!entry || !isKnownFilesystemAccess(entry.access)) { @@ -103,14 +109,23 @@ export function resolveDeepWorkerParentSandbox( ); } literalFilesystemDenies.push(path.path); - } else if ( - entry.access === "read" && - pluginRoot !== undefined && - isAbsolute(path.path) && - relative(toNamespacedPath(path.path), toNamespacedPath(pluginRoot)) === - "" - ) { - pluginReadRoot = path.path; + } else if (entry.access === "read" && isAbsolute(path.path)) { + if ( + pluginRoot !== undefined && + relative( + toNamespacedPath(path.path), + toNamespacedPath(pluginRoot), + ) === "" + ) + pluginReadRoot = path.path; + if ( + sourceRoot !== undefined && + relative( + toNamespacedPath(path.path), + toNamespacedPath(sourceRoot), + ) === "" + ) + sourceReadRoot = path.path; } } else if (path.type === "glob_pattern") { if (!isNonEmptyString(path.pattern)) { @@ -150,6 +165,7 @@ export function resolveDeepWorkerParentSandbox( return { filesystemDenies, ...(pluginReadRoot === undefined ? {} : { pluginReadRoot }), + ...(sourceReadRoot === undefined ? {} : { sourceReadRoot }), ...(literalFilesystemDenies.length ? { literalFilesystemDenies } : {}), ...(globScanMaxDepth !== undefined ? { globScanMaxDepth } : {}), }; 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 f29cbcde4..f7712ba2d 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 @@ -1655,8 +1655,13 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`, index === 0 ? path.join(fixture.root, `plugin-${index}`) : undefined; + const sourceReadRoot = path.join( + fixture.root, + `private source [${index}]`, + ); const parentSandbox = { pluginReadRoot, + sourceReadRoot, filesystemDenies: [ ...trustedParentSandboxWithDenials.filesystemDenies, ...(nestedReceipts ? [] : [workerUsageDirectory]), @@ -1725,6 +1730,7 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`, ...deniedWorkerPermissionProfile, filesystem: { ...deniedWorkerPermissionProfile.filesystem, + [sourceReadRoot]: { ".": "read" }, ...(pluginReadRoot === undefined ? {} : { [pluginReadRoot]: { ".": "read" } }), diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_parent_sandbox.ts b/plugins/codex-security/mcp-app/tests/test_deep_scan_parent_sandbox.ts index 59fa601b4..baca98f42 100644 --- a/plugins/codex-security/mcp-app/tests/test_deep_scan_parent_sandbox.ts +++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_parent_sandbox.ts @@ -18,6 +18,35 @@ const pinnedReadOnly = { }; const stagedPlugin = path.resolve("bundled plugin [fixture]"); +const selectedSource = path.resolve("private source [fixture]"); +for (const access of ["read", "write"] as const) { + assert.deepEqual( + resolveDeepWorkerParentSandbox( + restricted([ + rootRead, + { path: { type: "path", path: selectedSource }, access }, + { + path: { type: "path", path: path.dirname(selectedSource) }, + access: "read", + }, + { + path: { + type: "path", + path: path.join(selectedSource, "config.toml"), + }, + access: "deny", + }, + ]), + stagedPlugin, + selectedSource, + ), + { + filesystemDenies: [], + literalFilesystemDenies: [path.join(selectedSource, "config.toml")], + ...(access === "read" ? { sourceReadRoot: selectedSource } : {}), + }, + ); +} assert.deepEqual( resolveDeepWorkerParentSandbox( restricted([ 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 348794eba..d5230e1c8 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 @@ -119,6 +119,7 @@ assert.deepEqual( "CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH", "CODEX_SECURITY_SCAN_DIR", "CODEX_SECURITY_PLUGIN_ROOT", + "CODEX_SECURITY_REPOSITORY", "CODEX_SECURITY_SCAN_ROOT", "CODEX_SECURITY_STATE_DIR", "CODEX_SECURITY_SURFACE", diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.ts index 4807bb6aa..6955d4999 100644 --- a/sdk/typescript/src/api.ts +++ b/sdk/typescript/src/api.ts @@ -1341,6 +1341,9 @@ export class CodexSecurity { const validationPermissions = { ...scanPermissions, filesystem: { + ...(process.platform === "win32" + ? { [inputs.repository]: { ".": "read" } } + : {}), ...(scanPermissions["filesystem"] as JsonObject), ":workspace_roots": "read", ...(runtime.deepScanConfigPath === undefined || @@ -1977,7 +1980,10 @@ export class CodexSecurity { : [runtime.deepScanConfigPath]), ...inputs.gitMetadataPaths, ], - await codexExecutableReadPaths(this.#codexCommand().command), + [ + ...(process.platform === "win32" ? policyReadRoots : []), + ...(await codexExecutableReadPaths(this.#codexCommand().command)), + ], ambientHome, ); const { codex } = await this.#createSessionCodex( @@ -4758,15 +4764,24 @@ export class CodexSecurity { environment[SAFETY_IDENTIFIER_ENV] = session.safetyIdentifier; } const sdkCodexConfig = structuredCodexConfig(config ?? sessionConfig); + // Windows configures sandbox ACL access for named roots, including private sources. + const sourceReadRoot = + process.platform === "win32" && command === "scan" + ? runtimePaths["CODEX_SECURITY_REPOSITORY"] + : undefined; // This snapshot outlives a Deep Scan when the client reuses its runtime. if ( runtime.deepScanConfigPath !== undefined || - pluginReadRoot !== undefined + pluginReadRoot !== undefined || + sourceReadRoot !== undefined ) { configOverrides = [ `permissions.${SCAN_PERMISSION_PROFILE}.filesystem=${inlineToml({ ":root": "read", ":workspace_roots": "write", + ...(sourceReadRoot !== undefined + ? { [sourceReadRoot]: { ".": "read" } } + : {}), ...(pluginReadRoot === undefined ? {} : { [pluginReadRoot]: { ".": "read" } }), @@ -7013,7 +7028,7 @@ export function scanRuntimeCodexConfig( function policyFilesystemPermissions( deniedPaths: readonly string[] = [], - codexPaths: readonly string[] = [], + readPaths: readonly string[] = [], ambientHome?: string, ): JsonObject { const filesystem: JsonObject = { @@ -7021,7 +7036,7 @@ function policyFilesystemPermissions( [process.platform === "win32" ? ":root" : ":minimal"]: "read", ":workspace_roots": "read", // Linux's sandbox re-executes Codex, including installations outside /usr. - ...Object.fromEntries(codexPaths.map((path) => [path, { ".": "read" }])), + ...Object.fromEntries(readPaths.map((path) => [path, { ".": "read" }])), // A scoped "." keeps native permission paths literal, including glob characters. ...Object.fromEntries(deniedPaths.map((path) => [path, { ".": "deny" }])), }; diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.ts index 67092898b..de319933a 100644 --- a/sdk/typescript/src/runtime.ts +++ b/sdk/typescript/src/runtime.ts @@ -3164,15 +3164,12 @@ async function pluginRuntimeProjection( } const environment = server["env_vars"]; if (environment !== undefined && !Array.isArray(environment)) return; - if ( - !Array.isArray(environment) || - !environment.includes("CODEX_SECURITY_PLUGIN_ROOT") - ) { - server["env_vars"] = [ - ...(Array.isArray(environment) ? environment : []), - "CODEX_SECURITY_PLUGIN_ROOT", - ]; - } + server["env_vars"] = [ + ...(environment ?? []), + ...["CODEX_SECURITY_PLUGIN_ROOT", "CODEX_SECURITY_REPOSITORY"].filter( + (name) => !environment?.includes(name), + ), + ]; const files: PluginRuntimeProjection["files"] = new Map(); server["command"] = server["command"] === "./scripts/launch_codex_security_mcp.cmd" diff --git a/sdk/typescript/tests-ts/api-policy.test.ts b/sdk/typescript/tests-ts/api-policy.test.ts index 04ee1263a..20e8bbe17 100644 --- a/sdk/typescript/tests-ts/api-policy.test.ts +++ b/sdk/typescript/tests-ts/api-policy.test.ts @@ -302,6 +302,14 @@ describe("CodexSecurity policy API", () => { filesystem: { [process.platform === "win32" ? ":root" : ":minimal"]: "read", ":workspace_roots": "read", + ...(process.platform === "win32" + ? Object.fromEntries( + f.threads[0]!.additionalDirectories!.map((path) => [ + path, + { ".": "read" }, + ]), + ) + : {}), ...Object.fromEntries( readPaths.map((path) => [path, { ".": "read" }]), ), diff --git a/sdk/typescript/tests-ts/api-runtime-storage.test.ts b/sdk/typescript/tests-ts/api-runtime-storage.test.ts index 8f01a3e3a..31d65dddc 100644 --- a/sdk/typescript/tests-ts/api-runtime-storage.test.ts +++ b/sdk/typescript/tests-ts/api-runtime-storage.test.ts @@ -160,6 +160,10 @@ test.each(["ready", "denied", "canceled"])( "filesystem" ] as Record; expect(roots[dirname(profileFile)]).toEqual({ ".": "deny" }); + if (process.platform === "win32" && operation !== "validation") + expect(roots[await realpath(repository)]).toEqual({ + ".": "read", + }); if (process.platform === "win32" && operation !== "validation") { const staged = options.env!["CODEX_SECURITY_PLUGIN_ROOT"]!; expect(dirname(staged)).toBe(protectedDirectory!); diff --git a/sdk/typescript/tests-ts/api-validation.test.ts b/sdk/typescript/tests-ts/api-validation.test.ts index f9e69d86b..10c5d5dd3 100644 --- a/sdk/typescript/tests-ts/api-validation.test.ts +++ b/sdk/typescript/tests-ts/api-validation.test.ts @@ -225,6 +225,9 @@ describe("CodexSecurity finding validation", () => { permissions: { codex_security_validation: { filesystem: { + ...(process.platform === "win32" + ? { [options.repositoryPath]: { ".": "read" } } + : {}), ":root": "read", ":workspace_roots": "read", ...credentialDenies, diff --git a/sdk/typescript/tests-ts/runtime-mcp-source-environment.test.ts b/sdk/typescript/tests-ts/runtime-mcp-source-environment.test.ts new file mode 100644 index 000000000..ad855e2a6 --- /dev/null +++ b/sdk/typescript/tests-ts/runtime-mcp-source-environment.test.ts @@ -0,0 +1,122 @@ +import { afterEach, expect, test } from "bun:test"; +import { spawnSync } from "node:child_process"; +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { createMarketplace } from "../src/runtime.js"; +import { createApiTestFixtures } from "./support/temporary-directories.js"; + +const { temporaryDirectory, cleanup } = createApiTestFixtures(); +afterEach(cleanup); +const pluginRoot = fileURLToPath( + new URL("../../../plugins/codex-security/", import.meta.url), +); +const parentSandbox = new URL( + "../../../plugins/codex-security/mcp-app/src/deep-scan/parent-sandbox.ts", + import.meta.url, +).href; + +test.each(["bundled", "legacy projection", "declared projection"])( + "%s forwards each scan's repository through the MCP environment", + async (configuration) => { + const root = await temporaryDirectory(); + let manifest = join(pluginRoot, ".mcp.json"); + if (configuration !== "bundled") { + const selected = join(root, "selected plugin"); + await mkdir(join(selected, ".codex-plugin"), { recursive: true }); + await writeFile( + join(selected, ".codex-plugin", "plugin.json"), + JSON.stringify({ name: "codex-security", version: "1.2.3" }), + ); + await writeFile( + join(selected, ".mcp.json"), + JSON.stringify({ + mcpServers: { + "codex-security": { + command: "./scripts/launch_codex_security_mcp", + env_vars: + configuration === "declared projection" + ? ["CODEX_SECURITY_PLUGIN_ROOT", "CODEX_SECURITY_REPOSITORY"] + : [], + }, + }, + }), + ); + const marketplace = await createMarketplace(join(root, "home"), selected); + manifest = join(marketplace, "plugins", "codex-security", ".mcp.json"); + } + const mcp = JSON.parse(await readFile(manifest, "utf8")); + const allowed: string[] = mcp.mcpServers["codex-security"].env_vars; + expect( + allowed.filter((name) => name === "CODEX_SECURITY_REPOSITORY"), + ).toHaveLength(1); + + for (const scan of ["fresh", "resumed"]) { + const source = join(root, `${scan} source [fixture]`); + const credentials = join(source, "config.toml"); + const parentEnvironment = { + CODEX_SECURITY_PLUGIN_ROOT: pluginRoot, + CODEX_SECURITY_REPOSITORY: source, + SYNTHETIC_UNDECLARED_VALUE: "ambient fixture", + }; + // Model the native MCP allowlist, then inspect the actual child process. + const environment = Object.fromEntries( + Object.entries(parentEnvironment).filter(([name]) => + allowed.includes(name), + ), + ); + const entries = [ + { path: { type: "special", value: { kind: "root" } }, access: "read" }, + { path: { type: "path", path: source }, access: "read" }, + { path: { type: "path", path: credentials }, access: "deny" }, + ]; + const extra = { + _meta: { + "codex/sandbox-state-meta": { + permissionProfile: { + type: "managed", + file_system: { type: "restricted", entries }, + }, + }, + }, + }; + const child = spawnSync( + process.execPath, + [ + "--eval", + `import { resolveDeepWorkerParentSandbox } from ${JSON.stringify(parentSandbox)}; +const extra = JSON.parse(process.argv[1]); +const inherited = resolveDeepWorkerParentSandbox(extra); +extra._meta["codex/sandbox-state-meta"].permissionProfile.file_system.entries.splice(1, 1); +console.log(JSON.stringify({ + repository: process.env.CODEX_SECURITY_REPOSITORY, + ambient: process.env.SYNTHETIC_UNDECLARED_VALUE, + inherited, + withoutNamedGrant: resolveDeepWorkerParentSandbox(extra), +}));`, + JSON.stringify(extra), + ], + { + env: { SystemRoot: process.env["SystemRoot"], ...environment }, + encoding: "utf8", + windowsHide: true, + }, + ); + expect(child.error).toBeUndefined(); + expect(child.stderr).toBe(""); + expect(child.status).toBe(0); + expect(JSON.parse(child.stdout)).toEqual({ + repository: source, + inherited: { + filesystemDenies: [], + literalFilesystemDenies: [credentials], + ...(process.platform === "win32" ? { sourceReadRoot: source } : {}), + }, + withoutNamedGrant: { + filesystemDenies: [], + literalFilesystemDenies: [credentials], + }, + }); + } + }, +); diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.ts index 00686838d..b46f16610 100644 --- a/sdk/typescript/tests-ts/runtime.test.ts +++ b/sdk/typescript/tests-ts/runtime.test.ts @@ -1047,7 +1047,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, 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] } }, inputSchema: { type: "object", properties: {} } }] } : request.method === "resources/list" ? { resources: [] } : request.method === "resources/templates/list" ? { resourceTemplates: [] } : {}; @@ -1125,12 +1125,11 @@ for await (const line of createInterface({ input: process.stdin })) { cwd: mcp.mcpServers["codex-security"].cwd, startup_timeout_sec: mcp.mcpServers["codex-security"].startup_timeout_sec, - env_vars: declaredRoot - ? mcp.mcpServers["codex-security"].env_vars - : [ - ...mcp.mcpServers["codex-security"].env_vars, - "CODEX_SECURITY_PLUGIN_ROOT", - ], + env_vars: [ + ...mcp.mcpServers["codex-security"].env_vars, + ...(declaredRoot ? [] : ["CODEX_SECURITY_PLUGIN_ROOT"]), + "CODEX_SECURITY_REPOSITORY", + ], }); expect( JSON.parse(await readFile(join(selected, ".mcp.json"), "utf8")), @@ -1156,6 +1155,11 @@ for await (const line of createInterface({ input: process.stdin })) { ...environment, CODEX_HOME: home, CODEX_SQLITE_HOME: sqliteHome, + CODEX_SECURITY_REPOSITORY: join( + root, + pluginRoot === second ? "second source" : "first source", + ), + SYNTHETIC_UNDECLARED_VALUE: "ambient fixture", ...(pluginRoot === undefined ? {} : { CODEX_SECURITY_PLUGIN_ROOT: pluginRoot }), @@ -1219,6 +1223,10 @@ for await (const line of createInterface({ input: process.stdin })) { }); const details = server.tools.probe._meta.launch; expect(details.pluginRoot).toBe(await realpath(pluginRoot)); + expect(details.repository).toBe( + join(root, pluginRoot === second ? "second source" : "first source"), + ); + expect(details.ambient).toBeUndefined(); expect(details.args).toEqual(argumentsAfterEntry); expect(details.cwd).toBe( process.platform === "win32" @@ -2292,7 +2300,11 @@ for await (const line of createInterface({ input: process.stdin })) { command: "./scripts/launch_codex_security_mcp_sdk", args: ["--stdio", "synthetic argument"], cwd: ".", - env_vars: ["CODEX_HOME", "CODEX_SECURITY_PLUGIN_ROOT"], + env_vars: [ + "CODEX_HOME", + "CODEX_SECURITY_PLUGIN_ROOT", + "CODEX_SECURITY_REPOSITORY", + ], }); expect( (await stat(join(staged, "scripts", "launch_codex_security_mcp"))) From 629d3a18ad97d928b042c735ee239f9e4228f117 Mon Sep 17 00:00:00 2001 From: Michael D'Angelo Date: Tue, 10 Nov 2026 01:19:34 -0800 Subject: [PATCH 08/28] test(windows): resolve usable Python in scan fixtures (#2553) * test(windows): probe Python for stopped scan fixtures * test(windows): probe Python in result contract fixtures * test(windows): reuse prepared Python in isolated imports * test(python): use normal isolated child deadline --------- Co-authored-by: Codex --- .../tests-ts/api-severity-rubric.test.ts | 5 +- sdk/typescript/tests-ts/contract.test.ts | 52 ++-- .../tests-ts/finding-preview.test.ts | 233 +++++++++++------- sdk/typescript/tests-ts/import-scan.test.ts | 7 +- .../tests-ts/python-executable.test.ts | 7 + .../tests-ts/stopped-scan-results.test.ts | 4 +- .../tests-ts/support/test-subprocess.ts | 12 +- 7 files changed, 199 insertions(+), 121 deletions(-) diff --git a/sdk/typescript/tests-ts/api-severity-rubric.test.ts b/sdk/typescript/tests-ts/api-severity-rubric.test.ts index 346dc0f86..67316ac24 100644 --- a/sdk/typescript/tests-ts/api-severity-rubric.test.ts +++ b/sdk/typescript/tests-ts/api-severity-rubric.test.ts @@ -7,6 +7,9 @@ import { bundledSeverityRubric } from "../src/severity-rubric.js"; import { mockWorkbench, TestClient } from "./support/api-client.js"; import { codexFactory, preparedRuntime } from "./support/api-events.js"; import { createApiTestFixtures } from "./support/temporary-directories.js"; +import { useTestPython } from "./support/python.js"; + +const pythonExecutable = useTestPython(); const { temporaryDirectory, cleanup } = createApiTestFixtures(); afterEach(cleanup); @@ -28,7 +31,7 @@ for (const mode of ["standard", "deep"] as const) { CODEX_SECURITY_ENABLE_REMOTE_SEVERITY_RUBRIC: source === "bundled" ? undefined : "1", }; - const python = Bun.which("python3") ?? Bun.which("python"); + const python = pythonExecutable(); if (!python) throw new Error("Python is required for this test."); const markdown = `Use this synthetic ${source} policy.`; const rubricPath = join(root, "policy.md"); diff --git a/sdk/typescript/tests-ts/contract.test.ts b/sdk/typescript/tests-ts/contract.test.ts index 7bd9ac95e..f109d9efe 100644 --- a/sdk/typescript/tests-ts/contract.test.ts +++ b/sdk/typescript/tests-ts/contract.test.ts @@ -24,11 +24,14 @@ import { } from "../src/contract.js"; import type { NormalizedTarget, ScanExpectation } from "../src/index.js"; import { PLUGIN_ROOT } from "./plugin-root.js"; +import { useTestPython } from "./support/python.js"; import { runPython } from "./support/python-probe.js"; import { createContractTestFixtures } from "./support/contract-fixture.js"; import { readJson as readJsonFile, writeJson } from "./support/json.js"; import { runTestInSubprocess } from "./support/test-subprocess.js"; +const pythonExecutable = useTestPython(); + const EXAMPLE = join(PLUGIN_ROOT, "examples", "legacy-completed-scan"); const { temporaryDirectory, cleanup, copyExample } = createContractTestFixtures(); @@ -50,7 +53,7 @@ async function reseal(scanDir: string): Promise { } function pythonExport(scanDir: string) { - return runPython(process.env["PYTHON"] ?? Bun.which("python3") ?? "python", [ + return runPython(pythonExecutable() ?? "python", [ join(PLUGIN_ROOT, "scripts", "finalize_scan_contract.py"), "--scan-dir", scanDir, @@ -89,14 +92,11 @@ describe("canonical scan contract", () => { } await writeJson(manifestPath, manifest); await loadContract(scanDir, { pluginRoot: PLUGIN_ROOT }); - const result = runPython( - process.env["PYTHON"] ?? Bun.which("python3") ?? "python", - [ - join(PLUGIN_ROOT, "scripts", "finalize_scan_contract.py"), - "--scan-dir", - scanDir, - ], - ); + const result = runPython(pythonExecutable() ?? "python", [ + join(PLUGIN_ROOT, "scripts", "finalize_scan_contract.py"), + "--scan-dir", + scanDir, + ]); expect(result.exitCode, new TextDecoder().decode(result.stderr)).toBe(0); for (const path of projections) expect(await readFile(join(scanDir, path), "utf8")).toBe(path); @@ -127,15 +127,12 @@ describe("canonical scan contract", () => { await writeJson(findingsPath, findings); await writeJson(manifestPath, manifest); await reseal(scanDir); - const result = runPython( - process.env["PYTHON"] ?? Bun.which("python3") ?? "python", - [ - "-c", - "import sys; from pathlib import Path; sys.path.insert(0, sys.argv[1]); from finalize_scan_contract import _prepare_scan_finalization; _prepare_scan_finalization(Path(sys.argv[2]))", - join(PLUGIN_ROOT, "scripts"), - scanDir, - ], - ); + const result = runPython(pythonExecutable() ?? "python", [ + "-c", + "import sys; from pathlib import Path; sys.path.insert(0, sys.argv[1]); from finalize_scan_contract import _prepare_scan_finalization; _prepare_scan_finalization(Path(sys.argv[2]))", + join(PLUGIN_ROOT, "scripts"), + scanDir, + ]); expect(result.exitCode, new TextDecoder().decode(result.stderr)).not.toBe( 0, ); @@ -512,14 +509,11 @@ describe("canonical scan contract", () => { manifest["scan"]["target"]["kind"] = kind; manifest["scan"]["target"]["revision"] = ""; await writeJson(manifestPath, manifest); - const result = runPython( - process.env["PYTHON"] ?? Bun.which("python3") ?? "python", - [ - join(PLUGIN_ROOT, "scripts", "finalize_scan_contract.py"), - "--scan-dir", - scanDir, - ], - ); + const result = runPython(pythonExecutable() ?? "python", [ + join(PLUGIN_ROOT, "scripts", "finalize_scan_contract.py"), + "--scan-dir", + scanDir, + ]); expect(result.exitCode, new TextDecoder().decode(result.stderr)).toBe(0); await loadContract(scanDir, { pluginRoot: PLUGIN_ROOT }); }, @@ -895,8 +889,7 @@ describe("canonical scan contract", () => { }); test("keeps bundled finalizer paths portable to Windows", () => { - const python = - process.env["PYTHON"] ?? Bun.which("python3") ?? Bun.which("python"); + const python = pythonExecutable(); expect(python).not.toBeNull(); const program = [ "import json, sys", @@ -1109,8 +1102,7 @@ describe("canonical scan contract", () => { loadContract(scanDir, { pluginRoot: PLUGIN_ROOT }), ).rejects.toThrow("duplicate artifact path"); - const python = - process.env["PYTHON"] ?? Bun.which("python3") ?? Bun.which("python"); + const python = pythonExecutable(); expect(python).not.toBeNull(); const result = runPython(python!, [ join(PLUGIN_ROOT, "scripts", "finalize_scan_contract.py"), diff --git a/sdk/typescript/tests-ts/finding-preview.test.ts b/sdk/typescript/tests-ts/finding-preview.test.ts index fc8b187b6..979a26ef6 100644 --- a/sdk/typescript/tests-ts/finding-preview.test.ts +++ b/sdk/typescript/tests-ts/finding-preview.test.ts @@ -2,9 +2,14 @@ import { join } from "node:path"; import { fileURLToPath } from "node:url"; import { describe, expect, test } from "bun:test"; import { PLUGIN_ROOT } from "./plugin-root.js"; +import { useTestPython } from "./support/python.js"; + +const pythonExecutable = useTestPython(); +// Source-scope scenarios exercise many native Git commands on Windows. +const previewTimeout = process.platform === "win32" ? 180_000 : 30_000; function checkSourceScope(scenario: string, expected: unknown = null): void { - const python = Bun.which("python3") ?? Bun.which("python") ?? Bun.which("py"); + const python = pythonExecutable(); expect(python).not.toBeNull(); const result = Bun.spawnSync( [ @@ -22,114 +27,170 @@ function checkSourceScope(scenario: string, expected: unknown = null): void { } describe("bundled finding previews", () => { - test("reads only the immutable source objects selected for the scan", () => { - checkSourceScope("boundaries", { - selected: "1 public source", - outside: null, - additional: "1 selected file", - repository: "1 private source", - fileDescendant: null, - traversal: null, - absolute: null, - redirected: null, - escaped: null, - legacyScoped: "1 public source", - legacyUnmarkedFile: "1 selected file", - legacyUnmarkedFileDescendant: null, - legacyRoot: "1 private source", - legacyKnownDirectory: "1 public source", - legacyKnownFile: "1 selected file", - legacyFileDescendant: null, - emptyAuthority: null, - dirty: null, - fallback: "1 public source", - rootControl: "1 public source", - replacedFile: "1 selected file", - replacedFileDescendant: null, - removedDirectory: "1 nested source", - offline: "1 public source", - missingObject: null, - }); - }, 30_000); + test( + "reads only the immutable source objects selected for the scan", + () => { + checkSourceScope("boundaries", { + selected: "1 public source", + outside: null, + additional: "1 selected file", + repository: "1 private source", + fileDescendant: null, + traversal: null, + absolute: null, + redirected: null, + escaped: null, + legacyScoped: "1 public source", + legacyUnmarkedFile: "1 selected file", + legacyUnmarkedFileDescendant: null, + legacyRoot: "1 private source", + legacyKnownDirectory: "1 public source", + legacyKnownFile: "1 selected file", + legacyFileDescendant: null, + emptyAuthority: null, + dirty: null, + fallback: "1 public source", + rootControl: "1 public source", + replacedFile: "1 selected file", + replacedFileDescendant: null, + removedDirectory: "1 nested source", + offline: "1 public source", + missingObject: null, + }); + }, + previewTimeout, + ); - test("keeps captured filesystem aliases usable after their source paths disappear", () => { - checkSourceScope("aliases", { - case: expect.any(Boolean), - unicode: expect.any(Boolean), - nonAscii: expect.any(Boolean), - collisionChecked: true, - }); - }, 30_000); + test( + "keeps captured filesystem aliases usable after their source paths disappear", + () => { + checkSourceScope("aliases", { + case: expect.any(Boolean), + unicode: expect.any(Boolean), + nonAscii: expect.any(Boolean), + collisionChecked: true, + }); + }, + previewTimeout, + ); - test("requires distinct filesystem witnesses for colliding descendants", () => { - checkSourceScope("descendant_aliases"); - }, 30_000); + test( + "requires distinct filesystem witnesses for colliding descendants", + () => { + checkSourceScope("descendant_aliases"); + }, + previewTimeout, + ); - test("keeps saved immutable objects readable after replacement refs change", () => { - checkSourceScope("replacements"); - }, 30_000); + test( + "keeps saved immutable objects readable after replacement refs change", + () => { + checkSourceScope("replacements"); + }, + previewTimeout, + ); - test("does not run working-tree filters when registering a committed-ref scan", () => { - checkSourceScope("replacement_filters"); - }, 30_000); + test( + "does not run working-tree filters when registering a committed-ref scan", + () => { + checkSourceScope("replacement_filters"); + }, + previewTimeout, + ); - test("omits source authority when replacement refs changed the scanned tree", () => { - checkSourceScope("replacement_snapshot"); - }, 30_000); + test( + "omits source authority when replacement refs changed the scanned tree", + () => { + checkSourceScope("replacement_snapshot"); + }, + previewTimeout, + ); - test("omits stale committed excerpts for working-tree diff scans", () => { - checkSourceScope("working_tree_excerpt", { - authorityOmitted: true, - currentExcerptOmitted: true, - legacyExcerptOmitted: true, - rangeExcerptPreserved: true, - }); - }, 30_000); + test( + "omits stale committed excerpts for working-tree diff scans", + () => { + checkSourceScope("working_tree_excerpt", { + authorityOmitted: true, + currentExcerptOmitted: true, + legacyExcerptOmitted: true, + rangeExcerptPreserved: true, + }); + }, + previewTimeout, + ); - test("indexes Git names once for large explicit scope lists", () => { - checkSourceScope("indexed_scopes", 256); - }, 30_000); + test( + "indexes Git names once for large explicit scope lists", + () => { + checkSourceScope("indexed_scopes", 256); + }, + previewTimeout, + ); - test("selects source excerpts from the displayed finding locations", () => { - checkSourceScope("display_locations", 8); - }, 30_000); + test( + "selects source excerpts from the displayed finding locations", + () => { + checkSourceScope("display_locations", 8); + }, + previewTimeout, + ); - test("does not grant source scope through a selected directory link", () => { - checkSourceScope("selected_redirects"); - }, 30_000); + test( + "does not grant source scope through a selected directory link", + () => { + checkSourceScope("selected_redirects"); + }, + previewTimeout, + ); - test("rejects unsafe finding locations before invoking Git", () => { - checkSourceScope("unsafe_locations"); - }, 30_000); + test( + "rejects unsafe finding locations before invoking Git", + () => { + checkSourceScope("unsafe_locations"); + }, + previewTimeout, + ); - test("does not treat links or reparse points as filesystem alias evidence", () => { - checkSourceScope("alias_evidence", { - ordinary: true, - hardlink: false, - symlink: false, - reparse: false, - }); - }, 30_000); + test( + "does not treat links or reparse points as filesystem alias evidence", + () => { + checkSourceScope("alias_evidence", { + ordinary: true, + hardlink: false, + symlink: false, + reparse: false, + }); + }, + previewTimeout, + ); - test("keeps subdirectory and linked-worktree targets bound to their selected tree", () => { - checkSourceScope("worktrees"); - }, 30_000); + test( + "keeps subdirectory and linked-worktree targets bound to their selected tree", + () => { + checkSourceScope("worktrees"); + }, + previewTimeout, + ); test.each(["workspace", "prompt", "headless", "deep", "cli"])( "records source authority through the %s scan-start path", (writer) => { checkSourceScope(`writer_${writer}`, writer); }, - 30_000, + previewTimeout, ); - test("preserves legacy scans and separately owned migration history", () => { - checkSourceScope("migration"); - }, 30_000); + test( + "preserves legacy scans and separately owned migration history", + () => { + checkSourceScope("migration"); + }, + previewTimeout, + ); }); test("bundled finding previews normalize details without changing stored findings", () => { - const python = Bun.which("python3") ?? Bun.which("python") ?? Bun.which("py"); + const python = pythonExecutable(); expect(python).not.toBeNull(); const original = { attackPath: { likelihood: "medium" }, diff --git a/sdk/typescript/tests-ts/import-scan.test.ts b/sdk/typescript/tests-ts/import-scan.test.ts index be4a99b7d..b2971f607 100644 --- a/sdk/typescript/tests-ts/import-scan.test.ts +++ b/sdk/typescript/tests-ts/import-scan.test.ts @@ -24,11 +24,14 @@ import { ScanResult } from "../src/result.js"; import { runWorkbench } from "../src/runtime.js"; import { VERSION } from "../src/version.js"; import { PLUGIN_ROOT } from "./plugin-root.js"; +import { useTestPython } from "./support/python.js"; import { runTestInSubprocess } from "./support/test-subprocess.js"; import { createApiTestFixtures } from "./support/temporary-directories.js"; import { rejecting } from "./support/errors.js"; import { TestClient } from "./support/api-client.js"; +const pythonExecutable = useTestPython(); + const { temporaryDirectories: roots, cleanup } = createApiTestFixtures(); afterEach(cleanup); @@ -86,7 +89,7 @@ async function fixture(format: "csv" | "json" = "csv") { join(await realpath(tmpdir()), "import-scan-test-"), ); roots.track(root); - const python = Bun.which("python3") ?? Bun.which("python"); + const python = pythonExecutable(); expect(python).not.toBeNull(); const stateDirectory = join(root, "state"); const environment = { @@ -170,6 +173,7 @@ test.each(["completed", "failed", "interrupted", "preview"] as const)( runTestInSubprocess( import.meta.path, `scratch cleanup failure preserves the ${outcome} import outcome`, + { PYTHON: pythonExecutable() ?? undefined }, ) ) return; @@ -634,6 +638,7 @@ test.each(["regular file", "symbolic link"])( runTestInSubprocess( import.meta.path, `import rejects a source replaced with a ${replacement} before reading`, + { PYTHON: pythonExecutable() ?? undefined }, ) ) return; diff --git a/sdk/typescript/tests-ts/python-executable.test.ts b/sdk/typescript/tests-ts/python-executable.test.ts index 36d76470c..5595564fb 100644 --- a/sdk/typescript/tests-ts/python-executable.test.ts +++ b/sdk/typescript/tests-ts/python-executable.test.ts @@ -43,11 +43,14 @@ test.skipIf(process.platform !== "win32")( ); const fixture = join(root, "python.test.ts"); const helper = new URL("./support/python.ts", import.meta.url).href; + const isolated = new URL("./support/test-subprocess.ts", import.meta.url) + .href; await writeFile( fixture, [ 'import { expect, test } from "bun:test";', `import { useTestPython } from ${JSON.stringify(helper)};`, + `import { runTestInSubprocess } from ${JSON.stringify(isolated)};`, "const resolve = useTestPython();", 'test("uses the prepared Python", () => {', " expect(resolve()).toBe(process.env.EXPECTED_PYTHON);", @@ -59,6 +62,10 @@ test.skipIf(process.platform !== "win32")( " expect(resolve()).toBe(process.env.EXPECTED_PYTHON);", " }", "});", + 'test("isolated child reuses the prepared Python", () => {', + ' if (runTestInSubprocess(import.meta.path, "isolated child reuses the prepared Python", { PYTHON: resolve() ?? undefined })) return;', + " expect(resolve()).toBe(process.env.EXPECTED_PYTHON);", + "}, 30000);", ].join("\n"), ); for (const configured of [python, ""]) { diff --git a/sdk/typescript/tests-ts/stopped-scan-results.test.ts b/sdk/typescript/tests-ts/stopped-scan-results.test.ts index 3a8868a35..83c83b59e 100644 --- a/sdk/typescript/tests-ts/stopped-scan-results.test.ts +++ b/sdk/typescript/tests-ts/stopped-scan-results.test.ts @@ -2,8 +2,10 @@ import { createTemporaryDirectoriesSync } from "./support/temporary-directories. import { afterEach, expect, test } from "bun:test"; import { PLUGIN_ROOT } from "./plugin-root.js"; import { runNodePython } from "./support/python-probe.js"; +import { useTestPython } from "./support/python.js"; const temporaryDirectories = createTemporaryDirectoriesSync(); +const pythonExecutable = useTestPython(); afterEach(temporaryDirectories.cleanup); @@ -171,7 +173,7 @@ function runStoppedScanProbe( prefix: string, terminalStatus?: string, ) { - const python = Bun.which("python3") ?? Bun.which("python"); + const python = pythonExecutable(); expect(python).not.toBeNull(); const root = temporaryDirectories.create(prefix); const result = runNodePython(python!, [ diff --git a/sdk/typescript/tests-ts/support/test-subprocess.ts b/sdk/typescript/tests-ts/support/test-subprocess.ts index d25121e9c..1b653c215 100644 --- a/sdk/typescript/tests-ts/support/test-subprocess.ts +++ b/sdk/typescript/tests-ts/support/test-subprocess.ts @@ -1,7 +1,11 @@ import { spawnSync } from "node:child_process"; import { expect } from "bun:test"; -export function runTestInSubprocess(file: string, name: string): boolean { +export function runTestInSubprocess( + file: string, + name: string, + environment: NodeJS.ProcessEnv = {}, +): boolean { const identity = `${file}::${name}`; if (process.env["CODEX_SECURITY_ISOLATED_TEST"] === identity) return false; const timeout = process.env["CODEX_SECURITY_TEST_TIMEOUT_MS"] ?? "30000"; @@ -13,7 +17,11 @@ export function runTestInSubprocess(file: string, name: string): boolean { { cwd: new URL("../../", import.meta.url), encoding: "utf8", - env: { ...process.env, CODEX_SECURITY_ISOLATED_TEST: identity }, + env: { + ...process.env, + ...environment, + CODEX_SECURITY_ISOLATED_TEST: identity, + }, windowsHide: true, }, ); From 4ede567343c9a48f468cb61de04c32ec44d4acff Mon Sep 17 00:00:00 2001 From: Michael D'Angelo Date: Tue, 10 Nov 2026 01:33:18 -0800 Subject: [PATCH 09/28] fix(scan): verify assumed-unchanged files for committed diffs (#2554) * fix(scan): verify assumed-unchanged files for committed diffs * test(workbench): read the index flag before asserting * fix(workbench): isolate Git settings during private index refresh --- .../scripts/workbench_target.py | 50 ++++++++++++++- .../tests/test_workbench_scan_validation.py | 49 +++++++++++++- sdk/typescript/docs/cli.md | 3 +- sdk/typescript/src/targets.ts | 64 +++++++++++++++++-- sdk/typescript/tests-ts/targets.test.ts | 45 ++++++++++++- 5 files changed, 200 insertions(+), 11 deletions(-) diff --git a/plugins/codex-security/scripts/workbench_target.py b/plugins/codex-security/scripts/workbench_target.py index 85fc06b28..5f62cf3a0 100644 --- a/plugins/codex-security/scripts/workbench_target.py +++ b/plugins/codex-security/scripts/workbench_target.py @@ -282,6 +282,7 @@ def git_command( work_tree: Path | None = None, stdout_file: BinaryIO | None = None, environment_overrides: dict[str, str] | None = None, + inherit_git_environment: bool = True, offline: bool = False, ) -> subprocess.CompletedProcess[str] | subprocess.CompletedProcess[bytes]: """Run Git against target and return the completed process with its exit status. @@ -292,7 +293,13 @@ def git_command( """ if (git_dir is None) != (work_tree is None): raise ValueError("git_dir and work_tree must be provided together") - environment = os.environ.copy() + environment = ( + os.environ.copy() + if inherit_git_environment + else { + name: value for name, value in os.environ.items() if not name.upper().startswith("GIT_") + } + ) for name in GIT_REPOSITORY_ENVIRONMENT: environment.pop(name, None) environment["GIT_LITERAL_PATHSPECS"] = "1" @@ -660,14 +667,18 @@ def require_scan_target_unchanged(scan: sqlite3.Row) -> None: if scan["diff_target_kind"] == "working_tree": expected_digest = scan["diff_content_digest"] elif scan["diff_target_kind"] in {"commit", "range"}: - tracked = git_bytes(Path(scan["target_path"]), "ls-files", "-t", "-z") + target = Path(scan["target_path"]) + tracked = git_bytes(target, "ls-files", "-v", "-z") if tracked is None: raise SystemExit("Could not inspect tracked files in the scan target.") - if any(entry.startswith(b"S ") for entry in tracked.split(b"\0")): + entries = tracked.split(b"\0") + if any(entry.startswith((b"S ", b"s ")) for entry in entries): raise SystemExit( "Committed-diff scans require a full repository checkout. " "Sparse checkouts are not supported; materialize skipped tracked files and retry." ) + if any(entry.startswith(b"h ") for entry in entries): + verify_assumed_unchanged_files(target) expected_digest = clean_worktree_content_digest() else: expected_digest = scan["target_snapshot_digest"] @@ -678,6 +689,39 @@ def require_scan_target_unchanged(scan: sqlite3.Row) -> None: ) +def verify_assumed_unchanged_files(target: Path) -> None: + index = git_output(target, "rev-parse", "--path-format=absolute", "--git-path", "index") + if index is None: + raise SystemExit("Could not locate the Git index for the scan target.") + with tempfile.TemporaryDirectory(prefix="codex-security-git-index-") as directory: + # Refresh a private index without running checkout hooks or updating its shared index. + index_copy = Path(directory) / "index" + shutil.copyfile(index, index_copy) + result = git_command( + target, + "-c", + f"core.hooksPath={directory}", + "-c", + "core.splitIndex=false", + "update-index", + "--really-refresh", + text=False, + environment_overrides={"GIT_INDEX_FILE": str(index_copy)}, + # A repository's clean filter can run while Git compares working-tree bytes. + inherit_git_environment=False, + offline=True, + ) + if result.returncode == 1: + raise SystemExit( + "A tracked file marked assume-unchanged changed since the scan. " + "Run a new scan before validating its findings." + ) + if result.returncode != 0: + raise SystemExit( + os.fsdecode(result.stderr) or "Could not refresh the scan target's Git index." + ) + + def worktree_content_digest_for_context( repository: Path, pathspec: str, diff --git a/plugins/codex-security/tests/test_workbench_scan_validation.py b/plugins/codex-security/tests/test_workbench_scan_validation.py index 877a9f0f8..0901c9e73 100644 --- a/plugins/codex-security/tests/test_workbench_scan_validation.py +++ b/plugins/codex-security/tests/test_workbench_scan_validation.py @@ -10,7 +10,7 @@ from pathlib import Path import pytest from test_workbench_scan_history import create_cli_scan -from workbench_test_support import get_scan, initialize_git_repository +from workbench_test_support import configure_git_command, get_scan, initialize_git_repository def start_validation_scan( @@ -119,6 +119,53 @@ def test_check_scan_target_rejects_changed_revision( workbench_api["remediation_checkout_snapshot"](stored_scan) +def test_check_committed_diff_target_rechecks_assume_unchanged_files(tmp_path: Path) -> None: + repository = tmp_path / "repository" + initialize_git_repository(repository) + state_dir, scan_id = start_validation_scan( + tmp_path, repository, target={"kind": "refs", "paths": [], "base": "HEAD", "head": "HEAD"} + ) + source = repository / "README.md" + original = source.read_bytes() + subprocess.run( + ["git", "update-index", "--assume-unchanged", "--", source.name], cwd=repository, check=True + ) + assert get_scan(state_dir, scan_id, "--check-target")["scan"]["scanId"] == scan_id + + (repository / ".git" / "info" / "attributes").write_text("README.md filter=fixture\n") + clean_filter = tmp_path / "clean_filter.py" + clean_filter.write_text( + "import os, sys\n" + "from pathlib import Path\n" + "if os.environ.get('GIT_INDEX_FILE'):\n" + " inherited = os.environ.get('GIT_CONFIG_VALUE_0') == 'synthetic-fixture-value'\n" + " Path(__file__).with_suffix('.result').write_text('inherited' if inherited else 'isolated')\n" + "sys.stdout.buffer.write(sys.stdin.buffer.read())\n" + ) + configure_git_command(repository, "filter.fixture.clean", clean_filter) + # Matching sizes force Git to compare the filtered contents. + source.write_bytes(b"x" * len(original)) + os.utime(source, (1, 1)) + changed = get_scan( + state_dir, + scan_id, + "--check-target", + check=False, + environment={ + "GIT_CONFIG_COUNT": "1", + "GIT_CONFIG_KEY_0": "http.extraHeader", + "GIT_CONFIG_VALUE_0": "synthetic-fixture-value", + }, + ) + assert changed["returncode"] != 0 + assert "changed" in changed["stderr"] + assert clean_filter.with_suffix(".result").read_text() == "isolated" + tracked = subprocess.check_output(["git", "ls-files", "-v", "--", source.name], cwd=repository) + assert tracked.split(maxsplit=1)[0] == b"h" + source.write_bytes(original) + assert get_scan(state_dir, scan_id, "--check-target")["scan"]["scanId"] == scan_id + + def test_check_committed_diff_target_rejects_sparse_checkout_after_scan(tmp_path: Path) -> None: repository = tmp_path / "repository" initialize_git_repository(repository) diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.md index c233e6882..949ae8438 100644 --- a/sdk/typescript/docs/cli.md +++ b/sdk/typescript/docs/cli.md @@ -509,7 +509,8 @@ be clean and at the commit recorded by the parent. Committed-diff scans require a clean, full checkout at the requested head revision, including when using `--validate`. A different checkout revision or local changes are rejected before scanning; check out the requested head and -commit or stash local changes before retrying. +commit or stash local changes before retrying. The check also verifies tracked +files marked `assume-unchanged` and preserves their Git index flags. `--owner-suggestions` writes optional `owner-suggestions.json` after a completed committed Git scan, using the same checkout, model, and reasoning effort. Owner diff --git a/sdk/typescript/src/targets.ts b/sdk/typescript/src/targets.ts index 5009dd0ff..5e6a68fd4 100644 --- a/sdk/typescript/src/targets.ts +++ b/sdk/typescript/src/targets.ts @@ -2,8 +2,16 @@ import { isNonEmptyString } from "./value.js"; import { isUtf8 } from "node:buffer"; import { execFile as execFileCallback } from "node:child_process"; import { realpathSync, type Stats } from "node:fs"; -import { lstat, readFile, realpath, stat } from "node:fs/promises"; -import { homedir } from "node:os"; +import { + copyFile, + lstat, + mkdtemp, + readFile, + realpath, + rm, + stat, +} from "node:fs/promises"; +import { homedir, tmpdir } from "node:os"; import { basename, dirname, @@ -675,12 +683,60 @@ export async function validateCommittedDiffCheckout( ); } - const tracked = await gitOutput(repository, ["ls-files", "-t", "-z"], signal); - if (tracked.split("\0").some((entry) => entry.startsWith("S "))) { + const tracked = ( + await gitOutput(repository, ["ls-files", "-v", "-z"], signal) + ).split("\0"); + if (tracked.some((entry) => /^[Ss] /u.test(entry))) { throw new InvalidTargetError( "Committed-diff scans require a full repository checkout. Sparse checkouts are not supported; materialize skipped tracked files and retry.", ); } + if (tracked.some((entry) => entry.startsWith("h "))) { + await verifyAssumedUnchangedFiles(repository, signal); + } +} + +async function verifyAssumedUnchangedFiles( + repository: string, + signal?: AbortSignal, +): Promise { + const index = await gitOutput( + repository, + ["rev-parse", "--path-format=absolute", "--git-path", "index"], + signal, + ); + // Git changes to the repository before resolving GIT_INDEX_FILE, even when TMPDIR is relative. + const directory = await mkdtemp( + join(await realpath(tmpdir()), "codex-security-git-index-"), + ); + const copy = join(directory, "index"); + try { + // Git refreshes stat data and flags. Keep that write and any hooks out of the checkout. + await copyFile(index, copy); + await gitOutput( + repository, + [ + "-c", + `core.hooksPath=${directory}`, + "-c", + "core.splitIndex=false", + "update-index", + "--really-refresh", + ], + signal, + { GIT_INDEX_FILE: copy }, + ); + } catch (error) { + if (error instanceof Error && "code" in error && error.code === 1) { + throw new InvalidTargetError( + "Committed-diff scans require a clean repository checkout. A tracked file marked assume-unchanged has changed on disk.", + { cause: error }, + ); + } + throw error; + } finally { + await rm(directory, { recursive: true, force: true }); + } } export function validateMode(target: NormalizedTarget, mode: ScanMode): void { diff --git a/sdk/typescript/tests-ts/targets.test.ts b/sdk/typescript/tests-ts/targets.test.ts index 4a824872a..47e5a3dee 100644 --- a/sdk/typescript/tests-ts/targets.test.ts +++ b/sdk/typescript/tests-ts/targets.test.ts @@ -14,7 +14,7 @@ import { writeFile, } from "node:fs/promises"; import { tmpdir } from "node:os"; -import { delimiter, join } from "node:path"; +import { delimiter, join, relative } from "node:path"; import { fileURLToPath } from "node:url"; import { afterEach, describe, expect, test } from "bun:test"; import { @@ -31,6 +31,7 @@ import { gitMarkerRoot, isGitMetadataDirectory, gitProtectionRoots, + validateCommittedDiffCheckout, } from "../src/targets.js"; import { createApiTestFixtures } from "./support/temporary-directories.js"; import { runCommand } from "./support/shell.js"; @@ -161,7 +162,10 @@ function git(repo: string, ...args: string[]): string { return execFileSync("git", args, { cwd: repo, encoding: "utf8" }).trim(); } -function validateCommittedDiffWithCredentialConfig(repo: string) { +function validateCommittedDiffWithCredentialConfig( + repo: string, + environment: NodeJS.ProcessEnv = {}, +) { return spawnSync( process.execPath, [ @@ -174,6 +178,7 @@ function validateCommittedDiffWithCredentialConfig(repo: string) { encoding: "utf8", env: { ...process.env, + ...environment, GIT_CONFIG_COUNT: "1", GIT_CONFIG_KEY_0: "http.extraHeader", GIT_CONFIG_VALUE_0: "SYNTHETIC_GIT_CREDENTIAL", @@ -569,6 +574,42 @@ describe("scan target normalization", () => { } }); + test("checks assumed-unchanged files against a committed diff without changing index flags", async () => { + const repo = await repository(); + const name = "src/app.ts"; + const file = join(repo, name); + const original = await readFile(file); + const target = await normalizeTarget( + repo, + DiffTarget.refs({ base: "HEAD" }), + ); + git(repo, "update-index", "--assume-unchanged", "--", name); + const hook = join(repo, ".git", "hooks", "post-index-change"); + await writeFile( + hook, + '#!/bin/sh\nif test -n "$GIT_INDEX_FILE"; then echo ran >.git/refresh-hook-ran; fi\n', + { mode: 0o755 }, + ); + await validateCommittedDiffCheckout(repo, target); + + await writeFile(file, "export const changed = true;\n"); + expect(git(repo, "status", "--porcelain")).toBe(""); + await expect(validateCommittedDiffCheckout(repo, target)).rejects.toThrow( + "clean repository checkout", + ); + if (process.platform !== "win32") { + const child = validateCommittedDiffWithCredentialConfig(repo, { + TMPDIR: relative(process.cwd(), join(repo, "..")), + }); + expect(child.status).toBe(1); + expect(child.stderr).toContain("clean repository checkout"); + } + expect(git(repo, "ls-files", "-v", "--", name)).toBe(`h ${name}`); + await writeFile(file, original); + await validateCommittedDiffCheckout(repo, target); + expect(existsSync(join(repo, ".git", "refresh-hook-ran"))).toBe(false); + }); + test("does not expose Git configuration to repository fsmonitor hooks", async () => { const repo = await repository(); const root = join(repo, ".."); From bae3008e79bbfba3bf09e41833eb586eb3603462 Mon Sep 17 00:00:00 2001 From: Michael D'Angelo Date: Tue, 10 Nov 2026 01:35:55 -0800 Subject: [PATCH 10/28] fix(cli): resolve temporary paths before patching a saved checkout (#2558) --- sdk/typescript/src/cli.ts | 8 ++++++-- sdk/typescript/src/finding-prompt.ts | 6 ++++-- sdk/typescript/tests-ts/cli-patch.test.ts | 18 +++++++++++++----- sdk/typescript/tests-ts/finding-prompt.test.ts | 8 ++++++-- 4 files changed, 29 insertions(+), 11 deletions(-) diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts index 7c48a4d11..22c35c36f 100644 --- a/sdk/typescript/src/cli.ts +++ b/sdk/typescript/src/cli.ts @@ -9097,7 +9097,9 @@ async function assessPatchRisk( request.files === undefined ? [] : ["--", ...request.files.map((file) => file)]; - const root = await mkdtemp(join(tmpdir(), "codex-security-patch-risk-")); + const root = await mkdtemp( + join(await realpath(tmpdir()), "codex-security-patch-risk-"), + ); const patchPath = join(root, "patch.diff"); try { const head = @@ -9170,7 +9172,9 @@ async function withPatchIndex( git: (args: string[], input?: string) => Promise, ) => Promise, ): Promise { - const root = await mkdtemp(join(tmpdir(), "codex-security-patch-tree-")); + const root = await mkdtemp( + join(await realpath(tmpdir()), "codex-security-patch-tree-"), + ); try { return await operation((args, input) => dependencies.runRepositoryCommand("git", args, repository, { diff --git a/sdk/typescript/src/finding-prompt.ts b/sdk/typescript/src/finding-prompt.ts index 7a32d82d2..fea0c24c3 100644 --- a/sdk/typescript/src/finding-prompt.ts +++ b/sdk/typescript/src/finding-prompt.ts @@ -1,4 +1,4 @@ -import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { mkdtemp, realpath, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { @@ -17,7 +17,9 @@ export async function prepareFindingPrompt( if (characterCount(prompt) <= MAX_CODEX_INPUT_CHARACTERS) return { prompt, async [Symbol.asyncDispose]() {} }; - const directory = await mkdtemp(join(tmpdir(), "codex-security-finding-")); + const directory = await mkdtemp( + join(await realpath(tmpdir()), "codex-security-finding-"), + ); const cleanup = async () => { // Cleanup must not replace a completed result or the original failure. await rm(directory, { recursive: true, force: true }).catch(() => {}); diff --git a/sdk/typescript/tests-ts/cli-patch.test.ts b/sdk/typescript/tests-ts/cli-patch.test.ts index cf31b03e7..d88922fc6 100644 --- a/sdk/typescript/tests-ts/cli-patch.test.ts +++ b/sdk/typescript/tests-ts/cli-patch.test.ts @@ -3,12 +3,12 @@ import { gitText } from "./support/shell.js"; import { emptyPage } from "./support/linear-pagination.js"; import { resolving } from "./support/promises.js"; import { parse as parseToml } from "smol-toml"; -import { afterEach, describe, expect, test, mock } from "bun:test"; +import { afterEach, describe, expect, test, mock, spyOn } from "bun:test"; import { execFileSync } from "node:child_process"; import { hash } from "node:crypto"; import { mkdir, readFile, rm, symlink, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; -import { dirname, join, relative, resolve } from "node:path"; +import * as os from "node:os"; +import { dirname, isAbsolute, join, relative, resolve } from "node:path"; import { Writable } from "node:stream"; import { stripVTControlCharacters } from "node:util"; import type { Finding, JsonObject, SeverityLevel } from "../src/index.js"; @@ -982,6 +982,9 @@ describe("scan and patch workflow", () => { test("assesses only changes made during a literal patch run", async () => { const directory = await temporaryDirectory("codex-security-patch-risk-"); + using _temporary = spyOn(os, "tmpdir").mockReturnValue( + relative(process.cwd(), directory), + ); const repository = join(directory, "repository"); await mkdir(repository, { recursive: true }); const git = repositoryGit(repository); @@ -1046,6 +1049,7 @@ describe("scan and patch workflow", () => { .split("\n") .find((line) => line.startsWith('{"path":'))!, ) as { path: string; sha256: string }; + expect(isAbsolute(artifact.path)).toBe(true); const patch = await readFile(artifact.path, "utf8"); expect(patch).toContain("+patch change"); expect(patch).not.toContain("+user change"); @@ -1059,7 +1063,11 @@ describe("scan and patch workflow", () => { output?.stdout.write("Patch complete."); return 0; }, - onRepositoryCommand: runGitRepositoryCommand, + onRepositoryCommand: (command, args, cwd, options) => { + const index = options?.environment?.["GIT_INDEX_FILE"]; + if (index !== undefined) expect(isAbsolute(index)).toBe(true); + return runGitRepositoryCommand(command, args, cwd, options); + }, }, ); @@ -1431,7 +1439,7 @@ describe("scan and patch workflow", () => { test.each(["synthetic.provider", "openai"])( "preserves %s command-provider authentication when patching after a scan", async (provider) => { - const home = join(tmpdir(), "synthetic-auth-home"); + const home = join(os.tmpdir(), "synthetic-auth-home"); let providerOverride: string | undefined; const outcome = await runWorkflow( [ diff --git a/sdk/typescript/tests-ts/finding-prompt.test.ts b/sdk/typescript/tests-ts/finding-prompt.test.ts index 9fd51c973..d8ba63937 100644 --- a/sdk/typescript/tests-ts/finding-prompt.test.ts +++ b/sdk/typescript/tests-ts/finding-prompt.test.ts @@ -1,6 +1,7 @@ import { readFile, stat } from "node:fs/promises"; -import { dirname } from "node:path"; -import { expect, test } from "bun:test"; +import * as os from "node:os"; +import { dirname, isAbsolute, relative } from "node:path"; +import { expect, spyOn, test } from "bun:test"; import { MAX_CODEX_INPUT_CHARACTERS } from "../src/codex-prompt.js"; import { prepareFindingPrompt } from "../src/finding-prompt.js"; @@ -20,6 +21,8 @@ test.each([false, true])( evidence: '"\\\n🦞'.repeat(200_000), tail: "Final evidence", }); + const temporaryRoot = relative(process.cwd(), os.tmpdir()) || "."; + using _temporary = spyOn(os, "tmpdir").mockReturnValue(temporaryRoot); let path = ""; const run = async () => { await using prepared = await prepareFindingPrompt( @@ -28,6 +31,7 @@ test.each([false, true])( ); expect(prepared.prompt.length).toBeLessThan(MAX_CODEX_INPUT_CHARACTERS); path = JSON.parse(prepared.prompt.match(/^".*finding\.json"$/m)![0]); + expect(isAbsolute(path)).toBe(true); expect(await readFile(path, "utf8")).toBe(finding); if (process.platform !== "win32") { expect((await stat(path)).mode & 0o777).toBe(0o600); From 0384bb30e587a9c82160ce4297bc6dc7f8c23b99 Mon Sep 17 00:00:00 2001 From: Michael D'Angelo Date: Tue, 10 Nov 2026 01:38:12 -0800 Subject: [PATCH 11/28] fix(sdk): stage knowledge in the selected temporary directory (#2559) --- sdk/typescript/src/knowledge-base.ts | 2 +- .../tests-ts/knowledge-base.test.ts | 33 ++++++++++++++++++- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/sdk/typescript/src/knowledge-base.ts b/sdk/typescript/src/knowledge-base.ts index 2afa5e2ed..a0ce4508e 100644 --- a/sdk/typescript/src/knowledge-base.ts +++ b/sdk/typescript/src/knowledge-base.ts @@ -154,7 +154,7 @@ export async function prepareKnowledgeBase( : await readKnowledgeBaseSnapshot(input, signal); const protectedRoots = await knowledgeBaseProtectedRoots(snapshot, signal); const path = await mkdtemp( - join(directory ?? tmpdir(), "codex-security-knowledge-"), + join(await realpath(directory ?? tmpdir()), "codex-security-knowledge-"), ); try { for (const [filename, text] of Object.entries(snapshot.documents)) { diff --git a/sdk/typescript/tests-ts/knowledge-base.test.ts b/sdk/typescript/tests-ts/knowledge-base.test.ts index 7497a3d84..371d0981b 100644 --- a/sdk/typescript/tests-ts/knowledge-base.test.ts +++ b/sdk/typescript/tests-ts/knowledge-base.test.ts @@ -11,7 +11,7 @@ import { } from "node:fs/promises"; import * as filesystem from "node:fs/promises"; import * as os from "node:os"; -import { join } from "node:path"; +import { dirname, join, relative, sep } from "node:path"; import { afterEach, describe, expect, mock, spyOn, test } from "bun:test"; import { strToU8, zipSync } from "fflate"; import { ConfigurationError } from "../src/errors.js"; @@ -896,6 +896,37 @@ describe("scan knowledge bases", () => { ]); }); + test.each(["relative", "linked parent"])( + "stages knowledge in the worker-readable temporary directory: %s", + async (spelling) => { + const root = await temporaryDirectory(); + const source = join(root, "policy.md"); + await writeFile(source, "Synthetic policy."); + const staging = join(root, "staging"); + await mkdir(staging); + let temporary = relative(process.cwd(), staging); + if (spelling === "linked parent") { + const child = join(staging, "child"); + const link = join(root, "alias"); + await mkdir(child); + await symlink( + child, + link, + process.platform === "win32" ? "junction" : "dir", + ); + temporary = link + sep + ".."; + } + const expected = await filesystem.realpath(temporary); + using _temporary = spyOn(os, "tmpdir").mockReturnValue(temporary); + const prepared = await prepareKnowledgeBase([source]); + temporaryDirectories.track(prepared.path); + expect(dirname(prepared.path)).toBe(expected); + expect(await extractedDocuments(prepared.path)).toEqual([ + "Synthetic policy.", + ]); + }, + ); + test("skips macOS metadata files copied next to documents", async () => { const root = await temporaryDirectory(); await writeFile(join(root, "guide.md"), "Rotate admin keys monthly."); From a86445c84151622b500093a2166d21ceb0fe1bdf Mon Sep 17 00:00:00 2001 From: Michael D'Angelo Date: Tue, 10 Nov 2026 02:14:50 -0800 Subject: [PATCH 12/28] fix(scan): isolate Git pathspec modes for file inventories (#2565) --- .../mcp-app/src/helpers/inventory-git.ts | 2 ++ .../tests/support/fake-codex-source.ts | 6 ++++-- .../mcp-app/tests/test_artifact_inventory.ts | 19 +++++++++++++++++++ .../mcp-app/tests/test_deep_scan_executor.ts | 2 ++ .../scripts/workbench_constants.py | 2 ++ .../tests/test_workbench_target.py | 6 +++++- 6 files changed, 34 insertions(+), 3 deletions(-) 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 6a3403a33..3c233794f 100644 --- a/plugins/codex-security/mcp-app/src/helpers/inventory-git.ts +++ b/plugins/codex-security/mcp-app/src/helpers/inventory-git.ts @@ -54,6 +54,8 @@ const repositoryEnvironment = [ "GIT_COMMON_DIR", "GIT_DIR", "GIT_DISCOVERY_ACROSS_FILESYSTEM", + "GIT_GLOB_PATHSPECS", + "GIT_ICASE_PATHSPECS", "GIT_INDEX_FILE", "GIT_LITERAL_PATHSPECS", "GIT_NAMESPACE", diff --git a/plugins/codex-security/mcp-app/tests/support/fake-codex-source.ts b/plugins/codex-security/mcp-app/tests/support/fake-codex-source.ts index 3ac8307a8..e5f1dd08a 100644 --- a/plugins/codex-security/mcp-app/tests/support/fake-codex-source.ts +++ b/plugins/codex-security/mcp-app/tests/support/fake-codex-source.ts @@ -21,7 +21,7 @@ const accountResult = ${JSON.stringify(accountResult)}; const preflightMarkerPath = process.env.FAKE_CODEX_PREFLIGHT_MARKER ?? ${JSON.stringify(preflightMarkerPath)}; const temporaryEnvironment = Object.fromEntries(['TEMP', 'TMP'].map(name => [name, process.env[name]])); if (process.argv.includes('app-server')) { - const preflight = { executablePath: process.argv[1], argv: process.argv.slice(2), configPath: process.env.CODEX_SECURITY_CONFIG_PATH, stateDirectory: process.env.CODEX_SECURITY_STATE_DIR, temporaryEnvironment, runnerTrackingId: process.env.RUNNER_TRACKING_ID, libraryPath: process.env["LD_LIBRARY_PATH"], cwd: process.cwd(), codexHome: process.env.CODEX_HOME, providerKey: process.env.SYNTHETIC_GATEWAY_KEY, providerHeaders: Object.fromEntries(['SYNTHETIC_HEADER_VALUE', 'OPENROUTER_API_KEY', 'FIREWORKS_API_KEY'].map(name => [name, process.env[name]])), providerHeader: process.env.SYNTHETIC_HEADER_VALUE, cacheDirectory: process.env.XDG_CACHE_HOME, gitEnvironment: Object.fromEntries(['PATH', 'HOME', 'NODE_OPTIONS', 'NODE_DEBUG', 'NODE_EXTRA_CA_CERTS', 'CODEX_MCP_NODE_PATH', 'CODEX_SECURITY_GIT', 'GIT_SSH_COMMAND', 'GIT_CONFIG_GLOBAL'].map(name => [name, process.env[name]])), requests: [] }; + const preflight = { executablePath: process.argv[1], argv: process.argv.slice(2), configPath: process.env.CODEX_SECURITY_CONFIG_PATH, stateDirectory: process.env.CODEX_SECURITY_STATE_DIR, temporaryEnvironment, runnerTrackingId: process.env.RUNNER_TRACKING_ID, libraryPath: process.env["LD_LIBRARY_PATH"], cwd: process.cwd(), codexHome: process.env.CODEX_HOME, providerKey: process.env.SYNTHETIC_GATEWAY_KEY, providerHeaders: Object.fromEntries(['SYNTHETIC_HEADER_VALUE', 'OPENROUTER_API_KEY', 'FIREWORKS_API_KEY'].map(name => [name, process.env[name]])), providerHeader: process.env.SYNTHETIC_HEADER_VALUE, cacheDirectory: process.env.XDG_CACHE_HOME, gitEnvironment: Object.fromEntries(['PATH', 'HOME', 'NODE_OPTIONS', 'NODE_DEBUG', 'NODE_EXTRA_CA_CERTS', 'CODEX_MCP_NODE_PATH', 'CODEX_SECURITY_GIT', 'GIT_SSH_COMMAND', 'GIT_CONFIG_GLOBAL', 'GIT_GLOB_PATHSPECS', 'GIT_ICASE_PATHSPECS'].map(name => [name, process.env[name]])), requests: [] }; writeFileSync(preflightMarkerPath, JSON.stringify(preflight)); ${jsonLineInputSource(` if (message.method === 'initialized') continue; if (message.method === 'config/read' || message.method === 'permissionProfile/list') { @@ -80,7 +80,7 @@ const pythonRuntime = pythonProbe ? JSON.parse(pythonProbe.stdout) : undefined; const knowledgePath = stdin.includes('synthetic worker configuration fixture') ? process.env.CODEX_SECURITY_KNOWLEDGE_BASE : undefined; const knowledgeDocuments = knowledgePath === undefined ? undefined : Object.fromEntries(readdirSync(knowledgePath).map(name => [name, readFileSync(join(knowledgePath, name), 'utf8')])); const deepConfig = process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH ? readFileSync(process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH, 'utf8') : undefined; -writeFileSync(process.env.FAKE_CODEX_MARKER, JSON.stringify({ executablePath: process.argv[1], ...(scopeInput === undefined ? {} : { scopeInput }), argv: process.argv.slice(2), stdin, cwd: process.cwd(), knowledgePath, knowledgeDocuments, deepConfig, codexHome: process.env.CODEX_HOME, temporaryEnvironment, cacheDirectory: process.env.XDG_CACHE_HOME, gitEnvironment: Object.fromEntries(['PATH', 'HOME', 'NODE_OPTIONS', 'NODE_DEBUG', 'NODE_EXTRA_CA_CERTS', 'CODEX_MCP_NODE_PATH', 'CODEX_SECURITY_GIT', 'GIT_SSH_COMMAND', 'GIT_CONFIG_GLOBAL'].map(name => [name, process.env[name]])), configPath: process.env.CODEX_SECURITY_CONFIG_PATH, deepConfigPath: process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH, python: process.env.PYTHON, mcpNodePath: process.env.CODEX_MCP_NODE_PATH, bundledTool: toolProbe?.stdout.trim(), pythonPrefix: pythonRuntime?.[0], pythonLibraryPath: pythonRuntime?.[1], runtimeEnvironment, codexConfig, providerHeaders: Object.fromEntries(['SYNTHETIC_HEADER_VALUE', 'OPENROUTER_API_KEY', 'FIREWORKS_API_KEY'].map(name => [name, process.env[name]])), providerKey: process.env.SYNTHETIC_GATEWAY_KEY, providerHeader: process.env.SYNTHETIC_HEADER_VALUE, originator: process.env.CODEX_INTERNAL_ORIGINATOR_OVERRIDE, ...(profileContents === undefined ? {} : { profileContents }), ...(openaiAuthentication ? { openaiAuthentication } : {}), ...(bedrockAuthentication ? { bedrockAuthentication } : {}) })); +writeFileSync(process.env.FAKE_CODEX_MARKER, JSON.stringify({ executablePath: process.argv[1], ...(scopeInput === undefined ? {} : { scopeInput }), argv: process.argv.slice(2), stdin, cwd: process.cwd(), knowledgePath, knowledgeDocuments, deepConfig, codexHome: process.env.CODEX_HOME, temporaryEnvironment, cacheDirectory: process.env.XDG_CACHE_HOME, gitEnvironment: Object.fromEntries(['PATH', 'HOME', 'NODE_OPTIONS', 'NODE_DEBUG', 'NODE_EXTRA_CA_CERTS', 'CODEX_MCP_NODE_PATH', 'CODEX_SECURITY_GIT', 'GIT_SSH_COMMAND', 'GIT_CONFIG_GLOBAL', 'GIT_GLOB_PATHSPECS', 'GIT_ICASE_PATHSPECS'].map(name => [name, process.env[name]])), configPath: process.env.CODEX_SECURITY_CONFIG_PATH, deepConfigPath: process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH, python: process.env.PYTHON, mcpNodePath: process.env.CODEX_MCP_NODE_PATH, bundledTool: toolProbe?.stdout.trim(), pythonPrefix: pythonRuntime?.[0], pythonLibraryPath: pythonRuntime?.[1], runtimeEnvironment, codexConfig, providerHeaders: Object.fromEntries(['SYNTHETIC_HEADER_VALUE', 'OPENROUTER_API_KEY', 'FIREWORKS_API_KEY'].map(name => [name, process.env[name]])), providerKey: process.env.SYNTHETIC_GATEWAY_KEY, providerHeader: process.env.SYNTHETIC_HEADER_VALUE, originator: process.env.CODEX_INTERNAL_ORIGINATOR_OVERRIDE, ...(profileContents === undefined ? {} : { profileContents }), ...(openaiAuthentication ? { openaiAuthentication } : {}), ...(bedrockAuthentication ? { bedrockAuthentication } : {}) })); if (stdin.includes('COMPLETE_THEN_HANG')) process.on('SIGTERM', () => { if (!stdin.includes('IGNORE_TERMINATION')) setTimeout(() => process.exit(0), 100); }); if (stdin.includes('THREAD_START_CONFIG_ERROR')) { console.error('Error: thread/start: thread/start failed: agents.max_threads cannot be set when features.multi_agent_v2 is enabled (code -32600)'); process.exit(1); } @@ -140,6 +140,8 @@ export function workerGitEnvironment(root: string) { ), CODEX_SECURITY_GIT: path.join(root, "selected tools", "git"), GIT_SSH_COMMAND: "synthetic-ssh --fixture", + GIT_GLOB_PATHSPECS: "1", + GIT_ICASE_PATHSPECS: "1", GIT_CONFIG_GLOBAL: path.join(root, "operator.gitconfig"), }; } diff --git a/plugins/codex-security/mcp-app/tests/test_artifact_inventory.ts b/plugins/codex-security/mcp-app/tests/test_artifact_inventory.ts index bd171620b..5e112bba5 100644 --- a/plugins/codex-security/mcp-app/tests/test_artifact_inventory.ts +++ b/plugins/codex-security/mcp-app/tests/test_artifact_inventory.ts @@ -236,6 +236,25 @@ test(async function testPrepareWithIgnoredTrackedFiles() { { items: [{ path: "-generated/b.ts" }] }, ); + // Git pathspec defaults cannot override the literal scope selected by the helper. + for (const mode of ["GIT_GLOB_PATHSPECS", "GIT_ICASE_PATHSPECS"]) { + await execFile( + process.execPath, + [ + path.join(fixture.scan.pluginRoot, "mcp", "helpers.mjs"), + "generate-in-scope-files", + `--repo=${fixture.repoRoot}`, + "--scope=-generated", + `--out=${fixture.scanInventory}`, + ], + { env: { ...process.env, [mode]: "1" } }, + ); + assert.equal( + await readFile(fixture.scanInventory, "utf8"), + "-generated/a.ts\n-generated/b.ts\n", + ); + } + const previous = await readFile(fixture.scanInventory); await fixture.writeRepositoryFile(".git/index", "invalid"); await assert.rejects( 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 f7712ba2d..c6ce61d45 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 @@ -1456,6 +1456,8 @@ async function testWorkerRuntimeSettings() { "CODEX_SECURITY_GIT", "GIT_SSH_COMMAND", "GIT_CONFIG_GLOBAL", + "GIT_GLOB_PATHSPECS", + "GIT_ICASE_PATHSPECS", "CODEX_CLI_PATH", "CODEX_BROWSER_USE_NODE_PATH", "CODEX_HOME", diff --git a/plugins/codex-security/scripts/workbench_constants.py b/plugins/codex-security/scripts/workbench_constants.py index befd0c27c..695d48172 100644 --- a/plugins/codex-security/scripts/workbench_constants.py +++ b/plugins/codex-security/scripts/workbench_constants.py @@ -58,6 +58,8 @@ GIT_REPOSITORY_ENVIRONMENT = ( "GIT_COMMON_DIR", "GIT_DIR", "GIT_DISCOVERY_ACROSS_FILESYSTEM", + "GIT_GLOB_PATHSPECS", + "GIT_ICASE_PATHSPECS", "GIT_INDEX_FILE", "GIT_NAMESPACE", "GIT_OBJECT_DIRECTORY", diff --git a/plugins/codex-security/tests/test_workbench_target.py b/plugins/codex-security/tests/test_workbench_target.py index 3d311fdc7..01f24a41e 100644 --- a/plugins/codex-security/tests/test_workbench_target.py +++ b/plugins/codex-security/tests/test_workbench_target.py @@ -1166,13 +1166,17 @@ def test_windows_directory_query_preserves_exclusions_with_inherited_noglob( assert dict(os.environ) == environment -def test_directory_content_digest_uses_git_file_set(tmp_path: Path) -> None: +@pytest.mark.parametrize("pathspec_mode", ["GIT_GLOB_PATHSPECS", "GIT_ICASE_PATHSPECS"]) +def test_directory_content_digest_uses_git_file_set( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, pathspec_mode: str +) -> None: target = tmp_path / "target" initialize_unborn_git_repository(target) (target / ".gitignore").write_text("ignored-cache/\n") source = target / "app.py" source.write_text("print('fixture')\n") original_digest = directory_content_digest(target) + monkeypatch.setenv(pathspec_mode, "1") source.write_text("print('changed')\n") assert directory_content_digest(target) != original_digest From 6993830d5d8bca07cb17ad298c2bd4deab08cbac Mon Sep 17 00:00:00 2001 From: Michael D'Angelo Date: Tue, 10 Nov 2026 02:18:52 -0800 Subject: [PATCH 13/28] fix(native): read sealed artifacts in searchable Linux directories (#2564) * fix(native): read sealed artifacts in searchable Linux directories * test(native): unlink the known directory symlink in the scan read proof --- .../codex-security/native/proof-scan-read.mts | 18 +++++++++++++++++- .../native/src/scan_read_unix.rs | 10 ++++++++-- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/plugins/codex-security/native/proof-scan-read.mts b/plugins/codex-security/native/proof-scan-read.mts index 0e76d99ac..4b65d24a9 100644 --- a/plugins/codex-security/native/proof-scan-read.mts +++ b/plugins/codex-security/native/proof-scan-read.mts @@ -1,12 +1,14 @@ import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import { + chmodSync, mkdirSync, mkdtempSync, realpathSync, renameSync, rmSync, symlinkSync, + unlinkSync, writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; @@ -65,6 +67,20 @@ export function scanReadProof(): Record { renameSync(scan, moved); renameSync(moved, scan); } + if (process.platform === "linux") { + chmodSync(artifacts, 0o100); + chmodSync(scan, 0o100); + try { + const searchable = openRoot(scan); + assert.deepEqual( + chunks(openFile(searchable, "artifacts/receipt.json")), + payload, + ); + } finally { + chmodSync(scan, 0o700); + chmodSync(artifacts, 0o700); + } + } const root = openRoot(scan); assert.deepEqual(chunks(openFile(root, "artifacts/receipt.json")), payload); assert.equal(root.openFile("missing.json"), null); @@ -97,7 +113,7 @@ export function scanReadProof(): Record { assert.deepEqual(chunks(held), payload); assert.throws(() => root.openFile("artifacts/receipt.json")); held.close(); - rmSync(artifacts); + unlinkSync(artifacts); renameSync(moved, artifacts); } assert.throws(() => held.read(1), /closed/i); diff --git a/plugins/codex-security/native/src/scan_read_unix.rs b/plugins/codex-security/native/src/scan_read_unix.rs index 31690413d..e87a9ddaf 100644 --- a/plugins/codex-security/native/src/scan_read_unix.rs +++ b/plugins/codex-security/native/src/scan_read_unix.rs @@ -11,6 +11,12 @@ use std::{ path::PathBuf, }; +// These descriptors anchor named lookups and metadata checks without listing the directory. +#[cfg(target_os = "linux")] +const DIRECTORY_ACCESS: i32 = libc::O_PATH; +#[cfg(not(target_os = "linux"))] +const DIRECTORY_ACCESS: i32 = libc::O_RDONLY; + pub(crate) struct ScanReadRootBackend { path: PathBuf, directory: Option, @@ -93,7 +99,7 @@ impl ScanReadRootBackend { let directory = open_at( libc::AT_FDCWD, path.as_os_str(), - libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW, + DIRECTORY_ACCESS | libc::O_DIRECTORY | libc::O_NOFOLLOW, ) .map_err(|error| failure("Cannot open scan directory", error))?; let opened = directory @@ -139,7 +145,7 @@ impl ScanReadRootBackend { let directory = match open_at( parent, OsStr::new(part), - libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW, + DIRECTORY_ACCESS | libc::O_DIRECTORY | libc::O_NOFOLLOW, ) { Ok(directory) => directory, Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None), From a353226b474921e17f65834ab101db5b0ad47a16 Mon Sep 17 00:00:00 2001 From: Michael D'Angelo Date: Tue, 10 Nov 2026 02:28:49 -0800 Subject: [PATCH 14/28] fix(workbench): pin Git metadata on another Windows fixed drive (#2539) * fix(workbench): recover nested Windows inventories with a pinned Git marker * fix(workbench): pin Git metadata on a separate Windows fixed drive --------- Co-authored-by: mldangelo-oai <269034524+mldangelo-oai@users.noreply.github.com> Co-authored-by: Codex --- .../scripts/windows_scan_local_files.py | 3 +- .../tests/test_workbench_target.py | 51 ++++++++++++++++++- 2 files changed, 52 insertions(+), 2 deletions(-) diff --git a/plugins/codex-security/scripts/windows_scan_local_files.py b/plugins/codex-security/scripts/windows_scan_local_files.py index f7d5c3b89..aed3acf64 100644 --- a/plugins/codex-security/scripts/windows_scan_local_files.py +++ b/plugins/codex-security/scripts/windows_scan_local_files.py @@ -1044,11 +1044,12 @@ def pinned_root_git_marker( not cwd.is_absolute() or not metadata.is_absolute() or len(cwd.drive) != 2 - or cwd.drive != metadata.drive + or len(metadata.drive) != 2 or len(work_tree.parts) < 2 or cwd.parts[: len(work_tree.parts)] != work_tree.parts or len(metadata.parts) < 2 or _GetDriveTypeW(cwd.anchor) != _DRIVE_FIXED + or _GetDriveTypeW(metadata.anchor) != _DRIVE_FIXED ): yield None return diff --git a/plugins/codex-security/tests/test_workbench_target.py b/plugins/codex-security/tests/test_workbench_target.py index 01f24a41e..3900c0a60 100644 --- a/plugins/codex-security/tests/test_workbench_target.py +++ b/plugins/codex-security/tests/test_workbench_target.py @@ -1724,7 +1724,9 @@ def test_root_git_marker_declines_unsupported_paths_without_opening_directories( ) -> None: import windows_scan_local_files as windows_files - monkeypatch.setattr(windows_files, "_GetDriveTypeW", lambda _anchor: 3) + monkeypatch.setattr( + windows_files, "_GetDriveTypeW", lambda anchor: 4 if anchor == "D:\\" else 3 + ) def unexpected_open(*_args, **_kwargs): pytest.fail("unsupported paths must be declined before opening directories") @@ -1732,6 +1734,7 @@ def test_root_git_marker_declines_unsupported_paths_without_opening_directories( monkeypatch.setattr(windows_files, "_open_directory", unexpected_open) for target, metadata in ( (r"C:\repo", r"D:\metadata"), + (r"C:\repo", r"\\server.invalid\share\metadata"), (r"\\?\C:\repo", r"\\?\C:\metadata"), (r"\\server.invalid\share\repo", r"\\server.invalid\share\metadata"), (r"C:checkout", r"C:\metadata"), @@ -1745,6 +1748,52 @@ def test_root_git_marker_declines_unsupported_paths_without_opening_directories( assert selected is None +@pytest.mark.native_windows +@pytest.mark.skipif(os.name != "nt", reason="requires Windows drive semantics") +def test_root_git_marker_pins_the_checkout_and_metadata_on_independent_fixed_drives( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + from unittest.mock import MagicMock + + import windows_scan_local_files as windows_files + + root, metadata = Path(r"C:\worktree"), Path(r"D:\metadata") + scope = root / "selected" + marker = tmp_path / "gitfile" + marker.write_bytes(f"gitdir: {metadata.as_posix()}\n".encode()) + drives = [] + opened = [] + + def fixed_drive(anchor): + drives.append(anchor) + return 3 + + def open_fixture(path): + opened.append(path) + return MagicMock(value=path) + + monkeypatch.setattr(windows_files, "_GetDriveTypeW", fixed_drive) + monkeypatch.setattr(windows_files, "_open_directory", open_fixture) + + monkeypatch.setattr(windows_files, "_final_path", windows_files._extended_path) + + def open_marker(parent, name, context): + assert (parent, name) == (root, ".git") + return os.open(marker, os.O_RDONLY | os.O_BINARY), name + + monkeypatch.setattr(windows_files, "open_read_fd_with_path", open_marker) + with windows_files.pinned_root_git_marker(scope, metadata, work_tree=root) as selected: + assert selected == Path("..", ".git") + assert opened == [ + Path(root.anchor), + root, + scope, + Path(metadata.anchor), + metadata, + ] + assert set(drives) == {root.anchor, metadata.anchor} + + @pytest.mark.native_windows @pytest.mark.skipif(os.name != "nt", reason="requires Windows directory junctions") @pytest.mark.parametrize("inside_scope", [False, True]) From 943ea05777f98575197ce35b18f59603aad25854 Mon Sep 17 00:00:00 2001 From: Michael D'Angelo Date: Tue, 10 Nov 2026 02:28:58 -0800 Subject: [PATCH 15/28] fix(windows): preserve long Git metadata in reviewed patch replay (#2543) * fix(windows): preserve long Git metadata in reviewed patch replay * fix(windows): keep reviewed patch replay within source limits * fix(windows): preserve metadata-free LF patch replay * test(workbench): select short replay case only on Windows --------- Co-authored-by: Codex --- .../scripts/windows_scan_local_files.py | 49 ++++ .../codex-security/scripts/workbench_db.py | 45 +-- .../scripts/workbench_remediation.py | 86 ++++++ .../scripts/workbench_target.py | 22 +- .../tests/test_workbench_target.py | 260 +++++++++++++++++- 5 files changed, 429 insertions(+), 33 deletions(-) diff --git a/plugins/codex-security/scripts/windows_scan_local_files.py b/plugins/codex-security/scripts/windows_scan_local_files.py index aed3acf64..5a9cbb571 100644 --- a/plugins/codex-security/scripts/windows_scan_local_files.py +++ b/plugins/codex-security/scripts/windows_scan_local_files.py @@ -1088,6 +1088,55 @@ def pinned_root_git_marker( yield marker +def pin_replay_metadata( + pins: contextlib.ExitStack, metadata: Path | None, scratch: Path +) -> Path | None: + """Bind the selected metadata and fresh private Windows scratch before copying into it.""" + if os.name != "nt" or metadata is None: + return None + try: + with contextlib.ExitStack() as checked: + checked.enter_context(_locked_parent(metadata, "HEAD", create=False)) + checked.enter_context(_locked_parent(scratch.parent, scratch.name, create=False)) + directory = _create_file( + scratch, + access=_FILE_TRAVERSE | _FILE_READ_ATTRIBUTES | _READ_CONTROL, + share=_FILE_SHARE_READ | _FILE_SHARE_WRITE, + disposition=_OPEN_EXISTING, + flags=_FILE_FLAG_BACKUP_SEMANTICS | _FILE_FLAG_OPEN_REPARSE_POINT, + ) + assert directory is not None and directory.value is not None + checked.enter_context(directory) + _verify_directory(directory.value, scratch) + if _output_directory_grants(directory.value, scratch): + return None + pins.enter_context(checked.pop_all()) + except (OSError, ValueError): + return None + return metadata + + +@contextlib.contextmanager +def pinned_replay_gitfile(checkout: Path, metadata: Path) -> Iterator[Path]: + """Keep Git's short metadata pointer outside the replay and immutable while Git uses it.""" + with _locked_parent(checkout, ".git", create=False): + # Git reads this path relative to its unchanged worktree cwd. Both volumes' + # literal ancestors are pinned, including the temporary directory above checkout. + marker = checkout.parent / "reviewed.git" + handle = _create_file( + marker, + access=_GENERIC_WRITE | _FILE_READ_ATTRIBUTES, + share=_FILE_SHARE_READ, + disposition=_CREATE_NEW, + flags=_FILE_ATTRIBUTE_NORMAL | _FILE_FLAG_OPEN_REPARSE_POINT, + ) + assert handle is not None and handle.value is not None + with handle: + _verify_regular_file(handle.value, marker) + _write_all(handle.value, f"gitdir: {metadata.as_posix()}\n".encode("utf-8")) + yield Path("..") / marker.name + + def open_read_fd(scan_dir: Path, relative_path: str, context: str) -> int: """Open a verified regular file and return an owned binary read descriptor.""" diff --git a/plugins/codex-security/scripts/workbench_db.py b/plugins/codex-security/scripts/workbench_db.py index d97437868..716b2589d 100644 --- a/plugins/codex-security/scripts/workbench_db.py +++ b/plugins/codex-security/scripts/workbench_db.py @@ -54,6 +54,7 @@ from finalize_scan_contract import ( open_scan_local_file_descriptor, ) from finding_preview import bounded_finding_details +from windows_scan_local_files import pin_replay_metadata from workbench import handoff from workbench.storage import ( create_private_directory, @@ -2371,12 +2372,17 @@ def require_reviewed_patch_applied( excluded = (Path(scan["scan_dir"]),) # Unborn repositories still need their config while metadata junctions are deferred. git_dir = git_output(target, "rev-parse", "--absolute-git-dir") + metadata = Path(git_dir) if git_dir is not None else None if not unversioned: repository, pathspec = git_worktree_context(target) if git_dir is None: raise SystemExit("Could not inspect the selected Git working tree.") excluded += tuple(path for path, _ in git_submodule_entries(target)) - with tempfile.TemporaryDirectory(prefix="codex-security-remediation-") as temporary: + with ( + tempfile.TemporaryDirectory(prefix="codex-security-remediation-") as temporary, + ExitStack() as pins, + ): + pinned_metadata = pin_replay_metadata(pins, metadata, Path(temporary)) reviewed_patch = Path(temporary) / "reviewed.patch" digest = hashlib.sha256() with open_scan_local_file(Path(scan["scan_dir"]), patch_path) as source: @@ -2392,35 +2398,28 @@ def require_reviewed_patch_applied( junctions = copy_directory_excluding(target, checkout, excluded) else: _, junctions = copy_git_worktree_files(target, checkout_root, excluded) - arguments = ["apply", "--reverse", "--whitespace=nowarn"] - if unversioned: - arguments.append("--no-index") - elif pathspec != ".": - arguments.append(f"--directory={pathspec}") - arguments.append(str(reviewed_patch)) - applied = git_command( - checkout if unversioned else checkout_root, - *arguments, - text=False, - git_dir=Path(git_dir) if git_dir is not None else None, - work_tree=checkout_root if git_dir is not None else None, + short, replay_root = remediation_state.reverse_reviewed_patch( + target, + checkout_root, + metadata, + pinned_metadata, + remediation["patch_digest"], + pins, + reviewed_patch, + None if unversioned else pathspec, ) - if applied.returncode != 0: - raise SystemExit( - "The selected checkout does not contain the reviewed remediation patch. Apply exactly that patch before recording it as applied." - ) restore_directory_junctions( target if unversioned else repository, checkout if unversioned else checkout_root, junctions, ) reverted_digest = ( - directory_content_digest(checkout) + directory_content_digest(checkout, replay_git_dir=replay_root) if unversioned else worktree_content_digest_for_context( checkout_root, pathspec or ".", - git_dir=Path(git_dir), + git_dir=short or metadata, work_tree=checkout_root, ) ) @@ -2431,12 +2430,16 @@ def require_reviewed_patch_applied( checkout, "-c", "core.autocrlf=input", - *arguments, + "apply", + "--reverse", + "--whitespace=nowarn", + "--no-index", + str(reviewed_patch), text=True, ) if applied_without_conversion.returncode == 0: restore_directory_junctions(target, checkout, junctions) - reverted_digest = directory_content_digest(checkout) + reverted_digest = directory_content_digest(checkout, replay_git_dir=replay_root) if reverted_digest != remediation["base_content_digest"]: raise SystemExit( "The selected checkout contains changes outside the reviewed patch. Remove them before recording the patch as applied." diff --git a/plugins/codex-security/scripts/workbench_remediation.py b/plugins/codex-security/scripts/workbench_remediation.py index a0848f8e2..1e197517a 100644 --- a/plugins/codex-security/scripts/workbench_remediation.py +++ b/plugins/codex-security/scripts/workbench_remediation.py @@ -46,6 +46,92 @@ COMMANDS = { SCAN_STATUS_ERROR = "Remediation is available only for successfully completed scans." +def reverse_reviewed_patch( + target: Path, + checkout: Path, + metadata: Path | None, + pinned_metadata: Path | None, + patch_digest: str, + pins: ExitStack, + patch: Path, + pathspec: str | None, +) -> tuple[Path | None, Path | None]: + """Reverse reviewed bytes and select the Git references for subsequent content snapshots.""" + + arguments = ["--reverse", "--whitespace=nowarn"] + if pathspec is None: + arguments.append("--no-index") + elif pathspec != ".": + arguments.append(f"--directory={pathspec}") + arguments.append(str(patch)) + + def reverse(*, git_dir: Path | None, check: bool = False): + return git_command( + checkout, + "apply", + *(["--check"] if check else []), + *arguments, + text=False, + git_dir=git_dir, + work_tree=checkout if git_dir else None, + environment_overrides={"LC_ALL": "C", "LANGUAGE": "C"} if check else None, + ) + + applied = reverse(git_dir=metadata) + short = None + diagnostic = b"fatal: '$GIT_DIR' too big" + if ( + os.name == "nt" + and metadata is not None + and applied.returncode == 128 + and not applied.stdout + and b"GIT_DIR" in applied.stderr + ): + # Confirm translated messages without applying the reverse patch twice. + failure = ( + applied + if diagnostic in applied.stderr.splitlines() + else reverse(git_dir=metadata, check=True) + ) + if ( + failure.returncode == 128 + and not failure.stdout + and diagnostic in failure.stderr.splitlines() + ): + short = prepare_replay_gitfile(checkout, pinned_metadata, patch_digest, pins) + applied = reverse(git_dir=short) + if applied.returncode != 0: + raise SystemExit( + "The selected checkout does not contain the reviewed remediation patch. Apply exactly that patch before recording it as applied." + ) + replay_root = None + if pathspec is None and short is not None: + selected_root = git_output(target, "rev-parse", "--show-toplevel") + if selected_root and Path(selected_root).samefile(target): + replay_root = short + return short, replay_root + + +def prepare_replay_gitfile( + checkout: Path, pinned_metadata: Path | None, patch_digest: str, pins: ExitStack +) -> Path: + """Retain the verified patch and short metadata reference through the final snapshot.""" + if pinned_metadata is None: + raise SystemExit( + "Could not bind the selected Windows Git directory and private patch replay directory." + ) + from windows_scan_local_files import open_read_fd, pinned_replay_gitfile + + try: + short = pins.enter_context(pinned_replay_gitfile(checkout, pinned_metadata)) + fd = open_read_fd(checkout.parent, "reviewed.patch", "reviewed remediation patch") + patch = pins.enter_context(os.fdopen(fd, "rb")) + matching_patch_metadata(patch, patch_digest) + except (OSError, ValueError) as exc: + raise SystemExit(f"Could not verify the reviewed patch replay: {exc}") from exc + return short + + def require_available(connection: sqlite3.Connection, args: Any, require_scan: Any) -> None: """Require a successfully completed scan for commands that act on a remediation request.""" if args.command not in COMMANDS: diff --git a/plugins/codex-security/scripts/workbench_target.py b/plugins/codex-security/scripts/workbench_target.py index 5f62cf3a0..612ec0107 100644 --- a/plugins/codex-security/scripts/workbench_target.py +++ b/plugins/codex-security/scripts/workbench_target.py @@ -956,11 +956,16 @@ def _windows_inventory_query( return result -def git_directory_snapshot_paths(target: Path) -> list[Path] | None: - repository_root = git_output(target, "rev-parse", "--show-toplevel") - if repository_root is None: - return None - repository, pathspec = git_worktree_context(target) +def git_directory_snapshot_paths( + target: Path, *, replay_git_dir: Path | None = None +) -> list[Path] | None: + if replay_git_dir is None: + if git_output(target, "rev-parse", "--show-toplevel") is None: + return None + repository, pathspec = git_worktree_context(target) + else: + # The temporary copy of an unborn repository uses the selected Git config and index. + repository, pathspec = target, "." scope = repository / pathspec scope_depth = len(Path(pathspec).parts) matching_prefixes: dict[str, bool] = {} @@ -988,6 +993,8 @@ def git_directory_snapshot_paths(target: Path) -> list[Path] | None: "-z", "--", inventory_pathspec, + git_dir=replay_git_dir, + work_tree=repository if replay_git_dir else None, ) if listed is None: raise SystemExit("Could not inspect files in the selected Git working tree.") @@ -1046,7 +1053,7 @@ def git_directory_snapshot_paths(target: Path) -> list[Path] | None: if _WINDOWS: # Git omits empty untracked directories from its file listing. Inventory # junction identities independently of whether their targets contain files. - git_directory = git_output(target, "rev-parse", "--absolute-git-dir") + git_directory = replay_git_dir or git_output(target, "rev-parse", "--absolute-git-dir") if git_directory is None: raise SystemExit("Could not inspect the selected Git working tree.") directories = _windows_inventory_query( @@ -1163,6 +1170,7 @@ def directory_content_digest( excluded: tuple[Path, ...] = (), include_ignored: bool = False, include_git_metadata: bool = False, + replay_git_dir: Path | None = None, ) -> str: def raise_walk_error(error: OSError) -> None: raise error @@ -1175,7 +1183,7 @@ def directory_content_digest( target, excluded, include_git_metadata=include_git_metadata, onerror=raise_walk_error ) if include_ignored - else git_directory_snapshot_paths(target) + else git_directory_snapshot_paths(target, replay_git_dir=replay_git_dir) ) if paths is None: paths = source_directory_snapshot_paths(target, excluded) diff --git a/plugins/codex-security/tests/test_workbench_target.py b/plugins/codex-security/tests/test_workbench_target.py index 3900c0a60..5f2b0494e 100644 --- a/plugins/codex-security/tests/test_workbench_target.py +++ b/plugins/codex-security/tests/test_workbench_target.py @@ -155,12 +155,14 @@ def test_recorded_checkout_distinguishes_a_replaced_parent_from_a_missing_path( def write_reviewed_patch( tmp_path: Path, source: Path, patch: bytes, revision: str = "unversioned" ) -> dict[str, object]: + from filesystem_identity import serialize_filesystem_identity + scan_dir = tmp_path / "scan" scan_dir.mkdir(mode=0o700) (scan_dir / "reviewed.patch").write_bytes(patch) return { "target_path": str(source), - "target_inode": source.stat().st_ino, + "target_inode": serialize_filesystem_identity(source.stat().st_ino), "target_revision": revision, "scan_dir": str(scan_dir), } @@ -174,6 +176,218 @@ def reviewed_remediation(patch: bytes, revision: str, digest: str) -> dict[str, } +@pytest.mark.cross_platform +@pytest.mark.parametrize("layout", ["separate", "linked", "unborn", "unborn-root"]) +def test_reviewed_patch_uses_long_source_metadata_in_its_private_replay( + tmp_path: Path, layout: str, monkeypatch: pytest.MonkeyPatch +) -> None: + import workbench_db + + # The metadata argument is long in UTF-8 even on hosts with short temporary paths. + padding = max(1, (230 - len((tmp_path / "metadata-").as_posix().encode("utf-8")) + 2) // 3) + metadata = tmp_path / ("metadata-" + "界" * padding) + source = tmp_path / "source" + if layout == "unborn-root": + source, metadata = metadata, metadata / ".git" + subprocess.run(["git", "init", "-q", str(source)], check=True) + else: + subprocess.run( + ["git", "init", "-q", "--separate-git-dir", str(metadata), str(source)], check=True + ) + subprocess.run(["git", "-C", str(source), "config", "core.autocrlf", "false"], check=True) + (source / "file.txt").write_bytes(b"before\n") + revision = "unversioned" + if layout in {"separate", "linked"}: + subprocess.run(["git", "-C", str(source), "add", "file.txt"], check=True) + subprocess.run( + [ + "git", + "-C", + str(source), + "-c", + "user.name=Fixture", + "-c", + "user.email=f@example.invalid", + "commit", + "-qm", + "base", + ], + check=True, + ) + if layout == "linked": + linked = tmp_path / "linked" + subprocess.run( + ["git", "-C", str(source), "worktree", "add", "--detach", str(linked)], check=True + ) + source = linked + revision = subprocess.check_output( + ["git", "-C", str(source), "rev-parse", "HEAD"], text=True + ).strip() + marker = source / ".git/HEAD" if layout == "unborn-root" else source / ".git" + original_marker = marker.read_bytes() + (metadata / "info/exclude").write_bytes(b"ignored.fixture\n") + (source / "ignored.fixture").write_bytes(b"outside the recorded content\n") + if os.name == "nt" and revision == "unversioned": + # The private copy keeps the original gitdir-conditional visibility when using the retry. + global_config, included, excludes = ( + tmp_path / name for name in ("global", "include", "excludes") + ) + excludes.write_bytes(b"conditional.fixture\n") + subprocess.run( + ["git", "config", "--file", included, "core.excludesFile", excludes.as_posix()], + check=True, + ) + subprocess.run( + [ + "git", + "config", + "--file", + global_config, + f"includeIf.gitdir:{metadata.as_posix()}.path", + included.as_posix(), + ], + check=True, + ) + monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(global_config)) + (source / "conditional.fixture").write_bytes(b"excluded by the selected Git directory\n") + ignored = subprocess.check_output( + ["git", "-C", source, "check-ignore", "conditional.fixture"] + ) + assert ignored.strip() + patch = b"diff --git a/file.txt b/file.txt\n--- a/file.txt\n+++ b/file.txt\n@@ -1 +1 @@\n-before\n+after\n" + scan = write_reviewed_patch(tmp_path, source, patch, revision) + _, digest = workbench_db.remediation_checkout_snapshot(scan) + remediation = reviewed_remediation(patch, revision, digest) + selected_file = source / "file.txt" + selected_file.write_bytes(b"after\n") + _, applied_digest = workbench_db.remediation_checkout_snapshot(scan) + verify = workbench_db.require_reviewed_patch_applied + assert verify(scan, remediation, "reviewed.patch") == applied_digest + assert selected_file.read_bytes() == b"after\n" + selected_file.write_bytes(b"other\n") + with pytest.raises(SystemExit, match="does not contain the reviewed remediation patch"): + verify(scan, remediation, "reviewed.patch") + assert selected_file.read_bytes() == b"other\n" + selected_file.write_bytes(b"after\n") + (source / "unrelated.txt").write_bytes(b"keep me\n") + with pytest.raises(SystemExit, match="changes outside the reviewed patch"): + verify(scan, remediation, "reviewed.patch") + assert (source / "unrelated.txt").read_bytes() == b"keep me\n" + (source / "unrelated.txt").unlink() + malformed = b"not a patch\n" + (tmp_path / "scan/reviewed.patch").write_bytes(malformed) + with pytest.raises(SystemExit, match="does not contain the reviewed remediation patch"): + verify(scan, reviewed_remediation(malformed, revision, digest), "reviewed.patch") + assert marker.read_bytes() == original_marker + assert selected_file.read_bytes() == b"after\n" + + +@pytest.mark.native_windows +@pytest.mark.skipif(os.name != "nt", reason="requires Windows directory and file sharing") +def test_replay_gitfile_remains_bound_until_the_private_replay_is_removed(tmp_path: Path) -> None: + import tempfile + from contextlib import ExitStack + + import windows_scan_local_files as windows + import workbench_target + + source = tmp_path / "source" + foreign = tmp_path / "foreign" + initialize_git_repository(source) + initialize_git_repository(foreign) + metadata = source / ".git" + stages = tmp_path / "replays" + stages.mkdir() + + def interrupt_replay(): + with tempfile.TemporaryDirectory(dir=stages) as temporary, ExitStack() as pins: + scratch = Path(temporary) + checkout = scratch / "checkout" + checkout.mkdir() + (checkout / ".git").write_bytes(f"gitdir: {(foreign / '.git').as_posix()}\n".encode()) + assert windows.pin_replay_metadata(pins, metadata, scratch) == metadata + with pytest.raises(PermissionError): + scratch.rename(stages / "elsewhere") + short = pins.enter_context(windows.pinned_replay_gitfile(checkout, metadata)) + assert ( + Path( + workbench_target.git_output( + checkout, + "rev-parse", + "--absolute-git-dir", + git_dir=short, + work_tree=checkout, + ) + ) + == metadata + ) + with pytest.raises(PermissionError): + (checkout / short).write_bytes(b"other") + for path in (metadata, checkout, scratch, checkout / short): + with pytest.raises(PermissionError): + path.rename(path.with_name("replaced")) + raise KeyboardInterrupt + + with pytest.raises(KeyboardInterrupt): + interrupt_replay() + assert not list(stages.iterdir()) + assert metadata.is_dir() and (foreign / ".git").is_dir() + + +@pytest.mark.native_windows +@pytest.mark.skipif(os.name != "nt", reason="requires Windows regular-file and junction checks") +@pytest.mark.parametrize( + "change", ["foreign-pointer", "changed-patch", "replaced-parent", "writable-scratch"] +) +def test_short_git_reference_refuses_changed_replay_inputs( + tmp_path: Path, change: str, monkeypatch: pytest.MonkeyPatch +) -> None: + from contextlib import ExitStack + + import windows_scan_local_files as windows + import workbench_remediation + + metadata, scratch = tmp_path / "metadata", tmp_path / "scratch" + metadata.mkdir() + scratch.mkdir() + worktree = scratch / "checkout" + worktree.mkdir() + patch = scratch / "reviewed.patch" + patch.write_bytes(b"expected") + expected = "sha256:" + hashlib.sha256(patch.read_bytes()).hexdigest() + marker = scratch / "reviewed.git" + if change == "foreign-pointer": + marker.write_bytes(b"gitdir: foreign\n") + elif change == "changed-patch": + patch.write_bytes(b"changed") + elif change == "replaced-parent": + alias = tmp_path / "alias" + subprocess.run(["cmd", "/c", "mklink", "/J", str(alias), str(scratch)], check=True) + worktree = alias / "checkout" + else: + subprocess.run(["icacls.exe", str(scratch), "/grant", "*S-1-1-0:(WD)"], check=True) + failed = subprocess.CompletedProcess([], 128, b"", b"fatal: '$GIT_DIR' too big\n") + monkeypatch.setattr(workbench_remediation, "git_command", lambda *args, **kwargs: failed) + with ExitStack() as pins: + selected = windows.pin_replay_metadata(pins, metadata, scratch) + if change == "writable-scratch": + assert selected is None + with pytest.raises(SystemExit, match="Could not bind"): + workbench_remediation.reverse_reviewed_patch( + tmp_path, worktree, metadata, selected, expected, pins, patch, "." + ) + assert not marker.exists() + return + with pytest.raises(SystemExit, match="Could not verify|Patch digest does not match"): + workbench_remediation.reverse_reviewed_patch( + tmp_path, worktree, metadata, selected, expected, pins, patch, "." + ) + if change == "foreign-pointer": + assert marker.read_bytes() == b"gitdir: foreign\n" + if change == "replaced-parent": + assert not marker.exists() + + @pytest.mark.parametrize( ("git_repository", "git_exclusion"), [ @@ -310,6 +524,7 @@ def test_versioned_reviewed_patch_preserves_nested_junctions( populated: bool, ) -> None: import workbench_db + import workbench_remediation repository = tmp_path / "repository" initialize_git_repository(repository) @@ -327,7 +542,7 @@ def test_versioned_reviewed_patch_preserves_nested_junctions( junction = nested / "linked" junction_factory(junction, outside) relative_junction = junction.relative_to(repository) - original_command = workbench_db.git_command + original_command = workbench_remediation.git_command original_restore = workbench_db.restore_directory_junctions reversed_roots: list[Path] = [] restored: list[Path] = [] @@ -351,7 +566,7 @@ def test_versioned_reviewed_patch_preserves_nested_junctions( original_restore(source, destination, junctions) restored.append(destination) - monkeypatch.setattr(workbench_db, "git_command", command) + monkeypatch.setattr(workbench_remediation, "git_command", command) monkeypatch.setattr(workbench_db, "restore_directory_junctions", restore) assert_reviewed_change( target, @@ -511,10 +726,43 @@ def test_reviewed_patch_restores_junction_git_context( assert (source / patched).read_bytes() == after.replace("\n", newline).encode() -@pytest.mark.cross_platform -def test_reviewed_patch_preserves_scoped_unborn_lf_bytes(tmp_path: Path) -> None: +@pytest.mark.parametrize( + "short_reference", + [ + pytest.param(False, marks=pytest.mark.cross_platform), + pytest.param( + True, + marks=[ + pytest.mark.native_windows, + pytest.mark.skipif(os.name != "nt", reason="requires Windows replay binding"), + ], + ), + ], + ids=["ordinary", "short-reference"], +) +def test_reviewed_patch_preserves_scoped_unborn_lf_bytes( + tmp_path: Path, short_reference: bool, monkeypatch: pytest.MonkeyPatch +) -> None: + import workbench_remediation + repository = tmp_path / "repository" initialize_unborn_git_repository(repository) + references = [] + reverse = workbench_remediation.reverse_reviewed_patch + git = workbench_remediation.git_command + + def record_references(*args, **kwargs): + selected = reverse(*args, **kwargs) + references.append(selected) + return selected + + def require_short_reference(target, *args, **kwargs): + if short_reference and kwargs.get("git_dir") == repository / ".git": + return subprocess.CompletedProcess([], 128, b"", b"fatal: '$GIT_DIR' too big\n") + return git(target, *args, **kwargs) + + monkeypatch.setattr(workbench_remediation, "reverse_reviewed_patch", record_references) + monkeypatch.setattr(workbench_remediation, "git_command", require_short_reference) attributes = tmp_path / "attributes" attributes.write_text("*.txt text eol=crlf\n") subprocess.run( @@ -526,6 +774,8 @@ def test_reviewed_patch_preserves_scoped_unborn_lf_bytes(tmp_path: Path) -> None assert_reviewed_change(source, tmp_path, "app.txt", "before\n", "after\n", newline="\n") assert (source / "app.txt").read_bytes() == b"after\n" + if short_reference: + assert references[0][0] is not None def assert_reviewed_change( From fbfba97201ba051e7e06749a16d04b76bf1b381e Mon Sep 17 00:00:00 2001 From: Michael D'Angelo Date: Tue, 10 Nov 2026 02:29:30 -0800 Subject: [PATCH 16/28] fix(windows): reuse verified generated plugin cache content (#2538) * fix(windows): retry rolled-back native plugin cache activation * fix(windows): verify recovered plugin entries against the selected source * fix(windows): accept regenerated native command output after recovery * fix(sdk): reuse verified native command migrations * fix(sdk): verify generated command skills before cache reuse * fix(sdk): preserve runtime files alongside matching native command output --------- Co-authored-by: mldangelo-oai <269034524+mldangelo-oai@users.noreply.github.com> Co-authored-by: Codex --- sdk/typescript/src/runtime.ts | 187 ++++++++++-- .../runtime-plugin-activation.test.ts | 276 +++++++++++++++++- 2 files changed, 438 insertions(+), 25 deletions(-) diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.ts index de319933a..9540c8a77 100644 --- a/sdk/typescript/src/runtime.ts +++ b/sdk/typescript/src/runtime.ts @@ -20,7 +20,7 @@ import { type ChildProcessWithoutNullStreams, type SpawnOptionsWithoutStdio, } from "node:child_process"; -import { randomUUID } from "node:crypto"; +import { createHash, randomUUID } from "node:crypto"; import { shortArchivePrefix } from "./scan-archive-path.js"; import { chmodSync, @@ -41,6 +41,7 @@ import { lstat, mkdir, mkdtemp, + open, readFile, readdir, realpath, @@ -3321,6 +3322,35 @@ export async function bootstrapPlugin( ); const stagedMatches = staged?.version === version && (await matchesSelected(stagedRoot)); + const matchesNativeInstall = async ( + installedRoot: string, + allowRuntimeFiles = false, + ) => + (await matchesSelected(stagedRoot)) && + // Ordinary reuse permits runtime files when all selected bytes are present. + // The native receipt still verifies the complete generated command output. + ((allowRuntimeFiles && (await matchesSelected(installedRoot, true))) || + (await matchesSelected( + installedRoot, + false, + migratedCommands(installedRoot), + ))); + const nativeMigration = (installedRoot: string, allowRuntimeFiles = false) => + verifiedCommandMigration( + installedRoot, + (path) => matchesNativeInstall(path, allowRuntimeFiles), + options.signal, + ); + const matchesReceipt = async (installedRoot: string, migration: unknown) => { + if ( + typeof migration === "string" && + options.runCodex === undefined && + (await isBundledPluginInstaller(command)) + ) { + return (await nativeMigration(installedRoot, true)) === migration; + } + return matchesSelected(installedRoot, true); + }; if (!stagedMatches) { if (existing !== null) { @@ -3399,7 +3429,10 @@ export async function bootstrapPlugin( isRecord(previous) && typeof previous["installedPath"] === "string" && previous["version"] === version && - (await matchesSelected(previous["installedPath"], true)) + (await matchesReceipt( + previous["installedPath"], + previous["nativeCommandMigration"], + )) ) { return { pluginRoot: root, @@ -3425,13 +3458,7 @@ export async function bootstrapPlugin( } catch (first) { if (!isRolledBackPluginActivation(first)) throw first; throwIfSignalAborted(options.signal); - let bundled: string; - try { - bundled = resolveBundledCodexExecutable(); - } catch { - throw first; - } - if (!(await sameFile(command.command, bundled))) throw first; + if (!(await isBundledPluginInstaller(command))) throw first; // The bundled CLI restored the old cache. A short-lived Windows reader // of the new tree can release it before a fresh installation attempt. try { @@ -3472,22 +3499,28 @@ export async function bootstrapPlugin( ); } - if (retried) { - const installedRoot = installed["installedPath"]; - // The pinned local installer converts plugin commands into skills here. - const migratedCommands = join( - installedRoot, - ".codex-plugin", - "migrated-command-skills", + // The bundled installer removes stale command skills before regenerating them. + const bundledInstaller = + retried || + (options.runCodex === undefined && + (await isBundledPluginInstaller(command))); + const hasSourceMigration = + bundledInstaller && + ( + await lstat(migratedCommands(root)).catch(nullIfMissingFileError) + )?.isDirectory() === true; + const nativeCommandMigration = hasSourceMigration + ? await nativeMigration(installed["installedPath"]) + : undefined; + if ( + retried && + !(hasSourceMigration + ? nativeCommandMigration !== undefined + : await matchesNativeInstall(installed["installedPath"])) + ) { + throw new PluginBootstrapError( + "The retried Codex plugin install did not install the selected plugin contents.", ); - if ( - !(await matchesSelected(stagedRoot)) || - !(await matchesSelected(installedRoot, false, migratedCommands)) - ) { - throw new PluginBootstrapError( - "The retried Codex plugin install did not install the selected plugin contents.", - ); - } } await writeFile( @@ -3495,6 +3528,7 @@ export async function bootstrapPlugin( JSON.stringify({ installedPath: installed["installedPath"], version, + ...(nativeCommandMigration ? { nativeCommandMigration } : {}), }), { mode: 0o600, signal: options.signal }, ); @@ -3509,6 +3543,111 @@ export async function bootstrapPlugin( }; } +async function isBundledPluginInstaller( + command: CodexCommand, +): Promise { + try { + return await sameFile(command.command, resolveBundledCodexExecutable()); + } catch { + return false; + } +} + +function migratedCommands(plugin: string): string { + return join(plugin, ".codex-plugin", "migrated-command-skills"); +} + +// Bind a receipt to the generated files observed in this installation. +// Entry names come from its directories, never from the saved digest. +async function verifiedCommandMigration( + installedRoot: string, + matchesSelected: (installedRoot: string) => Promise, + signal?: AbortSignal, +): Promise { + const digest = createHash("sha256"); + const record = (...fields: (string | number)[]) => + digest.update(JSON.stringify(fields)).update("\n"); + async function visit(path: string, name: string): Promise { + throwIfSignalAborted(signal); + const metadata = await lstat(path, { bigint: true }); + if ( + metadata.isSymbolicLink() || + relative(path, await realpath(path)) !== "" + ) + return false; + if (metadata.isDirectory()) { + record("directory", name); + for (const entry of (await readdir(path)).sort()) { + const child = join(path, entry); + if (!(await visit(child, name ? `${name}/${entry}` : entry))) + return false; + } + return sameInode(metadata, await lstat(path, { bigint: true })); + } + if (!metadata.isFile()) return false; + const file = await open( + path, + constants.O_RDONLY | + (constants.O_NOFOLLOW ?? 0) | + (constants.O_NONBLOCK ?? 0), + ); + try { + const opened = await file.stat({ bigint: true }); + if (!opened.isFile()) return false; + if (!sameInode(metadata, opened)) { + if (process.platform !== "win32") return false; + // Some Windows Node versions report a different device on an open handle. + const { sameCheckedFileDevice } = await import("./contract.js"); + if (!(await sameCheckedFileDevice(file, { path, metadata }, opened))) + return false; + } + const contents = createHash("sha256") + .update(await file.readFile({ signal })) + .digest("hex"); + record("file", name, Number(opened.mode & 0o111n), contents); + } finally { + await file.close(); + } + return true; + } + throwIfSignalAborted(signal); + const installation = await lstat(installedRoot, { bigint: true }).catch( + nullIfMissingFileError, + ); + if ( + !installation?.isDirectory() || + installation.ino === 0n || + !(await matchesSelected(installedRoot)) + ) + return; + try { + const directory = migratedCommands(await realpath(installedRoot)); + const parent = dirname(directory); + if ( + !(await lstat(parent)).isDirectory() || + relative(parent, await realpath(parent)) !== "" + ) + return; + const root = await lstat(directory, { bigint: true }).catch( + nullIfMissingFileError, + ); + if (root && (!root.isDirectory() || !(await visit(directory, "")))) return; + // Native activation replaces the installed directory even at the same version. + if (!sameInode(installation, await lstat(installedRoot, { bigint: true }))) + return; + throwIfSignalAborted(signal); + return root ? `sha256:${digest.digest("hex")}` : "absent"; + } catch (error) { + throwIfSignalAborted(signal); + if ( + !["ENOENT", "ENOTDIR", "ELOOP", "EISDIR", "EACCES", "EPERM"].includes( + nodeErrorCode(error) ?? "", + ) + ) + throw error; + } +} + async function pluginContentsMatch( source: string, destination: string, diff --git a/sdk/typescript/tests-ts/runtime-plugin-activation.test.ts b/sdk/typescript/tests-ts/runtime-plugin-activation.test.ts index 19d441325..770998524 100644 --- a/sdk/typescript/tests-ts/runtime-plugin-activation.test.ts +++ b/sdk/typescript/tests-ts/runtime-plugin-activation.test.ts @@ -1,5 +1,15 @@ import { afterEach, expect, spyOn, test } from "bun:test"; -import { cp, mkdir, readFile, readdir, writeFile } from "node:fs/promises"; +import * as files from "node:fs/promises"; +import { + cp, + mkdir, + readFile, + readdir, + rename, + rm, + symlink, + writeFile, +} from "node:fs/promises"; import { join } from "node:path"; import * as timers from "node:timers/promises"; import * as executable from "../src/codex-sdk-environment.js"; @@ -57,6 +67,7 @@ const fakeCli = ` process.exit(step.exit); } const installedPath = join(home, "installed"); + fs.rmSync(installedPath, { recursive: true, force: true }); fs.cpSync(staged, installedPath, { recursive: true }); if (step.stale) fs.writeFileSync(join(installedPath, "marker.txt"), "previous"); if (step.extraSkill === "installed") addSkill(installedPath, "skills/unselected"); @@ -118,6 +129,7 @@ async function fixture( const command = nodeCommand().command; return { command, + selected, previous, record, previousReceipt, @@ -204,10 +216,272 @@ test result.installedRoot, ); expect(await f.remaining()).toHaveLength(0); + expect((await f.install()).installedRoot).toBe(result.installedRoot); expect(resolver).toHaveBeenCalled(); }, ); +test("only the bundled installer reuses its regenerated command output", async () => { + const f = await fixture([{}, {}, {}], "regenerated"); + using resolver = spyOn( + executable, + "resolveBundledCodexExecutable", + ).mockReturnValue(f.previous); + await f.install(); + expect(await f.remaining()).toHaveLength(2); + + resolver.mockReturnValue(f.command); + const installed = await f.install(); + expect(await f.remaining()).toHaveLength(1); + expect((await f.install()).installedRoot).toBe(installed.installedRoot); + expect(await f.remaining()).toHaveLength(1); + + resolver.mockReturnValue(f.previous); + await f.install(); + expect(await f.remaining()).toHaveLength(0); +}); + +test("rechecks the full marketplace selection and the recovered installed files", async () => { + const f = await fixture([{}, {}, {}], "regenerated"); + using resolver = spyOn( + executable, + "resolveBundledCodexExecutable", + ).mockReturnValue(f.command); + const { installedRoot } = await f.install(); + const staleSkill = join( + f.selected, + ".codex-plugin", + "migrated-command-skills", + "source-command-retired", + "SKILL.md", + ); + await writeFile(staleSkill, "revised stale source"); + await f.install(); + expect(await f.remaining()).toHaveLength(1); + + await mkdir(join(installedRoot, "skills", "other-selection"), { + recursive: true, + }); + await writeFile( + join(installedRoot, "skills", "other-selection", "SKILL.md"), + "other", + ); + await f.install(); + expect(await f.remaining()).toHaveLength(0); + expect(resolver).toHaveBeenCalled(); +}); + +test("preserves runtime files when the selection already contains the native command output", async () => { + const f = await fixture([{}, {}, {}, {}]); + using resolver = spyOn( + executable, + "resolveBundledCodexExecutable", + ).mockReturnValue(f.command); + const { installedRoot } = await f.install(); + const migration = join(".codex-plugin", "migrated-command-skills"); + const generated = join(installedRoot, migration); + await cp(generated, join(f.selected, migration), { recursive: true }); + await f.install(); + const receipt = await readFile(f.record, "utf8"); + expect(JSON.parse(receipt).nativeCommandMigration).toMatch(/^sha256:/u); + const bytecode = join(installedRoot, "scripts", "__pycache__"); + await mkdir(bytecode, { recursive: true }); + const cached = join(bytecode, "helper.cpython-312.pyc"); + await writeFile(cached, "runtime-generated"); + + expect((await f.install()).installedRoot).toBe(installedRoot); + expect(await f.remaining()).toHaveLength(2); + expect(await readFile(cached, "utf8")).toBe("runtime-generated"); + expect(await readFile(f.record, "utf8")).toBe(receipt); + + const skill = join(generated, "source-command-sample", "SKILL.md"); + await rm(skill); + await f.install(); + expect(await f.remaining()).toHaveLength(1); + expect(await readFile(skill, "utf8")).toBe("synthetic skill"); + await mkdir(join(generated, "foreign-command")); + await writeFile(join(generated, "foreign-command", "SKILL.md"), "foreign"); + await f.install(); + expect(await f.remaining()).toHaveLength(0); + expect(await readdir(generated)).toEqual(["source-command-sample"]); + expect(resolver).toHaveBeenCalled(); +}); + +test("a link replacing the installed command migration directory requires reinstall", async () => { + const f = await fixture([{}, {}], "regenerated"); + using resolver = spyOn( + executable, + "resolveBundledCodexExecutable", + ).mockReturnValue(f.command); + const { installedRoot } = await f.install(); + const migration = join( + installedRoot, + ".codex-plugin", + "migrated-command-skills", + ); + const outside = await temporaryDirectory(); + await writeFile(join(outside, "marker.txt"), "unrelated"); + await rm(migration, { recursive: true }); + await symlink( + outside, + migration, + process.platform === "win32" ? "junction" : "dir", + ); + await f.install(); + expect(await f.remaining()).toHaveLength(0); + expect(await readFile(join(outside, "marker.txt"), "utf8")).toBe("unrelated"); + expect(resolver).toHaveBeenCalled(); +}); + +test.each([ + "missing file", + "changed bytes", + "renamed skill", + "changed file type", + "restored source with changed output", + "extra output", + "missing directory", + "nested link", + "previously absent", +] as const)( + "repairs %s in a recorded native command migration", + async (damage) => { + const absent = damage === "previously absent"; + const f = await fixture([{}, {}], absent ? "removed" : "regenerated"); + using resolver = spyOn( + executable, + "resolveBundledCodexExecutable", + ).mockReturnValue(f.command); + const { installedRoot } = await f.install(); + const migration = join( + installedRoot, + ".codex-plugin", + "migrated-command-skills", + ); + const skill = join(migration, "source-command-sample"); + const file = join(skill, "SKILL.md"); + const outside = await temporaryDirectory(); + const sentinel = join(outside, "SKILL.md"); + await writeFile(sentinel, "outside"); + switch (damage) { + case "missing file": + await rm(file); + break; + case "restored source with changed output": + await cp( + join(f.selected, ".codex-plugin", "migrated-command-skills"), + migration, + { recursive: true }, + ); + await writeFile(file, "different skill"); + break; + case "changed bytes": + await writeFile(file, "different skill"); + break; + case "renamed skill": + await rename(skill, join(migration, "other-command-name")); + break; + case "changed file type": + await rm(file); + await mkdir(file); + break; + case "extra output": + await writeFile(join(skill, "extra.md"), "unselected"); + break; + case "missing directory": + await rm(migration, { recursive: true }); + break; + case "nested link": + await rm(skill, { recursive: true }); + await symlink( + outside, + skill, + process.platform === "win32" ? "junction" : "dir", + ); + break; + case "previously absent": + await mkdir(migration); + break; + } + await f.install(); + expect(await f.remaining()).toHaveLength(0); + if (absent) { + await expect(readdir(migration)).rejects.toMatchObject({ + code: "ENOENT", + }); + } else { + expect(await readdir(migration)).toEqual(["source-command-sample"]); + expect(await readdir(skill)).toEqual(["SKILL.md"]); + expect(await readFile(file, "utf8")).toBe("synthetic skill"); + } + expect(await readFile(sentinel, "utf8")).toBe("outside"); + expect(resolver).toHaveBeenCalled(); + }, +); + +test("canceling a generated skill read leaves its native receipt and caller reason intact", async () => { + const f = await fixture([{}], "regenerated"); + using resolver = spyOn( + executable, + "resolveBundledCodexExecutable", + ).mockReturnValue(f.command); + const { installedRoot } = await f.install(); + const generated = join( + installedRoot, + ".codex-plugin", + "migrated-command-skills", + "source-command-sample", + "SKILL.md", + ); + const receipt = await readFile(f.record); + const controller = new AbortController(); + const reason = new Error( + "synthetic cancellation while reading generated skill", + ); + const prior = files.open; + using opening = spyOn(files, "open").mockImplementation(async (...args) => { + const result = await prior(...args); + if (String(args[0]) === generated) controller.abort(reason); + return result; + }); + await expect(f.install(controller.signal)).rejects.toBe(reason); + expect(await f.remaining()).toHaveLength(0); + expect(await readFile(f.record)).toEqual(receipt); + expect(opening).toHaveBeenCalled(); + expect(resolver).toHaveBeenCalled(); +}); + +test("checks the generated output and selected files in the same installation", async () => { + const f = await fixture([{}, {}], "regenerated"); + using resolver = spyOn( + executable, + "resolveBundledCodexExecutable", + ).mockReturnValue(f.command); + const { installedRoot } = await f.install(); + const previous = join(await temporaryDirectory(), "previous"); + const original = files.realpath; + let replaced = false; + using resolving = spyOn(files, "realpath").mockImplementation((async ( + ...args: Parameters + ) => { + if (!replaced && args[0] === installedRoot) { + replaced = true; + await rename(installedRoot, previous); + await cp(previous, installedRoot, { recursive: true }); + await writeFile(join(installedRoot, "marker.txt"), "other selection"); + } + return original(...args); + }) as typeof original); + await f.install(); + expect(replaced).toBe(true); + expect(await f.remaining()).toHaveLength(0); + expect(await readFile(join(installedRoot, "marker.txt"), "utf8")).toBe( + "selected", + ); + expect(resolving).toHaveBeenCalled(); + expect(resolver).toHaveBeenCalled(); +}); + test.skipIf(process.platform !== "win32").each([ [ "persistent denial", From 34d0e634ea0d5a2e2d2b740b3634e74e55ba2fab Mon Sep 17 00:00:00 2001 From: Michael D'Angelo Date: Tue, 10 Nov 2026 03:46:29 -0800 Subject: [PATCH 17/28] fix(mcp): use UTF-8 for workbench responses and diagnostics (#2566) --- .../mcp-app/src/server/workbench-process.ts | 2 ++ .../mcp-app/tests/support/fake-codex-source.ts | 2 +- .../mcp-app/tests/test_deep_scan_executor.ts | 8 ++++++++ .../mcp-app/tests/test_workbench_state.ts | 12 ++++++++++-- 4 files changed, 21 insertions(+), 3 deletions(-) diff --git a/plugins/codex-security/mcp-app/src/server/workbench-process.ts b/plugins/codex-security/mcp-app/src/server/workbench-process.ts index 7a62de447..8e00f0d11 100644 --- a/plugins/codex-security/mcp-app/src/server/workbench-process.ts +++ b/plugins/codex-security/mcp-app/src/server/workbench-process.ts @@ -1,6 +1,8 @@ export const WORKBENCH_PYTHON = ` import json, sys from pathlib import Path +sys.stdout.reconfigure(encoding="utf-8", errors=sys.stdout.errors) +sys.stderr.reconfigure(encoding="utf-8", errors=sys.stderr.errors) script = Path(sys.argv.pop(1)).resolve() sys.path.insert(0, str(script.parent)) args = json.loads(sys.stdin.buffer.readline()) diff --git a/plugins/codex-security/mcp-app/tests/support/fake-codex-source.ts b/plugins/codex-security/mcp-app/tests/support/fake-codex-source.ts index e5f1dd08a..9e2a92cae 100644 --- a/plugins/codex-security/mcp-app/tests/support/fake-codex-source.ts +++ b/plugins/codex-security/mcp-app/tests/support/fake-codex-source.ts @@ -71,7 +71,7 @@ const profileContents = profileIndex === -1 ? undefined : readFileSync(join(proc const openaiAuthentication = stdin.includes('CAPTURE_SYNTHETIC_OPENAI_AUTH') ? { OPENAI_API_KEY: process.env.OPENAI_API_KEY, CODEX_API_KEY: process.env.CODEX_API_KEY } : undefined; const bedrockAuthentication = stdin.includes('CAPTURE_SYNTHETIC_BEDROCK_AUTH') ? Object.fromEntries(JSON.parse(process.env.FAKE_CODEX_BEDROCK_ENV_KEYS).map((name) => [name, process.env[name]])) : undefined; const codexConfig = stdin.includes('CAPTURE_SYNTHETIC_CODEX_CONFIG') ? readFileSync(join(process.env.CODEX_HOME, 'config.toml'), 'utf8') : undefined; -const runtimeEnvironment = Object.fromEntries(['PATH', 'HOME', 'PYTHON', 'PYTHONUTF8', 'CODEX_MCP_NODE_PATH', 'CODEX_BROWSER_USE_NODE_PATH', 'CODEX_ELECTRON_RESOURCES_PATH', 'LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH', 'DYLD_FALLBACK_LIBRARY_PATH', 'CODEX_SECURITY_STATE_DIR', 'RUNNER_TRACKING_ID'].map(name => [name, process.env[name]])); +const runtimeEnvironment = Object.fromEntries(['PATH', 'HOME', 'PYTHON', 'PYTHONUTF8', 'PYTHONIOENCODING', 'CODEX_MCP_NODE_PATH', 'CODEX_BROWSER_USE_NODE_PATH', 'CODEX_ELECTRON_RESOURCES_PATH', 'LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH', 'DYLD_FALLBACK_LIBRARY_PATH', 'CODEX_SECURITY_STATE_DIR', 'RUNNER_TRACKING_ID'].map(name => [name, process.env[name]])); const toolProbe = stdin.includes('CAPTURE_SYNTHETIC_RG') ? spawnSync('rg', ['--version'], { encoding: 'utf8' }) : undefined; if (toolProbe && toolProbe.status !== 0) throw toolProbe.error ?? new Error(toolProbe.stderr); const pythonProbe = stdin.includes('CAPTURE_SYNTHETIC_PYTHON') ? spawnSync(process.env.PYTHON, ['-I', '-c', 'import json,os,sys; print(json.dumps([sys.prefix,os.environ.get("LD_LIBRARY_PATH")]))'], { encoding: 'utf8' }) : undefined; 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 c6ce61d45..0ce4f8508 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 @@ -1446,6 +1446,7 @@ async function testWorkerRuntimeSettings() { ]; const saved = [ "PYTHON", + "PYTHONIOENCODING", "CODEX_SECURITY_PYTHON_COMMAND", "PATH", "HOME", @@ -1717,6 +1718,7 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`, }; return { nativePaths, + pythonIoEncoding: index % 2 === 0 ? "utf-16-le" : "utf-8-sig", knowledgePath: path.join(fixture.root, `knowledge-${index}`), knowledgeDocuments: { "1-architecture.md.txt": `Synthetic architecture for scan ${index}.`, @@ -2125,6 +2127,8 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`, ]) { process.env[name] = path.join(fixture.root, `libraries-${index}`); } + process.env.PYTHONIOENCODING = + workerConfigurations[index].pythonIoEncoding; restoreEnv( "CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH", workerConfigurations[index].workerConfigPath, @@ -2248,6 +2252,10 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`, workerLaunch.environment![name], ); } + assert.equal( + invocation.runtimeEnvironment.PYTHONIOENCODING, + workerConfigurations[index].pythonIoEncoding, + ); assert.equal( invocation.knowledgePath, workerConfigurations[index].knowledgePath, diff --git a/plugins/codex-security/mcp-app/tests/test_workbench_state.ts b/plugins/codex-security/mcp-app/tests/test_workbench_state.ts index e3c2b2730..a3c5a008b 100644 --- a/plugins/codex-security/mcp-app/tests/test_workbench_state.ts +++ b/plugins/codex-security/mcp-app/tests/test_workbench_state.ts @@ -97,7 +97,10 @@ try { const diagnostic = direct.stderr.trim().split("\n").at(-1)!; assert.match(diagnostic, /FileExistsError/); assert.equal(wrapped.stderr.trim().split("\n").at(-1), diagnostic); - const failure = await openWorkspace(environment); + const failure = await openWorkspace({ + ...environment, + PYTHONIOENCODING: "utf-16-le", + }); assert.equal(failure.error, undefined); assert.equal(failure.result.isError, true); assert.ok( @@ -111,7 +114,12 @@ try { ...environment, CODEX_SECURITY_STATE_DIR: explicitState, }; - assertNoError(await openWorkspace(explicitEnvironment)); + assertNoError( + await openWorkspace({ + ...explicitEnvironment, + PYTHONIOENCODING: "utf-8-sig", + }), + ); assert.equal( (await stat(path.join(explicitState, "workbench.sqlite3"))).isFile(), true, From 770d369c127e2426f454ea01941e52c48793ac25 Mon Sep 17 00:00:00 2001 From: Michael D'Angelo Date: Tue, 10 Nov 2026 03:47:28 -0800 Subject: [PATCH 18/28] fix(cli): report local failures from mock scans (#2567) --- sdk/typescript/src/cli.ts | 7 ++++++- sdk/typescript/tests-ts/cli.test.ts | 19 +++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts index 22c35c36f..8016dc431 100644 --- a/sdk/typescript/src/cli.ts +++ b/sdk/typescript/src/cli.ts @@ -10472,6 +10472,7 @@ async function executeScan( let patchDaybreakFeatures: JsonObject = {}; let selectedAuthentication: ScanAuthentication | null = null; let repository = ""; + let runningMockScan = false; let failed = false; let failure: unknown; try { @@ -11115,7 +11116,9 @@ async function executeScan( if (arguments_.dryRun) { preflight = await security.preflight(repository, options); } else { + runningMockScan = arguments_.mock === true; result = await security.run(repository, options); + runningMockScan = false; scanDir = result.scanDir; repository = resolve(dependencies.currentDirectory(), repository); if (arguments_.validate) { @@ -11313,7 +11316,9 @@ async function executeScan( if (failed) { const costLimitFailure = failure instanceof ScanCostLimitExceededError ? failure : undefined; - const classification = classifyScanFailure(failure); + const classification = runningMockScan + ? "local" + : classifyScanFailure(failure); const message = failure instanceof OutputInsideProtectedRootError ? errorMessage(protectedRootErrorMessage(failure)) diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.ts index 5f2f31284..c8872c4e1 100644 --- a/sdk/typescript/tests-ts/cli.test.ts +++ b/sdk/typescript/tests-ts/cli.test.ts @@ -5049,6 +5049,25 @@ describe("CLI", () => { } }); + test("reports an unreadable mock scan artifact as a local failure", async () => { + const message = + "Could not save the mock scan: scan-manifest.json: [Errno 13] Permission denied"; + const { stdout, stderr, runCli } = createCliTest(main); + const deps = dependencies(); + deps.createSecurity = () => failingSecurity(message); + + expect( + await runCli(["scan", ".", "--mock", "--json", "--verbose"], deps), + ).toBe(2); + expect(JSON.parse(stdout.text())).toEqual({ + status: "failed", + code: "SCAN_FAILED", + message, + }); + expect(stderr.text()).toContain(message); + expect(stderr.text()).toContain('scan.failed classification="local"'); + }); + test("keeps model authorization advice for genuine transport failures", async () => { // The bypass must not swallow real 401/403 handling, and the advice must // still replace upstream text that can name the organization or project. From 429ae351c58d1a7c72c22972301e1394e22cdfd7 Mon Sep 17 00:00:00 2001 From: Michael D'Angelo Date: Tue, 10 Nov 2026 03:58:00 -0800 Subject: [PATCH 19/28] fix(windows): stage validated plugin ZIPs for scan workers (#2507) * Stage validated custom ZIP plugins for Windows scans * Support long Windows plugin ZIP staging paths * Prefer shorter trusted paths for Windows ZIP scan plugins * Keep Windows path-length and ZIP publication tests independently mergeable * Cancel slow Windows scan-input parent lookup promptly * Verify ZIP fixtures exercise their temporary-path spies * test: accept either eligible Windows ZIP resume stage parent * test(windows): allow the CI timeout for ZIP workspace reuse * test: restore owned sticky parents before cleanup --------- Co-authored-by: mldangelo-oai <269034524+mldangelo-oai@users.noreply.github.com> Co-authored-by: Codex --- sdk/typescript/src/api.ts | 47 ++- sdk/typescript/src/runtime.ts | 154 +++++++- .../tests-ts/api-runtime-storage.test.ts | 348 +++++++++++++++++- sdk/typescript/tests-ts/runtime.test.ts | 106 ++++-- sdk/typescript/tests-ts/scan-resume.test.ts | 70 +++- 5 files changed, 657 insertions(+), 68 deletions(-) diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.ts index 6955d4999..4f20e02b9 100644 --- a/sdk/typescript/src/api.ts +++ b/sdk/typescript/src/api.ts @@ -281,6 +281,7 @@ import { prepareOutputDir, prepareScanRegistrationOutput, preparePersistentOutputRoot, + prepareWindowsScanPluginZip, probeCodexSandbox, requireModelSafeOutputDir, requireOutputOutsideRepositories, @@ -289,11 +290,13 @@ import { preparePolicyOutputDirectory, resolveCodexCommand, resolvePluginPath, + resolvePluginSource, resolvePluginPython, runWorkbench, setCodexSecurityCredentialLogout, type CodexCommand, type PluginInstall, + type PluginZipSource, type ProcessEnvironment, type ScanArtifactRestorer, type WorkbenchCommandOptions, @@ -340,6 +343,7 @@ interface CodexClientLike { interface PreparedRuntime { codexHome: string; bootstrapWorkspace?: string; + pluginZipSource?: PluginZipSource; configPath?: string; deepScanConfigDirectory?: string; deepScanConfigPath?: string; @@ -2200,6 +2204,7 @@ export class CodexSecurity { let scanDir = ""; let targetPathsFile: string | null = null; let stagedPluginRoot: string | undefined; + let stagedPluginDirectory: string | undefined; let knowledgeBase: PreparedKnowledgeBase | null = null; let costTracker: ScanCostTracker | null = null; let scanProgressTracker: ScanProgressTracker | null = null; @@ -2496,14 +2501,14 @@ export class CodexSecurity { ); } // Windows grants directory reads to its sandbox account through inheritable - // ACLs. Keep those grants on a disposable copy of the SDK's shipped plugin. + // ACLs. Grant only disposable plugin content prepared for this scan. if ( process.platform === "win32" && this.config.pluginPath === undefined && runtime.bootstrapWorkspace !== undefined && this.#dependencies.hostedScan === undefined ) { - stagedPluginRoot = await mkdtemp( + stagedPluginDirectory = stagedPluginRoot = await mkdtemp( join(runtime.bootstrapWorkspace, "bundled-plugin-"), ); await copyPluginTree( @@ -2511,6 +2516,27 @@ export class CodexSecurity { stagedPluginRoot, signal, ); + } else if (runtime.pluginZipSource !== undefined) { + const staged = await prepareWindowsScanPluginZip( + runtime.pluginZipSource, + scanDir, + [ + runtimeHome, + ...(runtime.bootstrapWorkspace ? [runtime.bootstrapWorkspace] : []), + await canonicalConfigPath( + scanCodexHome(this.#dependencies.environment), + ), + ], + (path) => + requireOutputOutsideRepositories( + inputs.protectedRoots, + path, + "runtime", + ), + signal, + ); + stagedPluginDirectory = staged?.workspace; + stagedPluginRoot = staged?.root; } const shellPluginRoot = stagedPluginRoot ?? runtime.plugin.pluginRoot; const skillName = skillNameFor(normalized, mode); @@ -4218,9 +4244,9 @@ export class CodexSecurity { for (const cleanup of await Promise.allSettled([ knowledgeBase?.cleanup(), removeTargetPathsFile(targetPathsFile), - stagedPluginRoot === undefined + stagedPluginDirectory === undefined ? undefined - : cleanupSdkDirectory(stagedPluginRoot), + : cleanupSdkDirectory(stagedPluginDirectory), savedProviderProfile?.cleanup(), ])) { if (cleanup.status === "rejected") { @@ -5670,11 +5696,13 @@ export class CodexSecurity { await lstat(bootstrapWorkspace), bootstrapWorkspace, ); - const pluginRoot = await resolvePluginPath( - this.config.pluginPath, - bootstrapWorkspace, - signal, - ); + const { root: pluginRoot, zip: pluginZipSource } = + await resolvePluginSource( + this.config.pluginPath, + bootstrapWorkspace, + signal, + process.platform === "win32", + ); const ambientHome = scanCodexHome(processEnvironment); const codexConfig = await preserveCodexSecurityPluginRegistration( codexHome, @@ -5717,6 +5745,7 @@ export class CodexSecurity { return { codexHome, bootstrapWorkspace, + pluginZipSource, configPath, deepScanConfigDirectory, deepScanConfigPath, diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.ts index 9540c8a77..e898679a4 100644 --- a/sdk/typescript/src/runtime.ts +++ b/sdk/typescript/src/runtime.ts @@ -12,7 +12,7 @@ import { PLUGIN_PYTHON_READY, } from "./plugin-python-probe.js"; import { resolveBundledCodexExecutable } from "./codex-sdk-environment.js"; -import { gitProtectionRoots } from "./targets.js"; +import { abortable, gitProtectionRoots } from "./targets.js"; import { isNonEmptyString, notify } from "./value.js"; import { execFile as execFileCallback, @@ -20,7 +20,7 @@ import { type ChildProcessWithoutNullStreams, type SpawnOptionsWithoutStdio, } from "node:child_process"; -import { createHash, randomUUID } from "node:crypto"; +import { createHash, randomUUID, type Hash } from "node:crypto"; import { shortArchivePrefix } from "./scan-archive-path.js"; import { chmodSync, @@ -2831,11 +2831,26 @@ export async function extractPluginZip( archive: string, destination: string, signal?: AbortSignal, +): Promise { + return extractValidatedPluginZip(archive, destination, signal); +} + +async function extractValidatedPluginZip( + archive: string, + destination: string, + signal?: AbortSignal, + digest?: Hash, ): Promise { const archivePath = resolve(expandHome(archive)); - await mkdir(dirname(destination), { recursive: true, mode: 0o700 }); + const parent = dirname(destination); + await mkdir(parent, { recursive: true, mode: 0o700 }); + // Windows mkdtemp otherwise fails at 248 UTF-16 units, including its suffix. + const stagingParent = + process.platform === "win32" + ? win32.toNamespacedPath(await realpath(parent)) + : parent; const staging = await realpath( - await mkdtemp(join(dirname(destination), ".codex-security-plugin-")), + await mkdtemp(join(stagingParent, ".codex-security-plugin-")), ); let publishingOnWindows = false; try { @@ -2886,6 +2901,7 @@ export async function extractPluginZip( const output = join(staging, ...path.split("/")); const entryMode = (entry.externalFileAttributes >>> 16) & 0xffff; const permissions = (entryMode || (directory ? 0o700 : 0o600)) & 0o777; + digest?.update(JSON.stringify([path, directory, permissions])); await mkdir(directory ? output : dirname(output), { recursive: true, ...(directory ? { mode: permissions } : {}), @@ -2910,6 +2926,7 @@ export async function extractPluginZip( `Plugin ZIP entry failed CRC-32 validation: ${path}`, ); } + digest?.update(createHash("sha256").update(bytes).digest()); } const pluginRoot = await discoverPluginRoot(staging); throwIfSignalAborted(signal); @@ -3048,23 +3065,46 @@ export async function resolvePluginPath( workspace: string, signal?: AbortSignal, ): Promise { + return (await resolvePluginSource(pluginPath, workspace, signal)).root; +} + +/** @internal */ +export interface PluginZipSource { + path: string; + digest: string; +} + +/** @internal */ +export async function resolvePluginSource( + pluginPath: string | undefined, + workspace: string, + signal?: AbortSignal, + pinZip = false, +): Promise<{ root: string; zip?: PluginZipSource }> { try { if (pluginPath === undefined) { - return await bundledPluginRoot(); + return { root: await bundledPluginRoot() }; } const path = resolve(expandHome(pluginPath)); const metadata = await lstat(path).catch(() => null); if (metadata?.isFile() && extname(path).toLowerCase() === ".zip") { - return await extractPluginZip( - path, + const digest = pinZip ? createHash("sha256") : undefined; + const archive = digest ? await realpath(path) : path; + const root = await extractValidatedPluginZip( + archive, join(workspace, "extracted-plugin"), signal, + digest, ); + return { + root, + ...(digest && { zip: { path: archive, digest: digest.digest("hex") } }), + }; } if (metadata?.isDirectory()) { throwIfSignalAborted(signal); - return await validatePluginRoot(path); + return { root: await validatePluginRoot(path) }; } throw new PluginBootstrapError( `Plugin path must be a directory or ZIP: ${path}`, @@ -3076,6 +3116,104 @@ export async function resolvePluginPath( } } +/** @internal */ +export async function prepareWindowsScanPluginZip( + source: PluginZipSource, + scanDirectory: string, + protectedDirectories: readonly string[], + validateLocation: (path: string) => void, + signal?: AbortSignal, +): Promise<{ workspace: string; root: string } | undefined> { + throwIfSignalAborted(signal); + const protectedPath = (path: string) => + protectedDirectories.some((directory) => isWithin(directory, path)); + if (protectedPath(source.path)) return; + const metadata = await lstat(source.path).catch(nullIfMissingFileError); + if (metadata === null) return; + const changed = "The selected plugin ZIP changed after runtime preparation."; + if (!metadata.isFile()) throw new LocalPluginBootstrapError(changed); + const canonicalSource = await realpath(source.path).catch( + nullIfMissingFileError, + ); + if (canonicalSource === null) return; + if (protectedPath(canonicalSource)) + throw new LocalPluginBootstrapError(changed); + let workspace: string | undefined; + const parents = [...new Set([dirname(scanDirectory), tmpdir()])].filter( + (parent) => !protectedPath(parent) && !isWithin(scanDirectory, parent), + ); + // PowerShell may fail to launch the selected plugin's .cmd at a long path. + // Prefer the shorter canonical parent, retaining the output parent on ties. + const candidates = await abortable( + () => Promise.allSettled(parents.map((path) => realpath(path))), + signal, + ); + const length = (candidate: PromiseSettledResult) => + candidate.status === "fulfilled" ? candidate.value.length : Infinity; + for (const candidate of candidates.sort((a, b) => length(a) - length(b))) { + throwIfSignalAborted(signal); + try { + if (candidate.status === "rejected") throw candidate.reason; + const canonical = candidate.value; + if (protectedPath(canonical) || isWithin(scanDirectory, canonical)) + continue; + // Host-side plugin helpers may execute from this copy. A sibling keeps it + // outside the writable scan, and the native creator verifies its parents. + workspace = await prepareOutputDir( + undefined, + "plugin-input", + canonical, + validateLocation, + ); + break; + } catch (error) { + if ( + !(error instanceof OutputDirectoryError) && + !["EACCES", "EPERM", "ENOENT"].includes(nodeErrorCode(error) ?? "") + ) + throw error; + } + } + // Keep existing plugin handling where neither scan input location is usable. + if (workspace === undefined) return; + try { + throwIfSignalAborted(signal); + const digest = createHash("sha256"); + const root = await extractValidatedPluginZip( + source.path, + join(workspace, "plugin"), + signal, + digest, + ); + throwIfSignalAborted(signal); + if (digest.digest("hex") !== source.digest) { + throw new LocalPluginBootstrapError(changed); + } + return { workspace, root }; + } catch (error) { + try { + await cleanupSdkDirectory(workspace); + } catch (cleanupError) { + throwIfSignalAborted(signal); + throw new LocalPluginBootstrapError( + `${errorMessage(error)}\nCould not remove scan input directory ${workspace}: ${errorMessage(cleanupError)}`, + { cause: error }, + ); + } + throwIfSignalAborted(signal); + const cause = + error instanceof PluginBootstrapError ? error.cause : undefined; + if ( + isRecord(cause) && + cause["code"] === "ENOENT" && + cause["syscall"] === "open" && + cause["path"] === source.path + ) + return; + throw error; + } +} + export async function createMarketplace( codexHome: string, pluginRoot: string, diff --git a/sdk/typescript/tests-ts/api-runtime-storage.test.ts b/sdk/typescript/tests-ts/api-runtime-storage.test.ts index 31d65dddc..12f13cbb3 100644 --- a/sdk/typescript/tests-ts/api-runtime-storage.test.ts +++ b/sdk/typescript/tests-ts/api-runtime-storage.test.ts @@ -5,11 +5,14 @@ import { readFile, readdir, realpath, + rm, stat, writeFile, } from "node:fs/promises"; import { existsSync } from "node:fs"; -import { spawnSync } from "node:child_process"; +import * as fsPromises from "node:fs/promises"; +import { spawn, spawnSync } from "node:child_process"; +import { once } from "node:events"; import * as os from "node:os"; import { basename, dirname, join } from "node:path"; import { afterEach, expect, spyOn, test } from "bun:test"; @@ -49,6 +52,244 @@ test("preflights with explicit storage paths when the account has no home direct } }); +test.skipIf(process.platform !== "win32").each(["changed", "canceled"])( + "retains a %s ZIP error when Windows holds the scan input open", + async (result) => { + const root = await temporaryDirectory(); + using temporary = spyOn(os, "tmpdir").mockReturnValue(root); + const bootstrap = join(root, "bootstrap"); + const output = join(root, "scan"); + const archive = join(root, "selected.zip"); + await mkdir(bootstrap); + await mkdir(output); + const plugin = (description: string) => + zipSync({ + ".codex-plugin/plugin.json": strToU8( + JSON.stringify({ + name: "codex-security", + version: "1.2.3", + description, + }), + ), + }); + await writeFile(archive, plugin("original")); + const { zip } = await runtime.resolvePluginSource( + archive, + bootstrap, + undefined, + true, + ); + if (result === "changed") await writeFile(archive, plugin("replacement")); + const controller = new AbortController(); + const reason = new Error("Canceled while preparing the scan input"); + const nativeRename = fsPromises.rename; + let held = ""; + let release: (() => Promise) | undefined; + using publication = spyOn(fsPromises, "rename").mockImplementation( + async (from, to) => { + await nativeRename(from, to); + if (basename(String(to)) !== "plugin") return; + held = dirname(String(to)); + const holder = spawn( + "node", + ["-e", 'process.stdout.write("ready"); process.stdin.resume()'], + { cwd: held, windowsHide: true }, + ); + const exited = once(holder, "exit"); + release = async () => { + holder.stdin.end(); + await exited; + }; + await once(holder.stdout, "data"); + if (result === "canceled") controller.abort(reason); + }, + ); + try { + const operation = runtime.prepareWindowsScanPluginZip( + zip!, + output, + [bootstrap], + () => {}, + controller.signal, + ); + if (result === "canceled") await expect(operation).rejects.toBe(reason); + else { + const failure = await operation.catch((error: unknown) => error); + expect((failure as Error).message).toContain( + `Could not remove scan input directory ${held}:`, + ); + expect(failure).toMatchObject({ + cause: { + name: "LocalPluginBootstrapError", + message: expect.stringContaining("ZIP changed"), + }, + }); + } + expect(publication).toHaveBeenCalled(); + expect(temporary).toHaveBeenCalled(); + expect(existsSync(held)).toBe(true); + } finally { + await release?.(); + } + }, +); + +test.skipIf(process.platform !== "win32")( + "cancels ZIP staging while a candidate parent is still being resolved", + async () => { + const root = await temporaryDirectory(); + const temp = join(root, "temp"); + const output = join(root, "longer-output-parent", "scan"); + const bootstrap = join(root, "bootstrap"); + const archive = join(root, "selected.zip"); + await mkdir(temp); + await mkdir(bootstrap); + await mkdir(output, { recursive: true }); + await writeFile( + archive, + zipSync({ + ".codex-plugin/plugin.json": strToU8( + '{"name":"codex-security","version":"1.2.3"}', + ), + }), + ); + const { zip } = await runtime.resolvePluginSource( + archive, + bootstrap, + undefined, + true, + ); + using temporary = spyOn(os, "tmpdir").mockReturnValue(temp); + const started = Promise.withResolvers(); + const held = Promise.withResolvers(); + const canonicalize = fsPromises.realpath; + using lookup = spyOn(fsPromises, "realpath").mockImplementation( + new Proxy(canonicalize, { + apply(target, receiver, args) { + if (args[0] !== temp) return Reflect.apply(target, receiver, args); + started.resolve(); + return held.promise; + }, + }), + ); + const controller = new AbortController(); + const reason = new Error("Canceled during scan input placement"); + let canceled: unknown; + const operation = runtime + .prepareWindowsScanPluginZip( + zip!, + output, + [bootstrap], + () => {}, + controller.signal, + ) + .catch((error: unknown) => { + canceled = error; + }); + try { + await started.promise; + controller.abort(reason); + await new Promise((resolve) => setImmediate(resolve)); + expect(canceled).toBe(reason); + } finally { + held.resolve(temp); + await operation; + } + expect(await readdir(temp)).toEqual([]); + expect(temporary).toHaveBeenCalled(); + expect(lookup).toHaveBeenCalledWith(temp); + expect(await readdir(dirname(output))).toEqual(["scan"]); + }, +); + +test.skipIf(process.platform !== "win32")( + "prepares the pinned ZIP from its original source for explicit and default Windows scan outputs", + async () => { + const root = await temporaryDirectory(); + const archive = join(root, "workflow [source].ZIP"); + const ambient = join(root, "ambient"); + const bootstrap = join(root, "bootstrap"); + const ordinaryTemp = join(root, "scan-temporary"); + const explicit = join(root, "explicit", "scan"); + const deepOutput = join(root, "nested-output-".repeat(8), "scan"); + const equalLengthTemp = join(root, "parallel"); + const configuredDefault = join(root, "state", "scans", "fixture", "scan"); + const privateDefault = join(ambient, "state", "scans", "fixture", "scan"); + for (const path of [ + bootstrap, + ordinaryTemp, + explicit, + deepOutput, + equalLengthTemp, + configuredDefault, + privateDefault, + ]) + await mkdir(path, { recursive: true }); + const contents = (skill: string) => + zipSync({ + "release/.codex-plugin/plugin.json": strToU8( + JSON.stringify({ name: "codex-security", version: "1.2.3" }), + ), + "release/skills/security-scan/SKILL.md": strToU8(skill), + }); + const original = Buffer.from(contents("# Selected workflow")); + await writeFile(archive, original); + const { zip } = await runtime.resolvePluginSource( + archive, + bootstrap, + undefined, + true, + ); + expect(zip).toBeDefined(); + // Removing the synthetic install proves every scan reads its selected ZIP. + await rm(bootstrap, { recursive: true }); + using temporary = spyOn(os, "tmpdir").mockReturnValue(ordinaryTemp); + const prepare = (scan: string) => + runtime.prepareWindowsScanPluginZip( + zip!, + scan, + [ambient, bootstrap], + () => {}, + ); + for (const [output, temp, expectedParent] of [ + [explicit, ordinaryTemp, dirname(explicit)], + [explicit, equalLengthTemp, dirname(explicit)], + [deepOutput, ordinaryTemp, ordinaryTemp], + [configuredDefault, ordinaryTemp, ordinaryTemp], + [deepOutput, ambient, dirname(deepOutput)], + [privateDefault, ordinaryTemp, ordinaryTemp], + ] as const) { + temporary.mockReturnValue(temp); + const staged = await prepare(output); + expect(staged).toBeDefined(); + try { + expect(dirname(staged!.workspace)).toBe(expectedParent); + expect(staged!.root).toBe(join(staged!.workspace, "plugin", "release")); + expect( + await readFile( + join(staged!.root, "skills/security-scan/SKILL.md"), + "utf8", + ), + ).toBe("# Selected workflow"); + } finally { + await runtime.cleanupSdkDirectory(staged!.workspace); + } + } + expect(await readFile(archive)).toEqual(original); + await writeFile(archive, contents("different bytes at the same version")); + await expect(prepare(explicit)).rejects.toThrow( + "changed after runtime preparation", + ); + expect(await readdir(dirname(explicit))).toEqual(["scan"]); + await rm(archive); + expect(await prepare(explicit)).toBeUndefined(); + expect(await readdir(dirname(explicit))).toEqual(["scan"]); + await writeFile(archive, original); + temporary.mockReturnValue(ambient); + expect(await prepare(privateDefault)).toBeUndefined(); + }, +); + function stubPluginInstall() { return spyOn(runtime, "bootstrapPlugin").mockImplementation( async (_home, pluginRoot) => ({ @@ -259,7 +500,7 @@ test.each(["directory", "zip"])( await writeFile(join(pluginPath, name), contents); } } - const snapshotAcl = () => { + const snapshotAcl = (path = temporary) => { const system = join(process.env["SystemRoot"]!, "System32"); const result = spawnSync( join(system, "WindowsPowerShell", "v1.0", "powershell.exe"), @@ -278,7 +519,7 @@ test.each(["directory", "zip"])( ([name]) => name.toUpperCase() !== "PSMODULEPATH", ), ), - CODEX_SECURITY_TEST_TEMP: temporary, + CODEX_SECURITY_TEST_TEMP: path, PSModulePath: join(system, "WindowsPowerShell", "v1.0", "Modules"), }, windowsHide: true, @@ -288,6 +529,8 @@ test.each(["directory", "zip"])( return result.stdout.trim(); }; let temporaryAcl: string | undefined; + const sourceAcl = + process.platform === "win32" ? snapshotAcl(pluginPath) : undefined; if (process.platform === "win32") { const grant = spawnSync( join(process.env["SystemRoot"]!, "System32", "icacls.exe"), @@ -312,6 +555,9 @@ test.each(["directory", "zip"])( const temporaryRoot = spyOn(os, "tmpdir").mockReturnValue(temporary); const install = stubPluginInstall(); const workspaces = new Map(); + const zipInputs = new Set(); + let defaultOutput = false; + let movedArchive = false; const clients: TestClient[] = []; const createClient = (index: number, stateDirectory = state) => { const client = new TestClient( @@ -357,19 +603,76 @@ test.each(["directory", "zip"])( const previous = workspaces.get(index); if (previous !== undefined) expect(workspace).toBe(previous); workspaces.set(index, workspace); - expect(environment["CODEX_SECURITY_PLUGIN_ROOT"]).toBe( - source === "zip" - ? join(workspace, "extracted-plugin") - : pluginPath, - ); + const plugin = environment["CODEX_SECURITY_PLUGIN_ROOT"]!; + if ( + source === "zip" && + process.platform === "win32" && + !movedArchive + ) { + const input = dirname(plugin); + expect(dirname(input)).toBe( + dirname(environment["CODEX_SECURITY_SCAN_DIR"]!), + ); + expect(zipInputs.has(input)).toBe(false); + zipInputs.add(input); + expect( + existsSync(join(plugin, "skills/security-scan/SKILL.md")), + ).toBe(true); + const overrides = options.configOverrides!.find((entry) => + entry.startsWith("permissions.codex_security_scan.filesystem="), + )!; + expect(parseToml(overrides)).toEqual({ + permissions: { + codex_security_scan: { + filesystem: { + ":root": "read", + ":workspace_roots": "write", + [plugin]: { ".": "read" }, + [repository]: { ".": "read" }, + [environment["CODEX_HOME"]!]: { ".": "deny" }, + }, + }, + }, + }); + } else { + expect(plugin).toBe( + source === "zip" + ? join(workspace, "extracted-plugin") + : pluginPath, + ); + if (movedArchive) { + const overrides = options.configOverrides!.find((entry) => + entry.startsWith( + "permissions.codex_security_scan.filesystem=", + ), + )!; + expect(parseToml(overrides)).toEqual({ + permissions: { + codex_security_scan: { + filesystem: { + ":root": "read", + ":workspace_roots": "write", + [repository]: { ".": "read" }, + [environment["CODEX_HOME"]!]: { ".": "deny" }, + }, + }, + }, + }); + } + } const codex = codexFactory(async function () { throw new Error("synthetic scan reached"); })(); return { startThread: (threadOptions) => { - expect(threadOptions.workingDirectory).toBe( - join(root, `scan-${index}`), - ); + if (defaultOutput) { + expect(dirname(threadOptions.workingDirectory!)).toBe( + join(stateDirectory, "scans", "repository"), + ); + } else + expect(threadOptions.workingDirectory).toBe( + join(root, `scan-${index}`), + ); return codex.startThread(); }, }; @@ -389,18 +692,39 @@ test.each(["directory", "zip"])( expect(run(second, 1)).rejects.toThrow("synthetic scan reached"), ]); expect(workspaces.size).toBe(2); + for (const input of zipInputs) expect(existsSync(input)).toBe(false); expect(workspaces.get(0)).not.toBe(workspaces.get(1)); await first.close(); expect(existsSync(workspaces.get(0)!)).toBe(false); expect(existsSync(workspaces.get(1)!)).toBe(true); await expect(run(second, 1)).rejects.toThrow("synthetic scan reached"); + for (const input of zipInputs) expect(existsSync(input)).toBe(false); if (process.platform === "win32") { + if (source === "zip") { + defaultOutput = true; + await expect(second.run(repository)).rejects.toThrow( + "synthetic scan reached", + ); + defaultOutput = false; + for (const input of zipInputs) expect(existsSync(input)).toBe(false); + movedArchive = true; + await fsPromises.rename(pluginPath, `${pluginPath}.moved`); + try { + await expect(run(second, 1)).rejects.toThrow( + "synthetic scan reached", + ); + } finally { + await fsPromises.rename(`${pluginPath}.moved`, pluginPath); + movedArchive = false; + } + } const rejected = createClient(2, join(temporary, "untrusted-state")); await expect(run(rejected, 2)).rejects.toThrow( "allows another identity to replace", ); expect(workspaces.has(2)).toBe(false); expect(snapshotAcl()).toBe(temporaryAcl!); + expect(snapshotAcl(pluginPath)).toBe(sourceAcl!); } expect({ TEMP: process.env["TEMP"], TMP: process.env["TMP"] }).toEqual( processTemporary, @@ -414,5 +738,5 @@ test.each(["directory", "zip"])( expect(existsSync(workspace)).toBe(false); } }, - 60_000, + process.platform === "win32" ? 120_000 : 60_000, ); diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.ts index b46f16610..ad0100d0a 100644 --- a/sdk/typescript/tests-ts/runtime.test.ts +++ b/sdk/typescript/tests-ts/runtime.test.ts @@ -1871,6 +1871,38 @@ for await (const line of createInterface({ input: process.stdin })) { } }); + test.skipIf(process.platform !== "win32")( + "extracts plugin ZIPs across Windows temporary directory path limits", + async () => { + const root = await temporaryDirectory(); + const archive = join(root, "plugin.zip"); + const manifest = ".codex-plugin/plugin.json"; + const data = JSON.stringify({ name: "codex-security", version: "1.2.3" }); + await writeFile( + archive, + zipSync({ [`release/${manifest}`]: strToU8(data) }), + ); + const templateLength = join(root, ".codex-security-plugin-XXXXXX").length; + using createStaging = spyOn(fsPromises, "mkdtemp"); + for (const length of [247, 248, 259, 260, 280]) { + const padding = Math.max(1, length - templateLength - 1); + const parent = join(root, "p".repeat(padding)); + const destination = join(parent, `extracted-${length}`); + const plugin = await extractPluginZip(archive, destination); + expect(createStaging).toHaveBeenLastCalledWith( + win32.toNamespacedPath(join(parent, ".codex-security-plugin-")), + ); + expect(plugin).toBe(join(destination, "release")); + expect(await readFile(join(plugin, manifest), "utf8")).toBe(data); + expect( + (await readdir(parent)).some((entry) => + entry.startsWith(".codex-security-plugin-"), + ), + ).toBe(false); + } + }, + ); + test("rejects a ZIP entry with an invalid CRC-32", async () => { const root = await temporaryDirectory(); const archive = join(root, "invalid-crc.zip"); @@ -3372,23 +3404,30 @@ describe("runtime directories and plugin Python boundary", () => { let stickyParent = shared; await mkdir(stickyParent, { mode: 0o1777 }); await chmod(stickyParent, 0o1777); - if (((await lstat(stickyParent)).mode & 0o1000) === 0) { - stickyParent = await realpath(tmpdir()); + try { if (((await lstat(stickyParent)).mode & 0o1000) === 0) { - return; + stickyParent = await realpath(tmpdir()); + if (((await lstat(stickyParent)).mode & 0o1000) === 0) { + return; + } } + const stateDirectory = join( + stickyParent, + `codex-security-sticky-${process.pid}-${Date.now()}`, + ); + if (stickyParent !== shared) temporaryDirectories.track(stateDirectory); + await mkdir(stateDirectory, { recursive: true, mode: 0o700 }); + const home = await prepareCodexSecurityCredentialHome({ + CODEX_SECURITY_STATE_DIR: stateDirectory, + }); + await expect(requireSecureCredentialHome(home)).resolves.toBeDefined(); + await expect( + requireSecureOutputAncestry(home), + ).resolves.toBeUndefined(); + } finally { + // Restore this fixture's parent before recursive cleanup on macOS. + await chmod(shared, 0o700); } - const stateDirectory = join( - stickyParent, - `codex-security-sticky-${process.pid}-${Date.now()}`, - ); - if (stickyParent !== shared) temporaryDirectories.track(stateDirectory); - await mkdir(stateDirectory, { recursive: true, mode: 0o700 }); - const home = await prepareCodexSecurityCredentialHome({ - CODEX_SECURITY_STATE_DIR: stateDirectory, - }); - await expect(requireSecureCredentialHome(home)).resolves.toBeDefined(); - await expect(requireSecureOutputAncestry(home)).resolves.toBeUndefined(); }, ); @@ -6520,25 +6559,30 @@ describe("runtime directories and plugin Python boundary", () => { const shared = join(root, "shared"); await mkdir(shared, { mode: 0o1777 }); await chmod(shared, 0o1777); - // Some filesystems (notably user dirs on macOS APFS) ignore sticky on - // chmod; fall back to the process temp root when it is already sticky. - let stickyParent = shared; - if (((await lstat(shared)).mode & 0o1000) === 0) { - stickyParent = await realpath(tmpdir()); - if (((await lstat(stickyParent)).mode & 0o1000) === 0) { - return; + try { + // Some filesystems (notably user dirs on macOS APFS) ignore sticky on + // chmod; fall back to the process temp root when it is already sticky. + let stickyParent = shared; + if (((await lstat(shared)).mode & 0o1000) === 0) { + stickyParent = await realpath(tmpdir()); + if (((await lstat(stickyParent)).mode & 0o1000) === 0) { + return; + } } - } - const output = join( - stickyParent, - `codex-security-sticky-${process.pid}-${Date.now()}`, - ); - if (stickyParent !== shared) temporaryDirectories.track(output); + const output = join( + stickyParent, + `codex-security-sticky-${process.pid}-${Date.now()}`, + ); + if (stickyParent !== shared) temporaryDirectories.track(output); - await expect( - requireSecureOutputAncestry(output), - ).resolves.toBeUndefined(); - expect(await prepareOutputDir(output, "repo")).toBe(output); + await expect( + requireSecureOutputAncestry(output), + ).resolves.toBeUndefined(); + expect(await prepareOutputDir(output, "repo")).toBe(output); + } finally { + // Restore this fixture's parent before recursive cleanup on macOS. + await chmod(shared, 0o700); + } }, ); diff --git a/sdk/typescript/tests-ts/scan-resume.test.ts b/sdk/typescript/tests-ts/scan-resume.test.ts index 34ad458b2..7291a05bb 100644 --- a/sdk/typescript/tests-ts/scan-resume.test.ts +++ b/sdk/typescript/tests-ts/scan-resume.test.ts @@ -20,10 +20,15 @@ import { import { 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"; import { main } from "../src/cli.js"; import { scanPreflightCodexConfig, type ScanOptions } from "../src/api.js"; -import { writeCodexConfig, type JsonObject } from "../src/config.js"; -import { runWorkbench } from "../src/runtime.js"; +import { + writeCodexConfig, + type CodexSecurityConfig, + type JsonObject, +} from "../src/config.js"; +import { resolvePluginSource, runWorkbench } from "../src/runtime.js"; import { readKnowledgeBaseSnapshot } from "../src/knowledge-base.js"; import { saveScanKnowledge, scanInputIdentity } from "../src/scan-inputs.js"; import { workflowDigest } from "../src/finding-workflow.js"; @@ -440,7 +445,14 @@ test.each([ }, ); -test("CLI resumes through native execution with current permissions and preserves interrupted state and output permissions", async () => { +const resumePlugins = + process.platform === "win32" ? ["bundled", "zip"] : ["bundled"]; +test.each(resumePlugins)( + "CLI resumes through native execution with current permissions and preserves interrupted state and output permissions (%s)", + resumeWithPlugin, +); + +async function resumeWithPlugin(source: string) { const markdown = "Keep the grading policy chosen when this scan started."; const severityRubric = { markdown, @@ -450,6 +462,24 @@ test("CLI resumes through native execution with current permissions and preserve const f = await interruptedScan("deep", false, { severityRubric }); const bootstrapWorkspace = join(f.root, "resumed-bootstrap"); await mkdir(bootstrapWorkspace); + const archive = join(f.root, "selected.zip"); + if (source === "zip") { + await writeFile( + archive, + zipSync({ + ".codex-plugin/plugin.json": strToU8( + JSON.stringify({ name: "codex-security", version: "0.1.0" }), + ), + "skills/deep-security-scan/SKILL.md": strToU8( + "# Custom resumed workflow", + ), + }), + ); + } + const selected = + source === "zip" + ? await resolvePluginSource(archive, bootstrapWorkspace, undefined, true) + : undefined; Object.assign(f.environment, { CODEX_SECURITY_ENABLE_REMOTE_SEVERITY_RUBRIC: "1", }); @@ -474,7 +504,9 @@ test("CLI resumes through native execution with current permissions and preserve ); const originalFeedback = JSON.stringify([{ reason: "Original reviewer rationale." }]) + "\n"; - await mkdir(join(f.scanDir, "artifacts", "01_context"), { recursive: true }); + await mkdir(join(f.scanDir, "artifacts", "01_context"), { + recursive: true, + }); await writeFile(feedbackPath, originalFeedback, { mode: 0o600 }); const originalHome = join(f.root, "original-codex-home"); await appendFile( @@ -503,17 +535,21 @@ test("CLI resumes through native execution with current permissions and preserve ]); let resumedThread: string | undefined; const { stderr, runCli } = createCliTest(main); + // The host can supply a ZIP through its SDK client when replaying a scan. + const withPlugin = (config: CodexSecurityConfig) => + selected ? { ...config, pluginPath: archive } : config; const flags = ["scans", "resume", f.scanId, "--json", "--verbose"]; const code = await runCli(flags, { ...dependencies({ environment: f.environment, currentDirectory: f.root }), runWorkbench: f.command, createSecurity: (config) => - new TestClient(config, { + new TestClient(withPlugin(config), { environment: f.environment, prepareRuntime: async () => ({ ...preparedRuntime(f.codexHome), bootstrapWorkspace, + pluginZipSource: selected?.zip, deepScanConfigDirectory: join(f.codexHome, "worker-config"), deepScanConfigPath: join( f.codexHome, @@ -549,7 +585,9 @@ test("CLI resumes through native execution with current permissions and preserve options.configOverrides!.join("\n"), ) as { permissions: { - codex_security_scan: { filesystem: Record }; + codex_security_scan: { + filesystem: Record; + }; }; }; const filesystem = @@ -558,7 +596,13 @@ test("CLI resumes through native execution with current permissions and preserve expect(filesystem[originalHome]).toBeUndefined(); if (process.platform === "win32") { const currentPlugin = options.env!["CODEX_SECURITY_PLUGIN_ROOT"]!; - expect(dirname(currentPlugin)).toBe(bootstrapWorkspace); + if (selected) { + // The fixture root and its process temp parent can both host the ZIP. + expect([f.root, dirname(f.root)]).toContain( + dirname(dirname(currentPlugin)), + ); + expect(currentPlugin).not.toBe(selected.root); + } else expect(dirname(currentPlugin)).toBe(bootstrapWorkspace); expect(filesystem[currentPlugin]).toEqual({ ".": "read" }); } expect(options.env).toMatchObject({ @@ -568,6 +612,16 @@ test("CLI resumes through native execution with current permissions and preserve return { id: threadId, async runStreamed(prompt) { + if (selected) + expect( + await readFile( + join( + options.env!["CODEX_SECURITY_PLUGIN_ROOT"]!, + "skills/deep-security-scan/SKILL.md", + ), + "utf8", + ), + ).toBe("# Custom resumed workflow"); if (process.platform !== "win32") expect((await stat(f.scanDir)).mode & 0o777).toBe(0o755); expect(await readFile(feedbackPath, "utf8")).toBe( @@ -616,7 +670,7 @@ test("CLI resumes through native execution with current permissions and preserve expect(await readFile(feedbackPath, "utf8")).toBe(originalFeedback); if (process.platform !== "win32") expect((await stat(f.scanDir)).mode & 0o777).toBe(0o755); -}); +} test.each([false, true])( "resume restores private provider refinements (bulk: %p)", From fce296540c5e337b8f8e9446de067428794a5c6a Mon Sep 17 00:00:00 2001 From: Michael D'Angelo Date: Tue, 10 Nov 2026 03:58:12 -0800 Subject: [PATCH 20/28] fix(windows): tolerate executable metadata changes on first launch (#2555) * fix(windows): preserve executable pins across first launch * fix(windows): cancel executable pin verification * fix: preserve active deep worker cancellation errors * style: format deep worker cancellation catch * test: make Windows pin metadata fixtures deterministic --------- Co-authored-by: Codex --- .../mcp-app/src/deep-scan/executor.ts | 152 +++++++++-- .../tests/deep_scan_executable_cases.ts | 118 +++++++++ .../support/deep-scan-executor-module.ts | 21 +- .../mcp-app/tests/test_deep_scan_executor.ts | 2 +- .../mcp-app/tests/test_helper_files.ts | 2 + .../windows_executable_cancellation_cases.ts | 132 ++++++++++ .../windows_executable_first_launch_cases.ts | 237 +++++++++++++++--- 7 files changed, 599 insertions(+), 65 deletions(-) create mode 100644 plugins/codex-security/mcp-app/tests/windows_executable_cancellation_cases.ts diff --git a/plugins/codex-security/mcp-app/src/deep-scan/executor.ts b/plugins/codex-security/mcp-app/src/deep-scan/executor.ts index d212d18e9..1a81d94c1 100644 --- a/plugins/codex-security/mcp-app/src/deep-scan/executor.ts +++ b/plugins/codex-security/mcp-app/src/deep-scan/executor.ts @@ -1,6 +1,7 @@ -import { randomUUID } from "node:crypto"; +import { createHash, randomUUID } from "node:crypto"; import { type BigIntStats, + createReadStream, existsSync, promises as fs, readdirSync, @@ -84,6 +85,7 @@ export interface CodexSdkWorkerArtifactContext { interface BoundCodexExecutable { readonly path: string; readonly identity: BigIntStats; + readonly sha256?: string; } interface CodexSdkWorkerRuntimeSettings { @@ -99,7 +101,10 @@ interface CodexSdkWorkerRuntimeSettings { export class CodexSdkWorkerExecutor implements CodexWorkerExecutor { private runtimeSettings?: Promise; // Each live coordinator keeps the executable selected for its first worker. - private codexExecutable?: Promise; + private codexExecutable?: { + signal: AbortSignal; + promise: Promise; + }; private parentCyberAccessProgram?: Promise; private pluginVersion?: Promise; @@ -131,6 +136,49 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor { return turn.finalResponse; } + private async getCodexExecutable( + environment: NodeJS.ProcessEnv, + cwd: string, + signal: AbortSignal, + ): Promise { + while (true) { + signal.throwIfAborted(); + let binding = this.codexExecutable; + if (!binding) { + binding = { + signal, + promise: bindCodexExecutable(environment, cwd, signal).catch( + (error) => { + // An unsuccessful snapshot has not pinned an executable yet. + if (this.codexExecutable === binding) + this.codexExecutable = undefined; + throw error; + }, + ), + }; + this.codexExecutable = binding; + } + const aborted = Promise.withResolvers(); + const onAbort = () => aborted.reject(signal.reason); + signal.addEventListener("abort", onAbort, { once: true }); + if (signal.aborted) onAbort(); + try { + const executable = await Promise.race([ + binding.promise, + aborted.promise, + ]); + signal.throwIfAborted(); + return executable; + } catch (error) { + signal.throwIfAborted(); + // Another worker's cancellation does not cancel this caller's first lookup. + if (!binding.signal.aborted) throw error; + } finally { + signal.removeEventListener("abort", onAbort); + } + } + } + private async runTurn( request: | CodexWorkerRequest @@ -153,6 +201,7 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor { ? undefined : resolve(dirname(discovery.promptPath), `limits-${randomUUID()}.toml`); try { + request.signal.throwIfAborted(); const parentSandbox = this.modelSettings.parentSandbox; if (!parentSandbox) { throw new DeepScanNonRetryableError( @@ -331,15 +380,12 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor { "CODEX_API_KEY", process.platform, )?.trim(); - const executable = await (this.codexExecutable ??= bindCodexExecutable( + const executable = await this.getCodexExecutable( childEnv, originalCwd, - ).catch((error) => { - // A failed first lookup has not pinned an executable yet; allow startup retries. - this.codexExecutable = undefined; - throw error; - })); - await verifyBoundCodexExecutable(executable); + request.signal, + ); + await verifyBoundCodexExecutable(executable, request.signal); const preflightOptions = { codexPath: executable.path, cwd: request.workingDirectory, @@ -446,7 +492,7 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor { try { // Detect updates during preflight before starting a fresh or resumed worker. - await verifyBoundCodexExecutable(executable); + await verifyBoundCodexExecutable(executable, controller.signal); const { events } = await thread.runStreamed(input, { signal: controller.signal, ...(request.kind === "compare" && { outputSchema: request.schema }), @@ -520,6 +566,9 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor { request.signal.removeEventListener("abort", forwardAbort); } } catch (error) { + // Pin checks throw the caller's reason directly; keep SDK worker errors intact. + if (request.signal.aborted && error === request.signal.reason) + throw error; throw classifyCodexWorkerError(error); } finally { if (includePathsFile !== undefined) @@ -781,34 +830,101 @@ function isRecord(value: unknown): value is Record { async function bindCodexExecutable( env: NodeJS.ProcessEnv, originalCwd: string, + signal?: AbortSignal, ): Promise { + signal?.throwIfAborted(); const path = resolveCodexPath( env, process.platform, process.arch, originalCwd, ); - return { path, identity: await codexExecutableIdentity(path) }; + const identity = await codexExecutableIdentity(path); + signal?.throwIfAborted(); + if (process.platform !== "win32") return { path, identity }; + const sha256 = await codexExecutableDigest(path, signal); + const after = await codexExecutableIdentity(path); + signal?.throwIfAborted(); + if ( + !sameCodexExecutableFile(after, identity) || + after.ctimeNs !== identity.ctimeNs + ) + throw codexExecutableChangedError(path); + return { path, identity, sha256 }; } async function verifyBoundCodexExecutable( executable: BoundCodexExecutable, + signal?: AbortSignal, ): Promise { + signal?.throwIfAborted(); let identity: BigIntStats; try { identity = await codexExecutableIdentity(executable.path); + signal?.throwIfAborted(); } catch (error) { + signal?.throwIfAborted(); throw codexExecutableChangedError(executable.path, error); } - if ( - identity.dev !== executable.identity.dev || - identity.ino !== executable.identity.ino || - identity.size !== executable.identity.size || - identity.mtimeNs !== executable.identity.mtimeNs || - identity.ctimeNs !== executable.identity.ctimeNs - ) { + if (!sameCodexExecutableFile(identity, executable.identity)) { throw codexExecutableChangedError(executable.path); } + if (identity.ctimeNs !== executable.identity.ctimeNs) { + if (process.platform === "win32" && executable.sha256 !== undefined) { + // Windows can advance change time on first execution without changing bytes. + try { + while (true) { + signal?.throwIfAborted(); + const sha256 = await codexExecutableDigest(executable.path, signal); + const after = await codexExecutableIdentity(executable.path); + signal?.throwIfAborted(); + if ( + !sameCodexExecutableFile(after, executable.identity) || + sha256 !== executable.sha256 + ) + break; + if (after.ctimeNs === identity.ctimeNs) return; + // Confirm a stable content snapshot if change time advanced during the read. + identity = after; + } + } catch (error) { + signal?.throwIfAborted(); + throw codexExecutableChangedError(executable.path, error); + } + } + throw codexExecutableChangedError(executable.path); + } +} + +async function codexExecutableDigest( + path: string, + signal?: AbortSignal, +): Promise { + signal?.throwIfAborted(); + const digest = createHash("sha256"); + try { + for await (const bytes of createReadStream(path, { signal })) { + signal?.throwIfAborted(); + digest.update(bytes); + } + } catch (error) { + signal?.throwIfAborted(); + throw error; + } + signal?.throwIfAborted(); + return digest.digest("hex"); +} + +function sameCodexExecutableFile( + actual: BigIntStats, + expected: BigIntStats, +): boolean { + return ( + actual.dev === expected.dev && + actual.ino === expected.ino && + actual.size === expected.size && + actual.mtimeNs === expected.mtimeNs + ); } async function codexExecutableIdentity(path: string): Promise { diff --git a/plugins/codex-security/mcp-app/tests/deep_scan_executable_cases.ts b/plugins/codex-security/mcp-app/tests/deep_scan_executable_cases.ts index 6e4f4cf85..cda76c03f 100644 --- a/plugins/codex-security/mcp-app/tests/deep_scan_executable_cases.ts +++ b/plugins/codex-security/mcp-app/tests/deep_scan_executable_cases.ts @@ -1,4 +1,5 @@ import assert from "node:assert/strict"; +import { existsSync, promises as fs } from "node:fs"; import childProcess, { type SpawnOptions } from "node:child_process"; import { copyFile, @@ -65,6 +66,8 @@ export async function testExecutorExecutablePinning({ await testExecutorPinsCodexExecutableAcrossWorkers(); await testExecutorRejectsChangedPinnedExecutable(); await testExecutorRejectsReplacementAfterPreflight(); + await testExecutorPinCancellation(); + await testConcurrentPinCancellation(); } finally { childProcess.spawn = originalSpawn; syncBuiltinESMExports(); @@ -333,6 +336,121 @@ export async function testExecutorExecutablePinning({ } } + async function testExecutorPinCancellation() { + for (const phase of ["binding", "after-preflight"]) { + await withWorkerFixture(async (fixture, promptPath, workingDirectory) => { + await writeFile(promptPath, "fixture executable pin cancellation\n"); + const controller = new AbortController(); + const reason = { message: "synthetic worker cancellation", phase }; + const originalStat = fs.stat; + fs.stat = (async (...args: Parameters) => { + const result = await originalStat(...args); + if ( + args[0] === fixture.executablePath && + (phase === "binding" || existsSync(fixture.preflightMarkerPath)) + ) { + controller.abort(reason); + } + return result; + }) as typeof fs.stat; + try { + await assert.rejects( + new CodexSdkWorkerExecutor({ parentSandbox }).run( + workerRequest(promptPath, workingDirectory, { + signal: controller.signal, + }), + ), + (error) => error === reason, + ); + } finally { + fs.stat = originalStat; + } + assert.equal( + existsSync(fixture.preflightMarkerPath), + phase === "after-preflight", + ); + assert.equal(existsSync(fixture.markerPath), false); + }); + } + } + + async function testConcurrentPinCancellation() { + for (const canceled of ["owner", "waiter"]) { + await withWorkerFixture(async (fixture, promptPath, workingDirectory) => { + await writeFile( + promptPath, + "fixture shared executable pin cancellation\n", + ); + const owner = new AbortController(); + const waiter = new AbortController(); + const reason = new Error(`synthetic ${canceled} cancellation`); + const entered = Promise.withResolvers(); + const release = Promise.withResolvers(); + const waiting = Promise.withResolvers(); + const originalStat = fs.stat; + const originalAdd = waiter.signal.addEventListener; + let held = false; + fs.stat = (async (...args: Parameters) => { + const result = await originalStat(...args); + if (args[0] === fixture.executablePath && !held) { + held = true; + entered.resolve(); + await release.promise; + } + return result; + }) as typeof fs.stat; + waiter.signal.addEventListener = function ( + ...args: Parameters + ) { + const result = originalAdd.apply(this, args); + if (args[0] === "abort") waiting.resolve(); + return result; + }; + const executor = new CodexSdkWorkerExecutor({ parentSandbox }); + const first = executor.run( + workerRequest(promptPath, workingDirectory, { signal: owner.signal }), + ); + let second: ReturnType | undefined; + try { + await entered.promise; + second = executor.run( + workerRequest(promptPath, workingDirectory, { + signal: waiter.signal, + }), + ); + const completed = Promise.allSettled([first, second]); + await waiting.promise; + (canceled === "owner" ? owner : waiter).abort(reason); + release.resolve(); + const results = await completed; + const rejected = results[canceled === "owner" ? 0 : 1]!; + const fulfilled = results[canceled === "owner" ? 1 : 0]!; + assert.equal(rejected.status, "rejected"); + if (rejected.status === "rejected") + assert.equal(rejected.reason, reason); + assert.equal(fulfilled.status, "fulfilled"); + if (fulfilled.status === "fulfilled") + assert.equal(fulfilled.value.threadId, "fixture-thread-id"); + // A successful pin survives its original caller's later cancellation. + (canceled === "owner" ? waiter : owner).abort( + new Error("fixture completed"), + ); + const next = await executor.run( + workerRequest(promptPath, workingDirectory), + ); + assert.equal(next.threadId, "fixture-thread-id"); + } finally { + release.resolve(); + owner.abort(reason); + waiter.abort(reason); + fs.stat = originalStat; + waiter.signal.addEventListener = originalAdd; + await Promise.allSettled([first, ...(second ? [second] : [])]); + } + }); + } + } + async function withWorkerFixture( action: ( fixture: Fixture, diff --git a/plugins/codex-security/mcp-app/tests/support/deep-scan-executor-module.ts b/plugins/codex-security/mcp-app/tests/support/deep-scan-executor-module.ts index 7d70488e1..00dc47951 100644 --- a/plugins/codex-security/mcp-app/tests/support/deep-scan-executor-module.ts +++ b/plugins/codex-security/mcp-app/tests/support/deep-scan-executor-module.ts @@ -14,7 +14,7 @@ export const executor = await importModule({ stdin: { // Expose internal worker checks only to the test fixtures. contents: `${await readFile(executorSource, "utf8")} -export { snapshotWorkerEnvironment, appendItemDiagnostic, verifyBoundCodexExecutable }; +export { snapshotWorkerEnvironment, appendItemDiagnostic, bindCodexExecutable, verifyBoundCodexExecutable }; export { parseDeepScan } from "./response.js";`, loader: "ts", resolveDir: path.dirname(fileURLToPath(executorSource)), @@ -22,7 +22,18 @@ export { parseDeepScan } from "./response.js";`, }, }); -export const verifyBoundCodexExecutable: (executable: { - path: string; - identity: import("node:fs").BigIntStats; -}) => Promise = executor.verifyBoundCodexExecutable; +export const verifyBoundCodexExecutable: ( + executable: { + path: string; + identity: import("node:fs").BigIntStats; + sha256?: string; + }, + signal?: AbortSignal, +) => Promise = executor.verifyBoundCodexExecutable; + +export const bindCodexExecutable: ( + environment: NodeJS.ProcessEnv, + cwd: string, + signal?: AbortSignal, +) => Promise[0]> = + executor.bindCodexExecutable; 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 0ce4f8508..4f9de0a89 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 @@ -95,9 +95,9 @@ try { ); await check(t, testWorkerTerminalEvents); await check(t, testCompletedWorkerSettlesWithoutWaitingForProcessExit); + await check(t, testAbortPropagation); if (process.platform !== "win32") { await check(t, testStreamTerminationWithoutTerminalEventFails); - await check(t, testAbortPropagation); } }); diff --git a/plugins/codex-security/mcp-app/tests/test_helper_files.ts b/plugins/codex-security/mcp-app/tests/test_helper_files.ts index ae790d5c7..75c1efb7f 100644 --- a/plugins/codex-security/mcp-app/tests/test_helper_files.ts +++ b/plugins/codex-security/mcp-app/tests/test_helper_files.ts @@ -9,6 +9,7 @@ import { after, test } from "node:test"; import { importModule, importSource } from "./import-module.ts"; import { createTemporaryDirectories } from "./support/temporary-directories.ts"; import { registerWorkerExecutableFirstLaunchTests } from "./windows_executable_first_launch_cases.ts"; +import { registerWorkerExecutableCancellationTests } from "./windows_executable_cancellation_cases.ts"; const packagedHelper = new URL( "../../../../sdk/typescript/_bundled_plugin/mcp/helpers.mjs", @@ -307,3 +308,4 @@ test( // The Windows CI job runs this entry point directly and retains native TAP results. registerWorkerExecutableFirstLaunchTests(); +registerWorkerExecutableCancellationTests(); diff --git a/plugins/codex-security/mcp-app/tests/windows_executable_cancellation_cases.ts b/plugins/codex-security/mcp-app/tests/windows_executable_cancellation_cases.ts new file mode 100644 index 000000000..c7543217a --- /dev/null +++ b/plugins/codex-security/mcp-app/tests/windows_executable_cancellation_cases.ts @@ -0,0 +1,132 @@ +import assert from "node:assert/strict"; +import fs, { promises } from "node:fs"; +import { rm, writeFile } from "node:fs/promises"; +import { syncBuiltinESMExports } from "node:module"; +import path from "node:path"; +import test from "node:test"; +import { temporaryDirectory } from "./support/temporary-directories.ts"; +import { + bindCodexExecutable, + verifyBoundCodexExecutable, +} from "./support/deep-scan-executor-module.ts"; + +export function registerWorkerExecutableCancellationTests(): void { + for (const phase of ["binding", "verification"]) { + test(`the worker pin preserves cancellation before ${phase}`, async (t) => { + const root = await temporaryDirectory("worker-cancelled-pin-", true); + t.after(() => rm(root, { recursive: true, force: true })); + const executable = path.join(root, "content-fixture.exe"); + await writeFile(executable, "fixture original bytes\n"); + const bound = await bindCodexExecutable( + { CODEX_CLI_PATH: executable }, + root, + ); + const controller = new AbortController(); + const reason = { message: "synthetic caller cancellation", phase }; + controller.abort(reason); + const inspect = t.mock.method(promises, "stat", () => { + throw new Error("An aborted pin operation must not inspect the file."); + }); + await assert.rejects( + phase === "binding" + ? bindCodexExecutable( + { CODEX_CLI_PATH: executable }, + root, + controller.signal, + ) + : verifyBoundCodexExecutable(bound, controller.signal), + (error) => error === reason, + ); + assert.equal(inspect.mock.callCount(), 0); + }); + } + + test( + "the worker pin cancels an active binding content stream", + { + skip: process.platform !== "win32", + }, + async (t) => { + const root = await temporaryDirectory("worker-cancelled-stream-", true); + t.after(() => rm(root, { recursive: true, force: true })); + const executable = path.join(root, "content-fixture.exe"); + await writeFile(executable, "fixture original bytes\n".repeat(8192)); + const controller = new AbortController(); + const reason = new Error("synthetic cancellation during binding read"); + const originalRead = fs.createReadStream; + let observed: fs.ReadStream | undefined; + const reading = t.mock.method( + fs, + "createReadStream", + (...args: Parameters) => { + const stream = originalRead(...args); + if (args[0] === executable) { + observed = stream; + stream.once("data", () => controller.abort(reason)); + } + return stream; + }, + ); + syncBuiltinESMExports(); + try { + await assert.rejects( + bindCodexExecutable( + { CODEX_CLI_PATH: executable }, + root, + controller.signal, + ), + (error) => error === reason, + ); + } finally { + reading.mock.restore(); + syncBuiltinESMExports(); + } + assert.ok(observed); + if (!observed.closed) + await new Promise((resolve) => observed!.once("close", resolve)); + assert.equal(observed.destroyed, true); + assert.equal(observed.closed, true); + }, + ); + + test( + "the worker pin cancels metadata churn with the caller's reason", + { + skip: process.platform !== "win32", + }, + async (t) => { + const root = await temporaryDirectory("worker-cancelled-churn-", true); + t.after(() => rm(root, { recursive: true, force: true })); + const executable = path.join(root, "content-fixture.exe"); + await writeFile(executable, "fixture original bytes\n"); + const bound = await bindCodexExecutable( + { CODEX_CLI_PATH: executable }, + root, + ); + const controller = new AbortController(); + const reason = new Error("synthetic cancellation during metadata churn"); + const originalStat = promises.stat; + let observations = 0; + t.mock.method( + promises, + "stat", + async (...args: Parameters) => { + if (args[0] !== executable) return originalStat(...args); + observations++; + if (observations === 3) controller.abort(reason); + const identity = await originalStat(args[0], { bigint: true }); + // Keep the real file and content stream while deterministically advancing + // the metadata observation, independent of filesystem chmod timestamps. + return Object.assign(identity, { + ctimeNs: bound.identity.ctimeNs + BigInt(observations), + }); + }, + ); + await assert.rejects( + verifyBoundCodexExecutable(bound, controller.signal), + (error) => error === reason, + ); + assert.equal(observations, 3); + }, + ); +} diff --git a/plugins/codex-security/mcp-app/tests/windows_executable_first_launch_cases.ts b/plugins/codex-security/mcp-app/tests/windows_executable_first_launch_cases.ts index cf79401bc..7b50bb968 100644 --- a/plugins/codex-security/mcp-app/tests/windows_executable_first_launch_cases.ts +++ b/plugins/codex-security/mcp-app/tests/windows_executable_first_launch_cases.ts @@ -1,8 +1,16 @@ import assert from "node:assert/strict"; import { execFile } from "node:child_process"; import { createHash } from "node:crypto"; -import { createReadStream } from "node:fs"; -import { copyFile, rm, stat, utimes, writeFile } from "node:fs/promises"; +import { createReadStream, promises as fs } from "node:fs"; +import { + copyFile, + mkdir, + rename, + rm, + stat, + utimes, + writeFile, +} from "node:fs/promises"; import path from "node:path"; import test from "node:test"; import { setTimeout as delay } from "node:timers/promises"; @@ -21,49 +29,47 @@ export function registerWorkerExecutableFirstLaunchTests(): void { "the first Windows version launch preserves the executable pin", { skip: process.platform !== "win32" }, async (t) => { - const { verifyBoundCodexExecutable } = + const { bindCodexExecutable, verifyBoundCodexExecutable } = await import("./support/deep-scan-executor-module.ts"); const root = await temporaryDirectory("worker-first-launch-", true); t.after(() => rm(root, { recursive: true, force: true })); - const executable = path.join(root, "version-fixture.exe"); - await copyFile(process.execPath, executable); - const beforeDigest = await digest(executable); - const identity = await stat(executable, { bigint: true }); - await verifyBoundCodexExecutable({ path: executable, identity }); - const { stdout } = await promisify(execFile)( - executablePathForSpawn(executable), - ["--version"], - { - windowsHide: true, - }, - ); - assert.equal(stdout.trim(), process.version); - const after = await stat(executable, { bigint: true }); - assert.equal(await digest(executable), beforeDigest); - assert.equal(after.dev, identity.dev); - assert.equal(after.ino, identity.ino); - assert.equal(after.size, identity.size); - assert.equal(after.mtimeNs, identity.mtimeNs); - try { - await verifyBoundCodexExecutable({ path: executable, identity }); - } catch (error) { - if ( - after.ctimeNs !== identity.ctimeNs && - error instanceof Error && - error.name === "DeepScanNonRetryableError" && - error.cause === undefined - ) { - t.todo( - "The current worker pin rejects an ordinary launch when only Windows change time advances.", + for (const name of [ + "version-fixture.exe", + path.join(...Array(10).fill("nested executable directory"), "node.exe"), + ]) { + const executable = path.join(root, name); + await mkdir(path.dirname(executable), { recursive: true }); + await copyFile(process.execPath, executable); + const beforeDigest = await digest(executable); + const bound = await bindCodexExecutable( + { CODEX_CLI_PATH: executable }, + root, + ); + const { identity } = bound; + await verifyBoundCodexExecutable(bound); + for (let launch = 0; launch < 2; launch++) { + const { stdout } = await promisify(execFile)( + executablePathForSpawn(executable), + ["--version"], + { + windowsHide: true, + }, ); + assert.equal(stdout.trim(), process.version); + const after = await stat(executable, { bigint: true }); + assert.equal(await digest(executable), beforeDigest); + assert.equal(after.dev, identity.dev); + assert.equal(after.ino, identity.ino); + assert.equal(after.size, identity.size); + assert.equal(after.mtimeNs, identity.mtimeNs); + await verifyBoundCodexExecutable(bound); } - throw error; } }, ); test("the worker pin rejects a changed synthetic file of the same size", async (t) => { - const { verifyBoundCodexExecutable } = + const { bindCodexExecutable, verifyBoundCodexExecutable } = await import("./support/deep-scan-executor-module.ts"); const root = await temporaryDirectory("worker-changed-pin-", true); t.after(() => rm(root, { recursive: true, force: true })); @@ -72,8 +78,12 @@ export function registerWorkerExecutableFirstLaunchTests(): void { const fixedTime = new Date("2025-01-01T00:00:00Z"); await writeFile(executable, "fixture revision A\n"); await utimes(executable, fixedTime, fixedTime); - const identity = await stat(executable, { bigint: true }); - await verifyBoundCodexExecutable({ path: executable, identity }); + const bound = await bindCodexExecutable( + { CODEX_CLI_PATH: executable }, + root, + ); + const { identity } = bound; + await verifyBoundCodexExecutable(bound); // Retry a real equal-length revision on a later tick if the first write is too fast. for (const [wait, revision] of [ [0, "B"], @@ -86,10 +96,9 @@ export function registerWorkerExecutableFirstLaunchTests(): void { assert.equal(updated.size, identity.size); assert.equal(updated.mtimeNs, identity.mtimeNs); if (updated.ctimeNs !== identity.ctimeNs) { - await assert.rejects( - verifyBoundCodexExecutable({ path: executable, identity }), - { name: "DeepScanNonRetryableError" }, - ); + await assert.rejects(verifyBoundCodexExecutable(bound), { + name: "DeepScanNonRetryableError", + }); return; } } @@ -97,4 +106,150 @@ export function registerWorkerExecutableFirstLaunchTests(): void { "The fixture filesystem reported the same change time across two separately timed content revisions.", ); }); + + test("the worker pin rejects a same-content file replacement", async (t) => { + const { bindCodexExecutable, verifyBoundCodexExecutable } = + await import("./support/deep-scan-executor-module.ts"); + const root = await temporaryDirectory("worker-replaced-pin-", true); + t.after(() => rm(root, { recursive: true, force: true })); + const executable = path.join(root, "content-fixture.exe"); + const replacement = path.join(root, "replacement.exe"); + const fixedTime = new Date("2025-01-01T00:00:00Z"); + await writeFile(executable, "fixture original bytes\n"); + await utimes(executable, fixedTime, fixedTime); + const bound = await bindCodexExecutable( + { CODEX_CLI_PATH: executable }, + root, + ); + await copyFile(executable, replacement); + await utimes(replacement, fixedTime, fixedTime); + assert.equal(await digest(replacement), await digest(executable)); + await rename(replacement, executable); + const replaced = await stat(executable, { bigint: true }); + assert.notEqual(replaced.ino, bound.identity.ino); + assert.equal(replaced.size, bound.identity.size); + assert.equal(replaced.mtimeNs, bound.identity.mtimeNs); + await assert.rejects(verifyBoundCodexExecutable(bound), { + name: "DeepScanNonRetryableError", + }); + }); + + test("the worker pin rejects a changed modification time with identical content", async (t) => { + const { bindCodexExecutable, verifyBoundCodexExecutable } = + await import("./support/deep-scan-executor-module.ts"); + const root = await temporaryDirectory("worker-modified-pin-", true); + t.after(() => rm(root, { recursive: true, force: true })); + const executable = path.join(root, "content-fixture.exe"); + await writeFile(executable, "fixture original bytes\n"); + const bound = await bindCodexExecutable( + { CODEX_CLI_PATH: executable }, + root, + ); + const beforeDigest = await digest(executable); + const changedTime = new Date("2025-01-01T00:00:00Z"); + await utimes(executable, changedTime, changedTime); + assert.equal(await digest(executable), beforeDigest); + assert.notEqual( + (await stat(executable, { bigint: true })).mtimeNs, + bound.identity.mtimeNs, + ); + await assert.rejects(verifyBoundCodexExecutable(bound), { + name: "DeepScanNonRetryableError", + }); + }); + + for (const phase of ["binding", "verification"]) { + test( + `the worker pin rejects a revision during content ${phase}`, + { + skip: process.platform !== "win32", + }, + async (t) => { + const { bindCodexExecutable, verifyBoundCodexExecutable } = + await import("./support/deep-scan-executor-module.ts"); + const root = await temporaryDirectory("worker-streamed-pin-", true); + t.after(() => rm(root, { recursive: true, force: true })); + const executable = path.join(root, "content-fixture.exe"); + const fixedTime = new Date("2025-01-01T00:00:00Z"); + await writeFile(executable, "fixture revision A\n"); + await utimes(executable, fixedTime, fixedTime); + const bind = () => + bindCodexExecutable({ CODEX_CLI_PATH: executable }, root); + const bound = phase === "verification" ? await bind() : undefined; + const originalStat = fs.stat; + let observations = 0; + let revised = false; + let changeTime = bound?.identity.ctimeNs; + t.mock.method( + fs, + "stat", + async (...args: Parameters) => { + if (args[0] !== executable) return originalStat(...args); + observations++; + if (observations === 2) { + await writeFile(executable, "fixture revision B\n"); + await utimes(executable, fixedTime, fixedTime); + revised = true; + } + const identity = await originalStat(args[0], { bigint: true }); + // chmod does not advance change time on every Windows filesystem. + // Inject only that observation while reading and revising real bytes. + changeTime ??= identity.ctimeNs; + return Object.assign(identity, { + ctimeNs: changeTime + BigInt(observations), + }); + }, + ); + await assert.rejects( + bound ? verifyBoundCodexExecutable(bound) : bind(), + { + name: "DeepScanNonRetryableError", + }, + ); + assert.equal(revised, true); + assert.equal(observations, phase === "verification" ? 3 : 2); + assert.equal( + await fs.readFile(executable, "utf8"), + "fixture revision B\n", + ); + }, + ); + } + + test( + "the worker pin accepts a metadata-only change during content verification", + { + skip: process.platform !== "win32", + }, + async (t) => { + const { bindCodexExecutable, verifyBoundCodexExecutable } = + await import("./support/deep-scan-executor-module.ts"); + const root = await temporaryDirectory("worker-metadata-pin-", true); + t.after(() => rm(root, { recursive: true, force: true })); + const executable = path.join(root, "content-fixture.exe"); + await writeFile(executable, "fixture original bytes\n"); + const bound = await bindCodexExecutable( + { CODEX_CLI_PATH: executable }, + root, + ); + const beforeDigest = await digest(executable); + const originalStat = fs.stat; + let observations = 0; + let changedMetadata = false; + t.mock.method(fs, "stat", async (...args: Parameters) => { + if (args[0] !== executable) return originalStat(...args); + observations++; + if (observations === 2) changedMetadata = true; + const identity = await originalStat(args[0], { bigint: true }); + // Report one metadata transition during the real content read, then stability. + return Object.assign(identity, { + ctimeNs: bound.identity.ctimeNs + BigInt(Math.min(observations, 2)), + }); + }); + await verifyBoundCodexExecutable(bound); + assert.equal(changedMetadata, true); + assert.equal(observations, 3); + assert.equal(await digest(executable), beforeDigest); + }, + ); } From bf9853020059a51e704808543b88d0da05697074 Mon Sep 17 00:00:00 2001 From: Michael D'Angelo Date: Tue, 10 Nov 2026 05:44:51 -0800 Subject: [PATCH 21/28] fix(sdk): discover Python for targets when launched from filesystem root (#2569) * fix(sdk): discover Python for targets when launched from filesystem root * test(sdk): launch the Python discovery regression from root --- .../mcp-app/tests/test_deep_scan_executor.ts | 7 ++- sdk/typescript/src/runtime.ts | 24 ++++++-- sdk/typescript/tests-ts/runtime.test.ts | 55 +++++++++++++++++++ .../tests-ts/support/test-subprocess.ts | 3 +- 4 files changed, 80 insertions(+), 9 deletions(-) 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 4f9de0a89..b441c402c 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 @@ -1503,14 +1503,17 @@ async function testWorkerRuntimeSettings() { ); const browserNode = path.join(fixture.root, "browser node"); process.env.CODEX_BROWSER_USE_NODE_PATH = browserNode; - const python = path.join(fixture.root, "selected venv", "bin", "python"); + const systemPython = process.platform === "win32" ? "python" : "python3"; + const python = + configuration === "" && process.platform !== "win32" + ? systemPython + : path.join(fixture.root, "selected venv", "bin", "python"); const helperPython = path.join( fixture.root, "helper venv", "bin", "python", ); - const systemPython = process.platform === "win32" ? "python" : "python3"; const workerPython = (index: number) => index === 0 ? systemPython : `${helperPython}-${index} `; process.env.PYTHON = python; diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.ts index e898679a4..d4bf700d4 100644 --- a/sdk/typescript/src/runtime.ts +++ b/sdk/typescript/src/runtime.ts @@ -3940,13 +3940,11 @@ export async function resolvePluginPython( options: PluginPythonOptions = {}, ): Promise { const environment = options.environment ?? process.env; - const requestedRoots = options.protectedRoot ?? process.cwd(); + const cwd = process.cwd(); + const requestedRoots = options.protectedRoot ?? cwd; const protectedRoot = typeof requestedRoots === "string" ? [requestedRoots] : [...requestedRoots]; - const callerDirectories = [ - process.cwd(), - options.currentDirectory ?? process.cwd(), - ]; + const callerDirectories = new Set([cwd, options.currentDirectory ?? cwd]); // Preserve target and enclosing-checkout protection for every interpreter. for (const directory of new Set([...callerDirectories, ...protectedRoot])) { for (const checkout of await gitProtectionRoots(directory, options.signal)) @@ -3954,7 +3952,21 @@ export async function resolvePluginPython( } // Named interpreters are ambient PATH discovery, even when PYTHON names one. // Explicit trusted paths and managed runtimes retain their existing precedence. - const discoveryRoots = [...protectedRoot, ...callerDirectories]; + const discoveryRoots = [...protectedRoot]; + for (const directory of callerDirectories) { + const physical = + directory === cwd + ? cwd + : await realpath(directory).catch(() => undefined); + // A filesystem-root launch directory also contains the operator's installed tools. + // Explicit scan roots and enclosing checkouts are already in protectedRoot. + if ( + protectedRoot.length === 0 || + physical === undefined || + dirname(physical) !== physical + ) + discoveryRoots.push(directory); + } if (options.configuredPath !== undefined) { return await requirePython( options.configuredPath, diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.ts index ad0100d0a..d120d6abd 100644 --- a/sdk/typescript/tests-ts/runtime.test.ts +++ b/sdk/typescript/tests-ts/runtime.test.ts @@ -7022,6 +7022,61 @@ describe("runtime directories and plugin Python boundary", () => { } }); + testPosix( + "discovers Python outside explicit targets from a filesystem-root working directory", + async () => { + if ( + runTestInSubprocess( + fileURLToPath(import.meta.url), + "discovers Python outside explicit targets from a filesystem-root working directory", + {}, + "/", + ) + ) + return; + const target = await temporaryDirectory(); + const tools = await temporaryDirectory(); + const system = pythonWithLauncher(); + expect(system).not.toBeNull(); + const name = "fixture-python"; + await symlink(system!, join(tools, name)); + await symlink(system!, join(target, name)); + const alias = join(tools, "root-directory"); + await symlink("/", alias, "dir"); + expect(process.cwd()).toBe("/"); + const environment = { PATH: [target, tools].join(":"), PYTHON: name }; + for (const caller of ["/", alias]) { + const selected = await resolvePluginPython({ + currentDirectory: caller, + protectedRoot: target, + environment, + }); + expect(selected).toBe(join(tools, name)); + } + await expect( + resolvePluginPython({ + currentDirectory: `/${basename(target)}-missing/..`, + protectedRoot: target, + environment, + }), + ).rejects.toThrow("unavailable"); + await expect(resolvePluginPython({ environment })).rejects.toThrow( + "unavailable", + ); + for (const protectedRoot of [[], "/"]) { + await expect( + resolvePluginPython({ protectedRoot, environment }), + ).rejects.toThrow("unavailable"); + } + await expect( + resolvePluginPython({ + protectedRoot: target, + environment: { PATH: target, PYTHON: name }, + }), + ).rejects.toThrow("unavailable"); + }, + ); + testPosix( "preserves literal executable override names and accepts padding", async () => { diff --git a/sdk/typescript/tests-ts/support/test-subprocess.ts b/sdk/typescript/tests-ts/support/test-subprocess.ts index 1b653c215..2584938ab 100644 --- a/sdk/typescript/tests-ts/support/test-subprocess.ts +++ b/sdk/typescript/tests-ts/support/test-subprocess.ts @@ -5,6 +5,7 @@ export function runTestInSubprocess( file: string, name: string, environment: NodeJS.ProcessEnv = {}, + cwd: string | URL = new URL("../../", import.meta.url), ): boolean { const identity = `${file}::${name}`; if (process.env["CODEX_SECURITY_ISOLATED_TEST"] === identity) return false; @@ -15,7 +16,7 @@ export function runTestInSubprocess( process.execPath, ["test", "--timeout", timeout, "--test-name-pattern", pattern, file], { - cwd: new URL("../../", import.meta.url), + cwd, encoding: "utf8", env: { ...process.env, From d2bbdbac95ac5a06de9f66dd68009803fe183042 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 10 Nov 2026 06:29:39 -0800 Subject: [PATCH 22/28] chore(deps): update the Linear SDK to 101.0.0 (#2563) Preserve Node-only TypeScript consumer support for the Linear client declarations. --- sdk/typescript/package.json | 2 +- sdk/typescript/pnpm-lock.yaml | 10 +++++----- sdk/typescript/src/linear.ts | 11 +++++++++++ 3 files changed, 17 insertions(+), 6 deletions(-) diff --git a/sdk/typescript/package.json b/sdk/typescript/package.json index e56f70fde..dea67b19c 100644 --- a/sdk/typescript/package.json +++ b/sdk/typescript/package.json @@ -87,7 +87,7 @@ "@inquirer/confirm": "6.3.5", "@inquirer/input": "5.1.9", "@inquirer/search": "4.3.6", - "@linear/sdk": "100.0.0", + "@linear/sdk": "101.0.0", "@octokit/core": "7.0.8", "@openai/codex": "0.167.0", "@openai/codex-sdk": "0.167.0", diff --git a/sdk/typescript/pnpm-lock.yaml b/sdk/typescript/pnpm-lock.yaml index fcc453172..116044f03 100644 --- a/sdk/typescript/pnpm-lock.yaml +++ b/sdk/typescript/pnpm-lock.yaml @@ -21,8 +21,8 @@ importers: specifier: 4.3.6 version: 4.3.6(@types/node@26.6.6) '@linear/sdk': - specifier: 100.0.0 - version: 100.0.0(graphql@17.0.2) + specifier: 101.0.0 + version: 101.0.0(graphql@17.0.2) '@octokit/core': specifier: 7.0.8 version: 7.0.8 @@ -360,8 +360,8 @@ packages: '@jsdevtools/ono@7.1.3': resolution: {integrity: sha512-4JQNk+3mVzK3xh2rqd6RB4J46qUR19azEHBneZyTZM+c456qOrbbM/5xcR8huNCCcbVt7+UmizG6GuUvPvKUYg==} - '@linear/sdk@100.0.0': - resolution: {integrity: sha512-7+n+Xqo6yYtexeDfaFnmT9j7bapkKyjB5cV63STuG8N1Wnjb9vyhpwOpn+t0VE3emGE7ZNEu2Rz1FHSWD84raw==} + '@linear/sdk@101.0.0': + resolution: {integrity: sha512-pQMaZmh/ewEMR9QmSZDuY+5NQy+xYS3DJDjqLEqlqj35M71Xde9vMHuNijamDZGqG6CojtCSU6YjgIg14pw+1A==} engines: {node: ^20.19.0 || >=22.12.0} '@modelcontextprotocol/server@2.0.0-alpha.4': @@ -1172,7 +1172,7 @@ snapshots: '@jsdevtools/ono@7.1.3': {} - '@linear/sdk@100.0.0(graphql@17.0.2)': + '@linear/sdk@101.0.0(graphql@17.0.2)': dependencies: '@graphql-typed-document-node/core': 3.2.0(graphql@17.0.2) transitivePeerDependencies: diff --git a/sdk/typescript/src/linear.ts b/sdk/typescript/src/linear.ts index a121c35cd..d7fe9217a 100644 --- a/sdk/typescript/src/linear.ts +++ b/sdk/typescript/src/linear.ts @@ -1,4 +1,5 @@ import { parseJson } from "./value.js"; +import type { webcrypto } from "node:crypto"; import { AuthenticationLinearError, ForbiddenLinearError, @@ -8,6 +9,16 @@ import { import type { JsonObject } from "./config.js"; import { CodexSecurityError, errorMessage } from "./errors.js"; +// Linear's DPoP declarations use these global types even for Node-only clients. +type NodeOnlyWebCrypto = typeof globalThis extends { onmessage: unknown } + ? {} + : T; + +declare global { + interface JsonWebKey extends NodeOnlyWebCrypto {} + interface CryptoKeyPair extends NodeOnlyWebCrypto {} +} + export type LinearClientFactory< Method extends keyof LinearClient = "issue" | "projects", > = ( From d4175bc3b5356ffc29d7de4d549a043604eea35e Mon Sep 17 00:00:00 2001 From: Michael D'Angelo Date: Tue, 10 Nov 2026 06:45:57 -0800 Subject: [PATCH 23/28] fix(native): read deep sealed artifacts under Linux descriptor limits (#2570) --- .../native/src/scan_read_unix.rs | 221 +++++++++++++++--- 1 file changed, 195 insertions(+), 26 deletions(-) diff --git a/plugins/codex-security/native/src/scan_read_unix.rs b/plugins/codex-security/native/src/scan_read_unix.rs index e87a9ddaf..03c6198c5 100644 --- a/plugins/codex-security/native/src/scan_read_unix.rs +++ b/plugins/codex-security/native/src/scan_read_unix.rs @@ -44,6 +44,52 @@ fn open_at(parent: RawFd, path: &OsStr, flags: i32) -> io::Result { Ok(unsafe { File::from_raw_fd(descriptor) }) } +// Retry a deep lookup from the held root when keeping every ancestor open exhausted +// the process descriptor limit. openat2 enforces the boundary and rejects symlinks +// throughout the parent path in a single kernel lookup. +#[cfg(target_os = "linux")] +fn open_beneath_root(root: &File, relative_path: &str) -> Result { + let (parent_path, name) = relative_path + .rsplit_once('/') + .unwrap_or((".", relative_path)); + let parent_path = CString::new(parent_path).map_err(|error| OpenError::Parent(error.into()))?; + // The kernel requires unused and future open_how fields to be zero. + let mut how: libc::open_how = unsafe { std::mem::zeroed() }; + how.flags = (libc::O_PATH | libc::O_DIRECTORY | libc::O_CLOEXEC) as u64; + how.resolve = libc::RESOLVE_BENEATH | libc::RESOLVE_NO_SYMLINKS; + let open_parent = || -> io::Result { + let descriptor = unsafe { + libc::syscall( + libc::SYS_openat2, + root.as_raw_fd(), + parent_path.as_ptr(), + &how, + std::mem::size_of_val(&how), + ) + }; + if descriptor < 0 { + return Err(io::Error::last_os_error()); + } + Ok(unsafe { File::from_raw_fd(descriptor as RawFd) }) + }; + + let parent = open_parent().map_err(OpenError::Parent)?; + let file = open_at( + parent.as_raw_fd(), + OsStr::new(name), + libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_NONBLOCK, + ) + .map_err(OpenError::Leaf)?; + let verify = || { + if !same_file(&parent.metadata()?, &open_parent()?.metadata()?) { + return Err(io::Error::other("Scan path changed while opening the file")); + } + verify_components(&parent, &[name], &[], &file) + }; + verify().map_err(OpenError::Verify)?; + Ok(file) +} + // Check the names against their held descriptors before returning the opened file. fn verify_components( root: &File, @@ -79,6 +125,58 @@ fn verify_components( Ok(()) } +#[derive(Debug)] +enum OpenError { + Parent(io::Error), + Leaf(io::Error), + Verify(io::Error), +} + +fn open_by_components(root: &File, parts: &[&str]) -> Result { + let mut directories = Vec::new(); + let mut parent = root.as_raw_fd(); + for part in &parts[..parts.len() - 1] { + let directory = open_at( + parent, + OsStr::new(part), + DIRECTORY_ACCESS | libc::O_DIRECTORY | libc::O_NOFOLLOW, + ) + .map_err(OpenError::Parent)?; + parent = directory.as_raw_fd(); + directories.push(directory); + } + let file = open_at( + parent, + OsStr::new(parts[parts.len() - 1]), + libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_NONBLOCK, + ) + .map_err(OpenError::Leaf)?; + verify_components(root, parts, &directories, &file).map_err(OpenError::Verify)?; + Ok(file) +} + +fn open_relative_file(root: &File, parts: &[&str]) -> Result { + let result = open_by_components(root, parts); + #[cfg(target_os = "linux")] + if matches!( + &result, + Err(OpenError::Parent(error) | OpenError::Leaf(error)) + if error.raw_os_error() == Some(libc::EMFILE) + ) { + // The unsuccessful walk has released its descriptors. Preserve its error + // when the kernel or sandbox cannot perform the bounded lookup. + let retry = open_beneath_root(root, &parts.join("/")); + if !matches!( + &retry, + Err(OpenError::Parent(error)) + if matches!(error.raw_os_error(), Some(libc::ENOSYS | libc::EPERM | libc::ENAMETOOLONG)) + ) { + return retry; + } + } + result +} + impl ScanReadRootBackend { pub(crate) fn open(path: Buffer) -> napi::Result { let path = PathBuf::from(OsStr::from_bytes(path.as_ref())); @@ -139,32 +237,23 @@ impl ScanReadRootBackend { .directory .as_ref() .ok_or_else(|| napi::Error::from_reason("Scan directory is closed"))?; - let mut directories = Vec::new(); - let mut parent = root.as_raw_fd(); - for part in &parts[..parts.len() - 1] { - let directory = match open_at( - parent, - OsStr::new(part), - DIRECTORY_ACCESS | libc::O_DIRECTORY | libc::O_NOFOLLOW, - ) { - Ok(directory) => directory, - Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None), - Err(error) => return Err(failure("Cannot open scan file parent", error)), - }; - parent = directory.as_raw_fd(); - directories.push(directory); - } - let file = match open_at( - parent, - OsStr::new(parts[parts.len() - 1]), - libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_NONBLOCK, - ) { + let file = match open_relative_file(root, &parts) { Ok(file) => file, - Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None), - Err(error) if error.raw_os_error() == Some(libc::EACCES) => { - return Err(crate::scan_read::access_denied(env, error)) + Err(OpenError::Parent(error) | OpenError::Leaf(error)) + if error.kind() == io::ErrorKind::NotFound => + { + return Ok(None) + } + Err(OpenError::Parent(error)) => { + return Err(failure("Cannot open scan file parent", error)) + } + Err(OpenError::Leaf(error)) if error.raw_os_error() == Some(libc::EACCES) => { + return Err(crate::scan_read::access_denied(env, error)); + } + Err(OpenError::Leaf(error)) => return Err(failure("Cannot open scan file", error)), + Err(OpenError::Verify(error)) => { + return Err(failure("Cannot verify opened scan file", error)) } - Err(error) => return Err(failure("Cannot open scan file", error)), }; if !file .metadata() @@ -175,8 +264,6 @@ impl ScanReadRootBackend { "Expected a regular non-symlink scan file", )); } - verify_components(root, &parts, &directories, &file) - .map_err(|error| failure("Cannot verify opened scan file", error))?; self.verify()?; Ok(Some(ScanReadFileBackend { file })) } @@ -216,6 +303,88 @@ impl ScanReadFileBackend { mod tests { use super::*; + #[cfg(target_os = "linux")] + #[test] + fn reads_deep_artifacts_with_a_low_descriptor_limit() -> io::Result<()> { + use std::{os::unix::process::CommandExt, process::Command}; + + const CHILD_ROOT: &str = "CODEX_SECURITY_TEST_FD_LIMIT_ROOT"; + let mut parts = vec!["tier"; 48]; + parts.push("receipt"); + if let Some(path) = std::env::var_os(CHILD_ROOT) { + let root = File::open(path)?; + assert!(matches!( + open_by_components(&root, &parts), + Err(OpenError::Parent(error) | OpenError::Leaf(error)) + if error.raw_os_error() == Some(libc::EMFILE) + )); + let mut file = open_relative_file(&root, &parts).unwrap(); + let mut value = String::new(); + file.read_to_string(&mut value)?; + assert_eq!(value, "sealed"); + *parts.last_mut().unwrap() = "missing"; + assert!(matches!( + open_relative_file(&root, &parts), + Err(OpenError::Leaf(error)) if error.kind() == io::ErrorKind::NotFound + )); + parts.pop(); + parts.extend(["link", "receipt"]); + assert!(open_relative_file(&root, &parts).is_err()); + return Ok(()); + } + + let fixture = + std::env::temp_dir().join(format!("codex-security-fd-limit-{}", std::process::id())); + fs::create_dir(&fixture)?; + let result = (|| { + let scan = fixture.join("scan"); + let path = scan.join(parts.join("/")); + let parent = path.parent().unwrap(); + fs::create_dir_all(parent)?; + fs::write(&path, "sealed")?; + fs::write(fixture.join("receipt"), "outside")?; + std::os::unix::fs::symlink(&fixture, parent.join("link"))?; + let root = File::open(&scan)?; + // Older kernels and sandboxes can disable openat2 entirely. + match open_beneath_root(&root, &parts.join("/")) { + Err(OpenError::Parent(error)) + if matches!(error.raw_os_error(), Some(libc::ENOSYS | libc::EPERM)) => + { + return Ok(()) + } + other => drop(other.unwrap()), + } + let mut child = Command::new(std::env::current_exe()?); + child.args([ + "--exact", + "scan_read_unix::tests::reads_deep_artifacts_with_a_low_descriptor_limit", + ]); + child.env(CHILD_ROOT, scan); + // Only the isolated test child receives the lower process limit. + unsafe { + child.pre_exec(|| { + let limit = libc::rlimit { + rlim_cur: 32, + rlim_max: 32, + }; + if libc::setrlimit(libc::RLIMIT_NOFILE, &limit) != 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) + }); + } + let output = child.output()?; + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stdout) + ); + Ok(()) + })(); + fs::remove_dir_all(fixture)?; + result + } + #[test] fn verifies_every_opened_component_including_the_leaf() -> io::Result<()> { let scan = From 1579aeb514be943df6c1d08e2611b0994f5ca127 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 10 Nov 2026 06:56:07 -0800 Subject: [PATCH 24/28] chore(deps): update semver to 7.8.6 across SDK and tooling (#2562) Align the SDK, mutation tools and triage eval locks on the comparator parsing fix. --- evals/triage-finding/pnpm-lock.yaml | 8 ++++---- sdk/mutation/pnpm-lock.yaml | 16 ++++++++-------- sdk/typescript/package.json | 2 +- sdk/typescript/pnpm-lock.yaml | 10 +++++----- 4 files changed, 18 insertions(+), 18 deletions(-) diff --git a/evals/triage-finding/pnpm-lock.yaml b/evals/triage-finding/pnpm-lock.yaml index 35b42a6e0..627a768ef 100644 --- a/evals/triage-finding/pnpm-lock.yaml +++ b/evals/triage-finding/pnpm-lock.yaml @@ -1753,8 +1753,8 @@ packages: seedrandom@3.0.5: resolution: {integrity: sha512-8OwmbklUNzwezjGInmZ+2clQmExQPvomqjL7LFqOYqtmuxRgQYqOD3mHaU+MvZn5FLUeVxVfQjwLZW/n/JFuqg==} - semver@7.8.5: - resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==} + semver@7.8.6: + resolution: {integrity: sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==} engines: {node: '>=10'} hasBin: true @@ -3549,7 +3549,7 @@ snapshots: python-shell: 5.0.0 rfdc: 1.4.1 saxes: 6.0.0 - semver: 7.8.5 + semver: 7.8.6 signal-exit: 4.1.0 simple-git: 4.0.2 socket.io: 4.8.4 @@ -3699,7 +3699,7 @@ snapshots: seedrandom@3.0.5: {} - semver@7.8.5: {} + semver@7.8.6: {} send@1.2.1: dependencies: diff --git a/sdk/mutation/pnpm-lock.yaml b/sdk/mutation/pnpm-lock.yaml index 1e370f3f5..e784f769b 100644 --- a/sdk/mutation/pnpm-lock.yaml +++ b/sdk/mutation/pnpm-lock.yaml @@ -700,8 +700,8 @@ packages: safer-buffer@2.1.2: resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} - semver@7.8.5: - resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==} + semver@7.8.6: + resolution: {integrity: sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==} engines: {node: '>=10'} hasBin: true @@ -822,7 +822,7 @@ snapshots: import-meta-resolve: 4.2.0 json5: 2.2.3 obug: 2.1.4 - semver: 7.8.5 + semver: 7.8.6 '@babel/generator@8.0.0': dependencies: @@ -843,7 +843,7 @@ snapshots: '@babel/helper-validator-option': 8.0.0 browserslist: 4.28.9 lru-cache: 11.5.2 - semver: 7.8.5 + semver: 7.8.6 '@babel/helper-create-class-features-plugin@8.0.1(@babel/core@8.0.1)': dependencies: @@ -854,7 +854,7 @@ snapshots: '@babel/helper-replace-supers': 8.0.1(@babel/core@8.0.1) '@babel/helper-skip-transparent-expression-wrappers': 8.0.0 '@babel/traverse': 8.0.4 - semver: 7.8.5 + semver: 7.8.6 '@babel/helper-globals@8.0.0': {} @@ -1210,7 +1210,7 @@ snapshots: npm-run-path: 6.0.0 progress: 2.0.3 rxjs: 7.8.2 - semver: 7.8.5 + semver: 7.8.6 source-map: 0.7.6 tree-kill: 1.2.2 tslib: 2.8.1 @@ -1233,7 +1233,7 @@ snapshots: '@stryker-mutator/api': 10.1.1 '@stryker-mutator/util': 10.1.1 angular-html-parser: 10.11.0 - semver: 7.8.5 + semver: 7.8.6 tslib: 2.8.1 weapon-regex: 2.0.5 @@ -1493,7 +1493,7 @@ snapshots: safer-buffer@2.1.2: {} - semver@7.8.5: {} + semver@7.8.6: {} shebang-command@2.0.0: dependencies: diff --git a/sdk/typescript/package.json b/sdk/typescript/package.json index dea67b19c..729454a11 100644 --- a/sdk/typescript/package.json +++ b/sdk/typescript/package.json @@ -99,7 +99,7 @@ "pdfjs-dist": "6.5.438", "react": "19.3.1", "saxes": "6.0.0", - "semver": "7.8.5", + "semver": "7.8.6", "smol-toml": "1.9.1", "string-width": "8.3.0", "strip-ansi": "7.2.0", diff --git a/sdk/typescript/pnpm-lock.yaml b/sdk/typescript/pnpm-lock.yaml index 116044f03..0b7261f83 100644 --- a/sdk/typescript/pnpm-lock.yaml +++ b/sdk/typescript/pnpm-lock.yaml @@ -57,8 +57,8 @@ importers: specifier: 6.0.0 version: 6.0.0 semver: - specifier: 7.8.5 - version: 7.8.5 + specifier: 7.8.6 + version: 7.8.6 smol-toml: specifier: 1.9.1 version: 1.9.1 @@ -934,8 +934,8 @@ packages: scheduler@0.28.0: resolution: {integrity: sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==} - semver@7.8.5: - resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==} + semver@7.8.6: + resolution: {integrity: sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==} engines: {node: '>=10'} hasBin: true @@ -1641,7 +1641,7 @@ snapshots: scheduler@0.28.0: {} - semver@7.8.5: {} + semver@7.8.6: {} signal-exit@3.0.7: {} From ea9114512ebe9744ec7e991271fc3347f38f68bf Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 10 Nov 2026 06:59:01 -0800 Subject: [PATCH 25/28] ci: update install-action to v2.90.0 (#2561) Pin the workflow-quality and lockfile-audit installer to the v2.90.0 commit. --- .github/actions/audit-pnpm-lockfiles/action.yml | 2 +- .github/workflows/workflow-quality.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/actions/audit-pnpm-lockfiles/action.yml b/.github/actions/audit-pnpm-lockfiles/action.yml index 013142b13..459a9396f 100644 --- a/.github/actions/audit-pnpm-lockfiles/action.yml +++ b/.github/actions/audit-pnpm-lockfiles/action.yml @@ -8,7 +8,7 @@ runs: using: composite steps: - name: Install Trivy - uses: taiki-e/install-action@682ce6c3c696a4cd5168a05f98e51aa02b877941 # v2.89.1 + uses: taiki-e/install-action@b80e2bb2635f28eb98b9fce1e2f0887e1535c6b2 # v2.90.0 with: tool: trivy@0.76.1 - name: Check for high and critical vulnerabilities diff --git a/.github/workflows/workflow-quality.yml b/.github/workflows/workflow-quality.yml index efaf7f595..ae99da62f 100644 --- a/.github/workflows/workflow-quality.yml +++ b/.github/workflows/workflow-quality.yml @@ -18,7 +18,7 @@ jobs: with: persist-credentials: false - name: Install ShellCheck and zizmor - uses: taiki-e/install-action@682ce6c3c696a4cd5168a05f98e51aa02b877941 # v2.89.1 + uses: taiki-e/install-action@b80e2bb2635f28eb98b9fce1e2f0887e1535c6b2 # v2.90.0 with: tool: shellcheck@0.11.0,zizmor@1.30.1 - name: Install actionlint From ba6702440e7c1e3e819c8d552376b36ded56d564 Mon Sep 17 00:00:00 2001 From: Michael D'Angelo Date: Tue, 10 Nov 2026 07:16:21 -0800 Subject: [PATCH 26/28] fix(scan): isolate Git display settings in content snapshots (#2568) * fix(scan): isolate Git display settings in content snapshots * fix(scan): pin hunk, file order, and rename rendering in snapshots * test(scan): write Git order fixtures with LF on every platform * fix(scan): stabilize submodule, indentation, and rename presentation * Capture the configured submodule diff before asserting * Normalize Git driver annotations and binary patch rendering --- .../tests/support/fake-codex-source.ts | 5 +- .../mcp-app/tests/test_deep_scan_executor.ts | 1 + .../codex-security/scripts/workbench_db.py | 14 +- .../scripts/workbench_scan_history.py | 11 +- .../scripts/workbench_scan_start.py | 3 +- .../codex-security/scripts/workbench_setup.py | 2 +- .../scripts/workbench_target.py | 156 +++++++++++++-- .../tests/test_workbench_target.py | 179 ++++++++++++++++++ 8 files changed, 345 insertions(+), 26 deletions(-) diff --git a/plugins/codex-security/mcp-app/tests/support/fake-codex-source.ts b/plugins/codex-security/mcp-app/tests/support/fake-codex-source.ts index 9e2a92cae..51ae582c3 100644 --- a/plugins/codex-security/mcp-app/tests/support/fake-codex-source.ts +++ b/plugins/codex-security/mcp-app/tests/support/fake-codex-source.ts @@ -21,7 +21,7 @@ const accountResult = ${JSON.stringify(accountResult)}; const preflightMarkerPath = process.env.FAKE_CODEX_PREFLIGHT_MARKER ?? ${JSON.stringify(preflightMarkerPath)}; const temporaryEnvironment = Object.fromEntries(['TEMP', 'TMP'].map(name => [name, process.env[name]])); if (process.argv.includes('app-server')) { - const preflight = { executablePath: process.argv[1], argv: process.argv.slice(2), configPath: process.env.CODEX_SECURITY_CONFIG_PATH, stateDirectory: process.env.CODEX_SECURITY_STATE_DIR, temporaryEnvironment, runnerTrackingId: process.env.RUNNER_TRACKING_ID, libraryPath: process.env["LD_LIBRARY_PATH"], cwd: process.cwd(), codexHome: process.env.CODEX_HOME, providerKey: process.env.SYNTHETIC_GATEWAY_KEY, providerHeaders: Object.fromEntries(['SYNTHETIC_HEADER_VALUE', 'OPENROUTER_API_KEY', 'FIREWORKS_API_KEY'].map(name => [name, process.env[name]])), providerHeader: process.env.SYNTHETIC_HEADER_VALUE, cacheDirectory: process.env.XDG_CACHE_HOME, gitEnvironment: Object.fromEntries(['PATH', 'HOME', 'NODE_OPTIONS', 'NODE_DEBUG', 'NODE_EXTRA_CA_CERTS', 'CODEX_MCP_NODE_PATH', 'CODEX_SECURITY_GIT', 'GIT_SSH_COMMAND', 'GIT_CONFIG_GLOBAL', 'GIT_GLOB_PATHSPECS', 'GIT_ICASE_PATHSPECS'].map(name => [name, process.env[name]])), requests: [] }; + const preflight = { executablePath: process.argv[1], argv: process.argv.slice(2), configPath: process.env.CODEX_SECURITY_CONFIG_PATH, stateDirectory: process.env.CODEX_SECURITY_STATE_DIR, temporaryEnvironment, runnerTrackingId: process.env.RUNNER_TRACKING_ID, libraryPath: process.env["LD_LIBRARY_PATH"], cwd: process.cwd(), codexHome: process.env.CODEX_HOME, providerKey: process.env.SYNTHETIC_GATEWAY_KEY, providerHeaders: Object.fromEntries(['SYNTHETIC_HEADER_VALUE', 'OPENROUTER_API_KEY', 'FIREWORKS_API_KEY'].map(name => [name, process.env[name]])), providerHeader: process.env.SYNTHETIC_HEADER_VALUE, cacheDirectory: process.env.XDG_CACHE_HOME, gitEnvironment: Object.fromEntries(['PATH', 'HOME', 'NODE_OPTIONS', 'NODE_DEBUG', 'NODE_EXTRA_CA_CERTS', 'CODEX_MCP_NODE_PATH', 'CODEX_SECURITY_GIT', 'GIT_SSH_COMMAND', 'GIT_CONFIG_GLOBAL', 'GIT_DIFF_OPTS', 'GIT_GLOB_PATHSPECS', 'GIT_ICASE_PATHSPECS'].map(name => [name, process.env[name]])), requests: [] }; writeFileSync(preflightMarkerPath, JSON.stringify(preflight)); ${jsonLineInputSource(` if (message.method === 'initialized') continue; if (message.method === 'config/read' || message.method === 'permissionProfile/list') { @@ -80,7 +80,7 @@ const pythonRuntime = pythonProbe ? JSON.parse(pythonProbe.stdout) : undefined; const knowledgePath = stdin.includes('synthetic worker configuration fixture') ? process.env.CODEX_SECURITY_KNOWLEDGE_BASE : undefined; const knowledgeDocuments = knowledgePath === undefined ? undefined : Object.fromEntries(readdirSync(knowledgePath).map(name => [name, readFileSync(join(knowledgePath, name), 'utf8')])); const deepConfig = process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH ? readFileSync(process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH, 'utf8') : undefined; -writeFileSync(process.env.FAKE_CODEX_MARKER, JSON.stringify({ executablePath: process.argv[1], ...(scopeInput === undefined ? {} : { scopeInput }), argv: process.argv.slice(2), stdin, cwd: process.cwd(), knowledgePath, knowledgeDocuments, deepConfig, codexHome: process.env.CODEX_HOME, temporaryEnvironment, cacheDirectory: process.env.XDG_CACHE_HOME, gitEnvironment: Object.fromEntries(['PATH', 'HOME', 'NODE_OPTIONS', 'NODE_DEBUG', 'NODE_EXTRA_CA_CERTS', 'CODEX_MCP_NODE_PATH', 'CODEX_SECURITY_GIT', 'GIT_SSH_COMMAND', 'GIT_CONFIG_GLOBAL', 'GIT_GLOB_PATHSPECS', 'GIT_ICASE_PATHSPECS'].map(name => [name, process.env[name]])), configPath: process.env.CODEX_SECURITY_CONFIG_PATH, deepConfigPath: process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH, python: process.env.PYTHON, mcpNodePath: process.env.CODEX_MCP_NODE_PATH, bundledTool: toolProbe?.stdout.trim(), pythonPrefix: pythonRuntime?.[0], pythonLibraryPath: pythonRuntime?.[1], runtimeEnvironment, codexConfig, providerHeaders: Object.fromEntries(['SYNTHETIC_HEADER_VALUE', 'OPENROUTER_API_KEY', 'FIREWORKS_API_KEY'].map(name => [name, process.env[name]])), providerKey: process.env.SYNTHETIC_GATEWAY_KEY, providerHeader: process.env.SYNTHETIC_HEADER_VALUE, originator: process.env.CODEX_INTERNAL_ORIGINATOR_OVERRIDE, ...(profileContents === undefined ? {} : { profileContents }), ...(openaiAuthentication ? { openaiAuthentication } : {}), ...(bedrockAuthentication ? { bedrockAuthentication } : {}) })); +writeFileSync(process.env.FAKE_CODEX_MARKER, JSON.stringify({ executablePath: process.argv[1], ...(scopeInput === undefined ? {} : { scopeInput }), argv: process.argv.slice(2), stdin, cwd: process.cwd(), knowledgePath, knowledgeDocuments, deepConfig, codexHome: process.env.CODEX_HOME, temporaryEnvironment, cacheDirectory: process.env.XDG_CACHE_HOME, gitEnvironment: Object.fromEntries(['PATH', 'HOME', 'NODE_OPTIONS', 'NODE_DEBUG', 'NODE_EXTRA_CA_CERTS', 'CODEX_MCP_NODE_PATH', 'CODEX_SECURITY_GIT', 'GIT_SSH_COMMAND', 'GIT_CONFIG_GLOBAL', 'GIT_DIFF_OPTS', 'GIT_GLOB_PATHSPECS', 'GIT_ICASE_PATHSPECS'].map(name => [name, process.env[name]])), configPath: process.env.CODEX_SECURITY_CONFIG_PATH, deepConfigPath: process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH, python: process.env.PYTHON, mcpNodePath: process.env.CODEX_MCP_NODE_PATH, bundledTool: toolProbe?.stdout.trim(), pythonPrefix: pythonRuntime?.[0], pythonLibraryPath: pythonRuntime?.[1], runtimeEnvironment, codexConfig, providerHeaders: Object.fromEntries(['SYNTHETIC_HEADER_VALUE', 'OPENROUTER_API_KEY', 'FIREWORKS_API_KEY'].map(name => [name, process.env[name]])), providerKey: process.env.SYNTHETIC_GATEWAY_KEY, providerHeader: process.env.SYNTHETIC_HEADER_VALUE, originator: process.env.CODEX_INTERNAL_ORIGINATOR_OVERRIDE, ...(profileContents === undefined ? {} : { profileContents }), ...(openaiAuthentication ? { openaiAuthentication } : {}), ...(bedrockAuthentication ? { bedrockAuthentication } : {}) })); if (stdin.includes('COMPLETE_THEN_HANG')) process.on('SIGTERM', () => { if (!stdin.includes('IGNORE_TERMINATION')) setTimeout(() => process.exit(0), 100); }); if (stdin.includes('THREAD_START_CONFIG_ERROR')) { console.error('Error: thread/start: thread/start failed: agents.max_threads cannot be set when features.multi_agent_v2 is enabled (code -32600)'); process.exit(1); } @@ -140,6 +140,7 @@ export function workerGitEnvironment(root: string) { ), CODEX_SECURITY_GIT: path.join(root, "selected tools", "git"), GIT_SSH_COMMAND: "synthetic-ssh --fixture", + GIT_DIFF_OPTS: "--unified=0", GIT_GLOB_PATHSPECS: "1", GIT_ICASE_PATHSPECS: "1", GIT_CONFIG_GLOBAL: path.join(root, "operator.gitconfig"), 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 b441c402c..adf48e7d4 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 @@ -1457,6 +1457,7 @@ async function testWorkerRuntimeSettings() { "CODEX_SECURITY_GIT", "GIT_SSH_COMMAND", "GIT_CONFIG_GLOBAL", + "GIT_DIFF_OPTS", "GIT_GLOB_PATHSPECS", "GIT_ICASE_PATHSPECS", "CODEX_CLI_PATH", diff --git a/plugins/codex-security/scripts/workbench_db.py b/plugins/codex-security/scripts/workbench_db.py index 716b2589d..d06eca4de 100644 --- a/plugins/codex-security/scripts/workbench_db.py +++ b/plugins/codex-security/scripts/workbench_db.py @@ -669,7 +669,8 @@ def require_working_tree_unchanged(target: Path, diff_target: dict[str, str] | N and diff_target["kind"] == "working_tree" and ( git_revision(target) != diff_target["headRevision"] - or worktree_content_digest(target) != diff_target["contentDigest"] + or worktree_content_digest(target, expected_digest=diff_target["contentDigest"]) + != diff_target["contentDigest"] ) ): raise SystemExit("The selected scan target changed while the scan was starting. Try again.") @@ -2362,7 +2363,9 @@ def require_reviewed_patch_applied( ) -> str | None: target = require_scan_target_identity(scan) _, content_digest = remediation_checkout_snapshot( - scan, expected_revision=remediation["base_revision"] + scan, + expected_revision=remediation["base_revision"], + expected_digest=remediation["base_content_digest"], ) if content_digest == remediation["base_content_digest"]: raise SystemExit( @@ -2421,6 +2424,7 @@ def require_reviewed_patch_applied( pathspec or ".", git_dir=short or metadata, work_tree=checkout_root, + expected_digest=remediation["base_content_digest"], ) ) if reverted_digest != remediation["base_content_digest"] and unversioned: @@ -2454,9 +2458,6 @@ def require_remediation_checkout_unchanged( require_applied_content: bool = False, require_base_content: bool = False, ) -> None: - _, content_digest = remediation_checkout_snapshot( - scan, expected_revision=remediation["base_revision"] - ) expected_digest = ( remediation["applied_content_digest"] if require_applied_content @@ -2464,6 +2465,9 @@ def require_remediation_checkout_unchanged( if require_base_content else None ) + _, content_digest = remediation_checkout_snapshot( + scan, expected_revision=remediation["base_revision"], expected_digest=expected_digest + ) if expected_digest is not None and content_digest != expected_digest: raise SystemExit( "Working-tree contents changed. Regenerate the remediation patch against the current checkout." diff --git a/plugins/codex-security/scripts/workbench_scan_history.py b/plugins/codex-security/scripts/workbench_scan_history.py index f87ba5d86..a26a7bb75 100644 --- a/plugins/codex-security/scripts/workbench_scan_history.py +++ b/plugins/codex-security/scripts/workbench_scan_history.py @@ -80,8 +80,11 @@ def _windows_resume_checkout(scan: sqlite3.Row) -> Path: except SystemExit as exc: raise SystemExit(replaced) from exc with verified_windows_checkout(scan, repository, replaced_message=replaced): - snapshot = (scan["target_revision"], scan["target_snapshot_digest"]) - if scan_target_identity(repository, None)[:2] != snapshot: + expected = (scan["target_revision"], scan["target_snapshot_digest"]) + current = scan_target_identity( + repository, None, expected_digest=scan["target_snapshot_digest"] + ) + if current[:2] != expected: raise SystemExit("Cannot resume: the original checkout revision or contents changed.") return repository @@ -127,7 +130,9 @@ def cli_scan_resume( raise SystemExit( "Cannot resume: the original checkout is missing or was replaced." ) from exc - if scan_target_identity(repository, None) != ( + if scan_target_identity( + repository, None, expected_digest=scan["target_snapshot_digest"] + ) != ( scan["target_revision"], scan["target_snapshot_digest"], scan["target_device"], diff --git a/plugins/codex-security/scripts/workbench_scan_start.py b/plugins/codex-security/scripts/workbench_scan_start.py index df73b5c71..d81a7ed9c 100644 --- a/plugins/codex-security/scripts/workbench_scan_start.py +++ b/plugins/codex-security/scripts/workbench_scan_start.py @@ -65,6 +65,7 @@ def scan_target_identity( diff_target: dict[str, str] | None, *, metadata: os.stat_result | None = None, + expected_digest: str | None = None, ) -> tuple[str, str | None, int | str, int | str]: """Return revision, content digest, device ID, and inode for scan registration. @@ -79,7 +80,7 @@ def scan_target_identity( snapshot_digest = ( directory_content_digest(target) if revision == "unversioned" - else worktree_content_digest(target) + else worktree_content_digest(target, expected_digest=expected_digest) ) return ( revision, diff --git a/plugins/codex-security/scripts/workbench_setup.py b/plugins/codex-security/scripts/workbench_setup.py index 6117ce609..dfb371e4d 100644 --- a/plugins/codex-security/scripts/workbench_setup.py +++ b/plugins/codex-security/scripts/workbench_setup.py @@ -76,7 +76,7 @@ def require_diff_target( if kind == "working_tree": base = resolve_git_commit(target, base_revision or "HEAD", "Working-tree base") head = resolve_git_commit(target, head_revision or current_head, "Working-tree HEAD") - current_digest = worktree_content_digest(target) + current_digest = worktree_content_digest(target, expected_digest=content_digest) if base != current_head or head != current_head: raise SystemExit( "Repository HEAD changed after these working-tree changes were selected. " diff --git a/plugins/codex-security/scripts/workbench_target.py b/plugins/codex-security/scripts/workbench_target.py index 612ec0107..3b6ed3dbb 100644 --- a/plugins/codex-security/scripts/workbench_target.py +++ b/plugins/codex-security/scripts/workbench_target.py @@ -585,6 +585,56 @@ def _visible_git_character(char: str) -> str: return ascii(char)[1:-1] +def _canonical_patch_chunks(output: BinaryIO) -> Iterator[bytes]: + """Drop Git's optional function label while preserving hunk coordinates and content.""" + line_start = True + # Limit each read even when source lines are arbitrarily large. + for part in iter(lambda: output.readline(1024 * 1024), b""): + next_line_start = part.endswith(b"\n") + if line_start and part.startswith(b"@@ "): + coordinates, end, _ = part.partition(b" @@") + if end: + part = coordinates + end + b"\n" + yield part + line_start = next_line_start + + +@contextmanager +def _diff_driver_config( + target: Path, git_dir: Path | None, work_tree: Path | None +) -> Iterator[tuple[str, ...]]: + names = git_command( + target, + "config", + "--name-only", + "--null", + "--get-regexp", + r"^diff\..+\.binary$", + text=False, + git_dir=git_dir, + work_tree=work_tree, + environment_overrides={"LC_ALL": "C"}, + ) + if names.returncode == 1: # Git returns 1 when there are no matching keys. + yield () + return + if names.returncode: + raise SystemExit( + os.fsdecode(names.stderr) or "Could not inspect Git diff-driver configuration." + ) + # A private command-scope include preserves case and arbitrary driver-name bytes + # without putting an unbounded number of keys on the command line. + with tempfile.TemporaryDirectory(prefix="codex-security-diff-") as directory: + config = Path(directory) / "drivers" + with config.open("wb") as stream: + for key in names.stdout.split(b"\0"): + if key: + driver = key.removeprefix(b"diff.").removesuffix(b".binary") + escaped = driver.replace(b"\\", b"\\\\").replace(b'"', b'\\"') + stream.write(b'[diff "' + escaped + b'"]\n\tbinary = auto\n') + yield "-c", f"include.path={config}" + + def _update_digest_field_from_git( digest: Any, label: bytes, @@ -592,15 +642,24 @@ def _update_digest_field_from_git( *args: str, git_dir: Path | None = None, work_tree: Path | None = None, + environment_overrides: dict[str, str] | None = None, + stable_display: bool = False, ) -> None: - with tempfile.TemporaryFile() as output: + with tempfile.TemporaryFile() as output, ExitStack() as stack: + driver_config = ( + stack.enter_context(_diff_driver_config(target, git_dir, work_tree)) + if stable_display + else () + ) completed = git_command( target, + *driver_config, *args, text=False, git_dir=git_dir, work_tree=work_tree, stdout_file=output, + environment_overrides=environment_overrides, ) if completed.returncode != 0: detail = completed.stderr.decode("utf-8", errors="backslashreplace").replace( @@ -610,25 +669,36 @@ def _update_digest_field_from_git( raise SystemExit( f"Could not snapshot the selected working-tree changes.\n{detail}".rstrip("\n") ) - output.seek(0, os.SEEK_END) - value_size = output.tell() + if stable_display: + output.seek(0) + value_size = sum(len(part) for part in _canonical_patch_chunks(output)) + else: + value_size = output.seek(0, os.SEEK_END) _update_digest_field_header(digest, label, value_size) output.seek(0) - for chunk in iter(lambda: output.read(1024 * 1024), b""): + chunks = ( + _canonical_patch_chunks(output) + if stable_display + else iter(lambda: output.read(1024 * 1024), b"") + ) + for chunk in chunks: digest.update(chunk) -def worktree_content_digest(target: Path) -> str: +def worktree_content_digest(target: Path, *, expected_digest: str | None = None) -> str: """Return the worktree digest for the selected path after checking the state of its submodules.""" require_clean_submodule_worktrees(target) repository, pathspec = git_worktree_context(target) - return worktree_content_digest_for_context(repository, pathspec) + return worktree_content_digest_for_context( + repository, pathspec, expected_digest=expected_digest + ) def remediation_checkout_snapshot( scan: sqlite3.Row, *, expected_revision: str | None = None, + expected_digest: str | None = None, head_changed_message: str = ( "Repository HEAD changed. Regenerate the remediation patch against the current checkout." ), @@ -640,7 +710,7 @@ def remediation_checkout_snapshot( if revision != required_revision: raise SystemExit(head_changed_message) content_digest = ( - worktree_content_digest(target) + worktree_content_digest(target, expected_digest=expected_digest) if revision != "unversioned" else directory_content_digest(target, excluded=(Path(scan["scan_dir"]),)) ) @@ -661,12 +731,16 @@ def require_scan_target_unchanged(scan: sqlite3.Row) -> None: raise SystemExit(head_changed_message) require_clean_submodule_worktrees(target) return - _, current_digest = remediation_checkout_snapshot( - scan, head_changed_message=head_changed_message - ) if scan["diff_target_kind"] == "working_tree": expected_digest = scan["diff_content_digest"] elif scan["diff_target_kind"] in {"commit", "range"}: + expected_digest = clean_worktree_content_digest() + else: + expected_digest = scan["target_snapshot_digest"] + _, current_digest = remediation_checkout_snapshot( + scan, expected_digest=expected_digest, head_changed_message=head_changed_message + ) + if scan["diff_target_kind"] in {"commit", "range"}: target = Path(scan["target_path"]) tracked = git_bytes(target, "ls-files", "-v", "-z") if tracked is None: @@ -679,9 +753,6 @@ def require_scan_target_unchanged(scan: sqlite3.Row) -> None: ) if any(entry.startswith(b"h ") for entry in entries): verify_assumed_unchanged_files(target) - expected_digest = clean_worktree_content_digest() - else: - expected_digest = scan["target_snapshot_digest"] if current_digest != expected_digest: raise SystemExit( "Scan target contents changed since the scan. " @@ -728,6 +799,28 @@ def worktree_content_digest_for_context( *, git_dir: Path | None = None, work_tree: Path | None = None, + expected_digest: str | None = None, +) -> str: + def calculate(stable_display: bool) -> str: + return _git_content_digest(repository, pathspec, git_dir, work_tree, stable_display) + + current = calculate(True) + # Older sealed snapshots may have included the user's Git display settings. + if ( + expected_digest is not None + and current != expected_digest + and calculate(False) == expected_digest + ): + return expected_digest + return current + + +def _git_content_digest( + repository: Path, + pathspec: str, + git_dir: Path | None, + work_tree: Path | None, + stable_display: bool, ) -> str: digest = hashlib.sha256() update_digest_field(digest, b"format", b"codex-security-snapshot/v1") @@ -736,12 +829,44 @@ def worktree_content_digest_for_context( ":(top,glob,exclude)**/.svn", ":(top,glob,exclude)**/.svn/**", ] + config = ( + ( + "-c", + "core.quotePath=true", + "-c", + "diff.suppressBlankEmpty=false", + "-c", + "core.compression=1", # Git uses the fastest zlib level for binary patches by default. + ) + if stable_display + else () + ) + display = ( + ( + "--no-color", + "--src-prefix=a/", + "--dst-prefix=b/", + "--unified=3", + "--diff-algorithm=myers", + "--indent-heuristic", + "--inter-hunk-context=0", + "--find-renames=50%", + "-l1000", # Git's default inexact rename limit. + "--submodule=short", + "-O", + os.devnull, + ) + if stable_display + else () + ) _update_digest_field_from_git( digest, b"tracked-diff", repository, + *config, "--no-literal-pathspecs", "diff", + *display, "--binary", "--full-index", "--no-ext-diff", @@ -752,6 +877,9 @@ def worktree_content_digest_for_context( *source_pathspecs, git_dir=git_dir, work_tree=work_tree, + # GIT_DIFF_OPTS overrides even an explicit --unified option. + environment_overrides={"GIT_DIFF_OPTS": ""} if stable_display else None, + stable_display=stable_display, ) untracked = git_bytes( repository, @@ -1570,7 +1698,7 @@ def scan_target_warning(scan: sqlite3.Row) -> str | None: expected_digest = ( scan["diff_content_digest"] if working_tree else scan["target_snapshot_digest"] ) - if worktree_content_digest(target) != expected_digest: + if worktree_content_digest(target, expected_digest=expected_digest) != expected_digest: return ( "Working-tree contents changed while the scan was running; " "results were saved for the original snapshot." diff --git a/plugins/codex-security/tests/test_workbench_target.py b/plugins/codex-security/tests/test_workbench_target.py index 5f2b0494e..806d6445c 100644 --- a/plugins/codex-security/tests/test_workbench_target.py +++ b/plugins/codex-security/tests/test_workbench_target.py @@ -5,6 +5,7 @@ from __future__ import annotations import difflib import errno import hashlib +import io import os import runpy import shutil @@ -1570,6 +1571,184 @@ def test_directory_content_digest_skips_missing_cached_paths(tmp_path: Path) -> assert directory_content_digest(target) == original_digest +@pytest.mark.cross_platform +@pytest.mark.parametrize( + ("option", "value"), + [ + ("color.ui", "always"), + ("color.diff", "always"), + ("diff.noprefix", "true"), + ("diff.mnemonicPrefix", "true"), + ("diff.context", "0"), + ("diff.algorithm", "histogram"), + ("diff.indentHeuristic", "false"), + ("diff.interHunkContext", "20"), + ("diff.suppressBlankEmpty", "true"), + ("diff.orderFile", "order"), + ("diff.renames", "false"), + ("diff.renameLimit", "1"), + ("core.quotePath", "false"), + ("GIT_DIFF_OPTS", "--unified=0"), + ], +) +def test_git_diff_display_settings_preserve_selected_working_content( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + workbench_api: dict[str, Any], + option: str, + value: str, +) -> None: + target = tmp_path / "source" + initialize_git_repository(target) + path = target / "café.txt" + path.write_bytes(b"heading\none\nC\nB\nB\nthree\n") + lines = target / "z-lines.txt" + original_lines = ["start", "", *(f"line {n}" for n in range(20)), "end"] + lines.write_text("\n".join(original_lines) + "\n", encoding="utf-8") + indent = target / "indent.txt" + indent.write_bytes(b"\ndone()\ndef sample():\n") + moved = [("first.txt", "new-first.txt"), ("second.txt", "new-second.txt")] + for name, _ in moved: + (target / name).write_text( + "".join(f"{name} line {n}\n" for n in range(20)), encoding="utf-8" + ) + subprocess.run(["git", "add", "--", "."], cwd=target, check=True) + subprocess.run(["git", "commit", "-qm", "Track fixture"], cwd=target, check=True) + indent.write_bytes(b"\ndone()\ndone()\ndef sample():\n") + for name, destination in moved: + subprocess.run(["git", "mv", name, destination], cwd=target, check=True) + with (target / destination).open("ab") as stream: + stream.write(b"added line\n") + subprocess.run(["git", "add", "--", destination], cwd=target, check=True) + path.write_bytes(b"heading\none\nB\nC\nC\nthree\n") + original_lines[0] = "changed start" + original_lines[-1] = "changed end" + lines.write_text("\n".join(original_lines) + "\n", encoding="utf-8") + if option == "diff.orderFile": + order_file = tmp_path / "diff order" + order_file.write_text(lines.name + "\n", encoding="utf-8", newline="\n") + value = str(order_file) + selected = workbench_api["require_diff_target"](target, "working_tree", None, None, None) + if option == "GIT_DIFF_OPTS": + monkeypatch.setenv(option, value) + else: + subprocess.run(["git", "config", "--local", option, value], cwd=target, check=True) + + # Reproduce a stored digest generated by a previous version with this setting. + old_patch = subprocess.check_output( + ["git", "diff", "--binary", "--full-index", "--no-ext-diff", "--no-textconv", "HEAD"], + cwd=target, + ) + old_hash = hashlib.sha256() + update_digest_field(old_hash, b"format", b"codex-security-snapshot/v1") + update_digest_field(old_hash, b"tracked-diff", old_patch) + legacy = f"codex-security-snapshot/v1:sha256:{old_hash.hexdigest()}" + assert legacy != selected["contentDigest"] + + def validate(digest: str | None) -> str: + return workbench_api["require_diff_target"](target, "working_tree", None, None, digest)[ + "contentDigest" + ] + + assert validate(None) == selected["contentDigest"] + assert validate(selected["contentDigest"]) == selected["contentDigest"] + assert validate(legacy) == legacy + + path.write_bytes(b"new source content\n") + for digest in (selected["contentDigest"], legacy): + with pytest.raises(SystemExit, match="contents changed"): + validate(digest) + + +@pytest.mark.cross_platform +@pytest.mark.parametrize("display", ["log", "diff"]) +def test_git_submodule_display_preserves_selected_working_content( + tmp_path: Path, workbench_api: dict[str, Any], display: str +) -> None: + target = tmp_path / "parent" + initialize_git_repository(target) + child = target / "submodule" + initial = initialize_git_repository(child) + add_submodule_gitlink(target, initial, ".") + subprocess.run(["git", "commit", "-qm", "Pin child"], cwd=target, check=True) + + def advance_child(content: str) -> None: + (child / "README.md").write_text(content + "\n", encoding="utf-8") + subprocess.run(["git", "commit", "-qam", content], cwd=child, check=True) + subprocess.run(["git", "add", "--", "submodule"], cwd=target, check=True) + + advance_child("Selected child") + require_target = workbench_api["require_diff_target"] + selected = require_target(target, "working_tree", None, None, None)["contentDigest"] + diff = ["git", "diff", "HEAD", "--", "submodule"] + original = subprocess.check_output(diff, cwd=target) + subprocess.run(["git", "config", "--local", "diff.submodule", display], cwd=target, check=True) + configured = subprocess.check_output(diff, cwd=target) + assert configured != original + assert require_target(target, "working_tree", None, None, selected)["contentDigest"] == selected + + advance_child("Changed child") + with pytest.raises(SystemExit, match="contents changed"): + require_target(target, "working_tree", None, None, selected) + + +@pytest.mark.cross_platform +@pytest.mark.parametrize( + ("key", "value", "binary"), + [ + ("diff.python.xfuncname", "^class.*$", False), + ("diff.python.binary", "true", False), + ("diff.Mixed=driver.binary", "true", False), + ("diff.python.binary", "false", True), + ("core.compression", "0", True), + ], +) +def test_git_driver_settings_preserve_selected_working_content( + tmp_path: Path, workbench_api: dict[str, Any], key: str, value: str, binary: bool +) -> None: + target = tmp_path / "source" + initialize_git_repository(target) + driver = "Mixed=driver" if key == "diff.Mixed=driver.binary" else "python" + (target / ".gitattributes").write_bytes(f"*.py diff={driver}\n".encode()) + source = target / "example.py" + initial = ( + b"class Example:\n def sample(self):\n" + + b"".join(f" a = {n}\n".encode() for n in range(24)) + + (b"\0" + b"abcde" * 4096 if binary else b"") + ) + source.write_bytes(initial) + subprocess.run(["git", "add", "--", "."], cwd=target, check=True) + subprocess.run(["git", "commit", "-qm", "Track example"], cwd=target, check=True) + source.write_bytes(initial.replace(b"a = 15", b"a = 42")) + require_target = workbench_api["require_diff_target"] + selected = require_target(target, "working_tree", None, None, None)["contentDigest"] + args = ["git", "diff", "--binary", "--full-index", "HEAD"] + original = subprocess.check_output(args, cwd=target) + subprocess.run(["git", "config", "--local", key, value], cwd=target, check=True) + configured = subprocess.check_output(args, cwd=target) + assert configured != original + assert require_target(target, "working_tree", None, None, selected)["contentDigest"] == selected + assert require_target(target, "working_tree", None, None, None)["contentDigest"] == selected + legacy_hash = hashlib.sha256() + update_digest_field(legacy_hash, b"format", b"codex-security-snapshot/v1") + update_digest_field(legacy_hash, b"tracked-diff", configured) + legacy = f"codex-security-snapshot/v1:sha256:{legacy_hash.hexdigest()}" + assert require_target(target, "working_tree", None, None, legacy)["contentDigest"] == legacy + source.write_bytes(initial + b"actual change\n") + for digest in (selected, legacy): + with pytest.raises(SystemExit, match="contents changed"): + require_target(target, "working_tree", None, None, digest) + + +def test_snapshot_keeps_hunk_coordinates_and_long_source_lines() -> None: + header = b"@@ -12,4 +12,5 @@" + # The next read starts with a header-shaped string in the middle of an added line. + long_line = b"+" + b"x" * (1024 * 1024 - 1) + header + b" literal content\n" + patch = header + b" def sample():\n" + long_line + header + b"\n" + chunks = WORKBENCH_TARGET["_canonical_patch_chunks"](io.BytesIO(patch)) + assert b"".join(chunks) == header + b"\n" + long_line + header + b"\n" + + def test_worktree_content_digest_streams_tracked_binary_patch( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: From 4fac2dfdf3628e64b4d5d2caf68b0f3693ed1022 Mon Sep 17 00:00:00 2001 From: Michael D'Angelo Date: Tue, 10 Nov 2026 08:12:09 -0800 Subject: [PATCH 27/28] fix(plugin): preserve native filename bytes in SQLite URIs (#2571) * fix(plugin): preserve native filename bytes in SQLite URIs * test(sdk): include SQLite URI support in the usage fixture --- .../codex-security/scripts/snapshot_sqlite.py | 10 +++++-- .../scripts/workbench_publication.py | 5 ++-- .../scripts/workbench_scan_usage.py | 4 +-- .../tests/test_finding_issue_receipts.py | 13 +++++++++ .../tests/test_workbench_scan_usage.py | 27 +++++++++---------- .../test_workbench_setup_and_migrations.py | 19 +++++++++++-- .../workbench-compressed-usage.test.ts | 1 + 7 files changed, 56 insertions(+), 23 deletions(-) diff --git a/plugins/codex-security/scripts/snapshot_sqlite.py b/plugins/codex-security/scripts/snapshot_sqlite.py index 4d8f7a3dc..d3e5918e2 100644 --- a/plugins/codex-security/scripts/snapshot_sqlite.py +++ b/plugins/codex-security/scripts/snapshot_sqlite.py @@ -4,11 +4,18 @@ from __future__ import annotations import argparse +import os import sqlite3 from pathlib import Path from urllib.parse import quote +def readonly_sqlite_uri(path: Path) -> str: + """Escape the native filename, including separators, without introducing a URI authority.""" + filename = os.fsencode(path) if os.name == "posix" else str(path) + return f"file:{quote(filename, safe='')}?mode=ro" + + def main() -> None: """Back up the read-only source database into a separate destination using SQLite’s backup API.""" parser = argparse.ArgumentParser(description=__doc__) @@ -21,8 +28,7 @@ def main() -> None: if destination.exists() and destination.samefile(source): parser.error(f"Destination must not be the same file as source: {destination}") destination.parent.mkdir(parents=True, exist_ok=True) - source_uri = f"file:{quote(str(source), safe='')}?mode=ro" - with sqlite3.connect(source_uri, uri=True) as source_connection: + with sqlite3.connect(readonly_sqlite_uri(source), uri=True) as source_connection: creation_destination = destination.resolve() try: creation_destination.touch(mode=0o600, exist_ok=False) diff --git a/plugins/codex-security/scripts/workbench_publication.py b/plugins/codex-security/scripts/workbench_publication.py index 42b606ad1..0a1e1dc80 100644 --- a/plugins/codex-security/scripts/workbench_publication.py +++ b/plugins/codex-security/scripts/workbench_publication.py @@ -12,7 +12,6 @@ import sys from contextlib import closing from pathlib import Path from typing import Any -from urllib.parse import quote # Some plugin hosts launch Python with safe-path isolation enabled. sys.path.insert(0, str(Path(__file__).resolve().parent)) @@ -27,6 +26,7 @@ from finalize_scan_contract import ( write_export_output, write_sarif_projection, ) +from snapshot_sqlite import readonly_sqlite_uri from validate_scan_contract import validate_contract from workbench_constants import PRIMARY_FINDING_LOCATION_SQL @@ -226,9 +226,8 @@ def finding_issues(db: Any, payload: Any) -> dict[str, Any]: except PermissionError: pass # Let SQLite report the open failure used by the host's state fallback. if payload["action"] == "inspect": - database_uri = f"file:{quote(str(path), safe='')}?mode=ro" try: - connection = sqlite3.connect(database_uri, uri=True, timeout=5) + connection = sqlite3.connect(readonly_sqlite_uri(path), uri=True, timeout=5) except sqlite3.OperationalError as exc: if str(exc) == "unable to open database file": exc._codex_security_state_unavailable = True diff --git a/plugins/codex-security/scripts/workbench_scan_usage.py b/plugins/codex-security/scripts/workbench_scan_usage.py index f06df3788..0972ca691 100644 --- a/plugins/codex-security/scripts/workbench_scan_usage.py +++ b/plugins/codex-security/scripts/workbench_scan_usage.py @@ -17,9 +17,9 @@ from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path from typing import Any, Mapping -from urllib.parse import quote sys.path.insert(0, str(Path(__file__).resolve().parent)) +from snapshot_sqlite import readonly_sqlite_uri from workbench.storage import archive_source_directory, worker_usage_directory TOKEN_FIELDS = { @@ -654,7 +654,7 @@ def _discover_rollout_sessions( completed_at: datetime | None, ) -> tuple[list[RolloutSession], set[str]]: database = sqlite3.connect( - f"file:{quote(str(state_database), safe='')}?mode=ro", + readonly_sqlite_uri(state_database), uri=True, timeout=STATE_DATABASE_TIMEOUT_SECONDS, ) diff --git a/plugins/codex-security/tests/test_finding_issue_receipts.py b/plugins/codex-security/tests/test_finding_issue_receipts.py index 81244f719..12767158e 100644 --- a/plugins/codex-security/tests/test_finding_issue_receipts.py +++ b/plugins/codex-security/tests/test_finding_issue_receipts.py @@ -6,6 +6,7 @@ import json import os import shutil import sqlite3 +import sys import uuid from contextlib import closing from pathlib import Path @@ -127,6 +128,18 @@ def test_inaccessible_state_preserves_sqlite_open_error(tmp_path: Path, action: state.chmod(0o700) +@pytest.mark.skipif(sys.platform != "linux", reason="requires Linux filename bytes") +def test_inspects_recorded_receipt_in_state_path_with_non_utf8_bytes(tmp_path: Path) -> None: + state = tmp_path / os.fsdecode(b"state-\xff?#%") + scan_dir, validated = source(tmp_path) + receipt = receipt_for(validated) + issues(state, scan_dir, "record", receipts=[receipt]) + assert ( + issues(state, scan_dir, "inspect")["receipts"][0]["issueIdentifier"] + == receipt["issueIdentifier"] + ) + + @pytest.mark.parametrize("project", [None, "project-example"]) def test_legacy_receipts_are_read_without_migration_and_preserved_on_upgrade( tmp_path: Path, project: str | None diff --git a/plugins/codex-security/tests/test_workbench_scan_usage.py b/plugins/codex-security/tests/test_workbench_scan_usage.py index bf85a47d8..c4fae3a14 100644 --- a/plugins/codex-security/tests/test_workbench_scan_usage.py +++ b/plugins/codex-security/tests/test_workbench_scan_usage.py @@ -4,6 +4,7 @@ from __future__ import annotations import hashlib import json +import os import sqlite3 import subprocess import sys @@ -1310,27 +1311,25 @@ def test_usage_finds_state_database_in_configured_home( @pytest.mark.cross_platform @pytest.mark.parametrize( - "spelling", - ["leading-relative", "trailing-absolute"] - + ([] if sys.platform == "win32" else ["literal-tilde"]), + ("spelling", "filename"), + [ + ("leading-relative", " usage.sqlite"), + ( + "trailing-absolute", + "usage.sqlite\N{NO-BREAK SPACE}" if sys.platform == "win32" else "usage.sqlite ", + ), + ] + + ([] if sys.platform == "win32" else [("literal-tilde", "~synthetic-usage.sqlite")]) + + ([("filesystem-bytes", b"usage-\xff?#%.sqlite")] if sys.platform == "linux" else []), ) def test_completion_reads_the_literal_usage_database( - tmp_path: Path, spelling: str, monkeypatch: pytest.MonkeyPatch + tmp_path: Path, spelling: str, filename: str | bytes, monkeypatch: pytest.MonkeyPatch ) -> None: fixture = _start_scan(tmp_path) counted = fixture.started_at + timedelta(microseconds=1) fixture.write_parent_rollout([_token_event(counted, 18, 2)]) original = Path(fixture.environment["CODEX_SQLITE_HOME"]) / "state_5.sqlite" - selected = ( - tmp_path - / { - "leading-relative": " usage.sqlite", - "trailing-absolute": "usage.sqlite\N{NO-BREAK SPACE}" - if sys.platform == "win32" - else "usage.sqlite ", - "literal-tilde": "~synthetic-usage.sqlite", - }[spelling] - ) + selected = tmp_path / os.fsdecode(filename) original.rename(selected) neighbor = tmp_path / "neighbor" diff --git a/plugins/codex-security/tests/test_workbench_setup_and_migrations.py b/plugins/codex-security/tests/test_workbench_setup_and_migrations.py index f78172ad5..2cdc36c9b 100644 --- a/plugins/codex-security/tests/test_workbench_setup_and_migrations.py +++ b/plugins/codex-security/tests/test_workbench_setup_and_migrations.py @@ -361,8 +361,23 @@ def assert_new_scan_model_is_independent(state_dir: Path, target: Path, scan_roo ).fetchone() == (None, None, "gpt-5.6-sol", "high") -def test_sqlite_snapshot_includes_uncheckpointed_wal_rows(tmp_path: Path) -> None: - source = tmp_path / "source.sqlite3" +@pytest.mark.parametrize( + "source_name", + [ + b"source.sqlite3", + pytest.param( + b"source-\xff?#%.sqlite3", + marks=pytest.mark.skipif( + sys.platform != "linux", reason="requires Linux filename bytes" + ), + id="linux-filename-bytes", + ), + ], +) +def test_sqlite_snapshot_includes_uncheckpointed_wal_rows( + tmp_path: Path, source_name: bytes +) -> None: + source = tmp_path / os.fsdecode(source_name) snapshot = tmp_path / "snapshot.sqlite3" with sqlite3.connect(source) as connection: connection.execute("PRAGMA journal_mode = WAL") diff --git a/sdk/typescript/tests-ts/workbench-compressed-usage.test.ts b/sdk/typescript/tests-ts/workbench-compressed-usage.test.ts index db2df5903..7e383c171 100644 --- a/sdk/typescript/tests-ts/workbench-compressed-usage.test.ts +++ b/sdk/typescript/tests-ts/workbench-compressed-usage.test.ts @@ -42,6 +42,7 @@ async function fixture() { const plugin = join(root, "plugin"); const paths = [ "scripts/workbench_scan_usage.py", + "scripts/snapshot_sqlite.py", "scripts/windows_scan_local_files.py", "scripts/read_codex_session.mjs", "scripts/workbench/__init__.py", From cf2aafaa92d14f7f06bc8b883bff87e049df09a9 Mon Sep 17 00:00:00 2001 From: Michael D'Angelo Date: Tue, 10 Nov 2026 08:30:13 -0800 Subject: [PATCH 28/28] fix(sdk): inventory policies in list-only POSIX directories (#2572) --- sdk/typescript/src/security-policy.ts | 20 ++++++++++++- .../tests-ts/security-policy.test.ts | 30 +++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/sdk/typescript/src/security-policy.ts b/sdk/typescript/src/security-policy.ts index 6efd3445a..824221571 100644 --- a/sdk/typescript/src/security-policy.ts +++ b/sdk/typescript/src/security-policy.ts @@ -482,7 +482,25 @@ async function securityPolicyPaths( const directory = directories.pop()!; if (isGitData(directory)) continue; const entries = await readdir(directory, { withFileTypes: true }); - if (await isGitMetadataDirectory(directory, signal)) { + let gitMetadata: boolean; + try { + gitMetadata = await isGitMetadataDirectory(directory, signal); + } catch (error) { + // POSIX can permit listing a directory but deny lookups of its children. + // A leaf containing only unrelated regular files needs no further lookups. + if ( + process.platform !== "win32" && + (error as NodeJS.ErrnoException).code === "EACCES" && + entries.every( + (entry) => + entry.isFile() && + !/^(?:\.git|HEAD|SECURITY\.md)$/iu.test(entry.name), + ) + ) + continue; + throw error; + } + if (gitMetadata) { gitDirectories.add(directory); const common = await readFile(join(directory, "commondir"), "utf8").catch( nullIfMissingFile, diff --git a/sdk/typescript/tests-ts/security-policy.test.ts b/sdk/typescript/tests-ts/security-policy.test.ts index bc50095e1..2af6bd6fa 100644 --- a/sdk/typescript/tests-ts/security-policy.test.ts +++ b/sdk/typescript/tests-ts/security-policy.test.ts @@ -1,6 +1,7 @@ import { nodeCommand, gitText } from "./support/shell.js"; import { execFileSync } from "node:child_process"; import { + chmod, cp, mkdir, readFile, @@ -398,6 +399,35 @@ describe("security policy generation", () => { expect(inventory.gitMetadataPaths).toEqual([]); }); + test.skipIf(process.platform === "win32" || process.getuid?.() === 0)( + "inventories policies when an unrelated leaf directory only permits listing", + async () => { + const f = await fixture(); + policyGit(f.repository, "init", "--quiet"); + const leaf = join(f.repository, "data"); + await mkdir(leaf); + await writeFile(join(leaf, "sample.txt"), "fixture\n"); + await writeFile(join(f.repository, "SECURITY.md"), POLICY); + const target = await resolveSecurityPolicyTarget(f.repository); + try { + await chmod(leaf, 0o400); + expect( + (await inspectSecurityPolicySources(target)).policyPaths, + ).toEqual(["SECURITY.md"]); + await chmod(leaf, 0o700); + await writeFile(join(leaf, "SECURITY.md"), POLICY); + await chmod(leaf, 0o400); + await expect( + inspectSecurityPolicySources(target), + ).rejects.toMatchObject({ + code: "EACCES", + }); + } finally { + await chmod(leaf, 0o700); + } + }, + ); + test("leaves Git-ignored dependencies out of the policy inventory", async () => { const f = await fixture(); policyGit(f.repository, "init", "--quiet");