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(auth): diagnose unsupported Windows credential ancestry (#1745)
Michael D'Angelo26e53dc18451
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.mdindex da34398a3..a9f0f640d 100644--- a/sdk/typescript/docs/cli.md+++ b/sdk/typescript/docs/cli.md@@ -837,10 +837,24 @@ Finish older-version operations before upgrading. Never remove`.codex-security-scan.sqlite3` during an operation. Stop all operations using thecredential home before manually removing an old `.codex-security-scan.lock`.-On Windows, an older sandboxed run can leave invalid ACLs on a credential-home-ancestor. Preserve that state, then select a new private `CODEX_SECURITY_STATE_DIR`-outside the old state and repository. Sign in again if needed; the new directory-has separate scan history.+On Windows, credential-home checks require trusted ownership and permissions+through every ancestor, including the volume root. Codex Security can repair+the credential home and its descendants; it does not change ancestor ownership+or ACLs. An error identifies the rejected ancestor and its underlying ACL+problem. A volume root owned by `Everyone` (`S-1-1-0`) is unsupported, even when+the credential home itself is private.++Preserve existing state, then choose a private `CODEX_SECURITY_STATE_DIR` outside+the rejected ancestor and the repository, with a full ancestor chain that passes+the same checks. If the volume root is rejected, another directory on that+volume cannot resolve it; use a separately provisioned volume with trusted+ancestry. Temporary bootstrap homes also need trusted ancestry: set `TEMP` and+`TMP` to a private directory on that volume before launching the CLI. Do not+change the system volume's owner or ACL to make a scan run. If no suitable+location is available, this layout cannot provision credentials safely under+the current checks. Sign in again if needed; a new state directory has separate+scan history and does not migrate credentials or reports from the old state+directory.### Progress and costdiff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.tsindex 4cdcef575..6b4bf936e 100644--- a/sdk/typescript/src/runtime.ts+++ b/sdk/typescript/src/runtime.ts@@ -423,10 +423,7 @@ function windowsCredentialAclFailure(error: unknown): string {typeof stderr === "string" && stderr.trim() !== ""? stderr: errorMessage(error);- const normalized = errorMessage(detail)- .replace(/\s+/gu, " ")- .trim()- .slice(0, 512);+ const normalized = errorMessage(detail).replace(/\s+/gu, " ").trim();return normalized === "" ? "" : `. ${normalized}`;}@@ -800,9 +797,9 @@ export async function inspectWindowsCredentialAclSnapshot(home: WindowsCredentialAcl;descendantsArePrivate: boolean;}> {- let ancestors = 0;+ const ancestors: string[] = [];for (let ancestor = dirname(path); ; ancestor = dirname(ancestor)) {- ancestors += 1;+ ancestors.push(ancestor);if (ancestor === dirname(ancestor)) break;}@@ -837,24 +834,36 @@ export async function inspectWindowsCredentialAclSnapshot(inspected += 1;await options.resolveDescriptorAliases?.(descriptor);- if (index < ancestors) {- const ancestor = inspectWindowsCredentialAcl(- descriptor,- currentUserSid,- {- resolvedAliases: options.resolvedAliases,- scope: "ancestor",- },- );- if (ancestor.untrustedPrincipals.length !== 0) {+ if (index < ancestors.length) {+ const ancestorPath = ancestors[index]!;+ try {+ const ancestor = inspectWindowsCredentialAcl(+ descriptor,+ currentUserSid,+ {+ resolvedAliases: options.resolvedAliases,+ scope: "ancestor",+ },+ );+ if (ancestor.untrustedPrincipals.length !== 0) {+ throw new Error(+ "Windows credential-home ancestor allows another identity to replace the directory",+ );+ }+ } catch (error) {+ const guidance =+ ancestorPath === dirname(ancestorPath)+ ? "This volume root is unsupported. Choose a location on a volume with trusted ancestry; another directory on the same volume will not resolve this."+ : "Choose a location outside this ancestor with trusted ownership and permissions.";throw new Error(- "Windows credential-home ancestor allows another identity to replace the directory",+ `Windows private-directory ancestor could not be trusted: ${ancestorPath}. ${errorMessage(error)}. ${guidance}`,+ { cause: error },);}return;}- if (index === ancestors) {+ if (index === ancestors.length) {try {home = inspectWindowsCredentialAcl(descriptor, currentUserSid, {resolvedAliases: options.resolvedAliases,@@ -889,7 +898,7 @@ export async function inspectWindowsCredentialAclSnapshot(if (error instanceof WindowsCredentialDescendantsChangedError) continue;throw error;}- if (inspected <= ancestors) {+ if (inspected <= ancestors.length) {throw new Error("Windows credential-home ancestry could not be verified");}if (!completed) {diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.tsindex 43c8453b9..58dac3346 100644--- a/sdk/typescript/tests-ts/runtime.test.ts+++ b/sdk/typescript/tests-ts/runtime.test.ts@@ -3843,8 +3843,9 @@ describe("runtime directories and plugin Python boundary", () => {const result = await outcome;if (kind === "unsafe") {expect(result.error).toMatchObject({- message:+ message: expect.stringContaining("Windows credential-home ancestor allows another identity to replace the directory",+ ),});expect(attempts).toBe(1);} else {@@ -3882,6 +3883,52 @@ describe("runtime directories and plugin Python boundary", () => {);});+ test.each(["parent", "volume root"] as const)(+ "identifies an Everyone-owned %s in streamed Windows ACL descriptors",+ async (location) => {+ const { home } = await credentialHome(false);+ const sid = "S-1-5-21-111-222-333-1001";+ const directory = `O:${sid}G:SYD:P(A;OICI;FA;;;${sid})`;+ const ancestors = credentialAncestors(home, directory);+ const rejected = location === "parent" ? dirname(home) : parse(home).root;+ ancestors[location === "parent" ? 0 : ancestors.length - 1] =+ `O:WDG:SYD:P(A;OICI;FA;;;${sid})`;++ const failure = await inspectWindowsCredentialAclSnapshot(home, sid, {+ command: process.execPath,+ args: [+ "--eval",+ `process.stdout.write(${JSON.stringify(windowsCredentialAclOutput([...ancestors, directory]))})`,+ ],+ }).catch((error: unknown) => error);++ expect(failure).toBeInstanceOf(Error);+ expect((failure as Error).message).toContain(+ `ancestor could not be trusted: ${rejected}.`,+ );+ expect((failure as Error).message).toContain(+ "Windows credential ACL owner is not a trusted principal: S-1-1-0",+ );+ expect((failure as Error).cause).toMatchObject({+ message:+ "Windows credential ACL owner is not a trusted principal: S-1-1-0",+ });+ if (location === "volume root") {+ expect((failure as Error).message).toContain(+ "volume root is unsupported",+ );+ expect((failure as Error).message).toContain(+ "another directory on the same volume will not resolve this",+ );+ } else {+ expect((failure as Error).message).toContain(+ "Choose a location outside this ancestor",+ );+ expect((failure as Error).message).not.toContain("volume root");+ }+ },+ );+test("rejects incomplete combined Windows credential ACL inspections", async () => {const { home } = await credentialHome(false);const sid = "S-1-5-21-111-222-333-1001";@@ -4485,6 +4532,55 @@ describe("runtime directories and plugin Python boundary", () => {).toBe(false);});+ test("preserves the public Windows ACL diagnosis for long ancestor paths", async () => {+ const root = await temporaryDirectory();+ const ancestor = join(+ root,+ ...Array.from({ length: 8 }, (_, index) =>+ `ancestor-${index}-`.padEnd(80, "x"),+ ),+ );+ const home = join(ancestor, "codex-home");+ const sid = "S-1-5-21-111-222-333-1001";+ const descriptor = `O:WDG:SYD:P(A;OICI;FA;;;${sid})`;+ const failure = await requirePrivateCredentialHome(+ await lstat(root),+ home,+ {+ platform: "win32",+ secureWindowsHome: async (path) => {+ await inspectWindowsCredentialAclSnapshot(path, sid, {+ command: process.execPath,+ args: [+ "--eval",+ `process.stdout.write(${JSON.stringify(`${descriptor}\n`)})`,+ ],+ });+ },+ },+ ).catch((error: unknown) => error);++ expect(failure).toBeInstanceOf(Error);+ expect((failure as Error).message).toContain(+ "Unable to create a private Windows credential home",+ );+ expect((failure as Error).message).toContain(+ `ancestor could not be trusted: ${ancestor}.`,+ );+ expect((failure as Error).message).toContain(+ "owner is not a trusted principal: S-1-1-0",+ );+ expect((failure as Error).message).toContain(+ "Choose a location outside this ancestor with trusted ownership and permissions.",+ );+ expect((failure as Error).cause).toMatchObject({+ cause: {+ message:+ "Windows credential ACL owner is not a trusted principal: S-1-1-0",+ },+ });+ });+test("preserves Windows ACL subprocess failures", async () => {const { home } = await credentialHome(false);const metadata = await lstat(home);diff --git a/sdk/typescript/tests-ts/windows-machine-policy.test.ts b/sdk/typescript/tests-ts/windows-machine-policy.test.tsindex 6820592a9..f2c92208b 100644--- a/sdk/typescript/tests-ts/windows-machine-policy.test.ts+++ b/sdk/typescript/tests-ts/windows-machine-policy.test.ts@@ -1,10 +1,22 @@import { spawnSync } from "node:child_process";import { existsSync } from "node:fs";-import { mkdir, rm } from "node:fs/promises";+import { mkdir, readFile, rm, writeFile } from "node:fs/promises";import { dirname, join } from "node:path";import { fileURLToPath, pathToFileURL } from "node:url";import { afterEach, describe, expect, test } from "bun:test";import { temporaryDirectory } from "./support/temporary-directories.js";+import {+ inspectWindowsCredentialAcl,+ prepareCodexSecurityCredentialHome,+ requireSecureCredentialHome,+} from "../src/runtime.js";++const testHostedWindows = test.skipIf(+ process.platform !== "win32" ||+ process.env["GITHUB_ACTIONS"] !== "true" ||+ process.env["RUNNER_ENVIRONMENT"] !== "github-hosted" ||+ process.env["CODEX_SECURITY_ALLOW_MACHINE_POLICY_TEST"] !== "true",+);let temporaryRoot: string | undefined;afterEach(async () => {@@ -14,12 +26,186 @@ afterEach(async () => {});describe("runtime directories and plugin Python boundary", () => {- test.skipIf(- process.platform !== "win32" ||- process.env["GITHUB_ACTIONS"] !== "true" ||- process.env["RUNNER_ENVIRONMENT"] !== "github-hosted" ||- process.env["CODEX_SECURITY_ALLOW_MACHINE_POLICY_TEST"] !== "true",- )(+ testHostedWindows(+ "diagnoses an Everyone-owned Windows ancestor before repairing credential ACLs",+ async () => {+ const root = await temporaryDirectory("codex-security-owner-", true);+ temporaryRoot = root;+ const home = await prepareCodexSecurityCredentialHome({+ CODEX_SECURITY_STATE_DIR: join(root, "state"),+ });+ const systemDirectory = join(+ process.env["SystemRoot"] ?? "C:\\Windows",+ "System32",+ );+ const windowsTestCommand = (+ tool: string,+ args: readonly string[],+ environment?: NodeJS.ProcessEnv,+ ) =>+ spawnSync(join(systemDirectory, tool), args, {+ encoding: "utf8",+ windowsHide: true,+ env: environment,+ });+ const inspectWindowsTestAcl = (+ statements: string[],+ environment: NodeJS.ProcessEnv,+ ) =>+ windowsTestCommand(+ join("WindowsPowerShell", "v1.0", "powershell.exe"),+ [+ "-NoLogo",+ "-NoProfile",+ "-NonInteractive",+ "-Command",+ statements.join("; "),+ ],+ {+ ...Object.fromEntries(+ Object.entries(environment).filter(+ ([name]) => name.toUpperCase() !== "PSMODULEPATH",+ ),+ ),+ PSModulePath: join(+ systemDirectory,+ "WindowsPowerShell",+ "v1.0",+ "Modules",+ ),+ },+ );+ const state = dirname(home);+ const auth = join(home, "auth.json");+ const contents = '{"token":"synthetic-credential"}\n';+ await writeFile(auth, contents);+ const grant = windowsTestCommand("icacls.exe", [+ home,+ "/grant",+ "*S-1-1-0:(OI)(CI)R",+ ]);+ expect(grant.status, grant.stderr).toBe(0);++ const ancestors: string[] = [];+ for (let ancestor = state; ; ancestor = dirname(ancestor)) {+ ancestors.push(ancestor);+ if (ancestor === dirname(ancestor)) break;+ }+ const paths = [...ancestors, home, auth];+ const snapshot = () => {+ const result = inspectWindowsTestAcl(+ [+ "$ErrorActionPreference = 'Stop'",+ "$paths = ConvertFrom-Json -InputObject $env:CODEX_SECURITY_TEST_ACL_PATHS",+ "@($paths | ForEach-Object { $acl = Get-Acl -LiteralPath $_; [pscustomobject]@{ owner = $acl.GetOwner([System.Security.Principal.SecurityIdentifier]).Value; sddl = $acl.Sddl } }) | ConvertTo-Json -Compress",+ ],+ {+ ...process.env,+ CODEX_SECURITY_TEST_ACL_PATHS: JSON.stringify(paths),+ },+ );+ expect(result.status, result.stderr).toBe(0);+ const descriptors = JSON.parse(result.stdout) as {+ owner: string;+ sddl: string;+ }[];+ expect(descriptors).toHaveLength(paths.length);+ return descriptors;+ };+ const setOwner = (owner: string) => {+ const result = inspectWindowsTestAcl(+ [+ "$ErrorActionPreference = 'Stop'",+ "$acl = Get-Acl -LiteralPath $env:CODEX_SECURITY_TEST_ACL_PATH",+ "$acl.SetOwner([System.Security.Principal.SecurityIdentifier]::new($env:CODEX_SECURITY_TEST_OWNER))",+ "Set-Acl -LiteralPath $env:CODEX_SECURITY_TEST_ACL_PATH -AclObject $acl",+ ],+ {+ ...process.env,+ CODEX_SECURITY_TEST_ACL_PATH: state,+ CODEX_SECURITY_TEST_OWNER: owner,+ },+ );+ expect(result.status, result.stderr).toBe(0);+ };+ const original = snapshot();+ const identity = windowsTestCommand("whoami.exe", [+ "/user",+ "/fo",+ "csv",+ "/nh",+ ]);+ expect(identity.status, identity.stderr).toBe(0);+ const sid = /"(S-1-(?:\d+-)*\d+)"\s*$/u.exec(identity.stdout)?.[1];+ expect(sid).toBeDefined();+ const administrator = inspectWindowsTestAcl(+ [+ "$ErrorActionPreference = 'Stop'",+ "Microsoft.PowerShell.Utility\\ConvertFrom-SddlString -Sddl 'O:LAG:SYD:(A;;GA;;;SY)' | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty RawDescriptor | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty Owner | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty Value",+ ],+ process.env,+ );+ expect(administrator.status, administrator.stderr).toBe(0);+ const localAdministrator = administrator.stdout.trim();+ expect(localAdministrator).toMatch(/^S-1-(?:\d+-)*500$/u);+ const resolvedAliases = { LA: localAdministrator };+ expect(+ inspectWindowsCredentialAcl(original[ancestors.length]!.sddl, sid!, {+ resolvedAliases,+ }).untrustedPrincipals,+ ).toContain("S-1-1-0");++ try {+ setOwner("S-1-1-0");+ const before = snapshot();+ expect(before[0]!.owner).toBe("S-1-1-0");+ const failure = await prepareCodexSecurityCredentialHome({+ CODEX_SECURITY_STATE_DIR: state,+ }).catch((error: unknown) => error);+ expect(failure).toBeInstanceOf(Error);+ expect((failure as Error).message).toContain(+ `ancestor could not be trusted: ${state}.`,+ );+ expect((failure as Error).message).toContain(+ "owner is not a trusted principal: S-1-1-0",+ );+ expect(snapshot()).toEqual(before);+ expect(await readFile(auth, "utf8")).toBe(contents);+ } finally {+ setOwner(original[0]!.owner);+ }++ expect(snapshot()).toEqual(original);+ expect(+ await prepareCodexSecurityCredentialHome({+ CODEX_SECURITY_STATE_DIR: state,+ }),+ ).toBe(home);+ const repaired = snapshot();+ expect(repaired.slice(0, ancestors.length)).toEqual(+ original.slice(0, ancestors.length),+ );+ for (const [offset, scope] of [+ [0, "directory"],+ [1, "file"],+ ] as const) {+ expect(+ inspectWindowsCredentialAcl(+ repaired[ancestors.length + offset]!.sddl,+ sid!,+ { scope, resolvedAliases },+ ),+ ).toMatchObject({+ grantsCurrentUserAccess: true,+ untrustedPrincipals: [],+ });+ }+ await expect(requireSecureCredentialHome(home)).resolves.toBeDefined();+ expect(await readFile(auth, "utf8")).toBe(contents);+ },+ );++ testHostedWindows("prepares managed credential homes under constrained PowerShell",async () => {const root = await temporaryDirectory("codex-security-policy-", true);