OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
fix(windows): stage validated plugin ZIPs for scan workers (#2507)
Michael D'Angelo429ae351c58d
diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex 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.tsindex 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<string> {+ return extractValidatedPluginZip(archive, destination, signal);+}++async function extractValidatedPluginZip(+ archive: string,+ destination: string,+ signal?: AbortSignal,+ digest?: Hash,): Promise<string> {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<string> {+ 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<string>) =>+ 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.tsindex 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<void>) | 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<void>();+ const held = Promise.withResolvers<string>();+ 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<void>((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<number, string>();+ const zipInputs = new Set<string>();+ 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.tsindex 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.tsindex 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 preserveconst 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 preserveoptions.configOverrides!.join("\n"),) as {permissions: {- codex_security_scan: { filesystem: Record<string, unknown> };+ codex_security_scan: {+ filesystem: Record<string, unknown>;+ };};};const filesystem =@@ -558,7 +596,13 @@ test("CLI resumes through native execution with current permissions and preserveexpect(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 preservereturn {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 preserveexpect(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)",