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(sandbox): keep new Windows SDK scan output private through archival (#1739)
Michael D'Angelo29ec9114367f
diff --git a/plugins/codex-security/mcp-app/tests/support/fake-codex-fixture.ts b/plugins/codex-security/mcp-app/tests/support/fake-codex-fixture.tsindex d8c6dd711..5fde2ee74 100644--- a/plugins/codex-security/mcp-app/tests/support/fake-codex-fixture.ts+++ b/plugins/codex-security/mcp-app/tests/support/fake-codex-fixture.ts@@ -2,6 +2,37 @@ import { chmod, writeFile } from "node:fs/promises";import path from "node:path";import { fakeCodexSource } from "./fake-codex-source.ts";import type { createTemporaryDirectories } from "./temporary-directories.ts";+import { privateWindowsOutputRoot } from "./windows-output-fixture.ts";++export const trustedParentSandbox = Object.freeze({+ filesystemDenies: [],+});+export const trustedParentSandboxWithDenials = Object.freeze({+ filesystemDenies: [+ "/repo/.env",+ "/repo/**/.secret",+ "/repo/**/*.pem",+ "/repo/temp[1]",+ "/repo/secret[1]",+ "/repo/.env",+ ],+ literalFilesystemDenies: ["/repo/temp[1]", "/repo/secret[1]"],+ globScanMaxDepth: 3,+});+export const deniedWorkerPermissionProfile = {+ extends: ":read-only",+ filesystem: {+ ":root": "read",+ "/repo/.env": "deny",+ "/repo/**/.secret": "deny",+ "/repo/**/*.pem": "deny",+ "/repo/temp[1]": { ".": "deny" },+ "/repo/secret[1]": { ".": "deny" },+ "/": { "repo/temp[1]": "deny", "repo/secret[1]": "deny" },+ glob_scan_max_depth: 3,+ },+ network: { enabled: false },+};export const emptyWorkerPermissionProfile = {extends: ":read-only",@@ -17,10 +48,10 @@ export async function createFakeCodexFixture(account: { type: string } | null;requiresOpenaiAuth: boolean;} = { account: { type: "apiKey" }, requiresOpenaiAuth: true },+ privateWindowsRoot = false,) {- const root = await temporaryDirectories.create(- "codex-security-sdk-executor-",- );+ let root = await temporaryDirectories.create("codex-security-sdk-executor-");+ if (privateWindowsRoot) root = await privateWindowsOutputRoot(root);const markerPath = path.join(root, "invocation.json");const preflightMarkerPath = path.join(root, "preflight.json");const scriptPath = path.join(root, "fake-codex.mjs");diff --git a/plugins/codex-security/mcp-app/tests/support/windows-output-fixture.ts b/plugins/codex-security/mcp-app/tests/support/windows-output-fixture.tsnew file mode 100644index 000000000..906a9bd30--- /dev/null+++ b/plugins/codex-security/mcp-app/tests/support/windows-output-fixture.ts@@ -0,0 +1,60 @@+import assert from "node:assert/strict";+import { spawnSync } from "node:child_process";+import { realpath } from "node:fs/promises";+import { createRequire } from "node:module";+import path from "node:path";+import { fileURLToPath } from "node:url";++export function windowsAcl(directory: string): string {+ const system = path.join(process.env.SystemRoot ?? "C:\\Windows", "System32");+ const result = spawnSync(+ path.join(system, "WindowsPowerShell", "v1.0", "powershell.exe"),+ [+ "-NoLogo",+ "-NoProfile",+ "-NonInteractive",+ "-Command",+ "$ErrorActionPreference = 'Stop'; Microsoft.PowerShell.Security\\Get-Acl -LiteralPath $env:CODEX_SECURITY_TEST_ACL_PATH | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty Sddl",+ ],+ {+ encoding: "utf8",+ env: {+ ...process.env,+ CODEX_SECURITY_TEST_ACL_PATH: directory,+ PSModulePath: path.join(system, "WindowsPowerShell", "v1.0", "Modules"),+ },+ },+ );+ assert.equal(result.status, 0, result.stderr);+ return result.stdout.trim();+}++export async function privateWindowsOutputRoot(root: string): Promise<string> {+ const icacls = path.join(+ process.env.SystemRoot ?? "C:\\Windows",+ "System32",+ "icacls.exe",+ );+ assert.equal(+ spawnSync(icacls, [root, "/grant", "*S-1-1-0:(OI)(CI)R"]).status,+ 0,+ );+ assert.ok(windowsAcl(root).includes(";;;WD)"));+ root = path.join(root, "private scan artifacts");+ // Use the same existing atomic creator as SDK scan-output preparation.+ const native = createRequire(import.meta.url)(+ path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ `../../../native/prebuilt/win32-${process.arch}/windows.node`,+ ),+ ) as { createPrivateWindowsDirectory(path: Buffer): number };+ assert.equal(+ native.createPrivateWindowsDirectory(+ Buffer.from(path.toNamespacedPath(root), "utf16le"),+ ),+ 0,+ );+ root = await realpath(root);+ assert.ok(windowsAcl(root).includes("D:P"));+ return root;+}diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.ts b/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.tsindex b9e5eaac6..8804bfccc 100644--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.ts+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.ts@@ -1,6 +1,10 @@+import { windowsAcl } from "./support/windows-output-fixture.ts";import {createFakeCodexFixture,+ deniedWorkerPermissionProfile,emptyWorkerPermissionProfile,+ trustedParentSandbox,+ trustedParentSandboxWithDenials,} from "./support/fake-codex-fixture.ts";import { readJson, writeJson } from "./support/json.ts";import { randomUUID } from "node:crypto";@@ -85,37 +89,8 @@ const fakeCodexFixture = createFakeCodexFixture.bind(temporaryDirectories,);const previousMarker = process.env.FAKE_CODEX_MARKER;-const trustedParentSandbox = Object.freeze({- filesystemDenies: [],-});-const trustedParentSandboxWithDenials = Object.freeze({- filesystemDenies: [- "/repo/.env",- "/repo/**/.secret",- "/repo/**/*.pem",- "/repo/temp[1]",- "/repo/secret[1]",- "/repo/.env",- ],- literalFilesystemDenies: ["/repo/temp[1]", "/repo/secret[1]"],- globScanMaxDepth: 3,-});const ipcFrameError ="code-mode delegate response exceeds the IPC frame limit: code-mode IPC frame length 76008279 exceeds 67108864 bytes";-const deniedWorkerPermissionProfile = {- extends: ":read-only",- filesystem: {- ":root": "read",- "/repo/.env": "deny",- "/repo/**/.secret": "deny",- "/repo/**/*.pem": "deny",- "/repo/temp[1]": { ".": "deny" },- "/repo/secret[1]": { ".": "deny" },- "/": { "repo/temp[1]": "deny", "repo/secret[1]": "deny" },- glob_scan_max_depth: 3,- },- network: { enabled: false },-};try {testCodeModeFrameDiagnosticBoundaries();@@ -1421,6 +1396,7 @@ async function testWorkerRuntimeSettings() {deniedWorkerPermissionProfile,true,{ account: null, requiresOpenaiAuth: false },+ process.platform === "win32" && configuration === "",);const python = path.join(fixture.root, "selected venv", "bin", "python");const helperPython = path.join(@@ -2018,6 +1994,15 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,workerConfigurations[index].knowledgePath,);const invocation = await readJson(workerLaunch.markerPath);+ if (+ process.platform === "win32" &&+ configuration === "" &&+ index === 0+ ) {+ const acl = windowsAcl(workerLaunch.markerPath);+ assert.ok(!acl.includes(";;;WD)"));+ assertFlagPair(invocation.argv, "--cd", fixture.root);+ }for (const name of ["LD_LIBRARY_PATH","DYLD_LIBRARY_PATH",diff --git a/plugins/codex-security/scripts/windows_scan_local_files.py b/plugins/codex-security/scripts/windows_scan_local_files.pyindex 2f57483ca..0bcdca618 100644--- a/plugins/codex-security/scripts/windows_scan_local_files.py+++ b/plugins/codex-security/scripts/windows_scan_local_files.py@@ -71,7 +71,9 @@ _ERROR_ACCESS_DENIED = 5_ERROR_SHARING_VIOLATION = 32_ERROR_LOCK_VIOLATION = 33_ERROR_FILE_EXISTS = 80+_ERROR_INSUFFICIENT_BUFFER = 122_ERROR_ALREADY_EXISTS = 183+_DACL_SECURITY_INFORMATION = 0x00000004_MISSING_ERRORS = {_ERROR_FILE_NOT_FOUND, _ERROR_PATH_NOT_FOUND}_COLLISION_ERRORS = {_ERROR_FILE_EXISTS, _ERROR_ALREADY_EXISTS}_INVALID_HANDLE_VALUE = ctypes.c_void_p(-1).value@@ -100,6 +102,14 @@ class _FileAttributeTagInfo(ctypes.Structure):]+class _SecurityAttributes(ctypes.Structure):+ _fields_ = [+ ("nLength", wintypes.DWORD),+ ("lpSecurityDescriptor", wintypes.LPVOID),+ ("bInheritHandle", wintypes.BOOL),+ ]++class _FileDispositionInfo(ctypes.Structure):_fields_ = [("DeleteFile", wintypes.BOOLEAN)]@@ -143,6 +153,17 @@ class _OwnedHandle:if os.name == "nt":_kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)+ _advapi32 = ctypes.WinDLL("advapi32", use_last_error=True)++ _GetFileSecurityW = _advapi32.GetFileSecurityW+ _GetFileSecurityW.argtypes = [+ wintypes.LPCWSTR,+ wintypes.DWORD,+ wintypes.LPVOID,+ wintypes.DWORD,+ ctypes.POINTER(wintypes.DWORD),+ ]+ _GetFileSecurityW.restype = wintypes.BOOL_CreateFileW = _kernel32.CreateFileW_CreateFileW.argtypes = [@@ -441,6 +462,27 @@ def _create_directory(path: Path) -> None:_raise_last_error("CreateDirectoryW", path)+def create_directory_with_same_dacl(path: Path, source: Path) -> None:+ """Create an archive replacement with the original directory's DACL."""+ _require_windows()+ source_path = _extended_path(source)+ size = wintypes.DWORD()+ _GetFileSecurityW(source_path, _DACL_SECURITY_INFORMATION, None, 0, ctypes.byref(size))+ if ctypes.get_last_error() != _ERROR_INSUFFICIENT_BUFFER:+ _raise_last_error("GetFileSecurityW", source)+ descriptor = ctypes.create_string_buffer(size.value)+ if not _GetFileSecurityW(+ source_path, _DACL_SECURITY_INFORMATION, descriptor, size.value, ctypes.byref(size)+ ):+ _raise_last_error("GetFileSecurityW", source)+ attributes = _SecurityAttributes(+ ctypes.sizeof(_SecurityAttributes), ctypes.cast(descriptor, wintypes.LPVOID), False+ )+ # Supply the descriptor at creation, without an inherited-access window.+ if not _CreateDirectoryW(_extended_path(path), ctypes.byref(attributes)):+ _raise_last_error("CreateDirectoryW", path)++@contextlib.contextmanagerdef _locked_parent(scan_dir: Path,diff --git a/plugins/codex-security/scripts/workbench_scan_start.py b/plugins/codex-security/scripts/workbench_scan_start.pyindex 28c893773..c9326f890 100644--- a/plugins/codex-security/scripts/workbench_scan_start.py+++ b/plugins/codex-security/scripts/workbench_scan_start.py@@ -161,8 +161,13 @@ def archive_scan(archived_scan_dir.rmdir()scan_dir.rename(archived_scan_dir)moved = True- scan_dir.mkdir(mode=0o700)- scan_dir.chmod(0o700)+ if os.name == "nt":+ from windows_scan_local_files import create_directory_with_same_dacl++ create_directory_with_same_dacl(scan_dir, archived_scan_dir)+ else:+ scan_dir.mkdir(mode=0o700)+ scan_dir.chmod(0o700)if previous_scan is not None:connection.execute("UPDATE scans SET scan_dir = ?, updated_at = ? WHERE id = ?",diff --git a/plugins/codex-security/tests/test_finalize_scan_contract.py b/plugins/codex-security/tests/test_finalize_scan_contract.pyindex 0528537c5..40504791a 100644--- a/plugins/codex-security/tests/test_finalize_scan_contract.py+++ b/plugins/codex-security/tests/test_finalize_scan_contract.py@@ -2409,8 +2409,8 @@ The extraction root is not enforced.self.read_json("scan-manifest.json")["scan"]["scope"]["includePaths"], ["."])- def test_preserves_literal_whitespace_repository_paths(self) -> None:- for path in (" ", " ", "\u00a0"):+ def test_preserves_literal_repository_paths(self) -> None:+ for path in (" ", " ", "\u00a0", "src/a:b.py", "report:summary.py"):with self.subTest(path=path):self.manifest["scan"]["scope"]["includePaths"] = [path]self.coverage["includePaths"] = [path]@@ -2435,7 +2435,7 @@ The extraction root is not enforced.self.assertEqual(coverage["deferred"][0]["paths"], [path])self.assertEqual(findings["findings"][0]["locations"][0]["path"], path)self.assertEqual(findings["findings"][0]["codeEvidence"][0]["path"], path)- if path.isascii():+ if path.isascii() and path.isspace():self.assertIn(f'- Included paths: `"{path}"`',(self.scan_dir / "report.md").read_text(encoding="utf-8"),diff --git a/plugins/codex-security/tests/test_windows_scan_local_files.py b/plugins/codex-security/tests/test_windows_scan_local_files.pyindex 25f4c8af3..05206cde6 100644--- a/plugins/codex-security/tests/test_windows_scan_local_files.py+++ b/plugins/codex-security/tests/test_windows_scan_local_files.py@@ -38,6 +38,27 @@ def test_accepts_normal_scan_local_path() -> None:)[email protected](os.name != "nt", reason="requires native Win32 security APIs")+def test_directory_acl_copy_does_not_create_from_a_missing_source(tmp_path: Path) -> None:+ destination = tmp_path / "replacement"+ with pytest.raises(WINDOWS_FILES.WindowsScanLocalFileError):+ WINDOWS_FILES.create_directory_with_same_dacl(destination, tmp_path / "missing")+ assert not destination.exists()++[email protected](os.name != "nt", reason="requires native Win32 security APIs")+def test_directory_acl_copy_does_not_reuse_an_existing_destination(tmp_path: Path) -> None:+ source = tmp_path / "original"+ destination = tmp_path / "replacement"+ source.mkdir()+ destination.mkdir()+ marker = destination / "retained.txt"+ marker.write_text("synthetic retained data", encoding="utf-8")+ with pytest.raises(WINDOWS_FILES.WindowsScanLocalFileError):+ WINDOWS_FILES.create_directory_with_same_dacl(destination, source)+ assert marker.read_text(encoding="utf-8") == "synthetic retained data"++@pytest.mark.skipif(os.name != "nt", reason="requires native Win32 file APIs")def test_native_windows_backend_writes_reads_replaces_and_deletes(tmp_path: Path) -> None:scan_dir = tmp_path / "scan"diff --git a/plugins/codex-security/tests/test_workbench_scan_archive.py b/plugins/codex-security/tests/test_workbench_scan_archive.pyindex 162c2cf20..059cb4619 100644--- a/plugins/codex-security/tests/test_workbench_scan_archive.py+++ b/plugins/codex-security/tests/test_workbench_scan_archive.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport argparseimport json+import osimport sqlite3import threadingimport uuid@@ -258,6 +259,7 @@ def test_archive_cannot_move_the_active_workbench_database(assert connection.execute("SELECT COUNT(*) FROM scans").fetchone()[0] == 1[email protected]_platformdef test_registration_rechecks_empty_output_after_competing_archive_rolls_back(tmp_path: Path,monkeypatch: pytest.MonkeyPatch,@@ -307,11 +309,19 @@ def test_registration_rechecks_empty_output_after_competing_archive_rolls_back(except SystemExit as error:outcomes.append(error)- mkdir = Path.mkdir+ creation_owner, creation_method = Path, "mkdir"+ if os.name == "nt":+ import windows_scan_local_files++ creation_owner, creation_method = (+ windows_scan_local_files,+ "create_directory_with_same_dacl",+ )+ create_directory = getattr(creation_owner, creation_method)competitor = threading.Thread(target=compete)def replacement(path, *args, **kwargs):- result = mkdir(path, *args, **kwargs)+ result = create_directory(path, *args, **kwargs)if path == scan_dir:competitor.start()assert waiting.wait(5)@@ -321,7 +331,7 @@ def test_registration_rechecks_empty_output_after_competing_archive_rolls_back(workbench_schema.backup(first)first.row_factory = sqlite3.Rowwith monkeypatch.context() as patch:- patch.setattr(Path, "mkdir", replacement)+ patch.setattr(creation_owner, creation_method, replacement)with pytest.raises(SystemExit, match="not found"):register(first, arguments)competitor.join(10)diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.tsindex 6b4bf936e..19232bc42 100644--- a/sdk/typescript/src/runtime.ts+++ b/sdk/typescript/src/runtime.ts@@ -47,6 +47,7 @@ import {relative,resolve,sep,+ win32,} from "node:path";import { fileURLToPath } from "node:url";import { promisify } from "node:util";@@ -1924,7 +1925,11 @@ export async function planOutputArchive(if (outputDirectory === null) return null;const entries = await readdir(outputDirectory).catch(nullIfMissingFileError);if (entries === null || entries.length === 0) return null;- return `${outputDirectory}.previous-${new Date()+ return `${outputDirectory}${outputArchiveSuffix()}`;+}++function outputArchiveSuffix(): string {+ return `.previous-${new Date().toISOString().replaceAll(/[-:]/g, "").replace(/\.\d{3}Z$/, "")}-${randomUUID().slice(0, 8)}`;@@ -2027,9 +2032,21 @@ async function prepareOutputDirectory();validateLocation?.(path ?? (await realpath(temporaryRoot)));if (path === null) {- const created = await mkdtemp(- join(temporaryRoot, `codex-security-${safePrefix(repositoryName)}-`),- );+ const prefix = `codex-security-${safePrefix(repositoryName)}`;+ let created: string;+ if (process.platform === "win32") {+ const suffix = `-${randomUUID()}`;+ // Reserve room within NTFS's 255-unit component limit for later archival.+ // The SDK suffix is longer than the workbench's .previous-<tempname> suffix.+ const prefixLength = 255 - suffix.length - outputArchiveSuffix().length;+ created = join(+ temporaryRoot,+ `${prefix.slice(0, prefixLength)}${suffix}`,+ );+ await createWindowsOutputDirectory(created, false);+ } else {+ created = await mkdtemp(join(temporaryRoot, `${prefix}-`));+ }try {if ((process.umask() & 0o700) !== 0) await chmod(created, 0o700);return await validatePreparedOutputDir(created, validateLocation);@@ -2050,7 +2067,10 @@ async function prepareOutputDirectory(}}if (existing === null) {- createdRoot = await mkdir(path, { recursive: true, mode: 0o700 });+ createdRoot =+ process.platform === "win32"+ ? await createWindowsOutputDirectory(path, true)+ : await mkdir(path, { recursive: true, mode: 0o700 });if ((process.umask() & 0o700) !== 0) await chmod(path, 0o700);}return await validatePreparedOutputDir(@@ -2072,6 +2092,44 @@ async function prepareOutputDirectory(}}+async function createWindowsOutputDirectory(+ path: string,+ recursive: boolean,+): Promise<string | undefined> {+ const native = createRequire(import.meta.url)(+ join(+ await bundledPluginRoot(),+ "mcp",+ "native",+ `win32-${process.arch}`,+ "windows.node",+ ),+ ) as { createPrivateWindowsDirectory(path: Buffer): number };+ const create = async (target: string): Promise<string | undefined> => {+ const createOne = () =>+ native.createPrivateWindowsDirectory(+ Buffer.from(win32.toNamespacedPath(target), "utf16le"),+ );+ let error = createOne();+ let firstCreated: string | undefined;+ if (+ recursive &&+ (error === 2 || error === 3) &&+ dirname(target) !== target+ ) {+ firstCreated = await create(dirname(target));+ error = createOne();+ }+ if (error === 0) return firstCreated ?? target;+ if (recursive && error === 183 && (await stat(target)).isDirectory())+ return firstCreated;+ throw new OutputDirectoryError(+ `Unable to create private Windows output directory (Windows error ${error}): ${target}`,+ );+ };+ return create(path);+}+export async function validatePreparedOutputDir(path: string,validateLocation?: (path: string) => void,diff --git a/sdk/typescript/tests-ts/api-provider-isolation.test.ts b/sdk/typescript/tests-ts/api-provider-isolation.test.tsindex f7671da5c..cd19c2a06 100644--- a/sdk/typescript/tests-ts/api-provider-isolation.test.ts+++ b/sdk/typescript/tests-ts/api-provider-isolation.test.ts@@ -455,7 +455,7 @@ test.each([}expect(existsSync(sharedHome)).toBe(true);},- 30_000,+ Number(process.env["CODEX_SECURITY_TEST_TIMEOUT_MS"] ?? "30000"),);test("workers preserve native provider inheritance without an explicit selection", async () => {diff --git a/sdk/typescript/tests-ts/config.test.ts b/sdk/typescript/tests-ts/config.test.tsindex 51dc1355c..c941a3850 100644--- a/sdk/typescript/tests-ts/config.test.ts+++ b/sdk/typescript/tests-ts/config.test.ts@@ -19,6 +19,7 @@ import {} from "../src/index.js";import {prepareCodexSecurityCredentialHome,+ prepareOutputDir,requireSecureCredentialHome,resolveCodexCommand,} from "../src/runtime.js";@@ -124,9 +125,10 @@ async function scanSandboxFixture() {});const workspace = join(stateDirectory, "scans", "workspace");const temporary = join(root, "temp");- await Promise.all(- [workspace, temporary].map((path) => mkdir(path, { recursive: true })),- );+ await Promise.all([+ prepareOutputDir(workspace, "sandbox-fixture"),+ mkdir(temporary, { recursive: true }),+ ]);await writeCodexConfig(join(codexHome, "config.toml"),scanRuntimeCodexConfig(await mergedCodexConfig({}), codexHome),diff --git a/sdk/typescript/tests-ts/support/windows-other-user-access.ps1 b/sdk/typescript/tests-ts/support/windows-other-user-access.ps1new file mode 100644index 000000000..623f664d5--- /dev/null+++ b/sdk/typescript/tests-ts/support/windows-other-user-access.ps1@@ -0,0 +1,56 @@+$ErrorActionPreference = 'Stop'+Add-Type -TypeDefinition @'+using System;+using System.IO;+using System.Runtime.InteropServices;+using System.Security.Principal;+using Microsoft.Win32.SafeHandles;++public static class ScanOutputAccessProbe {+ [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]+ [return: MarshalAs(UnmanagedType.Bool)]+ public static extern bool LogonUser(string user, string domain, string password,+ int logonType, int provider, out SafeAccessTokenHandle token);++ public static bool Read(SafeAccessTokenHandle token, string path) {+ return WindowsIdentity.RunImpersonated(token, () => {+ try { File.ReadAllText(path); return true; }+ catch (UnauthorizedAccessException) { return false; }+ });+ }++ public static bool Write(SafeAccessTokenHandle token, string path) {+ return WindowsIdentity.RunImpersonated(token, () => {+ try { File.AppendAllText(path, "synthetic outsider write"); return true; }+ catch (UnauthorizedAccessException) { return false; }+ });+ }+}+'@++# Run only on disposable CI machines. The account and token are removed below;+# its generated password stays in this process and is never printed.+$name = 'csec' + [Guid]::NewGuid().ToString('N').Substring(0, 12)+$password = [Guid]::NewGuid().ToString('N') + 'aA1!'+$created = $false+$token = $null+try {+ $user = New-LocalUser -Name $name -Password (ConvertTo-SecureString $password -AsPlainText -Force)+ $created = $true+ Add-LocalGroupMember -SID 'S-1-5-32-545' -Member $user+ if (-not [ScanOutputAccessProbe]::LogonUser($name, '.', $password, 2, 0, [ref]$token)) {+ throw [System.ComponentModel.Win32Exception]::new([System.Runtime.InteropServices.Marshal]::GetLastWin32Error())+ }+ $results = @(+ foreach ($path in ($env:CODEX_SECURITY_TEST_ACCESS_PATHS | ConvertFrom-Json)) {+ [pscustomobject]@{+ read = [ScanOutputAccessProbe]::Read($token, $path)+ write = [ScanOutputAccessProbe]::Write($token, $path)+ }+ }+ )+ ConvertTo-Json -InputObject $results -Compress+} finally {+ if ($null -ne $token) { $token.Dispose() }+ if ($created) { Remove-LocalUser -Name $name }+}diff --git a/sdk/typescript/tests-ts/windows-scan-output.test.ts b/sdk/typescript/tests-ts/windows-scan-output.test.tsnew file mode 100644index 000000000..b678bfd81--- /dev/null+++ b/sdk/typescript/tests-ts/windows-scan-output.test.ts@@ -0,0 +1,398 @@+import { execFile } from "node:child_process";+import {+ cp,+ lstat,+ mkdir,+ readFile,+ realpath,+ symlink,+ writeFile,+} from "node:fs/promises";+import { basename, join } from "node:path";+import { promisify } from "node:util";+import { afterEach, expect, test } from "bun:test";+import { loadContract } from "../src/contract.js";+import * as runtime from "../src/runtime.js";+import { PLUGIN_ROOT } from "./plugin-root.js";+import { createApiTestFixtures } from "./support/temporary-directories.js";++const { temporaryDirectory, cleanup } = createApiTestFixtures(+ "codex-security-output-acl-",+);+afterEach(cleanup);+const exec = promisify(execFile);+const windowsTest = test.skipIf(process.platform !== "win32");+const example = join(PLUGIN_ROOT, "examples", "completed-scan");++async function icacls(path: string, ...args: string[]): Promise<void> {+ await exec(+ join(process.env["SystemRoot"] ?? "C:\\Windows", "System32", "icacls.exe"),+ [path, ...args],+ );+}++async function inspectAcl(path: string, expression: string): Promise<string> {+ const system = join(process.env["SystemRoot"] ?? "C:\\Windows", "System32");+ const result = await exec(+ join(system, "WindowsPowerShell", "v1.0", "powershell.exe"),+ [+ "-NoLogo",+ "-NoProfile",+ "-NonInteractive",+ "-Command",+ `$ErrorActionPreference = 'Stop'; $acl = Microsoft.PowerShell.Security\\Get-Acl -LiteralPath $env:CODEX_SECURITY_TEST_ACL_PATH; ${expression}`,+ ],+ {+ env: {+ ...process.env,+ CODEX_SECURITY_TEST_ACL_PATH: path,+ PSModulePath: join(system, "WindowsPowerShell", "v1.0", "Modules"),+ },+ },+ );+ return result.stdout.trim();+}++async function descriptor(path: string): Promise<string> {+ return inspectAcl(path, "$acl.Sddl");+}++async function accessRules(path: string): Promise<string> {+ return inspectAcl(+ path,+ "[pscustomobject]@{ protected = $acl.AreAccessRulesProtected; entries = @($acl.Access | Select-Object FileSystemRights, AccessControlType, IdentityReference, IsInherited, InheritanceFlags, PropagationFlags) } | ConvertTo-Json -Depth 4 -Compress",+ );+}++async function archiveWorkbenchOutput(+ output: string,+ root: string,+): Promise<string> {+ const python = await runtime.resolvePluginPython();+ const result = await exec(+ python,+ [+ "-I",+ "-B",+ "-c",+ [+ "import argparse, json, sqlite3, sys",+ "from pathlib import Path",+ "sys.path.insert(0, sys.argv[1])",+ "from workbench_scan_start import archive_scan",+ "connection = sqlite3.connect(':memory:')",+ "connection.execute('CREATE TABLE scans (id TEXT, status TEXT, scan_dir TEXT)')",+ "args = argparse.Namespace(archived_scan_dir=None, archive_existing=True)",+ "with archive_scan(connection, args, Path(sys.argv[2]), '2026-10-08T00:00:00Z', lambda path: path.resolve()) as archive:",+ " print(json.dumps(str(archive)))",+ ].join("\n"),+ join(PLUGIN_ROOT, "scripts"),+ output,+ ],+ {+ env: {+ PATH: process.env["PATH"],+ SystemRoot: process.env["SystemRoot"],+ CODEX_SECURITY_STATE_DIR: join(root, "state"),+ },+ },+ );+ return JSON.parse(result.stdout) as string;+}++windowsTest(+ "new Windows scan roots start private beneath a shared parent",+ async () => {+ const root = await temporaryDirectory();+ await icacls(root, "/grant", "*S-1-1-0:(OI)(CI)R");+ const before = await descriptor(root);+ expect(before).toContain(";;;WD)");+ const explicit = join(root, "new parent", "scan");+ expect(await runtime.prepareOutputDir(explicit, "fixture")).toBe(+ await realpath(explicit),+ );+ const generated = await runtime.prepareOutputDir(+ undefined,+ "fixture",+ root,+ );+ for (const output of [join(root, "new parent"), explicit, generated]) {+ const acl = await descriptor(output);+ expect(acl).toContain("D:P");+ expect(acl).not.toContain(";;;WD)");+ }+ expect(await descriptor(root)).toBe(before);+ },+);++windowsTest.each([204, 233])(+ "generated Windows output supports a %i-character repository name",+ async (length) => {+ const root = await temporaryDirectory();+ await icacls(root, "/grant", "*S-1-1-0:(OI)(CI)R");+ const output = await runtime.prepareOutputDir(+ undefined,+ "r".repeat(length),+ root,+ );+ expect((await lstat(output)).isDirectory()).toBe(true);+ expect(basename(output).length).toBeLessThanOrEqual(255);+ expect(basename(output)).toMatch(+ /-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u,+ );+ const acl = await descriptor(output);+ expect(acl).toContain("D:P");+ expect(acl).not.toContain(";;;WD)");+ },+);++windowsTest(+ "fresh SDK output keeps its private identity through workbench registration",+ async () => {+ const root = await temporaryDirectory();+ await icacls(root, "/grant", "*S-1-1-0:(OI)(CI)R");+ const repository = join(root, "repository");+ await mkdir(repository);+ await writeFile(join(repository, "source.txt"), "Synthetic repository");+ const output = await runtime.prepareScanRegistrationOutput(+ undefined,+ "repository",+ root,+ );+ const before = await lstat(output, { bigint: true });+ const originalAcl = await descriptor(output);+ const registered = await runtime.runWorkbench(+ {+ python: await runtime.resolvePluginPython(),+ pluginRoot: PLUGIN_ROOT,+ environment: {+ PATH: process.env["PATH"],+ SystemRoot: process.env["SystemRoot"],+ CODEX_SECURITY_STATE_DIR: join(root, "state"),+ },+ },+ [+ "register-cli-scan",+ "--repository",+ repository,+ "--scan-dir",+ output,+ "--registration-json-stdin",+ ],+ JSON.stringify({+ recipe: {+ config: {},+ mode: "standard",+ repository,+ target: { kind: "repository", paths: [] },+ },+ }),+ );+ expect(registered["scanDir"]).toBe(await realpath(output));+ const after = await lstat(output, { bigint: true });+ expect([after.dev, after.ino]).toEqual([before.dev, before.ino]);+ expect(originalAcl).not.toContain(";;;WD)");+ expect(await descriptor(output)).toBe(originalAcl);+ },+);++windowsTest.each(+ [190, 204, 233].flatMap((length) =>+ ["SDK", "workbench"].map((archiver) => [archiver, length] as const),+ ),+)(+ "generated Windows output remains archivable through %s for a %i-character repository name",+ async (archiver, length) => {+ const root = await temporaryDirectory();+ await icacls(root, "/grant", "*S-1-1-0:(OI)(CI)R");+ const output = await runtime.prepareOutputDir(+ undefined,+ "r".repeat(length),+ root,+ );+ await writeFile(+ join(output, "retained.txt"),+ "Synthetic retained scan data",+ );+ const original = await descriptor(output);+ let archive: string | undefined;+ if (archiver === "SDK") {+ await runtime.prepareOutputDir(+ output,+ "fixture",+ root,+ undefined,+ true,+ (path) => {+ archive = path;+ },+ );+ } else {+ archive = await archiveWorkbenchOutput(output, root);+ }+ expect(await descriptor(output)).toBe(original);+ expect(archive).toBeDefined();+ expect(basename(archive!).length).toBeLessThanOrEqual(255);+ expect(await readFile(join(archive!, "retained.txt"), "utf8")).toBe(+ "Synthetic retained scan data",+ );+ expect(await descriptor(archive!)).toBe(original);+ },+);++windowsTest("existing Windows scan ACLs are preserved", async () => {+ const root = await temporaryDirectory();+ const output = join(root, "scan");+ await mkdir(output);+ // Built-in Users exists on every Windows host; only this fixture gets the grant.+ await icacls(output, "/grant", "*S-1-5-32-545:(OI)(CI)M");+ const before = await descriptor(output);+ const permissions = await accessRules(output);+ expect(before).toContain(";;;BU)");+ expect(await runtime.prepareOutputDir(output, "fixture")).toBe(+ await realpath(output),+ );+ expect(await descriptor(output)).toBe(before);+ await cp(example, output, { recursive: true });+ expect(+ await runtime.prepareScanRegistrationOutput(+ output,+ "fixture",+ root,+ undefined,+ true,+ ),+ ).toBe(await realpath(output));+ await loadContract(output, { pluginRoot: PLUGIN_ROOT });+ expect(await descriptor(output)).toBe(before);+ const archive = await archiveWorkbenchOutput(output, root);+ expect(await descriptor(archive)).toBe(before);+ // Creation can change the auto-inheritance marker without changing the rules.+ expect(await accessRules(output)).toBe(permissions);+ await icacls(root, "/grant", "*S-1-1-0:(OI)(CI)R");+ for (const path of [archive, output]) {+ expect(await descriptor(path)).toContain(";;;WD)");+ }+ await icacls(root, "/remove:g", "*S-1-1-0");+ for (const path of [archive, output]) {+ expect(await accessRules(path)).toBe(permissions);+ }+});++windowsTest(+ "archiving Windows output preserves old ACLs and privately creates the replacement",+ async () => {+ const root = await temporaryDirectory();+ await icacls(root, "/grant", "*S-1-1-0:(OI)(CI)R");+ const output = join(root, "scan");+ await mkdir(output);+ await writeFile(join(output, "retained.txt"), "Synthetic retained data");+ const original = await descriptor(output);+ let archive: string | undefined;+ await runtime.prepareOutputDir(+ output,+ "fixture",+ root,+ undefined,+ true,+ (path) => {+ archive = path;+ },+ );+ expect(archive).toBeDefined();+ expect(await descriptor(archive!)).toBe(original);+ expect(await readFile(join(archive!, "retained.txt"), "utf8")).toBe(+ "Synthetic retained data",+ );+ expect(await descriptor(output)).not.toContain(";;;WD)");+ },+);++windowsTest(+ "new Windows output creation accepts parent aliases and leaves rejected locations absent",+ async () => {+ const root = await temporaryDirectory();+ const destination = join(root, "destination");+ const alias = join(root, "alias");+ await mkdir(destination);+ await symlink(destination, alias, "junction");+ const prepared = await runtime.prepareOutputDir(+ join(alias, "scan"),+ "fixture",+ );+ expect(prepared).toBe(await realpath(join(destination, "scan")));+ const rejected = join(alias, "rejected");+ const failure = new Error("Synthetic rejected location");+ await expect(+ runtime.prepareOutputDir(rejected, "fixture", root, () => {+ throw failure;+ }),+ ).rejects.toBe(failure);+ await expect(lstat(rejected)).rejects.toMatchObject({ code: "ENOENT" });+ },+);++// Creating a separate local account requires administrator rights and belongs on+// the disposable hosted Windows runners, not a developer's workstation.+test.skipIf(+ process.platform !== "win32" || process.env["GITHUB_ACTIONS"] !== "true",+)(+ "another local user cannot read or change new and archived scan output",+ async () => {+ const root = await temporaryDirectory();+ await icacls(root, "/grant", "*S-1-1-0:(OI)(CI)R");+ const shared = join(root, "shared.txt");+ await writeFile(shared, "synthetic shared data");+ await icacls(shared, "/grant", "*S-1-1-0:M");+ const explicit = await runtime.prepareOutputDir(+ join(root, "explicit"),+ "fixture",+ );+ const generated = await runtime.prepareOutputDir(+ undefined,+ "fixture",+ root,+ );+ for (const output of [explicit, generated]) {+ await writeFile(join(output, "probe.txt"), "synthetic private data");+ }+ const archive = await archiveWorkbenchOutput(generated, root);+ await writeFile(join(generated, "probe.txt"), "synthetic private data");+ const paths = [+ shared,+ ...[explicit, generated, archive].map((path) => join(path, "probe.txt")),+ ];+ const script = await readFile(+ join(import.meta.dir, "support", "windows-other-user-access.ps1"),+ "utf8",+ );+ const system = join(process.env["SystemRoot"] ?? "C:\\Windows", "System32");+ const result = await exec(+ join(system, "WindowsPowerShell", "v1.0", "powershell.exe"),+ [+ "-NoLogo",+ "-NoProfile",+ "-NonInteractive",+ "-EncodedCommand",+ Buffer.from(script, "utf16le").toString("base64"),+ ],+ {+ env: {+ ...process.env,+ CODEX_SECURITY_TEST_ACCESS_PATHS: JSON.stringify(paths),+ PSModulePath: join(system, "WindowsPowerShell", "v1.0", "Modules"),+ },+ },+ );+ expect(JSON.parse(result.stdout)).toEqual([+ { read: true, write: true },+ { read: false, write: false },+ { read: false, write: false },+ { read: false, write: false },+ ]);+ for (const path of paths.slice(1)) {+ expect(await readFile(path, "utf8")).toBe("synthetic private data");+ }+ },+ 60_000,+);