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(windows): verify scan output directory ownership and ancestry (#2432)

Michael D'Angelo0a127333739f
diff --git a/plugins/codex-security/mcp-app/src/sealed-contract.ts b/plugins/codex-security/mcp-app/src/sealed-contract.ts
index aa6b99125..e58ba60e1 100644
--- a/plugins/codex-security/mcp-app/src/sealed-contract.ts
+++ b/plugins/codex-security/mcp-app/src/sealed-contract.ts
@@ -1,7 +1,7 @@
import { isDeepStrictEqual as sameArray } from "node:util";
import { createHash, hash } from "node:crypto";
import { lstat, readFile, realpath } from "node:fs/promises";
-import { dirname, join, resolve } from "node:path";
+import { dirname, join, resolve, win32 } from "node:path";
import { fileURLToPath } from "node:url";
import { setImmediate } from "node:timers/promises";
import Ajv2020, { type ErrorObject } from "ajv/dist/2020.js";
@@ -755,7 +755,18 @@ async function verifyScanRoot(
}
async function requireOwnedScanRoot(path: string): Promise<void> {
- if (process.platform === "win32") return;
+ if (process.platform === "win32") {
+ const error = windowsBinding().validateWindowsOutputPath(
+ widePath(win32.toNamespacedPath(path)),
+ false,
+ );
+ if (error !== 0) {
+ throw new ContractValidationError(
+ `Scan output directory or its parent could not be trusted (Windows error ${error}): ${path}`,
+ );
+ }
+ return;
+ }
const effectiveUid = process.geteuid?.();
const metadata = await lstat(encodePosixPath(path));
if (effectiveUid !== undefined && metadata.uid !== effectiveUid)
diff --git a/plugins/codex-security/native/Cargo.toml b/plugins/codex-security/native/Cargo.toml
index 6d5a5be97..77cdb5969 100644
--- a/plugins/codex-security/native/Cargo.toml
+++ b/plugins/codex-security/native/Cargo.toml
@@ -17,7 +17,7 @@ napi-derive = { version = "=3.7.0", default-features = false, features = ["stric
libc = "=0.2.191" # Requalify the Unix account lookup on glibc, musl, and macOS when updating these bindings.
[target.'cfg(windows)'.dependencies]
-windows-sys = { version = "=0.61.2", features = ["Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_Environment", "Win32_System_Threading", "Win32_System_JobObjects"] }
+windows-sys = { version = "=0.61.2", features = ["Wdk_Foundation", "Wdk_Storage_FileSystem", "Win32_System_IO", "Win32_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_Environment", "Win32_System_Threading", "Win32_System_JobObjects"] }
[build-dependencies]
napi-build = "=2.6.0" # notices.mts supplies the license for this exact release.
diff --git a/plugins/codex-security/native/src/lib.rs b/plugins/codex-security/native/src/lib.rs
index 69e29138d..c6e8806d7 100644
--- a/plugins/codex-security/native/src/lib.rs
+++ b/plugins/codex-security/native/src/lib.rs
@@ -7,3 +7,5 @@ mod scan_read_windows;
mod unix;
#[cfg(windows)]
mod windows;
+#[cfg(windows)]
+mod windows_output;
diff --git a/plugins/codex-security/native/src/windows.rs b/plugins/codex-security/native/src/windows.rs
index 019f55a07..66c5012e3 100644
--- a/plugins/codex-security/native/src/windows.rs
+++ b/plugins/codex-security/native/src/windows.rs
@@ -14,19 +14,19 @@ use std::{
};
use windows_sys::Win32::{
Foundation::{
- GetLastError, LocalFree, SetLastError, ERROR_FILE_NOT_FOUND, ERROR_INVALID_HANDLE,
- ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED, HANDLE, INVALID_HANDLE_VALUE,
+ GetLastError, LocalFree, SetLastError, ERROR_ACCESS_DENIED, ERROR_FILE_NOT_FOUND,
+ ERROR_INVALID_HANDLE, ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED, HANDLE,
+ INVALID_HANDLE_VALUE,
},
Security::{
Authorization::{
ConvertSidToStringSidA, ConvertStringSecurityDescriptorToSecurityDescriptorW,
SDDL_REVISION_1,
},
- GetTokenInformation, TokenUser, SECURITY_ATTRIBUTES, SECURITY_MAX_SID_SIZE, TOKEN_QUERY,
- TOKEN_USER,
+ GetTokenInformation, TokenUser, SECURITY_ATTRIBUTES,
},
Storage::FileSystem::*,
- System::Threading::{GetCurrentProcess, OpenProcessToken},
+ System::{SystemServices::SE_TOKEN_USER, Threading::GetCurrentProcess},
};
fn invalid(message: &str) -> napi::Error {
@@ -41,8 +41,10 @@ fn status(success: i32) -> u32 {
}
}
-fn io_error(error: io::Error) -> u32 {
- error.raw_os_error().unwrap() as u32
+pub(crate) fn io_error(error: io::Error) -> u32 {
+ error
+ .raw_os_error()
+ .map_or(ERROR_ACCESS_DENIED, |code| code as u32)
}
fn io_status(result: io::Result<()>) -> u32 {
@@ -85,7 +87,7 @@ fn wide_bytes(units: impl IntoIterator<Item = u16>) -> Buffer {
.into()
}
-fn os_string(bytes: Buffer) -> napi::Result<OsString> {
+pub(crate) fn os_string(bytes: Buffer) -> napi::Result<OsString> {
let path = wide_path(bytes)?;
Ok(OsString::from_wide(&path[..path.len() - 1]))
}
@@ -655,48 +657,54 @@ pub fn create_windows_directories(path: Buffer) -> napi::Result<u32> {
Ok(io_status(fs::create_dir_all(os_string(path)?)))
}
-#[napi]
-pub fn create_private_windows_directory(path: Buffer) -> napi::Result<u32> {
- let path = wide_path(path)?;
- let mut token = null_mut();
- let error = status(unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) });
- if error != 0 {
- return Ok(error);
- }
- let token = unsafe { OwnedHandle::from_raw_handle(token) };
- // TOKEN_USER is followed by the SID; use Windows' defined maximum SID size.
- #[repr(C)]
- struct TokenUserBuffer {
- user: TOKEN_USER,
- sid: [u8; SECURITY_MAX_SID_SIZE as usize],
- }
- let mut user = TokenUserBuffer {
- user: TOKEN_USER::default(),
- sid: [0; SECURITY_MAX_SID_SIZE as usize],
- };
+pub(crate) fn current_user_sid() -> Result<String, u32> {
+ // GetCurrentProcessToken() is the SDK's query-only pseudo-handle.
+ const CURRENT_PROCESS_TOKEN: HANDLE = -4isize as HANDLE;
+ let mut user = SE_TOKEN_USER::default();
let mut length = 0;
let error = status(unsafe {
GetTokenInformation(
- token.as_raw_handle(),
+ CURRENT_PROCESS_TOKEN,
TokenUser,
- (&mut user as *mut TokenUserBuffer).cast(),
- size_of::<TokenUserBuffer>() as u32,
+ (&raw mut user).cast(),
+ size_of::<SE_TOKEN_USER>() as u32,
&mut length,
)
});
if error != 0 {
- return Ok(error);
+ return Err(error);
}
+ // GetTokenInformation filled the inline user SID in this buffer.
+ unsafe { sid_string(user.Anonymous1.User.Sid) }
+}
+
+/// The SID must remain valid until Windows has copied its string representation.
+pub(crate) unsafe fn sid_string(value: windows_sys::Win32::Security::PSID) -> Result<String, u32> {
let mut sid = null_mut();
- let error = status(unsafe { ConvertSidToStringSidA(user.user.User.Sid, &mut sid) });
+ let error = status(unsafe { ConvertSidToStringSidA(value, &mut sid) });
if error != 0 {
- return Ok(error);
+ return Err(error);
}
- let descriptor = format!(
- "D:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FA;;;{})",
- unsafe { CStr::from_ptr(sid.cast()) }.to_str().unwrap()
- );
+ // A string SID contains only ASCII digits, hyphens and the S prefix.
+ let text = unsafe { CStr::from_ptr(sid.cast()) }
+ .to_str()
+ .unwrap()
+ .to_owned();
unsafe { LocalFree(sid.cast()) };
+ Ok(text)
+}
+
+#[napi]
+pub fn create_private_windows_directory(
+ path: Buffer,
+ check_output: Option<bool>,
+) -> napi::Result<u32> {
+ let path = wide_path(path)?;
+ let sid = match current_user_sid() {
+ Ok(sid) => sid,
+ Err(error) => return Ok(error),
+ };
+ let descriptor = format!("D:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FA;;;{sid})");
let mut attributes = SECURITY_ATTRIBUTES {
nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
..Default::default()
@@ -714,7 +722,19 @@ pub fn create_private_windows_directory(path: Buffer) -> napi::Result<u32> {
if error != 0 {
return Ok(error);
}
- let error = status(unsafe { CreateDirectoryW(path.as_ptr(), &attributes) });
+ let error = if check_output == Some(true) {
+ let target = OsString::from_wide(&path[..path.len() - 1]);
+ crate::windows_output::inspect_output_path(
+ std::path::Path::new(&target),
+ &sid,
+ Some(attributes.lpSecurityDescriptor),
+ None,
+ None,
+ )
+ .map_or_else(|error| error, |()| 0)
+ } else {
+ status(unsafe { CreateDirectoryW(path.as_ptr(), &attributes) })
+ };
unsafe { LocalFree(attributes.lpSecurityDescriptor) };
Ok(error)
}
diff --git a/plugins/codex-security/native/src/windows_output.rs b/plugins/codex-security/native/src/windows_output.rs
new file mode 100644
index 000000000..94111f6b8
--- /dev/null
+++ b/plugins/codex-security/native/src/windows_output.rs
@@ -0,0 +1,358 @@
+use crate::windows::{current_user_sid, io_error, os_string, sid_string};
+use napi::bindgen_prelude::Buffer;
+use napi_derive::napi;
+use std::{
+ collections::HashMap,
+ ffi::OsStr,
+ fs::{File, OpenOptions},
+ mem::size_of,
+ os::windows::{
+ ffi::OsStrExt,
+ fs::{MetadataExt, OpenOptionsExt},
+ io::{AsRawHandle, FromRawHandle},
+ },
+ path::Path,
+ ptr::{null, null_mut},
+};
+use windows_sys::Wdk::{
+ Foundation::OBJECT_ATTRIBUTES,
+ Storage::FileSystem::{
+ NtCreateFile, FILE_CREATE, FILE_DIRECTORY_FILE, FILE_OPEN, FILE_OPEN_REPARSE_POINT,
+ },
+};
+use windows_sys::Win32::{
+ Foundation::{
+ GetLastError, LocalFree, RtlNtStatusToDosError, ERROR_ACCESS_DENIED, ERROR_ALREADY_EXISTS,
+ ERROR_FILENAME_EXCED_RANGE, ERROR_FILE_NOT_FOUND, ERROR_INSUFFICIENT_BUFFER,
+ ERROR_INVALID_ACL, ERROR_PATH_NOT_FOUND, GENERIC_ALL, GENERIC_WRITE, OBJ_CASE_INSENSITIVE,
+ OBJ_DONT_REPARSE, UNICODE_STRING,
+ },
+ Security::{
+ Authorization::{GetSecurityInfo, SE_FILE_OBJECT},
+ LookupAccountSidW, SidTypeUser, ACL, DACL_SECURITY_INFORMATION, INHERIT_ONLY_ACE,
+ OWNER_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR, PSID,
+ },
+ Storage::FileSystem::{
+ DELETE, FILE_ADD_SUBDIRECTORY, FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_NORMAL,
+ FILE_ATTRIBUTE_REPARSE_POINT, FILE_DELETE_CHILD, FILE_FLAG_BACKUP_SEMANTICS,
+ FILE_FLAG_OPEN_REPARSE_POINT, FILE_READ_ATTRIBUTES, FILE_SHARE_READ, FILE_SHARE_WRITE,
+ FILE_TRAVERSE, FILE_WRITE_ATTRIBUTES, FILE_WRITE_DATA, READ_CONTROL, WRITE_DAC,
+ WRITE_OWNER,
+ },
+};
+
+use windows_sys::Win32::System::IO::IO_STATUS_BLOCK;
+
+const CHANGE_ACL: u32 = WRITE_DAC | WRITE_OWNER;
+const SET_REPARSE_POINT: u32 = FILE_WRITE_ATTRIBUTES | FILE_WRITE_DATA;
+const OUTPUT_RIGHTS: u32 =
+ FILE_ADD_SUBDIRECTORY | FILE_DELETE_CHILD | DELETE | CHANGE_ACL | SET_REPARSE_POINT;
+const EVERYONE: &str = "S-1-1-0";
+const AUTHENTICATED_USERS: &str = "S-1-5-11";
+
+fn trusted(sid: &str, user: &str) -> bool {
+ sid == user
+ || matches!(
+ sid,
+ "S-1-5-18" // SYSTEM
+ | "S-1-5-32-544" // Administrators
+ | "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464" // TrustedInstaller
+ )
+}
+
+fn named_authenticated_user(sid: PSID, text: &str) -> bool {
+ // Account-domain SIDs also identify groups and the Guest account.
+ if !text.starts_with("S-1-5-21-") || text.ends_with("-501") {
+ return false;
+ }
+ let (mut names, mut domains, mut kind) = (0, 0, 0);
+ let lookup = |name, names: &mut u32, domain, domains: &mut u32, kind: &mut i32| unsafe {
+ LookupAccountSidW(null(), sid, name, names, domain, domains, kind)
+ };
+ lookup(null_mut(), &mut names, null_mut(), &mut domains, &mut kind);
+ if unsafe { GetLastError() } != ERROR_INSUFFICIENT_BUFFER {
+ return false;
+ }
+ let (mut name, mut domain) = (vec![0; names as usize], vec![0; domains as usize]);
+ lookup(
+ name.as_mut_ptr(),
+ &mut names,
+ domain.as_mut_ptr(),
+ &mut domains,
+ &mut kind,
+ ) != 0
+ && kind == SidTypeUser
+}
+
+fn inspect_dacl(acl: *const ACL, user: &str) -> Result<u32, u32> {
+ if acl.is_null() {
+ return Ok(OUTPUT_RIGHTS); // A NULL DACL grants everyone full access.
+ }
+ let mut grants = 0;
+ let mut denied = HashMap::<String, u32>::new();
+ // GetSecurityInfo owns the ACL and its ACEs in one descriptor until LocalFree.
+ let header = unsafe { &*acl };
+ let bytes = unsafe { std::slice::from_raw_parts(acl.cast::<u8>(), header.AclSize.into()) };
+ let mut entries = bytes.get(size_of::<ACL>()..).ok_or(ERROR_INVALID_ACL)?;
+ for _ in 0..header.AceCount {
+ let &[kind, flags, low, high, ..] = entries else {
+ return Err(ERROR_INVALID_ACL);
+ };
+ let size = usize::from(u16::from_le_bytes([low, high]));
+ if size < 4 {
+ return Err(ERROR_INVALID_ACL);
+ }
+ let (bytes, rest) = entries.split_at_checked(size).ok_or(ERROR_INVALID_ACL)?;
+ entries = rest;
+ if u32::from(flags) & INHERIT_ONLY_ACE != 0 {
+ continue;
+ }
+ // Every access ACE starts with its four-byte header and access mask.
+ let (mask, payload) = bytes[4..]
+ .split_first_chunk::<4>()
+ .ok_or(ERROR_INVALID_ACL)?;
+ let mut mask = u32::from_le_bytes(*mask);
+ if mask & GENERIC_ALL != 0 {
+ mask |= OUTPUT_RIGHTS;
+ }
+ if mask & GENERIC_WRITE != 0 {
+ mask |= FILE_ADD_SUBDIRECTORY | SET_REPARSE_POINT;
+ }
+ mask &= OUTPUT_RIGHTS;
+ if mask == 0 {
+ continue;
+ }
+ // ACCESS_ALLOWED, ACCESS_DENIED, their object and callback variants.
+ // A conditional deny cannot prove that another identity lacks access.
+ let sid_bytes = match kind {
+ 0 | 1 | 9 => payload,
+ 5 | 6 | 11 => {
+ let (flags, rest) = payload.split_first_chunk::<4>().ok_or(ERROR_INVALID_ACL)?;
+ let flags = u32::from_le_bytes(*flags);
+ if kind == 6 && flags & 1 != 0 {
+ continue; // Object-specific deny.
+ }
+ rest.get(16 * (flags & 3).count_ones() as usize..)
+ .ok_or(ERROR_INVALID_ACL)?
+ }
+ 10 | 12 => continue, // Conditional deny.
+ _ => return Err(ERROR_INVALID_ACL),
+ };
+ let (sid_header, subauthorities) = sid_bytes
+ .split_first_chunk::<8>()
+ .ok_or(ERROR_INVALID_ACL)?;
+ if subauthorities.len() < 4 * usize::from(sid_header[1]) {
+ return Err(ERROR_INVALID_ACL);
+ }
+ let raw_sid = sid_bytes.as_ptr().cast_mut().cast();
+ let sid = unsafe { sid_string(raw_sid) }?;
+ if trusted(&sid, user) || sid == "S-1-3-4" {
+ continue; // OWNER RIGHTS applies to the already-verified owner.
+ }
+ if matches!(kind, 1 | 6) {
+ *denied.entry(sid).or_default() |= mask;
+ } else {
+ let mut excluded =
+ denied.get(EVERYONE).copied().unwrap_or(0) | denied.get(&sid).copied().unwrap_or(0);
+ if let Some(&authenticated) = denied.get(AUTHENTICATED_USERS) {
+ if mask & authenticated != 0 && named_authenticated_user(raw_sid, &sid) {
+ excluded |= authenticated;
+ }
+ }
+ grants |= mask & !excluded;
+ }
+ }
+ Ok(if grants & CHANGE_ACL != 0 {
+ OUTPUT_RIGHTS
+ } else {
+ grants
+ })
+}
+
+fn output_rights(file: &File, user: &str) -> Result<u32, u32> {
+ let attributes = file.metadata().map_err(io_error)?.file_attributes();
+ if attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)
+ != FILE_ATTRIBUTE_DIRECTORY
+ {
+ return Err(ERROR_ACCESS_DENIED);
+ }
+ let mut owner = null_mut();
+ let mut acl = null_mut();
+ let mut descriptor = null_mut();
+ let error = unsafe {
+ GetSecurityInfo(
+ file.as_raw_handle(),
+ SE_FILE_OBJECT,
+ OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
+ &mut owner,
+ null_mut(),
+ &mut acl,
+ null_mut(),
+ &mut descriptor,
+ )
+ };
+ if error != 0 {
+ return Err(error);
+ }
+ let rights = unsafe { sid_string(owner) }.and_then(|sid| {
+ if trusted(&sid, user) {
+ inspect_dacl(acl, user)
+ } else {
+ Err(ERROR_ACCESS_DENIED)
+ }
+ });
+ unsafe { LocalFree(descriptor) };
+ rights
+}
+
+const PIN_ACCESS: u32 = FILE_TRAVERSE | FILE_READ_ATTRIBUTES | READ_CONTROL;
+
+fn relative_directory(
+ parent: &File,
+ name: &OsStr,
+ descriptor: Option<PSECURITY_DESCRIPTOR>,
+) -> Result<File, u32> {
+ let mut units: Vec<_> = name.encode_wide().collect();
+ let length = u16::try_from(units.len() * 2).map_err(|_| ERROR_FILENAME_EXCED_RANGE)?;
+ let mut name = UNICODE_STRING {
+ Buffer: units.as_mut_ptr(),
+ Length: length,
+ MaximumLength: length,
+ };
+ let attributes = OBJECT_ATTRIBUTES {
+ Length: size_of::<OBJECT_ATTRIBUTES>() as u32,
+ RootDirectory: parent.as_raw_handle(),
+ ObjectName: &mut name,
+ Attributes: OBJ_CASE_INSENSITIVE | OBJ_DONT_REPARSE,
+ SecurityDescriptor: descriptor.unwrap_or(null_mut()).cast(),
+ ..Default::default()
+ };
+ let mut handle = null_mut();
+ let mut io = IO_STATUS_BLOCK::default();
+ let status = unsafe {
+ NtCreateFile(
+ &mut handle,
+ PIN_ACCESS,
+ &attributes,
+ &mut io,
+ null(),
+ FILE_ATTRIBUTE_NORMAL,
+ FILE_SHARE_READ | FILE_SHARE_WRITE,
+ if descriptor.is_some() {
+ FILE_CREATE
+ } else {
+ FILE_OPEN
+ },
+ FILE_DIRECTORY_FILE | FILE_OPEN_REPARSE_POINT,
+ null(),
+ 0,
+ )
+ };
+ if status < 0 {
+ return Err(unsafe { RtlNtStatusToDosError(status) });
+ }
+ Ok(unsafe { File::from_raw_handle(handle) })
+}
+
+/// Open each directory relative to its verified parent, including creation of
+/// a missing leaf. A reparse point added to an empty directory cannot redirect
+/// an absolute-path operation beyond the directory whose ACL we inspected.
+/// For validation, an omitted writable_leaf preflights a prospective path.
+/// Both read and write validation of a selected directory require it to exist.
+pub(crate) fn inspect_output_path(
+ path: &Path,
+ user: &str,
+ create: Option<PSECURITY_DESCRIPTOR>,
+ writable_leaf: Option<bool>,
+ retained_directory: Option<&OsStr>,
+) -> Result<(), u32> {
+ let mut ancestors: Vec<File> = Vec::new();
+ let mut parent = 0;
+ for entry in path.ancestors().collect::<Vec<_>>().into_iter().rev() {
+ let opened = if let Some(handle) = ancestors.last() {
+ relative_directory(handle, entry.file_name().ok_or(ERROR_ACCESS_DENIED)?, None)
+ } else {
+ OpenOptions::new()
+ .access_mode(PIN_ACCESS)
+ .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
+ .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS)
+ .open(entry)
+ .map_err(io_error)
+ };
+ let file = match opened {
+ Ok(file) => file,
+ Err(error @ (ERROR_FILE_NOT_FOUND | ERROR_PATH_NOT_FOUND)) => {
+ if replaceable(parent, 0) {
+ return Err(ERROR_ACCESS_DENIED);
+ }
+ if create.is_none() {
+ return if writable_leaf.is_some() {
+ Err(error)
+ } else {
+ Ok(())
+ };
+ }
+ if entry != path {
+ return Err(ERROR_PATH_NOT_FOUND);
+ }
+ relative_directory(
+ ancestors.last().ok_or(ERROR_PATH_NOT_FOUND)?,
+ entry.file_name().ok_or(ERROR_ACCESS_DENIED)?,
+ create,
+ )?;
+ return Ok(());
+ }
+ Err(error) => return Err(error),
+ };
+ let rights = output_rights(&file, user)?;
+ if replaceable(parent, rights) {
+ return Err(ERROR_ACCESS_DENIED);
+ }
+ if entry == path && writable_leaf == Some(true) && rights & SET_REPARSE_POINT != 0 {
+ // Windows can retag only an empty directory. A known child that
+ // another user cannot remove keeps a resumed output nonempty.
+ let name = retained_directory
+ .filter(|name| Path::new(name).file_name() == Some(*name))
+ .ok_or(ERROR_ACCESS_DENIED)?;
+ if rights & FILE_DELETE_CHILD != 0 {
+ return Err(ERROR_ACCESS_DENIED);
+ }
+ let child = relative_directory(&file, name, None)?;
+ if output_rights(&child, user)? & DELETE != 0 {
+ return Err(ERROR_ACCESS_DENIED);
+ }
+ }
+ ancestors.push(file);
+ parent = rights;
+ }
+ if create.is_some() {
+ Err(ERROR_ALREADY_EXISTS)
+ } else {
+ Ok(())
+ }
+}
+
+fn replaceable(parent: u32, child: u32) -> bool {
+ parent & (FILE_ADD_SUBDIRECTORY | SET_REPARSE_POINT) != 0
+ && (parent & FILE_DELETE_CHILD != 0 || child & DELETE != 0)
+}
+
+#[napi]
+pub fn validate_windows_output_path(
+ path: Buffer,
+ writable_leaf: Option<bool>,
+ retained_directory: Option<String>,
+) -> napi::Result<u32> {
+ let path = os_string(path)?;
+ Ok(current_user_sid()
+ .and_then(|user| {
+ inspect_output_path(
+ Path::new(&path),
+ &user,
+ None,
+ writable_leaf,
+ retained_directory.as_deref().map(OsStr::new),
+ )
+ })
+ .map_or_else(|e| e, |_| 0))
+}
diff --git a/plugins/codex-security/native/windows-binding.mts b/plugins/codex-security/native/windows-binding.mts
index dbf908f09..45f51c8dc 100644
--- a/plugins/codex-security/native/windows-binding.mts
+++ b/plugins/codex-security/native/windows-binding.mts
@@ -43,7 +43,12 @@ export interface WindowsBinding {
flags: number,
): { error: number; handle?: WindowsHandle | null };
createWindowsDirectories(path: Buffer): number;
- createPrivateWindowsDirectory(path: Buffer): number;
+ createPrivateWindowsDirectory(path: Buffer, checkOutput?: boolean): number;
+ validateWindowsOutputPath(
+ path: Buffer,
+ writableLeaf?: boolean,
+ retainedDirectory?: string,
+ ): number;
}
export { windowsFlags } from "./windows-flags.mjs";
diff --git a/plugins/codex-security/scripts/deep_scan_workbench.py b/plugins/codex-security/scripts/deep_scan_workbench.py
index c15896d7a..98c9999ff 100644
--- a/plugins/codex-security/scripts/deep_scan_workbench.py
+++ b/plugins/codex-security/scripts/deep_scan_workbench.py
@@ -793,11 +793,8 @@ def begin_deep_scan_for_target(
workflow_version = optional_text(args.workflow_version, maximum=256)
if workflow_version is None:
raise SystemExit("workflow-version is required.")
- root = dependencies().resolve_scan_root(args.scan_root)
- target_root = (root / dependencies().safe_segment(target.name)).resolve()
- if target_root == target or target in target_root.parents:
- raise SystemExit("The scan artifact directory must be outside the selected target.")
- create_private_directory(target_root)
+ target_root = dependencies().scan_target_root(args.scan_root, target)
+ create_private_directory(target_root, scan_output=True)
model = optional_text(args.model, maximum=200)
reasoning_effort = optional_text(args.reasoning_effort, maximum=32)
workspace_id = str(uuid.uuid4())
diff --git a/plugins/codex-security/scripts/windows_scan_local_files.py b/plugins/codex-security/scripts/windows_scan_local_files.py
index 81a4a274c..c3c6b6ad4 100644
--- a/plugins/codex-security/scripts/windows_scan_local_files.py
+++ b/plugins/codex-security/scripts/windows_scan_local_files.py
@@ -25,10 +25,12 @@ import contextlib
import ctypes
import ctypes.wintypes as wintypes
import errno
+import functools
import importlib
import ntpath
import os
import secrets
+import struct
from collections.abc import Callable, Iterator
from pathlib import Path, PurePosixPath
from typing import BinaryIO
@@ -47,8 +49,16 @@ class WindowsScanLocalPathError(WindowsScanLocalFileError):
# CreateFile access and sharing flags.
_DRIVE_FIXED = 3
_DELETE = 0x00010000
+_FILE_ADD_SUBDIRECTORY = 0x00000004
+_FILE_DELETE_CHILD = 0x00000040
+_CHANGE_ACL = 0x000C0000 # WRITE_DAC | WRITE_OWNER
+_SET_REPARSE_POINT = 0x00000102 # FILE_WRITE_ATTRIBUTES | FILE_WRITE_DATA
+_OUTPUT_RIGHTS = (
+ _DELETE | _FILE_ADD_SUBDIRECTORY | _FILE_DELETE_CHILD | _CHANGE_ACL | _SET_REPARSE_POINT
+)
_FILE_TRAVERSE = 0x00000020
_FILE_READ_ATTRIBUTES = 0x00000080
+_READ_CONTROL = 0x00020000
_GENERIC_READ = 0x80000000
_GENERIC_WRITE = 0x40000000
_FILE_SHARE_READ = 0x00000001
@@ -122,9 +132,9 @@ class _FileAttributeTagInfo(ctypes.Structure):
class _SecurityAttributes(ctypes.Structure):
_fields_ = [
- ("nLength", wintypes.DWORD),
- ("lpSecurityDescriptor", wintypes.LPVOID),
- ("bInheritHandle", wintypes.BOOL),
+ ("length", wintypes.DWORD),
+ ("descriptor", wintypes.LPVOID),
+ ("inherit", wintypes.BOOL),
]
@@ -172,6 +182,7 @@ class _OwnedHandle:
if os.name == "nt":
_kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
_advapi32 = ctypes.WinDLL("advapi32", use_last_error=True)
+ _ntdll = ctypes.WinDLL("ntdll")
_GetFileSecurityW = _advapi32.GetFileSecurityW
_GetFileSecurityW.argtypes = [
@@ -516,16 +527,285 @@ def _directory_security_descriptor(source: Path, information: int) -> ctypes.Arr
return descriptor
+def _sid_text(sid: wintypes.LPVOID) -> str:
+ value = wintypes.LPWSTR()
+ if not _advapi32.ConvertSidToStringSidW(sid, ctypes.byref(value)):
+ _raise_last_error("ConvertSidToStringSidW")
+ try:
+ return value.value
+ finally:
+ _kernel32.LocalFree(value)
+
+
+def _current_user_sid() -> str:
+ token = wintypes.HANDLE(-4) # GetCurrentProcessToken pseudo-handle.
+ size = wintypes.DWORD()
+ _advapi32.GetTokenInformation(token, 1, None, 0, ctypes.byref(size))
+ if ctypes.get_last_error() != _ERROR_INSUFFICIENT_BUFFER:
+ _raise_last_error("GetTokenInformation")
+ user = ctypes.create_string_buffer(size.value)
+ if not _advapi32.GetTokenInformation(token, 1, user, size, ctypes.byref(size)):
+ _raise_last_error("GetTokenInformation")
+ return _sid_text(wintypes.LPVOID.from_buffer(user))
+
+
+def _output_directory_grants(handle: int, path: Path) -> int:
+ """Inspect the descriptor of the opened directory, even if its pathname changes."""
+ owner, acl, descriptor = wintypes.LPVOID(), wintypes.LPVOID(), wintypes.LPVOID()
+ status = _advapi32.GetSecurityInfo(
+ wintypes.HANDLE(handle),
+ 1,
+ _OWNER_SECURITY_INFORMATION | _DACL_SECURITY_INFORMATION,
+ ctypes.byref(owner),
+ None,
+ ctypes.byref(acl),
+ None,
+ ctypes.byref(descriptor),
+ )
+ if status:
+ raise ctypes.WinError(status)
+ try:
+ trusted = {
+ _current_user_sid(),
+ "S-1-5-18",
+ "S-1-5-32-544", # Current user, SYSTEM, Administrators.
+ "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464", # TrustedInstaller.
+ }
+ if _sid_text(owner) not in trusted:
+ raise _invalid_path(path, "Scan output directory must have a trusted owner.")
+ return _output_dacl_grants(acl, trusted, path)
+ finally:
+ _kernel32.LocalFree(descriptor)
+
+
+def _authenticated_account(sid: wintypes.LPVOID, trustee: str) -> bool:
+ # The Guest account can have its own SID without Authenticated Users membership.
+ if not trustee.startswith("S-1-5-21-") or trustee.endswith("-501"):
+ return False
+ name_size, domain_size, sid_type = (ctypes.pointer(wintypes.DWORD()) for _ in range(3))
+ lookup = _advapi32.LookupAccountSidW
+ lookup(None, sid, None, name_size, None, domain_size, sid_type)
+ if ctypes.get_last_error() != _ERROR_INSUFFICIENT_BUFFER:
+ return False
+ name = ctypes.create_unicode_buffer(name_size.contents.value)
+ domain = ctypes.create_unicode_buffer(domain_size.contents.value)
+ found = lookup(None, sid, name, name_size, domain, domain_size, sid_type)
+ return bool(found) and sid_type.contents.value == 1 # SidTypeUser
+
+
+def _output_dacl_grants(acl: wintypes.LPVOID, trusted: set[str], path: Path) -> int:
+ if not acl.value: # A NULL DACL grants full access.
+ return _OUTPUT_RIGHTS
+ # Read ACEs in DACL order. A deny masks future grants for its trustee.
+ denied: dict[str, int] = {}
+ granted = 0
+ for index in range(wintypes.WORD.from_address(acl.value + 4).value): # ACL.AceCount
+ ace = wintypes.LPVOID()
+ if not _advapi32.GetAce(acl, index, ctypes.byref(ace)):
+ _raise_last_error("GetAce", path)
+ kind, flags, size = struct.unpack("<BBH", ctypes.string_at(ace, 4))
+ if flags & 8 or kind in {10, 12}: # INHERIT_ONLY or conditional deny.
+ continue
+ entry = ctypes.string_at(ace, size)
+ mask = struct.unpack_from("<I", entry, 4)[0]
+ if mask & 0x10000000: # GENERIC_ALL
+ mask |= _OUTPUT_RIGHTS
+ if mask & _GENERIC_WRITE:
+ mask |= _FILE_ADD_SUBDIRECTORY | _SET_REPARSE_POINT
+ mask &= _OUTPUT_RIGHTS
+ if not mask:
+ continue
+ offset = 8 # ACE_HEADER and ACCESS_MASK precede the trustee SID.
+ if kind in {5, 6, 11}:
+ object_flags = struct.unpack_from("<I", entry, offset)[0]
+ offset += 4 + 16 * (object_flags & 3).bit_count()
+ if kind == 6 and object_flags & 1:
+ continue # This deny is scoped to a particular object type.
+ elif kind not in {0, 1, 9}:
+ raise _invalid_path(path, "Unable to evaluate scan output directory permissions.")
+ if len(entry) < offset + 8 or len(entry) < offset + 8 + 4 * entry[offset + 1]:
+ raise _invalid_path(path, "Invalid scan output directory trustee.")
+ sid = wintypes.LPVOID(ace.value + offset)
+ trustee = _sid_text(sid)
+ if trustee in trusted or trustee == "S-1-3-4": # OWNER RIGHTS applies to the checked owner.
+ continue
+ if kind in {1, 6}:
+ denied[trustee] = denied.get(trustee, 0) | mask
+ else:
+ blocked = denied.get(trustee, 0) | denied.get("S-1-1-0", 0)
+ authenticated = denied.get("S-1-5-11", 0)
+ if mask & authenticated and _authenticated_account(sid, trustee):
+ blocked |= authenticated
+ granted |= mask & ~blocked
+ if granted & _CHANGE_ACL:
+ granted |= _OUTPUT_RIGHTS
+ return granted
+
+
+def _require_stable_output(path: Path, parent_grants: int, child_grants: int = 0) -> None:
+ can_remove = parent_grants & _FILE_DELETE_CHILD or child_grants & _DELETE
+ can_replace = parent_grants & (_FILE_ADD_SUBDIRECTORY | _SET_REPARSE_POINT)
+ if can_remove and can_replace:
+ raise _invalid_path(path, "Scan output directory can be replaced by another user.")
+
+
+def _checked_output_directory(path: Path) -> Iterator[tuple[int, int]]:
+ """Hold the checked canonical chain and expose its final directory handle and grants."""
+ parent_grants = 0
+ parent = None
+ with contextlib.ExitStack() as pins:
+ for directory in (*reversed(path.parents), path):
+ if parent is None:
+ handle = _create_file(
+ directory,
+ access=_FILE_TRAVERSE | _FILE_READ_ATTRIBUTES | _READ_CONTROL,
+ share=_FILE_SHARE_READ | _FILE_SHARE_WRITE,
+ disposition=_OPEN_EXISTING,
+ flags=_FILE_FLAG_BACKUP_SEMANTICS | _FILE_FLAG_OPEN_REPARSE_POINT,
+ )
+ assert handle is not None
+ else:
+ error, child = _relative_output_directory(parent, directory.name)
+ if error:
+ raise WindowsScanLocalPathError(
+ error, ctypes.FormatError(error), str(directory)
+ )
+ handle = _OwnedHandle(child)
+ pins.enter_context(handle)
+ assert handle.value is not None
+ _verify_directory(handle.value, directory)
+ grants = _output_directory_grants(handle.value, directory)
+ _require_stable_output(directory, parent_grants, grants)
+ parent, parent_grants = handle.value, grants
+ yield parent, parent_grants
+
+
+def require_windows_output_path(path: Path, *, writable_output: bool = False) -> None:
+ with _checked_output_directory(path) as (_, grants):
+ if writable_output and grants & _SET_REPARSE_POINT:
+ raise _invalid_path(
+ path, "Another user can turn the output directory into a reparse point when empty."
+ )
+
+
+class _UnicodeString(ctypes.Structure):
+ _fields_ = [
+ ("length", wintypes.USHORT),
+ ("capacity", wintypes.USHORT),
+ ("text", wintypes.LPWSTR),
+ ]
+
+
+class _ObjectAttributes(ctypes.Structure):
+ _fields_ = [
+ ("length", wintypes.ULONG),
+ ("root", wintypes.HANDLE),
+ ("name", ctypes.POINTER(_UnicodeString)),
+ ("attributes", wintypes.ULONG),
+ ("security", wintypes.LPVOID),
+ ("qos", wintypes.LPVOID),
+ ]
+
+
+def _relative_output_directory(
+ parent: int, basename: str, descriptor=None
+) -> tuple[int, int | None]:
+ """Open or create one component relative to its checked parent without reparsing it."""
+ size = len(basename.encode("utf-16-le", errors="surrogatepass"))
+ if size >= 1 << 16: # UNICODE_STRING.Length is a byte count in a USHORT.
+ return 206, None
+ name = _UnicodeString(size, size, basename)
+ attributes = _ObjectAttributes(
+ ctypes.sizeof(_ObjectAttributes),
+ parent,
+ ctypes.pointer(name),
+ 0x40 | 0x1000, # OBJ_CASE_INSENSITIVE | OBJ_DONT_REPARSE
+ descriptor,
+ None,
+ )
+ handle = wintypes.HANDLE()
+ io_status = (ctypes.c_void_p * 2)() # IO_STATUS_BLOCK
+ status = _ntdll.NtCreateFile(
+ ctypes.byref(handle),
+ _FILE_TRAVERSE | _FILE_READ_ATTRIBUTES | _READ_CONTROL | 0x100000,
+ ctypes.byref(attributes),
+ ctypes.byref(io_status),
+ None,
+ _FILE_ATTRIBUTE_NORMAL,
+ _FILE_SHARE_READ | _FILE_SHARE_WRITE,
+ 1 if descriptor is None else 2, # FILE_OPEN or FILE_CREATE
+ 0x200021, # FILE_OPEN_REPARSE_POINT | FILE_SYNCHRONOUS_IO_NONALERT | FILE_DIRECTORY_FILE
+ None,
+ 0,
+ )
+ return (_ntdll.RtlNtStatusToDosError(status), None) if status < 0 else (0, handle.value)
+
+
+def create_windows_output_directory(path: Path, descriptor: wintypes.LPVOID) -> int:
+ with _checked_output_directory(path.parent) as (parent, grants):
+ _require_stable_output(path, grants)
+ error, handle = _relative_output_directory(parent, path.name, descriptor)
+ if not error:
+ _close_handle(handle)
+ return error
+
+
+def create_private_directory(path: Path, *, exist_ok: bool, scan_output: bool) -> Path:
+ """Create one Windows directory with a protected inheritable DACL."""
+ _require_windows()
+ # Older supported Python releases ignore mkdir's 0700 mode on Windows.
+ # Apply the same owner/SYSTEM/Administrators policy at creation so a
+ # writable parent never becomes an inheritance window.
+ volume = ctypes.create_unicode_buffer(32768)
+ flags = wintypes.DWORD()
+ if not _kernel32.GetVolumePathNameW(str(path.parent.resolve()), volume, len(volume)):
+ raise ctypes.WinError(ctypes.get_last_error())
+ if not _kernel32.GetVolumeInformationW(
+ volume, None, 0, None, None, ctypes.byref(flags), None, 0
+ ):
+ raise ctypes.WinError(ctypes.get_last_error())
+ if not flags.value & 0x8: # FILE_PERSISTENT_ACLS
+ raise ValueError("Select a directory on a Windows volume that supports ACLs.")
+
+ sid = _current_user_sid()
+ owner = "" if exist_ok else f"O:{sid}"
+ dacl = f"{owner}D:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FA;;;{sid})"
+
+ descriptor = wintypes.LPVOID()
+ if not _advapi32.ConvertStringSecurityDescriptorToSecurityDescriptorW(
+ dacl, 1, ctypes.byref(descriptor), None
+ ):
+ raise ctypes.WinError(ctypes.get_last_error())
+ try:
+ if scan_output:
+ error = create_windows_output_directory(path, descriptor)
+ else:
+ attributes = _SecurityAttributes(ctypes.sizeof(_SecurityAttributes), descriptor, False)
+ error = (
+ 0
+ if _CreateDirectoryW(str(path), ctypes.byref(attributes))
+ else ctypes.get_last_error()
+ )
+ if not error:
+ return path if exist_ok else verify_private_scan_root(path, descriptor)
+ if exist_ok and error == 183 and path.is_dir(): # ERROR_ALREADY_EXISTS
+ if scan_output:
+ require_windows_output_path(path)
+ return path
+ raise ctypes.WinError(error)
+ finally:
+ _kernel32.LocalFree(descriptor)
+
+
def create_directory_with_same_dacl(path: Path, source: Path) -> None:
"""Create an archive replacement with the original directory's DACL."""
_require_windows()
descriptor = _directory_security_descriptor(source, _DACL_SECURITY_INFORMATION)
- 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)
+ error = create_windows_output_directory(path, ctypes.cast(descriptor, wintypes.LPVOID))
+ if error:
+ raise WindowsScanLocalFileError(error, ctypes.FormatError(error), str(path))
@contextlib.contextmanager
diff --git a/plugins/codex-security/scripts/workbench/storage.py b/plugins/codex-security/scripts/workbench/storage.py
index 4d9150fd0..85e5933f2 100644
--- a/plugins/codex-security/scripts/workbench/storage.py
+++ b/plugins/codex-security/scripts/workbench/storage.py
@@ -8,6 +8,9 @@ import tempfile
from pathlib import Path
from typing import Any
+if os.name == "nt":
+ import windows_scan_local_files as windows_files
+
def state_dir(*, canonical: bool = True) -> Path:
"""Return the workbench state path, resolving symlinks unless canonical is false."""
@@ -66,92 +69,16 @@ def saved_deep_workers(connection: sqlite3.Connection, scan: sqlite3.Row) -> lis
]
-def _create_private_windows_directory(path: Path, *, exist_ok: bool) -> Path:
- """Create one Windows directory with a protected inheritable DACL."""
- import ctypes
- import ctypes.wintypes
-
- from windows_scan_local_files import verify_private_scan_root
-
- class SecurityAttributes(ctypes.Structure):
- _fields_ = [
- ("length", ctypes.wintypes.DWORD),
- ("descriptor", ctypes.wintypes.LPVOID),
- ("inherit", ctypes.wintypes.BOOL),
- ]
-
- # Older supported Python releases ignore mkdir's 0700 mode on Windows.
- # Apply the same owner/SYSTEM/Administrators policy at creation so a
- # writable parent never becomes an inheritance window.
- kernel = ctypes.WinDLL("kernel32", use_last_error=True)
- volume = ctypes.create_unicode_buffer(32768)
- flags = ctypes.wintypes.DWORD()
- if not kernel.GetVolumePathNameW(str(path.parent.resolve()), volume, len(volume)):
- raise ctypes.WinError(ctypes.get_last_error())
- if not kernel.GetVolumeInformationW(volume, None, 0, None, None, ctypes.byref(flags), None, 0):
- raise ctypes.WinError(ctypes.get_last_error())
- if not flags.value & 0x8: # FILE_PERSISTENT_ACLS
- raise ValueError("Select a directory on a Windows volume that supports ACLs.")
-
- security = ctypes.WinDLL("advapi32", use_last_error=True)
- # GetCurrentProcessToken() is a Windows pseudo-handle and does not need closing.
- token = ctypes.wintypes.HANDLE(-4)
- token_user = 1 # TOKEN_INFORMATION_CLASS.TokenUser
- size = ctypes.wintypes.DWORD()
- security.GetTokenInformation(token, token_user, None, 0, ctypes.byref(size))
- if ctypes.get_last_error() != 122: # ERROR_INSUFFICIENT_BUFFER
- raise ctypes.WinError(ctypes.get_last_error())
- user = ctypes.create_string_buffer(size.value)
- if not security.GetTokenInformation(token, token_user, user, size, ctypes.byref(size)):
- raise ctypes.WinError(ctypes.get_last_error())
- # TOKEN_USER starts with SID_AND_ATTRIBUTES.Sid.
- sid = ctypes.wintypes.LPWSTR()
- if not security.ConvertSidToStringSidW(
- ctypes.wintypes.LPVOID.from_buffer(user), ctypes.byref(sid)
- ):
- raise ctypes.WinError(ctypes.get_last_error())
- try:
- owner = "" if exist_ok else f"O:{sid.value}"
- dacl = f"{owner}D:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FA;;;{sid.value})"
- finally:
- kernel.LocalFree(sid)
-
- descriptor = ctypes.wintypes.LPVOID()
- if not security.ConvertStringSecurityDescriptorToSecurityDescriptorW(
- dacl, 1, ctypes.byref(descriptor), None
- ):
- raise ctypes.WinError(ctypes.get_last_error())
- try:
- attributes = SecurityAttributes(ctypes.sizeof(SecurityAttributes), descriptor, False)
- if kernel.CreateDirectoryW(str(path), ctypes.byref(attributes)):
- if exist_ok:
- return path
- return verify_private_scan_root(path, descriptor)
- error = ctypes.get_last_error()
- if exist_ok and error == 183 and path.is_dir(): # ERROR_ALREADY_EXISTS
- return path
- raise ctypes.WinError(error)
- finally:
- kernel.LocalFree(descriptor)
-
-
-def create_private_directory(path: Path) -> None:
+def create_private_directory(path: Path, *, scan_output: bool = False) -> None:
"""Create missing directories privately without changing existing permissions."""
- if os.name == "nt" and path.is_dir():
- return
- try:
- if os.name == "nt":
- _create_private_windows_directory(path, exist_ok=True)
- else:
- path.mkdir(mode=0o700, exist_ok=True)
- except FileNotFoundError:
- if path.parent == path:
- raise
- create_private_directory(path.parent)
- if os.name == "nt":
- _create_private_windows_directory(path, exist_ok=True)
- else:
- path.mkdir(mode=0o700, exist_ok=True)
+ if path.parent != path and not path.parent.is_dir():
+ create_private_directory(path.parent, scan_output=scan_output)
+ if os.name != "nt":
+ path.mkdir(mode=0o700, exist_ok=True)
+ elif not path.is_dir():
+ windows_files.create_private_directory(path, exist_ok=True, scan_output=scan_output)
+ elif scan_output:
+ windows_files.require_windows_output_path(path)
def create_private_temporary_directory(parent: Path, *, prefix: str) -> Path:
@@ -164,7 +91,7 @@ def create_private_temporary_directory(parent: Path, *, prefix: str) -> Path:
for _ in range(100):
path = parent / f"{prefix}{secrets.token_hex(4)}"
try:
- return _create_private_windows_directory(path, exist_ok=False)
+ return windows_files.create_private_directory(path, exist_ok=False, scan_output=True)
except FileExistsError:
continue
raise FileExistsError(f"Could not create a unique directory beneath {parent}.")
diff --git a/plugins/codex-security/scripts/workbench_db.py b/plugins/codex-security/scripts/workbench_db.py
index 8ff80600b..f66ccc6e1 100644
--- a/plugins/codex-security/scripts/workbench_db.py
+++ b/plugins/codex-security/scripts/workbench_db.py
@@ -640,7 +640,9 @@ def save_workspace(connection: sqlite3.Connection, args: argparse.Namespace) ->
def scan_target_root(scan_root: str | None, target: Path) -> Path:
root = resolve_scan_root(scan_root)
- target_root = (root / safe_segment(target.name)).resolve()
+ target_root = root / safe_segment(target.name)
+ if os.name != "nt":
+ target_root = target_root.resolve()
if target_root == target or target in target_root.parents:
raise SystemExit("The scan artifact directory must be outside the selected target.")
return target_root
@@ -720,7 +722,7 @@ def start_scan(connection: sqlite3.Connection, args: argparse.Namespace) -> dict
diff_target_kind=diff_target["kind"] if diff_target is not None else None,
)
target_root = scan_target_root(args.scan_root, target)
- create_private_directory(target_root)
+ create_private_directory(target_root, scan_output=True)
require_working_tree_unchanged(target, diff_target)
if manages_transaction:
connection.execute("BEGIN IMMEDIATE")
@@ -892,7 +894,7 @@ def _start_prompt_driven_scan(
**scan_context(connection, existing["id"], model_thread_id=thread_id),
"startDisposition": "joined",
}
- create_private_directory(target_root)
+ create_private_directory(target_root, scan_output=True)
workspace_id = str(uuid.uuid4())
scan_id = str(uuid.uuid4())
timestamp = now()
@@ -1472,7 +1474,11 @@ def complete_scan_locked(
def require_cli_scan_directory(repository: Path, args: argparse.Namespace) -> Path:
- scan_dir = require_canonical_scan_directory(Path(args.scan_dir).expanduser())
+ # Registration uses an empty output, including the replacement created with
+ # the original DACL after archival. Check that ACL before moving any results.
+ scan_dir = require_canonical_scan_directory(
+ Path(args.scan_dir).expanduser(), writable_output=True
+ )
if scan_dir == repository or repository in scan_dir.parents or scan_dir in repository.parents:
raise SystemExit(
"The scan artifact directory must be outside and not contain the selected target."
@@ -3283,7 +3289,7 @@ def artifact_path(scan_dir: Path, file_name: str, *, required: bool) -> Path | N
return resolved
-def require_canonical_scan_directory(scan_dir: Path) -> Path:
+def require_canonical_scan_directory(scan_dir: Path, *, writable_output: bool = False) -> Path:
scan_dir = scan_dir.absolute()
try:
metadata = scan_dir.lstat()
@@ -3297,7 +3303,14 @@ def require_canonical_scan_directory(scan_dir: Path) -> Path:
):
raise SystemExit("Scan directory must be an existing canonical non-symlink directory.")
# Re-check ownership and parents so the scan directory cannot be substituted.
- if os.name != "nt":
+ if os.name == "nt":
+ from windows_scan_local_files import require_windows_output_path
+
+ try:
+ require_windows_output_path(scan_dir, writable_output=writable_output)
+ except OSError as exc:
+ raise SystemExit(str(exc)) from exc
+ else:
geteuid = getattr(os, "geteuid", None)
effective_uid = geteuid() if geteuid is not None else None
if effective_uid is not None and metadata.st_uid != effective_uid:
diff --git a/plugins/codex-security/tests/test_windows_workbench_output_permissions.py b/plugins/codex-security/tests/test_windows_workbench_output_permissions.py
index 99014086f..a453a6d59 100644
--- a/plugins/codex-security/tests/test_windows_workbench_output_permissions.py
+++ b/plugins/codex-security/tests/test_windows_workbench_output_permissions.py
@@ -2,7 +2,10 @@
from __future__ import annotations
+import argparse
+import base64
import os
+import string
import subprocess
import sys
from pathlib import Path
@@ -13,6 +16,7 @@ SCRIPTS = Path(__file__).resolve().parents[1] / "scripts"
sys.path.insert(0, str(SCRIPTS))
import windows_scan_local_files # noqa: E402
+import workbench_db # noqa: E402
from workbench import storage # noqa: E402
pytestmark = [
@@ -21,17 +25,152 @@ pytestmark = [
]
+def grant(path: Path, rights: str) -> None:
+ subprocess.run(["icacls.exe", str(path), "/grant", f"*S-1-1-0:{rights}"], check=True)
+
+
+def make_junction(path: Path, target: Path) -> None:
+ subprocess.run(["cmd", "/c", "mklink", "/J", str(path), str(target)], check=True)
+
+
+def test_missing_output_drive_reports_a_filesystem_error() -> None:
+ for letter in reversed(string.ascii_uppercase):
+ drive = Path(f"{letter}:/")
+ if not drive.is_dir():
+ with pytest.raises(OSError):
+ storage.create_private_directory(drive, scan_output=True)
+ return
+ pytest.skip("requires an unavailable drive letter")
+
+
+def test_scan_directory_checks_parent_replacement_rights(tmp_path: Path) -> None:
+ shared = tmp_path / "shared"
+ selected = shared / "selected"
+ selected.mkdir(parents=True)
+ grant(shared, "(AD)")
+ scan = storage.create_private_temporary_directory(selected, prefix="scan_")
+ assert workbench_db.require_canonical_scan_directory(scan) == scan
+ grant(selected, "(DE)")
+ with pytest.raises(OSError, match="can be replaced"):
+ storage.create_private_temporary_directory(selected, prefix="next_")
+ with pytest.raises(SystemExit, match="can be replaced"):
+ workbench_db.require_canonical_scan_directory(scan)
+
+
[email protected]("right", ["WA", "WD"])
+def test_registration_checks_reparse_access_before_archiving(tmp_path: Path, right: str) -> None:
+ output = tmp_path / "output"
+ output.mkdir()
+ grant(output, f"({right})")
+ args = argparse.Namespace(scan_dir=output, archive_existing=False, archived_scan_dir=None)
+ with pytest.raises(SystemExit, match="reparse point"):
+ workbench_db.require_cli_scan_directory(tmp_path / "repo", args)
+
+ saved = output / "result"
+ saved.write_text("synthetic result")
+ assert workbench_db.require_canonical_scan_directory(output) == output
+ args.archive_existing = True
+ with pytest.raises(SystemExit, match="reparse point"):
+ workbench_db.require_cli_scan_directory(tmp_path / "repo", args)
+ assert saved.read_text() == "synthetic result"
+
+
+ os.environ.get("GITHUB_ACTIONS") != "true",
+ reason="creates a disposable local account on a hosted Windows runner",
+)
+def test_native_directory_write_rights_for_setting_reparse_data(tmp_path: Path) -> None:
+ grant(tmp_path, "(OI)(CI)RX")
+ target = tmp_path / "synthetic target"
+ target.mkdir()
+ (target / "src").mkdir()
+ make_junction(tmp_path / "source junction", target)
+ leaves = {
+ "write attributes": "(WA)",
+ "write data": "(WD)",
+ "write data and attributes": "(WD,WA)",
+ "writable control": "M",
+ }
+ for name, rights in leaves.items():
+ leaf = tmp_path / name
+ leaf.mkdir()
+ grant(leaf, rights)
+
+ intermediate = tmp_path / "intermediate"
+ child = intermediate / "src"
+ storage.create_private_directory(child)
+ grant(child, "RX")
+ grant(intermediate, "(RD,RA,REA,RC,S,X,DC,WA)")
+ with pytest.raises(SystemExit, match="can be replaced"):
+ workbench_db.require_canonical_scan_directory(child)
+
+ script = Path(__file__).with_name("windows-other-user-access.ps1").read_text(encoding="utf-8")
+ powershell = Path(os.environ["SystemRoot"]) / "System32/WindowsPowerShell/v1.0/powershell.exe"
+ subprocess.run(
+ [
+ str(powershell),
+ "-NoProfile",
+ "-NonInteractive",
+ "-EncodedCommand",
+ base64.b64encode(script.encode("utf-16-le")).decode("ascii"),
+ ],
+ env={**os.environ, "CODEX_SECURITY_TEST_REPARSE_PARENT": str(tmp_path)},
+ check=True,
+ )
+ for name in leaves:
+ assert (tmp_path / name).resolve() == target
+ assert child.resolve() == target / "src"
+
+
+def test_delete_child_and_parent_reparse_rights_require_no_create_grant(tmp_path: Path) -> None:
+ parent = tmp_path / "parent"
+ output = parent / "output"
+ output.mkdir(parents=True)
+ grant(parent, "(DC,WA)")
+ with pytest.raises(SystemExit, match="can be replaced"):
+ workbench_db.require_canonical_scan_directory(output)
+
+
[email protected]("existing", [True, False], ids=["initial-selection", "concurrent-create"])
+def test_generated_target_name_must_be_an_ordinary_directory(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, existing: bool
+) -> None:
+ root = tmp_path / "output"
+ root.mkdir()
+ other = tmp_path / "other"
+ other.mkdir()
+ project = tmp_path / "project"
+ segment = root / project.name
+
+ if existing:
+ make_junction(segment, other)
+ else:
+ open_relative = windows_scan_local_files._relative_output_directory
+
+ def create_competing_directory(parent, basename, descriptor=None):
+ if descriptor is not None and basename == project.name:
+ make_junction(segment, other)
+ return open_relative(parent, basename, descriptor)
+
+ monkeypatch.setattr(
+ windows_scan_local_files, "_relative_output_directory", create_competing_directory
+ )
+ try:
+ directory = workbench_db.scan_target_root(str(root), project)
+ with pytest.raises(OSError):
+ storage.create_private_directory(directory, scan_output=True)
+ finally:
+ segment.rmdir()
+ assert not list(other.iterdir())
+
+
@pytest.mark.parametrize("junction", [False, True], ids=["ordinary-directory", "junction"])
def test_private_temporary_directory_rejects_post_creation_substitution(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, junction: bool
) -> None:
parent = tmp_path / "shared"
parent.mkdir()
- subprocess.run(
- ["icacls.exe", str(parent), "/grant", "*S-1-1-0:(OI)(CI)R"],
- check=True,
- capture_output=True,
- )
+ grant(parent, "(OI)(CI)R")
external = tmp_path / "external"
external.mkdir()
substituted: list[Path] = []
@@ -40,12 +179,7 @@ def test_private_temporary_directory_rejects_post_creation_substitution(
def replace_before_verification(path: Path, descriptor: object) -> Path:
path.rmdir()
if junction:
- subprocess.run(
- ["cmd", "/c", "mklink", "/J", str(path), str(external)],
- check=True,
- capture_output=True,
- text=True,
- )
+ make_junction(path, external)
else:
path.mkdir() # An ordinary replacement inherits its parent's DACL.
substituted.append(path)
diff --git a/plugins/codex-security/tests/windows-other-user-access.ps1 b/plugins/codex-security/tests/windows-other-user-access.ps1
new file mode 100644
index 000000000..ca6768062
--- /dev/null
+++ b/plugins/codex-security/tests/windows-other-user-access.ps1
@@ -0,0 +1,160 @@
+$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);
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
+ private static extern bool MoveFile(string existingName, string newName);
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
+ private static extern bool RemoveDirectory(string path);
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
+ private static extern SafeFileHandle CreateFile(string path, uint access, uint share,
+ IntPtr security, uint disposition, uint flags, IntPtr template);
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ private static extern bool DeviceIoControl(SafeFileHandle handle, uint code,
+ byte[] input, int inputLength, [Out] byte[] output, int outputLength,
+ out int returned, IntPtr overlapped);
+
+ private static SafeFileHandle OpenReparseDirectory(string path, uint access) {
+ // OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT
+ return CreateFile(path, access, 7, IntPtr.Zero, 3, 0x02200000, IntPtr.Zero);
+ }
+
+ private static void Check(bool succeeded, string operation) {
+ if (!succeeded) {
+ int error = Marshal.GetLastWin32Error();
+ throw new System.ComponentModel.Win32Exception(error, operation + " (Win32 " + error + ")");
+ }
+ }
+
+ public static void CopyJunction(SafeAccessTokenHandle token, string source, string destination, uint access) {
+ byte[] data = new byte[16384]; // MAXIMUM_REPARSE_DATA_BUFFER_SIZE
+ int length;
+ using (var handle = OpenReparseDirectory(source, 0)) {
+ Check(!handle.IsInvalid, "open template");
+ Check(DeviceIoControl(handle, 0x900a8, null, 0, data, data.Length, out length, IntPtr.Zero),
+ "FSCTL_GET_REPARSE_POINT");
+ }
+ WindowsIdentity.RunImpersonated(token, () => {
+ using (var handle = OpenReparseDirectory(destination, access)) {
+ Check(!handle.IsInvalid, "open destination");
+ int returned;
+ Check(DeviceIoControl(handle, 0x900a4, data, length, null, 0, out returned, IntPtr.Zero),
+ "FSCTL_SET_REPARSE_POINT");
+ }
+ });
+ }
+
+ 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; }
+ });
+ }
+
+ public static void ReplaceDirectory(SafeAccessTokenHandle token, string path) {
+ WindowsIdentity.RunImpersonated(token, () => {
+ Directory.Move(path, path + ".retained");
+ Directory.Move(path + ".replacement", path);
+ File.WriteAllText(Path.Combine(path, "marker.txt"), "replacement");
+ });
+ }
+
+ public static bool CanRename(SafeAccessTokenHandle token, string path) {
+ return WindowsIdentity.RunImpersonated(token, () => {
+ if (!MoveFile(path, path + ".moved")) {
+ int error = Marshal.GetLastWin32Error();
+ if (error == 5) return false; // ERROR_ACCESS_DENIED
+ throw new System.ComponentModel.Win32Exception(error);
+ }
+ Directory.Move(path + ".moved", path);
+ return true;
+ });
+ }
+
+ public static void RemoveEmptyDirectory(SafeAccessTokenHandle token, string path) {
+ WindowsIdentity.RunImpersonated(token, () => Check(RemoveDirectory(path), "RemoveDirectory"));
+ }
+}
+'@
+
+# 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())
+ }
+ if ($env:CODEX_SECURITY_TEST_REPARSE_PARENT) {
+ $root = $env:CODEX_SECURITY_TEST_REPARSE_PARENT
+ $source = Join-Path $root 'source junction'
+ $rights = @{
+ 'write attributes' = 0x100; 'write data' = 0x2
+ 'write data and attributes' = 0x102; 'writable control' = 0x40000000
+ }
+ foreach ($leaf in $rights.GetEnumerator()) {
+ $path = Join-Path $root $leaf.Key
+ if ($leaf.Key -ne 'writable control' -and [ScanOutputAccessProbe]::CanRename($token, $path)) {
+ throw "The leaf-only grant unexpectedly permitted renaming $path."
+ }
+ [ScanOutputAccessProbe]::CopyJunction($token, $source, $path, $leaf.Value)
+ }
+ $intermediate = Join-Path $root 'intermediate'
+ [ScanOutputAccessProbe]::RemoveEmptyDirectory($token, (Join-Path $intermediate 'src'))
+ [ScanOutputAccessProbe]::CopyJunction($token, $source, $intermediate, 0x100)
+ return
+ }
+ [ScanOutputAccessProbe]::ReplaceDirectory($token, $env:CODEX_SECURITY_TEST_REPLACE_DIRECTORY)
+ $protected = $env:CODEX_SECURITY_TEST_DENIED_DIRECTORY
+ $icacls = Join-Path $env:SystemRoot 'System32\icacls.exe'
+ & $icacls $protected /grant "*$($user.SID.Value):(DE)" | Out-Null
+ if ($LASTEXITCODE -ne 0 -or -not [ScanOutputAccessProbe]::CanRename($token, $protected)) {
+ throw 'The named-user delete grant did not permit a directory rename.'
+ }
+ & $icacls $protected /deny '*S-1-5-11:(DE)' | Out-Null
+ if ($LASTEXITCODE -ne 0 -or [ScanOutputAccessProbe]::CanRename($token, $protected)) {
+ throw 'The Authenticated Users deny did not prevent the directory rename.'
+ }
+ # Exercise the SDK while the named account still exists for SID resolution.
+ $env:CODEX_SECURITY_TEST_DENIED_OUTPUT = Join-Path $protected 'scan'
+ $check = 'const { prepareOutputDir } = await import(process.env.CODEX_SECURITY_TEST_RUNTIME); await prepareOutputDir(process.env.CODEX_SECURITY_TEST_DENIED_OUTPUT, `fixture`);'
+ & $env:CODEX_SECURITY_TEST_BUN -e $check | Out-Null
+ if ($LASTEXITCODE -ne 0) { throw 'The SDK rejected the protected output location.' }
+ $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/docs/cli.md b/sdk/typescript/docs/cli.md
index e3bff1e2e..fb53c1376 100644
--- a/sdk/typescript/docs/cli.md
+++ b/sdk/typescript/docs/cli.md
@@ -528,8 +528,14 @@ with every repository.
Use `--output-dir DIR` to choose where a scan saves its results. The directory
must be empty and outside the scanned directory and enclosing Git worktree.
-Existing directories keep their permissions; newly created directories are
-private to you by default.
+Existing directories keep their permissions. Newly created directories are
+private to you by default. On Windows, the directory and its parents must be
+owned by your account, Administrators, SYSTEM, or TrustedInstaller. Choose a
+path where another user cannot replace the output directory or one of its
+parents. A parent can allow other users to read it or create sibling directories.
+For an empty write destination, grant content-writing permissions to children
+through inheritance. Other users must not have permission to set reparse data
+on the destination directory itself.
`--archive-existing` moves earlier output to a sibling directory with a unique
suffix, such as `results.previous-ab12cd34` for an output directory named
`results`. Use `--dry-run` to preview the move.
diff --git a/sdk/typescript/src/multiscan.ts b/sdk/typescript/src/multiscan.ts
index 334bfbea9..a93988a1a 100644
--- a/sdk/typescript/src/multiscan.ts
+++ b/sdk/typescript/src/multiscan.ts
@@ -49,6 +49,7 @@ import {
canonicalConfigPath,
createWindowsOutputDirectory,
requireSecureOutputAncestry,
+ requireWindowsOutputPath,
resolvePluginPath,
validateOutputDir,
} from "./runtime.js";
@@ -236,8 +237,8 @@ export async function runMultiscan(
if (!manifest?.isFile())
throw new Error("Bulk recovery requires an existing campaign manifest.");
}
- const output = await ensureOutputDirectory(requestedOutput);
- await requireSecureOutputAncestry(output);
+ const output = await ensureOutputDirectory(requestedOutput, "artifacts");
+ if (process.platform !== "win32") await requireSecureOutputAncestry(output);
const unlock = await acquireLock(output);
let pluginWorkspace: string | undefined;
let pluginRoot: Promise<string> | undefined;
@@ -758,7 +759,12 @@ async function removeCheckout(path: string): Promise<string | undefined> {
);
}
-async function ensureOutputDirectory(path: string): Promise<string> {
+async function ensureOutputDirectory(
+ path: string,
+ retainedDirectory?: string,
+): Promise<string> {
+ const linkedOutput =
+ "Multiscan output directories must not be symbolic links.";
let metadata = await lstat(path, { bigint: true }).catch(
undefinedIfMissingFile,
);
@@ -766,14 +772,21 @@ async function ensureOutputDirectory(path: string): Promise<string> {
if (process.platform === "win32") {
// Resolve parent aliases while leaving the leaf for lstat to verify.
path = join(await canonicalConfigPath(dirname(path)), basename(path));
- await createWindowsOutputDirectory(path, true);
+ try {
+ await createWindowsOutputDirectory(path, true);
+ } catch (error) {
+ if ((await lstat(path).catch(() => undefined))?.isSymbolicLink()) {
+ throw new Error(linkedOutput, { cause: error });
+ }
+ throw error;
+ }
} else {
await mkdir(path, { recursive: true, mode: 0o700 });
}
metadata = await lstat(path, { bigint: true });
}
if (metadata.isSymbolicLink()) {
- throw new Error("Multiscan output directories must not be symbolic links.");
+ throw new Error(linkedOutput);
}
if (!metadata.isDirectory()) {
throw new Error("Multiscan output paths must be directories.");
@@ -783,7 +796,10 @@ async function ensureOutputDirectory(path: string): Promise<string> {
if (directory.dev !== metadata.dev || directory.ino !== metadata.ino) {
throw new Error("Multiscan output directories changed during preparation.");
}
- if (process.platform === "win32") return canonical;
+ if (process.platform === "win32") {
+ await requireWindowsOutputPath(canonical, true, retainedDirectory);
+ return canonical;
+ }
if ((directory.mode & 0o022n) !== 0n) {
throw new Error(
"Multiscan output directories must not be group- or world-writable.",
diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.ts
index faf5d9c5e..08339ffe8 100644
--- a/sdk/typescript/src/runtime.ts
+++ b/sdk/typescript/src/runtime.ts
@@ -1996,8 +1996,10 @@ export async function validateOutputDir(
throw new OutputDirectoryNotEmptyError(path);
}
requireOutputDirectoryOwnership(metadata, path);
- await requireSecureOutputAncestry(path);
- const canonical = await realpath(path);
+ const writableLeaf =
+ !archiveExisting ||
+ (process.platform === "win32" && (await readdir(path)).length === 0);
+ const canonical = await checkedOutputPath(path, writableLeaf);
requireModelSafeOutputDir(canonical);
return canonical;
}
@@ -2235,16 +2237,15 @@ async function prepareOutputDirectory(
existingOutput: "reject" | "archive" | "preserve",
onOutputArchived?: (archiveDir: string) => void,
): Promise<string> {
- if (outputDirectory === undefined) {
- requireModelSafeOutputDir(temporaryRoot);
- requireModelSafeOutputDir(await realpath(temporaryRoot));
- }
const path = await validateOutputDir(
outputDirectory,
existingOutput !== "reject",
);
- validateLocation?.(path ?? (await realpath(temporaryRoot)));
if (path === null) {
+ requireModelSafeOutputDir(temporaryRoot);
+ const canonicalRoot = await realpath(temporaryRoot);
+ requireModelSafeOutputDir(canonicalRoot);
+ validateLocation?.(canonicalRoot);
const prefix = `codex-security-${safePrefix(repositoryName)}`;
let created: string;
if (process.platform === "win32") {
@@ -2253,12 +2254,12 @@ async function prepareOutputDirectory(
// The SDK suffix is longer than the workbench's .previous-<tempname> suffix.
const prefixLength = 255 - suffix.length - outputArchiveSuffix().length;
created = join(
- temporaryRoot,
+ canonicalRoot,
`${prefix.slice(0, prefixLength)}${suffix}`,
);
await createWindowsOutputDirectory(created, false);
} else {
- created = await mkdtemp(join(temporaryRoot, `${prefix}-`));
+ created = await mkdtemp(join(canonicalRoot, `${prefix}-`));
}
try {
if ((process.umask() & 0o700) !== 0) await chmod(created, 0o700);
@@ -2268,6 +2269,7 @@ async function prepareOutputDirectory(
throw error;
}
}
+ validateLocation?.(path);
let createdRoot: string | undefined;
try {
let existing = await lstat(path).catch(nullIfMissingFileError);
@@ -2286,10 +2288,15 @@ async function prepareOutputDirectory(
: await mkdir(path, { recursive: true, mode: 0o700 });
if ((process.umask() & 0o700) !== 0) await chmod(path, 0o700);
}
+ // Registration retains a populated scan for archival. An empty Windows
+ // directory must still satisfy the checks for a writable scan output.
+ const preserveContents =
+ existingOutput === "preserve" &&
+ (process.platform !== "win32" || (await readdir(path)).length !== 0);
return await validatePreparedOutputDir(
path,
validateLocation,
- existingOutput === "preserve",
+ preserveContents,
);
} catch (error) {
if (createdRoot !== undefined) {
@@ -2305,11 +2312,8 @@ async function prepareOutputDirectory(
}
}
-export async function createWindowsOutputDirectory(
- path: string,
- recursive: boolean,
-): Promise<string | undefined> {
- const native = createRequire(import.meta.url)(
+async function windowsOutputBinding() {
+ return createRequire(import.meta.url)(
join(
await bundledPluginRoot(),
"mcp",
@@ -2317,11 +2321,43 @@ export async function createWindowsOutputDirectory(
`win32-${process.arch}`,
"windows.node",
),
- ) as { createPrivateWindowsDirectory(path: Buffer): number };
+ ) as {
+ createPrivateWindowsDirectory(path: Buffer, checkOutput: boolean): number;
+ validateWindowsOutputPath(
+ path: Buffer,
+ writableLeaf?: boolean,
+ retainedDirectory?: string,
+ ): number;
+ };
+}
+
+export async function requireWindowsOutputPath(
+ path: string,
+ writableLeaf?: boolean,
+ retainedDirectory?: string,
+): Promise<void> {
+ const native = await windowsOutputBinding();
+ const error = native.validateWindowsOutputPath(
+ Buffer.from(win32.toNamespacedPath(path), "utf16le"),
+ writableLeaf,
+ retainedDirectory,
+ );
+ if (error !== 0)
+ throw new OutputDirectoryError(
+ `Scan output directory or its parent could not be trusted (Windows error ${error}): ${path}`,
+ );
+}
+
+export async function createWindowsOutputDirectory(
+ path: string,
+ recursive: boolean,
+): Promise<string | undefined> {
+ const native = await windowsOutputBinding();
const create = async (target: string): Promise<string | undefined> => {
const createOne = () =>
native.createPrivateWindowsDirectory(
Buffer.from(win32.toNamespacedPath(target), "utf16le"),
+ true,
);
let error = createOne();
let firstCreated: string | undefined;
@@ -2334,8 +2370,10 @@ export async function createWindowsOutputDirectory(
error = createOne();
}
if (error === 0) return firstCreated ?? target;
- if (recursive && error === 183 && (await stat(target)).isDirectory())
+ if (recursive && error === 183 && (await stat(target)).isDirectory()) {
+ await requireWindowsOutputPath(target, target === path);
return firstCreated;
+ }
throw new OutputDirectoryError(
`Unable to create private Windows output directory (Windows error ${error}): ${target}`,
);
@@ -2352,7 +2390,7 @@ export async function validatePreparedOutputDir(
if (!metadata.isDirectory()) {
throw new OutputDirectoryError(`Scan output is not a directory: ${path}`);
}
- const canonical = await realpath(path);
+ const canonical = await checkedOutputPath(path, !allowNonempty);
requireModelSafeOutputDir(canonical);
validateLocation?.(canonical);
if (!allowNonempty && (await readdir(canonical)).length !== 0) {
@@ -2361,7 +2399,39 @@ export async function validatePreparedOutputDir(
);
}
requireOutputDirectoryOwnership(metadata, path);
- await requireSecureOutputAncestry(canonical);
+ return canonical;
+}
+
+async function checkedOutputPath(
+ path: string,
+ writableLeaf: boolean,
+): Promise<string> {
+ if (process.platform === "win32") {
+ // Keep the selected leaf for the no-follow check, including across an
+ // in-place directory change between lstat and canonicalization.
+ const directory = dirname(path);
+ const parent = await realpath(directory);
+ const selected = join(parent, relative(directory, path));
+ await requireWindowsOutputPath(selected, writableLeaf);
+ const canonical = await realpath(selected);
+ if (canonical === selected) return selected;
+ // Accept a canonical leaf spelling (case or short name) within the checked parent.
+ if (dirname(canonical) === parent) {
+ const [leaf, resolved] = await Promise.all([
+ lstat(selected, { bigint: true }),
+ lstat(canonical, { bigint: true }),
+ ]);
+ if (leaf.isDirectory() && leaf.ino !== 0n && sameInode(leaf, resolved)) {
+ return canonical;
+ }
+ }
+ throw new OutputDirectoryError(
+ `Scan output directory changed during preparation: ${path}`,
+ );
+ }
+ await requireSecureOutputAncestry(path);
+ const canonical = await realpath(path);
+ if (canonical !== path) await requireSecureOutputAncestry(canonical);
return canonical;
}
@@ -2397,7 +2467,7 @@ export async function requireSecureOutputAncestry(
path: string,
effectiveUid = process.geteuid?.(),
): Promise<void> {
- if (process.platform === "win32") return;
+ if (process.platform === "win32") return requireWindowsOutputPath(path);
let current = dirname(resolve(path));
while (true) {
try {
diff --git a/sdk/typescript/tests-ts/api-runtime-storage.test.ts b/sdk/typescript/tests-ts/api-runtime-storage.test.ts
index 6e3e8470c..ec9be3090 100644
--- a/sdk/typescript/tests-ts/api-runtime-storage.test.ts
+++ b/sdk/typescript/tests-ts/api-runtime-storage.test.ts
@@ -255,7 +255,11 @@ test.each(["directory", "zip"])(
);
expect(grant.status, grant.stderr).toBe(0);
temporaryAcl = snapshotAcl();
- const rejected = await runtime.createIsolatedHome(temporary);
+ await expect(runtime.createIsolatedHome(temporary)).rejects.toThrow(
+ "could not be trusted",
+ );
+ const rejected = join(temporary, "credential-home");
+ await mkdir(rejected);
await expect(
runtime.requirePrivateCredentialHome(await lstat(rejected), rejected),
).rejects.toThrow("allows another identity to replace");
diff --git a/sdk/typescript/tests-ts/cost.test.ts b/sdk/typescript/tests-ts/cost.test.ts
index 649c48608..4396a27f2 100644
--- a/sdk/typescript/tests-ts/cost.test.ts
+++ b/sdk/typescript/tests-ts/cost.test.ts
@@ -6036,16 +6036,18 @@ describe("live scan cost tracking", () => {
type: "item.completed",
item: { type: "agent_message", text },
});
- await appendSessionItem(parent, {
- type: "custom_tool_call_output",
- output:
- 'CODEX_SECURITY_SCAN_PROGRESS {"phase":"discovery","filesCompleted":0,"filesTotal":8}',
- });
- // The inventory marker is absent from this persisted output. Matching its
- // completion is the only proof that the live 9-file inventory is newer.
+ // Publish the older receipt and its ordering evidence in the same batch.
+ // Until the persisted command is visible, the tool receipt can be newer.
await appendFile(
parent,
jsonLines([
+ {
+ type: "response_item",
+ payload: {
+ type: "custom_tool_call_output",
+ output: progressMarker("discovery", 0, 8),
+ },
+ },
native({
type: "CommandExecution",
command: ["inventory"],
diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.ts
index bdfa0e23e..a996d793b 100644
--- a/sdk/typescript/tests-ts/runtime.test.ts
+++ b/sdk/typescript/tests-ts/runtime.test.ts
@@ -10,7 +10,7 @@ import { execFile, spawnSync } from "node:child_process";
import { Codex } from "@openai/codex-sdk";
import * as childProcess from "node:child_process";
import { EventEmitter, once } from "node:events";
-import { existsSync, renameSync, symlinkSync } from "node:fs";
+import { existsSync, renameSync, symlinkSync, unlinkSync } from "node:fs";
import {
chmod,
copyFile,
@@ -89,6 +89,7 @@ import {
preparePersistentOutputRoot,
prepareScanArtifactRestorer,
prepareScanRegistrationOutput,
+ requireWindowsOutputPath,
preserveCodexSecurityPluginRegistration,
environmentWithGit,
requirePrivateCredentialHome,
@@ -6442,6 +6443,94 @@ describe("runtime directories and plugin Python boundary", () => {
},
);
+ testPosix(
+ "rejects a selected directory replaced in a shared parent during validation",
+ async () => {
+ const root = await temporaryDirectory();
+ const shared = join(root, "shared");
+ const output = join(shared, "output");
+ const unrelated = join(root, "unrelated");
+ await mkdir(output, { recursive: true });
+ await chmod(shared, 0o777);
+ await mkdir(unrelated);
+ const uid = process.geteuid!();
+ using _swap = spyOn(process, "geteuid").mockImplementationOnce(() => {
+ renameSync(output, join(shared, "moved"));
+ symlinkSync(unrelated, output);
+ return uid;
+ });
+ await expect(validateOutputDir(output)).rejects.toThrow("writable");
+ expect(await realpath(output)).toBe(unrelated);
+ },
+ );
+
+ test("creates temporary output under the directory selected before an alias changes", async () => {
+ const root = await temporaryDirectory();
+ const selected = join(root, "selected");
+ const replacement = join(root, "replacement");
+ const alias = join(root, "alias");
+ await mkdir(selected);
+ await mkdir(replacement);
+ await symlink(selected, alias, "junction");
+ const output = await prepareOutputDir(undefined, "repo", alias, (path) => {
+ if (path === selected) {
+ unlinkSync(alias);
+ symlinkSync(replacement, alias, "junction");
+ }
+ });
+ expect(await realpath(alias)).toBe(replacement);
+ expect(dirname(output)).toBe(selected);
+ expect(await readdir(replacement)).toEqual([]);
+ });
+
+ test.skipIf(process.platform !== "win32")(
+ "keeps existing output validation on the selected Windows directory",
+ async () => {
+ const root = await temporaryDirectory();
+ const output = join(root, "output");
+ for (const writable of [false, true]) {
+ await expect(
+ requireWindowsOutputPath(output, writable),
+ ).rejects.toThrow();
+ }
+ await mkdir(output);
+ await writeFile(join(output, "old"), "");
+ expect(await validateOutputDir(join(root, "OUTPUT"), true)).toBe(output);
+
+ const staged = join(root, "staged");
+ const unrelated = join(staged, "output");
+ await mkdir(unrelated, { recursive: true });
+ await writeFile(join(unrelated, "keep"), "");
+ const original = fsPromises.realpath;
+ const substitution = spyOn(fsPromises, "realpath").mockImplementation(
+ new Proxy(original, {
+ async apply(target, receiver, args) {
+ if (args[0] !== output)
+ return Reflect.apply(target, receiver, args);
+ const moved = join(root, "moved");
+ renameSync(output, moved);
+ symlinkSync(unrelated, output, "junction");
+ const redirected = await original(output);
+ unlinkSync(output);
+ renameSync(moved, output);
+ renameSync(staged, join(root, "saved"));
+ symlinkSync(root, staged, "junction");
+ return redirected;
+ },
+ }),
+ );
+ try {
+ // The redirected path now identifies the original leaf under a different parent.
+ await expect(validateOutputDir(output, true)).rejects.toThrow(
+ "changed during preparation",
+ );
+ expect(await readdir(join(root, "saved", "output"))).toEqual(["keep"]);
+ } finally {
+ substitution.mockRestore();
+ }
+ },
+ );
+
test("validates explicit output directories and creates private temporary paths", async () => {
const root = await temporaryDirectory();
const absent = join(root, "scan");
diff --git a/sdk/typescript/tests-ts/support/windows-other-user-access.ps1 b/sdk/typescript/tests-ts/support/windows-other-user-access.ps1
deleted file mode 100644
index 623f664d5..000000000
--- a/sdk/typescript/tests-ts/support/windows-other-user-access.ps1
+++ /dev/null
@@ -1,56 +0,0 @@
-$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.ts
index fa42aa94c..44560b36d 100644
--- a/sdk/typescript/tests-ts/windows-scan-output.test.ts
+++ b/sdk/typescript/tests-ts/windows-scan-output.test.ts
@@ -1,4 +1,5 @@
import { execFile } from "node:child_process";
+import { symlinkSync } from "node:fs";
import {
cp,
lstat,
@@ -11,6 +12,7 @@ import {
import { basename, dirname, join } from "node:path";
import { promisify } from "node:util";
import { afterEach, expect, test } from "bun:test";
+import { runComponentScans } from "../src/component-scan.js";
import { loadContract } from "../src/contract.js";
import { runMultiscan } from "../src/multiscan.js";
import * as runtime from "../src/runtime.js";
@@ -347,7 +349,12 @@ windowsTest("existing Windows scan ACLs are preserved", async () => {
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");
+ await icacls(
+ output,
+ "/grant",
+ "*S-1-5-32-545:(AD)",
+ "*S-1-5-32-545:(OI)(CI)(IO)M",
+ );
const before = await descriptor(output);
const permissions = await accessRules(output);
expect(before).toContain(";;;BU)");
@@ -387,13 +394,100 @@ windowsTest(
const root = await temporaryDirectory();
const output = join(root, "campaign");
await mkdir(output);
- await icacls(output, "/grant", "*S-1-5-32-545:(OI)(CI)M");
+ await icacls(
+ output,
+ "/grant",
+ "*S-1-5-32-545:(AD)",
+ "*S-1-5-32-545:(OI)(CI)(IO)M",
+ );
const permissions = await accessRules(output);
await createMultiscanCampaign(output);
expect(await accessRules(output)).toBe(permissions);
},
);
+windowsTest.each([
+ "(RD,RA,REA,RC,S,WA)",
+ "(RD,RA,REA,RC,S,WD)",
+ "(RD,RA,REA,RC,S,WA,WD)",
+ "M",
+])(
+ "rejects component planning on an empty retaggable output with peer rights %s",
+ async (right) => {
+ const repository = await temporaryDirectory();
+ await writeFile(join(repository, "source.txt"), "Synthetic component");
+ const outputDir = await runtime.prepareOutputDir(
+ join(await temporaryDirectory(), "output"),
+ "fixture",
+ );
+ await icacls(outputDir, "/grant", `*S-1-1-0:${right}`);
+ const before = await descriptor(outputDir);
+ await expect(
+ runComponentScans({
+ repository,
+ outputDir,
+ components: [{ name: "Source", paths: ["source.txt"] }],
+ planOnly: true,
+ }),
+ ).rejects.toThrow("could not be trusted");
+ await expect(
+ lstat(join(outputDir, "components.json")),
+ ).rejects.toMatchObject({ code: "ENOENT" });
+ expect(await descriptor(outputDir)).toBe(before);
+ await cp(example, outputDir, { recursive: true });
+ await loadContract(outputDir, { pluginRoot: PLUGIN_ROOT });
+ },
+);
+
+windowsTest(
+ "resumes a campaign whose retained artifacts keep it nonempty",
+ async () => {
+ const { paths } = await repositoryFixture("retained-campaign-source");
+ const configured = options(paths, client(completeRun), { maxAttempts: 1 });
+ await expect(runMultiscan(configured)).resolves.toMatchObject({
+ completed: 1,
+ });
+ await icacls(paths.output, "/grant", "*S-1-1-0:(WA)");
+ const before = await descriptor(paths.output);
+ await expect(runMultiscan(configured)).resolves.toMatchObject({
+ skipped: 1,
+ failed: 0,
+ });
+ expect(await descriptor(paths.output)).toBe(before);
+ await icacls(join(paths.output, "artifacts"), "/grant", "*S-1-1-0:(DE)");
+ await expect(runMultiscan(configured)).rejects.toThrow();
+ },
+);
+
+windowsTest("rejects a parent that can be emptied and retagged", async () => {
+ const root = await temporaryDirectory();
+ const parent = join(root, "directory");
+ const output = join(parent, "scan");
+ await mkdir(parent);
+ await runtime.prepareOutputDir(output, "fixture");
+ await icacls(parent, "/grant", "*S-1-1-0:(DC,WA)");
+ await expect(runtime.prepareOutputDir(output, "fixture")).rejects.toThrow();
+});
+
+windowsTest(
+ "output admission distinguishes effective parent delete-child grants",
+ async () => {
+ const root = await sharedRoot();
+ await icacls(root, "/grant", "*S-1-1-0:(AD)", "*S-1-1-0:(OI)(CI)(IO)(DC)");
+ const output = await runtime.prepareOutputDir(
+ join(root, "scan"),
+ "fixture",
+ );
+ expect(await descriptor(output)).toContain("D:P");
+
+ await icacls(root, "/grant", "*S-1-1-0:(DC)");
+ await expect(runtime.prepareOutputDir(output, "fixture")).rejects.toThrow();
+ const fresh = join(root, "fresh");
+ await expect(runtime.prepareOutputDir(fresh, "fixture")).rejects.toThrow();
+ await expect(lstat(fresh)).rejects.toMatchObject({ code: "ENOENT" });
+ },
+);
+
windowsTest(
"archiving Windows output preserves old ACLs and privately creates the replacement",
async () => {
@@ -435,21 +529,45 @@ windowsTest(
},
);
+windowsTest(
+ "creation keeps the output location selected during preflight",
+ async () => {
+ const root = await temporaryDirectory();
+ const destination = join(root, "destination");
+ const missing = join(root, "parent");
+ await mkdir(destination);
+ let selected = false;
+ await expect(
+ runtime.prepareOutputDir(join(missing, "scan"), "fixture", root, () => {
+ if (!selected) {
+ symlinkSync(destination, missing, "junction");
+ selected = true;
+ }
+ }),
+ ).rejects.toThrow();
+ expect(selected).toBe(true);
+ await expect(lstat(join(destination, "scan"))).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",
+ "private scan output excludes a second user and rejects replaceable directories",
async () => {
const root = await sharedRoot();
const writableParent = join(root, "writable parent");
await mkdir(writableParent);
- await icacls(writableParent, "/grant", "*S-1-1-0:(OI)(CI)M");
+ await icacls(writableParent, "/grant", "*S-1-1-0:(AD)");
const direct = await createDirectPluginOutput(writableParent);
expect(await descriptor(direct.targetRoot)).toBe(direct.targetRootAcl);
const shared = join(direct.targetRoot, "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",
@@ -473,11 +591,44 @@ test.skipIf(
campaign,
direct.scanDir,
].map((path) => join(path, "probe.txt"));
+
+ const selected = join(writableParent, "selected");
+ const replacement = selected + ".replacement";
+ const scan = join(selected, "scan");
+ await runtime.prepareOutputDir(scan, "fixture");
+ await cp(example, scan, { recursive: true });
+ await loadContract(scan, { pluginRoot: PLUGIN_ROOT });
+ await writeFile(join(selected, "marker.txt"), "original");
+ // Both trees contain a valid sealed scan. Grant the other user permission to
+ // rename these two directories within the create-only parent.
+ await mkdir(replacement);
+ await cp(example, join(replacement, "scan"), { recursive: true });
+ await writeFile(join(replacement, "marker.txt"), "");
+ await icacls(join(replacement, "marker.txt"), "/grant", "*S-1-1-0:M");
+ for (const path of [selected, replacement]) {
+ await icacls(path, "/grant", "*S-1-1-0:M");
+ }
+ await expect(
+ runtime.prepareOutputDir(join(selected, "new scan"), "fixture"),
+ ).rejects.toThrow();
+ await expect(lstat(join(selected, "new scan"))).rejects.toMatchObject({
+ code: "ENOENT",
+ });
const script = await readFile(
- join(import.meta.dir, "support", "windows-other-user-access.ps1"),
+ new URL(
+ "../../../plugins/codex-security/tests/windows-other-user-access.ps1",
+ import.meta.url,
+ ),
"utf8",
);
+ const denied = join(writableParent, "named-user grant");
+ await mkdir(denied);
const result = await runPowerShell(script, {
+ CODEX_SECURITY_TEST_BUN: process.execPath,
+ CODEX_SECURITY_TEST_RUNTIME: new URL("../src/runtime.ts", import.meta.url)
+ .href,
+ CODEX_SECURITY_TEST_DENIED_DIRECTORY: denied,
+ CODEX_SECURITY_TEST_REPLACE_DIRECTORY: selected,
CODEX_SECURITY_TEST_ACCESS_PATHS: JSON.stringify([
shared,
...privateProbes,
@@ -487,6 +638,15 @@ test.skipIf(
{ read: true, write: true },
...privateProbes.map(() => ({ read: false, write: false })),
]);
+ expect(await readFile(join(selected, "marker.txt"), "utf8")).toBe(
+ "replacement",
+ );
+ expect(
+ await readFile(join(selected + ".retained", "marker.txt"), "utf8"),
+ ).toBe("original");
+ await expect(
+ loadContract(scan, { pluginRoot: PLUGIN_ROOT }),
+ ).rejects.toThrow();
for (const path of privateProbes) {
expect(await readFile(path, "utf8")).toBe("synthetic private data");
}