Skip to content

OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security

fix: support managed Windows credential authentication (#280)

mldangelo-oaie117f662d082
diff --git a/.github/workflows/node-ci.yml b/.github/workflows/node-ci.yml
index e4f4d7e55..c7a1e08e7 100644
--- a/.github/workflows/node-ci.yml
+++ b/.github/workflows/node-ci.yml
@@ -23,6 +23,8 @@ jobs:
os: [ubuntu-latest, macos-latest, windows-latest]
node: ["22.13.0"]
include:
+ - os: windows-latest
+ node: "24"
- os: ubuntu-latest
node: "24.0.0"
- os: ubuntu-latest
@@ -68,12 +70,26 @@ jobs:
- name: Typecheck
run: pnpm --dir sdk/typescript run types
+ - name: Prepare private Windows test root
+ if: runner.os == 'Windows'
+ id: windows-temp
+ shell: pwsh
+ run: |
+ $ErrorActionPreference = 'Stop'
+ $path = Join-Path $env:USERPROFILE '.codex-security-ci-temp'
+ New-Item -ItemType Directory -Path $path -Force | Out-Null
+ $sid = (whoami /user /fo csv /nh | ConvertFrom-Csv -Header Name, Sid).Sid
+ & icacls $path /inheritance:r /grant:r "*${sid}:(OI)(CI)F" '*S-1-5-18:(OI)(CI)F' '*S-1-5-32-544:(OI)(CI)F' | Out-Null
+ if ($LASTEXITCODE -ne 0) { throw 'Could not secure the Windows test root' }
+ "path=$path" >> $env:GITHUB_OUTPUT
+
- name: Test
timeout-minutes: 10
env:
- TEMP: ${{ runner.temp }}
- TMP: ${{ runner.temp }}
- TMPDIR: ${{ runner.temp }}
+ TEMP: ${{ steps.windows-temp.outputs.path || runner.temp }}
+ TMP: ${{ steps.windows-temp.outputs.path || runner.temp }}
+ TMPDIR: ${{ steps.windows-temp.outputs.path || runner.temp }}
+ CODEX_SECURITY_ALLOW_MACHINE_POLICY_TEST: ${{ runner.environment == 'github-hosted' && runner.os == 'Windows' && 'true' || 'false' }}
run: pnpm --dir sdk/typescript run test
- name: Check formatting
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md
index b43aa35ba..2804da1ec 100644
--- a/sdk/typescript/README.md
+++ b/sdk/typescript/README.md
@@ -141,7 +141,11 @@ Check or remove the stored sign-in with `npx @openai/codex-security login status
and `npx @openai/codex-security logout`. Codex Security keeps its sign-in in a
private, stable Codex home at `$CODEX_SECURITY_STATE_DIR/codex-home`, or at
`$CODEX_HOME/state/plugins/codex-security/codex-home` when no state directory is
-configured. Login, status, logout, and scans use the same home. Codex manages
+configured. On managed Windows devices, inherited access for `SYSTEM` and local
+`Administrators` is preserved while protecting the home against future changes
+to its parents. Other users and broad groups are rejected, and PowerShell
+Constrained Language Mode is supported. Login,
+status, logout, and scans use the same home. Codex manages
credentials using its configured file or system-keyring backend and honors
managed-device policies. An existing file-based Codex sign-in is imported only
when the dedicated home does not already contain stored credentials. Logging
diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.ts
index 16283140b..a530f8899 100644
--- a/sdk/typescript/src/runtime.ts
+++ b/sdk/typescript/src/runtime.ts
@@ -1,4 +1,4 @@
-import { execFile as execFileCallback } from "node:child_process";
+import { execFile as execFileCallback, spawn } from "node:child_process";
import { createHash, randomUUID } from "node:crypto";
import { constants, existsSync, type Stats } from "node:fs";
import {
@@ -31,6 +31,7 @@ import {
resolve,
sep,
} from "node:path";
+import { createInterface } from "node:readline";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { crc32 } from "node:zlib";
@@ -42,6 +43,7 @@ import {
OutputDirectoryError,
PluginBootstrapError,
PluginPythonUnavailableError,
+ redactedErrorMessage,
} from "./errors.js";
import type { JsonObject } from "./config.js";
import { resolveTrustedExecutable } from "./trusted-executable.js";
@@ -64,6 +66,7 @@ const CREDENTIAL_LOCK_NAME = ".codex-security-scan.lock";
const CREDENTIAL_LOGOUT_MARKER = ".codex-security-logged-out";
const CREDENTIAL_LOCK_POLL_MILLISECONDS = 25;
const INCOMPLETE_CREDENTIAL_LOCK_MILLISECONDS = 30_000;
+const MAX_WINDOWS_CREDENTIAL_ACL_STDERR = 64 * 1024;
export interface PluginInstall {
pluginRoot: string;
@@ -261,52 +264,691 @@ export async function requirePrivateCredentialHome(
try {
await (options.secureWindowsHome ?? secureWindowsCredentialHome)(path);
} catch (error) {
+ const detail = windowsCredentialAclFailure(error);
throw new OutputDirectoryError(
- `Unable to create a private Windows credential home: ${path}`,
+ `Unable to create a private Windows credential home: ${path}${detail}`,
{ cause: error },
);
}
}
+function windowsCredentialAclFailure(error: unknown): string {
+ const stderr =
+ typeof error === "object" && error !== null && "stderr" in error
+ ? error.stderr
+ : undefined;
+ const detail =
+ typeof stderr === "string" && stderr.trim() !== ""
+ ? stderr
+ : error instanceof Error
+ ? error.message
+ : String(error);
+ const sanitized = redactedErrorMessage(detail)
+ .replace(/\s+/gu, " ")
+ .trim()
+ .slice(0, 512);
+ return sanitized === "" ? "" : `. ${sanitized}`;
+}
+
+const WINDOWS_SYSTEM_SID = "S-1-5-18";
+const WINDOWS_ADMINISTRATORS_SID = "S-1-5-32-544";
+const WINDOWS_TRUSTED_INSTALLER_SID =
+ "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464";
+const WINDOWS_LOCAL_SERVICE_SID = "S-1-5-19";
+const WINDOWS_NETWORK_SERVICE_SID = "S-1-5-20";
+const WINDOWS_EVERYONE_SID = "S-1-1-0";
+const WINDOWS_AUTHENTICATED_USERS_SID = "S-1-5-11";
+const WINDOWS_USERS_SID = "S-1-5-32-545";
+const WINDOWS_CREATOR_OWNER_SID = "S-1-3-0";
+const WINDOWS_CREATOR_GROUP_SID = "S-1-3-1";
+const WINDOWS_OWNER_RIGHTS_SID = "S-1-3-4";
+const WINDOWS_ALL_APPLICATION_PACKAGES_SID = "S-1-15-2-1";
+const WINDOWS_PRINCIPAL_ALIASES: Readonly<Record<string, string>> = {
+ SY: WINDOWS_SYSTEM_SID,
+ BA: WINDOWS_ADMINISTRATORS_SID,
+ LS: WINDOWS_LOCAL_SERVICE_SID,
+ NS: WINDOWS_NETWORK_SERVICE_SID,
+ WD: WINDOWS_EVERYONE_SID,
+ AU: WINDOWS_AUTHENTICATED_USERS_SID,
+ BU: WINDOWS_USERS_SID,
+ CO: WINDOWS_CREATOR_OWNER_SID,
+ CG: WINDOWS_CREATOR_GROUP_SID,
+ OW: WINDOWS_OWNER_RIGHTS_SID,
+ AC: WINDOWS_ALL_APPLICATION_PACKAGES_SID,
+ AN: "S-1-5-7",
+ IU: "S-1-5-4",
+ NU: "S-1-5-2",
+ SU: "S-1-5-6",
+ RC: "S-1-5-12",
+ ED: "S-1-5-9",
+ BG: "S-1-5-32-546",
+ PU: "S-1-5-32-547",
+ AO: "S-1-5-32-548",
+ SO: "S-1-5-32-549",
+ PO: "S-1-5-32-550",
+ BO: "S-1-5-32-551",
+ RE: "S-1-5-32-552",
+ RU: "S-1-5-32-554",
+ RD: "S-1-5-32-555",
+ NO: "S-1-5-32-556",
+ MU: "S-1-5-32-558",
+ LU: "S-1-5-32-559",
+ IS: "S-1-5-32-568",
+ CY: "S-1-5-32-569",
+ ER: "S-1-5-32-573",
+ CD: "S-1-5-32-574",
+ RA: "S-1-5-32-575",
+ ES: "S-1-5-32-576",
+ HA: "S-1-5-32-578",
+ AA: "S-1-5-32-579",
+};
+const WINDOWS_SID = /^S-1-(?:\d+-)*\d+$/u;
+const WINDOWS_GUID =
+ /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu;
+const WINDOWS_SDDL_SID = "(?:S-1-(?:\\d+-)*\\d+|[A-Z]{2})";
+const WINDOWS_SECURITY_DESCRIPTOR = new RegExp(
+ `^O:(${WINDOWS_SDDL_SID})(?:G:${WINDOWS_SDDL_SID})?D:([A-Z_]*)(.*)$`,
+ "u",
+);
+
+export interface WindowsCredentialAcl {
+ owner: string;
+ protected: boolean;
+ grantsCurrentUserAccess: boolean;
+ untrustedPrincipals: string[];
+ deniedPrincipals: string[];
+}
+
+class UntrustedWindowsCredentialOwnerError extends Error {
+ public constructor(owner: string) {
+ super(`Windows credential ACL owner is not a trusted principal: ${owner}`);
+ }
+}
+
+class RepairableWindowsCredentialAclError extends Error {
+ public constructor(cause: unknown) {
+ super("Windows credential ACL requires repair", { cause });
+ }
+}
+
+/** Inspect a Windows DACL without translating locale-specific account names. */
+export function inspectWindowsCredentialAcl(
+ descriptor: string,
+ currentUserSid: string,
+ options: {
+ resolvedAliases?: Readonly<Record<string, string>>;
+ scope?: "directory" | "file" | "ancestor";
+ } = {},
+): WindowsCredentialAcl {
+ if (!WINDOWS_SID.test(currentUserSid)) {
+ throw new Error("Unable to identify the current Windows user SID");
+ }
+ const match = WINDOWS_SECURITY_DESCRIPTOR.exec(descriptor.trim());
+ if (match === null) {
+ throw new Error("Windows credential ACL has no owner or DACL");
+ }
+
+ const principalAliases: Readonly<Record<string, string>> = {
+ ...WINDOWS_PRINCIPAL_ALIASES,
+ ...options.resolvedAliases,
+ };
+ const trustedPrincipals = new Set([
+ currentUserSid,
+ WINDOWS_SYSTEM_SID,
+ WINDOWS_ADMINISTRATORS_SID,
+ principalAliases["LA"] ?? "LA",
+ ]);
+ if (options.scope === "ancestor") {
+ trustedPrincipals.add(WINDOWS_TRUSTED_INSTALLER_SID);
+ }
+ const normalizePrincipal = (principal: string): string =>
+ principalAliases[principal] ?? principal;
+ const trustedPrincipal = (principal: string): boolean =>
+ trustedPrincipals.has(principal);
+ const owner = normalizePrincipal(match[1]!);
+ if (!trustedPrincipal(owner)) {
+ throw new UntrustedWindowsCredentialOwnerError(owner);
+ }
+ const flags = match[2]!;
+ if (flags.includes("NO_ACCESS_CONTROL")) {
+ throw new Error("Windows credential ACL grants unrestricted access");
+ }
+
+ let remaining = match[3]!;
+ let grantsCurrentDirectoryAccess = false;
+ let grantsCurrentFileAccess = false;
+ let grantsCurrentContainerAccess = false;
+ let hasAccessRules = false;
+ const untrustedPrincipals = new Set<string>();
+ const deniedPrincipals = new Set<string>();
+ while (remaining.startsWith("(")) {
+ const { rule, rest } = windowsSecurityDescriptorRule(remaining);
+ const fields = rule.split(";");
+ const callback = ["XA", "XD", "ZA"].includes(fields[0]!);
+ if ((callback && fields.length < 7) || (!callback && fields.length !== 6)) {
+ throw new Error("Windows credential ACL has a malformed access rule");
+ }
+ const [
+ type,
+ inheritance,
+ rights,
+ objectGuid,
+ inheritObjectGuid,
+ rawPrincipal,
+ ] = fields;
+ if (!["A", "OA", "D", "OD", "XA", "XD", "ZA"].includes(type!)) {
+ throw new Error("Windows credential ACL has an unsupported access rule");
+ }
+ if (rawPrincipal === "" || rights === "") {
+ throw new Error("Windows credential ACL has an incomplete access rule");
+ }
+ const objectRule = type === "OA" || type === "OD" || type === "ZA";
+ for (const guid of [objectGuid!, inheritObjectGuid!]) {
+ if (guid !== "" && (!objectRule || !WINDOWS_GUID.test(guid))) {
+ throw new Error("Windows credential ACL has a malformed object rule");
+ }
+ }
+ const inheritanceFlags = windowsAceFlags(inheritance!);
+ hasAccessRules = true;
+ const principal = normalizePrincipal(rawPrincipal!);
+ if (type === "A" || type === "OA" || type === "XA" || type === "ZA") {
+ if (!trustedPrincipal(principal)) {
+ if (
+ options.scope !== "ancestor" ||
+ windowsAceAllowsAncestorReplacement(rights!, inheritanceFlags)
+ ) {
+ untrustedPrincipals.add(principal);
+ }
+ } else if (
+ !callback &&
+ objectGuid === "" &&
+ inheritObjectGuid === "" &&
+ principal === currentUserSid &&
+ windowsAceGrantsFullControl(rights!)
+ ) {
+ if (!inheritanceFlags.has("IO")) {
+ grantsCurrentDirectoryAccess = true;
+ }
+ if (inheritanceFlags.has("OI") && !inheritanceFlags.has("NP")) {
+ grantsCurrentFileAccess = true;
+ }
+ if (inheritanceFlags.has("CI") && !inheritanceFlags.has("NP")) {
+ grantsCurrentContainerAccess = true;
+ }
+ }
+ } else {
+ deniedPrincipals.add(principal);
+ }
+ remaining = rest;
+ }
+ if (!hasAccessRules || (remaining !== "" && !remaining.startsWith("S:"))) {
+ throw new Error("Windows credential ACL has an invalid access-rule list");
+ }
+
+ return {
+ owner,
+ protected: flags.includes("P"),
+ grantsCurrentUserAccess:
+ grantsCurrentDirectoryAccess &&
+ (options.scope === "file" ||
+ (grantsCurrentFileAccess && grantsCurrentContainerAccess)) &&
+ deniedPrincipals.size === 0,
+ untrustedPrincipals: [...untrustedPrincipals],
+ deniedPrincipals: [...deniedPrincipals],
+ };
+}
+
+function windowsSecurityDescriptorRule(value: string): {
+ rule: string;
+ rest: string;
+} {
+ let depth = 0;
+ let quoted = false;
+ let escaped = false;
+ for (let index = 0; index < value.length; index += 1) {
+ const character = value[index]!;
+ if (quoted) {
+ if (!escaped && character === '"') quoted = false;
+ escaped = character === "\\" && !escaped;
+ continue;
+ }
+ if (character === '"') {
+ quoted = true;
+ } else if (character === "(") {
+ depth += 1;
+ } else if (character === ")") {
+ depth -= 1;
+ if (depth === 0) {
+ return { rule: value.slice(1, index), rest: value.slice(index + 1) };
+ }
+ }
+ }
+ throw new Error("Windows credential ACL has a malformed rule");
+}
+
+function windowsAceFlags(value: string): ReadonlySet<string> {
+ if (value.length % 2 !== 0) {
+ throw new Error("Windows credential ACL has malformed inheritance flags");
+ }
+ const flags = new Set<string>();
+ for (let offset = 0; offset < value.length; offset += 2) {
+ const flag = value.slice(offset, offset + 2);
+ if (!["OI", "CI", "NP", "IO", "ID"].includes(flag)) {
+ throw new Error(
+ "Windows credential ACL has unsupported inheritance flags",
+ );
+ }
+ flags.add(flag);
+ }
+ return flags;
+}
+
+function windowsAceGrantsFullControl(rights: string): boolean {
+ if (rights === "FA" || rights === "GA") return true;
+ if (!/^0x[\da-f]+$/iu.test(rights)) return false;
+ const mask = BigInt(rights);
+ return (mask & 0x1f01ffn) === 0x1f01ffn || (mask & 0x10000000n) !== 0n;
+}
+
+function windowsAceAllowsAncestorReplacement(
+ rights: string,
+ inheritanceFlags: ReadonlySet<string>,
+): boolean {
+ if (inheritanceFlags.has("IO")) return false;
+ if (/^0x[\da-f]+$/iu.test(rights)) {
+ return (BigInt(rights) & 0x100d0040n) !== 0n;
+ }
+ for (let index = 0; index < rights.length; index += 2) {
+ if (
+ ["FA", "GA", "FW", "GW", "SD", "WD", "WO", "DC", "DT"].includes(
+ rights.slice(index, index + 2),
+ )
+ ) {
+ return true;
+ }
+ }
+ return false;
+}
+
+export async function verifyStableWindowsCredentialDescendants(
+ path: string,
+ inspectDescriptors: () => Promise<number>,
+): Promise<void> {
+ for (let attempt = 0; attempt < 3; attempt += 1) {
+ let descendants = 0;
+ const pending = [path];
+ 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);
+ }
+ }
+ if (descendants === 0) return;
+
+ if ((await inspectDescriptors()) === descendants) return;
+ }
+
+ throw new Error("Windows credential descendants could not be verified");
+}
+
+export async function streamWindowsCredentialAclDescriptors(
+ command: string,
+ args: readonly string[],
+ inspectDescriptor: (descriptor: string) => Promise<void>,
+ options: { environment?: NodeJS.ProcessEnv } = {},
+): Promise<number> {
+ const child = spawn(command, [...args], {
+ env: options.environment,
+ stdio: ["ignore", "pipe", "pipe"],
+ windowsHide: true,
+ });
+ let stderr = "";
+ child.stderr.setEncoding("utf8");
+ child.stderr.on("data", (chunk: string) => {
+ const remaining = MAX_WINDOWS_CREDENTIAL_ACL_STDERR - stderr.length;
+ if (remaining > 0) stderr += chunk.slice(0, remaining);
+ });
+
+ const completion = new Promise<void>((resolve, reject) => {
+ child.once("error", reject);
+ child.once("close", (code, signal) => {
+ if (code === 0) {
+ resolve();
+ return;
+ }
+ const reason = signal === null ? `exit code ${code}` : `signal ${signal}`;
+ reject(
+ Object.assign(
+ new Error(`Windows credential ACL inspection failed with ${reason}`),
+ { code, signal, stderr },
+ ),
+ );
+ });
+ });
+
+ let descriptors = 0;
+ try {
+ await Promise.all([
+ completion,
+ (async () => {
+ const lines = createInterface({
+ input: child.stdout,
+ crlfDelay: Infinity,
+ });
+ for await (const descriptor of lines) {
+ if (descriptor === "") continue;
+ await inspectDescriptor(descriptor);
+ descriptors += 1;
+ }
+ })(),
+ ]);
+ } catch (error) {
+ if (child.exitCode === null && child.signalCode === null) child.kill();
+ throw error;
+ }
+
+ return descriptors;
+}
+
async function secureWindowsCredentialHome(path: string): Promise<void> {
const systemRoot = process.env["SystemRoot"] ?? "C:\\Windows";
+ const systemDirectory = join(systemRoot, "System32");
const powershell = join(
- systemRoot,
- "System32",
+ systemDirectory,
"WindowsPowerShell",
"v1.0",
"powershell.exe",
);
+ const inheritedEnvironment = Object.fromEntries(
+ Object.entries(process.env).filter(
+ ([name]) => name.toUpperCase() !== "PSMODULEPATH",
+ ),
+ );
+ const processOptions = {
+ env: {
+ ...inheritedEnvironment,
+ CODEX_SECURITY_CREDENTIAL_ACL_PATH: path,
+ PSModulePath: join(
+ systemDirectory,
+ "WindowsPowerShell",
+ "v1.0",
+ "Modules",
+ ),
+ },
+ encoding: "utf8" as const,
+ windowsHide: true,
+ maxBuffer: 1024 * 1024,
+ };
+ const identity = await execFile(
+ join(systemDirectory, "whoami.exe"),
+ ["/user", "/fo", "csv", "/nh"],
+ processOptions,
+ );
+ const sid = /^"(?:[^"]|"")*","(S-1-(?:\d+-)*\d+)"$/u.exec(
+ identity.stdout.trim(),
+ )?.[1];
+ if (sid === undefined) {
+ throw new Error("Unable to identify the current Windows user SID");
+ }
+
+ // Signed built-in cmdlets remain available under ConstrainedLanguage;
+ // arbitrary .NET constructors, static methods, and SID translation do not.
const script = [
"$ErrorActionPreference = 'Stop'",
- "$path = [Environment]::GetEnvironmentVariable('CODEX_SECURITY_CREDENTIAL_ACL_PATH', 'Process')",
- "$identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()",
- "if ($null -eq $identity.User) { throw 'Unable to identify the current Windows user' }",
- "$acl = New-Object System.Security.AccessControl.DirectorySecurity",
- "$acl.SetAccessRuleProtection($true, $false)",
- "$inheritance = [System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInherit",
- "$rule = New-Object System.Security.AccessControl.FileSystemAccessRule($identity.User, [System.Security.AccessControl.FileSystemRights]::FullControl, $inheritance, [System.Security.AccessControl.PropagationFlags]::None, [System.Security.AccessControl.AccessControlType]::Allow)",
- "$acl.SetOwner($identity.User)",
- "$acl.SetAccessRule($rule)",
- "[System.IO.Directory]::SetAccessControl($path, $acl)",
- "$verified = [System.IO.Directory]::GetAccessControl($path)",
- "if (-not $verified.AreAccessRulesProtected) { throw 'Credential ACL still inherits access rules' }",
- "$unexpected = @($verified.Access | Where-Object { $_.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Allow -and $_.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value -ne $identity.User.Value })",
- "if ($unexpected.Count -ne 0) { throw 'Credential ACL grants access to another identity' }",
+ "Microsoft.PowerShell.Security\\Get-Acl -LiteralPath $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty Sddl",
].join("; ");
- await execFile(
- powershell,
- ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script],
- {
- env: {
- ...process.env,
- CODEX_SECURITY_CREDENTIAL_ACL_PATH: path,
+ const resolvePrincipalScript = [
+ "$ErrorActionPreference = 'Stop'",
+ "$descriptor = 'O:' + $env:CODEX_SECURITY_CREDENTIAL_PRINCIPAL + 'G:SYD:(A;;GA;;;SY)'",
+ "Microsoft.PowerShell.Utility\\ConvertFrom-SddlString -Sddl $descriptor | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty RawDescriptor | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty Owner | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty Value",
+ ].join("; ");
+ const resolvedAliases: Record<string, string> = {};
+ const resolvePrincipal = async (principal: string): Promise<void> => {
+ if (
+ !/^[A-Z]{2}$/u.test(principal) ||
+ WINDOWS_PRINCIPAL_ALIASES[principal] !== undefined ||
+ resolvedAliases[principal] !== undefined
+ ) {
+ return;
+ }
+ const resolved = await execFile(
+ powershell,
+ [
+ "-NoLogo",
+ "-NoProfile",
+ "-NonInteractive",
+ "-Command",
+ resolvePrincipalScript,
+ ],
+ {
+ ...processOptions,
+ env: {
+ ...processOptions.env,
+ CODEX_SECURITY_CREDENTIAL_PRINCIPAL: principal,
+ },
},
- encoding: "utf8",
- windowsHide: true,
- maxBuffer: 1024 * 1024,
- },
+ );
+ const numeric = resolved.stdout.trim();
+ if (!WINDOWS_SID.test(numeric)) {
+ throw new Error(
+ "Windows credential ACL contains an unresolvable identity",
+ );
+ }
+ resolvedAliases[principal] = numeric;
+ };
+ const resolveDescriptorAliases = async (
+ descriptor: string,
+ ): Promise<void> => {
+ const header = WINDOWS_SECURITY_DESCRIPTOR.exec(descriptor.trim());
+ if (header === null) return;
+ await resolvePrincipal(header[1]!);
+ let remaining = header[3]!;
+ while (remaining.startsWith("(")) {
+ const { rule, rest } = windowsSecurityDescriptorRule(remaining);
+ const principal = rule.split(";")[5];
+ if (principal !== undefined) await resolvePrincipal(principal);
+ remaining = rest;
+ }
+ };
+ const readAcl = async (): Promise<WindowsCredentialAcl> => {
+ const descriptor = await execFile(
+ powershell,
+ ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script],
+ processOptions,
+ );
+ try {
+ await resolveDescriptorAliases(descriptor.stdout);
+ return inspectWindowsCredentialAcl(descriptor.stdout, sid, {
+ resolvedAliases,
+ });
+ } catch (error) {
+ if (error instanceof UntrustedWindowsCredentialOwnerError) throw error;
+ throw new RepairableWindowsCredentialAclError(error);
+ }
+ };
+
+ const icacls = join(systemDirectory, "icacls.exe");
+ const installTrustedAcl = async (target = path): Promise<void> => {
+ await execFile(
+ icacls,
+ [
+ target,
+ "/inheritance:r",
+ "/grant:r",
+ `*${sid}:(OI)(CI)F`,
+ `*${WINDOWS_SYSTEM_SID}:(OI)(CI)F`,
+ `*${WINDOWS_ADMINISTRATORS_SID}:(OI)(CI)F`,
+ ],
+ processOptions,
+ );
+ };
+ const ancestorScript = [
+ "$ErrorActionPreference = 'Stop'",
+ "$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 }",
+ ].join("; ");
+ const ancestorPaths: string[] = [];
+ for (let ancestor = dirname(path); ; ancestor = dirname(ancestor)) {
+ ancestorPaths.push(ancestor);
+ if (ancestor === dirname(ancestor)) break;
+ }
+ const ancestry = await execFile(
+ powershell,
+ ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", ancestorScript],
+ processOptions,
);
+ const ancestorDescriptors = ancestry.stdout
+ .split(/\r?\n/u)
+ .filter((descriptor) => descriptor !== "");
+ if (ancestorDescriptors.length !== ancestorPaths.length) {
+ throw new Error("Windows credential-home ancestry could not be verified");
+ }
+ for (const descriptor of ancestorDescriptors) {
+ await resolveDescriptorAliases(descriptor);
+ const ancestor = inspectWindowsCredentialAcl(descriptor, sid, {
+ resolvedAliases,
+ scope: "ancestor",
+ });
+ if (ancestor.untrustedPrincipals.length === 0) continue;
+ throw new Error(
+ "Windows credential-home ancestor allows another identity to replace the directory",
+ );
+ }
+
+ const descendantsArePrivate = async (): Promise<boolean> => {
+ const descendantScript = [
+ "$ErrorActionPreference = 'Stop'",
+ "Microsoft.PowerShell.Management\\Get-ChildItem -LiteralPath $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH -Recurse -Force | Microsoft.PowerShell.Security\\Get-Acl | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty Sddl",
+ ].join("; ");
+ let privateDescendants = true;
+ await verifyStableWindowsCredentialDescendants(path, async () => {
+ privateDescendants = true;
+ return streamWindowsCredentialAclDescriptors(
+ powershell,
+ [
+ "-NoLogo",
+ "-NoProfile",
+ "-NonInteractive",
+ "-Command",
+ descendantScript,
+ ],
+ async (descriptor) => {
+ await resolveDescriptorAliases(descriptor);
+ const descendant = inspectWindowsCredentialAcl(descriptor, sid, {
+ resolvedAliases,
+ scope: "file",
+ });
+ if (
+ !descendant.grantsCurrentUserAccess ||
+ descendant.untrustedPrincipals.length !== 0
+ ) {
+ privateDescendants = false;
+ }
+ },
+ { environment: processOptions.env },
+ );
+ });
+ return privateDescendants;
+ };
+
+ let existing: WindowsCredentialAcl | undefined;
+ for (let attempt = 0; existing === undefined && attempt < 3; attempt += 1) {
+ try {
+ existing = await readAcl();
+ } catch (error) {
+ if (error instanceof UntrustedWindowsCredentialOwnerError) {
+ await execFile(icacls, [path, "/setowner", `*${sid}`], processOptions);
+ } else if (error instanceof RepairableWindowsCredentialAclError) {
+ await installTrustedAcl();
+ } else {
+ throw error;
+ }
+ }
+ }
+ if (existing === undefined) {
+ throw new Error("Windows credential ACL could not be repaired");
+ }
+ if (
+ existing.grantsCurrentUserAccess &&
+ existing.untrustedPrincipals.length === 0 &&
+ !existing.protected
+ ) {
+ await execFile(icacls, [path, "/inheritance:d"], processOptions);
+ existing = await readAcl();
+ }
+
+ let verified = existing;
+ if (
+ !verified.protected ||
+ !verified.grantsCurrentUserAccess ||
+ verified.untrustedPrincipals.length !== 0
+ ) {
+ await installTrustedAcl();
+ verified = await readAcl();
+ for (const principal of verified.untrustedPrincipals) {
+ if (!WINDOWS_SID.test(principal)) {
+ throw new Error(
+ "Windows credential ACL contains an unresolvable identity",
+ );
+ }
+ await execFile(
+ icacls,
+ [path, "/remove:g", `*${principal}`],
+ processOptions,
+ );
+ }
+ for (const principal of verified.deniedPrincipals) {
+ if (!WINDOWS_SID.test(principal)) {
+ throw new Error(
+ "Windows credential ACL contains an unresolvable identity",
+ );
+ }
+ await execFile(
+ icacls,
+ [path, "/remove:d", `*${principal}`],
+ processOptions,
+ );
+ }
+ if (
+ verified.untrustedPrincipals.length !== 0 ||
+ verified.deniedPrincipals.length !== 0
+ ) {
+ verified = await readAcl();
+ }
+ }
+ if (!verified.protected) {
+ throw new Error("Windows credential ACL still inherits access rules");
+ }
+ if (!verified.grantsCurrentUserAccess) {
+ throw new Error(
+ "Windows credential ACL does not grant the current user access",
+ );
+ }
+ if (verified.untrustedPrincipals.length !== 0) {
+ throw new Error("Windows credential ACL grants access to another identity");
+ }
+ if (!(await descendantsArePrivate())) {
+ await execFile(
+ icacls,
+ [join(path, "*"), "/reset", "/t", "/q"],
+ processOptions,
+ );
+ if (!(await descendantsArePrivate())) {
+ throw new Error("Windows credential descendants remain accessible");
+ }
+ }
}
export async function acquireCodexSecurityCredentialHomeLock(
diff --git a/sdk/typescript/tests-ts/cli-authentication.test.ts b/sdk/typescript/tests-ts/cli-authentication.test.ts
index 287918eab..1a8ad98ef 100644
--- a/sdk/typescript/tests-ts/cli-authentication.test.ts
+++ b/sdk/typescript/tests-ts/cli-authentication.test.ts
@@ -655,7 +655,7 @@ describe("CLI authentication", () => {
} finally {
await rm(root, { recursive: true, force: true });
}
- }, 30_000);
+ }, 60_000);
test("reports selected scan credentials without contaminating JSON output", async () => {
const stdout = capture();
diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.ts
index 3646f2785..6ce95cf5d 100644
--- a/sdk/typescript/tests-ts/runtime.test.ts
+++ b/sdk/typescript/tests-ts/runtime.test.ts
@@ -28,6 +28,7 @@ import {
relative,
sep,
} from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
import { brotliDecompressSync } from "node:zlib";
import { afterEach, describe, expect, mock, test } from "bun:test";
import { strToU8, zipSync } from "fflate";
@@ -55,6 +56,7 @@ import {
codexSecurityHasStoredFileCredentials,
codexSecurityStateDirectory,
codexPlatformPackage,
+ inspectWindowsCredentialAcl,
isPythonPathCandidate,
planOutputArchive,
prepareCodexSecurityCredentialHome,
@@ -67,6 +69,8 @@ import {
requireTrustedOutputAncestor,
runWorkbench,
setCodexSecurityCredentialLogout,
+ streamWindowsCredentialAclDescriptors,
+ verifyStableWindowsCredentialDescendants,
} from "../src/runtime.js";
import { PLUGIN_ROOT } from "./plugin-root.js";
@@ -1811,6 +1815,517 @@ 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("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("streams Windows credential ACL output larger than the subprocess buffer", async () => {
+ const descriptor =
+ "O:S-1-5-21-111-222-333-1001G:SYD:P(A;;FA;;;S-1-5-21-111-222-333-1001)";
+ const expected = Math.ceil((1024 * 1024) / (descriptor.length + 1)) + 1;
+ let observed = 0;
+
+ const count = await streamWindowsCredentialAclDescriptors(
+ process.execPath,
+ [
+ "--eval",
+ `process.stdout.write(${JSON.stringify(`${descriptor}\n`)}.repeat(${expected}))`,
+ ],
+ async (received) => {
+ if (observed === 0 || observed === expected - 1) {
+ expect(received).toBe(descriptor);
+ }
+ observed += 1;
+ },
+ );
+
+ expect(count).toBe(expected);
+ expect(observed).toBe(expected);
+ });
+
+ test("preserves Windows credential ACL subprocess failures while streaming", async () => {
+ await expect(
+ streamWindowsCredentialAclDescriptors(
+ process.execPath,
+ [
+ "--eval",
+ 'process.stderr.write("synthetic ACL inspection failure"); process.exitCode = 1',
+ ],
+ async () => {},
+ ),
+ ).rejects.toMatchObject({ stderr: "synthetic ACL inspection failure" });
+ });
+
+ test("accepts managed Windows ACLs with trusted system principals", () => {
+ const user = "S-1-5-21-111-222-333-1001";
+ const descriptor =
+ `O:${user}G:${user}D:AI` +
+ `(A;OICIID;FA;;;${user})` +
+ "(A;OICIID;FA;;;SY)" +
+ "(A;OICIID;FA;;;BA)";
+
+ expect(inspectWindowsCredentialAcl(descriptor, user)).toEqual({
+ owner: user,
+ protected: false,
+ grantsCurrentUserAccess: true,
+ untrustedPrincipals: [],
+ deniedPrincipals: [],
+ });
+ expect(
+ inspectWindowsCredentialAcl(
+ `O:BAG:SYD:P(A;OICI;FA;;;${user})(A;OICI;FA;;;SY)`,
+ user,
+ ),
+ ).toMatchObject({
+ owner: "S-1-5-32-544",
+ protected: true,
+ untrustedPrincipals: [],
+ });
+ });
+
+ test("identifies Windows ancestor grants that can replace credential homes", () => {
+ const user = "S-1-5-21-111-222-333-1001";
+ for (const rights of [
+ "FA",
+ "GA",
+ "FW",
+ "GW",
+ "GAGX",
+ "GXGA",
+ "GWGX",
+ "GXGW",
+ "FAGX",
+ "FWGX",
+ "SD",
+ "WD",
+ "WO",
+ "DC",
+ "0x40",
+ "0x10000",
+ "0x40000",
+ "0x80000",
+ "0x1301bf",
+ ]) {
+ expect(
+ inspectWindowsCredentialAcl(
+ `O:${user}G:SYD:(A;OICI;FA;;;${user})(A;;${rights};;;WD)`,
+ user,
+ { scope: "ancestor" },
+ ).untrustedPrincipals,
+ ).toEqual(["S-1-1-0"]);
+ }
+
+ for (const [flags, rights] of [
+ ["", "FR"],
+ ["", "FRGX"],
+ ["", "GRGX"],
+ ["", "0x1200a9"],
+ ["IO", "FA"],
+ ] as const) {
+ expect(
+ inspectWindowsCredentialAcl(
+ `O:${user}G:SYD:(A;OICI;FA;;;${user})(A;${flags};${rights};;;WD)`,
+ user,
+ { scope: "ancestor" },
+ ).untrustedPrincipals,
+ ).toEqual([]);
+ }
+
+ const service = "S-1-5-80-111-222-333-444-555";
+ for (const [principal, expected] of [
+ ["LS", "S-1-5-19"],
+ ["NS", "S-1-5-20"],
+ [service, service],
+ ] as const) {
+ expect(
+ inspectWindowsCredentialAcl(
+ `O:${user}G:SYD:(A;OICI;FA;;;${user})(A;;DC;;;${principal})`,
+ user,
+ { scope: "ancestor" },
+ ).untrustedPrincipals,
+ ).toEqual([expected]);
+ }
+ expect(() =>
+ inspectWindowsCredentialAcl(
+ `O:${service}G:SYD:(A;OICI;FA;;;${user})`,
+ user,
+ { scope: "ancestor" },
+ ),
+ ).toThrow("owner is not a trusted principal");
+
+ const installer =
+ "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464";
+ expect(
+ inspectWindowsCredentialAcl(
+ `O:${installer}G:SYD:(A;OICI;FA;;;${installer})(A;OICI;FA;;;${user})`,
+ user,
+ { scope: "ancestor" },
+ ).untrustedPrincipals,
+ ).toEqual([]);
+ expect(() =>
+ inspectWindowsCredentialAcl(
+ `O:${installer}G:SYD:(A;OICI;FA;;;${user})`,
+ user,
+ ),
+ ).toThrow("owner is not a trusted principal");
+ });
+
+ test("accepts private credential-file ACLs without inheritance flags", () => {
+ const user = "S-1-5-21-111-222-333-1001";
+ const descriptor = `O:${user}G:SYD:P(A;;FA;;;${user})(A;;FA;;;SY)`;
+
+ expect(inspectWindowsCredentialAcl(descriptor, user)).toMatchObject({
+ grantsCurrentUserAccess: false,
+ });
+ expect(
+ inspectWindowsCredentialAcl(descriptor, user, { scope: "file" }),
+ ).toMatchObject({
+ grantsCurrentUserAccess: true,
+ untrustedPrincipals: [],
+ });
+ });
+
+ test("identifies broad, foreign, and inherited Windows ACL grants", () => {
+ const user = "S-1-5-21-111-222-333-1001";
+ const stranger = "S-1-5-21-111-222-333-1002";
+ for (const [principal, expected] of [
+ ["WD", "S-1-1-0"],
+ ["BU", "S-1-5-32-545"],
+ ["AU", "S-1-5-11"],
+ ["CO", "S-1-3-0"],
+ ["CG", "S-1-3-1"],
+ ["OW", "S-1-3-4"],
+ ["AC", "S-1-15-2-1"],
+ ["AN", "S-1-5-7"],
+ ["IU", "S-1-5-4"],
+ ["SU", "S-1-5-6"],
+ ["RD", "S-1-5-32-555"],
+ ["DA", "S-1-5-21-111-222-333-512"],
+ ["DU", "S-1-5-21-111-222-333-513"],
+ [stranger, stranger],
+ ] as const) {
+ expect(
+ inspectWindowsCredentialAcl(
+ `O:${user}G:${user}D:AI(A;OICIID;FA;;;${user})(A;OICIID;FR;;;${principal})`,
+ user,
+ {
+ resolvedAliases: {
+ DA: "S-1-5-21-111-222-333-512",
+ DU: "S-1-5-21-111-222-333-513",
+ },
+ },
+ ).untrustedPrincipals,
+ ).toEqual([expected]);
+ }
+ expect(
+ inspectWindowsCredentialAcl(
+ `O:${user}G:${user}D:P(D;OICI;FR;;;WD)(A;OICI;FA;;;${user})`,
+ user,
+ ),
+ ).toMatchObject({
+ grantsCurrentUserAccess: false,
+ untrustedPrincipals: [],
+ deniedPrincipals: ["S-1-1-0"],
+ });
+ });
+
+ test("requires effective, inheritable Windows credential access", () => {
+ const user = "S-1-5-21-111-222-333-1001";
+ for (const [flags, rights] of [
+ ["OICI", "FR"],
+ ["OICI", "FW"],
+ ["", "FA"],
+ ["OI", "FA"],
+ ["CI", "FA"],
+ ["OICIIO", "FA"],
+ ["OICINP", "FA"],
+ ["OICINPID", "FA"],
+ ["CIIOID", "FA"],
+ ] as const) {
+ expect(
+ inspectWindowsCredentialAcl(
+ `O:${user}G:${user}D:P(A;${flags};${rights};;;${user})`,
+ user,
+ ).grantsCurrentUserAccess,
+ ).toBe(false);
+ }
+
+ for (const rights of ["FA", "GA", "0x1f01ff", "0x10000000"]) {
+ expect(
+ inspectWindowsCredentialAcl(
+ `O:${user}G:${user}D:P(A;OICI;${rights};;;${user})`,
+ user,
+ ).grantsCurrentUserAccess,
+ ).toBe(true);
+ }
+
+ expect(
+ inspectWindowsCredentialAcl(
+ `O:${user}G:${user}D:P(A;;FA;;;${user})(A;OICIIO;FA;;;${user})`,
+ user,
+ ).grantsCurrentUserAccess,
+ ).toBe(true);
+ expect(
+ inspectWindowsCredentialAcl(
+ `O:${user}G:${user}D:P(A;CIOI;FA;;;${user})`,
+ user,
+ ).grantsCurrentUserAccess,
+ ).toBe(true);
+ expect(
+ inspectWindowsCredentialAcl(
+ `O:${user}G:${user}D:P(A;;FA;;;${user})(A;OINP;FA;;;${user})(A;CI;FA;;;${user})`,
+ user,
+ ).grantsCurrentUserAccess,
+ ).toBe(false);
+ });
+
+ test("normalizes built-in Windows user and service SID aliases", () => {
+ for (const [alias, user] of [
+ ["SY", "S-1-5-18"],
+ ["LS", "S-1-5-19"],
+ ["NS", "S-1-5-20"],
+ ["LA", "S-1-5-21-111-222-333-500"],
+ ["LG", "S-1-5-21-111-222-333-501"],
+ ] as const) {
+ expect(
+ inspectWindowsCredentialAcl(
+ `O:${alias}G:SYD:P(A;OICI;FA;;;${alias})(A;OICI;FA;;;BA)`,
+ user,
+ {
+ resolvedAliases:
+ alias === "LA" || alias === "LG" ? { [alias]: user } : {},
+ },
+ ),
+ ).toMatchObject({
+ owner: user,
+ protected: true,
+ grantsCurrentUserAccess: true,
+ untrustedPrincipals: [],
+ deniedPrincipals: [],
+ });
+ }
+ });
+
+ test("does not confuse domain accounts with local Administrator or Guest", () => {
+ const administrator = "S-1-5-21-111-222-333-500";
+ const guest = "S-1-5-21-111-222-333-501";
+ const localAdministrator = "S-1-5-21-444-555-666-500";
+ const localGuest = "S-1-5-21-444-555-666-501";
+
+ expect(
+ inspectWindowsCredentialAcl(
+ `O:LAG:SYD:P(A;OICI;FA;;;LA)(A;OICI;FA;;;BA)`,
+ administrator,
+ { resolvedAliases: { LA: localAdministrator } },
+ ),
+ ).toMatchObject({
+ owner: localAdministrator,
+ grantsCurrentUserAccess: false,
+ });
+ expect(
+ inspectWindowsCredentialAcl(
+ `O:${guest}G:SYD:P(A;OICI;FA;;;${guest})(A;OICI;FA;;;LG)`,
+ guest,
+ { resolvedAliases: { LG: localGuest } },
+ ).untrustedPrincipals,
+ ).toEqual([localGuest]);
+ expect(() =>
+ inspectWindowsCredentialAcl(
+ `O:LGG:SYD:P(A;OICI;FA;;;${guest})(A;OICI;FA;;;LG)`,
+ guest,
+ { resolvedAliases: { LG: localGuest } },
+ ),
+ ).toThrow("owner is not a trusted principal");
+ });
+
+ test("resolves domain and forest aliases against their actual SID domain", () => {
+ const currentUser = "S-1-5-21-111-222-333-1001";
+ const joinedDomainAdmins = "S-1-5-21-444-555-666-512";
+ const forestRootAdmins = "S-1-5-21-777-888-999-519";
+ const domainRasServers = "S-1-5-21-444-555-666-553";
+
+ expect(
+ inspectWindowsCredentialAcl(
+ `O:${currentUser}G:SYD:P(A;OICI;FA;;;${currentUser})(A;OICI;FR;;;DA)(A;OICI;FR;;;EA)(A;OICI;FR;;;RS)`,
+ currentUser,
+ {
+ resolvedAliases: {
+ DA: joinedDomainAdmins,
+ EA: forestRootAdmins,
+ RS: domainRasServers,
+ },
+ },
+ ).untrustedPrincipals,
+ ).toEqual([joinedDomainAdmins, forestRootAdmins, domainRasServers]);
+ });
+
+ test("classifies conditional Windows access rules without trusting callbacks", () => {
+ const user = "S-1-5-21-111-222-333-1001";
+ const condition = '(@User.department == "(Managed;QA)")';
+
+ expect(
+ inspectWindowsCredentialAcl(
+ `O:${user}G:SYD:P(A;OICI;FA;;;${user})(XA;OICI;FR;;;WD;${condition})`,
+ user,
+ ),
+ ).toMatchObject({
+ grantsCurrentUserAccess: true,
+ untrustedPrincipals: ["S-1-1-0"],
+ });
+ expect(
+ inspectWindowsCredentialAcl(
+ `O:${user}G:SYD:P(XA;OICI;FA;;;${user};${condition})`,
+ user,
+ ).grantsCurrentUserAccess,
+ ).toBe(false);
+ expect(
+ inspectWindowsCredentialAcl(
+ `O:${user}G:SYD:P(A;OICI;FA;;;${user})(ZA;OICI;FR;;;WD;${condition})`,
+ user,
+ ),
+ ).toMatchObject({
+ grantsCurrentUserAccess: true,
+ untrustedPrincipals: ["S-1-1-0"],
+ });
+ expect(
+ inspectWindowsCredentialAcl(
+ `O:${user}G:SYD:P(ZA;OICI;FA;;;${user};${condition})`,
+ user,
+ ).grantsCurrentUserAccess,
+ ).toBe(false);
+ expect(
+ inspectWindowsCredentialAcl(
+ `O:${user}G:SYD:P(A;OICI;FA;;;${user})(XD;OICI;FR;;;WD;${condition})`,
+ user,
+ ),
+ ).toMatchObject({
+ grantsCurrentUserAccess: false,
+ deniedPrincipals: ["S-1-1-0"],
+ });
+ });
+
+ test("classifies object-specific Windows ACLs without treating them as unrestricted", () => {
+ const user = "S-1-5-21-111-222-333-1001";
+ const guid = "bf967aba-0de6-11d0-a285-00aa003049e2";
+
+ expect(
+ inspectWindowsCredentialAcl(
+ `O:${user}G:SYD:P(A;OICI;FA;;;${user})(OA;OICI;FR;${guid};;WD)`,
+ user,
+ ),
+ ).toMatchObject({
+ grantsCurrentUserAccess: true,
+ untrustedPrincipals: ["S-1-1-0"],
+ });
+ expect(
+ inspectWindowsCredentialAcl(
+ `O:${user}G:SYD:P(OA;OICI;FA;${guid};;${user})`,
+ user,
+ ).grantsCurrentUserAccess,
+ ).toBe(false);
+ expect(
+ inspectWindowsCredentialAcl(
+ `O:${user}G:SYD:P(A;OICI;FA;;;${user})(OD;OICI;FR;;${guid};WD)`,
+ user,
+ ),
+ ).toMatchObject({
+ grantsCurrentUserAccess: false,
+ deniedPrincipals: ["S-1-1-0"],
+ });
+ });
+
+ test("rejects incomplete, unowned, and unsupported Windows ACLs", () => {
+ const user = "S-1-5-21-111-222-333-1001";
+ const stranger = "S-1-5-21-111-222-333-1002";
+ for (const descriptor of [
+ `G:${user}D:P(A;OICI;FA;;;${user})`,
+ `O:${user}G:${user}`,
+ `O:${user}G:${user}D:NO_ACCESS_CONTROL`,
+ `O:${user}G:${user}D:P`,
+ `O:${stranger}G:${user}D:P(A;OICI;FA;;;${user})`,
+ `O:${user}G:${user}D:P(XA;OICI;FA;;;${user})`,
+ `O:${user}G:${user}D:P(A;OIN;FA;;;${user})`,
+ `O:${user}G:${user}D:P(A;ZZ;FA;;;${user})`,
+ `O:${user}G:${user}D:P(OA;OICI;FA;not-a-guid;;${user})`,
+ `O:${user}G:${user}D:P(A;OICI;FA;bf967aba-0de6-11d0-a285-00aa003049e2;;${user})`,
+ `O:${user}G:${user}D:P(A;OICI;FA;;;${user};(@User.Department == \"QA\"))`,
+ ]) {
+ expect(() => inspectWindowsCredentialAcl(descriptor, user)).toThrow();
+ }
+ expect(() =>
+ inspectWindowsCredentialAcl(
+ `O:${user}G:${user}D:P(A;OICI;FA;;;${user})`,
+ "not-a-sid",
+ ),
+ ).toThrow("current Windows user SID");
+ expect(
+ inspectWindowsCredentialAcl(
+ `O:${user}G:${user}D:P(A;OICIIO;FA;;;${user})`,
+ user,
+ ).grantsCurrentUserAccess,
+ ).toBe(false);
+ });
+
+ test("surfaces redacted Windows ACL subprocess failures", async () => {
+ const root = await temporaryDirectory();
+ const home = join(root, "home");
+ await mkdir(home);
+ const metadata = await lstat(home);
+ const underlying = Object.assign(new Error("PowerShell failed"), {
+ stderr:
+ "Method invocation is supported only on core types in this language mode. " +
+ "token=sk-proj-SYNTHETIC_WINDOWS_ACL_SECRET_123",
+ });
+
+ try {
+ await requirePrivateCredentialHome(metadata, home, {
+ platform: "win32",
+ secureWindowsHome: async () => {
+ throw underlying;
+ },
+ });
+ throw new Error("expected the Windows ACL operation to fail");
+ } catch (error) {
+ expect(error).toBeInstanceOf(Error);
+ expect((error as Error).message).toContain("core types");
+ expect((error as Error).message).toContain("token=[redacted]");
+ expect((error as Error).message).not.toContain(
+ "SYNTHETIC_WINDOWS_ACL_SECRET",
+ );
+ expect((error as Error).cause).toBe(underlying);
+ }
+ });
+
test("revalidates the Windows credential ACL every time the home is used", async () => {
const root = await temporaryDirectory();
const home = join(root, "home");
@@ -1836,7 +2351,7 @@ describe("runtime directories and plugin Python boundary", () => {
});
test.skipIf(process.platform !== "win32")(
- "creates credential homes with a verified current-user-only Windows ACL",
+ "creates credential homes with a verified managed-compatible Windows ACL",
async () => {
const root = await temporaryDirectory();
const home = await prepareCodexSecurityCredentialHome({
@@ -1854,8 +2369,9 @@ describe("runtime directories and plugin Python boundary", () => {
"$path = [Environment]::GetEnvironmentVariable('CODEX_SECURITY_TEST_ACL_PATH', 'Process')",
"$identity = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value",
"$acl = [System.IO.Directory]::GetAccessControl($path)",
- "$unexpected = @($acl.Access | Where-Object { $_.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Allow -and $_.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value -ne $identity })",
- "[pscustomobject]@{ protected = $acl.AreAccessRulesProtected; unexpected = $unexpected.Count } | ConvertTo-Json -Compress",
+ "$trusted = @($identity, 'S-1-5-18', 'S-1-5-32-544')",
+ "$unexpected = @($acl.Access | Where-Object { $_.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Allow -and $trusted -notcontains $_.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value })",
+ "[pscustomobject]@{ unexpected = $unexpected.Count } | ConvertTo-Json -Compress",
].join("; ");
const result = spawnSync(
powershell,
@@ -1868,14 +2384,519 @@ describe("runtime directories and plugin Python boundary", () => {
},
);
+ expect(result.status).toBe(0);
+ expect(JSON.parse(result.stdout)).toEqual({ unexpected: 0 });
+ },
+ );
+
+ test.skipIf(process.platform !== "win32")(
+ "preserves SYSTEM and Administrators when protecting inherited access",
+ async () => {
+ const root = await temporaryDirectory();
+ const state = join(root, "state");
+ await mkdir(state);
+ const systemDirectory = join(
+ process.env["SystemRoot"] ?? "C:\\Windows",
+ "System32",
+ );
+ const user = spawnSync(
+ join(systemDirectory, "whoami.exe"),
+ ["/user", "/fo", "csv", "/nh"],
+ { encoding: "utf8", windowsHide: true },
+ );
+ expect(user.status).toBe(0);
+ const sid = /"(S-1-(?:\d+-)*\d+)"\s*$/u.exec(user.stdout)?.[1];
+ expect(sid).toBeDefined();
+ const configured = spawnSync(
+ join(systemDirectory, "icacls.exe"),
+ [
+ state,
+ "/inheritance:r",
+ "/grant:r",
+ `*${sid}:(OI)(CI)F`,
+ "*S-1-5-18:(OI)(CI)F",
+ "*S-1-5-32-544:(OI)(CI)F",
+ ],
+ { encoding: "utf8", windowsHide: true },
+ );
+ expect(configured.status).toBe(0);
+
+ const home = await prepareCodexSecurityCredentialHome({
+ CODEX_SECURITY_STATE_DIR: state,
+ });
+ const descriptor = spawnSync(
+ join(systemDirectory, "WindowsPowerShell", "v1.0", "powershell.exe"),
+ [
+ "-NoLogo",
+ "-NoProfile",
+ "-NonInteractive",
+ "-Command",
+ [
+ "$acl = [System.IO.Directory]::GetAccessControl($env:CODEX_SECURITY_TEST_ACL_PATH)",
+ "$allowed = @($acl.Access | Where-Object { $_.AccessControlType -eq 'Allow' })",
+ "$denied = @($acl.Access | Where-Object { $_.AccessControlType -eq 'Deny' })",
+ "$owner = $acl.GetOwner([System.Security.Principal.SecurityIdentifier]).Value",
+ "$principals = @($allowed | ForEach-Object { $_.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value })",
+ "$deniedPrincipals = @($denied | ForEach-Object { $_.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value })",
+ "$fullControl = @($allowed | Where-Object { $_.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value -eq $env:CODEX_SECURITY_TEST_USER_SID -and ($_.FileSystemRights -band [System.Security.AccessControl.FileSystemRights]::FullControl) -eq [System.Security.AccessControl.FileSystemRights]::FullControl -and ($_.InheritanceFlags -band [System.Security.AccessControl.InheritanceFlags]::ContainerInherit) -ne 0 -and ($_.InheritanceFlags -band [System.Security.AccessControl.InheritanceFlags]::ObjectInherit) -ne 0 -and $_.PropagationFlags -eq [System.Security.AccessControl.PropagationFlags]::None })",
+ "[pscustomobject]@{ owner = $owner; protected = $acl.AreAccessRulesProtected; principals = $principals; deniedPrincipals = $deniedPrincipals; grantsCurrentUserAccess = ($fullControl.Count -gt 0 -and $denied.Count -eq 0) } | ConvertTo-Json -Compress",
+ ].join("; "),
+ ],
+ {
+ encoding: "utf8",
+ env: {
+ ...process.env,
+ CODEX_SECURITY_TEST_ACL_PATH: home,
+ CODEX_SECURITY_TEST_USER_SID: sid!,
+ },
+ windowsHide: true,
+ },
+ );
+ expect(descriptor.status).toBe(0);
+ const access = JSON.parse(descriptor.stdout) as {
+ owner: string;
+ protected: boolean;
+ principals: string[];
+ deniedPrincipals: string[];
+ grantsCurrentUserAccess: boolean;
+ };
+ expect(access).toMatchObject({
+ protected: true,
+ deniedPrincipals: [],
+ grantsCurrentUserAccess: true,
+ });
+ expect(access.principals).toEqual(
+ expect.arrayContaining([sid!, "S-1-5-18", "S-1-5-32-544"]),
+ );
+ expect([sid!, "S-1-5-18", "S-1-5-32-544"]).toContain(access.owner);
+ expect(new Set(access.principals)).toEqual(
+ new Set([sid!, "S-1-5-18", "S-1-5-32-544"]),
+ );
+ },
+ );
+
+ test.skipIf(process.platform !== "win32")(
+ "removes unsafe inherited Windows credential-home permissions",
+ async () => {
+ const root = await temporaryDirectory();
+ const state = join(root, "state");
+ await mkdir(state);
+ const systemDirectory = join(
+ process.env["SystemRoot"] ?? "C:\\Windows",
+ "System32",
+ );
+ const shared = spawnSync(
+ join(systemDirectory, "icacls.exe"),
+ [state, "/grant", "*S-1-1-0:(OI)(CI)R"],
+ { encoding: "utf8", windowsHide: true },
+ );
+ expect(shared.status).toBe(0);
+
+ const home = await prepareCodexSecurityCredentialHome({
+ CODEX_SECURITY_STATE_DIR: state,
+ });
+ const result = spawnSync(
+ join(systemDirectory, "WindowsPowerShell", "v1.0", "powershell.exe"),
+ [
+ "-NoLogo",
+ "-NoProfile",
+ "-NonInteractive",
+ "-Command",
+ [
+ "$acl = [System.IO.Directory]::GetAccessControl($env:CODEX_SECURITY_TEST_ACL_PATH)",
+ "$everyone = @($acl.Access | Where-Object { $_.AccessControlType -eq 'Allow' -and $_.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value -eq 'S-1-1-0' })",
+ "[pscustomobject]@{ protected = $acl.AreAccessRulesProtected; everyone = $everyone.Count } | ConvertTo-Json -Compress",
+ ].join("; "),
+ ],
+ {
+ encoding: "utf8",
+ env: { ...process.env, CODEX_SECURITY_TEST_ACL_PATH: home },
+ windowsHide: true,
+ },
+ );
expect(result.status).toBe(0);
expect(JSON.parse(result.stdout)).toEqual({
protected: true,
- unexpected: 0,
+ everyone: 0,
});
},
);
+ test.skipIf(process.platform !== "win32")(
+ "removes explicit foreign Windows credential-home grants",
+ async () => {
+ const root = await temporaryDirectory();
+ const state = join(root, "state");
+ const home = join(state, "codex-home");
+ await mkdir(home, { recursive: true });
+ const systemDirectory = join(
+ process.env["SystemRoot"] ?? "C:\\Windows",
+ "System32",
+ );
+ const configured = spawnSync(
+ join(systemDirectory, "icacls.exe"),
+ [home, "/grant", "*S-1-1-0:(OI)(CI)R"],
+ { encoding: "utf8", windowsHide: true },
+ );
+ expect(configured.status).toBe(0);
+
+ expect(
+ await prepareCodexSecurityCredentialHome({
+ CODEX_SECURITY_STATE_DIR: state,
+ }),
+ ).toBe(await realpath(home));
+ const result = spawnSync(
+ join(systemDirectory, "WindowsPowerShell", "v1.0", "powershell.exe"),
+ [
+ "-NoLogo",
+ "-NoProfile",
+ "-NonInteractive",
+ "-Command",
+ [
+ "$acl = [System.IO.Directory]::GetAccessControl($env:CODEX_SECURITY_TEST_ACL_PATH)",
+ "$everyone = @($acl.Access | Where-Object { $_.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value -eq 'S-1-1-0' })",
+ "[pscustomobject]@{ protected = $acl.AreAccessRulesProtected; everyone = $everyone.Count } | ConvertTo-Json -Compress",
+ ].join("; "),
+ ],
+ {
+ encoding: "utf8",
+ env: { ...process.env, CODEX_SECURITY_TEST_ACL_PATH: home },
+ windowsHide: true,
+ },
+ );
+ expect(result.status).toBe(0);
+ expect(JSON.parse(result.stdout)).toEqual({
+ protected: true,
+ everyone: 0,
+ });
+ },
+ );
+
+ test.skipIf(process.platform !== "win32")(
+ "rejects attacker-writable Windows credential-home ancestry without changing it",
+ async () => {
+ const root = await temporaryDirectory();
+ const state = join(root, "state");
+ await mkdir(state);
+ const systemDirectory = join(
+ process.env["SystemRoot"] ?? "C:\\Windows",
+ "System32",
+ );
+ const identity = spawnSync(
+ join(systemDirectory, "whoami.exe"),
+ ["/user", "/fo", "csv", "/nh"],
+ { encoding: "utf8", windowsHide: true },
+ );
+ expect(identity.status).toBe(0);
+ const sid = /"(S-1-(?:\d+-)*\d+)"\s*$/u.exec(identity.stdout)?.[1];
+ expect(sid).toBeDefined();
+ for (const ancestor of [root, state]) {
+ const owned = spawnSync(
+ join(systemDirectory, "icacls.exe"),
+ [ancestor, "/setowner", `*${sid}`],
+ { encoding: "utf8", windowsHide: true },
+ );
+ expect(owned.status).toBe(0);
+ const writable = spawnSync(
+ join(systemDirectory, "icacls.exe"),
+ [ancestor, "/grant", "*S-1-1-0:(OI)(CI)M"],
+ { encoding: "utf8", windowsHide: true },
+ );
+ expect(writable.status).toBe(0);
+ }
+
+ await expect(
+ prepareCodexSecurityCredentialHome({
+ CODEX_SECURITY_STATE_DIR: state,
+ }),
+ ).rejects.toThrow(
+ "Windows credential-home ancestor allows another identity to replace the directory",
+ );
+
+ for (const ancestor of [root, state]) {
+ const inspection = spawnSync(
+ join(systemDirectory, "WindowsPowerShell", "v1.0", "powershell.exe"),
+ [
+ "-NoLogo",
+ "-NoProfile",
+ "-NonInteractive",
+ "-Command",
+ [
+ "$acl = [System.IO.Directory]::GetAccessControl($env:CODEX_SECURITY_TEST_ACL_PATH)",
+ "$everyone = @($acl.Access | Where-Object { $_.AccessControlType -eq 'Allow' -and $_.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value -eq 'S-1-1-0' })",
+ "[pscustomobject]@{ protected = $acl.AreAccessRulesProtected; everyone = $everyone.Count } | ConvertTo-Json -Compress",
+ ].join("; "),
+ ],
+ {
+ encoding: "utf8",
+ env: { ...process.env, CODEX_SECURITY_TEST_ACL_PATH: ancestor },
+ windowsHide: true,
+ },
+ );
+ expect(inspection.status).toBe(0);
+ expect(JSON.parse(inspection.stdout).everyone).toBeGreaterThan(0);
+ }
+ },
+ );
+
+ test.skipIf(process.platform !== "win32")(
+ "repairs unsafe ACLs on existing nested Windows credential files",
+ async () => {
+ const root = await temporaryDirectory();
+ const state = join(root, "state");
+ const home = join(state, "codex-home");
+ const nested = join(home, "sessions");
+ await mkdir(nested, { recursive: true });
+ const auth = join(home, "auth.json");
+ const nestedAuth = join(nested, "credentials.json");
+ await writeFile(auth, '{"token":"synthetic-root"}\n');
+ await writeFile(nestedAuth, '{"token":"synthetic-nested"}\n');
+
+ const systemDirectory = join(
+ process.env["SystemRoot"] ?? "C:\\Windows",
+ "System32",
+ );
+ const identity = spawnSync(
+ join(systemDirectory, "whoami.exe"),
+ ["/user", "/fo", "csv", "/nh"],
+ { encoding: "utf8", windowsHide: true },
+ );
+ expect(identity.status).toBe(0);
+ const sid = /"(S-1-(?:\d+-)*\d+)"\s*$/u.exec(identity.stdout)?.[1];
+ expect(sid).toBeDefined();
+
+ for (const credential of [auth, nestedAuth]) {
+ const unsafe = spawnSync(
+ join(systemDirectory, "icacls.exe"),
+ [credential, "/inheritance:r", "/grant:r", `*${sid}:F`, "*S-1-1-0:R"],
+ { encoding: "utf8", windowsHide: true },
+ );
+ expect(unsafe.status).toBe(0);
+ }
+
+ expect(
+ await prepareCodexSecurityCredentialHome({
+ CODEX_SECURITY_STATE_DIR: state,
+ }),
+ ).toBe(await realpath(home));
+
+ const inspection = spawnSync(
+ join(systemDirectory, "WindowsPowerShell", "v1.0", "powershell.exe"),
+ [
+ "-NoLogo",
+ "-NoProfile",
+ "-NonInteractive",
+ "-Command",
+ [
+ "$paths = @($env:CODEX_SECURITY_TEST_AUTH_PATH, $env:CODEX_SECURITY_TEST_NESTED_AUTH_PATH)",
+ "$unexpected = @($paths | ForEach-Object { $acl = Get-Acl -LiteralPath $_; $acl.Access | Where-Object { $_.AccessControlType -eq 'Allow' -and $_.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value -eq 'S-1-1-0' } })",
+ "[pscustomobject]@{ unexpected = $unexpected.Count } | ConvertTo-Json -Compress",
+ ].join("; "),
+ ],
+ {
+ encoding: "utf8",
+ env: {
+ ...process.env,
+ CODEX_SECURITY_TEST_AUTH_PATH: auth,
+ CODEX_SECURITY_TEST_NESTED_AUTH_PATH: nestedAuth,
+ },
+ windowsHide: true,
+ },
+ );
+ expect(inspection.status).toBe(0);
+ expect(JSON.parse(inspection.stdout)).toEqual({ unexpected: 0 });
+ expect(await readFile(auth, "utf8")).toContain("synthetic-root");
+ expect(await readFile(nestedAuth, "utf8")).toContain("synthetic-nested");
+ },
+ );
+
+ 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",
+ )(
+ "prepares managed credential homes under constrained PowerShell",
+ async () => {
+ const root = await temporaryDirectory();
+ const powershell = join(
+ process.env["SystemRoot"] ?? "C:\\Windows",
+ "System32",
+ "WindowsPowerShell",
+ "v1.0",
+ "powershell.exe",
+ );
+ const constrainedEnvironment = {
+ ...process.env,
+ CODEX_SECURITY_STATE_DIR: join(root, "state"),
+ PSModulePath: join(root, "untrusted-or-incompatible-modules"),
+ PSMODULEPATH: join(root, "uppercase-untrusted-modules"),
+ };
+ const registry = join(dirname(dirname(dirname(powershell))), "reg.exe");
+ const policyKey =
+ "HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment";
+ const policyName = "__PSLockdownPolicy";
+ const original = spawnSync(
+ registry,
+ ["query", policyKey, "/v", policyName],
+ { encoding: "utf8", timeout: 15_000, windowsHide: true },
+ );
+ expect(original.status === 0 || original.status === 1).toBe(true);
+ const originalEntry =
+ original.status === 0
+ ? /^\s*__PSLockdownPolicy\s+(REG_[A-Z_]+)\s*(.*?)\s*$/mu.exec(
+ original.stdout,
+ )
+ : null;
+ if (original.status === 0) expect(originalEntry).not.toBeNull();
+ const originalPolicy =
+ originalEntry === null
+ ? null
+ : { type: originalEntry[1]!, value: originalEntry[2]! };
+ const enabled = spawnSync(
+ registry,
+ ["add", policyKey, "/v", policyName, "/t", "REG_SZ", "/d", "4", "/f"],
+ { encoding: "utf8", timeout: 15_000, windowsHide: true },
+ );
+ expect(enabled.status).toBe(0);
+
+ try {
+ const mode = spawnSync(
+ powershell,
+ [
+ "-NoLogo",
+ "-NoProfile",
+ "-NonInteractive",
+ "-Command",
+ "$ExecutionContext.SessionState.LanguageMode",
+ ],
+ {
+ encoding: "utf8",
+ env: constrainedEnvironment,
+ timeout: 15_000,
+ windowsHide: true,
+ },
+ );
+ expect(mode.status).toBe(0);
+ expect(mode.stdout.trim()).toBe("ConstrainedLanguage");
+
+ const oldImplementation = spawnSync(
+ powershell,
+ [
+ "-NoLogo",
+ "-NoProfile",
+ "-NonInteractive",
+ "-Command",
+ "$ErrorActionPreference = 'Stop'; New-Object System.Security.AccessControl.DirectorySecurity",
+ ],
+ {
+ encoding: "utf8",
+ env: constrainedEnvironment,
+ timeout: 15_000,
+ windowsHide: true,
+ },
+ );
+ expect(oldImplementation.status).not.toBe(0);
+
+ const trustedPowerShellEnvironment = {
+ ...Object.fromEntries(
+ Object.entries(process.env).filter(
+ ([name]) => name.toUpperCase() !== "PSMODULEPATH",
+ ),
+ ),
+ PSModulePath: join(dirname(powershell), "Modules"),
+ };
+ const guest = spawnSync(
+ powershell,
+ [
+ "-NoLogo",
+ "-NoProfile",
+ "-NonInteractive",
+ "-Command",
+ [
+ "Microsoft.PowerShell.Utility\\ConvertFrom-SddlString -Sddl 'O:LGG: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",
+ ].join(" | "),
+ ],
+ {
+ encoding: "utf8",
+ env: trustedPowerShellEnvironment,
+ timeout: 15_000,
+ windowsHide: true,
+ },
+ );
+ expect(guest.status).toBe(0);
+ expect(guest.stdout.trim()).toMatch(/^S-1-(?:\d+-)*501$/u);
+ const home = join(root, "state", "codex-home");
+ await mkdir(home, { recursive: true });
+ const foreignGrant = spawnSync(
+ join(dirname(dirname(dirname(powershell))), "icacls.exe"),
+ [home, "/grant", `*${guest.stdout.trim()}:(OI)(CI)R`],
+ { encoding: "utf8", timeout: 15_000, windowsHide: true },
+ );
+ expect(foreignGrant.status).toBe(0);
+
+ const fixtureModule = join(root, "runtime-node-fixture.mjs");
+ const build = spawnSync(
+ process.execPath,
+ [
+ "build",
+ fileURLToPath(new URL("../src/runtime.ts", import.meta.url)),
+ "--target=node",
+ "--format=esm",
+ `--outfile=${fixtureModule}`,
+ ],
+ { encoding: "utf8", timeout: 30_000, windowsHide: true },
+ );
+ expect(build.status).toBe(0);
+ const selectedNode = spawnSync("node", ["-p", "process.execPath"], {
+ encoding: "utf8",
+ timeout: 15_000,
+ windowsHide: true,
+ });
+ expect(selectedNode.status).toBe(0);
+ const fixture = spawnSync(
+ selectedNode.stdout.trim(),
+ [
+ "--input-type=module",
+ "--eval",
+ `import { prepareCodexSecurityCredentialHome } from ${JSON.stringify(pathToFileURL(fixtureModule).href)}; await prepareCodexSecurityCredentialHome();`,
+ ],
+ {
+ encoding: "utf8",
+ env: constrainedEnvironment,
+ timeout: 30_000,
+ windowsHide: true,
+ },
+ );
+ expect(fixture.stderr).toBe("");
+ expect(fixture.status).toBe(0);
+ expect(existsSync(home)).toBe(true);
+ } finally {
+ const restore = spawnSync(
+ registry,
+ originalPolicy === null
+ ? ["delete", policyKey, "/v", policyName, "/f"]
+ : [
+ "add",
+ policyKey,
+ "/v",
+ policyName,
+ "/t",
+ originalPolicy.type,
+ "/d",
+ originalPolicy.value,
+ "/f",
+ ],
+ { encoding: "utf8", timeout: 15_000, windowsHide: true },
+ );
+ expect(restore.status).toBe(0);
+ }
+ },
+ );
+
test("derives persistent state from the ambient home or explicit override", async () => {
const root = await temporaryDirectory();
expect(codexSecurityStateDirectory({ CODEX_HOME: root })).toBe(