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): keep credential state reusable across scans (#635)
faizan-oai5210198992c4
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex 776fdb2c6..7be01610d 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -771,11 +771,19 @@ or excludes their original scope. With one ID, `scans compare` compares itto the latest completed scan.History lives in `$CODEX_SECURITY_STATE_DIR/workbench.sqlite3`, or-`$CODEX_HOME/state/plugins/codex-security/workbench.sqlite3`. Keep this directory-writable and outside the scanned repository. Scan configurations don't store-credentials; session logs and live details can contain them. Press `d` during-a scan for details, then `a` for all sources, `m` for the main scan, or-`1` through `9` for a worker.+`$CODEX_HOME/state/plugins/codex-security/workbench.sqlite3`. The CLI and+workbench maintain the database and its journal files as the current user.+Keep state private, writable, and outside the scanned repository.++On Windows, an older sandboxed run can leave an invalid credential-home ancestor+ACL. Preserve that state and its reports, and select a **new**, private+`CODEX_SECURITY_STATE_DIR` outside both the old state and the repository.+Sign in again if needed and keep using the new setting; it starts separate scan+history. Existing ancestor ACLs are not rewritten.++Scan configurations don't store credentials; session logs and live details can+contain them. Press `d` during a scan for details, then `a` for all sources,+`m` for the main scan, or `1` through `9` for a worker.### Exports and CI@@ -934,8 +942,8 @@ repositories you trust and are authorized to assess. Local tools and scansunder the same account aren't separate security principals.The `codex_security_scan` profile allows reads across the local filesystem and-writes to workspace roots and the scan state directory. Execution approvals-are reviewed automatically and may grant extra permissions for one operation. Set+writes to workspace roots. Execution approvals are reviewed automatically and+may grant extra permissions for one operation. Set`--codex 'approval_policy="never"'`, directly or in a selected profile, to denyrequests. Other overrides can't replace the reviewer or filesystem profile.Saved scans keep their approval policy; older scans stay deny-all on rerun.diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex 4e23946d2..426452c9b 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -681,7 +681,7 @@ export class CodexSecurity {checkOpen();const session = await this.#prepareSession(- { protectedRoot, stateDirectory },+ { protectedRoot },options,signal,temporaryRoot,@@ -1877,10 +1877,7 @@ export class CodexSecurity {}async #prepareSession(- {- protectedRoot,- stateDirectory,- }: { protectedRoot: string; stateDirectory: string },+ { protectedRoot }: { protectedRoot: string },options: Pick<ScanOptions,| "auth"@@ -1965,7 +1962,6 @@ export class CodexSecurity {requireOutputOutsideRepository(protectedRoot, runtimeHome, "runtime");const sessionConfig = scanRuntimeCodexConfig(effectiveConfig,- stateDirectory,runtimeHome,);if (@@ -2141,11 +2137,7 @@ export class CodexSecurity {throwIfAborted(signal);const config = await preserveCodexSecurityPluginRegistration(runtime.codexHome,- sharedCredentialCodexConfig(- mergedConfig,- codexSecurityStateDirectory(environment),- runtime.codexHome,- ),+ sharedCredentialCodexConfig(mergedConfig, runtime.codexHome),);await writeCodexConfig(join(runtime.codexHome, "config.toml"), config);runtime.plugin = await bootstrapPlugin(@@ -2299,11 +2291,7 @@ export class CodexSecurity {requestedConfig ?? (await mergedCodexConfig(this.config));const codexConfig = await preserveCodexSecurityPluginRegistration(codexHome,- sharedCredentialCodexConfig(- mergedConfig,- codexSecurityStateDirectory(processEnvironment),- codexHome,- ),+ sharedCredentialCodexConfig(mergedConfig, codexHome),);await writeCodexConfig(join(codexHome, "config.toml"), codexConfig);const configPath = join(bootstrapWorkspace, "config-preflight.toml");@@ -3321,7 +3309,6 @@ export function classifyConnectionFailure(export function scanRuntimeCodexConfig(config: JsonObject,- stateDirectory: string,protectedCredentialHome?: string,): JsonObject {const approvalPolicy = scanApprovalPolicy(config);@@ -3354,7 +3341,6 @@ export function scanRuntimeCodexConfig(filesystem: {":root": "read",":workspace_roots": "write",- [stateDirectory]: "write",...(protectedCredentialHome === undefined? {}: { [protectedCredentialHome]: "read" }),@@ -3366,7 +3352,6 @@ export function scanRuntimeCodexConfig(function sharedCredentialCodexConfig(config: JsonObject,- stateDirectory: string,credentialHome: string,): JsonObject {const shared: JsonObject = {@@ -3390,7 +3375,7 @@ function sharedCredentialCodexConfig(};}}- return scanRuntimeCodexConfig(shared, stateDirectory, credentialHome);+ return scanRuntimeCodexConfig(shared, credentialHome);}export function scanPreflightCodexConfig(config: JsonObject): JsonObject {diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.tsindex 37858dee5..17cc88dc7 100644--- a/sdk/typescript/src/runtime.ts+++ b/sdk/typescript/src/runtime.ts@@ -17,7 +17,6 @@ import {mkdir,mkdtemp,open,- opendir,readFile,readdir,realpath,@@ -82,6 +81,7 @@ const CREDENTIAL_LOCK_POLL_MILLISECONDS = 25;const INCOMPLETE_CREDENTIAL_LOCK_MILLISECONDS = 30_000;const MAX_PROCESS_ID = 2_147_483_647;const MAX_WINDOWS_CREDENTIAL_ACL_STDERR = 64 * 1024;+const WINDOWS_CREDENTIAL_ACL_COMPLETE_PREFIX = "CODEX_SECURITY_ACL_COMPLETE:";const WINDOWS_CREDENTIAL_DESCENDANTS_CHANGED_EXIT_CODE = 2;export interface PluginInstall {@@ -618,54 +618,6 @@ function windowsAceAllowsAncestorReplacement(return false;}-export async function verifyStableWindowsCredentialDescendants(- path: string,- inspectDescriptors: () => Promise<number>,- options: { inspectEmpty?: boolean } = {},-): Promise<void> {- for (let attempt = 0; attempt < 3; attempt += 1) {- let descendants = 0;- const pending = [path];- try {- while (pending.length !== 0) {- const current = pending.pop()!;- const directory = await opendir(current);- for await (const entry of directory) {- const child = join(current, entry.name);- const metadata = await lstat(child);- if (metadata.isSymbolicLink()) {- throw new Error(- "Windows credential home contains a symbolic link or junction",- );- }- if (!metadata.isDirectory() && !metadata.isFile()) {- throw new Error("Windows credential home contains an unsafe entry");- }- descendants += 1;- if (metadata.isDirectory()) pending.push(child);- }- }- } catch (error) {- const failure = error as NodeJS.ErrnoException;- if (failure.code === "ENOENT" && failure.path !== path) {- continue;- }- throw error;- }- if (descendants === 0 && options.inspectEmpty !== true) return;-- try {- if ((await inspectDescriptors()) === descendants) return;- } catch (error) {- if (!(error instanceof WindowsCredentialDescendantsChangedError)) {- throw error;- }- }- }-- throw new Error("Windows credential descendants could not be verified");-}-export async function streamWindowsCredentialAclDescriptors(command: string,args: readonly string[],@@ -757,18 +709,33 @@ export async function inspectWindowsCredentialAclSnapshot(if (ancestor === dirname(ancestor)) break;}- let home: WindowsCredentialAcl | undefined;- let descendantsArePrivate = true;- await verifyStableWindowsCredentialDescendants(- path,- async () => {- home = undefined;- descendantsArePrivate = true;- let inspected = 0;- const descriptors = await streamWindowsCredentialAclDescriptors(+ for (let attempt = 0; attempt < 3; attempt += 1) {+ let home: WindowsCredentialAcl | undefined;+ let descendantsArePrivate = true;+ let inspected = 0;+ let completed = false;+ try {+ await streamWindowsCredentialAclDescriptors(options.command,options.args,async (descriptor) => {+ if (completed) {+ throw new Error(+ "Windows credential ACL inspection continued after completion",+ );+ }+ if (descriptor.startsWith(WINDOWS_CREDENTIAL_ACL_COMPLETE_PREFIX)) {+ if (+ descriptor !==+ `${WINDOWS_CREDENTIAL_ACL_COMPLETE_PREFIX}${inspected}`+ ) {+ throw new Error(+ "Windows credential descendants could not be verified",+ );+ }+ completed = true;+ return;+ }const index = inspected;inspected += 1;await options.resolveDescriptorAliases?.(descriptor);@@ -821,20 +788,22 @@ export async function inspectWindowsCredentialAclSnapshot(},{ environment: options.environment },);- if (descriptors <= ancestors) {- throw new Error(- "Windows credential-home ancestry could not be verified",- );- }- return descriptors - ancestors - 1;- },- { inspectEmpty: true },- );-- if (home === undefined) {- throw new Error("Windows credential ACL could not be verified");+ } catch (error) {+ if (error instanceof WindowsCredentialDescendantsChangedError) continue;+ throw error;+ }+ if (inspected <= ancestors) {+ throw new Error("Windows credential-home ancestry could not be verified");+ }+ if (!completed) {+ throw new Error("Windows credential descendants could not be verified");+ }+ if (home === undefined) {+ throw new Error("Windows credential ACL could not be verified");+ }+ return { home, descendantsArePrivate };}- return { home, descendantsArePrivate };+ throw new Error("Windows credential descendants could not be verified");}async function secureWindowsCredentialHome(path: string): Promise<void> {@@ -880,15 +849,33 @@ async function secureWindowsCredentialHome(path: string): Promise<void> {// Signed built-in cmdlets remain available under ConstrainedLanguage;// arbitrary .NET constructors, static methods, and SID translation do not.+ // Enumerate and count ACLs in the same process: parallel startup can create+ // or remove private cache and lock files while this traversal is running.const script = ["$ErrorActionPreference = 'Stop'",+ "$script:descriptorCount = 0",+ "function Write-CredentialAcl($path) { $descriptor = Microsoft.PowerShell.Security\\Get-Acl -LiteralPath $path | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty Sddl; if (-not $descriptor) { throw 'Windows credential ACL could not be verified' }; $script:descriptorCount += 1; $descriptor }",+ "function Read-CredentialDescendants($path) {",+ " try { $entries = @(Microsoft.PowerShell.Management\\Get-ChildItem -LiteralPath $path -Force) } catch {",+ // A child can disappear while an existing directory is being enumerated.+ // Retry that incomplete listing before accepting a vanished descendant.+ ` if ($_.FullyQualifiedErrorId -eq 'System.IO.FileNotFoundException,Microsoft.PowerShell.Commands.GetChildItemCommand') { exit ${WINDOWS_CREDENTIAL_DESCENDANTS_CHANGED_EXIT_CODE} }`,+ " if ($path -ne $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH -and $_.CategoryInfo.Category -eq 'ObjectNotFound') { return }",+ " throw",+ " }",+ " foreach ($entry in $entries) {",+ " if (($entry.Attributes -band 1024) -and ($entry.LinkType -in @('SymbolicLink', 'Junction'))) { throw 'Windows credential home contains a symbolic link or junction' }",+ " if ($entry.PSObject.TypeNames -notcontains 'System.IO.DirectoryInfo' -and $entry.PSObject.TypeNames -notcontains 'System.IO.FileInfo') { throw 'Windows credential home contains an unsafe entry' }",+ " try { Write-CredentialAcl $entry.FullName } catch { if ($_.FullyQualifiedErrorId -like 'GetAcl_PathNotFound,*') { continue }; throw }",+ " if ($entry.PSIsContainer) { Read-CredentialDescendants $entry.FullName }",+ " }",+ "}","$path = $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH",- "while ($true) { $parent = Microsoft.PowerShell.Management\\Split-Path -Path $path -Parent; if (-not $parent -or $parent -eq $path) { break }; Microsoft.PowerShell.Security\\Get-Acl -LiteralPath $parent | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty Sddl; $path = $parent }",- "Microsoft.PowerShell.Security\\Get-Acl -LiteralPath $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty Sddl",- // Temporary descendants can disappear during enumeration or ACL reads.- // Retry interrupted enumeration as well as incomplete descriptor counts.- `try { Microsoft.PowerShell.Management\\Get-ChildItem -LiteralPath $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH -Recurse -Force | Microsoft.PowerShell.Core\\ForEach-Object { try { Microsoft.PowerShell.Security\\Get-Acl -LiteralPath $_.FullName | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty Sddl } catch { if ($_.FullyQualifiedErrorId -notlike 'GetAcl_PathNotFound,*') { throw } } } } catch { if ($_.FullyQualifiedErrorId -eq 'System.IO.FileNotFoundException,Microsoft.PowerShell.Commands.GetChildItemCommand') { exit ${WINDOWS_CREDENTIAL_DESCENDANTS_CHANGED_EXIT_CODE} }; throw }`,- ].join("; ");+ "while ($true) { $parent = Microsoft.PowerShell.Management\\Split-Path -Path $path -Parent; if (-not $parent -or $parent -eq $path) { break }; Write-CredentialAcl $parent; $path = $parent }",+ "Write-CredentialAcl $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH",+ "Read-CredentialDescendants $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH",+ `"${WINDOWS_CREDENTIAL_ACL_COMPLETE_PREFIX}$script:descriptorCount"`,+ ].join("\n");const resolvePrincipalScript = ["$ErrorActionPreference = 'Stop'","$descriptor = 'O:' + $env:CODEX_SECURITY_CREDENTIAL_PRINCIPAL + 'G:SYD:(A;;GA;;;SY)'",diff --git a/sdk/typescript/tests-ts/api-credentials.test.ts b/sdk/typescript/tests-ts/api-credentials.test.tsindex e8935a636..148b69656 100644--- a/sdk/typescript/tests-ts/api-credentials.test.ts+++ b/sdk/typescript/tests-ts/api-credentials.test.ts@@ -90,8 +90,6 @@ describe("CodexSecurity orchestration", () => {filesystem: {":root": "read",":workspace_roots": "write",- [join(ambientHome, "state", "plugins", "codex-security")]:- "write",[join(ambientHome,"state",diff --git a/sdk/typescript/tests-ts/api-preflight-config.test.ts b/sdk/typescript/tests-ts/api-preflight-config.test.tsindex 07c741a38..13d6c1af1 100644--- a/sdk/typescript/tests-ts/api-preflight-config.test.ts+++ b/sdk/typescript/tests-ts/api-preflight-config.test.ts@@ -357,8 +357,7 @@ describe("CodexSecurity preflight configuration", () => {);});- test("uses a root-read filesystem profile with writable workspace and workbench state", () => {- const stateDirectory = join(tmpdir(), "codex-security-persistent-state");+ test("uses a root-read filesystem profile with only writable workspaces", () => {const original = {approval_policy: "on-request",approvals_reviewer: "user",@@ -374,7 +373,7 @@ describe("CodexSecurity preflight configuration", () => {},};- expect(scanRuntimeCodexConfig(original, stateDirectory)).toEqual({+ expect(scanRuntimeCodexConfig(original)).toEqual({approval_policy: "on-request",approvals_reviewer: "auto_review",allow_login_shell: false,@@ -385,7 +384,6 @@ describe("CodexSecurity preflight configuration", () => {filesystem: {":root": "read",":workspace_roots": "write",- [stateDirectory]: "write",},},},@@ -399,33 +397,28 @@ describe("CodexSecurity preflight configuration", () => {});});- test("keeps persistent credentials read-only within writable scan state", () => {+ test("keeps persistent credentials and their ancestry read-only", () => {const stateDirectory = join(tmpdir(), "codex-security-persistent-state");const credentialHome = join(stateDirectory, "codex-home");- const config = scanRuntimeCodexConfig({}, stateDirectory, credentialHome);-- expect(config).toMatchObject({- permissions: {- codex_security_scan: {- filesystem: {- ":root": "read",- ":workspace_roots": "write",- [stateDirectory]: "write",- [credentialHome]: "read",- },+ const config = scanRuntimeCodexConfig({}, credentialHome);++ expect(config["permissions"]).toEqual({+ codex_security_scan: {+ filesystem: {+ ":root": "read",+ ":workspace_roots": "write",+ [credentialHome]: "read",},},});});test("preserves an explicitly requested strict approval policy", () => {- const stateDirectory = join(tmpdir(), "codex-security-persistent-state");-expect(- scanRuntimeCodexConfig(- { approval_policy: "never", approvals_reviewer: "user" },- stateDirectory,- ),+ scanRuntimeCodexConfig({+ approval_policy: "never",+ approvals_reviewer: "user",+ }),).toMatchObject({approval_policy: "never",approvals_reviewer: "auto_review",@@ -434,7 +427,6 @@ describe("CodexSecurity preflight configuration", () => {});test("preserves a strict approval policy from the selected profile", () => {- const stateDirectory = join(tmpdir(), "codex-security-persistent-state");const config = {approval_policy: "on-request",profile: "strict",@@ -444,7 +436,7 @@ describe("CodexSecurity preflight configuration", () => {},};- expect(scanRuntimeCodexConfig(config, stateDirectory)).toMatchObject({+ expect(scanRuntimeCodexConfig(config)).toMatchObject({approval_policy: "never",approvals_reviewer: "auto_review",profiles: { strict: { model: "profile-model" }, other: {} },@@ -453,7 +445,6 @@ describe("CodexSecurity preflight configuration", () => {});test("removes execution and permission overrides from every configured profile", () => {- const stateDirectory = join(tmpdir(), "codex-security-persistent-state");const original = {profile: "selected",profiles: {@@ -476,7 +467,7 @@ describe("CodexSecurity preflight configuration", () => {},};- const hardened = scanRuntimeCodexConfig(original, stateDirectory);+ const hardened = scanRuntimeCodexConfig(original);expect(hardened).toMatchObject({approval_policy: "on-request",approvals_reviewer: "auto_review",@@ -505,7 +496,6 @@ describe("CodexSecurity preflight configuration", () => {request_trace: "preserve-configured-metadata",},},- stateDirectory,credentialHome,);diff --git a/sdk/typescript/tests-ts/config.test.ts b/sdk/typescript/tests-ts/config.test.tsindex 6cc2c4765..e0c3f9d08 100644--- a/sdk/typescript/tests-ts/config.test.ts+++ b/sdk/typescript/tests-ts/config.test.ts@@ -1,6 +1,13 @@-import { mkdir, mkdtemp, readFile, rm, stat } from "node:fs/promises";+import {+ mkdir,+ mkdtemp,+ readFile,+ rm,+ stat,+ writeFile,+} from "node:fs/promises";import { tmpdir } from "node:os";-import { join } from "node:path";+import { join, resolve } from "node:path";import { afterEach, describe, expect, test } from "bun:test";import { parse } from "smol-toml";import { scanRuntimeCodexConfig } from "../src/api.js";@@ -12,6 +19,11 @@ import {mergedCodexConfig,writeCodexConfig,} from "../src/index.js";+import {+ prepareCodexSecurityCredentialHome,+ requireSecureCredentialHome,+} from "../src/runtime.js";+import { PLUGIN_ROOT } from "./plugin-root.js";const temporaryDirectories: string[] = [];@@ -29,13 +41,18 @@ async function temporaryDirectory(): Promise<string> {return path;}-function runPinnedCodex(codexHome: string, arguments_: readonly string[]) {+function runPinnedCodex(+ codexHome: string,+ arguments_: readonly string[],+ overrides: NodeJS.ProcessEnv = {},+) {const node = Bun.which("node");if (node === null) {throw new Error("The pinned Codex CLI requires Node.js.");}const environment: NodeJS.ProcessEnv = {...process.env,+ ...overrides,CODEX_HOME: codexHome,};delete environment["OPENAI_API_KEY"];@@ -84,21 +101,27 @@ function macOsSandboxUnavailable(): boolean {async function scanSandboxFixture() {const root = await temporaryDirectory();- const codexHome = join(root, "codex-home");- const workspace = join(root, "workspace");const stateDirectory = join(root, "state");+ const codexHome = await prepareCodexSecurityCredentialHome({+ CODEX_SECURITY_STATE_DIR: stateDirectory,+ });+ const workspace = join(stateDirectory, "scans", "workspace");+ const temporary = join(root, "temp");await Promise.all(- [codexHome, workspace, stateDirectory].map((path) => mkdir(path)),+ [workspace, temporary].map((path) => mkdir(path, { recursive: true })),);await writeCodexConfig(join(codexHome, "config.toml"),- scanRuntimeCodexConfig(- await mergedCodexConfig({}),- stateDirectory,- codexHome,- ),+ scanRuntimeCodexConfig(await mergedCodexConfig({}), codexHome),);- return { root, codexHome, workspace };+ return {+ root,+ codexHome,+ stateDirectory,+ workspace,+ // Native sandbox temp grants must not cover the credential-home ancestry.+ environment: { TEMP: temporary, TMP: temporary, TMPDIR: temporary },+ };}describe("Codex configuration", () => {@@ -354,10 +377,9 @@ describe("Codex configuration", () => {});test("retains the Windows sandbox in the hardened scan profile", async () => {- const stateDirectory = join(tmpdir(), "codex-security-windows-state");const merged = await mergedCodexConfig({});- expect(scanRuntimeCodexConfig(merged, stateDirectory)).toMatchObject({+ expect(scanRuntimeCodexConfig(merged)).toMatchObject({windows: { sandbox: "unelevated" },default_permissions: "codex_security_scan",permissions: {@@ -365,7 +387,6 @@ describe("Codex configuration", () => {filesystem: {":root": "read",":workspace_roots": "write",- [stateDirectory]: "write",},},},@@ -373,43 +394,50 @@ describe("Codex configuration", () => {});test("writes scan permissions accepted by the pinned Codex CLI", async () => {- const { codexHome, workspace } = await scanSandboxFixture();- const result = runPinnedCodex(codexHome, [- "--cd",- workspace,- "features",- "list",- ]);+ const { codexHome, workspace, environment } = await scanSandboxFixture();+ const result = runPinnedCodex(+ codexHome,+ ["--cd", workspace, "features", "list"],+ environment,+ );expect(result.exitCode, new TextDecoder().decode(result.stderr)).toBe(0);expect(result.stdout.length).toBeGreaterThan(0);});test.skipIf(macOsSandboxUnavailable())(- "denies writes outside the scan workspace and state directory",+ "allows scan helpers to write workspace files without writable credential ancestry",async () => {- const { root, codexHome, workspace } = await scanSandboxFixture();+ const { root, codexHome, stateDirectory, workspace, environment } =+ await scanSandboxFixture();const node = Bun.which("node");expect(node).not.toBeNull();const attemptWrite = (path: string) =>- runPinnedCodex(codexHome, [- "sandbox",- "--config",- "permissions.codex_security_scan.network.enabled=true",- "--permission-profile",- "codex_security_scan",- "--cd",- workspace,- node!,- "-e",- "require('node:fs').writeFileSync(process.argv[1], 'probe')",- path,- ]);+ runPinnedCodex(+ codexHome,+ [+ "sandbox",+ "--config",+ "permissions.codex_security_scan.network.enabled=true",+ "--permission-profile",+ "codex_security_scan",+ "--cd",+ workspace,+ node!,+ "-e",+ "require('node:fs').writeFileSync(process.argv[1], 'probe')",+ path,+ ],+ environment,+ );const allowed = join(workspace, "inside.txt");const permitted = attemptWrite(allowed);const outside = join(root, "outside.txt");expect(attemptWrite(outside).exitCode).not.toBe(0);await expect(stat(outside)).rejects.toMatchObject({ code: "ENOENT" });+ const stateFile = join(stateDirectory, "outside.txt");+ expect(attemptWrite(stateFile).exitCode).not.toBe(0);+ await expect(stat(stateFile)).rejects.toMatchObject({ code: "ENOENT" });if (permitted.exitCode !== 0) {const details = new TextDecoder().decode(permitted.stderr);if (@@ -428,6 +456,47 @@ describe("Codex configuration", () => {);}expect(await readFile(allowed, "utf8")).toBe("probe");++ const repository = join(root, "repository");+ await mkdir(repository);+ await writeFile(join(repository, "fixture.txt"), "synthetic source\n");+ const inventory = join(workspace, "in-scope-files.txt");+ const python =+ Bun.which("python3") ?? Bun.which("python") ?? Bun.which("py");+ expect(python).not.toBeNull();+ const helper = runPinnedCodex(+ codexHome,+ [+ "sandbox",+ "--config",+ "permissions.codex_security_scan.network.enabled=true",+ "--permission-profile",+ "codex_security_scan",+ "--cd",+ workspace,+ python!,+ join(PLUGIN_ROOT, "scripts", "generate_in_scope_files.py"),+ "--repo",+ repository,+ "--scope",+ ".",+ "--out",+ inventory,+ ],+ environment,+ );+ expect(helper.exitCode, new TextDecoder().decode(helper.stderr)).toBe(0);+ const inventoryPaths = (await readFile(inventory, "utf8"))+ .trim()+ .split(/\r?\n/u)+ .map((path) => resolve(repository, path));+ expect(inventoryPaths).toEqual([join(repository, "fixture.txt")]);+ await requireSecureCredentialHome(codexHome);+ expect(+ await prepareCodexSecurityCredentialHome({+ CODEX_SECURITY_STATE_DIR: stateDirectory,+ }),+ ).toBe(codexHome);},);diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.tsindex 396057bdd..66fc9bff7 100644--- a/sdk/typescript/tests-ts/runtime.test.ts+++ b/sdk/typescript/tests-ts/runtime.test.ts@@ -1,4 +1,6 @@import { execFile, spawnSync } from "node:child_process";+import * as childProcess from "node:child_process";+import { EventEmitter, once } from "node:events";import { existsSync, renameSync, symlinkSync } from "node:fs";import {chmod,@@ -29,6 +31,8 @@ import {relative,sep,} from "node:path";+import { PassThrough } from "node:stream";+import { setImmediate as nextTurn } from "node:timers/promises";import { promisify } from "node:util";import { fileURLToPath } from "node:url";import { brotliDecompressSync } from "node:zlib";@@ -75,7 +79,6 @@ import {runWorkbench,setCodexSecurityCredentialLogout,streamWindowsCredentialAclDescriptors,- verifyStableWindowsCredentialDescendants,} from "../src/runtime.js";import { loadBundledRuntime, PLUGIN_ROOT } from "./plugin-root.js";import { runTestInSubprocess } from "./support/test-subprocess.js";@@ -99,6 +102,10 @@ async function temporaryDirectory(return path;}+function windowsCredentialAclOutput(descriptors: readonly string[]): string {+ return `${descriptors.join("\n")}\nCODEX_SECURITY_ACL_COMPLETE:${descriptors.length}\n`;+}+async function plantCredentialHomeLock(home: string,pid: number,@@ -2704,178 +2711,49 @@ describe("runtime directories and plugin Python boundary", () => {).rejects.toThrow("private Windows credential home");});- test("retries Windows credential descendant verification after concurrent changes", async () => {- const root = await temporaryDirectory();- const home = join(root, "home");- const temporary = join(home, ".auth-temporary");- await mkdir(home);- await writeFile(join(home, "auth.json"), "credential\n");- await writeFile(temporary, "temporary credential\n");- let attempts = 0;-- await verifyStableWindowsCredentialDescendants(home, async () => {- attempts += 1;- if (attempts === 1) await rm(temporary);- return 1;- });-- expect(attempts).toBe(2);- });-- test("retries Windows credential verification when a descendant disappears", async () => {- if (- runTestInSubprocess(- import.meta.path,- "retries Windows credential verification when a descendant disappears",- )- ) {- return;- }- const root = await temporaryDirectory();- const home = join(root, "home");- const temporary = join(home, ".auth-temporary");- await mkdir(home);- await writeFile(join(home, "auth.json"), "credential\n");- await writeFile(temporary, "temporary credential\n");- const originalLstat = fsPromises.lstat;- let removed = false;- let inspections = 0;- mock.module("node:fs/promises", () => ({- ...fsPromises,- lstat: async (path: Parameters<typeof lstat>[0]) => {- if (path === temporary && !removed) {- removed = true;- await rm(temporary);- }- return originalLstat(path);- },- }));+ test.each(["created", "removed"] as const)(+ "inspects Windows credentials once while private descendants are %s",+ async (change) => {+ const root = await temporaryDirectory();+ const home = join(root, "home");+ const inspectionCount = join(root, "inspection-count");+ const temporary = join(home, ".auth-temporary");+ await mkdir(home);+ await writeFile(join(home, "auth.json"), "credential\n");+ if (change === "removed") await writeFile(temporary, "temporary\n");+ const sid = "S-1-5-21-111-222-333-1001";+ const directory = `O:${sid}G:SYD:P(A;OICI;FA;;;${sid})`;+ const file = `O:${sid}G:SYD:P(A;;FA;;;${sid})`;+ const ancestors: string[] = [];+ for (let ancestor = dirname(home); ; ancestor = dirname(ancestor)) {+ ancestors.push(directory);+ if (ancestor === dirname(ancestor)) break;+ }+ const script = [+ 'const fs = require("node:fs")',+ `fs.appendFileSync(${JSON.stringify(inspectionCount)}, "inspection\\n")`,+ change === "created"+ ? `fs.writeFileSync(${JSON.stringify(temporary)}, "temporary")`+ : `fs.rmSync(${JSON.stringify(temporary)})`,+ `const descriptors = [...${JSON.stringify([...ancestors, directory])}, ...fs.readdirSync(${JSON.stringify(home)}).map(() => ${JSON.stringify(file)})]`,+ 'process.stdout.write(descriptors.join("\\n") + "\\nCODEX_SECURITY_ACL_COMPLETE:" + descriptors.length + "\\n")',+ ].join("; ");- try {- await verifyStableWindowsCredentialDescendants(home, async () => {- inspections += 1;- return 1;+ const snapshot = await inspectWindowsCredentialAclSnapshot(home, sid, {+ command: process.execPath,+ args: ["--eval", script],});- } finally {- mock.module("node:fs/promises", () => ({- ...fsPromises,- lstat: originalLstat,- }));- }-- expect(removed).toBe(true);- expect(inspections).toBe(1);- });- test("rejects Windows credential descendants that repeatedly disappear", async () => {- if (- runTestInSubprocess(- import.meta.path,- "rejects Windows credential descendants that repeatedly disappear",- )- ) {- return;- }- const root = await temporaryDirectory();- const home = join(root, "home");- const credential = join(home, "auth.json");- await mkdir(home);- await writeFile(credential, "credential\n");- const originalLstat = fsPromises.lstat;- let attempts = 0;- mock.module("node:fs/promises", () => ({- ...fsPromises,- lstat: async (path: Parameters<typeof lstat>[0]) => {- if (path === credential) {- attempts += 1;- throw Object.assign(new Error("credential disappeared"), {- code: "ENOENT",- path,- });- }- return originalLstat(path);- },- }));-- try {- await expect(- verifyStableWindowsCredentialDescendants(home, async () => 1),- ).rejects.toThrow("Windows credential descendants could not be verified");- } finally {- mock.module("node:fs/promises", () => ({- ...fsPromises,- lstat: originalLstat,- }));- }-- expect(attempts).toBe(3);- });-- test("does not retry a missing Windows credential home", async () => {- const root = await temporaryDirectory();- const home = join(root, "missing-home");- let inspections = 0;-- await expect(- verifyStableWindowsCredentialDescendants(home, async () => {- inspections += 1;- return 0;- }),- ).rejects.toMatchObject({ code: "ENOENT", path: home });-- expect(inspections).toBe(0);- });-- test("rejects Windows credential descendants that never stabilize", async () => {- const root = await temporaryDirectory();- const home = join(root, "home");- await mkdir(home);- await writeFile(join(home, "auth.json"), "credential\n");- let attempts = 0;-- await expect(- verifyStableWindowsCredentialDescendants(home, async () => {- attempts += 1;- return 0;- }),- ).rejects.toThrow("Windows credential descendants could not be verified");- expect(attempts).toBe(3);- });-- test("inspects Windows credential ancestry, home, and descendants in one subprocess", async () => {- const root = await temporaryDirectory();- const home = join(root, "home");- const inspectionCount = join(root, "inspection-count");- await mkdir(home);- await writeFile(join(home, "auth.json"), "credential\n");- const sid = "S-1-5-21-111-222-333-1001";- const directory = `O:${sid}G:SYD:P(A;OICI;FA;;;${sid})`;- const file = `O:${sid}G:SYD:P(A;;FA;;;${sid})`;- const ancestors: string[] = [];- for (let ancestor = dirname(home); ; ancestor = dirname(ancestor)) {- ancestors.push(directory);- if (ancestor === dirname(ancestor)) break;- }- const descriptors = [...ancestors, directory, file];- const script = [- `require("node:fs").appendFileSync(${JSON.stringify(inspectionCount)}, "inspection\\n")`,- `process.stdout.write(${JSON.stringify(`${descriptors.join("\n")}\n`)})`,- ].join("; ");-- const snapshot = await inspectWindowsCredentialAclSnapshot(home, sid, {- command: process.execPath,- args: ["--eval", script],- });-- expect(snapshot.home).toMatchObject({- owner: sid,- protected: true,- grantsCurrentUserAccess: true,- untrustedPrincipals: [],- });- expect(snapshot.descendantsArePrivate).toBe(true);- expect(await readFile(inspectionCount, "utf8")).toBe("inspection\n");- });+ expect(snapshot.home).toMatchObject({+ owner: sid,+ protected: true,+ grantsCurrentUserAccess: true,+ untrustedPrincipals: [],+ });+ expect(snapshot.descendantsArePrivate).toBe(true);+ expect(await readFile(inspectionCount, "utf8")).toBe("inspection\n");+ },+ );test("inspects Windows credential ancestry and the home even without descendants", async () => {const root = await temporaryDirectory();@@ -2895,7 +2773,7 @@ describe("runtime directories and plugin Python boundary", () => {command: process.execPath,args: ["--eval",- `process.stdout.write(${JSON.stringify(`${descriptors.join("\n")}\n`)})`,+ `process.stdout.write(${JSON.stringify(windowsCredentialAclOutput(descriptors))})`,],}),).resolves.toMatchObject({@@ -2924,8 +2802,10 @@ describe("runtime directories and plugin Python boundary", () => {const script = ['const fs = require("node:fs")',`fs.appendFileSync(${JSON.stringify(inspectionCount)}, "inspection\\n")`,- `process.stdout.write(${JSON.stringify(`${descriptors.join("\n")}\n`)})`,- `if (fs.existsSync(${JSON.stringify(temporary)})) { fs.unlinkSync(${JSON.stringify(temporary)}); process.exitCode = 2 }`,+ `const interrupted = fs.existsSync(${JSON.stringify(temporary)})`,+ `if (interrupted) fs.unlinkSync(${JSON.stringify(temporary)})`,+ `process.stdout.write(interrupted ? ${JSON.stringify(`${descriptors.join("\n")}\n`)} : ${JSON.stringify(windowsCredentialAclOutput(descriptors))})`,+ "process.exitCode = interrupted ? 2 : 0",].join("; ");await expect(@@ -2969,6 +2849,137 @@ describe("runtime directories and plugin Python boundary", () => {},);+ test.each(["safe", "unsafe"] as const)(+ "drains Windows credential callbacks before retrying %s snapshots",+ async (kind) => {+ if (+ runTestInSubprocess(+ import.meta.path,+ `drains Windows credential callbacks before retrying ${kind} snapshots`,+ )+ ) {+ return;+ }+ const home = join(await temporaryDirectory(), "home");+ const sid = "S-1-5-21-111-222-333-1001";+ const directory = `O:${sid}G:SYD:P(A;OICI;FA;;;${sid})`;+ const descriptors: string[] = [];+ for (let ancestor = dirname(home); ; ancestor = dirname(ancestor)) {+ descriptors.push(directory);+ if (ancestor === dirname(ancestor)) break;+ }+ descriptors.push(directory);+ const firstDescriptors = [...descriptors];+ if (kind === "unsafe") {+ firstDescriptors[0] = `${directory}(A;OICI;FA;;;WD)`;+ }++ const makeChild = () =>+ Object.assign(new EventEmitter(), {+ stdout: new PassThrough(),+ stderr: new PassThrough(),+ exitCode: null as number | null,+ signalCode: null,+ kill: () => true,+ });+ const first = makeChild();+ let enterCallback!: () => void;+ const callbackEntered = new Promise<void>((resolve) => {+ enterCallback = resolve;+ });+ let releaseCallback!: () => void;+ const callbackReleased = new Promise<void>((resolve) => {+ releaseCallback = resolve;+ });+ let paused = false;+ let callbackFinished = false;+ let attempts = 0;+ const originalSpawn = childProcess.spawn;+ mock.module("node:child_process", () => ({+ ...childProcess,+ spawn: () => {+ attempts += 1;+ if (attempts === 1) return first;+ expect(attempts).toBe(2);+ expect(callbackFinished).toBe(true);+ const child = makeChild();+ queueMicrotask(() => {+ child.stdout.end(windowsCredentialAclOutput(descriptors));+ child.stderr.end();+ child.exitCode = 0;+ child.emit("close", 0, null);+ });+ return child;+ },+ }));+ let settled = false;+ const outcome = inspectWindowsCredentialAclSnapshot(home, sid, {+ command: "synthetic-credential-inspector",+ args: [],+ resolveDescriptorAliases: async () => {+ if (paused) return;+ paused = true;+ enterCallback();+ await callbackReleased;+ callbackFinished = true;+ },+ }).then(+ (value) => {+ settled = true;+ return { value, error: undefined };+ },+ (error: unknown) => {+ settled = true;+ return { value: undefined, error };+ },+ );+ try {+ first.stdout.write(`${firstDescriptors.join("\n")}\n`);+ await Promise.race([+ callbackEntered,+ outcome.then(() => {+ throw new Error(+ "Credential inspection settled before its callback",+ );+ }),+ ]);+ const ended = once(first.stdout, "end");+ first.stdout.end();+ first.stderr.end();+ await ended;+ first.exitCode = 2;+ first.emit("close", 2, null);+ await nextTurn();+ expect(settled).toBe(false);+ expect(attempts).toBe(1);+ releaseCallback();+ const result = await outcome;+ if (kind === "unsafe") {+ expect(result.error).toMatchObject({+ message:+ "Windows credential-home ancestor allows another identity to replace the directory",+ });+ expect(attempts).toBe(1);+ } else {+ expect(result.error).toBeUndefined();+ expect(result.value).toMatchObject({+ home: { owner: sid, protected: true },+ descendantsArePrivate: true,+ });+ expect(attempts).toBe(2);+ }+ } finally {+ releaseCallback();+ first.stdout.destroy();+ first.stderr.destroy();+ mock.module("node:child_process", () => ({+ ...childProcess,+ spawn: originalSpawn,+ }));+ }+ },+ );+test("rejects unsafe Windows credential ancestry during combined ACL inspection", async () => {const root = await temporaryDirectory();const home = join(root, "home");@@ -3007,6 +3018,54 @@ describe("runtime directories and plugin Python boundary", () => {).rejects.toThrow("Windows credential-home ancestry could not be verified");});+ test("rejects incomplete or failed Windows credential descendant streams", async () => {+ const root = await temporaryDirectory();+ const home = join(root, "home");+ await mkdir(home);+ const sid = "S-1-5-21-111-222-333-1001";+ const directory = `O:${sid}G:SYD:P(A;OICI;FA;;;${sid})`;+ const file = `O:${sid}G:SYD:P(A;;FA;;;${sid})`;+ const descriptors: string[] = [];+ for (let ancestor = dirname(home); ; ancestor = dirname(ancestor)) {+ descriptors.push(directory);+ if (ancestor === dirname(ancestor)) break;+ }+ descriptors.push(directory, file);+ const complete = windowsCredentialAclOutput(descriptors);+ for (const { output, exitCode, error } of [+ {+ output: `${descriptors.join("\n")}\n`,+ exitCode: 0,+ error: "Windows credential descendants could not be verified",+ },+ {+ output: `${descriptors.slice(0, -1).join("\n")}\nCODEX_SECURITY_ACL_COMPLETE:${descriptors.length}\n`,+ exitCode: 0,+ error: "Windows credential descendants could not be verified",+ },+ {+ output: `${complete}${file}\n`,+ exitCode: 0,+ error: "Windows credential ACL inspection continued after completion",+ },+ {+ output: complete,+ exitCode: 1,+ error: "Windows credential ACL inspection failed",+ },+ ]) {+ await expect(+ inspectWindowsCredentialAclSnapshot(home, sid, {+ command: process.execPath,+ args: [+ "--eval",+ `process.stdout.write(${JSON.stringify(output)}); process.exitCode = ${exitCode}`,+ ],+ }),+ ).rejects.toThrow(error);+ }+ });+test("detects unsafe descendants during combined Windows credential ACL inspections", async () => {const root = await temporaryDirectory();const home = join(root, "home");@@ -3027,7 +3086,7 @@ describe("runtime directories and plugin Python boundary", () => {command: process.execPath,args: ["--eval",- `process.stdout.write(${JSON.stringify(`${descriptors.join("\n")}\n`)})`,+ `process.stdout.write(${JSON.stringify(windowsCredentialAclOutput(descriptors))})`,],}),).resolves.toMatchObject({ descendantsArePrivate: false });@@ -3574,6 +3633,32 @@ describe("runtime directories and plugin Python boundary", () => {).rejects.toThrow("private Windows credential home");});+ test.skipIf(process.platform !== "win32")(+ "rejects Windows credential-home junctions even if their targets disappear",+ async () => {+ const root = await temporaryDirectory();+ const home = await prepareCodexSecurityCredentialHome({+ CODEX_SECURITY_STATE_DIR: join(root, "state"),+ });+ const outside = join(root, "outside");+ await mkdir(outside);+ const credential = join(outside, "auth.json");+ await writeFile(credential, "synthetic outside credential\n");+ await symlink(outside, join(home, "linked-cache"), "junction");++ await expect(requireSecureCredentialHome(home)).rejects.toThrow(+ "Windows credential home contains a symbolic link or junction",+ );+ expect(await readFile(credential, "utf8")).toBe(+ "synthetic outside credential\n",+ );+ await rename(outside, join(root, "moved-outside"));+ await expect(requireSecureCredentialHome(home)).rejects.toThrow(+ "Windows credential home contains a symbolic link or junction",+ );+ },+ );+test.skipIf(process.platform !== "win32")("creates credential homes with a verified managed-compatible Windows ACL",async () => {