aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-11 11:06:46 +01:00
parent df99318392
commit 86e7c72e5f
10383 changed files with 749164 additions and 749170 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,197 @@
use super::acl_api_result;
use super::deny_ace_already_present;
use super::ensure_allow_mask_aces_with_inheritance;
use super::ensure_handle_is_not_filesystem_root;
use super::fetch_dacl_handle;
use crate::token::LocalSid;
use crate::winutil::to_wide;
use pretty_assertions::assert_eq;
use std::ffi::c_void;
use std::fs::OpenOptions;
use std::os::windows::fs::OpenOptionsExt;
use std::path::Path;
use windows_sys::Win32::Foundation::ERROR_ACCESS_DENIED;
use windows_sys::Win32::Foundation::HLOCAL;
use windows_sys::Win32::Foundation::LocalFree;
use windows_sys::Win32::Security::ACL_SIZE_INFORMATION;
use windows_sys::Win32::Security::AclSizeInformation;
use windows_sys::Win32::Security::Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW;
use windows_sys::Win32::Security::Authorization::SDDL_REVISION_1;
use windows_sys::Win32::Security::DACL_SECURITY_INFORMATION;
use windows_sys::Win32::Security::GetAclInformation;
use windows_sys::Win32::Security::GetSecurityDescriptorControl;
use windows_sys::Win32::Security::SE_DACL_PROTECTED;
use windows_sys::Win32::Security::SetFileSecurityW;
use windows_sys::Win32::Security::UNPROTECTED_DACL_SECURITY_INFORMATION;
use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS;
use windows_sys::Win32::Storage::FileSystem::FILE_READ_ATTRIBUTES;
use windows_sys::Win32::Storage::FileSystem::READ_CONTROL;
#[test]
fn deny_ace_update_failure_is_an_error() {
let path = std::path::Path::new(r"C:\world-writable");
let error = acl_api_result(path, "SetNamedSecurityInfoW", ERROR_ACCESS_DENIED)
.expect_err("access denied must not look like an already-present ACE");
assert_eq!(
error.to_string(),
r"SetNamedSecurityInfoW failed for C:\world-writable: 5"
);
}
#[test]
fn deny_read_root_check_uses_the_open_handle() {
let cwd = std::env::current_dir().expect("current directory");
let root = cwd.ancestors().last().expect("filesystem root");
let root_directory = OpenOptions::new()
.access_mode(READ_CONTROL)
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
.open(root)
.expect("open filesystem root");
let diagnostic_path = std::path::Path::new(r"C:\not-a-root");
let error = ensure_handle_is_not_filesystem_root(&root_directory, diagnostic_path)
.expect_err("classification must follow the root handle, not the diagnostic path");
assert_eq!(
error.to_string(),
r"refusing to apply a deny-read ACE to filesystem root C:\not-a-root"
);
}
#[test]
fn existing_deny_ace_is_visible_without_write_dac() {
let target = tempfile::NamedTempFile::new().expect("temporary file");
let sid = LocalSid::from_string("S-1-5-21-10-20-30-40").expect("test SID");
let path = target.path();
let psid = sid.as_ptr();
assert!(unsafe { super::add_deny_read_ace(path, psid) }.expect("add deny ACE"));
let already_present =
unsafe { deny_ace_already_present(target.as_file(), path, psid, super::DenyAceKind::Read) }
.expect("read existing deny ACE");
assert!(already_present);
}
#[test]
fn revoking_absent_sid_preserves_child_null_dacl() {
let parent = tempfile::tempdir().expect("parent directory");
let child = parent.path().join("child");
std::fs::create_dir(&child).expect("child directory");
let sid = LocalSid::from_string("S-1-5-21-10-20-30-40").expect("absent SID");
let other_sid = LocalSid::from_string("S-1-5-21-10-20-30-41").expect("inherited SID");
unsafe {
super::add_allow_ace(parent.path(), other_sid.as_ptr()).expect("inheritable parent ACE");
let mut descriptor = std::ptr::null_mut();
assert_ne!(
ConvertStringSecurityDescriptorToSecurityDescriptorW(
crate::winutil::to_wide("D:NO_ACCESS_CONTROL").as_ptr(),
SDDL_REVISION_1,
&mut descriptor,
std::ptr::null_mut(),
),
0,
);
// The legacy setter preserves a null DACL without applying automatic inheritance.
let set = SetFileSecurityW(
crate::winutil::to_wide(&child).as_ptr(),
DACL_SECURITY_INFORMATION | UNPROTECTED_DACL_SECURITY_INFORMATION,
descriptor,
);
LocalFree(descriptor as HLOCAL);
assert_ne!(set, 0, "set an unprotected null DACL");
for revoke in [false, true] {
if revoke {
super::revoke_ace(parent.path(), sid.as_ptr()).expect("revoke absent SID");
}
let (dacl, descriptor) = super::fetch_dacl_handle(&child).expect("child permissions");
let mut control = 0;
let mut revision = 0;
let valid = GetSecurityDescriptorControl(descriptor, &mut control, &mut revision);
LocalFree(descriptor as HLOCAL);
assert_ne!(valid, 0, "read child inheritance flags");
assert_eq!(control & SE_DACL_PROTECTED, 0, "child permits inheritance");
assert!(
dacl.is_null(),
"revocation must preserve the child's null DACL"
);
}
}
}
fn acl_snapshot(path: &Path) -> (u16, Vec<u8>) {
unsafe {
let (acl, descriptor) = fetch_dacl_handle(path).expect("read directory ACL");
let mut control = 0;
let mut revision = 0;
assert_ne!(
GetSecurityDescriptorControl(descriptor, &mut control, &mut revision),
0
);
let mut info: ACL_SIZE_INFORMATION = std::mem::zeroed();
assert_ne!(
GetAclInformation(
acl,
&mut info as *mut _ as *mut c_void,
std::mem::size_of::<ACL_SIZE_INFORMATION>() as u32,
AclSizeInformation,
),
0
);
let dacl =
std::slice::from_raw_parts(acl.cast::<u8>(), info.AclBytesInUse as usize).to_vec();
LocalFree(descriptor as HLOCAL);
(control, dacl)
}
}
#[test]
fn noninheriting_read_attributes_preserve_unprotected_child_dacl() {
let parent = tempfile::tempdir().expect("create parent");
let child = parent.path().join("child");
let marker = LocalSid::from_string("S-1-5-21-915763429-1123581321-271828182-4243").unwrap();
let target = LocalSid::from_string("S-1-5-21-915763429-1123581321-271828182-4244").unwrap();
std::fs::create_dir(&child).unwrap();
let original = acl_snapshot(&child).1;
// Restore the original child DACL after adding an inheritable parent ACE.
// An ordinary parent update would re-propagate this missing permission.
unsafe {
let (_, descriptor) = fetch_dacl_handle(&child).unwrap();
ensure_allow_mask_aces_with_inheritance(
parent.path(),
&[marker.as_ptr()],
FILE_READ_ATTRIBUTES,
super::CONTAINER_INHERIT_ACE | super::OBJECT_INHERIT_ACE,
)
.unwrap();
assert_ne!(
acl_snapshot(&child).1,
original,
"child should inherit the ACE"
);
assert_ne!(
SetFileSecurityW(
to_wide(&child).as_ptr(),
DACL_SECURITY_INFORMATION,
descriptor
),
0
);
LocalFree(descriptor as HLOCAL);
}
let before = acl_snapshot(&child);
assert_eq!(before.0 & SE_DACL_PROTECTED, 0);
assert!(unsafe {
ensure_allow_mask_aces_with_inheritance(
parent.path(),
&[target.as_ptr()],
FILE_READ_ATTRIBUTES,
/*inheritance*/ 0,
)
.unwrap()
});
assert_eq!(acl_snapshot(&child), before);
}

View File

@@ -0,0 +1,383 @@
use crate::resolved_permissions::ResolvedWindowsSandboxPermissions;
use dunce::canonicalize;
use std::collections::HashMap;
use std::collections::HashSet;
use std::path::Path;
use std::path::PathBuf;
#[derive(Debug, Default, PartialEq, Eq)]
pub struct AllowDenyPaths {
pub allow: HashSet<PathBuf>,
pub deny: HashSet<PathBuf>,
}
pub(crate) fn compute_allow_paths_for_permissions(
permissions: &ResolvedWindowsSandboxPermissions,
command_cwd: &Path,
env_map: &HashMap<String, String>,
) -> AllowDenyPaths {
let mut allow: HashSet<PathBuf> = HashSet::new();
let mut deny: HashSet<PathBuf> = HashSet::new();
let mut add_allow_path = |p: PathBuf| {
if p.exists() {
allow.insert(p);
}
};
let mut add_deny_path = |p: PathBuf| {
if p.exists() {
deny.insert(p);
}
};
for writable_root in permissions.writable_roots_for_cwd(command_cwd, env_map) {
let canonical = canonicalize(&writable_root.root).unwrap_or(writable_root.root);
add_allow_path(canonical);
for read_only_subpath in writable_root.read_only_subpaths {
add_deny_path(read_only_subpath);
}
}
AllowDenyPaths { allow, deny }
}
#[cfg(test)]
mod tests {
use super::*;
use akode_protocol::models::PermissionProfile;
use akode_protocol::permissions::NetworkSandboxPolicy;
use akode_utils_absolute_path::AbsolutePathBuf;
use std::fs;
use tempfile::TempDir;
fn workspace_write_profile(
writable_roots: &[AbsolutePathBuf],
exclude_tmpdir_env_var: bool,
exclude_slash_tmp: bool,
) -> PermissionProfile {
PermissionProfile::workspace_write_with(
writable_roots,
NetworkSandboxPolicy::Restricted,
exclude_tmpdir_env_var,
exclude_slash_tmp,
)
}
fn workspace_roots_for(root: &Path) -> Vec<AbsolutePathBuf> {
vec![AbsolutePathBuf::from_absolute_path(root).expect("absolute workspace root")]
}
fn compute_allow_paths(
permission_profile: &PermissionProfile,
workspace_roots: &[AbsolutePathBuf],
command_cwd: &Path,
env_map: &HashMap<String, String>,
) -> AllowDenyPaths {
let permissions =
ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots(
permission_profile,
workspace_roots,
)
.expect("managed permission profile");
compute_allow_paths_for_permissions(&permissions, command_cwd, env_map)
}
#[test]
fn includes_additional_writable_roots() {
let tmp = TempDir::new().expect("tempdir");
let command_cwd = tmp.path().join("workspace");
let extra_root = tmp.path().join("extra");
let _ = fs::create_dir_all(&command_cwd);
let _ = fs::create_dir_all(&extra_root);
let writable_roots = vec![AbsolutePathBuf::try_from(extra_root.as_path()).unwrap()];
let permission_profile = workspace_write_profile(
&writable_roots,
/*exclude_tmpdir_env_var*/ false,
/*exclude_slash_tmp*/ false,
);
let workspace_roots = workspace_roots_for(command_cwd.as_path());
let paths = compute_allow_paths(
&permission_profile,
workspace_roots.as_slice(),
&command_cwd,
&HashMap::new(),
);
assert!(
paths
.allow
.contains(&dunce::canonicalize(&command_cwd).unwrap())
);
assert!(
paths
.allow
.contains(&dunce::canonicalize(&extra_root).unwrap())
);
assert!(paths.deny.is_empty(), "no deny paths expected");
}
#[test]
fn uses_runtime_workspace_roots_for_workspace_root() {
let tmp = TempDir::new().expect("tempdir");
let workspace_root = tmp.path().join("workspace");
let command_cwd = workspace_root.join("subdir");
fs::create_dir_all(&command_cwd).expect("create command cwd");
let permission_profile = workspace_write_profile(
&[],
/*exclude_tmpdir_env_var*/ true,
/*exclude_slash_tmp*/ true,
);
let workspace_roots = workspace_roots_for(workspace_root.as_path());
let paths = compute_allow_paths(
&permission_profile,
workspace_roots.as_slice(),
&command_cwd,
&HashMap::new(),
);
assert!(
paths
.allow
.contains(&dunce::canonicalize(&workspace_root).unwrap())
);
assert!(
!paths
.allow
.contains(&dunce::canonicalize(&command_cwd).unwrap())
);
assert!(paths.deny.is_empty(), "no deny paths expected");
}
#[test]
fn excludes_tmp_env_vars_when_requested() {
let tmp = TempDir::new().expect("tempdir");
let command_cwd = tmp.path().join("workspace");
let temp_dir = tmp.path().join("temp");
let _ = fs::create_dir_all(&command_cwd);
let _ = fs::create_dir_all(&temp_dir);
let permission_profile = workspace_write_profile(
&[],
/*exclude_tmpdir_env_var*/ true,
/*exclude_slash_tmp*/ false,
);
let mut env_map = HashMap::new();
env_map.insert("TEMP".into(), temp_dir.to_string_lossy().to_string());
env_map.insert("TMP".into(), temp_dir.to_string_lossy().to_string());
let workspace_roots = workspace_roots_for(command_cwd.as_path());
let paths = compute_allow_paths(
&permission_profile,
workspace_roots.as_slice(),
&command_cwd,
&env_map,
);
assert!(
paths
.allow
.contains(&dunce::canonicalize(&command_cwd).unwrap())
);
assert!(
!paths
.allow
.contains(&dunce::canonicalize(&temp_dir).unwrap())
);
assert!(paths.deny.is_empty(), "no deny paths expected");
}
#[test]
fn includes_tmp_env_vars_when_requested() {
let tmp = TempDir::new().expect("tempdir");
let command_cwd = tmp.path().join("workspace");
let temp_dir = tmp.path().join("temp");
let _ = fs::create_dir_all(&command_cwd);
let _ = fs::create_dir_all(&temp_dir);
let permission_profile = workspace_write_profile(
&[],
/*exclude_tmpdir_env_var*/ false,
/*exclude_slash_tmp*/ false,
);
let mut env_map = HashMap::new();
env_map.insert("TEMP".into(), temp_dir.to_string_lossy().to_string());
env_map.insert("TMP".into(), temp_dir.to_string_lossy().to_string());
let workspace_roots = workspace_roots_for(command_cwd.as_path());
let paths = compute_allow_paths(
&permission_profile,
workspace_roots.as_slice(),
&command_cwd,
&env_map,
);
let expected_allow: HashSet<PathBuf> = [
dunce::canonicalize(&command_cwd).unwrap(),
dunce::canonicalize(&temp_dir).unwrap(),
]
.into_iter()
.collect();
assert_eq!(expected_allow, paths.allow);
assert!(paths.deny.is_empty(), "no deny paths expected");
}
#[test]
fn ignores_unix_slash_tmp_for_windows_allow_roots() {
let tmp = TempDir::new().expect("tempdir");
let command_cwd = tmp.path().join("workspace");
let _ = fs::create_dir_all(&command_cwd);
let permission_profile = workspace_write_profile(
&[],
/*exclude_tmpdir_env_var*/ true,
/*exclude_slash_tmp*/ false,
);
let workspace_roots = workspace_roots_for(command_cwd.as_path());
let paths = compute_allow_paths(
&permission_profile,
workspace_roots.as_slice(),
&command_cwd,
&HashMap::new(),
);
let expected_allow: HashSet<PathBuf> = [dunce::canonicalize(&command_cwd).unwrap()]
.into_iter()
.collect();
assert_eq!(expected_allow, paths.allow);
assert!(paths.deny.is_empty(), "no deny paths expected");
}
#[test]
fn denies_git_dir_inside_writable_root() {
let tmp = TempDir::new().expect("tempdir");
let command_cwd = tmp.path().join("workspace");
let git_dir = command_cwd.join(".git");
let _ = fs::create_dir_all(&git_dir);
let permission_profile = workspace_write_profile(
&[],
/*exclude_tmpdir_env_var*/ true,
/*exclude_slash_tmp*/ false,
);
let workspace_roots = workspace_roots_for(command_cwd.as_path());
let paths = compute_allow_paths(
&permission_profile,
workspace_roots.as_slice(),
&command_cwd,
&HashMap::new(),
);
let expected_allow: HashSet<PathBuf> = [dunce::canonicalize(&command_cwd).unwrap()]
.into_iter()
.collect();
let expected_deny: HashSet<PathBuf> = [dunce::canonicalize(&git_dir).unwrap()]
.into_iter()
.collect();
assert_eq!(expected_allow, paths.allow);
assert_eq!(expected_deny, paths.deny);
}
#[test]
fn denies_git_file_inside_writable_root() {
let tmp = TempDir::new().expect("tempdir");
let command_cwd = tmp.path().join("workspace");
let git_file = command_cwd.join(".git");
let _ = fs::create_dir_all(&command_cwd);
let _ = fs::write(&git_file, "gitdir: .git/worktrees/example");
let permission_profile = workspace_write_profile(
&[],
/*exclude_tmpdir_env_var*/ true,
/*exclude_slash_tmp*/ false,
);
let workspace_roots = workspace_roots_for(command_cwd.as_path());
let paths = compute_allow_paths(
&permission_profile,
workspace_roots.as_slice(),
&command_cwd,
&HashMap::new(),
);
let expected_allow: HashSet<PathBuf> = [dunce::canonicalize(&command_cwd).unwrap()]
.into_iter()
.collect();
let expected_deny: HashSet<PathBuf> = [dunce::canonicalize(&git_file).unwrap()]
.into_iter()
.collect();
assert_eq!(expected_allow, paths.allow);
assert_eq!(expected_deny, paths.deny);
}
#[test]
fn denies_codex_agents_and_aws_inside_writable_root() {
let tmp = TempDir::new().expect("tempdir");
let command_cwd = tmp.path().join("workspace");
let codex_dir = command_cwd.join(".akode");
let agents_dir = command_cwd.join(".agents");
let aws_dir = command_cwd.join(".aws");
let _ = fs::create_dir_all(&codex_dir);
let _ = fs::create_dir_all(&agents_dir);
let _ = fs::create_dir_all(&aws_dir);
let permission_profile = workspace_write_profile(
&[],
/*exclude_tmpdir_env_var*/ true,
/*exclude_slash_tmp*/ false,
);
let workspace_roots = workspace_roots_for(command_cwd.as_path());
let paths = compute_allow_paths(
&permission_profile,
workspace_roots.as_slice(),
&command_cwd,
&HashMap::new(),
);
let expected_allow: HashSet<PathBuf> = [dunce::canonicalize(&command_cwd).unwrap()]
.into_iter()
.collect();
let expected_deny: HashSet<PathBuf> = [
dunce::canonicalize(&codex_dir).unwrap(),
dunce::canonicalize(&agents_dir).unwrap(),
dunce::canonicalize(&aws_dir).unwrap(),
]
.into_iter()
.collect();
assert_eq!(expected_allow, paths.allow);
assert_eq!(expected_deny, paths.deny);
}
#[test]
fn skips_protected_subdirs_when_missing() {
let tmp = TempDir::new().expect("tempdir");
let command_cwd = tmp.path().join("workspace");
let _ = fs::create_dir_all(&command_cwd);
let permission_profile = workspace_write_profile(
&[],
/*exclude_tmpdir_env_var*/ true,
/*exclude_slash_tmp*/ false,
);
let workspace_roots = workspace_roots_for(command_cwd.as_path());
let paths = compute_allow_paths(
&permission_profile,
workspace_roots.as_slice(),
&command_cwd,
&HashMap::new(),
);
assert_eq!(paths.allow.len(), 1);
assert!(
paths.deny.is_empty(),
"no deny when protected dirs are absent"
);
}
}

View File

@@ -0,0 +1,253 @@
//! Select the requested runtime without inferring authority from directory or manifest text.
//! Registered runners still require OS package identity and the exact staged runner image.
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use anyhow::ensure;
use std::ffi::OsStr;
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
use std::path::Path;
use std::path::PathBuf;
use std::sync::OnceLock;
use windows_sys::Win32::Foundation::APPMODEL_ERROR_NO_PACKAGE;
use windows_sys::Win32::Foundation::ERROR_INSUFFICIENT_BUFFER;
use windows_sys::Win32::Foundation::ERROR_SUCCESS;
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::NetworkManagement::NetManagement::UF_ACCOUNTDISABLE;
use windows_sys::Win32::Storage::Packaging::Appx::GetPackageFullName;
use windows_sys::Win32::System::Threading::GetCurrentProcess;
use windows_sys::Win32::System::Threading::QueryFullProcessImageNameW;
#[link(name = "kernel32")]
unsafe extern "system" {
fn GetStagedPackagePathByFullName(
package_full_name: *const u16,
path_length: *mut u32,
path: *mut u16,
) -> i32;
}
/// Capture the startup request once; this flag never authorizes a package or process.
pub fn registered_core_requested() -> bool {
static REQUESTED: OnceLock<bool> = OnceLock::new();
*REQUESTED.get_or_init(|| {
requested_value(std::env::var_os("AKODE_WINDOWS_REGISTERED_CORE").as_deref())
})
}
fn requested_value(value: Option<&OsStr>) -> bool {
value == Some(OsStr::new("1"))
}
fn current_package_full_name() -> Result<Option<String>> {
process_package_name(unsafe { GetCurrentProcess() })
}
fn process_package_name(process: HANDLE) -> Result<Option<String>> {
query_package_name(
|length, buffer| unsafe { GetPackageFullName(process, length, buffer) },
/*max_length*/ 32768,
)
}
pub(crate) fn query_package_name(
mut query: impl FnMut(*mut u32, *mut u16) -> u32,
max_length: u32,
) -> Result<Option<String>> {
let mut length = 0;
let status = query(&mut length, std::ptr::null_mut());
if status == APPMODEL_ERROR_NO_PACKAGE {
return Ok(None);
}
ensure!(
status == ERROR_INSUFFICIENT_BUFFER && length > 1 && length <= max_length,
"package name query failed: {status}"
);
let mut family = vec![0u16; length as usize];
let status = query(&mut length, family.as_mut_ptr());
ensure!(
status == ERROR_SUCCESS && length > 1 && length as usize <= family.len(),
"package name read failed: {status}"
);
let family = family[..length as usize]
.strip_suffix(&[0])
.context("unterminated package name")?;
ensure!(!family.contains(&0), "invalid package name");
Ok(Some(String::from_utf16(family)?))
}
/// Preserve the caller's OS-assigned package identity for sandboxed descendants.
pub(crate) fn current_process_has_package_identity() -> Result<bool> {
let has_identity = current_package_full_name()?.is_some();
ensure!(
has_identity || !registered_core_requested(),
"registered Core process has no package identity"
);
Ok(has_identity)
}
fn staged_package_root(name: &[u16]) -> Result<PathBuf> {
let mut staged = vec![0u16; 32768];
let mut length = staged.len() as u32;
let status =
unsafe { GetStagedPackagePathByFullName(name.as_ptr(), &mut length, staged.as_mut_ptr()) };
ensure!(
status == 0 && length > 1 && length as usize <= staged.len(),
"registered Core staged package query failed: {status}"
);
let staged = &staged[..length as usize];
ensure!(
staged.last() == Some(&0) && !staged[..staged.len() - 1].contains(&0),
"invalid registered Core staged package path"
);
dunce::canonicalize(OsString::from_wide(&staged[..staged.len() - 1]))
.context("resolve OS-staged package root")
}
pub(crate) fn verify_registered_core_runner(process: HANDLE, expected_runner: &Path) -> Result<()> {
let name =
process_package_name(process)?.context("registered Core runner has no package identity")?;
let staged = staged_package_root(&crate::winutil::to_wide(name))?;
let expected =
dunce::canonicalize(expected_runner).context("resolve registered Core runner")?;
ensure!(
expected.as_os_str().eq_ignore_ascii_case(
staged
.join("app")
.join("resources")
.join("akode-command-runner.exe")
.as_os_str()
),
"registered alias selected a different package identity"
);
let mut image = vec![0u16; 32768];
let mut length = image.len() as u32;
if unsafe { QueryFullProcessImageNameW(process, 0, image.as_mut_ptr(), &mut length) } == 0 {
return Err(std::io::Error::last_os_error())
.context("inspect registered Core runner image");
}
ensure!(
length > 0 && length as usize <= image.len(),
"invalid registered Core image length"
);
let image = dunce::canonicalize(OsString::from_wide(&image[..length as usize]))?;
ensure!(
image.as_os_str().eq_ignore_ascii_case(expected.as_os_str()),
"registered alias selected a different runner image"
);
Ok(())
}
/// Checks the service's committed receipt without provisioning or mutating either account.
pub(crate) fn registered_setup_is_ready(codex_home: &Path) -> Result<bool> {
for account in [
crate::setup::OFFLINE_USERNAME,
crate::setup::ONLINE_USERNAME,
] {
if crate::winutil::local_user_flags(account)?
.is_none_or(|flags| flags & UF_ACCOUNTDISABLE != 0)
{
return Ok(false);
}
}
let Some(package) = current_package_full_name()? else {
return Ok(false);
};
let Some(record) = crate::runtime_ownership::load_installation()? else {
return Ok(false);
};
Ok(record.codex_home == codex_home.canonicalize()?
&& record.runtime()?.ready_for_package(&package))
}
/// A startup hint only; the service rechecks ownership and readiness under its setup lock.
#[doc(hidden)]
pub fn registered_core_needs_refresh(codex_home: &Path) -> Result<bool> {
let Some(package) = current_package_full_name()? else {
return Ok(false);
};
let Some(record) = crate::runtime_ownership::load_installation()? else {
return Ok(false);
};
let runtime = record.runtime()?;
Ok(record.codex_home == codex_home.canonicalize()?
&& runtime
.ready_package
.as_deref()
.is_some_and(|ready| ready != package && runtime.ready_for_package(ready)))
}
/// Consume the service's setup receipt; launching a command never installs a package.
pub(crate) fn registered_runner_alias(
codex_home: &Path,
sandbox_username: &str,
) -> anyhow::Result<PathBuf> {
let account = if sandbox_username.eq_ignore_ascii_case(crate::setup::OFFLINE_USERNAME) {
crate::SandboxRuntimeAccount::Offline
} else if sandbox_username.eq_ignore_ascii_case(crate::setup::ONLINE_USERNAME) {
crate::SandboxRuntimeAccount::Online
} else {
bail!("app runtime registration requires a managed sandbox account");
};
let record = crate::runtime_ownership::load_installation()?
.context("registered Core setup has not completed")?;
let package =
current_package_full_name()?.context("registered Core launch requires an installed app")?;
let owner = crate::winutil::resolve_sid(&crate::runtime_ownership::current_setup_user()?)?;
let owner = crate::winutil::string_from_sid_bytes(&owner).map_err(anyhow::Error::msg)?;
authorize_runner_receipt(&record, &owner, &codex_home.canonicalize()?, &package)?;
let entry = record
.runtime()?
.accounts
.iter()
.find(|entry| entry.account == account)
.context("managed account registration is not ready; retry setup")?;
let sid = crate::winutil::resolve_sid(sandbox_username)?;
anyhow::ensure!(
entry.user_sid
== crate::winutil::string_from_sid_bytes(&sid).map_err(anyhow::Error::msg)?,
"managed runtime account changed; retry setup"
);
let path = entry
.alias_path
.as_ref()
.context("registered Core alias is not ready; retry setup")?;
anyhow::ensure!(
path.is_absolute()
&& path.file_name() == Some(std::ffi::OsStr::new(crate::APP_CORE_RUNNER_ALIAS)),
"registered Core setup contains an invalid alias"
);
Ok(path.clone())
}
fn authorize_runner_receipt(
record: &crate::installation_record::InstallationRecord,
owner: &str,
codex_home: &Path,
package: &str,
) -> Result<()> {
ensure!(
record.user_sid == owner,
"registered Core setup belongs to another owner"
);
ensure!(
record.codex_home == codex_home,
"registered Core setup belongs to another Codex home"
);
let runtime = record.runtime()?;
ensure!(
runtime.retiring.is_none(),
"registered Core setup is being removed"
);
ensure!(
runtime.ready_for_package(package),
"registered Core setup is not complete for the installed app; retry sandbox setup"
);
Ok(())
}
#[cfg(test)]
#[path = "app_package_tests.rs"]
mod tests;

View File

@@ -0,0 +1,176 @@
//! Runtime opt-in and bounded OS package-name results, without installed-state changes.
use super::authorize_runner_receipt;
use super::query_package_name;
use super::requested_value;
use crate::installation_record::InstallationRecord;
use crate::runtime_ownership::RuntimeAccountRegistration;
use crate::runtime_ownership::RuntimeRegistration;
use crate::runtime_ownership::SandboxRuntimeAccount;
use pretty_assertions::assert_eq;
use std::ffi::OsStr;
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
use std::path::Path;
use windows_sys::Win32::Foundation::APPMODEL_ERROR_NO_PACKAGE;
use windows_sys::Win32::Foundation::ERROR_ACCESS_DENIED;
use windows_sys::Win32::Foundation::ERROR_INSUFFICIENT_BUFFER;
use windows_sys::Win32::Foundation::ERROR_SUCCESS;
#[test]
fn only_exact_opt_in_requests_registered_core() {
let values = [
None,
Some(""),
Some("0"),
Some("1"),
Some("true"),
Some(" 1"),
Some("1 "),
];
assert_eq!(
values.map(|value| requested_value(value.map(OsStr::new))),
[false, false, false, true, false, false, false]
);
assert!(!requested_value(Some(&OsString::from_wide(&[0xd800]))));
}
#[test]
fn runner_receipt_distinguishes_incomplete_setup_from_owner_and_removal() {
let owner = "S-1-5-21-100";
let home = Path::new(r"C:\Users\owner\.akode");
let package = "OpenAI.Codex_current";
let runtime = RuntimeRegistration {
package_family: "OpenAI.Codex_family".to_owned(),
accounts: Vec::new(),
metadata_roots: Vec::new(),
ready_package: None,
retiring: None,
};
let mut record = InstallationRecord {
user_sid: owner.to_owned(),
codex_home: home.to_owned(),
session_id: 1,
desktop_installation: None,
runtime: Some(runtime),
};
let incomplete =
"registered Core setup is not complete for the installed app; retry sandbox setup";
assert_eq!(
authorize_runner_receipt(&record, owner, home, package)
.unwrap_err()
.to_string(),
incomplete
);
record.runtime.as_mut().unwrap().retiring = Some("removing".to_owned());
for (candidate_owner, candidate_home, message) in [
(
"S-1-5-21-200",
home,
"registered Core setup belongs to another owner",
),
(
owner,
Path::new(r"C:\Users\other\.akode"),
"registered Core setup belongs to another Codex home",
),
(owner, home, "registered Core setup is being removed"),
] {
assert_eq!(
authorize_runner_receipt(&record, candidate_owner, candidate_home, package)
.unwrap_err()
.to_string(),
message
);
}
let runtime = record.runtime.as_mut().unwrap();
runtime.retiring = None;
runtime.accounts = [
SandboxRuntimeAccount::Offline,
SandboxRuntimeAccount::Online,
]
.into_iter()
.map(|account| RuntimeAccountRegistration {
cleanup_logon_pending: false,
account,
user_sid: format!("{account:?}"),
alias_path: Some(home.join(account.username())),
})
.collect();
runtime.ready_package = Some(package.to_owned());
assert!(authorize_runner_receipt(&record, owner, home, package).is_ok());
assert_eq!(
authorize_runner_receipt(&record, owner, home, "OpenAI.Codex_updated")
.unwrap_err()
.to_string(),
incomplete
);
}
#[test]
fn package_query_distinguishes_absence_from_failure_and_bounds_allocation() {
assert_eq!(
query_package_name(|_, _| APPMODEL_ERROR_NO_PACKAGE, /*max_length*/ 256).unwrap(),
None
);
assert!(query_package_name(|_, _| ERROR_ACCESS_DENIED, /*max_length*/ 256).is_err());
for max_length in [256, 32768] {
assert!(
query_package_name(
|length, buffer| {
assert!(buffer.is_null());
unsafe { *length = max_length + 1 };
ERROR_INSUFFICIENT_BUFFER
},
max_length
)
.is_err()
);
}
}
#[test]
fn package_query_validates_returned_length_termination_and_utf16() {
for (value, returned, expected) in [
(vec![65, 0], 2, Some("A")),
(vec![65, 0], 0, None),
(vec![65, 0], 3, None),
(vec![65, 66], 2, None),
(vec![65, 0, 66, 0], 4, None),
(vec![0xd800, 0], 2, None),
] {
let actual = query_package_name(
|length, buffer| {
if buffer.is_null() {
unsafe { *length = value.len() as u32 };
ERROR_INSUFFICIENT_BUFFER
} else {
unsafe {
std::ptr::copy_nonoverlapping(value.as_ptr(), buffer, value.len());
*length = returned;
}
ERROR_SUCCESS
}
},
/*max_length*/ 256,
);
match expected {
Some(name) => assert_eq!(actual.unwrap(), Some(name.to_owned())),
None => assert!(actual.is_err()),
}
}
assert!(
query_package_name(
|length, buffer| {
unsafe { *length = 2 };
if buffer.is_null() {
ERROR_INSUFFICIENT_BUFFER
} else {
ERROR_ACCESS_DENIED
}
},
/*max_length*/ 256
)
.is_err()
);
}

View File

@@ -0,0 +1,14 @@
#![cfg_attr(all(target_os = "windows", not(test)), windows_subsystem = "windows")]
#[cfg(target_os = "windows")]
mod win;
#[cfg(target_os = "windows")]
fn main() -> anyhow::Result<()> {
win::main()
}
#[cfg(not(target_os = "windows"))]
fn main() {
panic!("akode-command-runner is Windows-only");
}

View File

@@ -0,0 +1,731 @@
//! Windows command runner used by the **elevated** sandbox path.
//!
//! The CLI launches this binary under the sandbox user when Windows sandbox level is
//! Elevated. It connects to the IPC pipes, reads the framed `SpawnRequest`, derives a
//! restricted token from the sandbox user, and spawns the child process via ConPTY
//! (`tty=true`) or pipes (`tty=false`). It then streams output frames back to the parent,
//! accepts stdin/terminate frames, and emits a final exit frame. The legacy restricted‑token
//! path spawns the child directly and does not use this runner.
#![allow(unsafe_op_in_unsafe_fn)]
mod cwd_junction;
#[cfg(test)]
#[path = "win/input_loop_tests.rs"]
mod input_loop_tests;
use anyhow::Context;
use anyhow::Result;
use akode_utils_pty::JobObject;
use akode_windows_sandbox::ConsoleMode;
use akode_windows_sandbox::ErrorPayload;
use akode_windows_sandbox::ErrorStage;
use akode_windows_sandbox::ExitPayload;
use akode_windows_sandbox::FramedMessage;
use akode_windows_sandbox::IPC_PROTOCOL_VERSION;
use akode_windows_sandbox::LaunchDesktop;
use akode_windows_sandbox::LocalSid;
use akode_windows_sandbox::Message;
use akode_windows_sandbox::OutputPayload;
use akode_windows_sandbox::OutputStream;
use akode_windows_sandbox::PipeSpawnHandles;
use akode_windows_sandbox::ResizePayload;
use akode_windows_sandbox::SpawnReady;
use akode_windows_sandbox::SpawnRequest;
use akode_windows_sandbox::StderrMode;
use akode_windows_sandbox::StdinMode;
use akode_windows_sandbox::WindowsSandboxTokenMode;
use akode_windows_sandbox::allow_null_device;
use akode_windows_sandbox::create_readonly_token_with_caps_and_user_from;
use akode_windows_sandbox::create_workspace_write_token_with_caps_and_user_from;
use akode_windows_sandbox::decode_bytes;
use akode_windows_sandbox::encode_bytes;
use akode_windows_sandbox::get_current_token_for_restriction;
use akode_windows_sandbox::hide_current_user_profile_dir;
use akode_windows_sandbox::log_note;
use akode_windows_sandbox::read_frame;
use akode_windows_sandbox::read_handle_loop;
use akode_windows_sandbox::spawn_process_with_pipes;
use akode_windows_sandbox::to_wide;
use akode_windows_sandbox::token_mode_for_permission_profile;
use akode_windows_sandbox::write_frame;
use std::ffi::OsStr;
use std::fs::File;
use std::os::windows::io::AsHandle;
use std::os::windows::io::AsRawHandle;
use std::os::windows::io::FromRawHandle;
use std::os::windows::io::OwnedHandle;
use std::path::Path;
use std::path::PathBuf;
use std::ptr;
use std::sync::Arc;
use std::sync::Mutex as StdMutex;
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::Foundation::ERROR_FILE_NOT_FOUND;
use windows_sys::Win32::Foundation::GetLastError;
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
use windows_sys::Win32::Storage::FileSystem::CreateFileW;
use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_READ;
use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_WRITE;
use windows_sys::Win32::Storage::FileSystem::OPEN_EXISTING;
use windows_sys::Win32::System::Console::COORD;
use windows_sys::Win32::System::Console::HPCON;
use windows_sys::Win32::System::Console::ResizePseudoConsole;
use windows_sys::Win32::System::Threading::GetExitCodeProcess;
use windows_sys::Win32::System::Threading::GetProcessId;
use windows_sys::Win32::System::Threading::INFINITE;
use windows_sys::Win32::System::Threading::MUTEX_ALL_ACCESS;
use windows_sys::Win32::System::Threading::OpenMutexW;
use windows_sys::Win32::System::Threading::PROCESS_INFORMATION;
use windows_sys::Win32::System::Threading::TerminateProcess;
use windows_sys::Win32::System::Threading::WaitForSingleObject;
const READ_ACL_MUTEX_NAME: &str = "Local\\CodexSandboxReadAcl";
const TERMINATION_WAIT_MS: u32 = 5_000;
const WAIT_TIMEOUT: u32 = 0x0000_0102;
struct IpcSpawnedProcess {
log_dir: PathBuf,
pi: PROCESS_INFORMATION,
job: Arc<JobObject>,
stdout_handle: HANDLE,
stderr_handle: HANDLE,
stdin_handle: Option<HANDLE>,
conpty_owner: Option<akode_windows_sandbox::ConptyInstance>,
hpc_handle: Option<HPCON>,
_pipe_handles: Option<PipeSpawnHandles>,
}
struct NonOwningProcessHandle(HANDLE);
// SAFETY: Process handles are opaque process-wide tokens that may be used from
// any thread. This wrapper does not own the handle or extend its lifetime.
unsafe impl Send for NonOwningProcessHandle {}
/// Small RAII wrapper for raw Win32 handles.
///
/// The elevated runner has a few early-return paths where we acquire a token, job, or pipe
/// handle and then may fail while preparing the child. Keeping those handles in a guard makes
/// the error paths read more directly and closes the gaps that were previously leaking them.
struct OwnedWinHandle(HANDLE);
impl OwnedWinHandle {
fn new(handle: HANDLE) -> Self {
Self(handle)
}
fn raw(&self) -> HANDLE {
self.0
}
fn into_raw(mut self) -> HANDLE {
// Transfer ownership to the caller. After this point the caller is responsible for
// eventually closing the returned HANDLE.
let handle = self.0;
self.0 = std::ptr::null_mut();
handle
}
}
impl Drop for OwnedWinHandle {
fn drop(&mut self) {
if !self.0.is_null() && self.0 != INVALID_HANDLE_VALUE {
unsafe {
CloseHandle(self.0);
}
}
}
}
/// Open a named pipe created by the parent process.
fn open_pipe(name: &str, access: u32) -> Result<HANDLE> {
let path = to_wide(name);
let handle = unsafe {
CreateFileW(
path.as_ptr(),
access,
0,
std::ptr::null_mut(),
OPEN_EXISTING,
0,
std::ptr::null_mut(),
)
};
if handle == windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE {
let err = unsafe { GetLastError() };
return Err(anyhow::anyhow!("CreateFileW failed for pipe {name}: {err}"));
}
Ok(handle)
}
/// Send an error frame back to the parent process.
fn send_error(
writer: &Arc<StdMutex<File>>,
stage: ErrorStage,
windows_error_code: Option<u32>,
message: String,
) -> Result<()> {
let msg = FramedMessage {
version: IPC_PROTOCOL_VERSION,
message: Message::Error {
payload: ErrorPayload {
message,
stage,
windows_error_code,
},
},
};
if let Ok(mut guard) = writer.lock() {
write_frame(&mut *guard, &msg)?;
}
Ok(())
}
fn windows_error_code(err: &anyhow::Error) -> Option<u32> {
err.chain().find_map(|cause| {
cause
.downcast_ref::<std::io::Error>()
.and_then(std::io::Error::raw_os_error)
.and_then(|code| u32::try_from(code).ok())
})
}
/// Read and validate the initial spawn request frame.
fn read_spawn_request(reader: &mut File) -> Result<SpawnRequest> {
let Some(msg) = read_frame(reader)? else {
anyhow::bail!("runner: pipe closed before spawn_request");
};
if msg.version != IPC_PROTOCOL_VERSION {
anyhow::bail!("runner: unsupported protocol version {}", msg.version);
}
match msg.message {
Message::SpawnRequest { payload } => Ok(*payload),
other => anyhow::bail!("runner: expected spawn_request, got {other:?}"),
}
}
fn read_acl_mutex_exists() -> Result<bool> {
let name = to_wide(OsStr::new(READ_ACL_MUTEX_NAME));
let handle = unsafe { OpenMutexW(MUTEX_ALL_ACCESS, 0, name.as_ptr()) };
if handle.is_null() {
let err = unsafe { GetLastError() };
if err == ERROR_FILE_NOT_FOUND {
return Ok(false);
}
return Err(anyhow::anyhow!("OpenMutexW failed: {err}"));
}
unsafe {
CloseHandle(handle);
}
Ok(true)
}
/// Pick an effective CWD, using a junction if the ACL helper is active.
fn effective_cwd(req_cwd: &Path, log_dir: Option<&Path>) -> PathBuf {
let use_junction = match read_acl_mutex_exists() {
Ok(exists) => exists,
Err(err) => {
log_note(
&format!(
"junction: failed to probe ACL mutex state: {err}; defaulting to junction cwd"
),
log_dir,
);
true
}
};
if use_junction {
cwd_junction::create_cwd_junction(req_cwd, log_dir).unwrap_or_else(|| req_cwd.to_path_buf())
} else {
req_cwd.to_path_buf()
}
}
fn spawn_ipc_process(req: &SpawnRequest) -> Result<IpcSpawnedProcess> {
let log_dir = req.codex_home.clone();
hide_current_user_profile_dir(req.codex_home.as_path());
let token_mode = token_mode_for_permission_profile(
&req.permission_profile,
&req.workspace_roots,
&req.cwd,
&req.env,
)
.context("resolve permission profile token mode")?;
let mut cap_psids: Vec<LocalSid> = Vec::new();
for sid in &req.cap_sids {
cap_psids.push(
LocalSid::from_string(sid)
.context("ConvertStringSidToSidW failed for capability SID")?,
);
}
if cap_psids.is_empty() {
anyhow::bail!("runner: empty capability SID list");
}
let network_proxy_restricting_sid = req
.network_proxy_restricting_sid
.as_deref()
.map(LocalSid::from_string)
.transpose()
.context("ConvertStringSidToSidW failed for network proxy restricting SID")?;
// The token helpers still take raw SID pointers, but we keep ownership in `LocalSid`
// wrappers for as long as possible. That way any failure after SID parsing but before the
// child is fully spawned still releases the backing LocalAlloc memory automatically.
let cap_psid_ptrs: Vec<*mut _> = cap_psids.iter().map(LocalSid::as_ptr).collect();
let additional_restricting_sid_ptrs: Vec<*mut _> = network_proxy_restricting_sid
.iter()
.map(LocalSid::as_ptr)
.collect();
let base = OwnedWinHandle::new(unsafe { get_current_token_for_restriction()? });
let h_token = unsafe {
match token_mode {
WindowsSandboxTokenMode::ReadOnlyCapability => {
create_readonly_token_with_caps_and_user_from(
base.raw(),
&cap_psid_ptrs,
&additional_restricting_sid_ptrs,
)
}
WindowsSandboxTokenMode::WritableRootsCapability => {
create_workspace_write_token_with_caps_and_user_from(
base.raw(),
&cap_psid_ptrs,
&additional_restricting_sid_ptrs,
)
}
}
}?;
// SAFETY: Both token helpers transfer ownership of the returned handle to the caller.
let h_token = unsafe { OwnedHandle::from_raw_handle(h_token) };
unsafe {
// These ACL adjustments need the raw SID values, but ownership stays with `cap_psids`.
// We do not manually `LocalFree` anything here; the wrappers handle every return path.
allow_null_device(cap_psid_ptrs[0]);
for psid in &cap_psid_ptrs {
allow_null_device(*psid);
}
}
let effective_cwd = effective_cwd(&req.cwd, Some(log_dir.as_path()));
let desktop = LaunchDesktop::open_private(
req.private_desktop_name
.as_deref()
.context("runner: missing parent-owned private desktop")?,
)?;
let mut conpty_owner = None;
let mut hpc_handle: Option<HPCON> = None;
let mut pipe_handles = None;
let (pi, job, stdout_handle, stderr_handle, stdin_handle) = if req.tty {
let (pi, mut conpty) = akode_windows_sandbox::spawn_conpty_process_as_user(
h_token.as_handle(),
&req.command,
&effective_cwd,
&req.env,
desktop,
)?;
let job = conpty
.job()
.context("spawned ConPTY is missing its process job")?;
hpc_handle = conpty.raw_handle();
let input_write = conpty.take_input_write();
let output_read = conpty.take_output_read();
conpty_owner = Some(conpty);
let stdin_handle = if req.stdin_open {
Some(input_write)
} else {
unsafe {
CloseHandle(input_write);
}
None
};
(
pi,
job,
output_read,
windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE,
stdin_handle,
)
} else {
let stdin_mode = if req.stdin_open {
StdinMode::Open
} else {
StdinMode::Closed
};
let spawned_pipes: PipeSpawnHandles = spawn_process_with_pipes(
h_token.as_handle(),
&req.command,
&effective_cwd,
&req.env,
stdin_mode,
StderrMode::Separate,
ConsoleMode::NoWindow,
desktop,
Some(log_dir.as_path()),
)?;
let pi = spawned_pipes.process;
let stdout_handle = spawned_pipes.stdout_read;
let stderr_handle = spawned_pipes
.stderr_read
.unwrap_or(windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE);
let stdin_handle = spawned_pipes.stdin_write;
let job = spawned_pipes.job();
pipe_handles = Some(spawned_pipes);
(pi, job, stdout_handle, stderr_handle, stdin_handle)
};
Ok(IpcSpawnedProcess {
log_dir,
pi,
job,
stdout_handle,
stderr_handle,
stdin_handle,
conpty_owner,
hpc_handle,
_pipe_handles: pipe_handles,
})
}
/// Stream stdout/stderr from the child into Output frames.
fn spawn_output_reader(
writer: Arc<StdMutex<File>>,
handle: HANDLE,
stream: OutputStream,
log_dir: Option<PathBuf>,
) -> std::thread::JoinHandle<()> {
// SAFETY: The spawn path transfers this pipe's read end to the reader.
let handle = unsafe { OwnedHandle::from_raw_handle(handle) };
read_handle_loop(handle, move |chunk| {
let msg = FramedMessage {
version: IPC_PROTOCOL_VERSION,
message: Message::Output {
payload: OutputPayload {
data_b64: encode_bytes(chunk),
stream,
},
},
};
if let Ok(mut guard) = writer.lock()
&& let Err(err) = write_frame(&mut *guard, &msg)
{
log_note(
&format!("runner output write failed: {err}"),
log_dir.as_deref(),
);
}
})
}
fn terminate_job_or_process(
job: &JobObject,
process: &NonOwningProcessHandle,
log_dir: Option<&Path>,
) {
if let Err(job_err) = job.terminate() {
log_note(
&format!("runner failed to terminate process tree: {job_err}"),
log_dir,
);
if unsafe { TerminateProcess(process.0, 1) } == 0 {
log_note(
&format!("runner failed to terminate root process: {}", unsafe {
GetLastError()
}),
log_dir,
);
}
}
}
/// Read stdin/terminate frames and forward to the child process.
fn spawn_input_loop(
mut reader: File,
stdin_handle: Option<HANDLE>,
hpc_handle: Arc<StdMutex<Option<HPCON>>>,
job: Arc<JobObject>,
process: NonOwningProcessHandle,
log_dir: Option<PathBuf>,
) -> std::thread::JoinHandle<()> {
// SAFETY: The spawn path transfers the pipe's write end to this input loop.
let stdin_handle = stdin_handle.map(|handle| unsafe { OwnedHandle::from_raw_handle(handle) });
std::thread::spawn(move || {
let mut stdin_handle = stdin_handle;
loop {
let msg = match read_frame(&mut reader) {
Ok(Some(v)) => v,
Ok(None) | Err(_) => {
terminate_job_or_process(&job, &process, log_dir.as_deref());
break;
}
};
match msg.message {
Message::Stdin { payload } => {
let Ok(bytes) = decode_bytes(&payload.data_b64) else {
continue;
};
if let Some(handle) = &stdin_handle {
let mut offset = 0usize;
// `WriteFile` can report success after consuming only part of the buffer
// when the target is a pipe. Treat this like a normal partial write and
// keep advancing until every decoded stdin byte has been forwarded.
//
// If the child closes stdin or the pipe enters an error state, we log
// that fact, close our local HANDLE, and stop trying to forward later
// `Stdin` frames. That prevents silent truncation while also avoiding an
// endless stream of failing writes after the child is already gone.
while offset < bytes.len() {
let chunk = &bytes[offset..];
let chunk_len = chunk.len().min(u32::MAX as usize);
let mut written = 0u32;
let ok = unsafe {
windows_sys::Win32::Storage::FileSystem::WriteFile(
handle.as_raw_handle(),
chunk.as_ptr(),
chunk_len as u32,
&mut written,
ptr::null_mut(),
)
};
if ok == 0 {
log_note(
&format!(
"runner stdin write failed after {offset} bytes: {}",
unsafe { GetLastError() }
),
log_dir.as_deref(),
);
stdin_handle = None;
break;
}
if written == 0 {
log_note(
"runner stdin write made no progress; closing child stdin",
log_dir.as_deref(),
);
stdin_handle = None;
break;
}
offset += written as usize;
}
}
}
Message::CloseStdin { .. } => {
drop(stdin_handle.take());
}
Message::Resize {
payload: ResizePayload { rows, cols },
} => {
if let Ok(guard) = hpc_handle.lock()
&& let Some(hpc) = guard.as_ref()
{
unsafe {
let _ = ResizePseudoConsole(
*hpc,
COORD {
X: cols as i16,
Y: rows as i16,
},
);
}
}
}
Message::Terminate { .. } => {
terminate_job_or_process(&job, &process, log_dir.as_deref());
}
Message::SpawnRequest { .. } => {}
Message::SpawnReady { .. } => {}
Message::Output { .. } => {}
Message::Exit { .. } => {}
Message::Error { .. } => {}
}
}
})
}
/// Entry point for the Windows command runner process.
pub fn main() -> Result<()> {
let mut pipe_in = None;
let mut pipe_out = None;
for arg in std::env::args().skip(1) {
if let Some(rest) = arg.strip_prefix("--pipe-in=") {
pipe_in = Some(rest.to_string());
} else if let Some(rest) = arg.strip_prefix("--pipe-out=") {
pipe_out = Some(rest.to_string());
}
}
let Some(pipe_in) = pipe_in else {
anyhow::bail!("runner: no pipe-in provided");
};
let Some(pipe_out) = pipe_out else {
anyhow::bail!("runner: no pipe-out provided");
};
// Open both pipe ends under guards first so a failure on the second open cannot leak the
// first HANDLE. Only after both opens succeed do we transfer ownership into `File`, which
// then becomes responsible for closing them.
let h_pipe_in = OwnedWinHandle::new(open_pipe(&pipe_in, FILE_GENERIC_READ)?);
let h_pipe_out = OwnedWinHandle::new(open_pipe(&pipe_out, FILE_GENERIC_WRITE)?);
let mut pipe_read = unsafe { File::from_raw_handle(h_pipe_in.into_raw() as _) };
let pipe_write = Arc::new(StdMutex::new(unsafe {
File::from_raw_handle(h_pipe_out.into_raw() as _)
}));
let req = match read_spawn_request(&mut pipe_read) {
Ok(v) => v,
Err(err) => {
let _ = send_error(
&pipe_write,
ErrorStage::ReadSpawnRequest,
/*windows_error_code*/ None,
err.to_string(),
);
return Err(err);
}
};
let ipc_spawn = match spawn_ipc_process(&req) {
Ok(value) => value,
Err(err) => {
let _ = send_error(
&pipe_write,
ErrorStage::SpawnChild,
windows_error_code(&err),
err.to_string(),
);
return Err(err);
}
};
let log_dir = Some(ipc_spawn.log_dir.as_path());
let pi = ipc_spawn.pi;
let stdout_handle = ipc_spawn.stdout_handle;
let stderr_handle = ipc_spawn.stderr_handle;
let job = Arc::clone(&ipc_spawn.job);
let mut conpty_owner = ipc_spawn.conpty_owner;
let stdin_handle = ipc_spawn.stdin_handle;
let hpc_handle = Arc::new(StdMutex::new(ipc_spawn.hpc_handle));
let msg = FramedMessage {
version: IPC_PROTOCOL_VERSION,
message: Message::SpawnReady {
payload: SpawnReady {
process_id: unsafe { GetProcessId(pi.hProcess) },
},
},
};
if let Err(err) = if let Ok(mut guard) = pipe_write.lock() {
write_frame(&mut *guard, &msg)
} else {
anyhow::bail!("runner spawn_ready write failed: pipe_write lock poisoned");
} {
let _ = send_error(
&pipe_write,
ErrorStage::WriteSpawnReady,
/*windows_error_code*/ None,
err.to_string(),
);
return Err(err);
}
let log_dir_owned = log_dir.map(Path::to_path_buf);
let out_thread = spawn_output_reader(
Arc::clone(&pipe_write),
stdout_handle,
OutputStream::Stdout,
log_dir_owned.clone(),
);
let err_thread = if stderr_handle != windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE {
Some(spawn_output_reader(
Arc::clone(&pipe_write),
stderr_handle,
OutputStream::Stderr,
log_dir_owned.clone(),
))
} else {
None
};
let _input_thread = spawn_input_loop(
pipe_read,
stdin_handle,
Arc::clone(&hpc_handle),
Arc::clone(&job),
NonOwningProcessHandle(pi.hProcess),
log_dir_owned,
);
let timeout = req.timeout_ms.map(|ms| ms as u32).unwrap_or(INFINITE);
let wait_res = unsafe { WaitForSingleObject(pi.hProcess, timeout) };
let timed_out = wait_res == WAIT_TIMEOUT;
let child_stopped = if timed_out {
terminate_job_or_process(&job, &NonOwningProcessHandle(pi.hProcess), log_dir);
let termination_wait = unsafe { WaitForSingleObject(pi.hProcess, TERMINATION_WAIT_MS) };
if termination_wait == WAIT_TIMEOUT {
log_note(
"runner root process did not exit after termination",
log_dir,
);
false
} else {
true
}
} else {
if let Err(err) = job.preserve_descendants() {
log_note(
&format!("runner failed to preserve descendants after root exit: {err}"),
log_dir,
);
}
true
};
let exit_code: i32;
unsafe {
if timed_out {
exit_code = 128 + 64;
} else {
let mut raw_exit: u32 = 1;
GetExitCodeProcess(pi.hProcess, &mut raw_exit);
exit_code = raw_exit as i32;
}
if !pi.hThread.is_null() {
CloseHandle(pi.hThread);
}
if !pi.hProcess.is_null() {
CloseHandle(pi.hProcess);
}
}
if let Ok(mut guard) = hpc_handle.lock() {
let _ = guard.take();
}
drop(conpty_owner.take());
if child_stopped {
if out_thread.join().is_err() {
log_note("runner stdout reader thread panicked", log_dir);
}
if let Some(thread) = err_thread
&& thread.join().is_err()
{
log_note("runner stderr reader thread panicked", log_dir);
}
}
let exit_msg = FramedMessage {
version: IPC_PROTOCOL_VERSION,
message: Message::Exit {
payload: ExitPayload {
exit_code,
timed_out,
},
},
};
if let Ok(mut guard) = pipe_write.lock()
&& let Err(err) = write_frame(&mut *guard, &exit_msg)
{
log_note(&format!("runner exit write failed: {err}"), log_dir);
}
std::process::exit(exit_code);
}

View File

@@ -0,0 +1,140 @@
use akode_windows_sandbox::log_note;
use std::collections::hash_map::DefaultHasher;
use std::hash::Hash;
use std::hash::Hasher;
use std::os::windows::fs::MetadataExt as _;
use std::os::windows::process::CommandExt as _;
use std::path::Path;
use std::path::PathBuf;
use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT;
fn junction_name_for_path(path: &Path) -> String {
let mut hasher = DefaultHasher::new();
path.to_string_lossy().hash(&mut hasher);
format!("{:x}", hasher.finish())
}
fn junction_root_for_userprofile(userprofile: &str) -> PathBuf {
PathBuf::from(userprofile)
.join(".akode")
.join(".sandbox")
.join("cwd")
}
pub fn create_cwd_junction(requested_cwd: &Path, log_dir: Option<&Path>) -> Option<PathBuf> {
let userprofile = std::env::var("USERPROFILE").ok()?;
let junction_root = junction_root_for_userprofile(&userprofile);
if let Err(err) = std::fs::create_dir_all(&junction_root) {
log_note(
&format!(
"junction: failed to create {}: {err}",
junction_root.display()
),
log_dir,
);
return None;
}
let junction_path = junction_root.join(junction_name_for_path(requested_cwd));
if junction_path.exists() {
// Reuse an existing junction if it looks like a reparse point; this keeps the hot path
// cheap and avoids repeatedly shelling out to mklink.
match std::fs::symlink_metadata(&junction_path) {
Ok(md) if (md.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT) != 0 => {
log_note(
&format!("junction: reusing existing {}", junction_path.display()),
log_dir,
);
return Some(junction_path);
}
Ok(_) => {
// Unexpected: something else exists at this path (regular directory/file). We'll
// try to remove it if possible and recreate the junction.
log_note(
&format!(
"junction: existing path is not a reparse point, recreating {}",
junction_path.display()
),
log_dir,
);
}
Err(err) => {
log_note(
&format!(
"junction: failed to stat existing {}: {err}",
junction_path.display()
),
log_dir,
);
return None;
}
}
if let Err(err) = std::fs::remove_dir(&junction_path) {
log_note(
&format!(
"junction: failed to remove existing {}: {err}",
junction_path.display()
),
log_dir,
);
return None;
}
}
let link = junction_path.to_string_lossy().to_string();
let target = requested_cwd.to_string_lossy().to_string();
// Use `cmd /c` so we can call `mklink` (a cmd builtin). We must quote paths so CWDs
// containing spaces work reliably.
//
// IMPORTANT: `std::process::Command::args()` will apply Windows quoting/escaping rules when
// constructing the command line. Passing a single argument that itself contains quotes can
// confuse `cmd.exe` and cause mklink to fail with "syntax is incorrect". We avoid that by
// using `raw_arg` to pass the tokens exactly as `cmd.exe` expects to parse them.
//
// Paths cannot contain quotes on Windows, so no extra escaping is needed here.
let link_quoted = format!("\"{link}\"");
let target_quoted = format!("\"{target}\"");
log_note(
&format!("junction: creating via cmd /c mklink /J {link_quoted} {target_quoted}"),
log_dir,
);
let output = match akode_utils_process::background_command("cmd")
.raw_arg("/c")
.raw_arg("mklink")
.raw_arg("/J")
.raw_arg(&link_quoted)
.raw_arg(&target_quoted)
.output()
{
Ok(output) => output,
Err(err) => {
log_note(&format!("junction: mklink failed to run: {err}"), log_dir);
return None;
}
};
if output.status.success() && junction_path.exists() {
log_note(
&format!(
"junction: created {} -> {}",
junction_path.display(),
requested_cwd.display()
),
log_dir,
);
return Some(junction_path);
}
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
log_note(
&format!(
"junction: mklink failed status={:?} stdout={} stderr={}",
output.status,
stdout.trim(),
stderr.trim()
),
log_dir,
);
None
}

View File

@@ -0,0 +1,86 @@
use std::os::windows::io::AsRawHandle;
use std::os::windows::io::FromRawHandle;
use std::os::windows::io::OwnedHandle;
use std::process::Stdio;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
use anyhow::Context;
use akode_utils_pty::JobObject;
use tokio::io::AsyncBufReadExt;
use tokio::io::BufReader;
use tokio::process::Command;
use windows_sys::Win32::Foundation::WAIT_OBJECT_0;
use windows_sys::Win32::System::Threading::OpenProcess;
use windows_sys::Win32::System::Threading::PROCESS_SYNCHRONIZE;
use windows_sys::Win32::System::Threading::WaitForSingleObject;
use super::NonOwningProcessHandle;
use super::spawn_input_loop;
#[tokio::test]
async fn disconnected_control_pipe_terminates_elevated_helper_and_descendants() -> anyhow::Result<()>
{
let mut command = Command::new("python");
command
.args([
"-u",
"-c",
"import subprocess,sys; child=subprocess.Popen([sys.executable,'-c','import time; time.sleep(60)']); print(child.pid,flush=True); child.wait()",
])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null());
let job = Arc::new(JobObject::create_without_breakaway()?);
let mut helper = job.spawn_contained(&mut command)?;
let stdout = helper.stdout.take().context("helper stdout")?;
let mut stdout = BufReader::new(stdout);
let mut descendant_pid = String::new();
tokio::time::timeout(
Duration::from_secs(/*secs*/ 10),
stdout.read_line(&mut descendant_pid),
)
.await??;
let descendant_pid = descendant_pid.trim().parse()?;
let descendant = unsafe {
OpenProcess(
PROCESS_SYNCHRONIZE,
/*bInheritHandle*/ 0,
descendant_pid,
)
};
anyhow::ensure!(!descendant.is_null(), "failed to open sandbox descendant");
let descendant = unsafe { OwnedHandle::from_raw_handle(descendant as _) };
let process = helper.raw_handle().context("helper process handle")?;
let input_loop = spawn_input_loop(
tempfile::tempfile()?,
/*stdin_handle*/ None,
Arc::new(Mutex::new(None)),
Arc::clone(&job),
NonOwningProcessHandle(process),
/*log_dir*/ None,
);
input_loop
.join()
.expect("elevated runner input loop should stop after pipe disconnect");
let status = tokio::time::timeout(Duration::from_secs(/*secs*/ 2), helper.wait())
.await
.context("elevated helper survived control-pipe disconnect")??;
anyhow::ensure!(!status.success(), "elevated helper unexpectedly succeeded");
let descendant_status = unsafe {
WaitForSingleObject(
descendant.as_raw_handle() as _,
/*dwMilliseconds*/ 2_000,
)
};
anyhow::ensure!(
descendant_status == WAIT_OBJECT_0,
"elevated descendant survived control-pipe disconnect"
);
Ok(())
}

View File

@@ -0,0 +1,13 @@
// Keep the ACL probe independent of test-harness startup, which writes AKODE_HOME.
#[cfg(target_os = "windows")]
mod win;
#[cfg(target_os = "windows")]
fn main() {
win::main();
}
#[cfg(not(target_os = "windows"))]
fn main() {
panic!("akode-windows-managed-deny-probe is Windows-only");
}

View File

@@ -0,0 +1,101 @@
use std::ffi::c_void;
use std::io::Write as _;
use std::os::windows::ffi::OsStrExt;
use std::path::Path;
use std::path::PathBuf;
#[link(name = "kernel32")]
unsafe extern "system" {
#[link_name = "LoadLibraryW"]
fn load_library_w(file_name: *const u16) -> *mut c_void;
#[link_name = "FreeLibrary"]
fn free_library(module: *mut c_void) -> i32;
}
fn load_library(path: &Path) -> std::io::Result<()> {
let wide_path: Vec<u16> = path
.as_os_str()
.encode_wide()
.chain(std::iter::once(0))
.collect();
// SAFETY: `wide_path` is NUL-terminated and remains alive for the call.
let module = unsafe { load_library_w(wide_path.as_ptr()) };
if module.is_null() {
return Err(std::io::Error::last_os_error());
}
// SAFETY: `module` is a non-null handle returned by `LoadLibraryW` above.
if unsafe { free_library(module) } == 0 {
return Err(std::io::Error::last_os_error());
}
Ok(())
}
fn access_was_denied(err: &std::io::Error) -> bool {
err.kind() == std::io::ErrorKind::PermissionDenied || err.raw_os_error() == Some(5)
}
fn probe_path(key: &str) -> PathBuf {
let Some(value) = std::env::var_os(key) else {
eprintln!("managed deny probe is missing {key}");
probe_exit(/*code*/ 21);
};
PathBuf::from(value)
}
fn probe_exit(code: i32) -> ! {
let _ = std::io::stdout().flush();
let _ = std::io::stderr().flush();
std::process::exit(code);
}
pub(super) fn main() {
let allowed_text = probe_path("AKODE_WINDOWS_ALLOWED_TEXT");
let denied_text = probe_path("AKODE_WINDOWS_DENIED_TEXT");
let allowed_module = probe_path("AKODE_WINDOWS_ALLOWED_MODULE");
let denied_module = probe_path("AKODE_WINDOWS_DENIED_MODULE");
match std::fs::read_to_string(&allowed_text) {
Ok(contents) if contents.trim() == "ALLOW-CONTROL" => println!("allowed-read:OK"),
Ok(_) => {
eprintln!("allowed read returned unexpected contents");
probe_exit(/*code*/ 21);
}
Err(err) => {
eprintln!("allowed read failed: {err}");
probe_exit(/*code*/ 21);
}
}
if let Err(err) = load_library(&allowed_module) {
eprintln!("allowed import failed: {err}");
probe_exit(/*code*/ 21);
}
println!("allowed-import:OK");
let mut failures = 0;
match std::fs::read(&denied_text) {
Ok(_) => {
println!("denied-read:UNEXPECTED_SUCCESS");
failures += 1;
}
Err(err) if access_was_denied(&err) => println!("denied-read:DENIED"),
Err(err) => {
eprintln!("denied read failed for a non-access reason: {err}");
probe_exit(/*code*/ 21);
}
}
match load_library(&denied_module) {
Ok(()) => {
println!("denied-import:UNEXPECTED_SUCCESS");
failures += 1;
}
Err(err) if access_was_denied(&err) => println!("denied-import:DENIED"),
Err(err) => {
eprintln!("denied import failed for a non-access reason: {err}");
probe_exit(/*code*/ 21);
}
}
if failures != 0 {
probe_exit(/*code*/ 20);
}
}

View File

@@ -0,0 +1,9 @@
#[cfg(target_os = "windows")]
fn main() -> anyhow::Result<()> {
akode_windows_sandbox::setup_helper_main()
}
#[cfg(not(target_os = "windows"))]
fn main() {
panic!("akode-windows-sandbox-setup is Windows-only");
}

View File

@@ -0,0 +1,203 @@
use crate::path_normalization::canonical_path_key;
use crate::path_normalization::canonicalize_path;
use anyhow::Context;
use anyhow::Result;
use rand::RngCore;
use rand::SeedableRng;
use rand::rngs::SmallRng;
use serde::Deserialize;
use serde::Serialize;
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use std::path::PathBuf;
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct CapSids {
pub workspace: String,
pub readonly: String,
/// Per-workspace capability SIDs keyed by canonicalized CWD string.
///
/// This is used to isolate workspaces from other workspace sandbox writes and to
/// apply per-workspace denies (e.g. protect `CWD/.akode`)
/// without permanently affecting other workspaces.
#[serde(default)]
pub workspace_by_cwd: HashMap<String, String>,
/// Per-write-root capability SIDs keyed by canonicalized write-root path.
///
/// These are included in a workspace-write token only when the root is
/// currently allowed, so stale ACLs from earlier extra roots do not expand
/// later workspace sandboxes.
#[serde(default)]
pub writable_root_by_path: HashMap<String, String>,
}
pub fn cap_sid_file(codex_home: &Path) -> PathBuf {
codex_home.join("cap_sid")
}
fn make_random_cap_sid_string() -> String {
let mut rng = SmallRng::from_entropy();
let a = rng.next_u32();
let b = rng.next_u32();
let c = rng.next_u32();
let d = rng.next_u32();
format!("S-1-5-21-{a}-{b}-{c}-{d}")
}
fn persist_caps(path: &Path, caps: &CapSids) -> Result<()> {
if let Some(dir) = path.parent() {
fs::create_dir_all(dir).with_context(|| format!("create cap sid dir {}", dir.display()))?;
}
let json = serde_json::to_string(caps)?;
fs::write(path, json).with_context(|| format!("write cap sid file {}", path.display()))?;
Ok(())
}
pub fn load_or_create_cap_sids(codex_home: &Path) -> Result<CapSids> {
let path = cap_sid_file(codex_home);
if path.exists() {
let txt = fs::read_to_string(&path)
.with_context(|| format!("read cap sid file {}", path.display()))?;
let t = txt.trim();
if t.starts_with('{') && t.ends_with('}') {
if let Ok(obj) = serde_json::from_str::<CapSids>(t) {
return Ok(obj);
}
} else if !t.is_empty() {
let caps = CapSids {
workspace: t.to_string(),
readonly: make_random_cap_sid_string(),
workspace_by_cwd: HashMap::new(),
writable_root_by_path: HashMap::new(),
};
persist_caps(&path, &caps)?;
return Ok(caps);
}
}
let caps = CapSids {
workspace: make_random_cap_sid_string(),
readonly: make_random_cap_sid_string(),
workspace_by_cwd: HashMap::new(),
writable_root_by_path: HashMap::new(),
};
persist_caps(&path, &caps)?;
Ok(caps)
}
/// Returns the workspace-specific capability SID for `cwd`, creating and persisting it if missing.
pub fn workspace_cap_sid_for_cwd(codex_home: &Path, cwd: &Path) -> Result<String> {
let path = cap_sid_file(codex_home);
let mut caps = load_or_create_cap_sids(codex_home)?;
let key = canonical_path_key(cwd);
if let Some(sid) = caps.workspace_by_cwd.get(&key) {
return Ok(sid.clone());
}
let sid = make_random_cap_sid_string();
caps.workspace_by_cwd.insert(key, sid.clone());
persist_caps(&path, &caps)?;
Ok(sid)
}
/// Returns the capability SID for an additional writable root, creating and persisting it if missing.
pub fn writable_root_cap_sid_for_path(codex_home: &Path, root: &Path) -> Result<String> {
let path = cap_sid_file(codex_home);
let mut caps = load_or_create_cap_sids(codex_home)?;
let key = canonical_path_key(root);
if let Some(sid) = caps.writable_root_by_path.get(&key) {
return Ok(sid.clone());
}
let sid = make_random_cap_sid_string();
caps.writable_root_by_path.insert(key, sid.clone());
persist_caps(&path, &caps)?;
Ok(sid)
}
pub fn workspace_write_cap_sid_for_root(
codex_home: &Path,
cwd: &Path,
root: &Path,
) -> Result<String> {
if canonical_path_key(root) == canonical_path_key(cwd) {
workspace_cap_sid_for_cwd(codex_home, cwd)
} else {
writable_root_cap_sid_for_path(codex_home, root)
}
}
pub fn workspace_write_root_contains_path(root: &Path, path: &Path) -> bool {
canonicalize_path(path).starts_with(canonicalize_path(root))
}
pub fn workspace_write_root_overlaps_path(root: &Path, path: &Path) -> bool {
workspace_write_root_contains_path(root, path) || workspace_write_root_contains_path(path, root)
}
pub fn workspace_write_root_specificity(root: &Path) -> usize {
canonicalize_path(root).components().count()
}
#[cfg(test)]
mod tests {
use super::load_or_create_cap_sids;
use super::workspace_cap_sid_for_cwd;
use super::workspace_write_cap_sid_for_root;
use super::writable_root_cap_sid_for_path;
use pretty_assertions::assert_eq;
use std::path::PathBuf;
#[test]
fn equivalent_cwd_spellings_share_workspace_sid_key() {
let temp = tempfile::tempdir().expect("tempdir");
let codex_home = temp.path().join("akode-home");
std::fs::create_dir_all(&codex_home).expect("create codex home");
let workspace = temp.path().join("WorkspaceRoot");
std::fs::create_dir_all(&workspace).expect("create workspace root");
let canonical = dunce::canonicalize(&workspace).expect("canonical workspace root");
let alt_spelling = PathBuf::from(
canonical
.to_string_lossy()
.replace('\\', "/")
.to_ascii_uppercase(),
);
let first_sid =
workspace_cap_sid_for_cwd(&codex_home, canonical.as_path()).expect("first sid");
let second_sid =
workspace_cap_sid_for_cwd(&codex_home, alt_spelling.as_path()).expect("second sid");
assert_eq!(first_sid, second_sid);
let caps = load_or_create_cap_sids(&codex_home).expect("load caps");
assert_eq!(caps.workspace_by_cwd.len(), 1);
}
#[test]
fn write_roots_get_path_scoped_sids() {
let temp = tempfile::tempdir().expect("tempdir");
let codex_home = temp.path().join("akode-home");
std::fs::create_dir_all(&codex_home).expect("create codex home");
let workspace = temp.path().join("workspace");
let extra_root = temp.path().join("extra-root");
std::fs::create_dir_all(&workspace).expect("create workspace");
std::fs::create_dir_all(&extra_root).expect("create extra root");
let workspace_sid = workspace_write_cap_sid_for_root(&codex_home, &workspace, &workspace)
.expect("workspace sid");
let extra_sid = workspace_write_cap_sid_for_root(&codex_home, &workspace, &extra_root)
.expect("extra root sid");
assert_ne!(workspace_sid, extra_sid);
assert_eq!(
extra_sid,
writable_root_cap_sid_for_path(&codex_home, &extra_root).expect("extra root sid again")
);
let caps = load_or_create_cap_sids(&codex_home).expect("load caps");
assert_eq!(caps.workspace_by_cwd.len(), 1);
assert_eq!(caps.writable_root_by_path.len(), 1);
}
}

View File

@@ -0,0 +1,182 @@
//! ConPTY helpers for spawning sandboxed processes with a PTY on Windows.
//!
//! This module encapsulates ConPTY creation and process spawn with the required
//! `PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE` plumbing. It is shared by both the legacy
//! restricted‑token path and the elevated runner path when unified_exec runs with
//! `tty=true`. The helpers are not tied to the IPC layer and can be reused by other
//! Windows sandbox flows that need a PTY.
use crate::desktop::LaunchDesktop;
use crate::proc_thread_attr::ProcThreadAttributeList;
use crate::winutil::format_last_error;
use crate::winutil::quote_windows_arg;
use crate::winutil::to_wide;
use anyhow::Context;
use anyhow::Result;
use akode_utils_pty::JobObject;
use akode_utils_pty::PsuedoCon;
use akode_utils_pty::RawConPty;
use std::collections::HashMap;
use std::ffi::c_void;
use std::os::windows::io::AsRawHandle;
use std::os::windows::io::BorrowedHandle;
use std::os::windows::io::FromRawHandle;
use std::os::windows::io::IntoRawHandle;
use std::os::windows::io::OwnedHandle;
use std::path::Path;
use std::sync::Arc;
use windows_sys::Win32::Foundation::GetLastError;
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
use windows_sys::Win32::System::Console::HPCON;
use windows_sys::Win32::System::Threading::CREATE_UNICODE_ENVIRONMENT;
use windows_sys::Win32::System::Threading::CreateProcessAsUserW;
use windows_sys::Win32::System::Threading::EXTENDED_STARTUPINFO_PRESENT;
use windows_sys::Win32::System::Threading::PROCESS_INFORMATION;
use windows_sys::Win32::System::Threading::STARTF_USESTDHANDLES;
use windows_sys::Win32::System::Threading::STARTUPINFOEXW;
use crate::process::make_env_block;
/// Owns a ConPTY handle and its backing pipe handles.
pub struct ConptyInstance {
pseudoconsole: Option<PsuedoCon>,
input_write: Option<OwnedHandle>,
output_read: Option<OwnedHandle>,
job: Option<Arc<JobObject>>,
_desktop: Option<LaunchDesktop>,
}
impl Drop for ConptyInstance {
fn drop(&mut self) {
drop(self.input_write.take());
drop(self.output_read.take());
drop(self.pseudoconsole.take());
}
}
impl ConptyInstance {
pub fn raw_handle(&self) -> Option<HPCON> {
self.pseudoconsole
.as_ref()
.map(|pseudoconsole| pseudoconsole.raw_handle() as HPCON)
}
pub fn take_input_write(&mut self) -> HANDLE {
self.input_write
.take()
.map_or(std::ptr::null_mut(), IntoRawHandle::into_raw_handle)
}
pub fn take_output_read(&mut self) -> HANDLE {
self.output_read
.take()
.map_or(std::ptr::null_mut(), IntoRawHandle::into_raw_handle)
}
/// Returns the Job Object containing the spawned process, if this instance owns one.
pub fn job(&self) -> Option<Arc<JobObject>> {
self.job.as_ref().map(Arc::clone)
}
}
/// Create a ConPTY with backing pipes.
///
/// This is public so callers that need lower-level PTY setup can build on the same
/// primitive, although the common entry point is `spawn_conpty_process_as_user`.
#[allow(dead_code)]
pub fn create_conpty(cols: i16, rows: i16) -> Result<ConptyInstance> {
let raw = RawConPty::new(cols, rows)?;
let (pseudoconsole, input_write, output_read) = raw.into_handles();
// SAFETY: into_raw_handle transfers each pipe to its new owner.
let input_write = unsafe { OwnedHandle::from_raw_handle(input_write.into_raw_handle()) };
let output_read = unsafe { OwnedHandle::from_raw_handle(output_read.into_raw_handle()) };
Ok(ConptyInstance {
pseudoconsole: Some(pseudoconsole),
input_write: Some(input_write),
output_read: Some(output_read),
job: None,
_desktop: None,
})
}
/// Spawn a process under `h_token` with ConPTY attached.
///
/// This is the main shared ConPTY entry point and is used by both the legacy/direct path
/// and the elevated runner path whenever a PTY-backed sandboxed process is needed.
pub fn spawn_conpty_process_as_user(
h_token: BorrowedHandle<'_>,
argv: &[String],
cwd: &Path,
env_map: &HashMap<String, String>,
desktop: LaunchDesktop,
) -> Result<(PROCESS_INFORMATION, ConptyInstance)> {
let cmdline_str = argv
.iter()
.map(|arg| quote_windows_arg(arg))
.collect::<Vec<_>>()
.join(" ");
let mut cmdline: Vec<u16> = to_wide(&cmdline_str);
let env_block = make_env_block(env_map);
let mut si: STARTUPINFOEXW = unsafe { std::mem::zeroed() };
si.StartupInfo.cb = std::mem::size_of::<STARTUPINFOEXW>() as u32;
si.StartupInfo.dwFlags = STARTF_USESTDHANDLES;
si.StartupInfo.hStdInput = INVALID_HANDLE_VALUE;
si.StartupInfo.hStdOutput = INVALID_HANDLE_VALUE;
si.StartupInfo.hStdError = INVALID_HANDLE_VALUE;
si.StartupInfo.lpDesktop = desktop.startup_info_desktop();
let job = Arc::new(JobObject::create().context("create process job")?);
let raw = RawConPty::new(/*cols*/ 80, /*rows*/ 24)?;
let (pseudoconsole, input_write, output_read) = raw.into_handles();
let hpc = pseudoconsole.raw_handle() as HPCON;
// SAFETY: into_raw_handle transfers each pipe to its new owner.
let input_write = unsafe { OwnedHandle::from_raw_handle(input_write.into_raw_handle()) };
let output_read = unsafe { OwnedHandle::from_raw_handle(output_read.into_raw_handle()) };
let conpty = ConptyInstance {
pseudoconsole: Some(pseudoconsole),
input_write: Some(input_write),
output_read: Some(output_read),
job: Some(Arc::clone(&job)),
_desktop: Some(desktop),
};
let preserve_app_context = crate::app_package::current_process_has_package_identity()?;
let mut attrs = ProcThreadAttributeList::new(2 + u32::from(preserve_app_context))?;
attrs.set_pseudoconsole(hpc)?;
attrs.set_job(job.as_raw_handle() as HANDLE)?;
if preserve_app_context {
attrs.preserve_desktop_app_context()?;
}
si.lpAttributeList = attrs.as_mut_ptr();
let mut pi: PROCESS_INFORMATION = unsafe { std::mem::zeroed() };
let ok = unsafe {
CreateProcessAsUserW(
h_token.as_raw_handle(),
std::ptr::null(),
cmdline.as_mut_ptr(),
std::ptr::null_mut(),
std::ptr::null_mut(),
0,
EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT,
env_block.as_ptr() as *mut c_void,
to_wide(cwd).as_ptr(),
&si.StartupInfo,
&mut pi,
)
};
if ok == 0 {
let err = unsafe { GetLastError() } as i32;
let message = format!(
"CreateProcessAsUserW failed: {} ({}) | cwd={} | cmd={} | env_u16_len={}",
err,
format_last_error(err),
cwd.display(),
cmdline_str,
env_block.len()
);
return Err(std::io::Error::from_raw_os_error(err)).context(message);
}
Ok((pi, conpty))
}

View File

@@ -0,0 +1,152 @@
use crate::acl::add_deny_read_ace;
use crate::acl::revoke_ace;
use anyhow::Context;
use anyhow::Result;
use std::collections::HashSet;
use std::ffi::c_void;
use std::path::Path;
use std::path::PathBuf;
/// Build the exact ACL paths that should receive a deny-read ACE.
///
/// We keep both the lexical policy path and, when it already exists, the
/// canonical target. The lexical path covers the path users configured and lets
/// missing exact denies be materialized later; the canonical path also covers
/// an existing reparse-point target so a sandbox cannot read the same object
/// through the resolved location. Filesystem roots are rejected after this
/// canonicalization so aliases cannot install a root deny ACE.
pub fn plan_deny_read_acl_paths(paths: &[PathBuf]) -> Result<Vec<PathBuf>> {
let mut planned = Vec::new();
let mut seen = HashSet::new();
for path in paths {
push_planned_path(&mut planned, &mut seen, path.to_path_buf());
let canonical = match dunce::canonicalize(path) {
Ok(canonical) => canonical,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => continue,
Err(err) => {
return Err(err)
.with_context(|| format!("canonicalize deny-read path {}", path.display()));
}
};
push_planned_path(&mut planned, &mut seen, canonical);
}
if let Some(root) = planned
.iter()
.find(|path| path.is_absolute() && path.parent().is_none())
{
anyhow::bail!(
"refusing to apply a deny-read ACE to filesystem root {}",
root.display()
);
}
Ok(planned)
}
fn push_planned_path(planned: &mut Vec<PathBuf>, seen: &mut HashSet<String>, path: PathBuf) {
if seen.insert(lexical_path_key(&path)) {
planned.push(path);
}
}
pub(crate) fn lexical_path_key(path: &Path) -> String {
path.to_string_lossy()
.replace('\\', "/")
.trim_end_matches('/')
.to_ascii_lowercase()
}
/// Applies deny-read ACEs to explicit paths. Missing paths are materialized as
/// directories before the ACE is applied so a sandboxed command cannot create a
/// previously absent denied path and then read from it in the same run.
/// If any path fails, deny ACEs applied by this call are revoked before the
/// error is returned so a one-shot sandbox run does not leave partial state.
///
/// # Safety
/// Caller must pass a valid SID pointer for the sandbox principal being denied.
pub unsafe fn apply_deny_read_acls(paths: &[PathBuf], psid: *mut c_void) -> Result<Vec<PathBuf>> {
let planned = plan_deny_read_acl_paths(paths)?;
let mut applied = Vec::new();
let mut seen = HashSet::new();
let mut added_in_this_call: Vec<PathBuf> = Vec::new();
for path in planned {
let result = (|| -> Result<bool> {
if !path.exists() {
std::fs::create_dir_all(&path)
.with_context(|| format!("create deny-read path {}", path.display()))?;
}
add_deny_read_ace(&path, psid)
.with_context(|| format!("apply deny-read ACE to {}", path.display()))
})();
let added = match result {
Ok(added) => added,
Err(err) => {
for added_path in &added_in_this_call {
let _ = revoke_ace(added_path, psid);
}
return Err(err);
}
};
if added {
added_in_this_call.push(path.clone());
}
push_planned_path(&mut applied, &mut seen, path);
}
Ok(applied)
}
#[cfg(test)]
mod tests {
use super::plan_deny_read_acl_paths;
use pretty_assertions::assert_eq;
use std::collections::HashSet;
use std::path::PathBuf;
use tempfile::TempDir;
#[test]
fn plan_preserves_missing_paths() {
let tmp = TempDir::new().expect("tempdir");
let missing = tmp.path().join("future-secret.env");
assert_eq!(
plan_deny_read_acl_paths(std::slice::from_ref(&missing)).expect("plan deny-read ACL"),
vec![missing]
);
}
#[test]
fn plan_includes_existing_canonical_targets() {
let tmp = TempDir::new().expect("tempdir");
let existing = tmp.path().join("secret.env");
std::fs::write(&existing, "secret").expect("write secret");
let planned: HashSet<PathBuf> = plan_deny_read_acl_paths(std::slice::from_ref(&existing))
.expect("plan deny-read ACL")
.into_iter()
.collect();
let expected: HashSet<PathBuf> = [
existing.clone(),
dunce::canonicalize(&existing).expect("canonical path"),
]
.into_iter()
.collect();
assert_eq!(planned, expected);
}
#[test]
fn plan_rejects_file_system_root() {
let cwd = std::env::current_dir().expect("current directory");
let root = cwd.ancestors().last().expect("filesystem root");
let err = plan_deny_read_acl_paths(&[root.to_path_buf()])
.expect_err("filesystem root must not receive a deny-read ACE");
assert_eq!(
err.to_string(),
format!(
"refusing to apply a deny-read ACE to filesystem root {}",
root.display()
)
);
}
}

View File

@@ -0,0 +1,700 @@
use akode_protocol::permissions::FileSystemAccessMode;
use akode_protocol::permissions::FileSystemPath;
use akode_protocol::permissions::FileSystemSandboxEntry;
use akode_protocol::permissions::FileSystemSandboxPolicy;
use akode_protocol::permissions::ReadDenyMatcher;
use akode_protocol::permissions::ResolvedFileSystemPermissions;
use akode_protocol::permissions::windows_deny_read_glob_scan;
use akode_utils_absolute_path::AbsolutePathBuf;
use ignore::overrides::OverrideBuilder;
use std::collections::HashSet;
use std::path::Path;
use std::path::PathBuf;
#[derive(Debug, Eq, PartialEq)]
struct GlobScanPlan {
root: PathBuf,
max_depth: Option<usize>,
globs: Vec<String>,
}
/// Resolve split filesystem `None` read entries into concrete Windows ACL targets.
///
/// Windows ACLs do not understand Codex filesystem glob patterns directly. Exact
/// unreadable roots can be passed through as-is, including paths that do not
/// exist yet. Glob entries are snapshot-expanded to the files/directories that
/// already exist under their literal scan root. Directory links below that root
/// are not traversed; explicitly linked scan roots are followed. Future exact
/// paths are materialized later before the deny ACE is applied.
pub fn resolve_windows_deny_read_paths(
file_system_sandbox_policy: &FileSystemSandboxPolicy,
cwd: &AbsolutePathBuf,
) -> Result<Vec<AbsolutePathBuf>, String> {
expand_deny_read_paths(
&file_system_sandbox_policy.get_unreadable_roots_with_cwd(cwd),
&file_system_sandbox_policy.get_unreadable_globs_with_cwd(cwd),
file_system_sandbox_policy.glob_scan_max_depth,
cwd,
)
}
/// Expand the denies from an already resolved filesystem policy into Windows ACL targets.
pub fn expand_windows_deny_read_paths(
permissions: &ResolvedFileSystemPermissions,
cwd: &AbsolutePathBuf,
) -> Result<Vec<AbsolutePathBuf>, String> {
expand_deny_read_paths(
&permissions.unreadable_roots,
&permissions.unreadable_globs,
permissions.glob_scan_max_depth,
cwd,
)
}
fn expand_deny_read_paths(
unreadable_roots: &[AbsolutePathBuf],
unreadable_globs: &[String],
glob_scan_max_depth: Option<usize>,
cwd: &AbsolutePathBuf,
) -> Result<Vec<AbsolutePathBuf>, String> {
let mut paths = Vec::new();
let mut seen = HashSet::new();
for path in unreadable_roots {
push_absolute_path(&mut paths, &mut seen, path.as_path())?;
}
if unreadable_globs.is_empty() {
return Ok(paths);
}
let glob_policy = FileSystemSandboxPolicy::restricted(
unreadable_globs
.iter()
.map(|pattern| FileSystemSandboxEntry {
path: FileSystemPath::GlobPattern {
pattern: pattern.clone(),
},
access: FileSystemAccessMode::Deny,
missing_path_behavior: None,
})
.collect(),
);
let Some(matcher) = ReadDenyMatcher::try_new_for_local_paths(&glob_policy, cwd.as_path())?
else {
return Ok(paths);
};
let scan_plans = glob_scan_plans(unreadable_globs, glob_scan_max_depth)?;
for scan_plan in scan_plans {
if !scan_plan.root.exists() {
continue;
}
// Snapshot matching entries without following directory links below the scan root.
let mut filter = OverrideBuilder::new(&scan_plan.root);
filter.allow_unclosed_class(/*yes*/ true);
filter
.case_insensitive(/*yes*/ true)
.map_err(|err| err.to_string())?;
for glob in &scan_plan.globs {
filter.add(glob).map_err(|err| err.to_string())?;
}
let filter = filter.build().map_err(|err| err.to_string())?;
for entry in ignore::WalkBuilder::new(&scan_plan.root)
.standard_filters(/*yes*/ false)
.follow_links(/*yes*/ false)
.max_depth(scan_plan.max_depth)
.overrides(filter)
.build()
{
let entry = entry.and_then(|entry| {
if entry.path_is_symlink() && matcher.is_local_path_read_denied(entry.path()) {
std::fs::metadata(entry.path()).map_err(ignore::Error::Io)?;
}
Ok(entry)
});
let entry = match entry {
Ok(entry) => entry,
Err(err)
if err.io_error().is_some_and(|err| {
matches!(
err.kind(),
std::io::ErrorKind::NotFound | std::io::ErrorKind::PermissionDenied
)
}) =>
{
continue;
}
Err(err) => {
return Err(format!(
"failed to enumerate unreadable glob paths under {}: {err}",
scan_plan.root.display()
));
}
};
if matcher.is_local_path_read_denied(entry.path()) {
push_absolute_path(&mut paths, &mut seen, entry.into_path())?;
}
}
}
Ok(paths)
}
fn push_absolute_path(
paths: &mut Vec<AbsolutePathBuf>,
seen: &mut HashSet<PathBuf>,
path: impl AsRef<Path>,
) -> Result<(), String> {
let absolute_path = AbsolutePathBuf::from_absolute_path(dunce::simplified(path.as_ref()))
.map_err(|err| err.to_string())?;
if seen.insert(absolute_path.to_path_buf()) {
paths.push(absolute_path);
}
Ok(())
}
fn glob_scan_plans(
patterns: &[String],
configured_max_depth: Option<usize>,
) -> Result<Vec<GlobScanPlan>, String> {
let mut scan_plans: Vec<GlobScanPlan> = Vec::new();
for pattern in patterns {
let mut scan_plan = glob_scan_plan(pattern, configured_max_depth);
if scan_plan.max_depth.is_none() && scan_plan.root.parent().is_none() {
return Err(format!(
"unreadable glob `{pattern}` cannot be safely expanded from a filesystem root without `glob_scan_max_depth`; configure `glob_scan_max_depth` or use a non-root directory prefix"
));
}
if let Some(existing) = scan_plans
.iter_mut()
.find(|existing| existing.root == scan_plan.root)
{
existing.max_depth = match (existing.max_depth, scan_plan.max_depth) {
(Some(existing_depth), Some(new_depth)) => Some(existing_depth.max(new_depth)),
_ => None,
};
existing.globs.append(&mut scan_plan.globs);
} else {
scan_plans.push(scan_plan);
}
}
Ok(scan_plans)
}
fn glob_scan_plan(pattern: &str, configured_max_depth: Option<usize>) -> GlobScanPlan {
let scan = windows_deny_read_glob_scan(pattern, configured_max_depth);
GlobScanPlan {
root: PathBuf::from(scan.root),
max_depth: scan.max_depth,
globs: vec![file_filter_glob(scan.pattern_suffix)],
}
}
fn file_filter_glob(pattern: &str) -> String {
let pattern = pattern.replace('\\', "/");
if pattern.starts_with("**/") {
pattern
} else {
format!("**/{pattern}")
}
}
#[cfg(test)]
#[path = "deny_read_resolver_access_tests.rs"]
mod access_tests;
#[cfg(test)]
mod tests {
use super::GlobScanPlan;
use super::file_filter_glob;
use super::glob_scan_plan;
use super::glob_scan_plans;
use super::resolve_windows_deny_read_paths;
use akode_protocol::permissions::FileSystemAccessMode;
use akode_protocol::permissions::FileSystemPath;
use akode_protocol::permissions::FileSystemSandboxEntry;
use akode_protocol::permissions::FileSystemSandboxPolicy;
use akode_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use std::collections::HashSet;
use std::path::PathBuf;
use tempfile::TempDir;
#[cfg(unix)]
use std::os::unix::fs::symlink;
fn unreadable_glob_entry(pattern: String) -> FileSystemSandboxEntry {
FileSystemSandboxEntry {
path: FileSystemPath::GlobPattern { pattern },
access: FileSystemAccessMode::Deny,
missing_path_behavior: None,
}
}
fn unreadable_path_entry(path: PathBuf) -> FileSystemSandboxEntry {
FileSystemSandboxEntry {
path: FileSystemPath::Path {
path: AbsolutePathBuf::from_absolute_path(path)
.expect("absolute path")
.into(),
},
access: FileSystemAccessMode::Deny,
missing_path_behavior: None,
}
}
#[test]
fn scan_root_uses_literal_prefix_before_glob() {
assert_eq!(
glob_scan_plan("/tmp/work/**/*.env", /*configured_max_depth*/ None).root,
PathBuf::from("/tmp/work")
);
assert_eq!(
glob_scan_plan(
r"C:\Users\dev\repo\**\*.env",
/*configured_max_depth*/ None,
)
.root,
PathBuf::from(r"C:\Users\dev\repo")
);
assert_eq!(
glob_scan_plan(r"C:\*.env", /*configured_max_depth*/ None).root,
PathBuf::from(r"C:\")
);
}
#[test]
fn scan_depth_is_bounded_for_non_recursive_globs() {
assert_eq!(
glob_scan_plan("/tmp/work/*.env", /*configured_max_depth*/ None).max_depth,
Some(1)
);
assert_eq!(
glob_scan_plan("/tmp/work/*/*.env", /*configured_max_depth*/ None).max_depth,
Some(2)
);
assert_eq!(
glob_scan_plan("/tmp/work/**/*.env", /*configured_max_depth*/ None).max_depth,
None
);
}
#[test]
fn configured_depth_caps_recursive_glob_scans() {
assert_eq!(
glob_scan_plan("/tmp/work/**/*.env", Some(2)).max_depth,
Some(2)
);
assert_eq!(
glob_scan_plan("/tmp/work/*/*.env", Some(1)).max_depth,
Some(1)
);
}
#[test]
fn glob_patterns_with_the_same_root_and_depth_share_one_scan() {
assert_eq!(
glob_scan_plans(
&[
"/tmp/work/**/*.env".to_string(),
"/tmp/work/**/*.pem".to_string(),
"/tmp/work/**/*.secret".to_string(),
],
/*configured_max_depth*/ Some(3),
)
.expect("combined scan plans"),
vec![GlobScanPlan {
root: PathBuf::from("/tmp/work"),
max_depth: Some(3),
globs: vec![
"**/*.env".to_string(),
"**/*.pem".to_string(),
"**/*.secret".to_string(),
],
}]
);
}
#[test]
fn bounded_globs_with_the_same_root_share_the_deepest_scan() {
assert_eq!(
glob_scan_plans(
&[
"/tmp/work/*.env".to_string(),
"/tmp/work/*/*.pem".to_string(),
],
/*configured_max_depth*/ None,
)
.expect("combined scan plans"),
vec![GlobScanPlan {
root: PathBuf::from("/tmp/work"),
max_depth: Some(2),
globs: vec!["**/*.env".to_string(), "**/*/*.pem".to_string()],
}]
);
}
#[test]
fn recursive_and_bounded_globs_with_the_same_root_share_one_scan() {
assert_eq!(
glob_scan_plans(
&[
"/tmp/work/*.env".to_string(),
"/tmp/work/**/*.pem".to_string(),
],
/*configured_max_depth*/ None,
)
.expect("combined scan plans"),
vec![GlobScanPlan {
root: PathBuf::from("/tmp/work"),
max_depth: None,
globs: vec!["**/*.env".to_string(), "**/*.pem".to_string()],
}]
);
}
#[test]
fn project_recursive_globs_without_depth_expand_existing_matches() {
let tmp = TempDir::new().expect("tempdir");
let cwd = AbsolutePathBuf::from_absolute_path(tmp.path()).expect("absolute cwd");
let secret = tmp.path().join("nested").join("secret.env");
std::fs::create_dir_all(secret.parent().expect("secret parent")).expect("create parent");
std::fs::write(&secret, "secret").expect("write secret");
let pattern = tmp.path().join("**").join("*.env").display().to_string();
let policy = FileSystemSandboxPolicy::restricted(vec![unreadable_glob_entry(pattern)]);
assert_eq!(
resolve_windows_deny_read_paths(&policy, &cwd).expect("unbounded project glob"),
vec![AbsolutePathBuf::from_absolute_path(secret).expect("absolute secret")]
);
}
#[test]
fn relative_recursive_globs_without_depth_expand_existing_matches() {
let tmp = TempDir::new().expect("tempdir");
let cwd = AbsolutePathBuf::from_absolute_path(tmp.path()).expect("absolute cwd");
let secret = tmp.path().join("nested").join("secret.env");
std::fs::create_dir_all(secret.parent().expect("secret parent")).expect("create parent");
std::fs::write(&secret, "secret").expect("write secret");
let policy = FileSystemSandboxPolicy::restricted(vec![unreadable_glob_entry(
"**/*.env".to_string(),
)]);
assert_eq!(
resolve_windows_deny_read_paths(&policy, &cwd)
.expect("unbounded relative project glob"),
vec![AbsolutePathBuf::from_absolute_path(secret).expect("absolute secret")]
);
}
#[test]
fn root_recursive_globs_without_depth_fail_before_expansion() {
let tmp = TempDir::new().expect("tempdir");
let cwd = AbsolutePathBuf::from_absolute_path(tmp.path()).expect("absolute cwd");
let root = cwd.as_path().ancestors().last().expect("filesystem root");
let pattern = root.join("**").join("*.env").display().to_string();
let policy =
FileSystemSandboxPolicy::restricted(vec![unreadable_glob_entry(pattern.clone())]);
assert_eq!(
resolve_windows_deny_read_paths(&policy, &cwd).expect_err("unbounded root glob"),
format!(
"unreadable glob `{pattern}` cannot be safely expanded from a filesystem root without `glob_scan_max_depth`; configure `glob_scan_max_depth` or use a non-root directory prefix"
)
);
}
#[test]
fn configured_depth_bounds_root_recursive_glob_scans() {
let tmp = TempDir::new().expect("tempdir");
let cwd = AbsolutePathBuf::from_absolute_path(tmp.path()).expect("absolute cwd");
let root = cwd.as_path().ancestors().last().expect("filesystem root");
let pattern = root.join("**").join("*.env").display().to_string();
let scan_plan = glob_scan_plan(&pattern, Some(2));
assert_eq!(scan_plan.root, root);
assert_eq!(scan_plan.max_depth, Some(2));
}
#[test]
fn exact_missing_paths_are_preserved() {
let tmp = TempDir::new().expect("tempdir");
let cwd = AbsolutePathBuf::from_absolute_path(tmp.path()).expect("absolute cwd");
let missing = tmp.path().join("missing.env");
let policy = FileSystemSandboxPolicy::restricted(vec![unreadable_path_entry(missing)]);
assert_eq!(
resolve_windows_deny_read_paths(&policy, &cwd).expect("resolve"),
vec![
AbsolutePathBuf::from_absolute_path(
dunce::canonicalize(tmp.path())
.expect("canonical tempdir")
.join("missing.env")
)
.expect("absolute missing")
]
);
}
#[test]
fn glob_patterns_expand_to_existing_matches() {
let tmp = TempDir::new().expect("tempdir");
let cwd = AbsolutePathBuf::from_absolute_path(tmp.path()).expect("absolute cwd");
let root_env = tmp.path().join(".env");
let nested_env = tmp.path().join("app").join(".env");
let uppercase_env = tmp.path().join("app").join("SECRET.ENV");
let notes = tmp.path().join("app").join("notes.txt");
std::fs::create_dir_all(notes.parent().expect("parent")).expect("create parent");
std::fs::write(&root_env, "secret").expect("write root env");
std::fs::write(&nested_env, "secret").expect("write nested env");
std::fs::write(&uppercase_env, "secret").expect("write uppercase env");
std::fs::write(&notes, "notes").expect("write notes");
let policy = FileSystemSandboxPolicy::restricted(vec![unreadable_glob_entry(format!(
"{}/**/*.env",
tmp.path().display()
))]);
let actual: HashSet<PathBuf> = resolve_windows_deny_read_paths(&policy, &cwd)
.expect("resolve")
.into_iter()
.map(AbsolutePathBuf::into_path_buf)
.collect();
let mut expected = [root_env, nested_env].into_iter().collect::<HashSet<_>>();
if cfg!(windows) {
expected.insert(uppercase_env);
}
assert_eq!(actual, expected);
}
#[test]
fn recursive_globs_include_hidden_and_ignored_matches() {
let tmp = TempDir::new().expect("tempdir");
let cwd = AbsolutePathBuf::from_absolute_path(tmp.path()).expect("absolute cwd");
let hidden_secret = tmp.path().join("nested").join(".env");
let ignored_secret = tmp.path().join("nested").join("ignored.env");
std::fs::create_dir_all(hidden_secret.parent().expect("secret parent"))
.expect("create parent");
std::fs::write(tmp.path().join(".ignore"), "ignored.env\n").expect("write ignore file");
std::fs::write(&hidden_secret, "secret").expect("write hidden secret");
std::fs::write(&ignored_secret, "secret").expect("write ignored secret");
let policy = FileSystemSandboxPolicy::restricted(vec![unreadable_glob_entry(
"**/*.env".to_string(),
)]);
let actual: HashSet<PathBuf> = resolve_windows_deny_read_paths(&policy, &cwd)
.expect("resolve hidden and ignored matches")
.into_iter()
.map(AbsolutePathBuf::into_path_buf)
.collect();
assert_eq!(
actual,
[hidden_secret, ignored_secret].into_iter().collect()
);
}
#[test]
fn recursive_globs_preserve_matching_empty_directories() {
let tmp = TempDir::new().expect("tempdir");
let cwd = AbsolutePathBuf::from_absolute_path(tmp.path()).expect("absolute cwd");
let root_secret = tmp.path().join("root.env");
let nested_secret = tmp.path().join("nested").join("empty.env");
std::fs::create_dir_all(&root_secret).expect("create root secret directory");
std::fs::create_dir_all(&nested_secret).expect("create nested secret directory");
let policy = FileSystemSandboxPolicy::restricted(vec![unreadable_glob_entry(
"**/*.env".to_string(),
)]);
let actual: HashSet<PathBuf> = resolve_windows_deny_read_paths(&policy, &cwd)
.expect("resolve matching directories")
.into_iter()
.map(AbsolutePathBuf::into_path_buf)
.collect();
assert_eq!(actual, [root_secret, nested_secret].into_iter().collect());
}
#[test]
fn configured_depth_excludes_deeper_recursive_matches() {
let tmp = TempDir::new().expect("tempdir");
let cwd = AbsolutePathBuf::from_absolute_path(tmp.path()).expect("absolute cwd");
let shallow_secret = tmp.path().join("shallow.env");
let deep_secret = tmp.path().join("nested").join("deep.env");
std::fs::create_dir_all(deep_secret.parent().expect("secret parent"))
.expect("create parent");
std::fs::write(&shallow_secret, "secret").expect("write shallow secret");
std::fs::write(&deep_secret, "secret").expect("write deep secret");
let mut policy = FileSystemSandboxPolicy::restricted(vec![unreadable_glob_entry(
"**/*.env".to_string(),
)]);
policy.glob_scan_max_depth = Some(1);
assert_eq!(
resolve_windows_deny_read_paths(&policy, &cwd).expect("resolve depth-limited glob"),
vec![AbsolutePathBuf::from_absolute_path(shallow_secret).expect("absolute secret")]
);
}
#[test]
fn recursive_globs_rescan_for_new_matches() {
let tmp = TempDir::new().expect("tempdir");
let cwd = AbsolutePathBuf::from_absolute_path(tmp.path()).expect("absolute cwd");
std::fs::write(tmp.path().join("notes.txt"), "notes").expect("write notes");
let policy = FileSystemSandboxPolicy::restricted(vec![unreadable_glob_entry(
"**/*.env".to_string(),
)]);
assert_eq!(
resolve_windows_deny_read_paths(&policy, &cwd).expect("resolve unmatched glob"),
Vec::<AbsolutePathBuf>::new()
);
let secret = tmp.path().join("new.env");
std::fs::write(&secret, "new secret").expect("create matching file");
assert_eq!(
resolve_windows_deny_read_paths(&policy, &cwd).expect("fresh resolution"),
vec![AbsolutePathBuf::from_absolute_path(secret).expect("secret path")]
);
}
#[test]
fn file_filter_globs_normalize_windows_separators_and_unclosed_classes() {
assert_eq!(file_filter_glob(r"**\*.env"), "**/*.env");
assert_eq!(file_filter_glob("nested/*.env"), "**/nested/*.env");
assert_eq!(file_filter_glob("[*.env"), "**/[*.env");
let tmp = TempDir::new().expect("tempdir");
let cwd = AbsolutePathBuf::from_absolute_path(tmp.path()).expect("cwd");
for (name, pattern) in [
("[]secret.env", "**/[]*.env"),
("[[secret.env", "**/[[*.env"),
] {
let secret = cwd.join(name);
std::fs::write(&secret, "secret").expect("write literal bracket name");
let policy = FileSystemSandboxPolicy::restricted(vec![unreadable_glob_entry(
pattern.to_owned(),
)]);
assert_eq!(
resolve_windows_deny_read_paths(&policy, &cwd).expect("valid literal bracket glob"),
vec![secret],
);
}
}
#[test]
fn shared_scan_roots_preserve_matches_at_each_required_depth() {
let tmp = TempDir::new().expect("tempdir");
let cwd = AbsolutePathBuf::from_absolute_path(tmp.path()).expect("absolute cwd");
let env = tmp.path().join(".env");
let pem = tmp.path().join("nested").join("credentials.pem");
std::fs::create_dir_all(pem.parent().expect("pem parent")).expect("create pem parent");
std::fs::write(&env, "secret").expect("write env");
std::fs::write(&pem, "secret").expect("write pem");
let policy = FileSystemSandboxPolicy::restricted(vec![
unreadable_glob_entry(format!("{}/*.env", tmp.path().display())),
unreadable_glob_entry(format!("{}/*/*.pem", tmp.path().display())),
]);
let actual: HashSet<PathBuf> = resolve_windows_deny_read_paths(&policy, &cwd)
.expect("resolve shared root")
.into_iter()
.map(AbsolutePathBuf::into_path_buf)
.collect();
let expected = [env, pem].into_iter().collect();
assert_eq!(actual, expected);
}
#[test]
fn invalid_glob_patterns_fail_before_expansion() {
let tmp = TempDir::new().expect("tempdir");
let cwd = AbsolutePathBuf::from_absolute_path(tmp.path()).expect("absolute cwd");
let policy = FileSystemSandboxPolicy::restricted(vec![unreadable_glob_entry(format!(
"{}/**/[z-a]",
tmp.path().display()
))]);
let err = resolve_windows_deny_read_paths(&policy, &cwd).expect_err("invalid glob");
assert!(
err.contains("invalid deny-read glob pattern"),
"unexpected error: {err}"
);
assert!(err.contains("invalid range"), "unexpected error: {err}");
}
#[test]
fn non_recursive_globs_do_not_expand_nested_matches() {
let tmp = TempDir::new().expect("tempdir");
let cwd = AbsolutePathBuf::from_absolute_path(tmp.path()).expect("absolute cwd");
let root_env = tmp.path().join(".env");
let nested_env = tmp.path().join("app").join(".env");
std::fs::create_dir_all(nested_env.parent().expect("parent")).expect("create parent");
std::fs::write(&root_env, "secret").expect("write root env");
std::fs::write(&nested_env, "secret").expect("write nested env");
let policy = FileSystemSandboxPolicy::restricted(vec![unreadable_glob_entry(format!(
"{}/*.env",
tmp.path().display()
))]);
assert_eq!(
resolve_windows_deny_read_paths(&policy, &cwd).expect("resolve"),
vec![AbsolutePathBuf::from_absolute_path(root_env).expect("absolute root env")]
);
}
#[cfg(unix)]
#[test]
fn aliased_glob_roots_each_preserve_their_lexical_matches() {
let tmp = TempDir::new().expect("tempdir");
let cwd = AbsolutePathBuf::from_absolute_path(tmp.path()).expect("absolute cwd");
let target = tmp.path().join("target");
let alias_a = tmp.path().join("alias-a");
let alias_b = tmp.path().join("alias-b");
let secret = target.join("secret.env");
std::fs::create_dir_all(&target).expect("create target");
std::fs::write(&secret, "secret").expect("write secret");
symlink(&target, &alias_a).expect("create alias a");
symlink(&target, &alias_b).expect("create alias b");
let policy = FileSystemSandboxPolicy::restricted(vec![
unreadable_glob_entry(format!("{}/**/*.env", alias_a.display())),
unreadable_glob_entry(format!("{}/**/*.env", alias_b.display())),
]);
let actual: HashSet<PathBuf> = resolve_windows_deny_read_paths(&policy, &cwd)
.expect("resolve")
.into_iter()
.map(AbsolutePathBuf::into_path_buf)
.collect();
let expected = [alias_a.join("secret.env"), alias_b.join("secret.env")]
.into_iter()
.collect();
assert_eq!(actual, expected);
}
#[cfg(unix)]
#[test]
fn recursive_globs_preserve_symlinked_file_matches() {
let tmp = TempDir::new().expect("tempdir");
let cwd = AbsolutePathBuf::from_absolute_path(tmp.path()).expect("absolute cwd");
let target = tmp.path().join("target.txt");
let alias = tmp.path().join("linked.env");
std::fs::write(&target, "secret").expect("write symlink target");
symlink(&target, &alias).expect("create symlink");
let policy = FileSystemSandboxPolicy::restricted(vec![unreadable_glob_entry(
"**/*.env".to_string(),
)]);
assert_eq!(
resolve_windows_deny_read_paths(&policy, &cwd).expect("resolve symlinked secret"),
vec![AbsolutePathBuf::from_absolute_path(alias).expect("absolute symlink")]
);
}
}

View File

@@ -0,0 +1,229 @@
use super::resolve_windows_deny_read_paths;
use akode_protocol::permissions::FileSystemAccessMode;
use akode_protocol::permissions::FileSystemPath;
use akode_protocol::permissions::FileSystemSandboxEntry;
use akode_protocol::permissions::FileSystemSandboxPolicy;
use akode_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use std::collections::HashSet;
use std::path::Path;
use std::path::PathBuf;
use tempfile::TempDir;
fn policy() -> FileSystemSandboxPolicy {
FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry {
path: FileSystemPath::GlobPattern {
pattern: "**/*.env".to_string(),
},
access: FileSystemAccessMode::Deny,
missing_path_behavior: None,
}])
}
struct ProtectedDirectory {
path: PathBuf,
#[cfg(unix)]
permissions: std::fs::Permissions,
}
impl ProtectedDirectory {
fn new(path: &Path) -> Self {
#[cfg(unix)]
let permissions = {
use std::os::unix::fs::PermissionsExt;
let permissions = path.metadata().expect("directory metadata").permissions();
std::fs::set_permissions(path, std::fs::Permissions::from_mode(/*mode*/ 0o000))
.expect("protect directory");
permissions
};
#[cfg(windows)]
assert!(
std::process::Command::new("icacls.exe")
.arg(path)
.args(["/deny", "*S-1-1-0:(OI)(CI)R"])
.output()
.expect("protect directory for every account")
.status
.success()
);
Self {
path: path.to_path_buf(),
#[cfg(unix)]
permissions,
}
}
}
impl Drop for ProtectedDirectory {
fn drop(&mut self) {
#[cfg(unix)]
std::fs::set_permissions(&self.path, self.permissions.clone())
.expect("restore directory permissions");
#[cfg(windows)]
assert!(
std::process::Command::new("icacls.exe")
.arg(&self.path)
.args(["/remove:d", "*S-1-1-0"])
.output()
.expect("restore directory permissions")
.status
.success()
);
}
}
#[test]
fn protected_directory_does_not_discard_accessible_deny_matches() {
#[cfg(windows)]
if let Some(root) = std::env::var_os("AKODE_TEST_DENY_READ_RESTRICTED_ROOT") {
assert_accessible_deny_matches(Path::new(&root));
return;
}
let temp = TempDir::new().expect("tempdir");
let protected = temp.path().join("protected");
let readable = temp.path().join("readable");
std::fs::create_dir(&protected).expect("protected directory");
std::fs::create_dir(&readable).expect("readable directory");
std::fs::write(protected.join("hidden.env"), "protected").expect("protected file");
std::fs::write(readable.join("secret.env"), "secret").expect("readable secret");
std::fs::create_dir(readable.join("empty.env")).expect("matching empty directory");
std::fs::write(readable.join("public.txt"), "public").expect("public file");
let guard = ProtectedDirectory::new(&protected);
#[cfg(windows)]
{
// CI enables backup privileges, which let directory enumeration bypass
// this fixture's ACL. Restrict a separate process,
// rather than changing the shared test process's privileges. The parent
// owns ACL setup and cleanup, which the restricted child cannot perform.
let codex_home = TempDir::new().expect("restricted codex home");
let cwd = AbsolutePathBuf::from_absolute_path(temp.path()).expect("workspace");
let mut env = std::collections::HashMap::from([
(
"AKODE_TEST_DENY_READ_RESTRICTED_ROOT".to_string(),
cwd.display().to_string(),
),
("TEMP".to_string(), cwd.display().to_string()),
("TMP".to_string(), cwd.display().to_string()),
]);
for name in ["PATH", "SystemRoot", "COMSPEC", "USERPROFILE"] {
if let Ok(value) = std::env::var(name) {
env.insert(name.to_string(), value);
}
}
let result = crate::run_windows_sandbox_capture(
&akode_protocol::models::PermissionProfile::workspace_write(),
std::slice::from_ref(&cwd),
codex_home.path(),
vec![
std::env::current_exe()
.expect("test binary")
.display()
.to_string(),
"--exact".to_string(),
std::thread::current()
.name()
.expect("test name")
.to_string(),
],
cwd.as_path(),
env,
/*timeout_ms*/ Some(30_000),
/*cancellation*/ None,
)
.expect("run protected-directory regression without backup privileges");
let stdout = String::from_utf8_lossy(&result.stdout);
let stderr = String::from_utf8_lossy(&result.stderr);
assert_eq!(
(result.exit_code, result.timed_out),
(0, false),
"{stdout}\n{stderr}"
);
assert!(stdout.contains("test result: ok. 1 passed"), "{stdout}");
}
#[cfg(not(windows))]
assert_accessible_deny_matches(temp.path());
drop(guard);
}
fn assert_accessible_deny_matches(root: &Path) {
let cwd = AbsolutePathBuf::from_absolute_path(root).expect("cwd");
let protected = root.join("protected");
let enumeration = std::fs::read_dir(&protected)
.and_then(std::iter::Iterator::collect::<std::io::Result<Vec<_>>>);
assert_eq!(
enumeration
.expect_err("fixture must deny directory enumeration")
.kind(),
std::io::ErrorKind::PermissionDenied
);
let actual = resolve_windows_deny_read_paths(&policy(), &cwd)
.expect("protected branches must not abort expansion of accessible paths")
.into_iter()
.map(AbsolutePathBuf::into_path_buf)
.collect::<HashSet<_>>();
assert_eq!(
actual,
HashSet::from([
root.join("readable/secret.env"),
root.join("readable/empty.env"),
])
);
}
#[test]
fn glob_scans_skip_child_directory_links_but_follow_linked_roots() {
let temp = TempDir::new().expect("tempdir");
let cwd = AbsolutePathBuf::from_absolute_path(temp.path()).expect("cwd");
let walk = temp.path().join("walk");
let target = temp.path().join("target");
std::fs::create_dir(&walk).expect("walk root");
std::fs::create_dir(&target).expect("link target");
std::fs::write(target.join("secret.env"), "secret").expect("secret");
std::fs::write(target.join("public.txt"), "public").expect("public");
let alias = walk.join("alias");
let cycle = target.join("cycle");
let dangling = walk.join("broken.env");
let missing = temp.path().join("missing");
for (link, destination) in [(&alias, &target), (&cycle, &walk), (&dangling, &missing)] {
#[cfg(unix)]
std::os::unix::fs::symlink(destination, link).expect("directory symlink");
#[cfg(windows)]
assert!(
std::process::Command::new("cmd.exe")
.args(["/d", "/c", "mklink", "/J"])
.arg(link)
.arg(destination)
.output()
.expect("directory junction")
.status
.success()
);
}
for (root, expected) in [
(&walk, Vec::new()),
(
&alias,
vec![
AbsolutePathBuf::from_absolute_path(alias.join("secret.env"))
.expect("linked secret"),
],
),
] {
let policy = FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry {
path: FileSystemPath::GlobPattern {
pattern: root.join("**").join("*.env").display().to_string(),
},
access: FileSystemAccessMode::Deny,
missing_path_behavior: None,
}]);
assert_eq!(
resolve_windows_deny_read_paths(&policy, &cwd).expect("resolve directory links"),
expected,
);
}
}

View File

@@ -0,0 +1,178 @@
use crate::acl::revoke_ace;
use crate::deny_read_acl::apply_deny_read_acls;
use crate::deny_read_acl::lexical_path_key;
use crate::setup::sandbox_dir;
use anyhow::Context;
use anyhow::Result;
use anyhow::ensure;
use serde::Deserialize;
use serde::Serialize;
use std::collections::BTreeMap;
use std::collections::HashSet;
use std::ffi::c_void;
use std::fs::File;
use std::fs::OpenOptions;
use std::io::Read;
use std::io::Write;
use std::os::windows::fs::OpenOptionsExt;
use std::os::windows::io::AsRawHandle;
use std::path::Path;
use std::path::PathBuf;
use std::time::Duration;
use std::time::Instant;
use windows_sys::Win32::Foundation as win;
use windows_sys::Win32::Storage::FileSystem as winfs;
const DENY_READ_ACL_STATE_FILE: &str = "deny_read_acl_state.json";
#[derive(Default, Deserialize, Serialize)]
struct PersistentDenyReadAclState {
principals: BTreeMap<String, Vec<PathBuf>>,
}
/// Reconciles the persistent deny-read ACEs owned by one sandbox principal.
///
/// Workspace-write and elevated sandbox sessions intentionally leave ACLs in
/// place after a command exits, because descendants may outlive the launcher.
/// That makes the ACL set stateful across runs. Persist the paths applied for
/// each SID, apply the new desired set first, and only then revoke stale paths
/// from the same SID so profile changes do not leave old deny-read ACEs behind.
///
/// Malformed bookkeeping is rebuilt after applying current denies. Unknown
/// historical restrictions cannot safely be revoked and remain in place.
///
/// # Safety
/// Caller must pass a valid SID pointer matching `principal_sid`.
pub unsafe fn sync_persistent_deny_read_acls(
codex_home: &Path,
principal_sid: &str,
desired_paths: &[PathBuf],
psid: *mut c_void,
) -> Result<Vec<PathBuf>> {
let state_path = sandbox_dir(codex_home).join(DENY_READ_ACL_STATE_FILE);
let mut state = load_state(&state_path)?;
let previous_paths = state
.principals
.get(principal_sid)
.cloned()
.unwrap_or_default();
let applied_paths = unsafe { apply_deny_read_acls(desired_paths, psid) }?;
let desired_keys = applied_paths
.iter()
.map(|path| lexical_path_key(path))
.collect::<HashSet<_>>();
for path in previous_paths {
if !desired_keys.contains(&lexical_path_key(&path)) {
let _ = revoke_ace(&path, psid);
}
}
if applied_paths.is_empty() {
state.principals.remove(principal_sid);
} else {
state
.principals
.insert(principal_sid.to_string(), applied_paths.clone());
}
store_state(&state_path, &state)?;
Ok(applied_paths)
}
fn load_state(path: &Path) -> Result<PersistentDenyReadAclState> {
let deadline = Instant::now() + Duration::from_secs(2);
loop {
let stable = Instant::now() >= deadline;
let bytes = (|| -> Result<Vec<u8>> {
// Ordinary reads allow legacy writers; malformed recovery excludes live writers.
let share_mode = if stable {
winfs::FILE_SHARE_READ | winfs::FILE_SHARE_DELETE
} else {
winfs::FILE_SHARE_READ | winfs::FILE_SHARE_WRITE | winfs::FILE_SHARE_DELETE
};
let mut file = OpenOptions::new()
.read(true)
.share_mode(share_mode)
.custom_flags(winfs::FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)?;
// Validate the same leaf before either accepting state or recovering it.
validate_state_file(&file)?;
let mut bytes = Vec::new();
file.read_to_end(&mut bytes)?;
Ok(bytes)
})();
match bytes {
Ok(bytes) => match serde_json::from_slice(&bytes) {
Ok(state) => return Ok(state),
Err(_) if !stable => std::thread::sleep(Duration::from_millis(25)),
Err(_) => return Ok(PersistentDenyReadAclState::default()),
},
Err(err)
if err
.downcast_ref::<std::io::Error>()
.is_some_and(|error| error.kind() == std::io::ErrorKind::NotFound) =>
{
return Ok(PersistentDenyReadAclState::default());
}
Err(err) => {
return Err(err)
.with_context(|| format!("read deny-read ACL state {}", path.display()));
}
}
}
}
fn store_state(path: &Path, state: &PersistentDenyReadAclState) -> Result<()> {
let bytes = serde_json::to_vec_pretty(state).context("serialize deny-read ACL state")?;
(|| -> Result<()> {
// Recovery makes malformed files writable. Never follow the state leaf
// or truncate it before checking the actual object. Resolve configured
// parent paths normally, including junctions and volume GUIDs.
let deadline = Instant::now() + Duration::from_secs(2);
let mut file = loop {
let opened = OpenOptions::new()
.write(true)
.create(true)
.truncate(false)
.share_mode(winfs::FILE_SHARE_READ | winfs::FILE_SHARE_WRITE)
.custom_flags(winfs::FILE_FLAG_OPEN_REPARSE_POINT)
.open(path);
match opened {
Ok(file) => break file,
Err(error)
if error.raw_os_error() == Some(win::ERROR_SHARING_VIOLATION as i32)
&& Instant::now() < deadline =>
{
std::thread::sleep(Duration::from_millis(25));
}
Err(error) => return Err(error.into()),
}
};
validate_state_file(&file)?;
file.write_all(&bytes)?;
file.set_len(bytes.len() as u64)?;
Ok(())
})()
.with_context(|| format!("write deny-read ACL state {}", path.display()))
}
fn validate_state_file(file: &File) -> Result<()> {
let mut info = unsafe { std::mem::zeroed::<winfs::BY_HANDLE_FILE_INFORMATION>() };
if unsafe { winfs::GetFileInformationByHandle(file.as_raw_handle() as win::HANDLE, &mut info) }
== 0
{
return Err(std::io::Error::last_os_error().into());
}
ensure!(
info.dwFileAttributes & winfs::FILE_ATTRIBUTE_REPARSE_POINT == 0,
"state file is a reparse point"
);
ensure!(info.nNumberOfLinks == 1, "state file has multiple links");
Ok(())
}
#[cfg(test)]
#[path = "deny_read_state_tests.rs"]
mod tests;

View File

@@ -0,0 +1,351 @@
//! Exercises recovery and its file-safety boundaries on real Windows files.
use super::*;
use crate::token::LocalSid;
use pretty_assertions::assert_eq;
use std::ffi::OsString;
use std::fs;
use std::fs::File;
use std::os::windows::ffi::OsStringExt;
use std::process::Command;
use tempfile::TempDir;
#[test]
fn load_propagates_io_errors_and_preserves_missing_file_behavior() -> Result<()> {
let temp = TempDir::new()?;
let state_path = temp.path().join(DENY_READ_ACL_STATE_FILE);
assert!(load_state(&state_path)?.principals.is_empty());
fs::create_dir(&state_path)?;
let error = load_state(&state_path).err().expect("read error");
assert!(error.downcast_ref::<std::io::Error>().is_some());
Ok(())
}
#[test]
fn load_waits_for_a_legacy_writer_without_recovering_over_it() -> Result<()> {
let temp = TempDir::new()?;
let path = temp.path().join(DENY_READ_ACL_STATE_FILE);
let valid = br#"{"principals":{"legacy":["existing"]}}"#;
fs::write(&path, valid)?;
let mut writer = OpenOptions::new().write(true).truncate(true).open(&path)?;
std::thread::scope(|scope| -> Result<()> {
let write = scope.spawn(move || {
std::thread::sleep(Duration::from_millis(75));
writer.write_all(valid)
});
let state = load_state(&path)?;
write.join().expect("legacy writer")?;
assert_eq!(state.principals["legacy"], vec![PathBuf::from("existing")]);
Ok(())
})?;
let _writer = OpenOptions::new().write(true).truncate(true).open(&path)?;
let error = load_state(&path)
.err()
.expect("active writer must prevent recovery");
let error = error
.downcast_ref::<std::io::Error>()
.expect("sharing error");
assert_eq!(
error.raw_os_error(),
Some(win::ERROR_SHARING_VIOLATION as i32)
);
Ok(())
}
#[test]
fn sync_rebuilds_corrupt_bookkeeping_only_after_successful_apply() -> Result<()> {
let temp = TempDir::new()?;
let state_dir = sandbox_dir(temp.path());
fs::create_dir(&state_dir)?;
let state_path = state_dir.join(DENY_READ_ACL_STATE_FILE);
let malformed = b" ";
fs::write(&state_path, malformed)?;
let blocker = temp.path().join("ordinary-file");
fs::write(&blocker, b"not a directory")?;
let sid_string = "S-1-5-21-10-20-30-40";
let sid = LocalSid::from_string(sid_string)?;
// Creating a child beneath a file fails before any ACL can be changed.
let error = unsafe {
sync_persistent_deny_read_acls(
temp.path(),
sid_string,
&[blocker.join("child")],
sid.as_ptr(),
)
}
.expect_err("apply error must propagate");
assert!(error.downcast_ref::<std::io::Error>().is_some());
assert_eq!(fs::read(&state_path)?.as_slice(), malformed);
let historical = temp.path().join("historical");
let current = temp.path().join("current");
fs::create_dir(&historical)?;
unsafe { crate::acl::add_deny_read_ace(&historical, sid.as_ptr()) }?;
let applied = unsafe {
sync_persistent_deny_read_acls(
temp.path(),
sid_string,
std::slice::from_ref(&current),
sid.as_ptr(),
)
}?;
assert_eq!(applied, vec![current.clone()]);
let rebuilt: PersistentDenyReadAclState = serde_json::from_slice(&fs::read(&state_path)?)?;
assert_eq!(
rebuilt.principals,
BTreeMap::from([(sid_string.to_owned(), vec![current])])
);
unsafe {
let (dacl, descriptor) = crate::acl::fetch_dacl_handle(&historical)?;
let preserved = crate::acl::dacl_has_read_deny_for_sid(dacl, sid.as_ptr());
win::LocalFree(descriptor as win::HLOCAL);
assert!(preserved, "unknown historical restrictions remain in place");
}
let error = unsafe {
sync_persistent_deny_read_acls(
&temp.path().join("missing-home"),
sid_string,
&[],
sid.as_ptr(),
)
}
.expect_err("save error must propagate");
assert!(error.downcast_ref::<std::io::Error>().is_some());
Ok(())
}
/// Linked bookkeeping, valid or malformed, must preserve its victim and existing denies without adding new ones.
#[test]
fn sync_rejects_linked_state_before_changing_acls() -> Result<()> {
let temp = TempDir::new()?;
let state_dir = sandbox_dir(temp.path());
fs::create_dir(&state_dir)?;
let path = state_dir.join(DENY_READ_ACL_STATE_FILE);
let victim = temp.path().join("victim");
let sid_string = "S-1-5-21-10-20-30-40";
let sid = LocalSid::from_string(sid_string)?;
let previous = temp.path().join("previous");
let desired = temp.path().join("desired");
fs::create_dir(&previous)?;
fs::create_dir(&desired)?;
unsafe { crate::acl::add_deny_read_ace(&previous, sid.as_ptr()) }?;
let valid = serde_json::to_vec(&PersistentDenyReadAclState {
principals: BTreeMap::from([(sid_string.to_owned(), vec![previous.clone()])]),
})?;
for contents in [b"not json: keep me".as_slice(), valid.as_slice()] {
fs::write(&victim, contents)?;
for link_kind in ["hardlink", "symlink"] {
if link_kind == "hardlink" {
fs::hard_link(&victim, &path)?;
} else {
std::os::windows::fs::symlink_file(&victim, &path)?;
}
let error = unsafe {
sync_persistent_deny_read_acls(
temp.path(),
sid_string,
std::slice::from_ref(&desired),
sid.as_ptr(),
)
}
.expect_err("linked state must be rejected");
assert!(format!("{error:#}").contains(if link_kind == "hardlink" {
"multiple links"
} else {
"reparse point"
}));
assert_eq!(fs::read(&victim)?, contents);
for (target, expected_deny) in [(&previous, true), (&desired, false)] {
unsafe {
let (dacl, descriptor) = crate::acl::fetch_dacl_handle(target)?;
let denied = crate::acl::dacl_has_read_deny_for_sid(dacl, sid.as_ptr());
win::LocalFree(descriptor as win::HLOCAL);
assert_eq!(denied, expected_deny, "rejected state must not change ACLs");
}
}
fs::remove_file(&path)?;
}
}
Ok(())
}
#[test]
fn store_keeps_file_identity_permissions_and_legacy_writer_compatibility() -> Result<()> {
let temp = TempDir::new()?;
let path = temp.path().join(DENY_READ_ACL_STATE_FILE);
let state = PersistentDenyReadAclState {
principals: BTreeMap::from([("kept".to_owned(), vec![PathBuf::from("secret")])]),
};
fs::write(
&path,
b"malformed longer than the new state ",
)?;
let sid = LocalSid::from_string("S-1-5-21-10-20-30-40")?;
unsafe { crate::acl::add_deny_read_ace(&path, sid.as_ptr()) }?;
let file = File::open(&path)?;
let mut before = unsafe { std::mem::zeroed::<winfs::BY_HANDLE_FILE_INFORMATION>() };
assert_ne!(
unsafe {
winfs::GetFileInformationByHandle(file.as_raw_handle() as win::HANDLE, &mut before)
},
0
);
// A legacy writer can remain open after finishing valid bytes; normal store
// must not newly fail just because that writer has not closed its handle.
let _writer = OpenOptions::new().write(true).open(&path)?;
// A delete-access holder may coexist with readers and legacy writers. Wait
// for it to close without allowing replacement during validation or writing.
let holder = OpenOptions::new()
.access_mode(winfs::DELETE)
.share_mode(winfs::FILE_SHARE_READ | winfs::FILE_SHARE_WRITE | winfs::FILE_SHARE_DELETE)
.open(&path)?;
std::thread::scope(|scope| -> Result<()> {
let release = scope.spawn(move || {
std::thread::sleep(Duration::from_millis(75));
drop(holder);
});
store_state(&path, &state)?;
release.join().expect("delete-access holder");
Ok(())
})?;
let root = path.ancestors().last().expect("drive root");
let mut volume = [0u16; 50];
assert_ne!(
unsafe {
winfs::GetVolumeNameForVolumeMountPointW(
crate::winutil::to_wide(root).as_ptr(),
volume.as_mut_ptr(),
volume.len() as u32,
)
},
0
);
let end = volume
.iter()
.position(|unit| *unit == 0)
.expect("volume name");
let volume_path =
PathBuf::from(OsString::from_wide(&volume[..end])).join(path.strip_prefix(root)?);
store_state(&volume_path, &state)?;
let alias_dir = TempDir::new()?;
let junction = alias_dir.path().join("sandbox-junction");
assert!(
Command::new("cmd.exe")
.args(["/c", "mklink", "/J"])
.arg(&junction)
.arg(temp.path())
.output()?
.status
.success()
);
store_state(&junction.join(DENY_READ_ACL_STATE_FILE), &state)?;
let reopened = File::open(&path)?;
let mut after = unsafe { std::mem::zeroed::<winfs::BY_HANDLE_FILE_INFORMATION>() };
assert_ne!(
unsafe {
winfs::GetFileInformationByHandle(reopened.as_raw_handle() as win::HANDLE, &mut after)
},
0
);
assert_eq!(
(
after.dwVolumeSerialNumber,
after.nFileIndexHigh,
after.nFileIndexLow
),
(
before.dwVolumeSerialNumber,
before.nFileIndexHigh,
before.nFileIndexLow
)
);
assert_eq!(load_state(&path)?.principals, state.principals);
unsafe {
let (dacl, descriptor) = crate::acl::fetch_dacl_handle(&path)?;
let preserved = crate::acl::dacl_has_read_deny_for_sid(dacl, sid.as_ptr());
win::LocalFree(descriptor as win::HLOCAL);
assert!(preserved);
}
Ok(())
}
// An unreleased delete-access handle must produce a bounded sharing error,
// leaving the existing bytes intact instead of truncating or replacing them.
#[test]
fn store_times_out_without_modifying_state_held_for_delete() -> Result<()> {
let temp = TempDir::new()?;
let path = temp.path().join(DENY_READ_ACL_STATE_FILE);
let original = br#"{"principals":{"kept":["secret"]}}"#;
fs::write(&path, original)?;
let holder = OpenOptions::new()
.access_mode(winfs::DELETE)
.share_mode(winfs::FILE_SHARE_READ | winfs::FILE_SHARE_WRITE | winfs::FILE_SHARE_DELETE)
.open(&path)?;
let started = Instant::now();
let error = store_state(&path, &PersistentDenyReadAclState::default())
.expect_err("delete-access holder must block storage");
assert!(started.elapsed() >= Duration::from_secs(2));
assert_eq!(
error
.downcast_ref::<std::io::Error>()
.expect("sharing error")
.raw_os_error(),
Some(win::ERROR_SHARING_VIOLATION as i32)
);
assert_eq!(fs::read(&path)?, original);
drop(holder);
assert_eq!(
load_state(&path)?.principals["kept"],
vec![PathBuf::from("secret")]
);
Ok(())
}
#[test]
fn recovered_bookkeeping_tracks_repeated_calls_and_a_later_profile_change() -> Result<()> {
let temp = TempDir::new()?;
let state_dir = sandbox_dir(temp.path());
fs::create_dir(&state_dir)?;
let path = state_dir.join(DENY_READ_ACL_STATE_FILE);
// Simulate an interrupted in-place save, after an older deny was applied.
fs::write(&path, br#"{"principals":"#)?;
let sid_string = "S-1-5-21-10-20-30-40";
let sid = LocalSid::from_string(sid_string)?;
let historical = temp.path().join("historical");
let first = temp.path().join("first");
let second = temp.path().join("second");
fs::create_dir(&historical)?;
unsafe { crate::acl::add_deny_read_ace(&historical, sid.as_ptr()) }?;
for desired in [&first, &first, &second, &second] {
let applied = unsafe {
sync_persistent_deny_read_acls(
temp.path(),
sid_string,
std::slice::from_ref(desired),
sid.as_ptr(),
)
}?;
assert_eq!(applied, vec![desired.clone()]);
let state = load_state(&path)?;
assert_eq!(
state.principals,
BTreeMap::from([(sid_string.to_owned(), vec![desired.clone()])])
);
}
// Recovery must preserve both unknown historical denies and the current profile.
for target in [&historical, &second] {
unsafe {
let (dacl, descriptor) = crate::acl::fetch_dacl_handle(target)?;
let denied = crate::acl::dacl_has_read_deny_for_sid(dacl, sid.as_ptr());
win::LocalFree(descriptor as win::HLOCAL);
assert!(denied, "deny must remain at {}", target.display());
}
}
Ok(())
}

View File

@@ -0,0 +1,472 @@
use crate::allow::compute_allow_paths_for_permissions;
use crate::deny_read_acl::plan_deny_read_acl_paths;
use crate::logging;
use crate::path_normalization::canonicalize_path;
use crate::resolved_permissions::ResolvedWindowsSandboxPermissions;
use crate::setup::SandboxSetupRequest;
use crate::setup::SetupRootOverrides;
use crate::setup::build_payload_deny_write_paths;
use crate::setup::build_payload_roots;
use crate::setup::gather_read_roots;
use crate::spawn_prep::LegacySessionSecurity;
use crate::token::get_current_token_for_restriction;
use crate::token::get_logon_sid_bytes;
use crate::token::get_user_sid_bytes;
use crate::winutil::format_last_error;
use crate::winutil::resolve_sid;
use crate::winutil::sid_bytes_from_string;
use crate::winutil::string_from_sid_bytes;
use crate::winutil::to_wide;
use anyhow::Result;
use rand::Rng;
use rand::SeedableRng;
use rand::rngs::SmallRng;
use std::collections::BTreeSet;
use std::collections::HashMap;
use std::ffi::c_void;
use std::path::Path;
use std::path::PathBuf;
use std::ptr;
use std::sync::Mutex;
use std::sync::OnceLock;
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::Foundation::ERROR_SUCCESS;
use windows_sys::Win32::Foundation::GetLastError;
use windows_sys::Win32::Foundation::HLOCAL;
use windows_sys::Win32::Foundation::LocalFree;
use windows_sys::Win32::Security::Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW;
use windows_sys::Win32::Security::Authorization::EXPLICIT_ACCESS_W;
use windows_sys::Win32::Security::Authorization::GRANT_ACCESS;
use windows_sys::Win32::Security::Authorization::SE_WINDOW_OBJECT;
use windows_sys::Win32::Security::Authorization::SetEntriesInAclW;
use windows_sys::Win32::Security::Authorization::SetSecurityInfo;
use windows_sys::Win32::Security::Authorization::TRUSTEE_IS_SID;
use windows_sys::Win32::Security::Authorization::TRUSTEE_IS_UNKNOWN;
use windows_sys::Win32::Security::Authorization::TRUSTEE_W;
use windows_sys::Win32::Security::DACL_SECURITY_INFORMATION;
use windows_sys::Win32::Security::PSECURITY_DESCRIPTOR;
use windows_sys::Win32::Security::SECURITY_ATTRIBUTES;
use windows_sys::Win32::System::StationsAndDesktops::CloseDesktop;
use windows_sys::Win32::System::StationsAndDesktops::CreateDesktopW;
use windows_sys::Win32::System::StationsAndDesktops::DESKTOP_CREATEMENU;
use windows_sys::Win32::System::StationsAndDesktops::DESKTOP_CREATEWINDOW;
use windows_sys::Win32::System::StationsAndDesktops::DESKTOP_DELETE;
use windows_sys::Win32::System::StationsAndDesktops::DESKTOP_ENUMERATE;
use windows_sys::Win32::System::StationsAndDesktops::DESKTOP_HOOKCONTROL;
use windows_sys::Win32::System::StationsAndDesktops::DESKTOP_JOURNALPLAYBACK;
use windows_sys::Win32::System::StationsAndDesktops::DESKTOP_JOURNALRECORD;
use windows_sys::Win32::System::StationsAndDesktops::DESKTOP_READ_CONTROL;
use windows_sys::Win32::System::StationsAndDesktops::DESKTOP_READOBJECTS;
use windows_sys::Win32::System::StationsAndDesktops::DESKTOP_SWITCHDESKTOP;
use windows_sys::Win32::System::StationsAndDesktops::DESKTOP_WRITE_DAC;
use windows_sys::Win32::System::StationsAndDesktops::DESKTOP_WRITE_OWNER;
use windows_sys::Win32::System::StationsAndDesktops::DESKTOP_WRITEOBJECTS;
use windows_sys::Win32::System::StationsAndDesktops::HDESK;
use windows_sys::Win32::System::StationsAndDesktops::OpenDesktopW;
const PRIVATE_DESKTOP_PREFIX: &str = "CodexSandboxDesktop-";
const DESKTOP_ALL_ACCESS: u32 = DESKTOP_READOBJECTS
| DESKTOP_CREATEWINDOW
| DESKTOP_CREATEMENU
| DESKTOP_HOOKCONTROL
| DESKTOP_JOURNALRECORD
| DESKTOP_JOURNALPLAYBACK
| DESKTOP_ENUMERATE
| DESKTOP_WRITEOBJECTS
| DESKTOP_SWITCHDESKTOP
| DESKTOP_DELETE
| DESKTOP_READ_CONTROL
| DESKTOP_WRITE_DAC
| DESKTOP_WRITE_OWNER;
const DESKTOP_PARTICIPANT_ACCESS: u32 =
DESKTOP_ALL_ACCESS & !(DESKTOP_WRITE_DAC | DESKTOP_WRITE_OWNER | DESKTOP_DELETE);
static SHARED_PRIVATE_DESKTOPS: OnceLock<Mutex<HashMap<(String, DesktopPolicy), PrivateDesktop>>> =
OnceLock::new();
#[derive(Clone, PartialEq, Eq, Hash)]
pub(crate) struct DesktopPolicy {
uses_write_capabilities: bool,
capability_sids: BTreeSet<Vec<u8>>,
network_enabled: bool,
network_proxy_restricting_sid: Option<Vec<u8>>,
// None denotes the legacy backend's unrestricted reads and different desktop ACLs.
read_roots: Option<BTreeSet<PathBuf>>,
write_roots: BTreeSet<PathBuf>,
deny_read_paths: BTreeSet<PathBuf>,
deny_write_paths: BTreeSet<PathBuf>,
}
impl DesktopPolicy {
pub(crate) fn elevated(
request: SandboxSetupRequest<'_>,
mut overrides: SetupRootOverrides,
capability_sids: &[String],
network_proxy_restricting_sid: Option<&str>,
) -> Result<Self> {
// Match the complete read override passed by credential setup to the ACL helper.
let runtime = crate::setup::current_setup_runtime();
overrides.read_roots.get_or_insert_with(|| {
gather_read_roots(
request.command_cwd,
request.permissions,
request.env_map,
request.codex_home,
runtime,
)
});
let (read_roots, write_roots) = build_payload_roots(&request, &overrides, runtime);
Ok(Self {
uses_write_capabilities: request
.permissions
.uses_write_capabilities_for_cwd(request.command_cwd, request.env_map),
capability_sids: capability_sids
.iter()
.map(|sid| sid_bytes_from_string(sid))
.collect::<Result<_>>()?,
network_enabled: request.permissions.network_policy().is_enabled(),
network_proxy_restricting_sid: network_proxy_restricting_sid
.map(sid_bytes_from_string)
.transpose()?,
read_roots: Some(read_roots.into_iter().collect()),
write_roots: write_roots.into_iter().collect(),
deny_read_paths: plan_deny_read_acl_paths(
overrides.deny_read_paths.as_deref().unwrap_or_default(),
)?
.into_iter()
.collect(),
deny_write_paths: build_payload_deny_write_paths(&request, overrides.deny_write_paths)
.into_iter()
.map(|path| canonicalize_path(&path))
.collect(),
})
}
}
pub struct LaunchDesktop {
_private_desktop: PrivateDesktop,
startup_name: Vec<u16>,
}
impl LaunchDesktop {
pub(crate) fn prepare_legacy(
permissions: &ResolvedWindowsSandboxPermissions,
cwd: &Path,
env: &HashMap<String, String>,
security: &LegacySessionSecurity,
additional_deny_write_paths: &[PathBuf],
logs_base_dir: Option<&Path>,
) -> Result<Self> {
Self::open_private(&Self::shared_legacy_name(
permissions,
cwd,
env,
security,
additional_deny_write_paths,
logs_base_dir,
)?)
}
pub(crate) fn shared_legacy_name(
permissions: &ResolvedWindowsSandboxPermissions,
cwd: &Path,
env: &HashMap<String, String>,
security: &LegacySessionSecurity,
additional_deny_write_paths: &[PathBuf],
logs_base_dir: Option<&Path>,
) -> Result<String> {
let sandbox_sid = unsafe { get_user_sid_bytes(security.h_token)? };
let sandbox_sid = string_from_sid_bytes(&sandbox_sid).map_err(anyhow::Error::msg)?;
let paths = compute_allow_paths_for_permissions(permissions, cwd, env);
let policy = DesktopPolicy {
uses_write_capabilities: security.readonly_sid.is_none(),
capability_sids: security
.readonly_sid_str
.iter()
.chain(security.write_root_sids.iter().map(|root| &root.sid_str))
.map(|sid| sid_bytes_from_string(sid))
.collect::<Result<_>>()?,
network_enabled: permissions.network_policy().is_enabled(),
network_proxy_restricting_sid: None,
read_roots: None,
write_roots: paths.allow.into_iter().collect(),
deny_read_paths: BTreeSet::new(),
deny_write_paths: paths
.deny
.into_iter()
.chain(additional_deny_write_paths.iter().cloned())
.map(|path| canonicalize_path(&path))
.collect(),
};
let mut desktops = SHARED_PRIVATE_DESKTOPS
.get_or_init(|| Mutex::new(HashMap::new()))
.lock()
.map_err(|_| anyhow::anyhow!("shared private desktop cache was poisoned"))?;
let desktop = match desktops.entry((sandbox_sid, policy)) {
std::collections::hash_map::Entry::Occupied(entry) => entry.into_mut(),
std::collections::hash_map::Entry::Vacant(entry) => {
entry.insert(PrivateDesktop::create(logs_base_dir)?)
}
};
Ok(desktop.name.clone())
}
pub fn prepare(logs_base_dir: Option<&Path>) -> Result<Self> {
let private_desktop = PrivateDesktop::create(logs_base_dir)?;
let startup_name = to_wide(format!("Winsta0\\{}", private_desktop.name));
Ok(Self {
_private_desktop: private_desktop,
startup_name,
})
}
/// Opens the caller-owned private desktop without creating one or falling back to Default.
pub fn open_private(name: &str) -> Result<Self> {
if !name
.strip_prefix(PRIVATE_DESKTOP_PREFIX)
.is_some_and(|nonce| {
!nonce.is_empty()
&& nonce.len() <= 32
&& nonce.bytes().all(|byte| byte.is_ascii_hexdigit())
})
{
anyhow::bail!("invalid private desktop name");
}
let name_wide = to_wide(name);
let handle = unsafe {
OpenDesktopW(
name_wide.as_ptr(),
/*dwflags*/ 0,
/*finherit*/ 0,
DESKTOP_PARTICIPANT_ACCESS,
)
};
if handle.is_null() {
anyhow::bail!("OpenDesktopW failed: {}", unsafe { GetLastError() });
}
Ok(Self {
_private_desktop: PrivateDesktop {
handle,
name: name.to_owned(),
},
startup_name: to_wide(format!("Winsta0\\{name}")),
})
}
pub fn startup_info_desktop(&self) -> *mut u16 {
self.startup_name.as_ptr() as *mut u16
}
}
/// Reuses a private desktop only for the same sandbox account and effective permissions.
pub(crate) fn shared_private_desktop_for_user(
sandbox_username: &str,
policy: &DesktopPolicy,
logs_base_dir: Option<&Path>,
) -> Result<String> {
let sandbox_sid =
string_from_sid_bytes(&resolve_sid(sandbox_username)?).map_err(anyhow::Error::msg)?;
let mut desktops = SHARED_PRIVATE_DESKTOPS
.get_or_init(|| Mutex::new(HashMap::new()))
.lock()
.map_err(|_| anyhow::anyhow!("shared private desktop cache was poisoned"))?;
let key = (sandbox_sid.clone(), policy.clone());
if let Some(desktop) = desktops.get(&key) {
return Ok(desktop.name.clone());
}
let owner_user_sid = unsafe {
let token = get_current_token_for_restriction()?;
let sid = get_user_sid_bytes(token);
CloseHandle(token);
sid?
};
let owner_user_sid = string_from_sid_bytes(&owner_user_sid).map_err(anyhow::Error::msg)?;
// CreateProcessWithLogonW shares the caller's logon SID with the sandbox account.
// Grant ACL-management rights to the caller's user SID instead.
// https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createprocesswithlogonw
let sddl = to_wide(format!(
"D:P(A;;0x{DESKTOP_ALL_ACCESS:x};;;{owner_user_sid})(A;;0x{DESKTOP_PARTICIPANT_ACCESS:x};;;{sandbox_sid})"
));
let mut security_descriptor: PSECURITY_DESCRIPTOR = ptr::null_mut();
if unsafe {
ConvertStringSecurityDescriptorToSecurityDescriptorW(
sddl.as_ptr(),
/*stringsdrevision*/ 1,
&mut security_descriptor,
ptr::null_mut(),
)
} == 0
{
anyhow::bail!(
"ConvertStringSecurityDescriptorToSecurityDescriptorW failed: {}",
unsafe { GetLastError() }
);
}
let attributes = SECURITY_ATTRIBUTES {
nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
lpSecurityDescriptor: security_descriptor,
bInheritHandle: 0,
};
let mut rng = SmallRng::from_entropy();
let name = format!("{PRIVATE_DESKTOP_PREFIX}{:032x}", rng.r#gen::<u128>());
let name_wide = to_wide(&name);
let handle = unsafe {
CreateDesktopW(
name_wide.as_ptr(),
ptr::null(),
ptr::null_mut(),
/*dwflags*/ 0,
DESKTOP_ALL_ACCESS,
&attributes,
)
};
let error = unsafe { GetLastError() };
unsafe {
LocalFree(security_descriptor as HLOCAL);
}
if handle.is_null() {
logging::debug_log(
&format!("CreateDesktopW failed for shared private desktop: {error}"),
logs_base_dir,
);
anyhow::bail!("CreateDesktopW failed for shared private desktop: {error}");
}
// Retain ownership across runner exits and idle gaps; different policies stay on separate
// desktops so GUI hooks do not automatically cross those policies.
desktops.insert(
key,
PrivateDesktop {
handle,
name: name.clone(),
},
);
Ok(name)
}
struct PrivateDesktop {
handle: HDESK,
name: String,
}
// SAFETY: HDESK is an opaque Windows handle, and this owner only uses it through
// Windows APIs. After setup, its only handle operation is CloseDesktop, which
// reports failure if a thread in the calling process is using the handle.
unsafe impl Send for PrivateDesktop {}
impl PrivateDesktop {
fn create(logs_base_dir: Option<&Path>) -> Result<Self> {
let mut rng = SmallRng::from_entropy();
let name = format!("CodexSandboxDesktop-{:x}", rng.r#gen::<u128>());
let name_wide = to_wide(&name);
let handle = unsafe {
CreateDesktopW(
name_wide.as_ptr(),
ptr::null(),
ptr::null_mut(),
0,
DESKTOP_ALL_ACCESS,
ptr::null_mut(),
)
};
if handle.is_null() {
let err = unsafe { GetLastError() } as i32;
logging::debug_log(
&format!(
"CreateDesktopW failed for {name}: {} ({})",
err,
format_last_error(err),
),
logs_base_dir,
);
return Err(anyhow::anyhow!("CreateDesktopW failed: {err}"));
}
unsafe {
if let Err(err) = grant_desktop_access(handle, logs_base_dir) {
let _ = CloseDesktop(handle);
return Err(err);
}
}
Ok(Self { handle, name })
}
}
unsafe fn grant_desktop_access(handle: HDESK, logs_base_dir: Option<&Path>) -> Result<()> {
let token = get_current_token_for_restriction()?;
let mut logon_sid = get_logon_sid_bytes(token)?;
CloseHandle(token);
let entries = [EXPLICIT_ACCESS_W {
grfAccessPermissions: DESKTOP_ALL_ACCESS,
grfAccessMode: GRANT_ACCESS,
grfInheritance: 0,
Trustee: TRUSTEE_W {
pMultipleTrustee: ptr::null_mut(),
MultipleTrusteeOperation: 0,
TrusteeForm: TRUSTEE_IS_SID,
TrusteeType: TRUSTEE_IS_UNKNOWN,
ptstrName: logon_sid.as_mut_ptr() as *mut c_void as *mut u16,
},
}];
let mut updated_dacl = ptr::null_mut();
let set_entries_code = SetEntriesInAclW(
entries.len() as u32,
entries.as_ptr(),
ptr::null_mut(),
&mut updated_dacl,
);
if set_entries_code != ERROR_SUCCESS {
logging::debug_log(
&format!("SetEntriesInAclW failed for private desktop: {set_entries_code}"),
logs_base_dir,
);
return Err(anyhow::anyhow!(
"SetEntriesInAclW failed for private desktop: {set_entries_code}"
));
}
let set_security_code = SetSecurityInfo(
handle,
SE_WINDOW_OBJECT,
DACL_SECURITY_INFORMATION,
ptr::null_mut(),
ptr::null_mut(),
updated_dacl,
ptr::null_mut(),
);
if !updated_dacl.is_null() {
LocalFree(updated_dacl as HLOCAL);
}
if set_security_code != ERROR_SUCCESS {
logging::debug_log(
&format!("SetSecurityInfo failed for private desktop: {set_security_code}"),
logs_base_dir,
);
return Err(anyhow::anyhow!(
"SetSecurityInfo failed for private desktop: {set_security_code}"
));
}
Ok(())
}
impl Drop for PrivateDesktop {
fn drop(&mut self) {
unsafe {
if !self.handle.is_null() {
let _ = CloseDesktop(self.handle);
}
}
}
}
#[cfg(test)]
#[path = "desktop_tests.rs"]
mod tests;

View File

@@ -0,0 +1,241 @@
use super::DesktopPolicy;
use super::LaunchDesktop;
use super::PRIVATE_DESKTOP_PREFIX;
use super::shared_private_desktop_for_user;
use crate::resolved_permissions::ResolvedWindowsSandboxPermissions;
use crate::setup::SandboxSetupRequest;
use crate::setup::SetupRootOverrides;
use crate::spawn_prep::legacy_session_capability_roots;
use crate::spawn_prep::prepare_legacy_session_security;
use anyhow::Result;
use akode_protocol::models::PermissionProfile;
use akode_protocol::permissions::NetworkSandboxPolicy;
use akode_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use rand::Rng;
use rand::SeedableRng;
use rand::rngs::SmallRng;
use std::collections::HashMap;
use std::os::windows::io::FromRawHandle;
use std::os::windows::io::OwnedHandle;
use std::path::Path;
use tempfile::TempDir;
use windows_sys::Win32::NetworkManagement::NetManagement::DNLEN;
use windows_sys::Win32::NetworkManagement::NetManagement::UNLEN;
use windows_sys::Win32::Security::Authentication::Identity::GetUserNameExW;
use windows_sys::Win32::Security::Authentication::Identity::NameSamCompatible;
#[test]
fn private_desktop_rejects_interactive_and_injected_names() {
for name in [
"Default",
r"Winsta0\Default",
"CodexSandboxDesktop-",
r"CodexSandboxDesktop-abcd\Default",
"CodexSandboxDesktop-abcd\0Default",
"CodexSandboxDesktop-0123456789abcdef0123456789abcdef0",
] {
assert!(LaunchDesktop::open_private(name).is_err(), "{name:?}");
}
}
#[test]
fn opening_missing_private_desktop_does_not_create_or_fall_back() {
let name = format!(
"{PRIVATE_DESKTOP_PREFIX}{:032x}",
SmallRng::from_entropy().r#gen::<u128>(),
);
assert!(LaunchDesktop::open_private(&name).is_err());
}
#[test]
fn shared_desktop_survives_launch_handles_and_concurrent_requests() -> Result<()> {
let policy = DesktopPolicy {
uses_write_capabilities: false,
capability_sids: Default::default(),
network_enabled: false,
network_proxy_restricting_sid: None,
read_roots: Some(Default::default()),
write_roots: Default::default(),
deny_read_paths: Default::default(),
deny_write_paths: Default::default(),
};
let account = current_account_name()?;
let names = std::thread::scope(|scope| {
let workers = [(); 4].map(|_| {
let account = &account;
let policy = &policy;
scope.spawn(move || {
shared_private_desktop_for_user(account, policy, /*logs_base_dir*/ None)
})
});
workers
.into_iter()
.map(|worker| worker.join().expect("desktop request panicked"))
.collect::<Result<Vec<_>>>()
})?;
let name = names[0].clone();
assert_eq!(names, vec![name.clone(); 4]);
drop(LaunchDesktop::open_private(&name)?);
assert_eq!(
shared_private_desktop_for_user(
&account.to_ascii_lowercase(),
&policy,
/*logs_base_dir*/ None
)?,
name,
);
drop(LaunchDesktop::open_private(&name)?);
Ok(())
}
#[test]
fn shared_desktop_reuses_only_equivalent_permissions() -> Result<()> {
let temp = TempDir::new()?;
let workspace = temp.path().join("workspace");
let readable = temp.path().join("readable");
let writable = temp.path().join("writable");
for path in [&workspace, &readable, &writable] {
std::fs::create_dir(path)?;
}
let codex_home = temp.path().join("akode-home");
let permissions = workspace_permissions(&workspace)?;
let env = HashMap::new();
let account = current_account_name()?;
let sids = ["S-1-5-21-10-20-30-40".into(), "S-1-5-21-10-20-30-41".into()];
let proxy_sid = "S-1-5-21-50-60-70-80";
let overrides = || SetupRootOverrides {
read_roots: Some(vec![readable.clone()]),
write_roots: Some(vec![workspace.clone(), writable.clone()]),
..Default::default()
};
let desktop = |overrides, capability_sids: &[String], network_proxy_restricting_sid| {
let policy = DesktopPolicy::elevated(
SandboxSetupRequest {
permissions: &permissions,
command_cwd: &workspace,
env_map: &env,
codex_home: &codex_home,
proxy_enforced: true,
},
overrides,
capability_sids,
Some(network_proxy_restricting_sid),
)?;
shared_private_desktop_for_user(&account, &policy, /*logs_base_dir*/ None)
};
let name = desktop(overrides(), &sids, proxy_sid)?;
assert_eq!(
desktop(
SetupRootOverrides {
read_roots: Some(vec![readable.clone(), readable.clone()]),
write_roots: Some(vec![
writable.join("..").join("writable"),
workspace.clone(),
writable.clone(),
]),
..Default::default()
},
&[sids[1].clone(), sids[0].clone(), sids[1].clone()],
proxy_sid,
)?,
name,
);
for (reason, changed) in [
(
"read roots",
SetupRootOverrides {
read_roots: Some(vec![workspace.clone()]),
..overrides()
},
),
(
"write roots",
SetupRootOverrides {
write_roots: Some(vec![workspace.clone()]),
..overrides()
},
),
(
"deny reads",
SetupRootOverrides {
deny_read_paths: Some(vec![readable.clone()]),
..overrides()
},
),
(
"deny writes",
SetupRootOverrides {
deny_write_paths: Some(vec![writable.clone()]),
..overrides()
},
),
] {
let changed_name = desktop(changed, &sids, proxy_sid)?;
assert_ne!(changed_name, name, "{reason}");
drop(LaunchDesktop::open_private(&changed_name)?);
}
assert_ne!(desktop(overrides(), &sids[..1], proxy_sid)?, name);
assert_ne!(desktop(overrides(), &sids, "S-1-5-21-50-60-70-81")?, name,);
assert_eq!(desktop(overrides(), &sids, proxy_sid)?, name);
Ok(())
}
#[test]
fn legacy_desktop_reuses_only_equivalent_permissions() -> Result<()> {
let temp = TempDir::new()?;
let workspace = temp.path().join("workspace");
std::fs::create_dir(&workspace)?;
let codex_home = temp.path().join("akode-home");
let permissions = workspace_permissions(&workspace)?;
let env = HashMap::new();
let security = prepare_legacy_session_security(
/*uses_write_capabilities*/ true,
&codex_home,
&workspace,
legacy_session_capability_roots(&permissions, &workspace, &env, &codex_home),
)?;
let _token = unsafe { OwnedHandle::from_raw_handle(security.h_token as *mut _) };
let desktop = |deny_write_paths| {
LaunchDesktop::prepare_legacy(
&permissions,
&workspace,
&env,
&security,
deny_write_paths,
/*logs_base_dir*/ None,
)
};
let first = desktop(&[])?;
let name = first.startup_name.clone();
drop(first);
assert_eq!(desktop(&[])?.startup_name, name);
assert_ne!(
desktop(std::slice::from_ref(&workspace))?.startup_name,
name
);
assert_eq!(desktop(&[])?.startup_name, name);
Ok(())
}
fn current_account_name() -> Result<String> {
// Bazel does not provide USERDOMAIN or USERNAME in the test environment.
let mut account = [0; (DNLEN + UNLEN + 2) as usize];
let mut length = account.len() as u32;
if !unsafe { GetUserNameExW(NameSamCompatible, account.as_mut_ptr(), &mut length) } {
return Err(std::io::Error::last_os_error().into());
}
Ok(String::from_utf16(&account[..length as usize])?)
}
fn workspace_permissions(workspace: &Path) -> Result<ResolvedWindowsSandboxPermissions> {
ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots(
&PermissionProfile::workspace_write_with(
&[],
NetworkSandboxPolicy::Restricted,
/*exclude_tmpdir_env_var*/ true,
/*exclude_slash_tmp*/ true,
),
&[AbsolutePathBuf::from_absolute_path(workspace)?],
)
}

View File

@@ -0,0 +1,85 @@
use anyhow::Result;
use anyhow::anyhow;
use windows_sys::Win32::Foundation::GetLastError;
use windows_sys::Win32::Foundation::HLOCAL;
use windows_sys::Win32::Foundation::LocalFree;
use windows_sys::Win32::Security::Cryptography::CRYPT_INTEGER_BLOB;
use windows_sys::Win32::Security::Cryptography::CRYPTPROTECT_LOCAL_MACHINE;
use windows_sys::Win32::Security::Cryptography::CRYPTPROTECT_UI_FORBIDDEN;
use windows_sys::Win32::Security::Cryptography::CryptProtectData;
use windows_sys::Win32::Security::Cryptography::CryptUnprotectData;
fn make_blob(data: &[u8]) -> CRYPT_INTEGER_BLOB {
CRYPT_INTEGER_BLOB {
cbData: data.len() as u32,
pbData: data.as_ptr() as *mut u8,
}
}
#[allow(clippy::unnecessary_mut_passed)]
pub fn protect(data: &[u8]) -> Result<Vec<u8>> {
let mut in_blob = make_blob(data);
let mut out_blob = CRYPT_INTEGER_BLOB {
cbData: 0,
pbData: std::ptr::null_mut(),
};
let ok = unsafe {
CryptProtectData(
&mut in_blob,
std::ptr::null(),
std::ptr::null(),
std::ptr::null_mut(),
std::ptr::null_mut(),
// Use machine scope so elevated and non-elevated processes can decrypt.
CRYPTPROTECT_UI_FORBIDDEN | CRYPTPROTECT_LOCAL_MACHINE,
&mut out_blob,
)
};
if ok == 0 {
return Err(anyhow!("CryptProtectData failed: {}", unsafe {
GetLastError()
}));
}
let slice =
unsafe { std::slice::from_raw_parts(out_blob.pbData, out_blob.cbData as usize) }.to_vec();
unsafe {
if !out_blob.pbData.is_null() {
LocalFree(out_blob.pbData as HLOCAL);
}
}
Ok(slice)
}
#[allow(clippy::unnecessary_mut_passed)]
pub fn unprotect(blob: &[u8]) -> Result<Vec<u8>> {
let mut in_blob = make_blob(blob);
let mut out_blob = CRYPT_INTEGER_BLOB {
cbData: 0,
pbData: std::ptr::null_mut(),
};
let ok = unsafe {
CryptUnprotectData(
&mut in_blob,
std::ptr::null_mut(),
std::ptr::null(),
std::ptr::null_mut(),
std::ptr::null_mut(),
// Use machine scope so elevated and non-elevated processes can decrypt.
CRYPTPROTECT_UI_FORBIDDEN | CRYPTPROTECT_LOCAL_MACHINE,
&mut out_blob,
)
};
if ok == 0 {
return Err(anyhow!("CryptUnprotectData failed: {}", unsafe {
GetLastError()
}));
}
let slice =
unsafe { std::slice::from_raw_parts(out_blob.pbData, out_blob.cbData as usize) }.to_vec();
unsafe {
if !out_blob.pbData.is_null() {
LocalFree(out_blob.pbData as HLOCAL);
}
}
Ok(slice)
}

View File

@@ -0,0 +1,262 @@
//! Framed IPC protocol used between the parent (CLI) and the elevated command runner.
//!
//! This module defines the JSON message schema (spawn request/ready, output, stdin,
//! exit, error, terminate) plus length‑prefixed framing helpers for a byte stream.
//! It is **elevated-path only**: the parent uses it to bootstrap the runner and
//! stream unified_exec I/O over named pipes. The legacy restricted‑token path does
//! not use this protocol, and non‑unified exec capture uses it only when running
//! through the elevated runner.
use anyhow::Result;
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD;
use akode_protocol::models::PermissionProfile;
use akode_utils_absolute_path::AbsolutePathBuf;
use serde::Deserialize;
use serde::Serialize;
use std::collections::HashMap;
use std::io::Read;
use std::io::Write;
use std::path::PathBuf;
/// Protocol version shared by the parent process and elevated command runner.
pub const IPC_PROTOCOL_VERSION: u8 = 6;
/// Length-prefixed, JSON-encoded frame.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct FramedMessage {
pub version: u8,
#[serde(flatten)]
pub message: Message,
}
/// IPC message variants exchanged between parent and runner.
///
/// `SpawnRequest`, `Stdin`, `CloseStdin`, `Resize`, and `Terminate` are parent->runner commands.
/// `SpawnReady`, `Output`, `Exit`, and `Error` are runner->parent events/results.
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Message {
SpawnRequest { payload: Box<SpawnRequest> },
SpawnReady { payload: SpawnReady },
Output { payload: OutputPayload },
Stdin { payload: StdinPayload },
CloseStdin { payload: EmptyPayload },
Resize { payload: ResizePayload },
Exit { payload: ExitPayload },
Error { payload: ErrorPayload },
Terminate { payload: EmptyPayload },
}
/// Spawn parameters sent from parent to runner.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct SpawnRequest {
pub command: Vec<String>,
pub cwd: PathBuf,
pub env: HashMap<String, String>,
pub permission_profile: PermissionProfile,
pub workspace_roots: Vec<AbsolutePathBuf>,
pub codex_home: PathBuf,
pub real_codex_home: PathBuf,
pub cap_sids: Vec<String>,
/// Optional managed-network identity added only to the child's restricting SID set.
#[serde(default)]
pub network_proxy_restricting_sid: Option<String>,
pub timeout_ms: Option<u64>,
pub tty: bool,
#[serde(default)]
pub stdin_open: bool,
/// Private desktop kept alive by the parent across command runners.
pub private_desktop_name: Option<String>,
}
/// Ack from runner after it spawns the child process.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct SpawnReady {
pub process_id: u32,
}
/// Output data sent from runner to parent.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct OutputPayload {
pub data_b64: String,
pub stream: OutputStream,
}
/// Output stream identifier for `OutputPayload`.
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum OutputStream {
Stdout,
Stderr,
}
/// Stdin bytes sent from parent to runner.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct StdinPayload {
pub data_b64: String,
}
/// PTY resize request sent from parent to runner.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ResizePayload {
pub rows: u16,
pub cols: u16,
}
/// Exit status sent from runner to parent.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ExitPayload {
pub exit_code: i32,
pub timed_out: bool,
}
/// Error payload sent when the runner fails to spawn or stream.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ErrorPayload {
pub message: String,
pub stage: ErrorStage,
pub windows_error_code: Option<u32>,
}
/// Runner startup stage that produced an error.
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ErrorStage {
ReadSpawnRequest,
SpawnChild,
WriteSpawnReady,
}
/// Empty payload for control messages.
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct EmptyPayload {}
/// Base64-encode raw bytes for IPC payloads.
pub fn encode_bytes(data: &[u8]) -> String {
STANDARD.encode(data)
}
/// Decode base64 payload data into raw bytes.
pub fn decode_bytes(data: &str) -> Result<Vec<u8>> {
Ok(STANDARD.decode(data.as_bytes())?)
}
/// Write a length-prefixed JSON frame.
pub fn write_frame<W: Write>(writer: W, msg: &FramedMessage) -> Result<()> {
crate::framed_io::write_frame(writer, msg)
}
/// Read a length-prefixed JSON frame; returns `Ok(None)` on EOF.
pub fn read_frame<R: Read>(reader: R) -> Result<Option<FramedMessage>> {
crate::framed_io::read_frame(reader)
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn framed_round_trip() {
let msg = FramedMessage {
version: IPC_PROTOCOL_VERSION,
message: Message::Output {
payload: OutputPayload {
data_b64: encode_bytes(b"hello"),
stream: OutputStream::Stdout,
},
},
};
let mut buf = Vec::new();
write_frame(&mut buf, &msg).expect("write");
let decoded = read_frame(buf.as_slice()).expect("read").expect("some");
assert_eq!(decoded.version, IPC_PROTOCOL_VERSION);
match decoded.message {
Message::Output { payload } => {
assert_eq!(payload.stream, OutputStream::Stdout);
let data = decode_bytes(&payload.data_b64).expect("decode");
assert_eq!(data, b"hello");
}
other => panic!("unexpected message: {other:?}"),
}
}
#[test]
fn spawn_request_serializes_permission_profile() {
let workspace_roots = vec![
AbsolutePathBuf::from_absolute_path(PathBuf::from(r"C:\workspace"))
.expect("absolute workspace root"),
];
let msg = FramedMessage {
version: IPC_PROTOCOL_VERSION,
message: Message::SpawnRequest {
payload: Box::new(SpawnRequest {
command: vec!["cmd.exe".to_string(), "/c".to_string(), "ver".to_string()],
cwd: PathBuf::from(r"C:\workspace"),
env: HashMap::new(),
permission_profile: PermissionProfile::read_only(),
workspace_roots: workspace_roots.clone(),
codex_home: PathBuf::from(r"C:\codex"),
real_codex_home: PathBuf::from(r"C:\Users\codex"),
cap_sids: vec!["S-1-15-3-1024-1".to_string()],
network_proxy_restricting_sid: Some("S-1-5-21-100-200-300-400".to_string()),
timeout_ms: Some(1000),
tty: false,
stdin_open: false,
private_desktop_name: Some("CodexSandboxDesktop-1234".to_string()),
}),
},
};
let encoded = serde_json::to_value(&msg).expect("serialize");
assert_eq!("spawn_request", encoded["type"]);
assert_eq!("managed", encoded["payload"]["permission_profile"]["type"]);
assert_eq!(None, encoded["payload"].get("policy_json_or_preset"));
assert_eq!(None, encoded["payload"].get("sandbox_policy_cwd"));
assert_eq!(None, encoded["payload"].get("permission_profile_cwd"));
let decoded: FramedMessage = serde_json::from_value(encoded).expect("deserialize");
let Message::SpawnRequest { payload } = decoded.message else {
panic!("unexpected message");
};
assert_eq!(PermissionProfile::read_only(), payload.permission_profile);
assert_eq!(workspace_roots, payload.workspace_roots);
assert_eq!(
Some("CodexSandboxDesktop-1234"),
payload.private_desktop_name.as_deref()
);
assert_eq!(
Some("S-1-5-21-100-200-300-400"),
payload.network_proxy_restricting_sid.as_deref()
);
}
#[test]
fn error_payload_serializes_stage_and_windows_error_code() {
let msg = FramedMessage {
version: IPC_PROTOCOL_VERSION,
message: Message::Error {
payload: ErrorPayload {
message: "CreateProcessAsUserW failed".to_string(),
stage: ErrorStage::SpawnChild,
windows_error_code: Some(1312),
},
},
};
let encoded = serde_json::to_value(&msg).expect("serialize");
assert_eq!(
serde_json::json!({
"version": IPC_PROTOCOL_VERSION,
"type": "error",
"payload": {
"message": "CreateProcessAsUserW failed",
"stage": "spawn_child",
"windows_error_code": 1312,
}
}),
encoded
);
}
}

View File

@@ -0,0 +1,4 @@
pub(crate) mod ipc_framed;
pub(crate) mod runner_client;
pub(crate) mod runner_metrics;
pub(crate) mod runner_pipe;

View File

@@ -0,0 +1,643 @@
use crate::app_package::registered_core_requested;
use crate::app_package::verify_registered_core_runner;
use crate::desktop::DesktopPolicy;
use crate::desktop::shared_private_desktop_for_user;
use crate::identity::SandboxCreds;
use crate::ipc_framed::ErrorPayload;
use crate::ipc_framed::ErrorStage;
use crate::ipc_framed::FramedMessage;
use crate::ipc_framed::IPC_PROTOCOL_VERSION;
use crate::ipc_framed::Message;
use crate::ipc_framed::SpawnRequest;
use crate::ipc_framed::read_frame;
use crate::ipc_framed::write_frame;
use crate::runner_pipe::PIPE_ACCESS_INBOUND;
use crate::runner_pipe::PIPE_ACCESS_OUTBOUND;
use crate::runner_pipe::connect_pipe;
use crate::runner_pipe::create_named_pipe;
use crate::runner_pipe::find_runner_exe;
use crate::runner_pipe::pipe_pair;
use crate::winutil::quote_windows_arg;
use crate::winutil::to_wide;
use anyhow::Context;
use anyhow::Result;
use std::fs::File;
use std::os::windows::io::AsRawHandle;
use std::os::windows::io::FromRawHandle;
use std::os::windows::io::OwnedHandle;
use std::path::Path;
use std::ptr;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use std::time::Instant;
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::Foundation::DUPLICATE_SAME_ACCESS;
use windows_sys::Win32::Foundation::DuplicateHandle;
use windows_sys::Win32::Foundation::ERROR_ACCOUNT_DISABLED;
use windows_sys::Win32::Foundation::ERROR_LOGON_FAILURE;
use windows_sys::Win32::Foundation::ERROR_NO_SUCH_LOGON_SESSION;
use windows_sys::Win32::Foundation::ERROR_NOT_FOUND;
use windows_sys::Win32::Foundation::ERROR_SERVICE_ALREADY_RUNNING;
use windows_sys::Win32::Foundation::GetLastError;
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::System::Diagnostics::Debug::SetErrorMode;
use windows_sys::Win32::System::IO::CancelSynchronousIo;
use windows_sys::Win32::System::Threading::CreateProcessWithLogonW;
use windows_sys::Win32::System::Threading::GetCurrentProcess;
use windows_sys::Win32::System::Threading::GetCurrentThread;
use windows_sys::Win32::System::Threading::LOGON_WITH_PROFILE;
use windows_sys::Win32::System::Threading::PROCESS_INFORMATION;
use windows_sys::Win32::System::Threading::STARTF_FORCEOFFFEEDBACK;
use windows_sys::Win32::System::Threading::STARTUPINFOW;
use windows_sys::Win32::System::Threading::TerminateProcess;
use windows_sys::Win32::System::Threading::WaitForSingleObject;
const RUNNER_SPAWN_READY_TIMEOUT: Duration = Duration::from_secs(15);
const RUNNER_PIPE_CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
const RUNNER_ERROR_MODE_FLAGS: u32 = 0x0001 | 0x0002;
const WAIT_OBJECT_0: u32 = 0;
struct NonOwningHandle(HANDLE);
// SAFETY: Pipe and thread handles are opaque process-wide tokens that may be
// passed between threads. This wrapper does not own or extend their lifetime.
unsafe impl Send for NonOwningHandle {}
impl NonOwningHandle {
fn raw(&self) -> HANDLE {
self.0
}
}
#[derive(Debug)]
pub(crate) struct RunnerLogonError {
pub(crate) code: u32,
}
impl std::fmt::Display for RunnerLogonError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "CreateProcessWithLogonW failed: {}", self.code)
}
}
impl std::error::Error for RunnerLogonError {}
#[derive(Debug)]
pub(crate) struct RunnerStartupError {
payload: ErrorPayload,
}
impl RunnerStartupError {
pub(crate) fn new(payload: ErrorPayload) -> Self {
Self { payload }
}
}
impl std::fmt::Display for RunnerStartupError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"runner failed during {:?}: {}",
self.payload.stage, self.payload.message
)?;
if let Some(code) = self.payload.windows_error_code {
write!(f, " (Windows error {code})")?;
}
Ok(())
}
}
impl std::error::Error for RunnerStartupError {}
pub(crate) struct RunnerTransport {
pipe_write: File,
pipe_read: File,
}
fn is_refreshable_windows_error(code: u32) -> bool {
matches!(
code,
ERROR_ACCOUNT_DISABLED | ERROR_LOGON_FAILURE | ERROR_NO_SUCH_LOGON_SESSION
)
}
fn command_targets_windows_apps(command: &[String]) -> bool {
command.first().is_some_and(|program| {
Path::new(program).components().any(|component| {
component
.as_os_str()
.to_string_lossy()
.eq_ignore_ascii_case("WindowsApps")
})
})
}
pub(crate) fn is_refreshable_sandbox_creds_error(err: &anyhow::Error, command: &[String]) -> bool {
if err
.downcast_ref::<RunnerLogonError>()
.is_some_and(|err| is_refreshable_windows_error(err.code))
{
return true;
}
err.downcast_ref::<RunnerStartupError>().is_some_and(|err| {
err.payload.stage == ErrorStage::SpawnChild
&& err.payload.windows_error_code.is_some_and(|code| {
// AppX activation can return 1312 for a healthy sandbox token. Rotating the
// account password cannot make the same WindowsApps command launch.
is_refreshable_windows_error(code)
&& (code != ERROR_NO_SUCH_LOGON_SESSION
|| !command_targets_windows_apps(command))
})
})
}
pub(crate) fn retry_runner_spawn_once<T>(
sandbox_creds: SandboxCreds,
command: &[String],
mut spawn: impl FnMut(SandboxCreds) -> Result<T>,
refresh: impl FnOnce() -> Result<SandboxCreds>,
) -> Result<T> {
let result = match spawn(sandbox_creds.clone()) {
Ok(result) => Ok(result),
// No runner (and therefore no user command) started. Keep credentials unchanged.
Err(err)
if err
.downcast_ref::<RunnerLogonError>()
.is_some_and(|err| err.code == ERROR_SERVICE_ALREADY_RUNNING) =>
{
spawn(sandbox_creds)
}
Err(err) if is_refreshable_sandbox_creds_error(&err, command) => refresh().and_then(spawn),
Err(err) => Err(err),
};
super::runner_metrics::record("startup", if result.is_ok() { "success" } else { "error" });
result
}
impl RunnerTransport {
pub(crate) fn send_spawn_request(&mut self, request: SpawnRequest) -> Result<()> {
let spawn_request = FramedMessage {
version: IPC_PROTOCOL_VERSION,
message: Message::SpawnRequest {
payload: Box::new(request),
},
};
write_frame(&mut self.pipe_write, &spawn_request)
}
pub(crate) fn read_spawn_ready(&mut self) -> Result<()> {
crate::framed_io::wait_for_complete_frame(
&self.pipe_read,
Instant::now() + RUNNER_SPAWN_READY_TIMEOUT,
)
.context("wait for runner spawn_ready")?;
let msg = read_frame(&mut self.pipe_read)?
.ok_or_else(|| anyhow::anyhow!("runner pipe closed before spawn_ready"))?;
match msg.message {
Message::SpawnReady { .. } => Ok(()),
Message::Error { payload } => Err(RunnerStartupError::new(payload).into()),
other => Err(anyhow::anyhow!(
"expected spawn_ready from runner, got {other:?}"
)),
}
}
pub(crate) fn into_files(self) -> (File, File) {
(self.pipe_write, self.pipe_read)
}
}
fn try_take_completed_connect_result(
connect_thread: &mut Option<thread::JoinHandle<()>>,
connect_result_rx: &mpsc::Receiver<Result<()>>,
thread_handle: HANDLE,
pipe_label: &str,
) -> Result<Option<Result<()>>> {
let thread_wait = unsafe { WaitForSingleObject(thread_handle, 0) };
if thread_wait != WAIT_OBJECT_0 {
return Ok(None);
}
if let Some(connect_thread) = connect_thread.take() {
let _ = connect_thread.join();
}
let result = connect_result_rx.recv().map_err(|_| {
anyhow::anyhow!("runner {pipe_label} connect thread exited before reporting its result")
})?;
Ok(Some(result))
}
fn connect_pipe_with_timeout(
h_pipe: HANDLE,
expected_runner_pid: u32,
pipe_label: &str,
) -> Result<()> {
let pipe_label = pipe_label.to_string();
let pipe_label_for_thread = pipe_label.clone();
let (thread_handle_tx, thread_handle_rx) = mpsc::sync_channel(1);
let (connect_result_tx, connect_result_rx) = mpsc::sync_channel(1);
let h_pipe = NonOwningHandle(h_pipe);
let mut connect_thread = Some(
thread::Builder::new()
.name(format!("codex-runner-connect-{pipe_label}"))
.spawn(move || {
let current_process = unsafe { GetCurrentProcess() };
let mut thread_handle = std::ptr::null_mut();
let duplicate_ok = unsafe {
DuplicateHandle(
current_process,
GetCurrentThread(),
current_process,
&mut thread_handle,
0,
0,
DUPLICATE_SAME_ACCESS,
)
};
if duplicate_ok == 0 {
let _ = thread_handle_tx.send(Err(anyhow::anyhow!(
"DuplicateHandle failed for runner {pipe_label_for_thread} connect thread: {}",
unsafe { GetLastError() }
)));
return;
}
// Publish the helper thread HANDLE before the blocking pipe connect so the
// parent can cancel this specific operation if it times out.
let _ = thread_handle_tx.send(Ok(NonOwningHandle(thread_handle)));
let result = connect_pipe(h_pipe.raw(), expected_runner_pid)
.map_err(anyhow::Error::from)
.context(format!("connect {pipe_label_for_thread}"));
let _ = connect_result_tx.send(result);
})?,
);
let thread_handle = thread_handle_rx.recv().map_err(|_| {
anyhow::anyhow!("runner {pipe_label} connect thread exited before publishing its handle")
})??;
let result = match connect_result_rx.recv_timeout(RUNNER_PIPE_CONNECT_TIMEOUT) {
Ok(result) => {
if let Some(connect_thread) = connect_thread.take() {
let _ = connect_thread.join();
}
result
}
Err(mpsc::RecvTimeoutError::Timeout) => {
if let Some(result) = try_take_completed_connect_result(
&mut connect_thread,
&connect_result_rx,
thread_handle.raw(),
&pipe_label,
)? {
result
} else {
let cancel_ok = unsafe { CancelSynchronousIo(thread_handle.raw()) };
if cancel_ok == 0 {
let err = unsafe { GetLastError() };
if err != ERROR_NOT_FOUND {
Err(anyhow::anyhow!(
"CancelSynchronousIo failed for runner {pipe_label} connect thread: {err}"
))
} else if let Some(result) = try_take_completed_connect_result(
&mut connect_thread,
&connect_result_rx,
thread_handle.raw(),
&pipe_label,
)? {
result
} else {
Err(anyhow::anyhow!(
"timed out after {}ms connecting runner {pipe_label}",
RUNNER_PIPE_CONNECT_TIMEOUT.as_millis()
))
}
} else {
// Do not join the helper thread on the timeout path. Parent-side cleanup will
// close the pipe handles, which lets the blocked connect unwind without
// risking another indefinite wait here.
Err(anyhow::anyhow!(
"timed out after {}ms connecting runner {pipe_label}",
RUNNER_PIPE_CONNECT_TIMEOUT.as_millis()
))
}
}
}
Err(mpsc::RecvTimeoutError::Disconnected) => {
if let Some(connect_thread) = connect_thread.take() {
let _ = connect_thread.join();
}
Err(anyhow::anyhow!(
"runner {pipe_label} connect thread exited before reporting its result"
))
}
};
unsafe {
CloseHandle(thread_handle.raw());
}
result
}
pub(crate) fn spawn_runner_transport(
codex_home: &Path,
cwd: &Path,
sandbox_creds: &SandboxCreds,
log_dir: Option<&Path>,
mut spawn_request: SpawnRequest,
desktop_policy: Option<&DesktopPolicy>,
) -> Result<RunnerTransport> {
let runner_exe = find_runner_exe(codex_home, log_dir)?;
let registered_alias = if registered_core_requested() {
Some(crate::app_package::registered_runner_alias(
codex_home,
&sandbox_creds.username,
)?)
} else {
None
};
if let Some(policy) = desktop_policy {
spawn_request.private_desktop_name = Some(shared_private_desktop_for_user(
&sandbox_creds.username,
policy,
log_dir,
)?);
}
let (pipe_in_name, pipe_out_name) = pipe_pair();
let pipe_write = unsafe {
File::from_raw_handle(create_named_pipe(
&pipe_in_name,
PIPE_ACCESS_OUTBOUND,
&sandbox_creds.username,
)? as _)
};
let pipe_read = unsafe {
File::from_raw_handle(create_named_pipe(
&pipe_out_name,
PIPE_ACCESS_INBOUND,
&sandbox_creds.username,
)? as _)
};
let h_pipe_in = pipe_write.as_raw_handle() as HANDLE;
let h_pipe_out = pipe_read.as_raw_handle() as HANDLE;
let runner_cmdline = registered_alias
.as_deref()
.unwrap_or(&runner_exe)
.to_str()
.map(str::to_owned)
.unwrap_or_else(|| "akode-command-runner.exe".to_string());
let runner_full_cmd = format!(
"{} {} {}",
quote_windows_arg(&runner_cmdline),
quote_windows_arg(&format!("--pipe-in={pipe_in_name}")),
quote_windows_arg(&format!("--pipe-out={pipe_out_name}"))
);
let mut cmdline_vec = to_wide(&runner_full_cmd);
let exe_w = to_wide(&runner_cmdline);
let cwd_w = to_wide(cwd);
let user_w = to_wide(&sandbox_creds.username);
let domain_w = to_wide(".");
let password_w = to_wide(&sandbox_creds.password);
let mut si: STARTUPINFOW = unsafe { std::mem::zeroed() };
si.cb = std::mem::size_of::<STARTUPINFOW>() as u32;
si.dwFlags = STARTF_FORCEOFFFEEDBACK;
let mut pi: PROCESS_INFORMATION = unsafe { std::mem::zeroed() };
let previous_error_mode = unsafe { SetErrorMode(RUNNER_ERROR_MODE_FLAGS) };
// Execution aliases require the registered account's profile.
// Other launches retain their existing profile-free behavior.
let spawn_res = unsafe {
CreateProcessWithLogonW(
user_w.as_ptr(),
domain_w.as_ptr(),
password_w.as_ptr(),
if registered_alias.is_some() {
LOGON_WITH_PROFILE
} else {
0
},
exe_w.as_ptr(),
cmdline_vec.as_mut_ptr(),
windows_sys::Win32::System::Threading::CREATE_NO_WINDOW
| windows_sys::Win32::System::Threading::CREATE_UNICODE_ENVIRONMENT,
ptr::null(),
cwd_w.as_ptr(),
&si,
&mut pi,
)
};
// Preserve the failure code before SetErrorMode can overwrite it.
let spawn_error = (spawn_res == 0).then(|| unsafe { GetLastError() });
unsafe {
SetErrorMode(previous_error_mode);
}
if let Some(err) = spawn_error {
return Err(RunnerLogonError { code: err }.into());
}
// Keep the process pinned through the entire startup handshake. Pipes close
// automatically on every error, including failure to create the second pipe.
let _runner_process = unsafe { OwnedHandle::from_raw_handle(pi.hProcess as _) };
let _runner_thread = unsafe { OwnedHandle::from_raw_handle(pi.hThread as _) };
let expected_runner_pid = pi.dwProcessId;
let mut transport = RunnerTransport {
pipe_write,
pipe_read,
};
let startup_result = (|| -> Result<()> {
// An update can retarget the alias after setup. Check the selected image
// and authenticate its pipes before sending it the command.
if registered_alias.is_some() {
verify_registered_core_runner(pi.hProcess, &runner_exe)?;
}
connect_pipe_with_timeout(h_pipe_in, expected_runner_pid, "pipe-in")?;
connect_pipe_with_timeout(h_pipe_out, expected_runner_pid, "pipe-out")?;
transport.send_spawn_request(spawn_request)?;
transport.read_spawn_ready()?;
Ok(())
})();
if let Err(err) = startup_result {
unsafe {
let _ = TerminateProcess(pi.hProcess, 1);
}
return Err(err);
}
if registered_alias.is_some() {
crate::logging::debug_log(
&format!(
"registered_core_runner_ready pid={expected_runner_pid} package_verified=true pipes_authenticated=true"
),
log_dir,
);
}
Ok(transport)
}
#[cfg(test)]
mod tests {
use super::RunnerLogonError;
use super::RunnerStartupError;
use super::is_refreshable_sandbox_creds_error;
use super::retry_runner_spawn_once;
use crate::identity::SandboxCreds;
use crate::ipc_framed::ErrorPayload;
use crate::ipc_framed::ErrorStage;
use pretty_assertions::assert_eq;
use windows_sys::Win32::Foundation::ERROR_ACCOUNT_DISABLED;
use windows_sys::Win32::Foundation::ERROR_LOGON_FAILURE;
use windows_sys::Win32::Foundation::ERROR_NO_SUCH_LOGON_SESSION;
use windows_sys::Win32::Foundation::ERROR_NOT_FOUND;
use windows_sys::Win32::Foundation::ERROR_SERVICE_ALREADY_RUNNING;
#[test]
fn logon_service_already_running_retries_once_without_refresh() {
let mut attempts = 0;
let result = retry_runner_spawn_once(
SandboxCreds {
username: "sandbox-user".into(),
password: "test-only".into(),
},
&[],
|creds| {
attempts += 1;
assert_eq!(
(creds.username.as_str(), creds.password.as_str()),
("sandbox-user", "test-only")
);
if attempts == 1 {
Err(anyhow::Error::new(RunnerLogonError {
code: ERROR_SERVICE_ALREADY_RUNNING,
})
.context("runner launch failed"))
} else {
Ok(42)
}
},
|| panic!("1056 must not refresh credentials"),
);
assert_eq!((result.unwrap(), attempts), (42, 2));
}
#[test]
fn logon_service_already_running_stops_after_two_failures() {
let mut attempts = 0;
let err = retry_runner_spawn_once::<()>(
SandboxCreds {
username: "sandbox-user".into(),
password: "test-only".into(),
},
&[],
|_| {
attempts += 1;
Err(RunnerLogonError {
code: ERROR_SERVICE_ALREADY_RUNNING,
}
.into())
},
|| panic!("1056 must not refresh credentials"),
)
.unwrap_err();
assert_eq!(
(
attempts,
err.downcast_ref::<RunnerLogonError>().unwrap().code
),
(2, ERROR_SERVICE_ALREADY_RUNNING)
);
}
#[test]
fn child_service_already_running_does_not_replay_command() {
let mut attempts = 0;
let err = retry_runner_spawn_once::<()>(
SandboxCreds {
username: "sandbox-user".into(),
password: "test-only".into(),
},
&[],
|_| {
attempts += 1;
Err(RunnerStartupError::new(ErrorPayload {
message: "child startup failed".into(),
stage: ErrorStage::SpawnChild,
windows_error_code: Some(ERROR_SERVICE_ALREADY_RUNNING),
})
.into())
},
|| panic!("1056 must not refresh credentials"),
)
.unwrap_err();
assert_eq!(
(
attempts,
err.downcast_ref::<RunnerStartupError>()
.unwrap()
.payload
.windows_error_code,
),
(1, Some(ERROR_SERVICE_ALREADY_RUNNING))
);
}
#[test]
fn refreshable_sandbox_creds_error_recognizes_credential_and_child_start_failures() {
assert_eq!(
[
ERROR_ACCOUNT_DISABLED,
ERROR_LOGON_FAILURE,
ERROR_NO_SUCH_LOGON_SESSION,
ERROR_NOT_FOUND,
]
.map(|code| {
let err =
anyhow::Error::new(RunnerLogonError { code }).context("runner launch failed");
is_refreshable_sandbox_creds_error(&err, &[])
}),
[true, true, true, false]
);
assert_eq!(
[
(ErrorStage::SpawnChild, ERROR_NO_SUCH_LOGON_SESSION),
(ErrorStage::SpawnChild, ERROR_NOT_FOUND),
(ErrorStage::ReadSpawnRequest, ERROR_NO_SUCH_LOGON_SESSION),
]
.map(|(stage, windows_error_code)| {
let err = anyhow::Error::new(RunnerStartupError::new(ErrorPayload {
message: "runner startup failed".to_string(),
stage,
windows_error_code: Some(windows_error_code),
}));
is_refreshable_sandbox_creds_error(&err, &["cmd.exe".to_string()])
}),
[true, false, false]
);
let windows_apps_commands = [
vec![
r"C:\Users\user\AppData\Local\Microsoft\WindowsApps\pwsh.exe".to_string(),
],
vec![
r"C:\Program Files\WindowsApps\Microsoft.PowerShell_7.6.3.0_x64__8wekyb3d8bbwe\pwsh.exe"
.to_string(),
],
];
assert_eq!(
windows_apps_commands.map(|command| {
let err = anyhow::Error::new(RunnerStartupError::new(ErrorPayload {
message: "runner startup failed".to_string(),
stage: ErrorStage::SpawnChild,
windows_error_code: Some(ERROR_NO_SUCH_LOGON_SESSION),
}));
is_refreshable_sandbox_creds_error(&err, &command)
}),
[false, false]
);
}
}

View File

@@ -0,0 +1,35 @@
//! Compare registered and legacy runner outcomes at the actual local execution boundary.
//! Startup is counted once after credential retry; commands are counted on exit or pipe failure.
pub(crate) fn record(phase: &'static str, outcome: &'static str) {
let runtime = if crate::app_package::registered_core_requested() {
"registered"
} else {
"legacy"
};
if let Some(metrics) = akode_otel::global() {
// Fixed labels only: never send command text, paths, or arbitrary error messages.
let _ = metrics.counter(
"codex.windows_sandbox.runner_result",
/*inc*/ 1,
&[("runtime", runtime), ("phase", phase), ("outcome", outcome)],
);
}
}
pub(crate) fn record_command(exit: Option<(i32, bool)>) {
record("command", command_outcome(exit));
}
fn command_outcome(exit: Option<(i32, bool)>) -> &'static str {
match exit {
Some((_, true)) => "timeout",
Some((0, false)) => "success",
Some((_, false)) => "nonzero_exit",
None => "transport_error",
}
}
#[cfg(test)]
#[path = "runner_metrics_tests.rs"]
mod tests;

View File

@@ -0,0 +1,27 @@
//! Keep command outcomes distinct without publishing arbitrary exit-code metric labels.
use super::command_outcome;
use pretty_assertions::assert_eq;
#[test]
fn command_results_distinguish_timeouts_transport_errors_and_nonzero_exits() {
assert_eq!(
[
Some((0, false)),
Some((1, false)),
Some((0xc0000135u32 as i32, false)), // Windows DLL-not-found status.
Some((0, true)),
Some((1, true)),
None,
]
.map(command_outcome),
[
"success",
"nonzero_exit",
"nonzero_exit",
"timeout",
"timeout",
"transport_error",
]
);
}

View File

@@ -0,0 +1,133 @@
//! Named pipe helpers for the elevated Windows sandbox runner.
//!
//! This module generates paired pipe names, creates server‑side pipes with
//! sandbox-user-scoped ACLs, and waits for the runner to connect. It is
//! **elevated-path only** and is
//! used by the parent to establish the IPC channel for both unified_exec sessions
//! and elevated capture. The legacy restricted‑token path spawns the child directly
//! and does not use these helpers.
use crate::helper_materialization::resolve_command_runner;
use crate::winutil::resolve_sid;
use crate::winutil::string_from_sid_bytes;
use crate::winutil::to_wide;
use rand::Rng;
use rand::SeedableRng;
use rand::rngs::SmallRng;
use std::io;
use std::path::Path;
use std::path::PathBuf;
use std::ptr;
use windows_sys::Win32::Foundation::GetLastError;
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::Foundation::HLOCAL;
use windows_sys::Win32::Foundation::LocalFree;
use windows_sys::Win32::Security::Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW;
use windows_sys::Win32::Security::PSECURITY_DESCRIPTOR;
use windows_sys::Win32::Security::SECURITY_ATTRIBUTES;
use windows_sys::Win32::System::Pipes::ConnectNamedPipe;
use windows_sys::Win32::System::Pipes::CreateNamedPipeW;
use windows_sys::Win32::System::Pipes::GetNamedPipeClientProcessId;
use windows_sys::Win32::System::Pipes::PIPE_READMODE_BYTE;
use windows_sys::Win32::System::Pipes::PIPE_TYPE_BYTE;
use windows_sys::Win32::System::Pipes::PIPE_WAIT;
/// PIPE_ACCESS_INBOUND (win32 constant), not exposed in windows-sys 0.52.
pub const PIPE_ACCESS_INBOUND: u32 = 0x0000_0001;
/// PIPE_ACCESS_OUTBOUND (win32 constant), not exposed in windows-sys 0.52.
pub const PIPE_ACCESS_OUTBOUND: u32 = 0x0000_0002;
/// Resolve the installed runner for registered Core; otherwise use the legacy copy path.
pub fn find_runner_exe(codex_home: &Path, log_dir: Option<&Path>) -> anyhow::Result<PathBuf> {
resolve_command_runner(codex_home, log_dir)
}
/// Generates a unique named-pipe path used to communicate with the runner process.
pub fn pipe_pair() -> (String, String) {
let mut rng = SmallRng::from_entropy();
let nonce: u128 = rng.r#gen();
let base = format!(r"\\.\pipe\codex-runner-{nonce:x}");
(format!("{base}-in"), format!("{base}-out"))
}
/// Creates a named pipe whose DACL only allows the sandbox user to connect.
pub fn create_named_pipe(name: &str, access: u32, sandbox_username: &str) -> io::Result<HANDLE> {
let sandbox_sid = resolve_sid(sandbox_username)
.map_err(|err| io::Error::new(io::ErrorKind::PermissionDenied, err.to_string()))?;
let sandbox_sid = string_from_sid_bytes(&sandbox_sid)
.map_err(|err| io::Error::new(io::ErrorKind::PermissionDenied, err))?;
let sddl = to_wide(format!("D:(A;;GA;;;{sandbox_sid})"));
let mut sd: PSECURITY_DESCRIPTOR = ptr::null_mut();
let ok = unsafe {
ConvertStringSecurityDescriptorToSecurityDescriptorW(
sddl.as_ptr(),
1, // SDDL_REVISION_1
&mut sd,
ptr::null_mut(),
)
};
if ok == 0 {
return Err(io::Error::from_raw_os_error(unsafe {
GetLastError() as i32
}));
}
let mut sa = SECURITY_ATTRIBUTES {
nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
lpSecurityDescriptor: sd,
bInheritHandle: 0,
};
let wide = to_wide(name);
let h = unsafe {
CreateNamedPipeW(
wide.as_ptr(),
access,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
1,
65536,
65536,
0,
&mut sa as *mut SECURITY_ATTRIBUTES,
)
};
unsafe {
LocalFree(sd as HLOCAL);
}
if h.is_null() || h == windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE {
return Err(io::Error::from_raw_os_error(unsafe {
GetLastError() as i32
}));
}
Ok(h)
}
/// Waits for the runner to connect to a parent-created server pipe.
///
/// This is parent-side only: the runner opens the pipe with `CreateFileW`, while the
/// parent calls `ConnectNamedPipe`, tolerates the already-connected case, and
/// verifies that the connected client is the runner process we just spawned.
pub fn connect_pipe(h: HANDLE, expected_runner_pid: u32) -> io::Result<()> {
let ok = unsafe { ConnectNamedPipe(h, ptr::null_mut()) };
if ok == 0 {
let err = unsafe { GetLastError() };
const ERROR_PIPE_CONNECTED: u32 = 535;
if err != ERROR_PIPE_CONNECTED {
return Err(io::Error::from_raw_os_error(err as i32));
}
}
let mut client_pid = 0;
let ok = unsafe { GetNamedPipeClientProcessId(h, &mut client_pid) };
if ok == 0 {
return Err(io::Error::from_raw_os_error(unsafe {
GetLastError() as i32
}));
}
if client_pid != expected_runner_pid {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
format!(
"named pipe client pid {client_pid} did not match runner pid {expected_runner_pid}"
),
));
}
Ok(())
}

View File

@@ -0,0 +1,332 @@
use akode_protocol::models::PermissionProfile;
use akode_utils_absolute_path::AbsolutePathBuf;
use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;
pub struct ElevatedSandboxProfileCaptureRequest<'a> {
pub permission_profile: &'a PermissionProfile,
pub workspace_roots: &'a [AbsolutePathBuf],
pub codex_home: &'a Path,
pub command: Vec<String>,
pub cwd: &'a Path,
pub env_map: HashMap<String, String>,
pub timeout_ms: Option<u64>,
pub cancellation: Option<crate::WindowsSandboxCancellationToken>,
pub proxy_enforced: bool,
pub network_proxy_restricting_sid: Option<String>,
pub read_roots_override: Option<&'a [PathBuf]>,
pub read_roots_include_platform_defaults: bool,
pub write_roots_override: Option<&'a [PathBuf]>,
pub deny_read_paths_override: &'a [AbsolutePathBuf],
pub deny_write_paths_override: &'a [AbsolutePathBuf],
}
mod windows_impl {
use super::ElevatedSandboxProfileCaptureRequest;
use crate::acl::allow_null_device;
use crate::cap::load_or_create_cap_sids;
use crate::cap::workspace_write_cap_sid_for_root;
use crate::env::ensure_non_interactive_pager;
use crate::env::inherit_path_env;
use crate::env::normalize_null_device_env;
use crate::identity::refresh_logon_sandbox_creds;
use crate::identity::require_logon_sandbox_creds;
use crate::ipc_framed::EmptyPayload;
use crate::ipc_framed::FramedMessage;
use crate::ipc_framed::Message;
use crate::ipc_framed::OutputStream;
use crate::ipc_framed::SpawnRequest;
use crate::ipc_framed::decode_bytes;
use crate::ipc_framed::read_frame;
use crate::ipc_framed::write_frame;
use crate::logging::log_failure;
use crate::logging::log_start;
use crate::logging::log_success;
use crate::resolved_permissions::ResolvedWindowsSandboxPermissions;
use crate::runner_client::retry_runner_spawn_once;
use crate::runner_client::spawn_runner_transport;
use crate::sandbox_utils::ensure_codex_home_exists;
use crate::sandbox_utils::inject_git_safe_directory;
use crate::setup::effective_write_roots_for_permissions;
use crate::token::LocalSid;
use anyhow::Result;
use akode_utils_absolute_path::AbsolutePathBuf;
use std::fs::File;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::time::Duration;
pub use crate::windows_impl::CaptureResult;
/// Polls for cancellation and sends the runner's terminate IPC frame when requested.
///
/// The 50 ms park bounds cancellation latency without busy-waiting.
fn spawn_cancel_writer(
pipe_write: &File,
cancellation: Option<crate::WindowsSandboxCancellationToken>,
) -> Result<Option<(std::thread::JoinHandle<()>, Arc<AtomicBool>)>> {
let Some(cancellation) = cancellation else {
return Ok(None);
};
let mut pipe_write = pipe_write.try_clone()?;
let done = Arc::new(AtomicBool::new(false));
let done_for_thread = Arc::clone(&done);
let handle = std::thread::spawn(move || {
while !done_for_thread.load(Ordering::SeqCst) {
if cancellation.is_cancelled() {
let _ = write_frame(
&mut pipe_write,
&FramedMessage {
version: 1,
message: Message::Terminate {
payload: EmptyPayload::default(),
},
},
);
break;
}
std::thread::park_timeout(Duration::from_millis(50));
}
});
Ok(Some((handle, done)))
}
/// Launches the command runner under the sandbox user and captures its output.
#[allow(clippy::too_many_arguments)]
pub fn run_windows_sandbox_capture_for_permission_profile(
request: ElevatedSandboxProfileCaptureRequest<'_>,
) -> Result<CaptureResult> {
let ElevatedSandboxProfileCaptureRequest {
permission_profile,
workspace_roots,
codex_home,
command,
cwd,
mut env_map,
timeout_ms,
cancellation,
proxy_enforced,
network_proxy_restricting_sid,
read_roots_override,
read_roots_include_platform_defaults,
write_roots_override,
deny_read_paths_override,
deny_write_paths_override,
} = request;
let permissions =
ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots(
permission_profile,
workspace_roots,
)?;
let deny_read_paths_override = deny_read_paths_override
.iter()
.map(AbsolutePathBuf::to_path_buf)
.collect::<Vec<_>>();
let deny_write_paths_override = deny_write_paths_override
.iter()
.map(AbsolutePathBuf::to_path_buf)
.collect::<Vec<_>>();
normalize_null_device_env(&mut env_map);
ensure_non_interactive_pager(&mut env_map);
inherit_path_env(&mut env_map);
inject_git_safe_directory(&mut env_map, cwd);
// Use a temp-based log dir that the sandbox user can write.
let sandbox_base = codex_home.join(".sandbox");
ensure_codex_home_exists(&sandbox_base)?;
let logs_base_dir: Option<&Path> = Some(sandbox_base.as_path());
log_start(&command, logs_base_dir);
let sandbox_creds = require_logon_sandbox_creds(
&permissions,
cwd,
&env_map,
codex_home,
read_roots_override,
read_roots_include_platform_defaults,
write_roots_override,
&deny_read_paths_override,
&deny_write_paths_override,
proxy_enforced,
crate::WindowsSandboxProxySettingsMode::Reconcile,
)?;
// Build capability SID for ACL grants.
let caps = load_or_create_cap_sids(codex_home)?;
let (sid_for_null, cap_sids) = if permissions.uses_write_capabilities_for_cwd(cwd, &env_map)
{
let write_roots = effective_write_roots_for_permissions(
&permissions,
cwd,
&env_map,
codex_home,
write_roots_override,
);
let cap_sids = write_roots
.iter()
.map(|root| workspace_write_cap_sid_for_root(codex_home, cwd, root))
.collect::<Result<Vec<_>>>()?;
if cap_sids.is_empty() {
anyhow::bail!("workspace-write sandbox has no writable root capability SIDs");
}
(LocalSid::from_string(&cap_sids[0])?, cap_sids)
} else {
let sid = LocalSid::from_string(&caps.readonly)?;
(sid, vec![caps.readonly])
};
unsafe {
allow_null_device(sid_for_null.as_ptr());
}
(|| -> Result<CaptureResult> {
let desktop_policy = crate::desktop::DesktopPolicy::elevated(
crate::setup::SandboxSetupRequest {
permissions: &permissions,
command_cwd: cwd,
env_map: &env_map,
codex_home,
proxy_enforced,
},
crate::setup::SetupRootOverrides {
read_roots: read_roots_override.map(<[PathBuf]>::to_vec),
read_roots_include_platform_defaults,
write_roots: write_roots_override.map(<[PathBuf]>::to_vec),
deny_read_paths: Some(deny_read_paths_override.clone()),
deny_write_paths: Some(deny_write_paths_override.clone()),
},
&cap_sids,
network_proxy_restricting_sid.as_deref(),
)?;
let spawn_request = SpawnRequest {
command: command.clone(),
cwd: cwd.to_path_buf(),
env: env_map.clone(),
permission_profile: permission_profile.clone(),
workspace_roots: workspace_roots.to_vec(),
codex_home: sandbox_base.clone(),
real_codex_home: codex_home.to_path_buf(),
cap_sids,
network_proxy_restricting_sid,
timeout_ms,
tty: false,
stdin_open: false,
private_desktop_name: None,
};
let transport = retry_runner_spawn_once(
sandbox_creds,
&spawn_request.command,
|sandbox_creds| {
spawn_runner_transport(
codex_home,
cwd,
&sandbox_creds,
logs_base_dir,
spawn_request.clone(),
Some(&desktop_policy),
)
},
|| {
refresh_logon_sandbox_creds(
&permissions,
cwd,
&env_map,
codex_home,
read_roots_override,
read_roots_include_platform_defaults,
write_roots_override,
&deny_read_paths_override,
&deny_write_paths_override,
proxy_enforced,
crate::WindowsSandboxProxySettingsMode::Reconcile,
)
},
)?;
let (pipe_write, mut pipe_read) = transport.into_files();
let cancel_writer = spawn_cancel_writer(&pipe_write, cancellation)?;
let mut stdout = Vec::new();
let mut stderr = Vec::new();
let result = loop {
let msg = match read_frame(&mut pipe_read) {
Ok(Some(msg)) => msg,
Ok(None) => break Err(anyhow::anyhow!("runner pipe closed before exit")),
Err(err) => break Err(err),
};
match msg.message {
Message::SpawnReady { .. } => {}
Message::Output { payload } => match decode_bytes(&payload.data_b64) {
Ok(bytes) => match payload.stream {
OutputStream::Stdout => stdout.extend_from_slice(&bytes),
OutputStream::Stderr => stderr.extend_from_slice(&bytes),
},
Err(err) => {
break Err(err);
}
},
Message::Exit { payload } => break Ok((payload.exit_code, payload.timed_out)),
Message::Error { payload } => {
break Err(anyhow::anyhow!("runner error: {}", payload.message));
}
other => {
break Err(anyhow::anyhow!(
"unexpected runner message during capture: {other:?}"
));
}
}
};
if let Some((cancel_handle, done)) = cancel_writer {
done.store(true, Ordering::SeqCst);
cancel_handle.thread().unpark();
let _ = cancel_handle.join();
}
drop(pipe_write);
crate::elevated::runner_metrics::record_command(result.as_ref().ok().copied());
let (exit_code, timed_out) = result?;
if exit_code == 0 {
log_success(&command, logs_base_dir);
} else {
log_failure(&command, &format!("exit code {exit_code}"), logs_base_dir);
}
Ok(CaptureResult {
exit_code,
stdout,
stderr,
timed_out,
})
})()
}
}
#[cfg(target_os = "windows")]
pub use windows_impl::run_windows_sandbox_capture_for_permission_profile;
#[cfg(not(target_os = "windows"))]
mod stub {
use super::ElevatedSandboxProfileCaptureRequest;
use anyhow::Result;
use anyhow::bail;
#[derive(Debug, Default)]
pub struct CaptureResult {
pub exit_code: i32,
pub stdout: Vec<u8>,
pub stderr: Vec<u8>,
pub timed_out: bool,
}
/// Stub implementation for non-Windows targets; sandboxing only works on Windows.
#[allow(clippy::too_many_arguments)]
pub fn run_windows_sandbox_capture_for_permission_profile(
_request: ElevatedSandboxProfileCaptureRequest<'_>,
) -> Result<CaptureResult> {
bail!("Windows sandbox is only available on Windows")
}
}
#[cfg(not(target_os = "windows"))]
pub use stub::run_windows_sandbox_capture_for_permission_profile;

View File

@@ -0,0 +1,177 @@
use anyhow::Result;
use anyhow::anyhow;
use dirs_next::home_dir;
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::fs::{self};
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
pub fn normalize_null_device_env(env_map: &mut HashMap<String, String>) {
let keys: Vec<String> = env_map.keys().cloned().collect();
for k in keys {
if let Some(v) = env_map.get(&k).cloned() {
let t = v.trim().to_ascii_lowercase();
if t == "/dev/null" || t == "\\\\\\\\dev\\\\\\\\null" {
env_map.insert(k, "NUL".to_string());
}
}
}
}
pub fn ensure_non_interactive_pager(env_map: &mut HashMap<String, String>) {
env_map
.entry("GIT_PAGER".into())
.or_insert_with(|| "more.com".into());
env_map
.entry("PAGER".into())
.or_insert_with(|| "more.com".into());
env_map.entry("LESS".into()).or_insert_with(|| "".into());
}
// Keep PATH and PATHEXT stable for callers that rely on inheriting the parent process env.
pub fn inherit_path_env(env_map: &mut HashMap<String, String>) {
if !env_map.contains_key("PATH")
&& let Ok(path) = env::var("PATH")
{
env_map.insert("PATH".into(), path);
}
if !env_map.contains_key("PATHEXT")
&& let Ok(pathext) = env::var("PATHEXT")
{
env_map.insert("PATHEXT".into(), pathext);
}
}
fn prepend_path(env_map: &mut HashMap<String, String>, prefix: &str) {
let existing = env_map
.get("PATH")
.cloned()
.or_else(|| env::var("PATH").ok())
.unwrap_or_default();
let parts: Vec<String> = existing.split(';').map(ToString::to_string).collect();
if parts
.first()
.map(|p| p.eq_ignore_ascii_case(prefix))
.unwrap_or(false)
{
return;
}
let mut new_path = String::new();
new_path.push_str(prefix);
if !existing.is_empty() {
new_path.push(';');
new_path.push_str(&existing);
}
env_map.insert("PATH".into(), new_path);
}
fn reorder_pathext_for_stubs(env_map: &mut HashMap<String, String>) {
let default = env_map
.get("PATHEXT")
.cloned()
.or_else(|| env::var("PATHEXT").ok())
.unwrap_or(".COM;.EXE;.BAT;.CMD".to_string());
let exts: Vec<String> = default
.split(';')
.filter(|e| !e.is_empty())
.map(ToString::to_string)
.collect();
let exts_norm: Vec<String> = exts.iter().map(|e| e.to_ascii_uppercase()).collect();
let want = [".BAT", ".CMD"];
let mut front: Vec<String> = Vec::new();
for w in want {
if let Some(idx) = exts_norm.iter().position(|e| e == w) {
front.push(exts[idx].clone());
}
}
let rest: Vec<String> = exts
.into_iter()
.enumerate()
.filter(|(i, _)| {
let up = &exts_norm[*i];
up != ".BAT" && up != ".CMD"
})
.map(|(_, e)| e)
.collect();
let mut combined = Vec::new();
combined.extend(front);
combined.extend(rest);
env_map.insert("PATHEXT".into(), combined.join(";"));
}
fn ensure_denybin(tools: &[&str], denybin_dir: Option<&Path>) -> Result<PathBuf> {
let base = match denybin_dir {
Some(p) => p.to_path_buf(),
None => {
let home = home_dir().ok_or_else(|| anyhow!("no home dir"))?;
home.join(".sbx-denybin")
}
};
fs::create_dir_all(&base)?;
for tool in tools {
for ext in [".bat", ".cmd"] {
let path = base.join(format!("{tool}{ext}"));
if !path.exists() {
let mut f = File::create(&path)?;
f.write_all(b"@echo off\\r\\nexit /b 1\\r\\n")?;
}
}
}
Ok(base)
}
pub fn apply_no_network_to_env(env_map: &mut HashMap<String, String>) -> Result<()> {
env_map.insert("SBX_NONET_ACTIVE".into(), "1".into());
env_map
.entry("HTTP_PROXY".into())
.or_insert_with(|| "http://127.0.0.1:9".into());
env_map
.entry("HTTPS_PROXY".into())
.or_insert_with(|| "http://127.0.0.1:9".into());
env_map
.entry("ALL_PROXY".into())
.or_insert_with(|| "http://127.0.0.1:9".into());
env_map
.entry("NO_PROXY".into())
.or_insert_with(|| "localhost,127.0.0.1,::1".into());
env_map
.entry("PIP_NO_INDEX".into())
.or_insert_with(|| "1".into());
env_map
.entry("PIP_DISABLE_PIP_VERSION_CHECK".into())
.or_insert_with(|| "1".into());
env_map
.entry("NPM_CONFIG_OFFLINE".into())
.or_insert_with(|| "true".into());
env_map
.entry("CARGO_NET_OFFLINE".into())
.or_insert_with(|| "true".into());
env_map
.entry("GIT_HTTP_PROXY".into())
.or_insert_with(|| "http://127.0.0.1:9".into());
env_map
.entry("GIT_HTTPS_PROXY".into())
.or_insert_with(|| "http://127.0.0.1:9".into());
env_map
.entry("GIT_SSH_COMMAND".into())
.or_insert_with(|| "cmd /c exit 1".into());
env_map
.entry("GIT_ALLOW_PROTOCOLS".into())
.or_insert_with(|| "".into());
let base = ensure_denybin(&["ssh", "scp"], /*denybin_dir*/ None)?;
for tool in ["curl", "wget"] {
for ext in [".bat", ".cmd"] {
let p = base.join(format!("{tool}{ext}"));
if p.exists() {
let _ = fs::remove_file(&p);
}
}
}
prepend_path(env_map, &base.to_string_lossy());
reorder_pathext_for_stubs(env_map);
Ok(())
}

View File

@@ -0,0 +1,197 @@
//! Bounded launcher-only environment transport for payloads too large for
//! Windows command lines.
use std::collections::HashMap;
use std::ffi::OsStr;
use anyhow::Context;
use anyhow::Result;
use anyhow::ensure;
const PREFIX: &str = "AKODE_SANDBOX_LAUNCH_";
const COUNT: &str = "AKODE_SANDBOX_LAUNCH_COUNT";
const LENGTH: &str = "AKODE_SANDBOX_LAUNCH_BYTES";
const CHUNK_BYTES: usize = 16 * 1024;
const MAX_BYTES: usize = 16 * 1024 * 1024;
const MAX_CHUNKS: usize = MAX_BYTES / (CHUNK_BYTES - 3) + 1;
/// Whether `key` belongs to the shared sandbox launch transport namespace.
pub fn is_key(key: &OsStr) -> bool {
environment_key_starts_with(key, PREFIX)
}
/// Split a UTF-8 payload into bounded environment variables.
///
/// Existing transport variables are removed only after the complete payload
/// has passed validation.
pub fn encode(payload: &str, env: &mut HashMap<String, String>) -> Result<()> {
ensure!(
!payload.is_empty() && payload.len() <= MAX_BYTES,
"sandbox launch payload must contain 1..={MAX_BYTES} bytes"
);
ensure!(
!payload.contains('\0'),
"sandbox launch payload contains a NUL"
);
let mut chunks = Vec::new();
let mut start = 0;
while start < payload.len() {
let mut end = (start + CHUNK_BYTES).min(payload.len());
while !payload.is_char_boundary(end) {
end -= 1;
}
chunks.push(payload[start..end].to_owned());
start = end;
}
ensure!(
chunks.len() <= MAX_CHUNKS,
"sandbox launch payload has too many chunks"
);
env.retain(|key, _| !is_key(key.as_ref()));
env.insert(COUNT.to_owned(), chunks.len().to_string());
env.insert(LENGTH.to_owned(), payload.len().to_string());
for (index, chunk) in chunks.into_iter().enumerate() {
env.insert(format!("{PREFIX}{index}"), chunk);
}
Ok(())
}
/// Reconstruct a payload without inspecting unrelated non-Unicode variables.
pub fn decode<K: AsRef<OsStr>, V: AsRef<OsStr>>(
env: impl IntoIterator<Item = (K, V)>,
) -> Result<String> {
let mut encoded = HashMap::new();
for (key, value) in env {
let key = key.as_ref();
if !is_key(key) {
continue;
}
let key = canonical_key(key)?;
let value = value
.as_ref()
.to_str()
.context("non-Unicode sandbox launch environment value")?;
ensure!(
encoded.len() < MAX_CHUNKS + 2
&& key.len() <= PREFIX.len() + 32
&& value.len() <= CHUNK_BYTES,
"oversized sandbox launch environment"
);
ensure!(
encoded.insert(key, value.to_owned()).is_none(),
"duplicate sandbox launch environment variables"
);
}
let count: usize = encoded
.get(COUNT)
.context("missing sandbox launch chunk count")?
.parse()?;
let length: usize = encoded
.get(LENGTH)
.context("missing sandbox launch payload length")?
.parse()?;
ensure!(
(1..=MAX_CHUNKS).contains(&count) && length <= MAX_BYTES,
"invalid sandbox launch payload size"
);
ensure!(
encoded.len() == count + 2,
"unexpected sandbox launch environment variables"
);
let mut payload = String::with_capacity(length);
for index in 0..count {
let chunk = encoded
.get(&format!("{PREFIX}{index}"))
.context("missing sandbox launch chunk")?;
ensure!(!chunk.is_empty(), "invalid sandbox launch chunk size");
ensure!(
payload.len() + chunk.len() <= length,
"sandbox launch payload length mismatch"
);
payload.push_str(chunk);
}
ensure!(
payload.len() == length,
"sandbox launch payload length mismatch"
);
Ok(payload)
}
/// Remove every transport variable from `env`, even when decoding fails.
pub fn decode_and_scrub(env: &mut HashMap<String, String>) -> Result<String> {
let payload = decode(env.iter());
env.retain(|key, _| !is_key(key.as_ref()));
payload
}
fn canonical_key(key: &OsStr) -> Result<String> {
if environment_key_eq(key, COUNT) {
return Ok(COUNT.to_owned());
}
if environment_key_eq(key, LENGTH) {
return Ok(LENGTH.to_owned());
}
let key = key
.to_str()
.context("non-Unicode sandbox launch environment key")?;
Ok(format!(
"{PREFIX}{}",
key.chars().skip(PREFIX.len()).collect::<String>()
))
}
#[cfg(windows)]
fn environment_key_eq(key: &OsStr, expected: &str) -> bool {
use std::os::windows::ffi::OsStrExt;
#[link(name = "kernel32")]
unsafe extern "system" {
fn CompareStringOrdinal(
left: *const u16,
left_len: i32,
right: *const u16,
right_len: i32,
ignore_case: i32,
) -> i32;
}
let key: Vec<u16> = key.encode_wide().collect();
let expected: Vec<u16> = expected.encode_utf16().collect();
key.len() == expected.len()
&& unsafe {
CompareStringOrdinal(
key.as_ptr(),
key.len() as i32,
expected.as_ptr(),
expected.len() as i32,
/*ignore_case*/ 1,
) == 2
}
}
#[cfg(not(windows))]
fn environment_key_eq(key: &OsStr, expected: &str) -> bool {
key.as_encoded_bytes()
.eq_ignore_ascii_case(expected.as_bytes())
}
#[cfg(windows)]
fn environment_key_starts_with(key: &OsStr, prefix: &str) -> bool {
use std::ffi::OsString;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::ffi::OsStringExt;
let key_prefix: Vec<u16> = key
.encode_wide()
.take(prefix.encode_utf16().count())
.collect();
environment_key_eq(&OsString::from_wide(&key_prefix), prefix)
}
#[cfg(not(windows))]
fn environment_key_starts_with(key: &OsStr, prefix: &str) -> bool {
key.as_encoded_bytes()
.get(..prefix.len())
.is_some_and(|start| start.eq_ignore_ascii_case(prefix.as_bytes()))
}
#[cfg(test)]
#[path = "environment_transport_tests.rs"]
mod tests;

View File

@@ -0,0 +1,146 @@
//! Shared transport roundtrips, validation, and environment cleanup.
use std::collections::HashMap;
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn unicode_payload_roundtrips_and_stale_chunks_are_replaced() {
let payload = "a🧊".repeat(500_000);
let expected = HashMap::from([("CUSTOM".to_owned(), "value".to_owned())]);
let mut env = expected.clone();
env.insert(
format!("{}999", PREFIX.to_ascii_lowercase()),
"spoofed".to_owned(),
);
encode(&payload, &mut env).unwrap();
assert!(!env.contains_key(&format!("{}999", PREFIX.to_ascii_lowercase())));
assert_eq!(decode_and_scrub(&mut env).unwrap(), payload);
assert_eq!(env, expected);
}
#[test]
fn malformed_transport_is_rejected_and_scrubbed() {
let expected = HashMap::from([("CUSTOM".to_owned(), "value".to_owned())]);
let mut valid = expected.clone();
encode("payload", &mut valid).unwrap();
for (key, value) in [
(COUNT.to_owned(), (MAX_CHUNKS + 1).to_string()),
(LENGTH.to_owned(), "0".to_owned()),
(LENGTH.to_owned(), (MAX_BYTES + 1).to_string()),
(format!("{PREFIX}0"), "x".repeat(CHUNK_BYTES + 1)),
(COUNT.to_ascii_lowercase(), "1".to_owned()),
(format!("{PREFIX}unexpected"), "x".to_owned()),
] {
let mut env = valid.clone();
env.insert(key, value);
assert!(decode_and_scrub(&mut env).is_err());
assert_eq!(env, expected);
}
valid.remove(&format!("{PREFIX}0"));
assert!(decode_and_scrub(&mut valid).is_err());
assert_eq!(valid, expected);
assert!(decode(HashMap::<String, String>::new()).is_err());
}
#[test]
fn rejected_payload_preserves_environment() {
let expected = HashMap::from([("CUSTOM".to_owned(), "value".to_owned())]);
for payload in [
String::new(),
"x".repeat(MAX_BYTES + 1),
"bad\0payload".into(),
] {
let mut env = expected.clone();
assert!(encode(&payload, &mut env).is_err());
assert_eq!(env, expected);
}
}
#[cfg(any(windows, unix))]
#[test]
fn native_environment_ignores_unrelated_non_unicode_and_rejects_invalid_transport() {
use std::ffi::OsString;
#[cfg(unix)]
use std::os::unix::ffi::OsStringExt;
#[cfg(windows)]
use std::os::windows::ffi::OsStringExt;
#[cfg(windows)]
let invalid = OsString::from_wide(&[0xd800]);
#[cfg(unix)]
let invalid = OsString::from_vec(vec![0xff]);
let mut env = vec![
(OsString::from(COUNT), OsString::from("1")),
(OsString::from(LENGTH), OsString::from("2")),
(OsString::from(format!("{PREFIX}0")), OsString::from("ok")),
(OsString::from("unrelated"), invalid.clone()),
(invalid.clone(), OsString::from("unrelated")),
];
assert_eq!(decode(env.clone()).unwrap(), "ok");
env.push((OsString::from(format!("{PREFIX}0")), invalid.clone()));
assert!(decode(env).is_err());
let mut invalid_key = OsString::from(PREFIX);
invalid_key.push(invalid);
assert!(decode([(invalid_key, OsString::from("bad"))]).is_err());
}
#[cfg(windows)]
#[test]
fn windows_equivalent_names_are_scrubbed_decoded_and_deduplicated() {
let alias_prefix = PREFIX.to_ascii_lowercase();
let alias_count = format!("{alias_prefix}count");
let alias_length = format!("{alias_prefix}bytes");
let mut env = HashMap::from([
(alias_count.clone(), "1".to_owned()),
(alias_length.clone(), "2".to_owned()),
(format!("{alias_prefix}0"), "ok".to_owned()),
]);
assert_eq!(decode(env.clone()).unwrap(), "ok");
env.insert(COUNT.to_owned(), "1".to_owned());
assert!(decode(env).is_err());
let mut stale = HashMap::from([
(alias_count, "1".to_owned()),
(alias_length, "2".to_owned()),
(format!("{alias_prefix}999"), "stale".to_owned()),
]);
encode("ok", &mut stale).unwrap();
assert_eq!(stale.len(), 3);
}
// Exercise a real Unicode Windows environment block, without provisioning or ACL changes.
#[cfg(windows)]
#[test]
fn large_payload_survives_windows_process_creation() {
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
let payload = r#"C:\fixture\秘密\file-😀.txt\""#.repeat(150_000);
let mut command = std::process::Command::new(std::env::current_exe().unwrap());
command
.arg("--exact")
.arg("environment_transport::tests::environment_child");
let mut env = HashMap::new();
encode(&payload, &mut env).unwrap();
// Command preserves the spelling of a Windows-equivalent inherited key.
command.env(LENGTH.replace('S', "s"), "stale");
command.env("unrelated", OsString::from_wide(&[0xd800]));
let output = command.envs(env).arg("--nocapture").output().unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
assert!(String::from_utf8_lossy(&output.stdout).contains("transport-child-ok"));
}
#[cfg(windows)]
#[test]
fn environment_child() {
if std::env::var_os(LENGTH).is_none() {
return;
}
let payload = r#"C:\fixture\秘密\file-😀.txt\""#.repeat(150_000);
assert_eq!(decode(std::env::vars_os()).unwrap(), payload);
println!("transport-child-ok");
}

View File

@@ -0,0 +1,149 @@
//! Writes helper outputs through fresh handles, replacing directory entries
//! without opening caller-supplied destination files or copying their ACLs.
use anyhow::Context;
use anyhow::Result;
use rand::RngCore;
use std::ffi::OsStr;
use std::ffi::c_void;
use std::fs::File;
use std::io::Write;
use std::mem::offset_of;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::io::AsRawHandle;
use std::os::windows::io::OwnedHandle;
use std::path::Path;
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::Foundation::NTSTATUS;
use windows_sys::Win32::Foundation::RtlNtStatusToDosError;
use windows_sys::Win32::Storage::FileSystem::DELETE;
use windows_sys::Win32::Storage::FileSystem::FILE_DISPOSITION_INFO;
use windows_sys::Win32::Storage::FileSystem::FILE_READ_ATTRIBUTES;
use windows_sys::Win32::Storage::FileSystem::FILE_RENAME_INFO;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_WRITE;
use windows_sys::Win32::Storage::FileSystem::FILE_TRAVERSE;
use windows_sys::Win32::Storage::FileSystem::FILE_WRITE_DATA;
use windows_sys::Win32::Storage::FileSystem::FileDispositionInfo;
use windows_sys::Win32::Storage::FileSystem::SYNCHRONIZE;
use windows_sys::Win32::Storage::FileSystem::SetFileInformationByHandle;
use windows_sys::Win32::System::IO::IO_STATUS_BLOCK;
use windows_sys::Win32::System::IO::IO_STATUS_BLOCK_0;
use crate::no_reparse_dir::DirectoryOpenDisposition;
use crate::no_reparse_dir::open_directory_no_reparse;
use crate::no_reparse_dir::open_no_reparse;
use crate::no_reparse_dir::validate_local_directory_path;
const FILE_CREATE: u32 = 2;
const FILE_SYNCHRONOUS_IO_NONALERT: u32 = 0x20;
const FILE_NON_DIRECTORY_FILE: u32 = 0x40;
const FILE_RENAME_INFORMATION: i32 = 10;
#[link(name = "ntdll")]
unsafe extern "system" {
fn NtSetInformationFile(
file_handle: HANDLE,
io_status_block: *mut IO_STATUS_BLOCK,
file_information: *const c_void,
length: u32,
file_information_class: i32,
) -> NTSTATUS;
}
/// Replaces an output with a fresh file that inherits its parent directory's ACL.
/// The destination is never opened for writing, even if replacement fails.
pub fn write_file_atomically(path: &Path, contents: &[u8]) -> Result<()> {
validate_local_directory_path(path)?;
let parent = path
.parent()
.context("output must have a parent directory")?;
let name: Vec<u16> = path
.file_name()
.context("output must have a file name")?
.encode_wide()
.collect();
let (mut file, directory) = create_temporary_file(parent, ".tmp")?;
let result: Result<()> = (|| {
file.write_all(contents)?;
// FILE_RENAME_INFO ends in a variable-length UTF-16 name. Allocate
// enough aligned storage for both the fixed header and that name.
let size = size_of::<FILE_RENAME_INFO>() + size_of_val(name.as_slice());
let mut buffer = vec![0_usize; size.div_ceil(size_of::<usize>())];
let info = buffer.as_mut_ptr().cast::<FILE_RENAME_INFO>();
let mut io_status = IO_STATUS_BLOCK {
Anonymous: IO_STATUS_BLOCK_0 { Status: 0 },
Information: 0,
};
unsafe {
(*info).Anonymous.ReplaceIfExists = true;
(*info).RootDirectory = directory.as_raw_handle() as HANDLE;
(*info).FileNameLength = u32::try_from(size_of_val(name.as_slice()))?;
let filename = buffer
.as_mut_ptr()
.cast::<u8>()
.add(offset_of!(FILE_RENAME_INFO, FileName))
.cast::<u16>();
std::ptr::copy_nonoverlapping(name.as_ptr(), filename, name.len());
// The Win32 wrapper rejects RootDirectory on some Windows versions.
// The native rename accepts the pinned parent and has the same layout.
let status = NtSetInformationFile(
file.as_raw_handle() as HANDLE,
&mut io_status,
info.cast(),
u32::try_from(size)?,
FILE_RENAME_INFORMATION,
);
if status < 0 {
return Err(
std::io::Error::from_raw_os_error(RtlNtStatusToDosError(status) as i32).into(),
);
}
}
Ok(())
})();
if result.is_err() {
// Clean up only the file we created, not a pathname the caller could
// have replaced. Preserve the original write/rename error.
let disposition = FILE_DISPOSITION_INFO { DeleteFile: true };
unsafe {
SetFileInformationByHandle(
file.as_raw_handle() as HANDLE,
FileDispositionInfo,
(&raw const disposition).cast(),
size_of::<FILE_DISPOSITION_INFO>() as u32,
);
}
}
result.with_context(|| format!("replace output {}", path.display()))
}
pub(crate) fn create_temporary_file(parent: &Path, suffix: &str) -> Result<(File, OwnedHandle)> {
let directory = open_directory_no_reparse(
parent,
FILE_TRAVERSE | FILE_READ_ATTRIBUTES,
FILE_SHARE_READ | FILE_SHARE_WRITE,
DirectoryOpenDisposition::OpenExisting,
)?;
let mut random = [0_u8; 8];
rand::rngs::OsRng
.try_fill_bytes(&mut random)
.context("generate sandbox output name")?;
let id = u64::from_le_bytes(random);
let name = format!("sandbox-{id:016x}{suffix}");
let mut name: Vec<u16> = OsStr::new(&name).encode_wide().chain(Some(0)).collect();
let file = open_no_reparse(
directory.as_raw_handle() as HANDLE,
&mut name,
FILE_WRITE_DATA | DELETE | SYNCHRONIZE,
FILE_SHARE_READ,
FILE_CREATE,
FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT,
)?;
Ok((File::from(file), directory))
}
#[cfg(test)]
#[path = "file_write_tests.rs"]
mod tests;

View File

@@ -0,0 +1,70 @@
//! Checks fresh output handles and safe replacement of caller-controlled entries.
use super::create_temporary_file;
use super::write_file_atomically;
use anyhow::Result;
use pretty_assertions::assert_eq;
use std::fs;
use std::fs::OpenOptions;
use std::io::Write;
use std::os::windows::fs::OpenOptionsExt;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_WRITE;
#[test]
fn replaces_hard_link_without_writing_to_its_target() -> Result<()> {
let temp = tempfile::tempdir()?;
let victim = temp.path().join("victim");
let output = temp.path().join("sandbox_users.json");
fs::write(&victim, b"unchanged")?;
fs::hard_link(&victim, &output)?;
write_file_atomically(&output, b"new contents")?;
assert_eq!(fs::read(&victim)?, b"unchanged");
assert_eq!(fs::read(&output)?, b"new contents");
assert_eq!(fs::read_dir(temp.path())?.count(), 2);
Ok(())
}
#[test]
fn failed_replacement_does_not_truncate_target_or_leave_temporary_file() -> Result<()> {
let temp = tempfile::tempdir()?;
let victim = temp.path().join("victim");
let output = temp.path().join("setup_error.json");
fs::write(&victim, b"unchanged")?;
fs::hard_link(&victim, &output)?;
let _held = OpenOptions::new()
.read(true)
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
.open(&output)?;
assert!(write_file_atomically(&output, b"new contents").is_err());
assert_eq!(fs::read(&victim)?, b"unchanged");
assert_eq!(fs::read(&output)?, b"unchanged");
assert_eq!(fs::read_dir(temp.path())?.count(), 2);
Ok(())
}
#[test]
fn fresh_output_cannot_be_written_or_replaced_while_held() -> Result<()> {
let temp = tempfile::tempdir()?;
let (mut file, _directory) = create_temporary_file(temp.path(), ".log")?;
let path = fs::read_dir(temp.path())?.next().unwrap()?.path();
assert!(
OpenOptions::new()
.write(true)
.truncate(true)
.open(&path)
.is_err()
);
assert!(fs::remove_file(&path).is_err());
assert!(fs::rename(&path, temp.path().join("moved")).is_err());
file.write_all(b"log contents")?;
drop(file);
assert_eq!(fs::read(path)?, b"log contents");
Ok(())
}

View File

@@ -0,0 +1,91 @@
//! Shared length-prefixed JSON framing for independent Windows sandbox IPC protocols.
use anyhow::Result;
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::fs::File;
use std::io;
use std::io::Read;
use std::io::Write;
use std::os::windows::io::AsRawHandle;
use std::ptr;
use std::time::Duration;
use std::time::Instant;
use windows_sys::Win32::System::Pipes::PeekNamedPipe;
/// Bound the memory used by an individual untrusted IPC frame.
const MAX_FRAME_LEN: usize = 8 * 1024 * 1024;
const FRAME_POLL_INTERVAL: Duration = Duration::from_millis(5);
pub(crate) fn write_frame<W: Write, T: Serialize>(mut writer: W, message: &T) -> Result<()> {
let payload = serde_json::to_vec(message)?;
if payload.len() > MAX_FRAME_LEN {
anyhow::bail!("frame too large: {}", payload.len());
}
let len = payload.len() as u32;
writer.write_all(&len.to_le_bytes())?;
writer.write_all(&payload)?;
writer.flush()?;
Ok(())
}
pub(crate) fn read_frame<R: Read, T: DeserializeOwned>(mut reader: R) -> Result<Option<T>> {
let mut len_buf = [0u8; 4];
match reader.read_exact(&mut len_buf) {
Ok(()) => {}
Err(err) if err.kind() == std::io::ErrorKind::UnexpectedEof => return Ok(None),
Err(err) => return Err(err.into()),
}
let len = u32::from_le_bytes(len_buf) as usize;
if len > MAX_FRAME_LEN {
anyhow::bail!("frame too large: {len}");
}
let mut payload = vec![0u8; len];
reader.read_exact(&mut payload)?;
let message = serde_json::from_slice(&payload)?;
Ok(Some(message))
}
pub(crate) fn wait_for_complete_frame(pipe: &File, deadline: Instant) -> io::Result<()> {
let mut len_buf = [0_u8; 4];
loop {
let mut bytes_read = 0_u32;
let mut total_available = 0_u32;
let ok = unsafe {
PeekNamedPipe(
pipe.as_raw_handle() as _,
len_buf.as_mut_ptr().cast(),
len_buf.len() as u32,
&mut bytes_read,
&mut total_available,
ptr::null_mut(),
)
};
if ok == 0 {
return Err(io::Error::last_os_error());
}
if bytes_read == len_buf.len() as u32 {
let frame_len = u32::from_le_bytes(len_buf) as usize;
if frame_len > MAX_FRAME_LEN {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("frame too large: {frame_len}"),
));
}
if total_available as usize >= len_buf.len() + frame_len {
return Ok(());
}
}
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
return Err(io::Error::new(
io::ErrorKind::TimedOut,
"timed out waiting for a complete IPC frame",
));
}
std::thread::sleep(remaining.min(FRAME_POLL_INTERVAL));
}
}

View File

@@ -0,0 +1,432 @@
//! Resolve sandbox helpers and materialize legacy executables with inherited sandbox ACLs.
//! An explicit registered-runtime request never falls through to copying or PATH lookup;
//! the service and startup handshake independently verify the installed image.
mod copy;
use copy::CopyOutcome;
use copy::copy_from_source_if_needed;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use std::ffi::OsStr;
use std::fs;
use std::path::Path;
use std::path::PathBuf;
use std::time::UNIX_EPOCH;
use crate::app_package::registered_core_requested;
use crate::logging::log_note;
use crate::sandbox_bin_dir;
use crate::setup::SetupRuntime;
const DEV_BUILD_VERSION_SENTINEL: &str = "0.0.0";
const COMMAND_RUNNER_EXE: &str = "akode-command-runner.exe";
pub(crate) const BIN_DIRNAME: &str = "bin";
pub(crate) const RESOURCES_DIRNAME: &str = "akode-resources";
pub(crate) fn helper_bin_dir(codex_home: &Path) -> PathBuf {
sandbox_bin_dir(codex_home)
}
fn legacy_lookup() -> PathBuf {
if let Ok(exe) = std::env::current_exe()
&& let Some(candidate) = bundled_executable_path_for_exe(&exe, COMMAND_RUNNER_EXE)
{
return candidate;
}
PathBuf::from(COMMAND_RUNNER_EXE)
}
pub(crate) fn resolve_command_runner(codex_home: &Path, log_dir: Option<&Path>) -> Result<PathBuf> {
if registered_core_requested() {
let exe = std::env::current_exe().context("resolve registered Core helper source")?;
let direct_path = exe.with_file_name(COMMAND_RUNNER_EXE);
log_note(
&format!(
"helper launch resolution: using app-contained command-runner path {}",
direct_path.display()
),
log_dir,
);
// Missing packaged helpers must fail rather than search PATH or create a copy.
return Ok(direct_path);
}
Ok(match copy_runner_if_needed(codex_home, log_dir) {
Ok(path) => {
log_note(
&format!(
"helper launch resolution: using copied command-runner path {}",
path.display()
),
log_dir,
);
path
}
Err(err) => {
let fallback = legacy_lookup();
log_note(
&format!(
"helper copy failed for command-runner: {err:#}; falling back to legacy path {}",
fallback.display()
),
log_dir,
);
fallback
}
})
}
pub fn resolve_exe_for_launch(source: &Path, codex_home: &Path) -> PathBuf {
let runtime = crate::setup::current_setup_runtime();
resolve_exe_for_runtime(source, codex_home, runtime)
}
fn resolve_exe_for_runtime(source: &Path, codex_home: &Path, runtime: SetupRuntime) -> PathBuf {
let sandbox_log_dir = crate::sandbox_dir(codex_home);
if runtime == SetupRuntime::Registered {
log_note(
&format!(
"helper executable resolution: route=direct source={} selected={}",
source.display(),
source.display()
),
Some(&sandbox_log_dir),
);
return source.to_path_buf();
}
let Some(file_name) = source.file_name() else {
return source.to_path_buf();
};
let destination = helper_bin_dir(codex_home).join(file_name);
match copy_from_source_if_needed(source, &destination) {
Ok(_) => {
log_note(
&format!(
"helper executable resolution: route=materialized source={} selected={}",
source.display(),
destination.display()
),
Some(&sandbox_log_dir),
);
destination
}
Err(err) => {
log_note(
&format!(
"helper copy failed for executable: {err:#}; falling back to legacy path {}",
source.display()
),
Some(&sandbox_log_dir),
);
source.to_path_buf()
}
}
}
fn copy_runner_if_needed(codex_home: &Path, log_dir: Option<&Path>) -> Result<PathBuf> {
let source = sibling_source_path()?;
let suffix = helper_version_suffix(&source)?;
let destination = helper_bin_dir(codex_home).join(materialized_file_name(&suffix));
log_note(
&format!(
"helper copy: validating command-runner source={} destination={}",
source.display(),
destination.display()
),
log_dir,
);
let outcome = copy_from_source_if_needed(&source, &destination)?;
let action = match outcome {
CopyOutcome::Reused => "reused",
CopyOutcome::ReCopied => "recopied",
};
log_note(
&format!(
"helper copy: {} command-runner source={} destination={}",
action,
source.display(),
destination.display()
),
log_dir,
);
Ok(destination)
}
fn sibling_source_path() -> Result<PathBuf> {
let exe = std::env::current_exe().context("resolve current executable for helper lookup")?;
bundled_executable_path_for_exe(&exe, COMMAND_RUNNER_EXE).ok_or_else(|| {
anyhow!(
"helper not found next to current executable or under {RESOURCES_DIRNAME}: {}",
exe.display()
)
})
}
pub(crate) fn bundled_executable_path_for_exe(exe: &Path, file_name: &str) -> Option<PathBuf> {
let find = |exe: &Path| {
let dir = exe.parent()?;
let direct_candidate = dir.join(file_name);
if direct_candidate.is_file() {
return Some(direct_candidate);
}
if dir.file_name() == Some(OsStr::new(BIN_DIRNAME))
&& let Some(package_dir) = dir.parent()
{
let package_resource_candidate = package_dir.join(RESOURCES_DIRNAME).join(file_name);
if package_resource_candidate.is_file() {
return Some(package_resource_candidate);
}
}
let resource_candidate = dir.join(RESOURCES_DIRNAME).join(file_name);
resource_candidate.is_file().then_some(resource_candidate)
};
// Installer bin directories can be junctions, so retry beside the real executable once.
find(exe).or_else(|| find(&dunce::canonicalize(exe).ok()?))
}
fn materialized_file_name(suffix: &str) -> String {
format!("codex-command-runner-{suffix}.exe")
}
fn helper_version_suffix(source: &Path) -> Result<String> {
let version = env!("CARGO_PKG_VERSION");
if version == DEV_BUILD_VERSION_SENTINEL {
dev_build_suffix(source)
} else {
Ok(version.to_string())
}
}
fn dev_build_suffix(source: &Path) -> Result<String> {
let metadata = fs::metadata(source)
.with_context(|| format!("read helper source metadata {}", source.display()))?;
let modified = metadata
.modified()
.with_context(|| format!("read helper source mtime {}", source.display()))?;
let duration = modified
.duration_since(UNIX_EPOCH)
.with_context(|| format!("convert helper source mtime {}", source.display()))?;
Ok(format!("{}-{:x}", metadata.len(), duration.as_secs(),))
}
#[cfg(test)]
mod tests {
use super::BIN_DIRNAME;
use super::CopyOutcome;
use super::DEV_BUILD_VERSION_SENTINEL;
use super::RESOURCES_DIRNAME;
use super::bundled_executable_path_for_exe;
use super::copy_from_source_if_needed;
use super::dev_build_suffix;
use super::helper_bin_dir;
use super::helper_version_suffix;
use super::materialized_file_name;
use super::resolve_exe_for_runtime;
use crate::setup::SetupRuntime;
use pretty_assertions::assert_eq;
use std::fs;
use std::path::Path;
use std::path::PathBuf;
use tempfile::TempDir;
#[test]
fn helper_bin_dir_is_under_sandbox_bin() {
let codex_home = Path::new(r"C:\Users\example\.akode");
assert_eq!(
PathBuf::from(r"C:\Users\example\.akode\.sandbox-bin"),
helper_bin_dir(codex_home)
);
}
#[test]
fn registered_request_does_not_materialize_or_replace_a_missing_source() {
let tmp = TempDir::new().expect("tempdir");
let executable = tmp.path().join("akode.exe");
let home = tmp.path().join("home");
for content in [None, Some(b"fixture".as_slice())] {
if let Some(content) = content {
fs::write(&executable, content).expect("write source");
}
assert_eq!(
resolve_exe_for_runtime(&executable, &home, SetupRuntime::Registered),
executable
);
assert!(!helper_bin_dir(&home).exists());
}
}
#[test]
fn legacy_request_materializes_the_same_source() {
let tmp = TempDir::new().expect("tempdir");
let executable = tmp.path().join("akode.exe");
let home = tmp.path().join("home");
fs::write(&executable, b"fixture").expect("write source");
let destination = helper_bin_dir(&home).join("akode.exe");
assert_eq!(
resolve_exe_for_runtime(&executable, &home, SetupRuntime::Legacy),
destination
);
assert_eq!(fs::read(destination).expect("read copy"), b"fixture");
}
#[test]
fn copy_runner_into_shared_bin_dir() {
let tmp = TempDir::new().expect("tempdir");
let codex_home = tmp.path().join("akode-home");
let source_dir = tmp.path().join("sibling-source");
fs::create_dir_all(&source_dir).expect("create source dir");
let runner_source = source_dir.join("akode-command-runner.exe");
fs::write(&runner_source, b"runner").expect("runner");
let runner_suffix = helper_version_suffix(&runner_source).expect("runner suffix");
let runner_destination =
helper_bin_dir(&codex_home).join(materialized_file_name(&runner_suffix));
let runner_outcome =
copy_from_source_if_needed(&runner_source, &runner_destination).expect("runner copy");
assert_eq!(CopyOutcome::ReCopied, runner_outcome);
assert_eq!(
b"runner".as_slice(),
fs::read(&runner_destination).expect("read runner")
);
}
#[test]
fn helper_source_lookup_checks_resource_dir() {
let tmp = TempDir::new().expect("tempdir");
let release_dir = tmp.path().join("release");
let resources_dir = release_dir.join(RESOURCES_DIRNAME);
fs::create_dir_all(&resources_dir).expect("create resources dir");
let exe = release_dir.join("akode.exe");
let helper = resources_dir.join("akode-command-runner.exe");
fs::write(&exe, b"codex").expect("write exe");
fs::write(&helper, b"runner").expect("write helper");
let resolved =
bundled_executable_path_for_exe(&exe, /*file_name*/ "akode-command-runner.exe")
.expect("helper path");
assert_eq!(resolved, helper);
}
#[test]
fn helper_source_lookup_checks_package_resource_dir_for_bin_exe() {
let tmp = TempDir::new().expect("tempdir");
let package_dir = tmp.path().join("package");
let bin_dir = package_dir.join(BIN_DIRNAME);
let resources_dir = package_dir.join(RESOURCES_DIRNAME);
fs::create_dir_all(&bin_dir).expect("create bin dir");
fs::create_dir_all(&resources_dir).expect("create resources dir");
let exe = bin_dir.join("akode.exe");
let helper = resources_dir.join("akode-command-runner.exe");
fs::write(&exe, b"codex").expect("write exe");
fs::write(&helper, b"runner").expect("write helper");
let resolved =
bundled_executable_path_for_exe(&exe, /*file_name*/ "akode-command-runner.exe")
.expect("helper path");
assert_eq!(resolved, helper);
}
#[test]
fn helper_source_lookup_resolves_bin_junctions() {
let tmp = TempDir::new().expect("tempdir");
let package_dir = tmp.path().join("package");
let bin_dir = package_dir.join(BIN_DIRNAME);
let resources_dir = package_dir.join(RESOURCES_DIRNAME);
let install_dir = tmp.path().join("install");
fs::create_dir_all(&bin_dir).expect("create bin dir");
fs::create_dir_all(&resources_dir).expect("create resources dir");
fs::create_dir_all(&install_dir).expect("create install dir");
fs::write(bin_dir.join("akode.exe"), b"codex").expect("write exe");
let helper = resources_dir.join("akode-windows-sandbox-setup.exe");
fs::write(&helper, b"setup").expect("write helper");
let junction = install_dir.join(BIN_DIRNAME);
let output = std::process::Command::new("cmd")
.args(["/c", "mklink", "/J"])
.arg(&junction)
.arg(&bin_dir)
.output()
.expect("create bin junction");
assert!(output.status.success());
assert_eq!(
bundled_executable_path_for_exe(
&junction.join("akode.exe"),
/*file_name*/ "akode-windows-sandbox-setup.exe"
),
Some(dunce::canonicalize(&helper).expect("canonical helper"))
);
}
#[test]
fn helper_source_lookup_prefers_package_resource_dir_over_bin_resource_dir() {
let tmp = TempDir::new().expect("tempdir");
let package_dir = tmp.path().join("package");
let bin_dir = package_dir.join(BIN_DIRNAME);
let package_resources_dir = package_dir.join(RESOURCES_DIRNAME);
let bin_resources_dir = bin_dir.join(RESOURCES_DIRNAME);
fs::create_dir_all(&package_resources_dir).expect("create package resources dir");
fs::create_dir_all(&bin_resources_dir).expect("create bin resources dir");
let exe = bin_dir.join("akode.exe");
let package_helper = package_resources_dir.join("akode-command-runner.exe");
let bin_helper = bin_resources_dir.join("akode-command-runner.exe");
fs::write(&exe, b"codex").expect("write exe");
fs::write(&package_helper, b"package runner").expect("write package helper");
fs::write(&bin_helper, b"bin runner").expect("write bin helper");
let resolved =
bundled_executable_path_for_exe(&exe, /*file_name*/ "akode-command-runner.exe")
.expect("helper path");
assert_eq!(resolved, package_helper);
}
#[test]
fn helper_source_lookup_prefers_direct_sibling_over_resource_dir() {
let tmp = TempDir::new().expect("tempdir");
let release_dir = tmp.path().join("release");
let resources_dir = release_dir.join(RESOURCES_DIRNAME);
fs::create_dir_all(&resources_dir).expect("create resources dir");
let exe = release_dir.join("akode.exe");
let sibling_helper = release_dir.join("akode-command-runner.exe");
let resource_helper = resources_dir.join("akode-command-runner.exe");
fs::write(&exe, b"codex").expect("write exe");
fs::write(&sibling_helper, b"sibling runner").expect("write sibling helper");
fs::write(&resource_helper, b"resource runner").expect("write resource helper");
let resolved =
bundled_executable_path_for_exe(&exe, /*file_name*/ "akode-command-runner.exe")
.expect("helper path");
assert_eq!(resolved, sibling_helper);
}
#[test]
fn helper_version_suffix_uses_cli_version_or_dev_build_metadata() {
let tmp = TempDir::new().expect("tempdir");
let source = tmp.path().join("source.exe");
fs::write(&source, b"runner-v1").expect("write source");
let suffix = helper_version_suffix(&source).expect("suffix");
if env!("CARGO_PKG_VERSION") == DEV_BUILD_VERSION_SENTINEL {
assert_eq!(suffix, dev_build_suffix(&source).expect("dev build suffix"));
} else {
assert_eq!(suffix, env!("CARGO_PKG_VERSION"));
}
}
#[test]
fn materialized_file_name_adds_suffix_before_extension() {
let file_name = materialized_file_name("test-suffix");
assert_eq!(file_name, "codex-command-runner-test-suffix.exe");
}
}

View File

@@ -0,0 +1,120 @@
//! Copies legacy helpers using destination-inherited ACLs and the existing freshness check.
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use std::fs;
use std::io::Write;
use std::path::Path;
use tempfile::NamedTempFile;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum CopyOutcome {
Reused,
ReCopied,
}
pub(super) fn copy_from_source_if_needed(source: &Path, destination: &Path) -> Result<CopyOutcome> {
if destination_is_fresh(source, destination)? {
return Ok(CopyOutcome::Reused);
}
let destination_dir = destination.parent().ok_or_else(|| {
anyhow!(
"helper destination has no parent: {}",
destination.display()
)
})?;
fs::create_dir_all(destination_dir).with_context(|| {
format!(
"create helper destination directory {}",
destination_dir.display()
)
})?;
let temp_path = NamedTempFile::new_in(destination_dir)
.with_context(|| {
format!(
"create temporary helper file in {}",
destination_dir.display()
)
})?
.into_temp_path();
let temp_path_buf = temp_path.to_path_buf();
let mut source_file = fs::File::open(source)
.with_context(|| format!("open helper source for read {}", source.display()))?;
let mut temp_file = fs::OpenOptions::new()
.write(true)
.truncate(true)
.open(&temp_path_buf)
.with_context(|| format!("open temporary helper file {}", temp_path_buf.display()))?;
// Write into a temp file created inside `.sandbox-bin` so the copied helper keeps the
// destination directory's inherited ACLs instead of reusing the source file's descriptor.
std::io::copy(&mut source_file, &mut temp_file).with_context(|| {
format!(
"copy helper from {} to {}",
source.display(),
temp_path_buf.display()
)
})?;
temp_file
.flush()
.with_context(|| format!("flush temporary helper file {}", temp_path_buf.display()))?;
drop(temp_file);
if destination.exists() {
fs::remove_file(destination).with_context(|| {
format!("remove stale helper destination {}", destination.display())
})?;
}
match fs::rename(&temp_path_buf, destination) {
Ok(()) => Ok(CopyOutcome::ReCopied),
Err(rename_err) => {
if destination_is_fresh(source, destination)? {
Ok(CopyOutcome::Reused)
} else {
Err(rename_err).with_context(|| {
format!(
"rename helper temp file {} to {}",
temp_path_buf.display(),
destination.display()
)
})
}
}
}
}
fn destination_is_fresh(source: &Path, destination: &Path) -> Result<bool> {
let source_meta = fs::metadata(source)
.with_context(|| format!("read helper source metadata {}", source.display()))?;
let destination_meta = match fs::metadata(destination) {
Ok(meta) => meta,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(false),
Err(err) => {
return Err(err).with_context(|| {
format!("read helper destination metadata {}", destination.display())
});
}
};
if source_meta.len() != destination_meta.len() {
return Ok(false);
}
let source_modified = source_meta
.modified()
.with_context(|| format!("read helper source mtime {}", source.display()))?;
let destination_modified = destination_meta
.modified()
.with_context(|| format!("read helper destination mtime {}", destination.display()))?;
Ok(destination_modified >= source_modified)
}
#[cfg(test)]
#[path = "copy_tests.rs"]
mod tests;

View File

@@ -0,0 +1,58 @@
//! Tests the legacy helper copy and freshness contract.
use super::CopyOutcome;
use super::copy_from_source_if_needed;
use super::destination_is_fresh;
use pretty_assertions::assert_eq;
use std::fs;
use tempfile::TempDir;
#[test]
fn copy_from_source_if_needed_copies_missing_destination() {
let tmp = TempDir::new().expect("tempdir");
let source = tmp.path().join("source.exe");
let destination = tmp.path().join("bin").join("helper.exe");
fs::write(&source, b"runner-v1").expect("write source");
let outcome = copy_from_source_if_needed(&source, &destination).expect("copy helper");
assert_eq!(CopyOutcome::ReCopied, outcome);
assert_eq!(
b"runner-v1".as_slice(),
fs::read(&destination).expect("read destination")
);
}
#[test]
fn destination_is_fresh_uses_size_and_mtime() {
let tmp = TempDir::new().expect("tempdir");
let source = tmp.path().join("source.exe");
let destination = tmp.path().join("destination.exe");
fs::write(&destination, b"same-size").expect("write destination");
std::thread::sleep(std::time::Duration::from_secs(1));
fs::write(&source, b"same-size").expect("write source");
assert!(!destination_is_fresh(&source, &destination).expect("stale metadata"));
fs::write(&destination, b"same-size").expect("rewrite destination");
assert!(destination_is_fresh(&source, &destination).expect("fresh metadata"));
}
#[test]
fn copy_from_source_if_needed_reuses_fresh_destination() {
let tmp = TempDir::new().expect("tempdir");
let source = tmp.path().join("source.exe");
let destination = tmp.path().join("bin").join("helper.exe");
fs::write(&source, b"runner-v1").expect("write source");
copy_from_source_if_needed(&source, &destination).expect("initial copy");
let outcome = copy_from_source_if_needed(&source, &destination).expect("revalidate helper");
assert_eq!(CopyOutcome::Reused, outcome);
assert_eq!(
b"runner-v1".as_slice(),
fs::read(&destination).expect("read destination")
);
}

View File

@@ -0,0 +1,198 @@
use crate::logging::log_note;
use crate::winutil::format_last_error;
use crate::winutil::to_wide;
use anyhow::anyhow;
use std::ffi::OsStr;
use std::path::Path;
use std::path::PathBuf;
use windows_sys::Win32::Foundation::ERROR_FILE_NOT_FOUND;
use windows_sys::Win32::Foundation::ERROR_PATH_NOT_FOUND;
use windows_sys::Win32::Foundation::ERROR_SUCCESS;
use windows_sys::Win32::Foundation::GetLastError;
use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_HIDDEN;
use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_SYSTEM;
use windows_sys::Win32::Storage::FileSystem::GetFileAttributesW;
use windows_sys::Win32::Storage::FileSystem::INVALID_FILE_ATTRIBUTES;
use windows_sys::Win32::Storage::FileSystem::SetFileAttributesW;
use windows_sys::Win32::System::Registry::HKEY;
use windows_sys::Win32::System::Registry::HKEY_LOCAL_MACHINE;
use windows_sys::Win32::System::Registry::KEY_SET_VALUE;
use windows_sys::Win32::System::Registry::KEY_WRITE;
use windows_sys::Win32::System::Registry::REG_DWORD;
use windows_sys::Win32::System::Registry::REG_OPTION_NON_VOLATILE;
use windows_sys::Win32::System::Registry::RegCloseKey;
use windows_sys::Win32::System::Registry::RegCreateKeyExW;
use windows_sys::Win32::System::Registry::RegDeleteValueW;
use windows_sys::Win32::System::Registry::RegOpenKeyExW;
use windows_sys::Win32::System::Registry::RegSetValueExW;
const USERLIST_KEY_PATH: &str =
r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts\UserList";
pub fn hide_newly_created_users(usernames: &[String], log_base: &Path) {
if usernames.is_empty() {
return;
}
if let Err(err) = hide_users_in_winlogon(usernames, log_base) {
log_note(
&format!("hide users: failed to update Winlogon UserList: {err}"),
Some(log_base),
);
}
}
pub(crate) fn unhide_sandbox_users(usernames: &[&str]) -> anyhow::Result<()> {
let mut key: HKEY = std::ptr::null_mut();
match unsafe {
RegOpenKeyExW(
HKEY_LOCAL_MACHINE,
to_wide(USERLIST_KEY_PATH).as_ptr(),
/*uloptions*/ 0,
KEY_SET_VALUE,
&mut key,
)
} {
ERROR_FILE_NOT_FOUND | ERROR_PATH_NOT_FOUND => return Ok(()),
ERROR_SUCCESS => {}
error => return Err(anyhow!("open sandbox hidden-user registry key: {error}")),
}
let mut errors = Vec::new();
for username in usernames {
let status = unsafe { RegDeleteValueW(key, to_wide(username).as_ptr()) };
match status {
ERROR_SUCCESS | ERROR_FILE_NOT_FOUND => {}
error => errors.push(format!("remove hidden sandbox user {username}: {error}")),
}
}
unsafe {
RegCloseKey(key);
}
if errors.is_empty() {
Ok(())
} else {
Err(anyhow!(errors.join("; ")))
}
}
/// Best-effort: hides the current sandbox user's profile directory once it exists.
///
/// Windows only creates profile directories when that user first logs in.
/// This intentionally runs in the command-runner (as the sandbox user) because
/// command running is what causes us to log in as a particular sandbox user.
pub fn hide_current_user_profile_dir(log_base: &Path) {
let Some(profile) = std::env::var_os("USERPROFILE") else {
return;
};
let profile_dir = PathBuf::from(profile);
if !profile_dir.exists() {
return;
}
match hide_directory(&profile_dir) {
Ok(true) => {
// Log only when we actually change attributes, so this stays one-time per profile dir.
log_note(
&format!(
"hide users: profile dir hidden for current user ({})",
profile_dir.display()
),
Some(log_base),
);
}
Ok(false) => {}
Err(err) => {
log_note(
&format!(
"hide users: failed to hide current user profile dir ({}): {err}",
profile_dir.display()
),
Some(log_base),
);
}
}
}
fn hide_users_in_winlogon(usernames: &[String], log_base: &Path) -> anyhow::Result<()> {
let key = create_userlist_key()?;
for username in usernames {
let name_w = to_wide(OsStr::new(username));
let value: u32 = 0;
let status = unsafe {
RegSetValueExW(
key,
name_w.as_ptr(),
0,
REG_DWORD,
&value as *const u32 as *const u8,
std::mem::size_of_val(&value) as u32,
)
};
if status != 0 {
log_note(
&format!(
"hide users: failed to set UserList value for {username}: {status} ({error})",
error = format_last_error(status as i32)
),
Some(log_base),
);
}
}
unsafe {
RegCloseKey(key);
}
Ok(())
}
fn create_userlist_key() -> anyhow::Result<HKEY> {
let key_path = to_wide(USERLIST_KEY_PATH);
let mut key: HKEY = std::ptr::null_mut();
let status = unsafe {
RegCreateKeyExW(
HKEY_LOCAL_MACHINE,
key_path.as_ptr(),
0,
std::ptr::null_mut(),
REG_OPTION_NON_VOLATILE,
KEY_WRITE,
std::ptr::null_mut(),
&mut key,
std::ptr::null_mut(),
)
};
if status != 0 {
return Err(anyhow!(
"RegCreateKeyExW failed: {status} ({error})",
error = format_last_error(status as i32)
));
}
Ok(key)
}
/// Sets HIDDEN|SYSTEM on `path` if needed, returning whether it changed anything.
fn hide_directory(path: &Path) -> anyhow::Result<bool> {
let wide = to_wide(path);
let attrs = unsafe { GetFileAttributesW(wide.as_ptr()) };
if attrs == INVALID_FILE_ATTRIBUTES {
let err = unsafe { GetLastError() } as i32;
return Err(anyhow!(
"GetFileAttributesW failed for {}: {err} ({error})",
path.display(),
error = format_last_error(err)
));
}
let new_attrs = attrs | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
if new_attrs == attrs {
return Ok(false);
}
let ok = unsafe { SetFileAttributesW(wide.as_ptr(), new_attrs) };
if ok == 0 {
let err = unsafe { GetLastError() } as i32;
return Err(anyhow!(
"SetFileAttributesW failed for {}: {err} ({error})",
path.display(),
error = format_last_error(err)
));
}
Ok(true)
}

View File

@@ -0,0 +1,613 @@
use crate::SandboxRuntimeAccount;
use crate::WindowsSandboxProvisioningOutcome;
use crate::WindowsSandboxProvisioningSettings;
use crate::WindowsSandboxProxyListeners;
use crate::dpapi;
use crate::logging::debug_log;
use crate::resolved_permissions::ResolvedWindowsSandboxPermissions;
use crate::setup::OFFLINE_USERNAME;
use crate::setup::ONLINE_USERNAME;
use crate::setup::OfflineProxySettings;
use crate::setup::SandboxNetworkIdentity;
use crate::setup::SandboxSetupRequest;
use crate::setup::SandboxUserRecord;
use crate::setup::SandboxUsersFile;
use crate::setup::SetupMarker;
use crate::setup::gather_read_roots;
use crate::setup::gather_write_roots_for_permissions;
use crate::setup::offline_proxy_settings_from_env;
use crate::setup::run_elevated_setup_with_proxy_settings;
use crate::setup::run_setup_refresh_with_overrides_and_proxy_settings;
use crate::setup::sandbox_users_path;
use crate::setup::setup_marker_path;
use crate::winutil::local_user_flags;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use anyhow::ensure;
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use std::collections::HashMap;
use std::fs;
use std::io;
use std::os::windows::io::FromRawHandle;
use std::os::windows::io::OwnedHandle;
use std::path::Path;
use std::path::PathBuf;
use windows_sys::Win32::Foundation::ERROR_LOGON_FAILURE;
use windows_sys::Win32::Foundation::ERROR_PASSWORD_EXPIRED;
use windows_sys::Win32::Foundation::ERROR_PASSWORD_MUST_CHANGE;
use windows_sys::Win32::NetworkManagement::NetManagement::UF_ACCOUNTDISABLE;
use windows_sys::Win32::NetworkManagement::NetManagement::UF_PASSWORD_EXPIRED;
use windows_sys::Win32::Security::LOGON32_LOGON_INTERACTIVE;
use windows_sys::Win32::Security::LOGON32_PROVIDER_DEFAULT;
use windows_sys::Win32::Security::LogonUserW;
#[cfg(test)]
#[path = "identity_integration_tests.rs"]
mod integration_tests;
#[derive(Debug, Clone)]
struct SandboxIdentity {
username: String,
password: String,
}
#[derive(Debug, Clone)]
pub struct SandboxCreds {
pub username: String,
pub password: String,
}
/// Windows rejected the stored sandbox password; credential-file and policy errors are distinct.
#[derive(Debug)]
pub struct SandboxAccountCredentialMismatch;
impl std::fmt::Display for SandboxAccountCredentialMismatch {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("Windows rejected the stored sandbox account password")
}
}
impl std::error::Error for SandboxAccountCredentialMismatch {}
/// Returns true when the on-disk setup artifacts exist and match the current
/// setup version.
///
/// This is a coarse readiness check; `require_logon_sandbox_creds` performs the
/// additional runtime validation for offline firewall settings.
pub fn sandbox_setup_is_complete(codex_home: &Path) -> bool {
let marker_ok = matches!(load_marker(codex_home), Ok(Some(marker)) if marker.version_matches());
if !marker_ok {
return false;
}
if crate::registered_core_requested()
&& !crate::app_package::registered_setup_is_ready(codex_home).unwrap_or(false)
{
return false;
}
matches!(load_users(codex_home), Ok(Some(users)) if users.version_matches())
}
/// Returns true when setup artifacts and provisioned network settings match.
pub fn sandbox_setup_is_complete_with_settings(
codex_home: &Path,
settings: &crate::WindowsSandboxProvisioningSettings,
) -> bool {
let Ok(Some(mut marker)) = load_marker(codex_home) else {
return false;
};
marker.proxy_ports.sort_unstable();
let mut proxy_ports = settings.proxy_ports.clone();
proxy_ports.sort_unstable();
marker.version_matches()
&& marker.proxy_ports == proxy_ports
&& marker.allow_local_binding == settings.allow_local_binding
&& matches!(load_users(codex_home), Ok(Some(users)) if users.version_matches())
}
fn load_marker(codex_home: &Path) -> Result<Option<SetupMarker>> {
let path = setup_marker_path(codex_home);
let marker = match fs::read_to_string(&path) {
Ok(contents) => match serde_json::from_str::<SetupMarker>(&contents) {
Ok(m) => Some(m),
Err(err) => {
debug_log(
&format!("sandbox setup marker parse failed: {err}"),
Some(codex_home),
);
None
}
},
Err(err) if err.kind() == std::io::ErrorKind::NotFound => None,
Err(err) => {
debug_log(
&format!("sandbox setup marker read failed: {err}"),
Some(codex_home),
);
None
}
};
Ok(marker)
}
fn load_users(codex_home: &Path) -> Result<Option<SandboxUsersFile>> {
let path = sandbox_users_path(codex_home);
let file = match fs::read_to_string(&path) {
Ok(contents) => contents,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(err) => {
debug_log(
&format!("sandbox users read failed: {err}"),
Some(codex_home),
);
return Ok(None);
}
};
match serde_json::from_str::<SandboxUsersFile>(&file) {
Ok(users) => Ok(Some(users)),
Err(err) => {
debug_log(
&format!("sandbox users parse failed: {err}"),
Some(codex_home),
);
Ok(None)
}
}
}
fn remove_sandbox_users_file(codex_home: &Path, reason: &str) -> Result<()> {
let path = sandbox_users_path(codex_home);
debug_log(
&format!("{reason}; deleting {}", path.display()),
Some(codex_home),
);
match fs::remove_file(&path) {
Ok(()) => Ok(()),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(err) => Err(err).with_context(|| format!("delete {}", path.display())),
}
}
fn decode_password(record: &SandboxUserRecord) -> Result<String> {
let blob = BASE64_STANDARD
.decode(record.password.as_bytes())
.context("base64 decode password")?;
let decrypted = dpapi::unprotect(&blob)?;
let pwd = String::from_utf8(decrypted).context("sandbox password not utf-8")?;
Ok(pwd)
}
/// Opens a token for one existing managed account without provisioning or changing it.
/// The caller must keep the authenticated credential directory pinned and verify
/// the token's recorded SID, group membership, and non-administrator status.
pub fn logon_existing_sandbox_account(
codex_home: &Path,
account: SandboxRuntimeAccount,
) -> Result<OwnedHandle> {
// Unlike the ordinary app-side readers, this service recovery path must
// never create diagnostic files beneath an owner-controlled directory.
let marker: SetupMarker = serde_json::from_slice(
&fs::read(setup_marker_path(codex_home)).context("read sandbox setup marker")?,
)
.context("parse sandbox setup marker")?;
ensure!(
marker.version_matches(),
"sandbox setup marker is missing or incompatible"
);
let users: SandboxUsersFile = serde_json::from_slice(
&fs::read(sandbox_users_path(codex_home)).context("read sandbox accounts")?,
)
.context("parse sandbox accounts")?;
ensure!(users.version_matches(), "sandbox accounts are incompatible");
let record = match account {
SandboxRuntimeAccount::Offline => users.offline,
SandboxRuntimeAccount::Online => users.online,
};
ensure!(
record.username.eq_ignore_ascii_case(account.username()),
"sandbox account record does not match the managed account"
);
let password = crate::to_wide(decode_password(&record)?);
let mut token = std::ptr::null_mut();
if unsafe {
LogonUserW(
crate::to_wide(account.username()).as_ptr(),
crate::to_wide(".").as_ptr(),
password.as_ptr(),
LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT,
&mut token,
)
} == 0
{
return Err(account_logon_error(io::Error::last_os_error()));
}
Ok(unsafe { OwnedHandle::from_raw_handle(token as _) })
}
fn account_logon_error(error: io::Error) -> anyhow::Error {
let bad_password = matches!(
error.raw_os_error().map(|code| code as u32),
Some(ERROR_LOGON_FAILURE | ERROR_PASSWORD_EXPIRED | ERROR_PASSWORD_MUST_CHANGE)
);
let error = anyhow::Error::new(error);
if bad_password {
error.context(SandboxAccountCredentialMismatch)
} else {
error.context("log on existing sandbox account")
}
}
fn select_identity(
network_identity: SandboxNetworkIdentity,
codex_home: &Path,
) -> Result<Option<SandboxIdentity>> {
let _marker = match load_marker(codex_home)? {
Some(m) if m.version_matches() => m,
_ => return Ok(None),
};
let users = match load_users(codex_home)? {
Some(u) if u.version_matches() => u,
_ => return Ok(None),
};
let chosen = match network_identity {
SandboxNetworkIdentity::Offline => users.offline,
SandboxNetworkIdentity::Online => users.online,
};
let password = decode_password(&chosen)?;
Ok(Some(SandboxIdentity {
username: chosen.username,
password,
}))
}
#[allow(clippy::too_many_arguments)]
pub fn require_logon_sandbox_creds(
permissions: &ResolvedWindowsSandboxPermissions,
command_cwd: &Path,
env_map: &HashMap<String, String>,
codex_home: &Path,
read_roots_override: Option<&[PathBuf]>,
read_roots_include_platform_defaults: bool,
write_roots_override: Option<&[PathBuf]>,
deny_read_paths_override: &[PathBuf],
deny_write_paths_override: &[PathBuf],
proxy_enforced: bool,
proxy_settings_mode: crate::WindowsSandboxProxySettingsMode,
) -> Result<SandboxCreds> {
let runtime = crate::setup::current_setup_runtime();
let needed_read = read_roots_override
.map(<[PathBuf]>::to_vec)
.unwrap_or_else(|| {
gather_read_roots(command_cwd, permissions, env_map, codex_home, runtime)
});
let needed_write = write_roots_override
.map(<[PathBuf]>::to_vec)
.unwrap_or_else(|| gather_write_roots_for_permissions(permissions, command_cwd, env_map));
// Do not grant the capability token write access to AKODE_HOME/.sandbox; the setup helper
// grants the sandbox group access separately through lock_sandbox_dir.
let request = SandboxSetupRequest {
permissions,
command_cwd,
env_map,
codex_home,
proxy_enforced,
};
let (creds, offline_proxy_settings) = require_sandbox_account(&request, proxy_settings_mode)?;
run_setup_refresh_with_overrides_and_proxy_settings(
request,
crate::setup::SetupRootOverrides {
read_roots: Some(needed_read),
read_roots_include_platform_defaults,
write_roots: Some(needed_write),
deny_read_paths: Some(deny_read_paths_override.to_vec()),
deny_write_paths: Some(deny_write_paths_override.to_vec()),
},
&offline_proxy_settings,
)?;
Ok(creds)
}
/// Ensures the selected account is ready; launchers must refresh filesystem ACLs separately.
pub(crate) fn require_sandbox_account(
request: &SandboxSetupRequest<'_>,
proxy_settings_mode: crate::WindowsSandboxProxySettingsMode,
) -> Result<(SandboxCreds, OfflineProxySettings)> {
require_sandbox_account_with_setup(
request,
proxy_settings_mode,
run_automatic_setup,
local_user_flags,
)
}
fn require_sandbox_account_with_setup(
request: &SandboxSetupRequest<'_>,
proxy_settings_mode: crate::WindowsSandboxProxySettingsMode,
run_full_setup: impl FnOnce(SandboxSetupRequest<'_>, &OfflineProxySettings) -> Result<()>,
read_local_user_flags: impl Fn(&str) -> Result<Option<u32>>,
) -> Result<(SandboxCreds, OfflineProxySettings)> {
let &SandboxSetupRequest {
permissions,
command_cwd,
env_map,
codex_home,
proxy_enforced,
} = request;
let sandbox_dir = crate::setup::sandbox_dir(codex_home);
let network_identity = SandboxNetworkIdentity::from_permissions(permissions, proxy_enforced);
let marker = load_marker(codex_home)?;
let desired_offline_proxy_settings = desired_offline_proxy_settings(
marker.as_ref(),
proxy_settings_mode,
env_map,
network_identity,
);
let mut setup_reason: Option<String> = None;
let mut identity = match marker {
Some(marker) if marker.version_matches() => {
if let Some(reason) =
marker.request_mismatch_reason(network_identity, &desired_offline_proxy_settings)
{
setup_reason = Some(reason);
None
} else {
let selected = select_identity(network_identity, codex_home)?;
if selected.is_none() {
setup_reason = Some(
"sandbox users missing or incompatible with marker version".to_string(),
);
}
selected
}
}
_ => {
setup_reason = Some("sandbox setup marker missing or incompatible".to_string());
None
}
};
if identity.is_some() {
// Cleanup may also have removed the group, so repair missing or disabled accounts before ACL
// refresh can fail. Expired passwords also require full setup, since an ACL refresh
// cannot rotate the account passwords and update the stored DPAPI credentials.
for username in [OFFLINE_USERNAME, ONLINE_USERNAME] {
let needs_repair = match read_local_user_flags(username) {
Ok(Some(flags)) => flags & (UF_ACCOUNTDISABLE | UF_PASSWORD_EXPIRED) != 0,
Ok(None) => true,
Err(_) => false,
};
if needs_repair {
let reason = "sandbox account is missing, disabled, or password expired";
// Older services trust these credentials as proof of completed setup.
remove_sandbox_users_file(codex_home, reason)?;
setup_reason = Some(reason.to_string());
identity = None;
break;
}
}
}
if identity.is_none() {
if let Some(reason) = &setup_reason {
crate::logging::log_note(
&format!("sandbox setup required: {reason}"),
Some(&sandbox_dir),
);
} else {
crate::logging::log_note("sandbox setup required", Some(&sandbox_dir));
}
run_full_setup(
crate::setup::SandboxSetupRequest {
permissions,
command_cwd,
env_map,
codex_home,
proxy_enforced,
},
&desired_offline_proxy_settings,
)?;
for username in [OFFLINE_USERNAME, ONLINE_USERNAME] {
if let Ok(Some(flags)) = read_local_user_flags(username) {
anyhow::ensure!(
flags & UF_PASSWORD_EXPIRED == 0,
"Windows sandbox account password is still expired after setup"
);
}
}
identity = select_identity(network_identity, codex_home)?;
}
let identity = identity.ok_or_else(|| {
anyhow!(
"Windows sandbox setup is missing or out of date; rerun the sandbox setup with elevation"
)
})?;
Ok((
SandboxCreds {
username: identity.username,
password: identity.password,
},
desired_offline_proxy_settings,
))
}
// Automatic setup prefers an installed service regardless of the onboarding feature gate.
// Only an unavailable service may fall back to the UAC helper; service errors propagate.
fn run_automatic_setup(
request: SandboxSetupRequest<'_>,
settings: &OfflineProxySettings,
) -> Result<()> {
let mut listeners = WindowsSandboxProxyListeners::from_proxy_environment(request.env_map);
// Preserve-mode setup can use saved ports that differ from the current environment.
listeners
.http_ports
.retain(|port| settings.proxy_ports.contains(port));
listeners
.socks_ports
.retain(|port| settings.proxy_ports.contains(port));
match crate::provision_windows_sandbox_via_service(
request.codex_home,
WindowsSandboxProvisioningSettings {
proxy_ports: settings.proxy_ports.clone(),
allow_local_binding: settings.allow_local_binding,
},
listeners,
)? {
WindowsSandboxProvisioningOutcome::Provisioned => Ok(()),
WindowsSandboxProvisioningOutcome::Unavailable => {
run_elevated_setup_with_proxy_settings(request, settings)
}
}
}
fn desired_offline_proxy_settings(
marker: Option<&SetupMarker>,
proxy_settings_mode: crate::WindowsSandboxProxySettingsMode,
env_map: &HashMap<String, String>,
network_identity: SandboxNetworkIdentity,
) -> crate::setup::OfflineProxySettings {
match (marker, proxy_settings_mode) {
(Some(marker), crate::WindowsSandboxProxySettingsMode::Preserve)
if marker.version_matches() =>
{
marker.offline_proxy_settings()
}
_ => offline_proxy_settings_from_env(env_map, network_identity),
}
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn refresh_logon_sandbox_creds(
permissions: &ResolvedWindowsSandboxPermissions,
command_cwd: &Path,
env_map: &HashMap<String, String>,
codex_home: &Path,
read_roots_override: Option<&[PathBuf]>,
read_roots_include_platform_defaults: bool,
write_roots_override: Option<&[PathBuf]>,
deny_read_paths_override: &[PathBuf],
deny_write_paths_override: &[PathBuf],
proxy_enforced: bool,
proxy_settings_mode: crate::WindowsSandboxProxySettingsMode,
) -> Result<SandboxCreds> {
remove_sandbox_users_file(codex_home, "sandbox user login failed")?;
require_logon_sandbox_creds(
permissions,
command_cwd,
env_map,
codex_home,
read_roots_override,
read_roots_include_platform_defaults,
write_roots_override,
deny_read_paths_override,
deny_write_paths_override,
proxy_enforced,
proxy_settings_mode,
)
}
#[cfg(test)]
mod tests {
use super::desired_offline_proxy_settings;
use super::remove_sandbox_users_file;
use crate::WindowsSandboxProxySettingsMode;
use crate::setup::SandboxNetworkIdentity;
use crate::setup::SetupMarker;
use crate::setup::sandbox_users_path;
use pretty_assertions::assert_eq;
use std::collections::HashMap;
use std::fs;
use tempfile::TempDir;
#[test]
fn remove_sandbox_users_file_deletes_existing_file() {
let codex_home = TempDir::new().expect("tempdir");
let users_path = sandbox_users_path(codex_home.path());
fs::create_dir_all(users_path.parent().expect("sandbox secrets dir"))
.expect("create sandbox secrets dir");
fs::write(&users_path, "users").expect("write users");
remove_sandbox_users_file(codex_home.path(), "stale creds").expect("remove users");
assert!(!users_path.exists());
}
#[test]
fn remove_sandbox_users_file_ignores_missing_file() {
let codex_home = TempDir::new().expect("tempdir");
let users_path = sandbox_users_path(codex_home.path());
remove_sandbox_users_file(codex_home.path(), "stale creds").expect("remove users");
assert!(!users_path.exists());
}
#[test]
fn preserving_proxy_settings_uses_the_existing_marker() {
let marker = SetupMarker {
version: crate::setup::SETUP_VERSION,
offline_username: "offline".to_string(),
online_username: "online".to_string(),
created_at: None,
proxy_ports: vec![7890],
allow_local_binding: true,
};
let env_map = HashMap::from([(
"HTTP_PROXY".to_string(),
"http://127.0.0.1:8080".to_string(),
)]);
assert_eq!(
desired_offline_proxy_settings(
Some(&marker),
WindowsSandboxProxySettingsMode::Preserve,
&env_map,
SandboxNetworkIdentity::Offline,
),
marker.offline_proxy_settings()
);
assert_eq!(
desired_offline_proxy_settings(
Some(&marker),
WindowsSandboxProxySettingsMode::Reconcile,
&env_map,
SandboxNetworkIdentity::Offline,
)
.proxy_ports,
vec![8080]
);
}
#[test]
fn guardian_preserve_mode_does_not_churn_marker_with_empty_proxy_ports() {
let marker = SetupMarker {
version: crate::setup::SETUP_VERSION,
offline_username: "offline".to_string(),
online_username: "online".to_string(),
created_at: None,
proxy_ports: vec![3128, 8081],
allow_local_binding: true,
};
let env_map = HashMap::new();
let reconciled = desired_offline_proxy_settings(
Some(&marker),
WindowsSandboxProxySettingsMode::Reconcile,
&env_map,
SandboxNetworkIdentity::Offline,
);
assert_eq!(reconciled.proxy_ports, Vec::<u16>::new());
let desired = desired_offline_proxy_settings(
Some(&marker),
WindowsSandboxProxySettingsMode::Preserve,
&env_map,
SandboxNetworkIdentity::Offline,
);
assert_eq!(desired, marker.offline_proxy_settings());
assert_eq!(
marker.request_mismatch_reason(SandboxNetworkIdentity::Offline, &desired),
None
);
}
}

View File

@@ -0,0 +1,262 @@
//! Exercises account preparation with real marker files and DPAPI credentials.
//! Setup and account lookup callbacks isolate machine state. This does not exercise
//! the public wrapper, native account queries, payload serialization, singleflight,
//! or helper launches.
use super::SandboxAccountCredentialMismatch;
use super::account_logon_error;
use super::logon_existing_sandbox_account;
use super::require_sandbox_account_with_setup;
use super::sandbox_setup_is_complete_with_settings;
use crate::SandboxRuntimeAccount;
use crate::WindowsSandboxProvisioningSettings;
use crate::WindowsSandboxProxySettingsMode;
use crate::resolved_permissions::ResolvedWindowsSandboxPermissions;
use crate::setup::OFFLINE_USERNAME;
use crate::setup::ONLINE_USERNAME;
use crate::setup::SETUP_VERSION;
use crate::setup::SandboxSetupRequest;
use crate::setup::SandboxUserRecord;
use crate::setup::SandboxUsersFile;
use crate::setup::SetupMarker;
use crate::setup::sandbox_users_path;
use crate::setup::setup_marker_path;
use anyhow::Result;
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use akode_protocol::models::PermissionProfile;
use pretty_assertions::assert_eq;
use std::cell::Cell;
use std::collections::HashMap;
use std::fs;
use std::io;
use windows_sys::Win32::Foundation as win32;
use windows_sys::Win32::NetworkManagement::NetManagement::UF_ACCOUNTDISABLE;
use windows_sys::Win32::NetworkManagement::NetManagement::UF_NORMAL_ACCOUNT;
use windows_sys::Win32::NetworkManagement::NetManagement::UF_PASSWORD_EXPIRED;
#[test]
fn only_native_bad_or_expired_passwords_trigger_credential_repair() -> Result<()> {
for code in [
win32::ERROR_LOGON_FAILURE,
win32::ERROR_PASSWORD_EXPIRED,
win32::ERROR_PASSWORD_MUST_CHANGE,
] {
let error = account_logon_error(io::Error::from_raw_os_error(code as i32));
assert!(error.is::<SandboxAccountCredentialMismatch>());
assert_eq!(
error.downcast_ref::<io::Error>().unwrap().raw_os_error(),
Some(code as i32)
);
}
for code in [
win32::ERROR_ACCESS_DENIED,
win32::ERROR_ACCOUNT_RESTRICTION,
win32::ERROR_LOGON_TYPE_NOT_GRANTED,
] {
let error = account_logon_error(io::Error::from_raw_os_error(code as i32));
assert!(!error.is::<SandboxAccountCredentialMismatch>());
}
let home = tempfile::tempdir()?;
let error =
logon_existing_sandbox_account(home.path(), SandboxRuntimeAccount::Offline).unwrap_err();
assert!(!error.is::<SandboxAccountCredentialMismatch>());
Ok(())
}
#[test]
fn credential_setup_repairs_expired_accounts_once_and_reloads_credentials() -> Result<()> {
let permissions = ResolvedWindowsSandboxPermissions::try_from_permission_profile(
&PermissionProfile::read_only(),
)?;
for (expired_username, repair_succeeds) in [
(None, true),
(Some(OFFLINE_USERNAME), true),
(Some(ONLINE_USERNAME), true),
(Some(OFFLINE_USERNAME), false),
(Some(ONLINE_USERNAME), false),
] {
let home = tempfile::tempdir()?;
let marker = SetupMarker {
version: SETUP_VERSION,
offline_username: OFFLINE_USERNAME.into(),
online_username: ONLINE_USERNAME.into(),
created_at: None,
proxy_ports: vec![],
allow_local_binding: false,
};
let mut users = SandboxUsersFile {
version: SETUP_VERSION,
offline: SandboxUserRecord {
username: OFFLINE_USERNAME.into(),
password: BASE64.encode(crate::dpapi::protect(b"old-test-password")?),
},
online: SandboxUserRecord {
username: ONLINE_USERNAME.into(),
password: BASE64.encode(crate::dpapi::protect(b"old-test-password")?),
},
};
for (path, bytes) in [
(setup_marker_path(home.path()), serde_json::to_vec(&marker)?),
(sandbox_users_path(home.path()), serde_json::to_vec(&users)?),
] {
fs::create_dir_all(path.parent().unwrap())?;
fs::write(path, bytes)?;
}
let setups = Cell::new(/*value*/ 0);
let env = HashMap::new();
let result = require_sandbox_account_with_setup(
&SandboxSetupRequest {
permissions: &permissions,
command_cwd: home.path(),
env_map: &env,
codex_home: home.path(),
proxy_enforced: false,
},
WindowsSandboxProxySettingsMode::Preserve,
|_, _| {
// Older services must not accept stale credentials instead of repairing expiry.
assert!(!sandbox_users_path(home.path()).exists());
setups.set(setups.get() + 1);
users.offline.password =
BASE64.encode(crate::dpapi::protect(b"new-test-password")?);
users.online.password = users.offline.password.clone();
fs::write(sandbox_users_path(home.path()), serde_json::to_vec(&users)?)?;
Ok(())
},
|username| {
Ok(Some(
if expired_username == Some(username) && (setups.get() == 0 || !repair_succeeds)
{
UF_NORMAL_ACCOUNT | UF_PASSWORD_EXPIRED
} else {
UF_NORMAL_ACCOUNT
},
))
},
);
assert_eq!(setups.get(), usize::from(expired_username.is_some()));
assert_eq!(
result
.map(|(creds, _)| (creds.username, creds.password))
.map_err(|err| err.to_string()),
if !repair_succeeds {
Err("Windows sandbox account password is still expired after setup".into())
} else {
Ok((
OFFLINE_USERNAME.into(),
if expired_username.is_some() {
"new-test-password"
} else {
"old-test-password"
}
.into(),
))
}
);
}
Ok(())
}
#[test]
fn credential_setup_reconciles_policy_and_repairs_accounts() -> Result<()> {
let permissions = ResolvedWindowsSandboxPermissions::try_from_permission_profile(
&PermissionProfile::read_only(),
)?;
let enabled = Some(UF_NORMAL_ACCOUNT);
let disabled = Some(UF_NORMAL_ACCOUNT | UF_ACCOUNTDISABLE);
for (stored_binding, desired_binding, ports, account_flags, expected_full_setups) in [
(true, true, "8080", enabled, 0),
(true, true, "", enabled, 0),
(true, true, "8080,3129", enabled, 0),
(false, false, "8080", enabled, 1),
(false, false, "", enabled, 1),
(false, true, "3128", enabled, 1),
(true, false, "3128", enabled, 1),
(true, true, "3128", None, 1),
(true, true, "3128", disabled, 1),
] {
let full_setups = Cell::new(/*value*/ 0);
let home = tempfile::tempdir()?;
let marker = SetupMarker {
version: SETUP_VERSION,
offline_username: "offline".into(),
online_username: "online".into(),
created_at: None,
proxy_ports: vec![3128],
allow_local_binding: stored_binding,
};
let user = SandboxUserRecord {
username: marker.offline_username.clone(),
password: BASE64.encode(crate::dpapi::protect(b"test-password")?),
};
let users = SandboxUsersFile {
version: SETUP_VERSION,
offline: user.clone(),
online: SandboxUserRecord {
username: marker.online_username.clone(),
..user
},
};
let marker_bytes = serde_json::to_vec(&marker)?;
for (path, bytes) in [
(setup_marker_path(home.path()), marker_bytes.clone()),
(sandbox_users_path(home.path()), serde_json::to_vec(&users)?),
] {
fs::create_dir_all(path.parent().unwrap())?;
fs::write(path, bytes)?;
}
let env = HashMap::from([
("AKODE_WINDOWS_SANDBOX_PROXY_PORTS".into(), ports.into()),
(
"AKODE_NETWORK_ALLOW_LOCAL_BINDING".into(),
u8::from(desired_binding).to_string(),
),
]);
let account_flags = Cell::new(account_flags);
let prepare = || {
require_sandbox_account_with_setup(
&SandboxSetupRequest {
permissions: &permissions,
command_cwd: home.path(),
env_map: &env,
codex_home: home.path(),
proxy_enforced: true,
},
WindowsSandboxProxySettingsMode::Reconcile,
|request, desired| {
// Matching artifacts must not let setup skip account repair.
assert!(!sandbox_setup_is_complete_with_settings(
request.codex_home,
&WindowsSandboxProvisioningSettings {
proxy_ports: desired.proxy_ports.clone(),
allow_local_binding: desired.allow_local_binding,
}
));
full_setups.set(full_setups.get() + 1);
let mut reconciled = marker.clone();
reconciled.proxy_ports = desired.proxy_ports.clone();
reconciled.allow_local_binding = desired.allow_local_binding;
fs::write(
setup_marker_path(home.path()),
serde_json::to_vec(&reconciled)?,
)?;
fs::write(sandbox_users_path(home.path()), serde_json::to_vec(&users)?)?;
account_flags.set(enabled);
Ok(())
},
|_| Ok(account_flags.get()),
)
};
for _ in 0..2 {
let (creds, _) = prepare()?;
assert_eq!(
(creds.username, creds.password),
("offline".into(), "test-password".into())
);
}
// The second command reuses reconciled settings, including when filtering removed the proxy.
assert_eq!(full_setups.get(), expected_full_setups);
}
Ok(())
}

View File

@@ -0,0 +1,101 @@
//! Persists the authenticated sandbox owner across service restarts and package updates.
//! The shared store keeps the service's existing key, bounded REG_SZ format, and semantics.
use std::io;
use std::mem::size_of;
use std::path::PathBuf;
use std::ptr;
use anyhow::Context;
use anyhow::Result;
use anyhow::ensure;
use serde::Deserialize;
use serde::Serialize;
use windows_sys::Win32::Foundation as foundation;
use windows_sys::Win32::System::Registry as registry;
use crate::runtime_ownership::RuntimeRegistration;
use crate::winutil::to_wide;
// Package updates can replace the service key, so keep this record outside it.
pub const INSTALLATION_KEY: &str = r"SOFTWARE\OpenAI\Codex\WindowsSandboxService";
pub const INSTALLATION_VALUE: &str = "ProvisionedInstallation";
const MAX_VALUE_UNITS: usize = 4096;
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct DesktopInstallation {
pub created_codex_home: bool,
pub cache_home: PathBuf,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct InstallationRecord {
pub user_sid: String,
pub codex_home: PathBuf,
pub session_id: u32,
#[serde(default)]
pub desktop_installation: Option<DesktopInstallation>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub runtime: Option<RuntimeRegistration>,
}
pub(crate) fn load_from(key: &str) -> Result<Option<InstallationRecord>> {
let mut value = [0_u16; MAX_VALUE_UNITS];
let mut value_length = std::mem::size_of_val(&value) as u32;
let status = unsafe {
registry::RegGetValueW(
registry::HKEY_LOCAL_MACHINE,
to_wide(key).as_ptr(),
to_wide(INSTALLATION_VALUE).as_ptr(),
registry::RRF_RT_REG_SZ,
ptr::null_mut(),
value.as_mut_ptr().cast(),
&mut value_length,
)
};
match status {
foundation::ERROR_FILE_NOT_FOUND | foundation::ERROR_PATH_NOT_FOUND => return Ok(None),
foundation::ERROR_SUCCESS => {}
status => {
return Err(io::Error::from_raw_os_error(status as i32))
.context("read protected sandbox installation record");
}
}
ensure!(
value_length as usize <= std::mem::size_of_val(&value)
&& value_length.is_multiple_of(size_of::<u16>() as u32),
"sandbox installation record has an invalid length"
);
let value = value[..value_length as usize / size_of::<u16>()]
.strip_suffix(&[0])
.context("sandbox installation record is not null-terminated")?;
let value = String::from_utf16(value).context("decode sandbox installation record")?;
let record = serde_json::from_str(&value).context("parse sandbox installation record")?;
Ok(Some(record))
}
pub(crate) fn save_to(key: &str, record: &InstallationRecord) -> Result<()> {
let value = to_wide(
serde_json::to_string(record).context("serialize protected sandbox installation record")?,
);
ensure!(
value.len() <= MAX_VALUE_UNITS,
"sandbox installation record exceeds its size limit"
);
let status = unsafe {
registry::RegSetKeyValueW(
registry::HKEY_LOCAL_MACHINE,
to_wide(key).as_ptr(),
to_wide(INSTALLATION_VALUE).as_ptr(),
registry::REG_SZ,
value.as_ptr().cast(),
(value.len() * size_of::<u16>()) as u32,
)
};
if status == foundation::ERROR_SUCCESS {
Ok(())
} else {
Err(io::Error::from_raw_os_error(status as i32))
.context("persist protected sandbox installation record")
}
}

View File

@@ -0,0 +1,38 @@
//! Invocation-scoped transport for Windows sandbox payloads that exceed argv.
//! Chunks stay below the per-variable limit; no process-global environment is mutated.
#[cfg(windows)]
use anyhow::Result;
#[cfg(windows)]
use crate::environment_transport;
#[cfg(windows)]
pub(crate) const ARG: &str = "--launch-payload-env";
/// Keep small launches compatible with the existing argv protocol.
pub(crate) fn needs_environment(payload: &str) -> bool {
payload.encode_utf16().count() > 24_000
}
#[cfg(windows)]
pub(crate) fn configure_command(command: &mut std::process::Command, payload: &str) -> Result<()> {
// A wrapper may itself carry a payload. Never inherit its chunks into setup.
for (key, _) in std::env::vars_os() {
if environment_transport::is_key(&key) {
command.env_remove(key);
}
}
if needs_environment(payload) {
let mut env = std::collections::HashMap::new();
environment_transport::encode(payload, &mut env)?;
command.arg(ARG).envs(env);
} else {
command.arg(payload);
}
Ok(())
}
#[cfg(test)]
#[path = "launch_environment_tests.rs"]
mod tests;

View File

@@ -0,0 +1,16 @@
//! Select the launch transport using Windows command-line UTF-16 units.
use super::needs_environment;
use pretty_assertions::assert_eq;
#[test]
fn only_large_payloads_use_environment_transport() {
for (payload, expected) in [
("a".repeat(24_000), false),
("a".repeat(24_001), true),
("🧊".repeat(12_000), false),
("🧊".repeat(12_001), true),
] {
assert_eq!(needs_environment(&payload), expected);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,254 @@
use anyhow::Context;
use anyhow::Result;
use std::fs::File;
use std::io::Write;
use std::os::windows::io::OwnedHandle;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Mutex;
use std::sync::OnceLock;
use akode_utils_string::take_bytes_at_char_boundary;
use tracing_appender::rolling::RollingFileAppender;
use tracing_appender::rolling::Rotation;
const LOG_COMMAND_PREVIEW_LIMIT: usize = 200;
pub const LOG_FILE_PREFIX: &str = "sandbox";
pub const LOG_FILE_SUFFIX: &str = "log";
pub const MAX_LOG_FILES: usize = 90;
// Service provisioning never appends to a caller-controlled existing log entry.
// An initialized but empty slot also prevents falling back after an open failure.
static SETUP_LOG: OnceLock<Mutex<Option<(File, OwnedHandle)>>> = OnceLock::new();
fn exe_label() -> &'static str {
static LABEL: OnceLock<String> = OnceLock::new();
LABEL.get_or_init(|| {
std::env::current_exe()
.ok()
.and_then(|p| p.file_name().map(|n| n.to_string_lossy().to_string()))
.unwrap_or_else(|| "proc".to_string())
})
}
fn preview(command: &[String]) -> String {
let joined = command.join(" ");
if joined.len() <= LOG_COMMAND_PREVIEW_LIMIT {
joined
} else {
take_bytes_at_char_boundary(&joined, LOG_COMMAND_PREVIEW_LIMIT).to_string()
}
}
pub fn log_file_path_for_utc_date(base_dir: &Path, date: chrono::NaiveDate) -> PathBuf {
base_dir.join(format!(
"{LOG_FILE_PREFIX}.{}.{}",
date.format("%Y-%m-%d"),
LOG_FILE_SUFFIX
))
}
pub fn current_log_file_path(base_dir: &Path) -> PathBuf {
log_file_path_for_utc_date(base_dir, chrono::Utc::now().date_naive())
}
pub fn current_log_file_path_for_codex_home(codex_home: &Path) -> PathBuf {
current_log_file_path(&crate::sandbox_dir(codex_home))
}
pub fn log_writer(base_dir: &Path) -> Option<RollingFileAppender> {
if !base_dir.is_dir() {
return None;
}
RollingFileAppender::builder()
.rotation(Rotation::DAILY)
.filename_prefix(LOG_FILE_PREFIX)
.filename_suffix(LOG_FILE_SUFFIX)
.max_log_files(MAX_LOG_FILES)
.build(base_dir)
.ok()
}
/// Opens one fresh log for service provisioning and retains its parent directory.
/// Subsequent setup diagnostics share this handle instead of reopening a pathname.
pub fn setup_log_writer(base_dir: &Path) -> Result<File> {
let mut log = SETUP_LOG
.get_or_init(|| Mutex::new(None))
.lock()
.map_err(|_| anyhow::anyhow!("setup log lock poisoned"))?;
match log.as_ref() {
Some((file, _parent)) => file.try_clone().context("clone setup log"),
None => {
let (file, parent) = crate::file_write::create_temporary_file(base_dir, ".log")?;
let writer = file.try_clone().context("clone setup log")?;
*log = Some((file, parent));
Ok(writer)
}
}
}
/// Release setup's retained handles under the setup lock, after its writers finish.
/// Keep the slot initialized so later diagnostics cannot reopen a caller-controlled path.
pub(crate) fn release_setup_log() -> Result<()> {
if let Some(log) = SETUP_LOG.get() {
let mut log = log
.lock()
.map_err(|_| anyhow::anyhow!("setup log lock poisoned"))?;
*log = None;
}
Ok(())
}
fn append_line(line: &str, base_dir: Option<&Path>) {
if let Some(log) = SETUP_LOG.get() {
if let Ok(mut log) = log.lock()
&& let Some((file, _parent)) = log.as_mut()
{
let _ = writeln!(file, "{line}");
}
return;
}
if let Some(dir) = base_dir
&& let Some(mut f) = log_writer(dir)
{
let _ = writeln!(f, "{line}");
}
}
pub fn log_start(command: &[String], base_dir: Option<&Path>) {
let p = preview(command);
log_note(&format!("START: {p}"), base_dir);
}
pub fn log_success(command: &[String], base_dir: Option<&Path>) {
let p = preview(command);
log_note(&format!("SUCCESS: {p}"), base_dir);
}
pub fn log_failure(command: &[String], detail: &str, base_dir: Option<&Path>) {
let p = preview(command);
log_note(&format!("FAILURE: {p} ({detail})"), base_dir);
}
// Debug logging helper. Emits only when SBX_DEBUG=1 to avoid noisy logs.
pub fn debug_log(msg: &str, base_dir: Option<&Path>) {
if std::env::var("SBX_DEBUG").ok().as_deref() == Some("1") {
append_line(&format!("DEBUG: {msg}"), base_dir);
eprintln!("{msg}");
}
}
// Unconditional note logging to the daily sandbox log.
pub fn log_note(msg: &str, base_dir: Option<&Path>) {
let ts = chrono::Local::now().format("%Y-%m-%d %H:%M:%S%.3f");
append_line(&format!("[{ts} {}] {}", exe_label(), msg), base_dir);
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn setup_log_releases_handles_without_path_fallback() {
const CHILD_ENV: &str = "AKODE_TEST_SETUP_LOG_RELEASE_CHILD";
if std::env::var(CHILD_ENV).ok().as_deref() != Some("1") {
// SETUP_LOG is process-global; isolate this test from ordinary daily logging.
let output = std::process::Command::new(std::env::current_exe().expect("test binary"))
.args([
"--exact",
"logging::tests::setup_log_releases_handles_without_path_fallback",
"--nocapture",
])
.env(CHILD_ENV, "1")
.output()
.expect("run isolated setup-log test");
assert!(output.status.success(), "isolated test failed: {output:?}");
assert!(
String::from_utf8_lossy(&output.stdout).contains("setup-log release verified"),
"isolated test did not run: {output:?}"
);
return;
}
let tempdir = tempfile::tempdir().expect("tempdir");
let directory = tempdir.path().join(".sandbox");
std::fs::create_dir(&directory).expect("create sandbox directory");
drop(setup_log_writer(&directory).expect("open retained setup log"));
let error =
std::fs::remove_dir_all(&directory).expect_err("setup handles prevent deletion");
assert_eq!(
error.raw_os_error(),
Some(windows_sys::Win32::Foundation::ERROR_SHARING_VIOLATION as i32)
);
release_setup_log().expect("release setup log");
std::fs::remove_dir_all(&directory).expect("delete sandbox after releasing handles");
std::fs::create_dir(&directory).expect("recreate caller-controlled directory");
release_setup_log().expect("repeated release is harmless");
log_note("must not reopen the directory", Some(&directory));
assert!(
std::fs::read_dir(&directory)
.expect("read directory")
.next()
.is_none()
);
println!("setup-log release verified");
}
#[test]
fn preview_does_not_panic_on_utf8_boundary() {
// Place a 4-byte emoji such that naive (byte-based) truncation would split it.
let prefix = "x".repeat(LOG_COMMAND_PREVIEW_LIMIT - 1);
let command = vec![format!("{prefix}😀")];
let result = std::panic::catch_unwind(|| preview(&command));
assert!(result.is_ok());
let previewed = result.unwrap();
assert!(previewed.len() <= LOG_COMMAND_PREVIEW_LIMIT);
}
#[test]
fn log_note_writes_to_daily_rolling_log() {
let tempdir = tempfile::tempdir().expect("tempdir");
log_note("hello daily log", Some(tempdir.path()));
let entries = std::fs::read_dir(tempdir.path())
.expect("read log dir")
.collect::<Result<Vec<_>, _>>()
.expect("read entries");
assert_eq!(entries.len(), 1);
let log_path = entries[0].path();
let filename = log_path
.file_name()
.and_then(|name| name.to_str())
.expect("utf-8 filename");
assert!(filename.starts_with("sandbox."));
assert!(filename.ends_with(".log"));
let log = std::fs::read_to_string(log_path).expect("read log");
assert!(log.contains("hello daily log"));
}
#[test]
fn log_file_path_for_utc_date_matches_rolling_appender_name() {
let date = chrono::NaiveDate::from_ymd_opt(2026, 5, 21).expect("valid date");
assert_eq!(
log_file_path_for_utc_date(Path::new("logs"), date),
PathBuf::from("logs").join("sandbox.2026-05-21.log")
);
}
#[test]
fn current_log_file_path_for_codex_home_uses_sandbox_dir() {
let codex_home = Path::new("akode-home");
assert_eq!(
current_log_file_path_for_codex_home(codex_home),
current_log_file_path(&codex_home.join(".sandbox"))
);
}
}

View File

@@ -0,0 +1,284 @@
//! Opens local directories without traversing reparse points. Callers choose
//! access, sharing, and creation behavior and retain handles for their operation.
//! Handle-relative guard files keep pinned directories from becoming reparses.
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use anyhow::ensure;
use rand::RngCore;
use std::ffi::OsStr;
use std::ffi::c_void;
use std::mem::size_of;
use std::mem::size_of_val;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::io::AsRawHandle;
use std::os::windows::io::BorrowedHandle;
use std::os::windows::io::FromRawHandle;
use std::os::windows::io::OwnedHandle;
use std::path::Component;
use std::path::Path;
use std::path::Prefix;
use std::ptr;
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
use windows_sys::Win32::Foundation::NTSTATUS;
use windows_sys::Win32::Foundation::OBJ_CASE_INSENSITIVE;
use windows_sys::Win32::Foundation::OBJ_DONT_REPARSE;
use windows_sys::Win32::Foundation::RtlNtStatusToDosError;
use windows_sys::Win32::Foundation::UNICODE_STRING;
use windows_sys::Win32::Storage::FileSystem::DELETE;
use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_NORMAL;
use windows_sys::Win32::Storage::FileSystem::FILE_READ_DATA;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_WRITE;
use windows_sys::Win32::Storage::FileSystem::QueryDosDeviceW;
use windows_sys::Win32::System::IO::IO_STATUS_BLOCK;
use windows_sys::Win32::System::IO::IO_STATUS_BLOCK_0;
const FILE_OPEN: u32 = 1;
const FILE_CREATE: u32 = 2;
const FILE_OPEN_IF: u32 = 3;
const FILE_DIRECTORY_FILE: u32 = 1;
const FILE_NON_DIRECTORY_FILE: u32 = 0x40;
const FILE_DELETE_ON_CLOSE: u32 = 0x1000;
const STATUS_REPARSE_POINT_ENCOUNTERED: NTSTATUS = 0xC000_050B_u32 as i32;
#[repr(C)]
struct ObjectAttributes {
length: u32,
root_directory: HANDLE,
object_name: *const UNICODE_STRING,
attributes: u32,
security_descriptor: *const c_void,
security_quality_of_service: *const c_void,
}
#[link(name = "ntdll")]
unsafe extern "system" {
fn NtCreateFile(
file_handle: *mut HANDLE,
desired_access: u32,
object_attributes: *const ObjectAttributes,
io_status_block: *mut IO_STATUS_BLOCK,
allocation_size: *const i64,
file_attributes: u32,
share_access: u32,
create_disposition: u32,
create_options: u32,
ea_buffer: *const c_void,
ea_length: u32,
) -> NTSTATUS;
}
/// Whether a no-reparse open may create the final directory.
#[derive(Clone, Copy, Debug)]
pub enum DirectoryOpenDisposition {
OpenExisting,
OpenOrCreate,
}
/// Validates an absolute local-drive directory path without accessing the filesystem.
///
/// Relative components and alternate data streams are not directory targets.
pub fn validate_local_directory_path(path: &Path) -> Result<()> {
ensure!(
path.is_absolute(),
"directory path must be absolute: {}",
path.display()
);
let mut components = path.components();
match components.next() {
Some(Component::Prefix(prefix))
if matches!(prefix.kind(), Prefix::Disk(_) | Prefix::VerbatimDisk(_)) => {}
_ => bail!(
"directory path must have a local disk prefix: {}",
path.display()
),
}
for component in components {
match component {
Component::RootDir => {}
Component::Normal(name) if !name.to_string_lossy().contains(':') => {}
Component::Normal(_) => bail!("directory path cannot contain alternate data streams"),
Component::ParentDir | Component::CurDir | Component::Prefix(_) => {
bail!("directory path cannot contain relative or nested prefix components");
}
}
}
Ok(())
}
/// Opens a directory without following a reparse point in any path component.
/// Parent directories must exist even when creating the final directory.
///
/// Retain the handle through handle-based security mutations. To also prevent
/// renaming or deleting the directory, omit `FILE_SHARE_DELETE` and request
/// access that participates in sharing checks, such as `FILE_TRAVERSE`.
pub fn open_directory_no_reparse(
path: &Path,
desired_access: u32,
share_access: u32,
disposition: DirectoryOpenDisposition,
) -> Result<OwnedHandle> {
let mut nt_path = local_directory_nt_path(path)?;
open_no_reparse(
ptr::null_mut(),
&mut nt_path,
desired_access,
share_access,
match disposition {
DirectoryOpenDisposition::OpenExisting => FILE_OPEN,
DirectoryOpenDisposition::OpenOrCreate => FILE_OPEN_IF,
},
FILE_DIRECTORY_FILE,
)
.with_context(|| format!("open directory {}", path.display()))
}
fn local_directory_nt_path(path: &Path) -> Result<Vec<u16>> {
validate_local_directory_path(path)?;
let source_offset = if matches!(
path.components().next(),
Some(Component::Prefix(prefix)) if matches!(prefix.kind(), Prefix::VerbatimDisk(_))
) {
4
} else {
0
};
// Windows 10 also rejects the Object Manager drive-letter link under
// OBJ_DONT_REPARSE. Resolve that alias only; never canonicalize filesystem
// components, which must still be checked by NtCreateFile.
let source: Vec<u16> = path.as_os_str().encode_wide().collect();
let drive = [source[source_offset], b':' as u16, 0];
let mut nt_path = vec![0_u16; 32_768];
let length =
unsafe { QueryDosDeviceW(drive.as_ptr(), nt_path.as_mut_ptr(), nt_path.len() as u32) };
if length == 0 {
return Err(std::io::Error::last_os_error()).context("resolve directory drive");
}
nt_path.truncate(
nt_path
.iter()
.position(|unit| *unit == 0)
.unwrap_or(length as usize),
);
ensure!(
is_disk_volume(&nt_path),
"directory drive must resolve directly to a disk volume"
);
for unit in source.into_iter().skip(source_offset + 2) {
nt_path.push(if unit == b'/' as u16 {
b'\\' as u16
} else {
unit
});
}
nt_path.push(0);
Ok(nt_path)
}
fn is_disk_volume(target: &[u16]) -> bool {
let Some((prefix, number)) = target.split_at_checked(br"\Device\HarddiskVolume".len()) else {
return false;
};
// Do not pass other devices or volume subpaths to NtCreateFile.
prefix
.iter()
.zip(br"\Device\HarddiskVolume")
.all(|(&unit, expected)| {
u8::try_from(unit).is_ok_and(|unit| unit.eq_ignore_ascii_case(expected))
})
&& !number.is_empty()
&& number
.iter()
.all(|unit| (u16::from(b'0')..=u16::from(b'9')).contains(unit))
}
/// Keeps a directory nonempty, preventing in-place reparse conversion while the
/// returned handle is held. The fresh file cannot be renamed or deleted by other
/// opens and uses delete-on-close cleanup after the guard and its duplicates close.
///
/// Creation is relative to the pinned directory, never to its mutable pathname.
/// The caller must still validate that pathname after installing the guard and
/// retain its directory pins alongside the guard throughout privileged work.
pub fn create_directory_guard(directory: BorrowedHandle<'_>) -> Result<OwnedHandle> {
let mut random = [0_u8; 8];
rand::rngs::OsRng
.try_fill_bytes(&mut random)
.context("generate sandbox directory guard name")?;
let guard_id = u64::from_le_bytes(random);
let name = format!(".codex-provisioning-{guard_id:016x}.guard");
let mut name: Vec<u16> = OsStr::new(&name).encode_wide().chain(Some(0)).collect();
open_no_reparse(
directory.as_raw_handle() as HANDLE,
&mut name,
FILE_READ_DATA | DELETE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
FILE_CREATE,
FILE_NON_DIRECTORY_FILE | FILE_DELETE_ON_CLOSE,
)
.context("create sandbox directory guard")
}
pub(crate) fn open_no_reparse(
root_directory: HANDLE,
name: &mut [u16],
desired_access: u32,
share_access: u32,
disposition: u32,
create_options: u32,
) -> Result<OwnedHandle> {
let name_length = u16::try_from((name.len() - 1) * size_of::<u16>())
.context("no-reparse path is too long")?;
let maximum_length = u16::try_from(size_of_val(name)).context("no-reparse path is too long")?;
let object_name = UNICODE_STRING {
Length: name_length,
MaximumLength: maximum_length,
Buffer: name.as_mut_ptr(),
};
let object_attributes = ObjectAttributes {
length: size_of::<ObjectAttributes>() as u32,
root_directory,
object_name: &object_name,
attributes: OBJ_CASE_INSENSITIVE | OBJ_DONT_REPARSE,
security_descriptor: ptr::null(),
security_quality_of_service: ptr::null(),
};
let mut io_status_block = IO_STATUS_BLOCK {
Anonymous: IO_STATUS_BLOCK_0 { Status: 0 },
Information: 0,
};
let mut handle = std::ptr::null_mut();
let status = unsafe {
NtCreateFile(
&mut handle,
desired_access,
&object_attributes,
&mut io_status_block,
ptr::null(),
FILE_ATTRIBUTE_NORMAL,
share_access,
disposition,
create_options,
ptr::null(),
/*ea_length*/ 0,
)
};
if status < 0 {
if status == STATUS_REPARSE_POINT_ENCOUNTERED {
bail!("path contains a reparse point");
}
let error = unsafe { RtlNtStatusToDosError(status) };
return Err(std::io::Error::from_raw_os_error(error as i32)).context("NtCreateFile");
}
ensure!(
!handle.is_null() && handle != INVALID_HANDLE_VALUE,
"NtCreateFile returned an invalid handle"
);
Ok(unsafe { OwnedHandle::from_raw_handle(handle) })
}
#[cfg(test)]
#[path = "no_reparse_dir_tests.rs"]
mod tests;

View File

@@ -0,0 +1,194 @@
use std::fs;
use std::os::windows::io::OwnedHandle;
use std::path::Path;
use std::process::Command;
use windows_sys::Win32::Storage::FileSystem::FILE_READ_ATTRIBUTES;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_DELETE;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_WRITE;
use windows_sys::Win32::Storage::FileSystem::FILE_TRAVERSE;
use windows_sys::Win32::Storage::FileSystem::READ_CONTROL;
use windows_sys::Win32::Storage::FileSystem::WRITE_DAC;
use anyhow::Result;
use pretty_assertions::assert_eq;
use super::DirectoryOpenDisposition;
use super::is_disk_volume;
use super::local_directory_nt_path;
use super::open_directory_no_reparse;
use super::validate_local_directory_path;
use windows_sys::Win32::Storage::FileSystem::QueryDosDeviceW;
fn open_for_acl(path: &Path, disposition: DirectoryOpenDisposition) -> Result<OwnedHandle> {
open_directory_no_reparse(
path,
READ_CONTROL | WRITE_DAC,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
disposition,
)
}
fn create_directory_junction(target: &Path, alias: &Path) -> Result<()> {
let output = Command::new("cmd")
.args(["/C", "mklink", "/J"])
.arg(alias)
.arg(target)
.output()?;
if !output.status.success() {
anyhow::bail!(
"mklink /J failed: stdout={} stderr={}",
String::from_utf8_lossy(&output.stdout).trim(),
String::from_utf8_lossy(&output.stderr).trim()
);
}
Ok(())
}
#[test]
fn creates_and_opens_plain_directory_leaf() -> Result<()> {
let temporary = tempfile::tempdir()?;
let directory = temporary.path().join(".sandbox-bin");
drop(open_for_acl(
&directory,
DirectoryOpenDisposition::OpenOrCreate,
)?);
let _handle = open_for_acl(&directory, DirectoryOpenDisposition::OpenExisting)?;
assert!(directory.is_dir());
Ok(())
}
#[test]
fn opens_drive_root_without_following_filesystem_reparses() -> Result<()> {
let temporary = tempfile::tempdir()?;
let directory = temporary.path().canonicalize()?;
let root = directory
.ancestors()
.last()
.expect("absolute path has a root");
// canonicalize gives a verbatim drive path; exercise both supported forms.
let ordinary = root
.to_string_lossy()
.trim_start_matches(r"\\?\")
.to_owned();
let drive: Vec<_> = ordinary.encode_utf16().take(2).chain(Some(0)).collect();
let mut device = vec![0; 32_768];
if unsafe { QueryDosDeviceW(drive.as_ptr(), device.as_mut_ptr(), device.len() as u32) } == 0 {
return Err(std::io::Error::last_os_error().into());
}
device.truncate(
device
.iter()
.position(|unit| *unit == 0)
.expect("QueryDosDeviceW returns a NUL-terminated target"),
);
assert!(is_disk_volume(&device));
for path in [root, Path::new(&ordinary)] {
for suffix in ["", "no-reparse-test"] {
let mut expected = device.clone();
expected.extend(format!(r"\{suffix}").encode_utf16());
expected.push(0);
assert_eq!(local_directory_nt_path(&path.join(suffix))?, expected);
}
drop(open_directory_no_reparse(
path,
FILE_READ_ATTRIBUTES | FILE_TRAVERSE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
DirectoryOpenDisposition::OpenExisting,
)?);
}
Ok(())
}
#[test]
fn disk_volume_mapping_excludes_other_devices_and_subpaths() {
for accepted in [
r"\Device\HarddiskVolume0",
r"\Device\HarddiskVolume1",
r"\device\harddiskvolume123",
] {
assert!(is_disk_volume(&accepted.encode_utf16().collect::<Vec<_>>()));
}
for rejected in [
r"\Device\NamedPipe",
r"\Device\NamedPipe\pipe",
r"\Device\HarddiskVolume",
r"\Device\HarddiskVolume1\directory",
r"\Device\HarddiskVolume1suffix",
r"\Device\HarddiskVolumeShadowCopy1",
r"\Device\CdRom0",
r"\??\C:\directory",
] {
assert!(
!is_disk_volume(&rejected.encode_utf16().collect::<Vec<_>>()),
"accepted {rejected}"
);
}
}
#[test]
fn rejects_final_directory_junction() -> Result<()> {
let temporary = tempfile::tempdir()?;
let target = temporary.path().join("target");
let alias = temporary.path().join(".sandbox-bin");
fs::create_dir(&target)?;
create_directory_junction(&target, &alias)?;
let _ = open_for_acl(&alias, DirectoryOpenDisposition::OpenOrCreate)
.expect_err("final directory junction must be rejected");
fs::remove_dir(&alias)?;
Ok(())
}
#[test]
fn rejects_ancestor_directory_junction() -> Result<()> {
let temporary = tempfile::tempdir()?;
let target_home = temporary.path().join("target-home");
let alias_home = temporary.path().join("linked-home");
fs::create_dir(&target_home)?;
fs::create_dir(target_home.join(".sandbox-bin"))?;
create_directory_junction(&target_home, &alias_home)?;
let _ = open_for_acl(
&alias_home.join(".sandbox-bin"),
DirectoryOpenDisposition::OpenOrCreate,
)
.expect_err("ancestor directory junction must be rejected");
fs::remove_dir(&alias_home)?;
Ok(())
}
#[test]
fn open_existing_does_not_create_missing_directory() -> Result<()> {
let temporary = tempfile::tempdir()?;
let directory = temporary.path().join("missing");
assert!(open_for_acl(&directory, DirectoryOpenDisposition::OpenExisting).is_err());
assert!(!directory.exists());
Ok(())
}
#[test]
fn local_directory_path_accepts_drive_and_verbatim_drive_paths() {
assert!(validate_local_directory_path(Path::new(r"C:\Users\alice\.akode")).is_ok());
assert!(validate_local_directory_path(Path::new(r"\\?\D:\Codex Data\home")).is_ok());
}
#[test]
fn local_directory_path_rejects_relative_network_parent_and_stream_paths() {
for path in [
r"relative\.akode",
r"C:relative\.akode",
r"\\server\share\.akode",
r"\\?\UNC\server\share\.akode",
r"\\.\C:\Users\alice",
r"C:\Users\alice\..\other",
r"C:\Users\alice\.akode:stream",
] {
assert!(
validate_local_directory_path(Path::new(path)).is_err(),
"unexpectedly accepted {path}"
);
}
}

View File

@@ -0,0 +1,48 @@
//! Queries held process package identities without trusting routing hints or environment state.
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use std::io;
use windows_sys::Win32::Foundation as foundation;
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::Storage::Packaging::Appx::GetPackageFamilyName;
/// Reads a process's OS package family. Absence is not authorization.
///
/// # Safety
/// The caller must keep the process handle valid throughout the query.
pub unsafe fn process_package_family(process: HANDLE) -> Result<Option<String>> {
let mut length = 0;
let status = unsafe { GetPackageFamilyName(process, &mut length, std::ptr::null_mut()) };
if status == foundation::APPMODEL_ERROR_NO_PACKAGE {
return Ok(None);
}
if status != foundation::ERROR_INSUFFICIENT_BUFFER {
return Err(io::Error::from_raw_os_error(status as i32))
.context("query the process package family");
}
if length == 0 || length > 256 {
bail!("the process package family has an invalid length");
}
let mut buffer = vec![0_u16; length as usize];
let status = unsafe { GetPackageFamilyName(process, &mut length, buffer.as_mut_ptr()) };
if status != foundation::ERROR_SUCCESS {
return Err(io::Error::from_raw_os_error(status as i32))
.context("read the process package family");
}
let value = buffer
.get(..length as usize)
.context("the package-family API returned an invalid length")?;
let Some((&0, value)) = value.split_last() else {
bail!("the process package family is not null-terminated");
};
if value.is_empty() || value.contains(&0) {
bail!("the process package family is malformed");
}
Ok(Some(
String::from_utf16(value).context("the package family contains invalid UTF-16")?,
))
}

View File

@@ -0,0 +1,31 @@
use std::path::Path;
use std::path::PathBuf;
pub fn canonicalize_path(path: &Path) -> PathBuf {
dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
}
pub fn canonical_path_key(path: &Path) -> String {
canonicalize_path(path)
.to_string_lossy()
.replace('\\', "/")
.to_ascii_lowercase()
}
#[cfg(test)]
mod tests {
use super::canonical_path_key;
use pretty_assertions::assert_eq;
use std::path::Path;
#[test]
fn canonical_path_key_normalizes_case_and_separators() {
let windows_style = Path::new(r"C:\Users\Dev\Repo");
let slash_style = Path::new("c:/users/dev/repo");
assert_eq!(
canonical_path_key(windows_style),
canonical_path_key(slash_style)
);
}
}

View File

@@ -0,0 +1,143 @@
use std::ffi::c_void;
use std::io;
use windows_sys::Win32::Foundation::GetLastError;
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::System::Console::HPCON;
use windows_sys::Win32::System::Threading::DeleteProcThreadAttributeList;
use windows_sys::Win32::System::Threading::InitializeProcThreadAttributeList;
use windows_sys::Win32::System::Threading::LPPROC_THREAD_ATTRIBUTE_LIST;
use windows_sys::Win32::System::Threading::PROC_THREAD_ATTRIBUTE_DESKTOP_APP_POLICY;
use windows_sys::Win32::System::Threading::UpdateProcThreadAttribute;
use windows_sys::Win32::System::WindowsProgramming::PROCESS_CREATION_DESKTOP_APP_BREAKAWAY_DISABLE_PROCESS_TREE;
use windows_sys::Win32::System::WindowsProgramming::PROCESS_CREATION_DESKTOP_APP_BREAKAWAY_OVERRIDE;
const PROC_THREAD_ATTRIBUTE_HANDLE_LIST: usize = 0x0002_0002;
const PROC_THREAD_ATTRIBUTE_JOB_LIST: usize = 0x0002_000D;
const PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE: usize = 0x0002_0016;
pub struct ProcThreadAttributeList {
buffer: Vec<u8>,
handle_list: Vec<HANDLE>,
job_list: Vec<HANDLE>,
desktop_app_policy: Option<Box<u32>>,
}
impl ProcThreadAttributeList {
pub fn new(attr_count: u32) -> io::Result<Self> {
let mut size: usize = 0;
unsafe {
InitializeProcThreadAttributeList(std::ptr::null_mut(), attr_count, 0, &mut size);
}
if size == 0 {
return Err(io::Error::from_raw_os_error(unsafe {
GetLastError() as i32
}));
}
let mut buffer = vec![0u8; size];
let list = buffer.as_mut_ptr() as LPPROC_THREAD_ATTRIBUTE_LIST;
let ok = unsafe { InitializeProcThreadAttributeList(list, attr_count, 0, &mut size) };
if ok == 0 {
return Err(io::Error::from_raw_os_error(unsafe {
GetLastError() as i32
}));
}
Ok(Self {
buffer,
handle_list: Vec::new(),
job_list: Vec::new(),
desktop_app_policy: None,
})
}
pub fn as_mut_ptr(&mut self) -> LPPROC_THREAD_ATTRIBUTE_LIST {
self.buffer.as_mut_ptr() as LPPROC_THREAD_ATTRIBUTE_LIST
}
pub fn set_pseudoconsole(&mut self, hpc: HPCON) -> io::Result<()> {
// SAFETY: `hpc` is the Windows-defined value and size for this attribute.
unsafe {
self.update(
PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE,
hpc as *mut c_void,
std::mem::size_of::<HPCON>(),
)
}
}
pub fn set_handle_list(&mut self, handles: Vec<HANDLE>) -> io::Result<()> {
self.handle_list = handles;
let value = self.handle_list.as_mut_ptr().cast();
let size = std::mem::size_of_val(self.handle_list.as_slice());
// SAFETY: `value` points to `self.handle_list`, which remains alive
// while the attribute list can reference it, and `size` covers that slice.
unsafe { self.update(PROC_THREAD_ATTRIBUTE_HANDLE_LIST, value, size) }
}
pub fn set_job(&mut self, job: HANDLE) -> io::Result<()> {
// Sandboxed processes must enter the job atomically. If Windows cannot
// honor the job list (for example, because a parent job forbids
// nesting), fail the spawn rather than briefly run an uncontained
// sandbox process tree.
self.job_list = vec![job];
let value = self.job_list.as_mut_ptr().cast();
let size = std::mem::size_of_val(self.job_list.as_slice());
// SAFETY: `value` points to `self.job_list`, which remains alive while
// the attribute list can reference it, and `size` covers that slice.
unsafe { self.update(PROC_THREAD_ATTRIBUTE_JOB_LIST, value, size) }
}
pub fn preserve_desktop_app_context(&mut self) -> io::Result<()> {
// System shells otherwise leave the package environment and cannot launch
// children from its protected directory. Keep the initial child and descendants
// inside it, using the caller-provided restricted token and job containment.
// Compare compatibility outcomes via codex.windows_sandbox.runner_result.
// https://learn.microsoft.com/windows/win32/api/processthreadsapi/nf-processthreadsapi-updateprocthreadattribute
let policy = self.desktop_app_policy.insert(Box::new(
PROCESS_CREATION_DESKTOP_APP_BREAKAWAY_DISABLE_PROCESS_TREE
| PROCESS_CREATION_DESKTOP_APP_BREAKAWAY_OVERRIDE,
));
let value = std::ptr::from_mut(policy.as_mut()).cast();
// SAFETY: the boxed DWORD remains at a stable address through process creation,
// even if the attribute list moves. It is released after DeleteProcThreadAttributeList.
unsafe {
self.update(
PROC_THREAD_ATTRIBUTE_DESKTOP_APP_POLICY as usize,
value,
std::mem::size_of::<u32>(),
)
}
}
unsafe fn update(
&mut self,
attribute: usize,
value: *mut c_void,
size: usize,
) -> io::Result<()> {
let ok = unsafe {
UpdateProcThreadAttribute(
self.as_mut_ptr(),
0,
attribute,
value,
size,
std::ptr::null_mut(),
std::ptr::null_mut(),
)
};
if ok == 0 {
return Err(io::Error::from_raw_os_error(unsafe {
GetLastError() as i32
}));
}
Ok(())
}
}
impl Drop for ProcThreadAttributeList {
fn drop(&mut self) {
unsafe {
DeleteProcThreadAttributeList(self.as_mut_ptr());
}
}
}

View File

@@ -0,0 +1,368 @@
use crate::desktop::LaunchDesktop;
use crate::logging;
use crate::proc_thread_attr::ProcThreadAttributeList;
use crate::winutil::argv_to_command_line;
use crate::winutil::format_last_error;
use crate::winutil::to_wide;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use akode_utils_pty::JobObject;
use std::collections::HashMap;
use std::ffi::c_void;
use std::os::windows::io::AsRawHandle;
use std::os::windows::io::BorrowedHandle;
use std::os::windows::io::OwnedHandle;
use std::path::Path;
use std::ptr;
use std::sync::Arc;
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::Foundation::GetLastError;
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::Foundation::HANDLE_FLAG_INHERIT;
use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
use windows_sys::Win32::Foundation::SetHandleInformation;
use windows_sys::Win32::Storage::FileSystem::ReadFile;
use windows_sys::Win32::System::Console::GetStdHandle;
use windows_sys::Win32::System::Console::STD_ERROR_HANDLE;
use windows_sys::Win32::System::Console::STD_INPUT_HANDLE;
use windows_sys::Win32::System::Console::STD_OUTPUT_HANDLE;
use windows_sys::Win32::System::Pipes::CreatePipe;
use windows_sys::Win32::System::Threading::CREATE_NO_WINDOW;
use windows_sys::Win32::System::Threading::CREATE_UNICODE_ENVIRONMENT;
use windows_sys::Win32::System::Threading::CreateProcessAsUserW;
use windows_sys::Win32::System::Threading::EXTENDED_STARTUPINFO_PRESENT;
use windows_sys::Win32::System::Threading::PROCESS_INFORMATION;
use windows_sys::Win32::System::Threading::STARTF_USESTDHANDLES;
use windows_sys::Win32::System::Threading::STARTUPINFOEXW;
use windows_sys::Win32::System::Threading::STARTUPINFOW;
pub struct CreatedProcess {
pub process_info: PROCESS_INFORMATION,
pub startup_info: STARTUPINFOW,
pub(crate) job: Arc<JobObject>,
_desktop: LaunchDesktop,
}
/// Controls console creation for pipe-backed child processes.
pub enum ConsoleMode {
Inherit,
NoWindow,
}
pub fn make_env_block(env: &HashMap<String, String>) -> Vec<u16> {
let mut w: Vec<u16> = Vec::new();
for (k, v) in ordered_env_entries(env) {
let mut s = to_wide(format!("{k}={v}"));
s.pop();
w.extend_from_slice(&s);
w.push(0);
}
w.push(0);
w
}
// Match the environment we actually serialize, including for callers which
// supply multiple spellings of a Windows key. Keep the first spelling in the
// existing block order instead of letting HashMap iteration pick the value.
pub(crate) fn ordered_env_entries(env: &HashMap<String, String>) -> Vec<(&str, &str)> {
let mut items: Vec<(&str, &str)> = env
.iter()
.map(|(key, value)| (key.as_str(), value.as_str()))
.collect();
items.sort_by(|a, b| {
a.0.to_uppercase()
.cmp(&b.0.to_uppercase())
.then(a.0.cmp(b.0))
});
items.dedup_by(|a, b| a.0.eq_ignore_ascii_case(b.0));
items
}
unsafe fn ensure_inheritable_stdio(si: &mut STARTUPINFOW) -> Result<()> {
for kind in [STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE] {
let h = GetStdHandle(kind);
if h.is_null() || h == INVALID_HANDLE_VALUE {
return Err(anyhow!("GetStdHandle failed: {}", GetLastError()));
}
if SetHandleInformation(h, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT) == 0 {
return Err(anyhow!("SetHandleInformation failed: {}", GetLastError()));
}
}
si.dwFlags |= STARTF_USESTDHANDLES;
si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
Ok(())
}
/// # Safety
/// Caller must provide a valid primary token handle (`h_token`) with appropriate access,
/// and the `argv`, `cwd`, and `env_map` must remain valid for the duration of the call.
// Low-level CreateProcessAsUserW wrapper mirrors the Windows API shape.
#[allow(clippy::too_many_arguments)]
pub unsafe fn create_process_as_user(
h_token: HANDLE,
argv: &[String],
cwd: &Path,
env_map: &HashMap<String, String>,
logs_base_dir: Option<&Path>,
stdio: Option<(HANDLE, HANDLE, HANDLE)>,
console_mode: ConsoleMode,
desktop: LaunchDesktop,
) -> Result<CreatedProcess> {
let cmdline_str = argv_to_command_line(argv);
let mut cmdline: Vec<u16> = to_wide(&cmdline_str);
let env_block = make_env_block(env_map);
let job = Arc::new(JobObject::create().context("create process job")?);
let mut pi: PROCESS_INFORMATION = std::mem::zeroed();
let cwd_wide = to_wide(cwd);
let env_block_len = env_block.len();
let console_flags = match (&stdio, console_mode) {
(Some(_), ConsoleMode::NoWindow) => CREATE_NO_WINDOW,
(Some(_), ConsoleMode::Inherit)
| (None, ConsoleMode::Inherit)
| (None, ConsoleMode::NoWindow) => 0,
};
let preserve_app_context = crate::app_package::current_process_has_package_identity()?;
let attr_count = if stdio.is_some() { 2 } else { 1 } + u32::from(preserve_app_context);
let mut attrs = ProcThreadAttributeList::new(attr_count)?;
attrs.set_job(job.as_raw_handle() as HANDLE)?;
if preserve_app_context {
attrs.preserve_desktop_app_context()?;
}
let mut si: STARTUPINFOEXW = std::mem::zeroed();
si.StartupInfo.cb = std::mem::size_of::<STARTUPINFOEXW>() as u32;
// Some processes (e.g., PowerShell) can fail with STATUS_DLL_INIT_FAILED
// if lpDesktop is not set when launching with a restricted token.
// Point explicitly at the interactive desktop or a private desktop.
si.StartupInfo.lpDesktop = desktop.startup_info_desktop();
match stdio {
Some((stdin_h, stdout_h, stderr_h)) => {
si.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
si.StartupInfo.hStdInput = stdin_h;
si.StartupInfo.hStdOutput = stdout_h;
si.StartupInfo.hStdError = stderr_h;
let mut inherited_handles = vec![stdin_h, stdout_h];
if !inherited_handles.contains(&stderr_h) {
inherited_handles.push(stderr_h);
}
for &handle in &inherited_handles {
if SetHandleInformation(handle, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT) == 0 {
return Err(anyhow!(
"SetHandleInformation failed for stdio handle: {}",
GetLastError()
));
}
}
attrs.set_handle_list(inherited_handles)?;
}
None => {
ensure_inheritable_stdio(&mut si.StartupInfo)?;
}
}
si.lpAttributeList = attrs.as_mut_ptr();
let creation_flags = CREATE_UNICODE_ENVIRONMENT | EXTENDED_STARTUPINFO_PRESENT | console_flags;
let ok = CreateProcessAsUserW(
h_token,
std::ptr::null(),
cmdline.as_mut_ptr(),
std::ptr::null_mut(),
std::ptr::null_mut(),
1,
creation_flags,
env_block.as_ptr() as *mut c_void,
cwd_wide.as_ptr(),
&si.StartupInfo,
&mut pi,
);
if ok == 0 {
let err = GetLastError() as i32;
let msg = format!(
"CreateProcessAsUserW failed: {} ({}) | cwd={} | cmd={} | env_u16_len={} | si_flags={} | creation_flags={}",
err,
format_last_error(err),
cwd.display(),
cmdline_str,
env_block_len,
si.StartupInfo.dwFlags,
creation_flags,
);
logging::debug_log(&msg, logs_base_dir);
return Err(std::io::Error::from_raw_os_error(err)).context(msg);
}
Ok(CreatedProcess {
process_info: pi,
startup_info: si.StartupInfo,
job,
_desktop: desktop,
})
}
/// Controls whether the child's stdin handle is kept open for writing.
#[allow(dead_code)]
pub enum StdinMode {
Closed,
Open,
}
/// Controls how stderr is wired for a pipe-spawned process.
#[allow(dead_code)]
pub enum StderrMode {
MergeStdout,
Separate,
}
/// Handles returned by `spawn_process_with_pipes`.
#[allow(dead_code)]
pub struct PipeSpawnHandles {
pub process: PROCESS_INFORMATION,
job: Arc<JobObject>,
pub stdin_write: Option<HANDLE>,
pub stdout_read: HANDLE,
pub stderr_read: Option<HANDLE>,
pub(crate) desktop: LaunchDesktop,
}
impl PipeSpawnHandles {
/// Returns the Job Object containing the spawned process.
pub fn job(&self) -> Arc<JobObject> {
Arc::clone(&self.job)
}
}
/// Spawns a process with anonymous pipes and returns the relevant handles.
#[allow(clippy::too_many_arguments)]
pub fn spawn_process_with_pipes(
h_token: BorrowedHandle<'_>,
argv: &[String],
cwd: &Path,
env_map: &HashMap<String, String>,
stdin_mode: StdinMode,
stderr_mode: StderrMode,
console_mode: ConsoleMode,
desktop: LaunchDesktop,
logs_base_dir: Option<&Path>,
) -> Result<PipeSpawnHandles> {
let mut in_r: HANDLE = std::ptr::null_mut();
let mut in_w: HANDLE = std::ptr::null_mut();
let mut out_r: HANDLE = std::ptr::null_mut();
let mut out_w: HANDLE = std::ptr::null_mut();
let mut err_r: HANDLE = std::ptr::null_mut();
let mut err_w: HANDLE = std::ptr::null_mut();
unsafe {
if CreatePipe(&mut in_r, &mut in_w, ptr::null_mut(), 0) == 0 {
return Err(anyhow!("CreatePipe stdin failed: {}", GetLastError()));
}
if CreatePipe(&mut out_r, &mut out_w, ptr::null_mut(), 0) == 0 {
CloseHandle(in_r);
CloseHandle(in_w);
return Err(anyhow!("CreatePipe stdout failed: {}", GetLastError()));
}
if matches!(stderr_mode, StderrMode::Separate)
&& CreatePipe(&mut err_r, &mut err_w, ptr::null_mut(), 0) == 0
{
CloseHandle(in_r);
CloseHandle(in_w);
CloseHandle(out_r);
CloseHandle(out_w);
return Err(anyhow!("CreatePipe stderr failed: {}", GetLastError()));
}
}
let stderr_handle = match stderr_mode {
StderrMode::MergeStdout => out_w,
StderrMode::Separate => err_w,
};
let stdio = Some((in_r, out_w, stderr_handle));
let spawn_result = unsafe {
create_process_as_user(
h_token.as_raw_handle(),
argv,
cwd,
env_map,
logs_base_dir,
stdio,
console_mode,
desktop,
)
};
let created = match spawn_result {
Ok(v) => v,
Err(err) => {
unsafe {
CloseHandle(in_r);
CloseHandle(in_w);
CloseHandle(out_r);
CloseHandle(out_w);
if matches!(stderr_mode, StderrMode::Separate) {
CloseHandle(err_r);
CloseHandle(err_w);
}
}
return Err(err);
}
};
let CreatedProcess {
process_info: pi,
job,
_desktop: desktop,
..
} = created;
unsafe {
CloseHandle(in_r);
CloseHandle(out_w);
if matches!(stderr_mode, StderrMode::Separate) {
CloseHandle(err_w);
}
if matches!(stdin_mode, StdinMode::Closed) {
CloseHandle(in_w);
}
}
Ok(PipeSpawnHandles {
process: pi,
job,
stdin_write: match stdin_mode {
StdinMode::Open => Some(in_w),
StdinMode::Closed => None,
},
stdout_read: out_r,
stderr_read: match stderr_mode {
StderrMode::Separate => Some(err_r),
StderrMode::MergeStdout => None,
},
desktop,
})
}
/// Reads an owned handle until EOF and invokes `on_chunk` for each read.
pub fn read_handle_loop<F>(handle: OwnedHandle, mut on_chunk: F) -> std::thread::JoinHandle<()>
where
F: FnMut(&[u8]) + Send + 'static,
{
std::thread::spawn(move || {
let mut buf = [0u8; 8192];
loop {
let mut read_bytes: u32 = 0;
let ok = unsafe {
ReadFile(
handle.as_raw_handle(),
buf.as_mut_ptr(),
buf.len() as u32,
&mut read_bytes,
ptr::null_mut(),
)
};
if ok == 0 || read_bytes == 0 {
break;
}
on_chunk(&buf[..read_bytes as usize]);
}
})
}

View File

@@ -0,0 +1,469 @@
//! Authenticated client for the packaged Windows sandbox provisioning service.
use crate::WindowsSandboxProvisioningSettings;
use crate::WindowsSandboxProxyListeners;
use std::collections::HashMap;
use std::fs::File;
use std::fs::OpenOptions;
use std::io;
use std::mem::size_of;
use std::os::windows::fs::OpenOptionsExt;
use std::os::windows::io::AsRawHandle;
use std::path::Path;
use std::ptr;
use std::time::Duration;
use std::time::Instant;
use anyhow::Context;
use anyhow::anyhow;
use anyhow::bail;
use akode_protocol::models::PermissionProfile;
use akode_protocol::shell_environment::OPENAI_FEDERATION_RULE_ID_ENV_VAR;
use akode_protocol::shell_environment::OPENAI_IDENTITY_TOKEN_FILE_ENV_VAR;
use windows_sys::Win32::Foundation::ERROR_BROKEN_PIPE;
use windows_sys::Win32::Foundation::ERROR_FILE_NOT_FOUND;
use windows_sys::Win32::Foundation::ERROR_NO_DATA;
use windows_sys::Win32::Foundation::ERROR_PIPE_BUSY;
use windows_sys::Win32::Foundation::ERROR_PIPE_NOT_CONNECTED;
use windows_sys::Win32::Foundation::ERROR_SEM_TIMEOUT;
use windows_sys::Win32::Foundation::ERROR_SERVICE_ALREADY_RUNNING;
use windows_sys::Win32::Foundation::ERROR_SERVICE_DOES_NOT_EXIST;
use windows_sys::Win32::Foundation::ERROR_SERVICE_MARKED_FOR_DELETE;
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::Storage::FileSystem::SECURITY_IMPERSONATION;
use windows_sys::Win32::Storage::FileSystem::SECURITY_SQOS_PRESENT;
use windows_sys::Win32::System::Pipes::GetNamedPipeServerProcessId;
use windows_sys::Win32::System::Pipes::WaitNamedPipeW;
use windows_sys::Win32::System::Services;
use windows_sys::Win32::System::Services::SC_HANDLE;
const PROVISIONING_TIMEOUT: Duration = Duration::from_secs(120);
const SERVICE_STARTUP_TIMEOUT: Duration = Duration::from_secs(5);
mod group_change;
mod refresh_retry;
impl WindowsSandboxProvisioningSettings {
/// Derives the full firewall settings using the same environment handling as elevated setup.
pub fn from_environment(
permission_profile: &PermissionProfile,
env_map: &HashMap<String, String>,
) -> Self {
let network_identity = if permission_profile.network_sandbox_policy().is_enabled() {
crate::setup::SandboxNetworkIdentity::Online
} else {
crate::setup::SandboxNetworkIdentity::Offline
};
let settings = crate::setup::offline_proxy_settings_from_env(env_map, network_identity);
Self {
proxy_ports: settings.proxy_ports,
allow_local_binding: settings.allow_local_binding,
}
}
}
impl WindowsSandboxProxyListeners {
/// Identifies known listener protocols without restricting the ports allowed by setup.
pub fn from_environment(
permission_profile: &PermissionProfile,
env_map: &HashMap<String, String>,
) -> Self {
if permission_profile.network_sandbox_policy().is_enabled() {
return Self::default();
}
Self::from_proxy_environment(env_map)
}
pub(crate) fn from_proxy_environment(env_map: &HashMap<String, String>) -> Self {
let mut listeners = Self::default();
for value in crate::setup::PROXY_ENV_KEYS
.iter()
.filter_map(|key| env_map.get(*key))
{
let Some((scheme, _)) = value.trim().split_once("://") else {
continue;
};
let Some(port) = crate::setup::loopback_proxy_port_from_url(value) else {
continue;
};
match scheme.to_ascii_lowercase().as_str() {
"http" | "https" => listeners.http_ports.push(port),
"socks4" | "socks4a" | "socks5" | "socks5h" => {
listeners.socks_ports.push(port);
}
_ => {}
}
}
listeners.http_ports.sort_unstable();
listeners.http_ports.dedup();
listeners.socks_ports.sort_unstable();
listeners.socks_ports.dedup();
listeners
}
}
/// Result of attempting setup through the packaged provisioning service.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum WindowsSandboxProvisioningOutcome {
/// The service completed elevated provisioning.
Provisioned,
/// The service was absent, did not support this caller, or timed out.
Unavailable,
}
enum ProvisioningIntent {
Setup,
RefreshRegistration,
}
/// Refreshes only an already-provisioned gated runtime; no helper or setup fallback.
#[doc(hidden)]
pub fn refresh_registered_core_via_service(
codex_home: &Path,
settings: WindowsSandboxProvisioningSettings,
listeners: WindowsSandboxProxyListeners,
) -> anyhow::Result<WindowsSandboxProvisioningOutcome> {
anyhow::ensure!(
crate::registered_core_requested(),
"registered Core is not enabled"
);
provision(
codex_home,
settings,
listeners,
ProvisioningIntent::RefreshRegistration,
)
}
/// Provisions the elevated Windows sandbox through the authenticated packaged service.
pub fn provision_windows_sandbox_via_service(
codex_home: &Path,
settings: WindowsSandboxProvisioningSettings,
listeners: WindowsSandboxProxyListeners,
) -> anyhow::Result<WindowsSandboxProvisioningOutcome> {
// The IPC request does not carry the caller's workload-identity environment.
// Select helper fallback here: a service error would propagate, not fall back.
// service_unavailable still rejects helper fallback for registered Core.
if std::env::var_os(OPENAI_FEDERATION_RULE_ID_ENV_VAR).is_some()
|| std::env::var_os(OPENAI_IDENTITY_TOKEN_FILE_ENV_VAR).is_some()
{
return service_unavailable();
}
provision(codex_home, settings, listeners, ProvisioningIntent::Setup)
}
fn provision(
codex_home: &Path,
settings: WindowsSandboxProvisioningSettings,
listeners: WindowsSandboxProxyListeners,
intent: ProvisioningIntent,
) -> anyhow::Result<WindowsSandboxProvisioningOutcome> {
let request = crate::FramedProvisioningMessage {
version: crate::PROVISIONING_PROTOCOL_VERSION,
message: crate::ProvisioningMessage::ProvisionSandboxRequest {
payload: crate::SandboxProvisioningRequest {
codex_home: codex_home
.to_str()
.context("sandbox provisioning home is not valid UTF-8")?
.to_owned(),
registered_core: crate::registered_core_requested(),
refresh_only: matches!(intent, ProvisioningIntent::RefreshRegistration),
settings,
listeners,
},
},
};
match send_service_request(&request, PROVISIONING_TIMEOUT)? {
crate::SandboxProvisioningResponse::Ok => {
Ok(WindowsSandboxProvisioningOutcome::Provisioned)
}
crate::SandboxProvisioningResponse::Unavailable => service_unavailable(),
crate::SandboxProvisioningResponse::Error { message } => Err(anyhow!(message)),
}
}
fn service_unavailable() -> anyhow::Result<WindowsSandboxProvisioningOutcome> {
if crate::registered_core_requested() {
bail!("app runtime provisioning service is unavailable; refusing helper fallback");
}
Ok(WindowsSandboxProvisioningOutcome::Unavailable)
}
/// Starts a stopped service only for explicit setup. The normal connection path
/// waits for startup and authenticates the pipe server; SCM authorizes the start.
pub fn start_windows_sandbox_service_for_setup() -> anyhow::Result<()> {
query_service_status()
.and_then(|status| {
if status.dwCurrentState == Services::SERVICE_STOPPED {
let service = open_service(Services::SERVICE_START)
.context("request permission to start sandbox service for setup")?;
if unsafe { Services::StartServiceW(service.0, 0, ptr::null()) } == 0 {
let error = io::Error::last_os_error();
if error.raw_os_error() != Some(ERROR_SERVICE_ALREADY_RUNNING as i32) {
return Err(error).context("start sandbox service for setup");
}
}
}
Ok(())
})
.or_else(|error| {
if error.downcast_ref::<io::Error>().is_some_and(|error| {
matches!(error.raw_os_error(), Some(code)
if code == ERROR_SERVICE_DOES_NOT_EXIST as i32
|| code == ERROR_SERVICE_MARKED_FOR_DELETE as i32)
}) {
// The connection path preserves registered Core's no-fallback error.
Ok(())
} else {
Err(error)
}
})
}
/// Records desktop uninstall ownership without creating or enabling a sandbox.
pub fn register_desktop_installation(codex_home: &Path) -> anyhow::Result<()> {
let request = crate::FramedProvisioningMessage {
version: crate::PROVISIONING_PROTOCOL_VERSION,
message: crate::ProvisioningMessage::RegisterInstallationRequest {
codex_home: codex_home
.to_str()
.context("desktop home is not valid UTF-8")?
.to_owned(),
},
};
match send_service_request(&request, Duration::from_secs(5))? {
crate::SandboxProvisioningResponse::Ok => Ok(()),
crate::SandboxProvisioningResponse::Unavailable => {
bail!("desktop uninstall registration service is unavailable")
}
crate::SandboxProvisioningResponse::Error { message } => Err(anyhow!(message)),
}
}
fn send_service_request(
request: &crate::FramedProvisioningMessage,
timeout: Duration,
) -> anyhow::Result<crate::SandboxProvisioningResponse> {
let deadline = Instant::now() + timeout;
let Some(mut pipe) = connect(deadline)? else {
return Ok(crate::SandboxProvisioningResponse::Unavailable);
};
if let crate::ProvisioningMessage::ProvisionSandboxRequest { payload } = &request.message
&& payload.registered_core
&& payload.refresh_only
{
return refresh_retry::send(pipe, request, deadline);
}
let response = match exchange_request(&mut pipe, request, deadline) {
Ok(response) => response,
Err(error)
if error.downcast_ref::<io::Error>().is_some_and(|error| {
matches!(
error.kind(),
io::ErrorKind::UnexpectedEof | io::ErrorKind::TimedOut
) || matches!(
error.raw_os_error(),
Some(code)
if code == ERROR_BROKEN_PIPE as i32
|| code == ERROR_NO_DATA as i32
|| code == ERROR_PIPE_NOT_CONNECTED as i32
)
}) =>
{
return Ok(crate::SandboxProvisioningResponse::Unavailable);
}
Err(error) => return Err(error),
};
if matches!(&response, crate::SandboxProvisioningResponse::Error { message }
if message == crate::SANDBOX_GROUP_CHANGED)
{
drop(pipe);
return group_change::retry(request, deadline);
}
Ok(response)
}
fn exchange_request(
pipe: &mut File,
request: &crate::FramedProvisioningMessage,
deadline: Instant,
) -> anyhow::Result<crate::SandboxProvisioningResponse> {
verify_server(pipe.as_raw_handle() as HANDLE)
.context("authenticate provisioning pipe server")?;
if Instant::now() >= deadline {
return Err(io::Error::new(
io::ErrorKind::TimedOut,
"sandbox provisioning deadline expired before sending request",
)
.into());
}
crate::write_provisioning_frame(&mut *pipe, request)
.context("send sandbox provisioning request")?;
read_response(pipe, deadline)
}
fn read_response(
pipe: &mut File,
deadline: Instant,
) -> anyhow::Result<crate::SandboxProvisioningResponse> {
crate::framed_io::wait_for_complete_frame(pipe, deadline)
.context("wait for sandbox provisioning response")?;
let response = crate::read_provisioning_frame(pipe)
.context("read sandbox provisioning response")?
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::UnexpectedEof,
"sandbox provisioning service closed the pipe without a response",
)
})
.context("read sandbox provisioning response")?;
if response.version != crate::PROVISIONING_PROTOCOL_VERSION {
return Ok(crate::SandboxProvisioningResponse::Unavailable);
}
let crate::ProvisioningMessage::ProvisionSandboxResponse { payload } = response.message else {
bail!("unexpected sandbox provisioning response message");
};
Ok(payload)
}
fn connect(deadline: Instant) -> anyhow::Result<Option<File>> {
// Startup should not hold up the desktop's readiness check for the full
// provisioning timeout. Keep the caller's original deadline for real work.
let startup_deadline = deadline.min(Instant::now() + SERVICE_STARTUP_TIMEOUT);
let pipe_name = crate::windows_sandbox_service_pipe_name()?;
let open_pipe = || {
OpenOptions::new()
.read(true)
.write(true)
.custom_flags(SECURITY_SQOS_PRESENT | SECURITY_IMPERSONATION)
.open(&pipe_name)
};
let pipe_name = crate::to_wide(&pipe_name);
loop {
match query_service_status() {
Ok(status) if status.dwCurrentState == Services::SERVICE_START_PENDING => {
let remaining = startup_deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
return Ok(None);
}
std::thread::sleep(remaining.min(Duration::from_millis(25)));
continue;
}
Ok(status) if status.dwCurrentState == Services::SERVICE_RUNNING => {}
Ok(_) => return Ok(None),
Err(error)
if error.downcast_ref::<io::Error>().is_some_and(|error| {
matches!(
error.raw_os_error(),
Some(code)
if code == ERROR_SERVICE_DOES_NOT_EXIST as i32
|| code == ERROR_SERVICE_MARKED_FOR_DELETE as i32
)
}) =>
{
return Ok(None);
}
Err(error) => return Err(error),
}
match open_pipe() {
Ok(pipe) => return Ok(Some(pipe)),
Err(error) if error.raw_os_error() == Some(ERROR_FILE_NOT_FOUND as i32) => {
return Ok(None);
}
Err(error) if error.raw_os_error() == Some(ERROR_PIPE_BUSY as i32) => {
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
return Ok(None);
}
let wait_ms = u32::try_from(remaining.as_millis())
.unwrap_or(u32::MAX)
.max(1);
if unsafe { WaitNamedPipeW(pipe_name.as_ptr(), wait_ms) } == 0 {
let error = io::Error::last_os_error();
if error.raw_os_error() == Some(ERROR_FILE_NOT_FOUND as i32) {
continue;
}
if error.raw_os_error() == Some(ERROR_SEM_TIMEOUT as i32) {
return Ok(None);
}
return Err(error).context("wait for sandbox provisioning pipe");
}
}
Err(error) => return Err(error).context("open sandbox provisioning pipe"),
}
}
}
fn pipe_server_process_id(pipe: HANDLE) -> anyhow::Result<u32> {
let mut pipe_process_id = 0;
if unsafe { GetNamedPipeServerProcessId(pipe, &mut pipe_process_id) } == 0 {
return Err(io::Error::last_os_error()).context("identify provisioning pipe server");
}
Ok(pipe_process_id)
}
fn verify_server(pipe: HANDLE) -> anyhow::Result<u32> {
let pipe_process_id = pipe_server_process_id(pipe)?;
let status = query_service_status()?;
if status.dwCurrentState != Services::SERVICE_RUNNING
|| status.dwProcessId == 0
|| status.dwProcessId != pipe_process_id
{
bail!("the provisioning pipe server does not match the running service");
}
Ok(pipe_process_id)
}
fn query_service_status() -> anyhow::Result<Services::SERVICE_STATUS_PROCESS> {
let service = open_service(Services::SERVICE_QUERY_STATUS)?;
let mut status: Services::SERVICE_STATUS_PROCESS = unsafe { std::mem::zeroed() };
let mut bytes_needed = 0;
if unsafe {
Services::QueryServiceStatusEx(
service.0,
Services::SC_STATUS_PROCESS_INFO,
ptr::from_mut(&mut status).cast(),
size_of::<Services::SERVICE_STATUS_PROCESS>() as u32,
&mut bytes_needed,
)
} == 0
{
return Err(io::Error::last_os_error()).context("query sandbox provisioning service");
}
if status.dwCurrentState == Services::SERVICE_STOPPED {
crate::service_diagnostics::record_stopped(&status, service.0);
}
Ok(status)
}
fn open_service(access: u32) -> anyhow::Result<ServiceHandle> {
let manager =
unsafe { Services::OpenSCManagerW(ptr::null(), ptr::null(), Services::SC_MANAGER_CONNECT) };
if manager.is_null() {
return Err(io::Error::last_os_error()).context("open service control manager");
}
let manager = ServiceHandle(manager);
let service_name = crate::to_wide(crate::windows_sandbox_service_name()?);
let service = unsafe { Services::OpenServiceW(manager.0, service_name.as_ptr(), access) };
if service.is_null() {
return Err(io::Error::last_os_error()).context("open sandbox provisioning service");
}
Ok(ServiceHandle(service))
}
struct ServiceHandle(SC_HANDLE);
impl Drop for ServiceHandle {
fn drop(&mut self) {
if !self.0.is_null() {
unsafe { Services::CloseServiceHandle(self.0) };
}
}
}
#[cfg(test)]
#[path = "provisioning_client_tests.rs"]
mod tests;

View File

@@ -0,0 +1,25 @@
//! Retry only the service's authenticated refusal before dispatch.
//! A lost response may follow a mutation, so the retry's transport errors stay errors.
use std::time::Duration;
use std::time::Instant;
use crate::FramedProvisioningMessage;
use crate::SandboxProvisioningResponse;
pub(super) fn retry(
request: &FramedProvisioningMessage,
deadline: Instant,
) -> anyhow::Result<SandboxProvisioningResponse> {
let mut pipe = loop {
if let Some(pipe) = super::connect(deadline)? {
break pipe;
}
anyhow::ensure!(
Instant::now() < deadline,
"refreshed sandbox service pipe is unavailable"
);
std::thread::sleep(Duration::from_millis(25));
};
super::exchange_request(&mut pipe, request, deadline)
}

View File

@@ -0,0 +1,105 @@
//! Resume gated registration refresh only after an authenticated service restart.
//! Only response-side pipe disconnections qualify, never failed authentication,
//! failed request writes, explicit replies, or protocol errors.
use std::fs::File;
use std::io;
use std::os::windows::io::AsRawHandle;
use std::time::Duration;
use std::time::Instant;
use anyhow::Context;
use windows_sys::Win32::Foundation::ERROR_BROKEN_PIPE;
use windows_sys::Win32::Foundation::ERROR_NO_DATA;
use windows_sys::Win32::Foundation::ERROR_PIPE_NOT_CONNECTED;
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::System::Services::SERVICE_START_PENDING;
use crate::FramedProvisioningMessage;
use crate::SandboxProvisioningResponse;
// Registering the service-bearing package can restart the service once for each
// of the two managed accounts. Keep both retries inside the original deadline.
const MAX_SERVICE_RESTARTS: usize = 2;
const RECONNECT_POLL_INTERVAL: Duration = Duration::from_millis(25);
pub(super) fn send(
mut pipe: File,
request: &FramedProvisioningMessage,
deadline: Instant,
) -> anyhow::Result<SandboxProvisioningResponse> {
let mut restarts_remaining = MAX_SERVICE_RESTARTS;
loop {
remaining_time(deadline)?;
let server_pid = super::verify_server(pipe.as_raw_handle() as HANDLE)
.context("authenticate provisioning pipe server")?;
crate::write_provisioning_frame(&mut pipe, request)
.context("send sandbox provisioning request")?;
let response = super::read_response(&mut pipe, deadline);
if !take_restart(&response, &mut restarts_remaining, deadline) {
return response;
}
drop(pipe);
pipe = connect_after_restart(server_pid, deadline)?;
}
}
fn connect_after_restart(previous_pid: u32, deadline: Instant) -> anyhow::Result<File> {
loop {
remaining_time(deadline)?;
if let Some(pipe) = super::connect(deadline)?
&& super::pipe_server_process_id(pipe.as_raw_handle() as HANDLE)? != previous_pid
// The service creates its listener before reporting RUNNING.
&& super::query_service_status()?.dwCurrentState != SERVICE_START_PENDING
{
// The caller authenticates this new PID against the running SCM
// service before writing. A same-PID reuse is conservatively refused.
return Ok(pipe);
}
std::thread::sleep(remaining_time(deadline)?.min(RECONNECT_POLL_INTERVAL));
}
}
fn remaining_time(deadline: Instant) -> io::Result<Duration> {
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
return Err(io::Error::new(
io::ErrorKind::TimedOut,
"timed out waiting for restarted sandbox provisioning service",
));
}
Ok(remaining)
}
fn take_restart(
response: &anyhow::Result<SandboxProvisioningResponse>,
restarts_remaining: &mut usize,
deadline: Instant,
) -> bool {
let Err(error) = response else {
return false;
};
if *restarts_remaining == 0
|| Instant::now() >= deadline
|| !error.downcast_ref::<io::Error>().is_some_and(|error| {
matches!(
error.kind(),
io::ErrorKind::UnexpectedEof | io::ErrorKind::BrokenPipe
) || matches!(
error.raw_os_error(),
Some(code)
if code == ERROR_BROKEN_PIPE as i32
|| code == ERROR_NO_DATA as i32
|| code == ERROR_PIPE_NOT_CONNECTED as i32
)
})
{
return false;
}
*restarts_remaining -= 1;
true
}
#[cfg(test)]
#[path = "refresh_retry_tests.rs"]
mod tests;

View File

@@ -0,0 +1,121 @@
//! Regression coverage for reply classification and the shared restart deadline/budget.
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn authentication_failure_cannot_write_or_replay_the_request() -> anyhow::Result<()> {
let pipe = tempfile::tempfile()?;
let observation = pipe.try_clone()?;
let request = FramedProvisioningMessage {
version: crate::PROVISIONING_PROTOCOL_VERSION,
message: crate::ProvisioningMessage::ProvisionSandboxRequest {
payload: crate::SandboxProvisioningRequest {
codex_home: r"C:\test-home".to_owned(),
registered_core: true,
refresh_only: true,
settings: crate::WindowsSandboxProvisioningSettings {
proxy_ports: Vec::new(),
allow_local_binding: false,
},
listeners: crate::WindowsSandboxProxyListeners::default(),
},
},
};
let error = send(pipe, &request, Instant::now() + Duration::from_secs(60)).unwrap_err();
assert_eq!(error.to_string(), "authenticate provisioning pipe server");
assert_eq!(observation.metadata()?.len(), 0);
Ok(())
}
#[test]
fn permits_two_response_disconnects_but_not_a_third() {
let deadline = Instant::now() + Duration::from_secs(60);
let response = Err(io::Error::from(io::ErrorKind::UnexpectedEof).into());
let mut remaining = MAX_SERVICE_RESTARTS;
let decisions = (0..3)
.map(|_| take_restart(&response, &mut remaining, deadline))
.collect::<Vec<_>>();
assert_eq!((decisions, remaining), (vec![true, true, false], 0));
}
#[test]
fn accepts_only_response_pipe_disconnect_errors() {
let deadline = Instant::now() + Duration::from_secs(60);
for error in [
io::Error::from(io::ErrorKind::UnexpectedEof),
io::Error::from(io::ErrorKind::BrokenPipe),
io::Error::from_raw_os_error(ERROR_BROKEN_PIPE as i32),
io::Error::from_raw_os_error(ERROR_NO_DATA as i32),
io::Error::from_raw_os_error(ERROR_PIPE_NOT_CONNECTED as i32),
] {
let response = Err(anyhow::Error::from(error).context("read response"));
let mut remaining = MAX_SERVICE_RESTARTS;
assert_eq!(
(take_restart(&response, &mut remaining, deadline), remaining),
(true, 1)
);
}
}
#[test]
fn explicit_replies_never_consume_a_restart() {
let deadline = Instant::now() + Duration::from_secs(60);
for response in [
SandboxProvisioningResponse::Ok,
SandboxProvisioningResponse::Unavailable,
SandboxProvisioningResponse::Error {
message: "refused".to_owned(),
},
SandboxProvisioningResponse::Error {
message: crate::SANDBOX_GROUP_CHANGED.to_owned(),
},
] {
let mut remaining = MAX_SERVICE_RESTARTS;
assert_eq!(
(
take_restart(&Ok(response), &mut remaining, deadline),
remaining
),
(false, MAX_SERVICE_RESTARTS)
);
}
}
#[test]
fn timeout_permission_and_protocol_errors_do_not_consume_a_restart() {
let deadline = Instant::now() + Duration::from_secs(60);
for error in [
io::Error::from(io::ErrorKind::TimedOut).into(),
io::Error::from(io::ErrorKind::PermissionDenied).into(),
io::Error::from(io::ErrorKind::InvalidData).into(),
anyhow::anyhow!("unexpected sandbox provisioning response message"),
serde_json::from_str::<FramedProvisioningMessage>("not JSON")
.unwrap_err()
.into(),
] {
let mut remaining = MAX_SERVICE_RESTARTS;
assert_eq!(
(
take_restart(&Err(error), &mut remaining, deadline),
remaining
),
(false, MAX_SERVICE_RESTARTS)
);
}
}
#[test]
fn disconnect_after_original_deadline_is_not_retried() {
let deadline = Instant::now();
let response = Err(io::Error::from(io::ErrorKind::UnexpectedEof).into());
let mut remaining = MAX_SERVICE_RESTARTS;
assert_eq!(
(take_restart(&response, &mut remaining, deadline), remaining),
(false, MAX_SERVICE_RESTARTS)
);
assert_eq!(
remaining_time(deadline).unwrap_err().kind(),
io::ErrorKind::TimedOut
);
}

View File

@@ -0,0 +1,70 @@
//! Exercises process-local workload-identity routing without contacting the service.
use super::WindowsSandboxProvisioningOutcome;
use super::provision_windows_sandbox_via_service;
use crate::WindowsSandboxProvisioningSettings;
use crate::WindowsSandboxProxyListeners;
use anyhow::Result;
use akode_protocol::shell_environment::OPENAI_FEDERATION_RULE_ID_ENV_VAR;
use akode_protocol::shell_environment::OPENAI_IDENTITY_TOKEN_FILE_ENV_VAR;
use pretty_assertions::assert_eq;
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
use std::path::PathBuf;
use std::process::Command;
#[test]
fn workload_identity_selects_helper_fallback_except_for_registered_core() -> Result<()> {
for variable in [
OPENAI_FEDERATION_RULE_ID_ENV_VAR,
OPENAI_IDENTITY_TOKEN_FILE_ENV_VAR,
] {
for registered_core in ["0", "1"] {
let output = Command::new(std::env::current_exe()?)
.args([
"--exact",
"provisioning_client::tests::workload_identity_child",
"--ignored",
"--nocapture",
])
.env_remove(OPENAI_FEDERATION_RULE_ID_ENV_VAR)
.env_remove(OPENAI_IDENTITY_TOKEN_FILE_ENV_VAR)
.env(variable, "test-only")
.env("AKODE_WINDOWS_REGISTERED_CORE", registered_core)
.output()?;
assert!(
output.status.success(),
"{variable}, registered_core={registered_core}: {}{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
);
}
}
Ok(())
}
#[test]
#[ignore = "child process for workload_identity_selects_helper_fallback_except_for_registered_core"]
fn workload_identity_child() -> Result<()> {
// If the early guard regresses, this fails payload validation before any IPC.
let invalid_home = PathBuf::from(OsString::from_wide(&[0xd800]));
let outcome = provision_windows_sandbox_via_service(
&invalid_home,
WindowsSandboxProvisioningSettings {
proxy_ports: Vec::new(),
allow_local_binding: false,
},
WindowsSandboxProxyListeners::default(),
);
if crate::registered_core_requested() {
assert_eq!(
outcome
.expect_err("registered Core must not fall back")
.to_string(),
"app runtime provisioning service is unavailable; refusing helper fallback"
);
} else {
assert_eq!(outcome?, WindowsSandboxProvisioningOutcome::Unavailable);
}
Ok(())
}

View File

@@ -0,0 +1,89 @@
//! Dedicated protocol exchanged with the Windows sandbox provisioning service.
use crate::WindowsSandboxProvisioningSettings;
use anyhow::Result;
use serde::Deserialize;
use serde::Serialize;
use std::io::Read;
use std::io::Write;
/// Protocol version shared by provisioning clients and the Windows service.
pub const PROVISIONING_PROTOCOL_VERSION: u8 = 1;
/// Named pipe used by the machine-wide Windows sandbox provisioning service.
pub const SANDBOX_PROVISIONING_PIPE_NAME: &str = r"\\.\pipe\OpenAI.CodexSandbox";
/// Pre-dispatch refusal: the caller may reconnect once to the refreshed pipe.
pub const SANDBOX_GROUP_CHANGED: &str = "sandbox group changed before authentication";
/// Versioned provisioning-service message carried in a length-prefixed JSON frame.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct FramedProvisioningMessage {
pub version: u8,
#[serde(flatten)]
pub message: ProvisioningMessage,
}
/// Request and response messages exchanged with the provisioning service.
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ProvisioningMessage {
/// Records uninstall ownership without provisioning sandbox resources.
RegisterInstallationRequest {
codex_home: String,
},
ProvisionSandboxRequest {
payload: SandboxProvisioningRequest,
},
ProvisionSandboxResponse {
payload: SandboxProvisioningResponse,
},
}
/// Sandbox setup parameters sent to the provisioning service.
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(deny_unknown_fields)]
pub struct SandboxProvisioningRequest {
pub codex_home: String,
/// Routing request; the service independently authenticates its installed caller.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub registered_core: bool,
/// Refresh an existing registration without creating or repairing sandbox accounts.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub refresh_only: bool,
pub settings: WindowsSandboxProvisioningSettings,
pub listeners: WindowsSandboxProxyListeners,
}
/// Known proxy protocols used for managed-policy validation, separate from firewall settings.
#[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct WindowsSandboxProxyListeners {
pub http_ports: Vec<u16>,
pub socks_ports: Vec<u16>,
}
/// Result returned by the sandbox provisioning service.
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(tag = "status", rename_all = "snake_case")]
pub enum SandboxProvisioningResponse {
Ok,
/// The client should fall back to its elevated setup helper.
Unavailable,
Error {
message: String,
},
}
/// Write a length-prefixed provisioning-service message.
pub fn write_provisioning_frame<W: Write>(
writer: W,
message: &FramedProvisioningMessage,
) -> Result<()> {
crate::framed_io::write_frame(writer, message)
}
/// Read a length-prefixed provisioning-service message, returning `None` on EOF.
pub fn read_provisioning_frame<R: Read>(reader: R) -> Result<Option<FramedProvisioningMessage>> {
crate::framed_io::read_frame(reader)
}

View File

@@ -0,0 +1,683 @@
use anyhow::Result;
use akode_protocol::models::PermissionProfile;
use akode_protocol::permissions::FileSystemPath;
use akode_protocol::permissions::FileSystemSandboxEntry;
use akode_protocol::permissions::FileSystemSandboxKind;
use akode_protocol::permissions::FileSystemSandboxPolicy;
use akode_protocol::permissions::FileSystemSpecialPath::Root;
use akode_protocol::permissions::NetworkSandboxPolicy;
use akode_protocol::permissions::ReadDenyMatcher;
use akode_utils_absolute_path::AbsolutePathBuf;
use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;
/// Windows-local view of the runtime permission profile.
///
/// Most Windows sandbox code needs resolved runtime permissions plus a few
/// Windows-specific path conventions, not the user/config-facing
/// `PermissionProfile` enum itself.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedWindowsSandboxPermissions {
file_system: FileSystemSandboxPolicy,
network: NetworkSandboxPolicy,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct WindowsWritableRoot {
pub(crate) root: PathBuf,
pub(crate) read_only_subpaths: Vec<PathBuf>,
}
/// Restricted-token family needed to enforce a Windows permission profile.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WindowsSandboxTokenMode {
ReadOnlyCapability,
WritableRootsCapability,
}
/// Chooses the restricted-token family needed for a managed permission profile.
pub fn token_mode_for_permission_profile(
permission_profile: &PermissionProfile,
workspace_roots: &[AbsolutePathBuf],
cwd: &Path,
env_map: &HashMap<String, String>,
) -> Result<WindowsSandboxTokenMode> {
let permissions =
ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots(
permission_profile,
workspace_roots,
)?;
if permissions.file_system.has_full_disk_write_access() {
anyhow::bail!(
"permission profile requests full-disk filesystem writes, which cannot be enforced by the Windows sandbox"
);
}
if permissions.writable_roots_for_cwd(cwd, env_map).is_empty() {
Ok(WindowsSandboxTokenMode::ReadOnlyCapability)
} else {
Ok(WindowsSandboxTokenMode::WritableRootsCapability)
}
}
impl ResolvedWindowsSandboxPermissions {
pub fn try_from_permission_profile(permission_profile: &PermissionProfile) -> Result<Self> {
if !matches!(permission_profile, PermissionProfile::Managed { .. }) {
anyhow::bail!(
"only managed permission profiles can be enforced by the Windows sandbox"
);
}
let (file_system, network) = permission_profile.to_runtime_permissions();
if !matches!(file_system.kind, FileSystemSandboxKind::Restricted) {
anyhow::bail!(
"only restricted managed filesystem permissions can be enforced by the Windows sandbox"
);
}
Ok(Self {
file_system,
network,
})
}
/// Resolves a managed permission profile and binds symbolic `:workspace_roots`
/// entries to the workspace roots supplied by the caller.
pub fn try_from_permission_profile_for_workspace_roots(
permission_profile: &PermissionProfile,
workspace_roots: &[AbsolutePathBuf],
) -> Result<Self> {
let mut permissions = Self::try_from_permission_profile(permission_profile)?;
permissions.file_system = permissions
.file_system
.materialize_project_roots_with_workspace_roots(workspace_roots);
Ok(permissions)
}
pub(crate) fn should_apply_network_block(&self) -> bool {
!self.network.is_enabled()
}
pub(crate) fn network_policy(&self) -> NetworkSandboxPolicy {
self.network
}
/// Rejects filesystem policies that the elevated Windows sandbox cannot
/// enforce safely.
pub fn validate_elevated_filesystem_policy(&self, cwd: &Path) -> Result<()> {
let root = cwd
.ancestors()
.last()
.ok_or_else(|| anyhow::anyhow!("command cwd has no filesystem root"))?;
let root_is_denied = ReadDenyMatcher::try_new_for_local_paths(&self.file_system, cwd)
.map_err(anyhow::Error::msg)?
.is_some_and(|matcher| matcher.is_local_path_read_denied(root));
if !self.file_system.can_read_local_path_with_cwd(root, cwd) || root_is_denied {
anyhow::bail!("elevated Windows sandbox requires effective `:root` read access");
}
Ok(())
}
pub(crate) fn has_full_disk_read_access(&self) -> bool {
self.file_system.has_full_disk_read_access()
}
pub(crate) fn has_symbolic_root_read_access(&self, cwd: &Path) -> bool {
self.file_system.entries.iter().any(|entry| {
matches!(&entry.path, FileSystemPath::Special { value: Root })
&& entry.access.can_read()
}) && cwd
.ancestors()
.last()
.is_some_and(|root| self.file_system.can_read_local_path_with_cwd(root, cwd))
}
pub(crate) fn include_platform_defaults(&self) -> bool {
self.file_system.include_platform_defaults()
}
pub(crate) fn readable_roots_for_cwd(&self, cwd: &Path) -> Vec<PathBuf> {
self.file_system
.get_readable_roots_with_cwd(cwd)
.into_iter()
.map(AbsolutePathBuf::into_path_buf)
.collect()
}
pub(crate) fn uses_write_capabilities_for_cwd(
&self,
cwd: &Path,
env_map: &HashMap<String, String>,
) -> bool {
!self.writable_roots_for_cwd(cwd, env_map).is_empty()
}
pub(crate) fn writable_roots_for_cwd(
&self,
cwd: &Path,
env_map: &HashMap<String, String>,
) -> Vec<WindowsWritableRoot> {
let mut file_system = self.file_system.clone();
resolve_workload_temp_paths(&mut file_system, env_map);
file_system
.get_writable_roots_with_cwd(cwd)
.into_iter()
.map(|root| WindowsWritableRoot {
root: root.root.into_path_buf(),
read_only_subpaths: root
.read_only_subpaths
.into_iter()
.map(AbsolutePathBuf::into_path_buf)
.collect(),
})
.collect()
}
}
/// Replace `:tmpdir` with absolute TEMP/TMP paths from the completed Windows
/// workload environment. Use the same key order as the child's environment
/// block; never use host TEMP/TMP. Preserve access and missing-path rules so
/// the ordinary policy evaluator still handles read/deny carveouts.
pub fn resolve_workload_temp_paths(
file_system: &mut FileSystemSandboxPolicy,
workload_env: &HashMap<String, String>,
) {
use akode_protocol::permissions::FileSystemSpecialPath;
file_system.entries = std::mem::take(&mut file_system.entries)
.into_iter()
.flat_map(|entry| match &entry.path {
FileSystemPath::Special {
value: FileSystemSpecialPath::Tmpdir,
} => crate::process::ordered_env_entries(workload_env)
.into_iter()
.filter(|(key, value)| {
(key.eq_ignore_ascii_case("TEMP") || key.eq_ignore_ascii_case("TMP"))
&& Path::new(value).is_absolute()
})
.filter_map(|(_, value)| AbsolutePathBuf::from_absolute_path(value).ok())
.map(|path| FileSystemSandboxEntry {
path: path.into(),
..entry.clone()
})
.collect(),
FileSystemPath::Special {
value: FileSystemSpecialPath::SlashTmp,
} => Vec::new(),
_ => vec![entry],
})
.collect();
}
#[cfg(test)]
mod tests {
use super::*;
use akode_protocol::models::ManagedFileSystemPermissions;
use akode_protocol::permissions::FileSystemAccessMode;
use akode_protocol::permissions::FileSystemSandboxEntry;
use akode_protocol::permissions::FileSystemSpecialPath;
use akode_protocol::permissions::project_roots_glob_pattern;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
fn workspace_roots_for(root: &Path) -> Vec<AbsolutePathBuf> {
vec![AbsolutePathBuf::from_absolute_path(root).expect("absolute workspace root")]
}
fn permission_profile_with_entries(entries: Vec<FileSystemSandboxEntry>) -> PermissionProfile {
PermissionProfile::Managed {
file_system: ManagedFileSystemPermissions::Restricted {
entries,
glob_scan_max_depth: None,
},
network: NetworkSandboxPolicy::Restricted,
}
}
#[test]
fn permission_profile_workspace_write_uses_windows_temp_env_vars() {
let tmp = TempDir::new().expect("tempdir");
let cwd = tmp.path().join("workspace");
let temp_dir = tmp.path().join("temp");
std::fs::create_dir_all(&cwd).expect("create cwd");
std::fs::create_dir_all(&temp_dir).expect("create temp dir");
let mut env_map = HashMap::new();
env_map.insert("TEMP".to_string(), temp_dir.to_string_lossy().to_string());
env_map.insert("TMP".to_string(), temp_dir.to_string_lossy().to_string());
let permissions = ResolvedWindowsSandboxPermissions::try_from_permission_profile(
&PermissionProfile::workspace_write(),
)
.expect("managed permission profile");
let roots = permissions
.writable_roots_for_cwd(&cwd, &env_map)
.into_iter()
.map(|root| root.root)
.collect::<std::collections::HashSet<_>>();
let expected_roots = [
dunce::canonicalize(&temp_dir).expect("canonicalize temp dir"),
dunce::canonicalize(&cwd).expect("canonicalize cwd"),
]
.into_iter()
.collect::<std::collections::HashSet<_>>();
assert_eq!(expected_roots, roots);
}
#[test]
fn explicit_empty_or_missing_override_does_not_fall_back_to_temp() {
let dir = TempDir::new().unwrap();
let cwd = dir.path().join("work");
let codex_home = dir.path().join("akode-home");
let temp = dir.path().join("temp");
for path in [&cwd, &codex_home, &temp] {
std::fs::create_dir_all(path).unwrap();
}
let env = HashMap::from([("Temp".into(), temp.to_string_lossy().into_owned())]);
let profile = permission_profile_with_entries(vec![
FileSystemSandboxEntry::new(
FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
},
FileSystemAccessMode::Read,
),
FileSystemSandboxEntry::new(
FileSystemPath::Special {
value: FileSystemSpecialPath::Tmpdir,
},
FileSystemAccessMode::Write,
),
]);
let permissions =
ResolvedWindowsSandboxPermissions::try_from_permission_profile(&profile).unwrap();
assert_eq!(
token_mode_for_permission_profile(&profile, &[], &cwd, &env).unwrap(),
WindowsSandboxTokenMode::WritableRootsCapability
);
for overrides in [vec![], vec![dir.path().join("missing")]] {
assert!(
crate::setup::effective_write_roots_for_permissions(
&permissions,
&cwd,
&env,
&codex_home,
Some(&overrides)
)
.is_empty(),
"invalid override {overrides:?}"
);
}
}
#[test]
fn unavailable_windows_temp_never_creates_write_capabilities() {
let dir = TempDir::new().unwrap();
let cwd = dir.path().join("work");
std::fs::create_dir_all(&cwd).unwrap();
let profile = permission_profile_with_entries(vec![
FileSystemSandboxEntry::new(
FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
},
FileSystemAccessMode::Read,
),
FileSystemSandboxEntry::new(
FileSystemPath::Special {
value: FileSystemSpecialPath::Tmpdir,
},
FileSystemAccessMode::Write,
),
FileSystemSandboxEntry::new(
FileSystemPath::Special {
value: FileSystemSpecialPath::SlashTmp,
},
FileSystemAccessMode::Write,
),
]);
let explicit_empty = HashMap::from([
("TEMP".into(), String::new()),
("TMP".into(), "relative".into()),
]);
assert_eq!(
token_mode_for_permission_profile(&profile, &[], &cwd, &explicit_empty).unwrap(),
WindowsSandboxTokenMode::ReadOnlyCapability
);
assert_eq!(
token_mode_for_permission_profile(&profile, &[], &cwd, &HashMap::new()).unwrap(),
WindowsSandboxTokenMode::ReadOnlyCapability
);
}
#[test]
fn permission_profile_workspace_root_uses_runtime_workspace_roots() {
let tmp = TempDir::new().expect("tempdir");
let workspace_root = tmp.path().join("workspace");
let command_cwd = workspace_root.join("subdir");
std::fs::create_dir_all(&command_cwd).expect("create command cwd");
let permission_profile = PermissionProfile::Managed {
file_system: ManagedFileSystemPermissions::Restricted {
entries: vec![FileSystemSandboxEntry {
path: FileSystemPath::Special {
value: FileSystemSpecialPath::project_roots(/*subpath*/ None),
},
access: FileSystemAccessMode::Write,
missing_path_behavior: None,
}],
glob_scan_max_depth: None,
},
network: NetworkSandboxPolicy::Restricted,
};
let workspace_roots = workspace_roots_for(workspace_root.as_path());
let permissions =
ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots(
&permission_profile,
workspace_roots.as_slice(),
)
.expect("managed permission profile");
let roots = permissions
.writable_roots_for_cwd(&command_cwd, &HashMap::new())
.into_iter()
.map(|root| root.root)
.collect::<Vec<_>>();
assert_eq!(
roots,
vec![dunce::canonicalize(&workspace_root).expect("canonical workspace root")]
);
}
#[test]
fn permission_profile_workspace_roots_expand_all_runtime_workspace_roots() {
let tmp = TempDir::new().expect("tempdir");
let first = AbsolutePathBuf::from_absolute_path(tmp.path().join("first"))
.expect("absolute first root");
let second = AbsolutePathBuf::from_absolute_path(tmp.path().join("second"))
.expect("absolute second root");
let permission_profile = PermissionProfile::Managed {
file_system: ManagedFileSystemPermissions::Restricted {
entries: vec![
FileSystemSandboxEntry {
path: FileSystemPath::Special {
value: FileSystemSpecialPath::project_roots(/*subpath*/ None),
},
access: FileSystemAccessMode::Write,
missing_path_behavior: None,
},
FileSystemSandboxEntry {
path: FileSystemPath::Special {
value: FileSystemSpecialPath::project_roots(Some(".git".into())),
},
access: FileSystemAccessMode::Deny,
missing_path_behavior: None,
},
FileSystemSandboxEntry {
path: FileSystemPath::GlobPattern {
pattern: project_roots_glob_pattern(Path::new("**/*.env")),
},
access: FileSystemAccessMode::Deny,
missing_path_behavior: None,
},
],
glob_scan_max_depth: None,
},
network: NetworkSandboxPolicy::Restricted,
};
let permissions =
ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots(
&permission_profile,
&[first.clone(), second.clone()],
)
.expect("managed permission profile");
assert_eq!(
permissions.file_system,
FileSystemSandboxPolicy::restricted(vec![
FileSystemSandboxEntry {
path: FileSystemPath::Path {
path: first.clone().into(),
},
access: FileSystemAccessMode::Write,
missing_path_behavior: None,
},
FileSystemSandboxEntry {
path: FileSystemPath::Path {
path: second.clone().into(),
},
access: FileSystemAccessMode::Write,
missing_path_behavior: None,
},
FileSystemSandboxEntry {
path: FileSystemPath::Path {
path: first.join(".git").into(),
},
access: FileSystemAccessMode::Deny,
missing_path_behavior: None,
},
FileSystemSandboxEntry {
path: FileSystemPath::Path {
path: second.join(".git").into(),
},
access: FileSystemAccessMode::Deny,
missing_path_behavior: None,
},
FileSystemSandboxEntry {
path: FileSystemPath::GlobPattern {
pattern: AbsolutePathBuf::resolve_path_against_base(
"**/*.env",
first.as_path(),
)
.to_string_lossy()
.into_owned(),
},
access: FileSystemAccessMode::Deny,
missing_path_behavior: None,
},
FileSystemSandboxEntry {
path: FileSystemPath::GlobPattern {
pattern: AbsolutePathBuf::resolve_path_against_base(
"**/*.env",
second.as_path(),
)
.to_string_lossy()
.into_owned(),
},
access: FileSystemAccessMode::Deny,
missing_path_behavior: None,
},
])
);
}
#[test]
fn token_mode_for_profile_without_writable_roots_uses_readonly_capability() {
let tmp = TempDir::new().expect("tempdir");
let cwd = tmp.path().join("workspace");
std::fs::create_dir_all(&cwd).expect("create cwd");
let workspace_roots = workspace_roots_for(cwd.as_path());
let token_mode = token_mode_for_permission_profile(
&PermissionProfile::read_only(),
workspace_roots.as_slice(),
&cwd,
&HashMap::new(),
)
.expect("token mode");
assert_eq!(WindowsSandboxTokenMode::ReadOnlyCapability, token_mode);
}
#[test]
fn token_mode_for_profile_with_writable_roots_uses_write_capabilities() {
let tmp = TempDir::new().expect("tempdir");
let cwd = tmp.path().join("workspace");
std::fs::create_dir_all(&cwd).expect("create cwd");
let workspace_roots = workspace_roots_for(cwd.as_path());
let token_mode = token_mode_for_permission_profile(
&PermissionProfile::workspace_write(),
workspace_roots.as_slice(),
&cwd,
&HashMap::new(),
)
.expect("token mode");
assert_eq!(WindowsSandboxTokenMode::WritableRootsCapability, token_mode);
}
#[test]
fn permission_profile_rejects_disabled_profiles() {
let err = ResolvedWindowsSandboxPermissions::try_from_permission_profile(
&PermissionProfile::Disabled,
)
.expect_err("disabled profile should not resolve for sandbox enforcement");
assert!(
err.to_string()
.contains("only managed permission profiles can be enforced")
);
}
#[test]
fn permission_profile_rejects_unrestricted_managed_filesystem() {
let permission_profile = PermissionProfile::Managed {
file_system: ManagedFileSystemPermissions::Unrestricted,
network: NetworkSandboxPolicy::Restricted,
};
let err =
ResolvedWindowsSandboxPermissions::try_from_permission_profile(&permission_profile)
.expect_err("unrestricted profile should not resolve for sandbox enforcement");
assert!(
err.to_string()
.contains("only restricted managed filesystem permissions can be enforced")
);
}
#[test]
fn elevated_filesystem_policy_requires_effective_root_read_access() {
let tmp = TempDir::new().expect("tempdir");
let cwd = tmp.path().join("workspace");
let denied_path = tmp.path().join("private");
std::fs::create_dir_all(&cwd).expect("create cwd");
let default_root_denied = ResolvedWindowsSandboxPermissions::try_from_permission_profile(
&permission_profile_with_entries(vec![FileSystemSandboxEntry::new(
FileSystemPath::Special {
value: FileSystemSpecialPath::project_roots(/*subpath*/ None),
},
FileSystemAccessMode::Write,
)]),
)
.expect("managed permission profile");
let root_read_with_carveout =
ResolvedWindowsSandboxPermissions::try_from_permission_profile(
&permission_profile_with_entries(vec![
FileSystemSandboxEntry::new(
FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
},
FileSystemAccessMode::Read,
),
FileSystemSandboxEntry::new(
FileSystemPath::Path {
path: AbsolutePathBuf::from_absolute_path(&denied_path)
.expect("absolute denied path")
.into(),
},
FileSystemAccessMode::Deny,
),
]),
)
.expect("managed permission profile");
let root = cwd.ancestors().last().expect("filesystem root");
let root_read_with_explicit_path =
ResolvedWindowsSandboxPermissions::try_from_permission_profile(
&permission_profile_with_entries(vec![FileSystemSandboxEntry::new(
FileSystemPath::Path {
path: AbsolutePathBuf::from_absolute_path(root)
.expect("absolute root")
.into(),
},
FileSystemAccessMode::Read,
)]),
)
.expect("managed permission profile");
let root_read_with_root_deny_glob =
ResolvedWindowsSandboxPermissions::try_from_permission_profile(
&permission_profile_with_entries(vec![
FileSystemSandboxEntry::new(
FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
},
FileSystemAccessMode::Read,
),
FileSystemSandboxEntry::new(
FileSystemPath::GlobPattern {
pattern: root.join("**").display().to_string(),
},
FileSystemAccessMode::Deny,
),
]),
)
.expect("managed permission profile");
assert!(
default_root_denied
.validate_elevated_filesystem_policy(&cwd)
.is_err()
);
assert!(
root_read_with_carveout
.validate_elevated_filesystem_policy(&cwd)
.is_ok()
);
assert!(
root_read_with_explicit_path
.validate_elevated_filesystem_policy(&cwd)
.is_ok()
);
assert!(
root_read_with_root_deny_glob
.validate_elevated_filesystem_policy(&cwd)
.is_err()
);
}
#[test]
fn token_mode_rejects_full_disk_write_entries() {
let tmp = TempDir::new().expect("tempdir");
let cwd = tmp.path().join("workspace");
std::fs::create_dir_all(&cwd).expect("create cwd");
let permission_profile = PermissionProfile::Managed {
file_system: ManagedFileSystemPermissions::Restricted {
entries: vec![FileSystemSandboxEntry {
path: FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
},
access: FileSystemAccessMode::Write,
missing_path_behavior: None,
}],
glob_scan_max_depth: None,
},
network: NetworkSandboxPolicy::Restricted,
};
let workspace_roots = workspace_roots_for(cwd.as_path());
let err = token_mode_for_permission_profile(
&permission_profile,
workspace_roots.as_slice(),
&cwd,
&HashMap::new(),
)
.expect_err("full disk writes should not resolve to a token mode");
assert!(
err.to_string()
.contains("full-disk filesystem writes, which cannot be enforced")
);
}
}

View File

@@ -0,0 +1,254 @@
//! Shares the protected installation record with mutating sandbox setup.
//! Callers must hold the sandbox setup mutex while admitting or changing ownership.
use std::io;
use anyhow::Context;
use anyhow::Result;
use anyhow::ensure;
use serde::Deserialize;
use serde::Serialize;
use windows_sys::Win32::Foundation as foundation;
use windows_sys::Win32::System::Registry as registry;
use windows_sys::Win32::UI::Shell::SHDeleteEmptyKeyW;
/// Selects legacy helper materialization or verified app-contained Core for setup.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum SetupRuntime {
#[default]
Legacy,
Registered,
}
impl SetupRuntime {
#[expect(
clippy::trivially_copy_pass_by_ref,
reason = "serde requires a borrowed field"
)]
pub(crate) fn is_legacy(&self) -> bool {
*self == Self::Legacy
}
}
/// Package-scoped execution alias declared for the app's sandbox runner.
pub const APP_CORE_RUNNER_ALIAS: &str = "codex-core-command-runner.exe";
/// The service may register its package only for these managed sandbox accounts.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum SandboxRuntimeAccount {
Offline,
Online,
}
impl SandboxRuntimeAccount {
pub fn username(self) -> &'static str {
match self {
Self::Offline => crate::setup::OFFLINE_USERNAME,
Self::Online => crate::setup::ONLINE_USERNAME,
}
}
}
pub use crate::installation_record::INSTALLATION_KEY;
pub use crate::installation_record::INSTALLATION_VALUE;
use crate::installation_record::InstallationRecord;
use crate::winutil::to_wide;
// Old services overwrite the parent value and delete its key on uninstall.
// A child key preserves Core state and makes that old whole-key delete fail.
pub const CORE_INSTALLATION_KEY: &str =
r"SOFTWARE\OpenAI\Codex\WindowsSandboxService\RegisteredCore";
/// Written before registration so a service restart cannot lose cleanup ownership.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct RuntimeRegistration {
pub package_family: String,
pub accounts: Vec<RuntimeAccountRegistration>,
/// Owner-authorized AppData roots, recorded before granting metadata access.
/// Retain former roots through redirection and package updates until cleanup.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub metadata_roots: Vec<std::path::PathBuf>,
/// Committed only after both registrations and metadata grants succeed.
#[serde(default)]
pub ready_package: Option<String>,
/// Fences setup during normal teardown; a restart must not replay it.
/// Old non-null phase journals fail to decode rather than lose their fence.
#[serde(default, alias = "cleanup")]
pub retiring: Option<String>,
}
impl RuntimeRegistration {
pub fn ready_for_package(&self, full_name: &str) -> bool {
self.can_resume_registration() && self.ready_package.as_deref() == Some(full_name)
}
/// Complete account ownership allows registration to resume, not runtime execution.
/// Callers must still authenticate the owner and verify the live account SIDs/settings.
pub fn can_resume_registration(&self) -> bool {
self.retiring.is_none()
&& self.accounts.len() == 2
&& self.accounts[0].account != self.accounts[1].account
&& self
.accounts
.iter()
.all(|account| account.alias_path.is_some() && !account.cleanup_logon_pending)
}
}
impl InstallationRecord {
pub fn runtime(&self) -> Result<&RuntimeRegistration> {
self.runtime
.as_ref()
.context("registered runtime ownership is missing")
}
pub fn runtime_mut(&mut self) -> Result<&mut RuntimeRegistration> {
self.runtime
.as_mut()
.context("registered runtime ownership is missing")
}
/// Any persisted cleanup has committed to removing this resource generation.
pub fn admit_owner(&self, owner: &InstallationRecord, family: &str) -> Result<()> {
ensure!(
self.user_sid == owner.user_sid
&& self.codex_home == owner.codex_home
&& self.runtime()?.package_family.eq_ignore_ascii_case(family),
"registered sandbox resources belong to a different owner or package"
);
ensure!(
self.runtime()?.retiring.is_none()
&& self
.runtime()?
.accounts
.iter()
.all(|account| !account.cleanup_logon_pending),
"registered sandbox cleanup must finish before provisioning"
);
Ok(())
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct RuntimeAccountRegistration {
/// Persisted before temporarily enabling an account; cleared only after re-disabling it.
#[serde(default)]
pub cleanup_logon_pending: bool,
pub account: SandboxRuntimeAccount,
pub user_sid: String,
/// OS-resolved alias written by the service, never inferred from a user name.
#[serde(default)]
pub alias_path: Option<std::path::PathBuf>,
}
/// Capture the requesting process identity before elevation, never USERNAME.
pub(crate) fn current_setup_user() -> Result<String> {
use std::os::windows::io::FromRawHandle;
use std::os::windows::io::OwnedHandle;
use windows_sys::Win32::Security as security;
use windows_sys::Win32::System::Threading as threading;
let mut token = std::ptr::null_mut();
if unsafe {
threading::OpenProcessToken(
threading::GetCurrentProcess(),
security::TOKEN_QUERY,
&mut token,
)
} == 0
{
return Err(io::Error::last_os_error()).context("query requesting setup identity");
}
let _token = unsafe { OwnedHandle::from_raw_handle(token as _) };
let sid = unsafe { crate::token::get_user_sid_bytes(token)? };
unsafe { crate::winutil::account_name_from_sid(sid.as_ptr() as _) }
.context("resolve requesting setup identity")
}
/// Core owns its complete record; the old parent is only a fallback before/after Core.
pub fn load_installation() -> Result<Option<InstallationRecord>> {
if let Some(record) = crate::installation_record::load_from(CORE_INSTALLATION_KEY)? {
ensure!(
record.runtime.is_some(),
"Core installation record is missing runtime state"
);
return Ok(Some(record));
}
crate::installation_record::load_from(INSTALLATION_KEY)
}
/// Retires only legacy ownership while the caller holds the setup lock.
/// Registered Core ownership belongs to its post-service-exit finalizer.
pub fn remove_installation() -> Result<()> {
let Some(record) = load_installation()? else {
return Ok(());
};
ensure!(
record.runtime.is_none(),
"registered Core ownership must be retired after service exit"
);
let status = unsafe {
registry::RegDeleteKeyValueW(
registry::HKEY_LOCAL_MACHINE,
to_wide(INSTALLATION_KEY).as_ptr(),
to_wide(INSTALLATION_VALUE).as_ptr(),
)
};
match status {
foundation::ERROR_SUCCESS
| foundation::ERROR_FILE_NOT_FOUND
| foundation::ERROR_PATH_NOT_FOUND => {
flush_installation(INSTALLATION_KEY)?;
// Best-effort pruning preserves any remaining values or subkeys.
let _ = unsafe {
SHDeleteEmptyKeyW(
registry::HKEY_LOCAL_MACHINE,
to_wide(INSTALLATION_KEY).as_ptr(),
)
};
Ok(())
}
status => Err(io::Error::from_raw_os_error(status as i32))
.context("remove protected legacy sandbox installation record"),
}
}
/// Persists and flushes ownership before an operation may outlive this service.
/// The caller must hold the sandbox setup mutex across its read/modify/write.
pub fn save_installation(record: &InstallationRecord) -> Result<()> {
let key = if record.runtime.is_some() {
CORE_INSTALLATION_KEY
} else {
INSTALLATION_KEY
};
crate::installation_record::save_to(key, record)?;
flush_installation(key)
}
fn flush_installation(path: &str) -> Result<()> {
let mut key = std::ptr::null_mut();
let status = unsafe {
registry::RegOpenKeyExW(
registry::HKEY_LOCAL_MACHINE,
to_wide(path).as_ptr(),
0,
registry::KEY_QUERY_VALUE,
&mut key,
)
};
if status != foundation::ERROR_SUCCESS {
return Err(io::Error::from_raw_os_error(status as i32))
.context("open runtime ownership record");
}
let status = unsafe { registry::RegFlushKey(key) };
unsafe { registry::RegCloseKey(key) };
if status != foundation::ERROR_SUCCESS {
return Err(io::Error::from_raw_os_error(status as i32))
.context("flush runtime ownership record");
}
Ok(())
}
#[cfg(test)]
#[path = "runtime_ownership_tests.rs"]
mod tests;

View File

@@ -0,0 +1,275 @@
//! Tests owner admission, readiness receipts, and backward-compatible record decoding.
use super::*;
use crate::DesktopInstallation;
use pretty_assertions::assert_eq;
use std::path::PathBuf;
fn record() -> InstallationRecord {
InstallationRecord {
user_sid: "S-1-5-21-1-2-3-1000".into(),
codex_home: PathBuf::from(r"C:\Users\owner\.akode"),
session_id: 1,
desktop_installation: Some(DesktopInstallation {
created_codex_home: true,
cache_home: PathBuf::from(r"C:\Users\owner\.cache"),
}),
runtime: Some(RuntimeRegistration {
package_family: "OpenAI.Codex_publisher".into(),
metadata_roots: Vec::new(),
ready_package: None,
accounts: vec![RuntimeAccountRegistration {
cleanup_logon_pending: false,
account: SandboxRuntimeAccount::Offline,
user_sid: "S-1-5-21-1-2-3-1001".into(),
alias_path: None,
}],
retiring: None,
}),
}
}
fn pending() -> InstallationRecord {
let mut record = record();
record.runtime_mut().unwrap().retiring = Some("one-cleanup-generation".into());
record
}
const READY_PACKAGE: &str = "OpenAI.Codex_1.0.0.0_arm64__publisher";
fn ready_runtime() -> RuntimeRegistration {
let mut runtime = record().runtime.unwrap();
runtime.ready_package = Some(READY_PACKAGE.into());
runtime.accounts[0].alias_path = Some(PathBuf::from(r"C:\aliases\offline.exe"));
runtime.accounts.push(RuntimeAccountRegistration {
cleanup_logon_pending: false,
account: SandboxRuntimeAccount::Online,
user_sid: "S-1-5-21-1-2-3-1002".into(),
alias_path: Some(PathBuf::from(r"C:\aliases\online.exe")),
});
runtime
}
#[test]
fn readiness_requires_a_receipt_for_the_current_package_version() {
let mut runtime = ready_runtime();
assert!(runtime.ready_for_package(READY_PACKAGE));
assert!(runtime.can_resume_registration());
assert!(!runtime.ready_for_package("OpenAI.Codex_2.0.0.0_arm64__publisher"));
runtime.ready_package = None;
assert!(!runtime.ready_for_package(READY_PACKAGE));
assert!(runtime.can_resume_registration());
}
#[test]
fn readiness_requires_both_distinct_account_receipts() {
let mut missing_account = ready_runtime();
missing_account.accounts.pop();
let mut missing_alias = ready_runtime();
missing_alias.accounts[1].alias_path = None;
let mut duplicate_role = ready_runtime();
duplicate_role.accounts[1].account = SandboxRuntimeAccount::Offline;
let mut extra_account = ready_runtime();
extra_account
.accounts
.push(extra_account.accounts[0].clone());
for runtime in [
missing_account,
missing_alias,
duplicate_role,
extra_account,
] {
assert!(!runtime.ready_for_package(READY_PACKAGE));
assert!(!runtime.can_resume_registration());
}
}
#[test]
fn readiness_is_revoked_by_the_retirement_fence() {
let mut runtime = ready_runtime();
runtime.retiring = Some("one-cleanup-generation".into());
assert!(!runtime.ready_for_package(READY_PACKAGE));
assert!(!runtime.can_resume_registration());
}
#[test]
fn admission_accepts_package_family_casing() {
for stored in ["OpenAI.Codex_publisher", "openai.codex_PUBLISHER"] {
let mut record = record();
record.runtime_mut().unwrap().package_family = stored.into();
let expected = record.clone();
for requested in ["OpenAI.Codex_publisher", "OPENAI.AKODE_PUBLISHER"] {
record.admit_owner(&record.clone(), requested).unwrap();
assert_eq!(record, expected);
}
}
}
#[test]
fn admission_rejects_other_owner_home_and_family() {
let record = record();
let expected = record.clone();
for (home, sid, family) in [
(
record.codex_home.as_path(),
"S-1-5-21-1-2-3-2000",
record.runtime().unwrap().package_family.as_str(),
),
(
std::path::Path::new(r"C:\Users\owner\other"),
record.user_sid.as_str(),
record.runtime().unwrap().package_family.as_str(),
),
(
record.codex_home.as_path(),
record.user_sid.as_str(),
"OpenAI.CodexBeta_publisher",
),
(
record.codex_home.as_path(),
record.user_sid.as_str(),
"OpenAI.Codex_otherpublisher",
),
] {
let mut requested = record.clone();
requested.codex_home = home.to_path_buf();
requested.user_sid = sid.to_owned();
assert!(record.admit_owner(&requested, family).is_err());
assert_eq!(record, expected);
}
}
#[test]
fn returned_owner_cannot_cancel_a_persisted_retirement_fence() {
let expected = pending();
let journal = serde_json::to_string(&expected).unwrap();
let restored: InstallationRecord = serde_json::from_str(&journal).unwrap();
let returning_owner = record();
assert!(
restored
.admit_owner(
&returning_owner,
&returning_owner.runtime().unwrap().package_family
)
.is_err()
);
assert_eq!(restored, expected);
}
#[test]
fn journal_round_trip_retains_desktop_ownership_and_retirement_fence() {
for record in [record(), pending()] {
let json = serde_json::to_string(&record).unwrap();
assert_eq!(
serde_json::from_str::<InstallationRecord>(&json).unwrap(),
record
);
}
}
#[test]
fn production_record_without_optional_core_or_desktop_fields_still_loads() {
let mut expected = record();
expected.runtime = None;
expected.desktop_installation = None;
let json = r#"{"user_sid":"S-1-5-21-1-2-3-1000","codex_home":"C:\\Users\\owner\\.akode","session_id":1}"#;
assert_eq!(
serde_json::from_str::<InstallationRecord>(json).unwrap(),
expected
);
}
#[test]
fn metadata_root_history_survives_record_round_trip() {
let mut expected = record();
expected.runtime_mut().unwrap().metadata_roots = vec![
PathBuf::from(r"C:\Users\owner\AppData\Roaming"),
PathBuf::from(r"D:\Redirected\Roaming"),
];
for record in [expected.clone(), {
let mut updated = expected;
updated.runtime_mut().unwrap().ready_package = Some(READY_PACKAGE.into());
updated
}] {
let json = serde_json::to_string(&record).unwrap();
assert_eq!(
serde_json::from_str::<InstallationRecord>(&json).unwrap(),
record
);
}
}
#[test]
fn older_runtime_receipts_default_to_no_metadata_roots_or_cleanup_logon() {
let expected = record();
let mut json = serde_json::to_value(&expected).unwrap();
json["runtime"]["accounts"][0]
.as_object_mut()
.unwrap()
.remove("cleanup_logon_pending");
assert!(json["runtime"].get("metadata_roots").is_none());
assert_eq!(
serde_json::from_value::<InstallationRecord>(json).unwrap(),
expected
);
}
#[test]
fn legacy_null_cleanup_alias_preserves_the_active_record() {
let expected = record();
let mut json = serde_json::to_value(&expected).unwrap();
let runtime = json["runtime"].as_object_mut().unwrap();
runtime.remove("retiring");
runtime.insert("cleanup".into(), serde_json::Value::Null);
assert_eq!(
serde_json::from_value::<InstallationRecord>(json).unwrap(),
expected
);
}
#[test]
fn legacy_non_null_cleanup_journal_cannot_silently_drop_its_fence() {
for stage in ["native_started", "native_complete"] {
let mut json = serde_json::to_value(record()).unwrap();
let runtime = json["runtime"].as_object_mut().unwrap();
runtime.remove("retiring");
let accounts = runtime["accounts"].clone();
runtime.insert(
"cleanup".into(),
serde_json::json!({
"id": "one-cleanup-generation",
"stage": stage,
"accounts": accounts,
}),
);
assert!(serde_json::from_value::<InstallationRecord>(json).is_err());
}
}
#[test]
fn interrupted_cleanup_logon_blocks_admission_after_record_reload() {
let mut original = record();
original.runtime = Some(ready_runtime());
original.runtime_mut().unwrap().accounts[0].cleanup_logon_pending = true;
let mut restored: InstallationRecord =
serde_json::from_str(&serde_json::to_string(&original).unwrap()).unwrap();
assert_eq!(restored, original);
assert!(!restored.runtime().unwrap().ready_for_package(READY_PACKAGE));
assert!(
restored
.admit_owner(&original, "OpenAI.Codex_publisher")
.is_err()
);
restored.runtime_mut().unwrap().accounts[0].cleanup_logon_pending = false;
assert!(restored.runtime().unwrap().ready_for_package(READY_PACKAGE));
assert!(
restored
.admit_owner(&original, "OpenAI.Codex_publisher")
.is_ok()
);
}

View File

@@ -0,0 +1,119 @@
//! Shared helper utilities for Windows sandbox setup.
//!
//! These helpers centralize small pieces of setup logic used across both legacy and
//! elevated paths, including unified_exec sessions and capture flows. They cover
//! codex home directory creation and git safe.directory injection so sandboxed
//! users can run git inside a repo owned by the primary user.
use anyhow::Result;
use std::collections::HashMap;
use std::path::Path;
/// Walk upward from `start` to locate the git worktree root for `safe.directory`.
fn find_git_worktree_root_for_safe_directory(start: &Path) -> Option<std::path::PathBuf> {
let mut cur = dunce::canonicalize(start).ok()?;
loop {
if cur.join(".git").exists() {
return Some(cur);
}
let parent = cur.parent()?;
if parent == cur {
return None;
}
cur = parent.to_path_buf();
}
}
/// Ensure the sandbox codex home directory exists.
pub fn ensure_codex_home_exists(p: &Path) -> Result<()> {
std::fs::create_dir_all(p)?;
Ok(())
}
/// Adds git safe.directory entries for the repository and nested repositories.
/// git will not otherwise allow the Sandbox user to run git commands on repositories
/// which are owned by the primary user.
pub fn inject_git_safe_directory(env_map: &mut HashMap<String, String>, cwd: &Path) {
if let Some(git_root) = find_git_worktree_root_for_safe_directory(cwd) {
let mut cfg_count: usize = env_map
.get("GIT_CONFIG_COUNT")
.and_then(|v| v.parse::<usize>().ok())
.unwrap_or(0);
let git_path = git_root.to_string_lossy().replace("\\\\", "/");
let nested_git_path = format!("{git_path}/*");
for git_path in [git_path, nested_git_path] {
env_map.insert(
format!("GIT_CONFIG_KEY_{cfg_count}"),
"safe.directory".to_string(),
);
env_map.insert(format!("GIT_CONFIG_VALUE_{cfg_count}"), git_path);
cfg_count += 1;
}
env_map.insert("GIT_CONFIG_COUNT".to_string(), cfg_count.to_string());
}
}
#[cfg(test)]
mod tests {
use super::inject_git_safe_directory;
use pretty_assertions::assert_eq;
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use tempfile::TempDir;
fn safe_directory_value(path: &Path) -> String {
dunce::canonicalize(path)
.expect("canonicalize path")
.to_string_lossy()
.replace("\\\\", "/")
}
#[test]
fn injects_safe_directory_for_git_directory() {
let temp = TempDir::new().expect("tempdir");
let repo = temp.path().join("repo");
let nested = repo.join("nested");
fs::create_dir_all(repo.join(".git")).expect("create .git");
fs::create_dir_all(&nested).expect("create nested dir");
let mut env_map = HashMap::new();
inject_git_safe_directory(&mut env_map, &nested);
let git_path = safe_directory_value(&repo);
let expected = HashMap::from([
("GIT_CONFIG_COUNT".to_string(), "2".to_string()),
("GIT_CONFIG_KEY_0".to_string(), "safe.directory".to_string()),
("GIT_CONFIG_VALUE_0".to_string(), git_path.clone()),
("GIT_CONFIG_KEY_1".to_string(), "safe.directory".to_string()),
("GIT_CONFIG_VALUE_1".to_string(), format!("{git_path}/*")),
]);
assert_eq!(env_map, expected);
}
#[test]
fn injects_worktree_root_for_gitfile() {
let temp = TempDir::new().expect("tempdir");
let repo = temp.path().join("repo");
let nested = repo.join("nested");
fs::create_dir_all(&nested).expect("create nested dir");
fs::write(
repo.join(".git"),
"gitdir: C:/Users/example/repo/.git/worktrees/codex3\n",
)
.expect("write .git file");
let mut env_map = HashMap::new();
inject_git_safe_directory(&mut env_map, &nested);
let git_path = safe_directory_value(&repo);
let expected = HashMap::from([
("GIT_CONFIG_COUNT".to_string(), "2".to_string()),
("GIT_CONFIG_KEY_0".to_string(), "safe.directory".to_string()),
("GIT_CONFIG_VALUE_0".to_string(), git_path.clone()),
("GIT_CONFIG_KEY_1".to_string(), "safe.directory".to_string()),
("GIT_CONFIG_VALUE_1".to_string(), format!("{git_path}/*")),
]);
assert_eq!(env_map, expected);
}
}

View File

@@ -0,0 +1,129 @@
//! Best-effort, numeric service-stop evidence. Core exports it only when SCM says stopped.
//! Missing/older records stay unknown; no event-log text or user data is collected.
use std::mem::size_of_val;
use std::ptr;
use windows_sys::Win32::System::Registry as registry;
use windows_sys::Win32::System::Services as services;
use windows_sys::Win32::System::Services::SERVICE_STATUS_PROCESS;
/// Last lifecycle outcome reported by the service, not an inferred crash diagnosis.
#[derive(Clone, Copy)]
#[repr(u32)]
pub enum ServiceStopReason {
Starting = 1,
StopRequested = 2,
Shutdown = 3,
OwnerRemoved = 4,
StartupFailed = 5,
BrokerFailed = 6,
RegistrationInterrupted = 7,
}
impl ServiceStopReason {
/// Called by the service, which owns the key. Failure must not affect its lifecycle.
pub fn record(self, hresult: u32) {
let Ok(service_name) = crate::windows_sandbox_service_name() else {
return;
};
let key = crate::to_wide(format!(r"SYSTEM\CurrentControlSet\Services\{service_name}"));
let value = ((self as u64) << 32) | u64::from(hresult);
let mut handle = ptr::null_mut();
unsafe {
// Do not recreate a service key that Windows is uninstalling.
if registry::RegOpenKeyExW(
registry::HKEY_LOCAL_MACHINE,
key.as_ptr(),
0,
registry::KEY_SET_VALUE,
&mut handle,
) != 0
{
return;
}
registry::RegSetValueExW(
handle,
windows_sys::w!("CodexLastStop"),
0,
registry::REG_QWORD,
ptr::from_ref(&value).cast(),
size_of_val(&value) as u32,
);
registry::RegCloseKey(handle);
}
}
}
pub(crate) fn record_stopped(status: &SERVICE_STATUS_PROCESS, service: services::SC_HANDLE) {
let Some(metrics) = akode_otel::global() else {
return;
};
let Ok(service_name) = crate::windows_sandbox_service_name() else {
return;
};
let key = crate::to_wide(format!(r"SYSTEM\CurrentControlSet\Services\{service_name}"));
let read_stop = || {
let mut value = 0_u64;
let mut size = size_of_val(&value) as u32;
unsafe {
registry::RegGetValueW(
registry::HKEY_LOCAL_MACHINE,
key.as_ptr(),
windows_sys::w!("CodexLastStop"),
registry::RRF_RT_REG_QWORD | registry::RRF_ZEROONFAILURE,
ptr::null_mut(),
ptr::from_mut(&mut value).cast(),
&mut size,
);
}
value
};
let value = read_stop();
// A concurrent restart can replace the registry record after the first query.
// Only pair it with SCM evidence if the stopped state and exit codes still match.
let mut current: SERVICE_STATUS_PROCESS = unsafe { std::mem::zeroed() };
let mut bytes_needed = 0;
if unsafe {
services::QueryServiceStatusEx(
service,
services::SC_STATUS_PROCESS_INFO,
ptr::from_mut(&mut current).cast(),
size_of_val(&current) as u32,
&mut bytes_needed,
)
} == 0
|| current.dwCurrentState != services::SERVICE_STOPPED
|| current.dwWin32ExitCode != status.dwWin32ExitCode
|| current.dwServiceSpecificExitCode != status.dwServiceSpecificExitCode
|| read_stop() != value
{
return;
}
// This counts observations, not unique outages. SCM's exit code also covers
// crashes/kills that cannot write a final record. The registry is advisory.
let _ = metrics.counter(
"codex.windows_sandbox.service_stopped",
/*inc*/ 1,
&[
(
"last_reported_reason",
match (value >> 32) as u32 {
1 => "no_stop_recorded",
2 => "stop_requested",
3 => "shutdown",
4 => "owner_removed",
5 => "startup_failed",
6 => "broker_failed",
7 => "registration_interrupted",
_ => "unknown",
},
),
("last_reported_hresult", &format!("0x{:08x}", value as u32)),
("win32_exit_code", &status.dwWin32ExitCode.to_string()),
(
"service_exit_code",
&status.dwServiceSpecificExitCode.to_string(),
),
],
);
}

View File

@@ -0,0 +1,67 @@
//! Keep each packaged channel's service and pipe separate while accounts remain shared.
//! An unpackaged client may use a routing hint; service admission still verifies OS identity.
use anyhow::Context;
use anyhow::Result;
use anyhow::ensure;
use windows_sys::Win32::System::Threading::GetCurrentProcess;
use crate::package_identity::process_package_family;
/// SCM name matching the packaged application's manifest. Unpackaged callers keep
/// the legacy service lookup and may use ordinary elevated setup when it is absent.
pub fn windows_sandbox_service_name() -> Result<String> {
let Some(family) = service_package_family()? else {
return Ok("CodexSandboxService".into());
};
let (name, _) = family.rsplit_once('_').context("invalid package family")?;
Ok(format!("CodexSandboxService.{name}"))
}
/// The full family, including publisher identity, qualifies the authenticated pipe.
pub fn windows_sandbox_service_pipe_name() -> Result<String> {
Ok(match service_package_family()? {
Some(family) => format!("{}.{}", crate::SANDBOX_PROVISIONING_PIPE_NAME, family),
None => crate::SANDBOX_PROVISIONING_PIPE_NAME.into(),
})
}
pub(crate) fn current_family() -> Result<Option<String>> {
unsafe { process_package_family(GetCurrentProcess()) }
}
fn service_package_family() -> Result<Option<String>> {
if let Some(family) = current_family()? {
return Ok(Some(family));
}
let Some(hint) = std::env::var_os("AKODE_WINDOWS_SANDBOX_PACKAGE_FAMILY") else {
return Ok(None);
};
let family = hint
.to_str()
.context("service package family is not UTF-8")?;
validate_service_family_hint(family)?;
// Lookup only: SCM/pipe verification and registered-client admission use OS identity.
Ok(Some(family.to_owned()))
}
fn validate_service_family_hint(family: &str) -> Result<()> {
let (name, publisher) = family
.rsplit_once('_')
.context("invalid service package family")?;
ensure!(
!name.is_empty()
&& name.len() <= 50
&& name
.bytes()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, b'.' | b'-'))
&& publisher.len() == 13
&& publisher.bytes().all(|c| c.is_ascii_alphanumeric()),
"invalid service package family"
);
Ok(())
}
#[cfg(test)]
#[path = "service_identity_tests.rs"]
mod tests;

View File

@@ -0,0 +1,26 @@
use super::validate_service_family_hint;
#[test]
fn service_routing_accepts_package_families() {
for family in [
"OpenAI.Codex_3k8sg7r9htsxt",
"OpenAI.CodexBeta_jabp31b5fhs74",
] {
assert!(validate_service_family_hint(family).is_ok());
}
}
#[test]
fn service_routing_rejects_paths_and_malformed_families() {
for family in [
"",
"_3k8sg7r9htsxt",
"OpenAI.Codex_bad",
"OpenAI.Codex_3k8sg7r9htsxt\\child",
"..\\OpenAI.Codex_3k8sg7r9htsxt",
"OpenAI.Codex_extra_3k8sg7r9htsxt",
"OpenAI.Codex\0_3k8sg7r9htsxt",
] {
assert!(validate_service_family_hint(family).is_err(), "{family:?}");
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,43 @@
//! Preserve native ACL failure causes in both refresh summaries and setup logs.
//! Recording a diagnostic never changes whether a failed ACL operation is fatal.
use anyhow::Error;
use anyhow::Result;
use std::path::Path;
pub(crate) enum WriteAclOperation {
Check,
Grant,
Deny,
}
pub(crate) fn record_acl_failure(
errors: &mut Vec<String>,
operation: WriteAclOperation,
path: &Path,
error: &Error,
write_log: impl FnOnce(&str) -> Result<()>,
) -> Result<()> {
let detail = format!("{}: {error:#}", path.display());
let (summary, log) = match operation {
WriteAclOperation::Check => (
format!("write ACE check failed on {detail}"),
format!("write ACE check failed on {detail}; continuing"),
),
WriteAclOperation::Grant => (
format!("write ACE failed on {detail}"),
format!("write ACE grant failed on {detail}"),
),
WriteAclOperation::Deny => (
format!("deny ACE failed on {detail}"),
format!("deny ACE failed on {detail}"),
),
};
// Retain the ACL failure even if writing its individual log line fails.
errors.push(summary);
write_log(&log)
}
#[cfg(test)]
#[path = "setup_acl_error_tests.rs"]
mod tests;

View File

@@ -0,0 +1,74 @@
use super::WriteAclOperation;
use super::record_acl_failure;
use anyhow::anyhow;
use pretty_assertions::assert_eq;
use std::io;
use std::path::Path;
#[test]
fn records_each_acl_operation_with_its_native_error_chain() {
let path = Path::new("project/.git");
let native_error = io::Error::from_raw_os_error(5);
// The native wording is platform-dependent; the code and cause chain are not.
let native_message = native_error.to_string();
let error = anyhow::Error::new(native_error)
.context("open ACL target (READ_CONTROL | WRITE_DAC)")
.context("prepare protected path");
let detail = format!(
"project/.git: prepare protected path: open ACL target (READ_CONTROL | WRITE_DAC): {native_message}"
);
let mut errors = Vec::new();
let mut log = Vec::new();
for operation in [
WriteAclOperation::Check,
WriteAclOperation::Grant,
WriteAclOperation::Deny,
] {
record_acl_failure(&mut errors, operation, path, &error, |message| {
log.push(message.to_owned());
Ok(())
})
.expect("record ACL failure");
}
assert_eq!(
(errors, log),
(
vec![
format!("write ACE check failed on {detail}"),
format!("write ACE failed on {detail}"),
format!("deny ACE failed on {detail}"),
],
vec![
format!("write ACE check failed on {detail}; continuing"),
format!("write ACE grant failed on {detail}"),
format!("deny ACE failed on {detail}"),
],
)
);
}
#[test]
fn log_failure_preserves_acl_failure_and_previous_roots() {
let mut errors = vec!["previous root failed".to_string()];
let error = anyhow!("SetSecurityInfo failed: 87").context("grant write ACL");
let log_error = record_acl_failure(
&mut errors,
WriteAclOperation::Grant,
Path::new("virtual-drive/project"),
&error,
|_| Err(anyhow!("log unavailable")),
)
.expect_err("report log failure");
assert_eq!(
(errors, log_error.to_string()),
(
vec![
"previous root failed".to_string(),
"write ACE failed on virtual-drive/project: grant write ACL: SetSecurityInfo failed: 87"
.to_string(),
],
"log unavailable".to_string(),
)
);
}

View File

@@ -0,0 +1,289 @@
use anyhow::Context;
use anyhow::Result;
use akode_utils_string::sanitize_metric_tag_value;
use serde::Deserialize;
use serde::Serialize;
use std::fs;
use std::io::ErrorKind;
use std::path::Path;
use std::path::PathBuf;
/// These represent the most common failures for the elevated sandbox setup.
///
/// Codes are used as metric tags.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SetupErrorCode {
// Orchestrator (run in CLI) failures.
/// Failed to create `codex_home/.sandbox` in the orchestrator.
OrchestratorSandboxDirCreateFailed,
/// Failed to determine whether the current process is elevated.
OrchestratorElevationCheckFailed,
/// The setup command requires an already elevated process.
OrchestratorElevationRequired,
/// Failed to serialize the elevation payload before launching the helper.
OrchestratorPayloadSerializeFailed,
/// Failed to launch the setup helper process (spawn or ShellExecuteExW).
OrchestratorHelperLaunchFailed,
/// User canceled the UAC prompt while launching the helper.
OrchestratorHelperLaunchCanceled,
/// Helper exited non-zero and no structured report was available.
OrchestratorHelperExitNonzero,
/// Helper exited non-zero and reading `setup_error.json` failed.
OrchestratorHelperReportReadFailed,
/// Helper exited successfully before setup completed.
OrchestratorHelperIncomplete,
// Helper (elevated process) failures.
/// Helper failed while validating or decoding the request payload.
HelperRequestArgsFailed,
/// Helper failed to create `codex_home/.sandbox`.
HelperSandboxDirCreateFailed,
/// Helper failed to open or write the setup log.
HelperLogFailed,
/// Helper failed in the provisioning phase (fallback bucket).
HelperUserProvisionFailed,
/// Helper failed to create the sandbox users local group.
HelperUsersGroupCreateFailed,
/// Helper failed to create or update a sandbox user account.
HelperUserCreateOrUpdateFailed,
/// Helper failed to protect user passwords with DPAPI.
HelperDpapiProtectFailed,
/// Helper failed to write the sandbox users secrets file.
HelperUsersFileWriteFailed,
/// Helper failed to write or protect the setup marker file.
HelperSetupMarkerWriteFailed,
/// Helper failed to resolve a SID or convert it to a PSID.
HelperSidResolveFailed,
/// Helper failed to load or convert capability SIDs.
HelperCapabilitySidFailed,
/// Helper failed to initialize COM for firewall configuration.
HelperFirewallComInitFailed,
/// Helper failed to access firewall policy or rule collections.
HelperFirewallPolicyAccessFailed,
/// Helper detected that local firewall policy changes will not fully take effect.
HelperFirewallPolicyIneffective,
/// Helper failed to create, update, or add the firewall rule.
HelperFirewallRuleCreateOrAddFailed,
/// Helper failed to verify the configured firewall rule scope.
HelperFirewallRuleVerifyFailed,
/// Helper failed to spawn the read-ACL helper process.
HelperReadAclHelperSpawnFailed,
/// Helper failed to lock down sandbox directories via ACLs.
HelperSandboxLockFailed,
/// Helper failed for an unmapped or unexpected reason.
HelperUnknownError,
}
impl SetupErrorCode {
pub fn as_str(self) -> &'static str {
match self {
Self::OrchestratorSandboxDirCreateFailed => "orchestrator_sandbox_dir_create_failed",
Self::OrchestratorElevationCheckFailed => "orchestrator_elevation_check_failed",
Self::OrchestratorElevationRequired => "orchestrator_elevation_required",
Self::OrchestratorPayloadSerializeFailed => "orchestrator_payload_serialize_failed",
Self::OrchestratorHelperLaunchFailed => "orchestrator_helper_launch_failed",
Self::OrchestratorHelperLaunchCanceled => "orchestrator_helper_launch_canceled",
Self::OrchestratorHelperExitNonzero => "orchestrator_helper_exit_nonzero",
Self::OrchestratorHelperReportReadFailed => "orchestrator_helper_report_read_failed",
Self::OrchestratorHelperIncomplete => "orchestrator_helper_incomplete",
Self::HelperRequestArgsFailed => "helper_request_args_failed",
Self::HelperSandboxDirCreateFailed => "helper_sandbox_dir_create_failed",
Self::HelperLogFailed => "helper_log_failed",
Self::HelperUserProvisionFailed => "helper_user_provision_failed",
Self::HelperUsersGroupCreateFailed => "helper_users_group_create_failed",
Self::HelperUserCreateOrUpdateFailed => "helper_user_create_or_update_failed",
Self::HelperDpapiProtectFailed => "helper_dpapi_protect_failed",
Self::HelperUsersFileWriteFailed => "helper_users_file_write_failed",
Self::HelperSetupMarkerWriteFailed => "helper_setup_marker_write_failed",
Self::HelperSidResolveFailed => "helper_sid_resolve_failed",
Self::HelperCapabilitySidFailed => "helper_capability_sid_failed",
Self::HelperFirewallComInitFailed => "helper_firewall_com_init_failed",
Self::HelperFirewallPolicyAccessFailed => "helper_firewall_policy_access_failed",
Self::HelperFirewallPolicyIneffective => "helper_firewall_policy_ineffective",
Self::HelperFirewallRuleCreateOrAddFailed => {
"helper_firewall_rule_create_or_add_failed"
}
Self::HelperFirewallRuleVerifyFailed => "helper_firewall_rule_verify_failed",
Self::HelperReadAclHelperSpawnFailed => "helper_read_acl_helper_spawn_failed",
Self::HelperSandboxLockFailed => "helper_sandbox_lock_failed",
Self::HelperUnknownError => "helper_unknown_error",
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SetupErrorReport {
pub code: SetupErrorCode,
pub message: String,
}
#[derive(Debug, PartialEq, Eq)]
pub struct SetupFailure {
pub code: SetupErrorCode,
pub message: String,
}
impl SetupFailure {
pub fn new(code: SetupErrorCode, message: impl Into<String>) -> Self {
Self {
code,
message: message.into(),
}
}
pub fn from_report(report: SetupErrorReport) -> Self {
Self::new(report.code, report.message)
}
pub fn metric_message(&self) -> String {
sanitize_setup_metric_tag_value(&self.message)
}
}
impl std::fmt::Display for SetupFailure {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {}", self.code.as_str(), self.message)
}
}
impl std::error::Error for SetupFailure {}
pub fn failure(code: SetupErrorCode, message: impl Into<String>) -> anyhow::Error {
anyhow::Error::new(SetupFailure::new(code, message))
}
pub fn extract_failure(err: &anyhow::Error) -> Option<&SetupFailure> {
err.downcast_ref::<SetupFailure>()
}
pub fn setup_error_path(codex_home: &Path) -> PathBuf {
codex_home.join(".sandbox").join("setup_error.json")
}
pub fn clear_setup_error_report(codex_home: &Path) -> Result<()> {
let path = setup_error_path(codex_home);
match fs::remove_file(&path) {
Ok(()) => Ok(()),
Err(err) if err.kind() == ErrorKind::NotFound => Ok(()),
Err(err) => Err(err).with_context(|| format!("remove {}", path.display())),
}
}
pub fn write_setup_error_report(codex_home: &Path, report: &SetupErrorReport) -> Result<()> {
let sandbox_dir = codex_home.join(".sandbox");
fs::create_dir_all(&sandbox_dir)
.with_context(|| format!("create sandbox dir {}", sandbox_dir.display()))?;
let path = setup_error_path(codex_home);
let json = serde_json::to_vec_pretty(report)?;
fs::write(&path, json).with_context(|| format!("write {}", path.display()))?;
Ok(())
}
pub fn read_setup_error_report(codex_home: &Path) -> Result<Option<SetupErrorReport>> {
let path = setup_error_path(codex_home);
let bytes = match fs::read(&path) {
Ok(bytes) => bytes,
Err(err) if err.kind() == ErrorKind::NotFound => return Ok(None),
Err(err) => return Err(err).with_context(|| format!("read {}", path.display())),
};
let report = serde_json::from_slice::<SetupErrorReport>(&bytes)
.with_context(|| format!("parse {}", path.display()))?;
Ok(Some(report))
}
/// Sanitize a setup error message for use as a metric tag.
pub fn sanitize_setup_metric_tag_value(value: &str) -> String {
sanitize_metric_tag_value(redact_home_paths(value).as_str())
}
fn redact_home_paths(value: &str) -> String {
let mut usernames: Vec<String> = Vec::new();
if let Ok(username) = std::env::var("USERNAME")
&& !username.trim().is_empty()
{
usernames.push(username);
}
if let Ok(user) = std::env::var("USER")
&& !user.trim().is_empty()
&& !usernames.iter().any(|v| v.eq_ignore_ascii_case(&user))
{
usernames.push(user);
}
redact_username_segments(value, &usernames)
}
fn redact_username_segments(value: &str, usernames: &[String]) -> String {
if usernames.is_empty() {
return value.to_string();
}
let mut segments: Vec<String> = Vec::new();
let mut separators: Vec<char> = Vec::new();
let mut current = String::new();
for ch in value.chars() {
if ch == '\\' || ch == '/' {
segments.push(std::mem::take(&mut current));
separators.push(ch);
} else {
current.push(ch);
}
}
segments.push(current);
for segment in &mut segments {
let matches = if cfg!(windows) {
usernames
.iter()
.any(|name| segment.eq_ignore_ascii_case(name))
} else {
usernames.iter().any(|name| segment == name)
};
if matches {
*segment = "<user>".to_string();
}
}
let mut out = String::new();
for (idx, segment) in segments.iter().enumerate() {
out.push_str(segment);
if let Some(sep) = separators.get(idx) {
out.push(*sep);
}
}
out
}
#[cfg(test)]
mod tests {
use super::redact_username_segments;
use pretty_assertions::assert_eq;
#[test]
fn sanitize_tag_value_redacts_username_segments() {
let usernames = vec!["Alice".to_string(), "Bob".to_string()];
let msg = "failed to write C:\\Users\\Alice\\file.txt; fallback D:\\Profiles\\Bob\\x";
let redacted = redact_username_segments(msg, &usernames);
assert_eq!(
redacted,
"failed to write C:\\Users\\<user>\\file.txt; fallback D:\\Profiles\\<user>\\x"
);
}
#[test]
fn sanitize_tag_value_leaves_unknown_segments() {
let usernames = vec!["Alice".to_string()];
let msg = "failed to write E:\\data\\file.txt";
let redacted = redact_username_segments(msg, &usernames);
assert_eq!(redacted, msg);
}
#[test]
fn sanitize_tag_value_redacts_multiple_occurrences() {
let usernames = vec!["Alice".to_string()];
let msg = "C:\\Users\\Alice\\a and C:\\Users\\Alice\\b";
let redacted = redact_username_segments(msg, &usernames);
assert_eq!(redacted, "C:\\Users\\<user>\\a and C:\\Users\\<user>\\b");
}
}

View File

@@ -0,0 +1,75 @@
//! Starts provisioning helpers only after their retained directory handles are installed.
//! The child owns its duplicates until exit, independently of the service lifetime.
use std::io;
use std::os::windows::io::AsRawHandle;
use std::os::windows::io::BorrowedHandle;
use std::os::windows::process::CommandExt;
use std::process::Child;
use std::process::Command;
use std::process::Stdio;
use windows_sys::Win32::Foundation::DUPLICATE_SAME_ACCESS;
use windows_sys::Win32::Foundation::DuplicateHandle;
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::Foundation::NTSTATUS;
use windows_sys::Win32::Foundation::RtlNtStatusToDosError;
use windows_sys::Win32::System::Threading::CREATE_NO_WINDOW;
use windows_sys::Win32::System::Threading::CREATE_SUSPENDED;
use windows_sys::Win32::System::Threading::GetCurrentProcess;
#[link(name = "ntdll")]
unsafe extern "system" {
fn NtResumeProcess(process_handle: HANDLE) -> NTSTATUS;
}
pub(super) fn spawn_with_retained_handles(
command: &mut Command,
retained_handles: &[BorrowedHandle<'_>],
) -> io::Result<Child> {
let mut child = command
.creation_flags(CREATE_NO_WINDOW | CREATE_SUSPENDED)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()?;
let initialized = (|| {
for handle in retained_handles {
let mut child_handle = std::ptr::null_mut();
if unsafe {
DuplicateHandle(
GetCurrentProcess(),
handle.as_raw_handle() as HANDLE,
child.as_raw_handle() as HANDLE,
&mut child_handle,
/*dwdesiredaccess*/ 0,
/*binherithandle*/ 0,
DUPLICATE_SAME_ACCESS,
)
} == 0
{
return Err(io::Error::last_os_error());
}
// This value belongs to the child's handle table. Do not close it here
// or make it inheritable by unrelated processes or helper descendants.
}
let status = unsafe { NtResumeProcess(child.as_raw_handle() as HANDLE) };
if status < 0 {
return Err(io::Error::from_raw_os_error(
unsafe { RtlNtStatusToDosError(status) } as i32,
));
}
Ok(())
})();
if let Err(error) = initialized {
// A partially initialized helper must never run after its parent drops
// the directory protections. Reap it, including any installed duplicates.
child.kill()?;
child.wait()?;
return Err(error);
}
Ok(child)
}
#[cfg(test)]
#[path = "setup_launch_tests.rs"]
mod tests;

View File

@@ -0,0 +1,136 @@
//! Exercises retained setup pins using bounded, disposable child processes.
use std::fs;
use std::io;
use std::io::Write;
use std::os::windows::fs::OpenOptionsExt;
use std::os::windows::io::AsHandle;
use std::path::PathBuf;
use std::process::Child;
use std::process::Command;
use std::time::Duration;
use std::time::Instant;
use pretty_assertions::assert_eq;
use windows_sys::Win32::Storage::FileSystem::DELETE;
use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS;
use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_DELETE_ON_CLOSE;
use windows_sys::Win32::Storage::FileSystem::FILE_READ_DATA;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_WRITE;
use super::spawn_with_retained_handles;
const CHILD_TEST: &str = "setup_launch::tests::retained_handles_child";
const CHILD_DIRECTORY_ENV: &str = "AKODE_TEST_SETUP_LAUNCH_DIRECTORY";
const CHILD_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 10);
const POLL_INTERVAL: Duration = Duration::from_millis(/*millis*/ 10);
struct ChildGuard(Child);
impl Drop for ChildGuard {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
#[test]
fn child_retains_directory_pin_until_exit() -> io::Result<()> {
let temporary = tempfile::tempdir()?;
let directory = temporary.path().join("pinned");
let renamed_directory = temporary.path().join("renamed");
fs::create_dir(&directory)?;
let pin = fs::OpenOptions::new()
.read(true)
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
.open(&directory)?;
let guard_path = directory.join(".guard");
let guard = fs::OpenOptions::new()
.write(true)
.create_new(true)
.access_mode(FILE_READ_DATA | DELETE)
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
.custom_flags(FILE_FLAG_DELETE_ON_CLOSE)
.open(&guard_path)?;
let mut command = Command::new(std::env::current_exe()?);
command
.args(["--exact", CHILD_TEST, "--ignored"])
.env(CHILD_DIRECTORY_ENV, temporary.path());
let mut child = ChildGuard(spawn_with_retained_handles(
&mut command,
&[pin.as_handle(), guard.as_handle()],
)?);
drop(pin);
drop(guard);
let started = Instant::now();
while !temporary.path().join("ready").exists() {
assert_eq!(
child.0.try_wait()?,
None,
"child exited before becoming ready"
);
assert!(
started.elapsed() < CHILD_TIMEOUT,
"child did not become ready"
);
std::thread::sleep(POLL_INTERVAL);
}
assert!(
fs::rename(&directory, &renamed_directory).is_err(),
"the child's duplicate must keep the directory pinned after the parent drops its handle"
);
assert_eq!(child.0.try_wait()?, None);
assert!(guard_path.exists(), "the child must retain the guard file");
fs::write(temporary.path().join("release"), b"")?;
let started = Instant::now();
let status = loop {
if let Some(status) = child.0.try_wait()? {
break status;
}
assert!(started.elapsed() < CHILD_TIMEOUT, "child did not exit");
std::thread::sleep(POLL_INTERVAL);
};
assert!(status.success(), "child failed: {status}");
assert!(
!guard_path.exists(),
"the guard must be deleted on child exit"
);
fs::rename(&directory, &renamed_directory)?;
Ok(())
}
#[test]
fn missing_executable_returns_spawn_error_without_closing_retained_handles() -> io::Result<()> {
let temporary = tempfile::tempdir()?;
let mut retained_file = tempfile::tempfile()?;
let mut command = Command::new(temporary.path().join("missing.exe"));
let error = spawn_with_retained_handles(&mut command, &[retained_file.as_handle()])
.expect_err("missing executable must fail to spawn");
assert_eq!(error.kind(), io::ErrorKind::NotFound);
retained_file.write_all(b"the caller still owns its handle")?;
Ok(())
}
#[test]
#[ignore = "child process for child_retains_directory_pin_until_exit"]
fn retained_handles_child() -> io::Result<()> {
let Some(directory) = std::env::var_os(CHILD_DIRECTORY_ENV).map(PathBuf::from) else {
return Ok(());
};
fs::write(directory.join("ready"), b"")?;
let started = Instant::now();
while !directory.join("release").exists() {
assert!(
started.elapsed() < CHILD_TIMEOUT,
"parent did not release child"
);
std::thread::sleep(POLL_INTERVAL);
}
Ok(())
}

View File

@@ -0,0 +1,83 @@
//! Serializes sandbox account and network changes across setup and uninstall.
//! The acquiring thread must hold the lock until those changes finish.
use std::io;
use std::marker::PhantomData;
use std::os::windows::io::AsRawHandle;
use std::os::windows::io::FromRawHandle;
use std::os::windows::io::OwnedHandle;
use std::ptr::null_mut;
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::Foundation::HLOCAL;
use windows_sys::Win32::Foundation::LocalFree;
use windows_sys::Win32::Foundation::WAIT_ABANDONED;
use windows_sys::Win32::Foundation::WAIT_OBJECT_0;
use windows_sys::Win32::Foundation::WAIT_TIMEOUT;
use windows_sys::Win32::Security::Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW;
use windows_sys::Win32::Security::SECURITY_ATTRIBUTES;
use windows_sys::Win32::System::Threading::CreateMutexW;
use windows_sys::Win32::System::Threading::ReleaseMutex;
use windows_sys::Win32::System::Threading::WaitForSingleObject;
use crate::winutil::to_wide;
/// Holds the machine-wide setup lock on the thread that acquired it.
#[must_use]
pub struct SandboxSetupLock {
handle: OwnedHandle,
_thread_bound: PhantomData<*mut ()>,
}
impl Drop for SandboxSetupLock {
fn drop(&mut self) {
unsafe {
ReleaseMutex(self.handle.as_raw_handle() as HANDLE);
}
}
}
/// Waits up to `timeout_ms` for exclusive access by LocalSystem or an elevated administrator.
pub fn acquire_sandbox_setup_lock(timeout_ms: u32) -> Result<SandboxSetupLock> {
let sddl = to_wide("D:P(A;;GA;;;SY)(A;;GA;;;BA)");
let mut descriptor = null_mut();
if unsafe {
ConvertStringSecurityDescriptorToSecurityDescriptorW(
sddl.as_ptr(),
/*stringsdrevision*/ 1,
&mut descriptor,
null_mut(),
)
} == 0
{
return Err(io::Error::last_os_error()).context("create sandbox setup mutex security");
}
let attributes = SECURITY_ATTRIBUTES {
nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
lpSecurityDescriptor: descriptor,
bInheritHandle: 0,
};
let name = to_wide(r"Global\CodexSandboxSetup");
let handle = unsafe {
CreateMutexW(&attributes, /*binitialowner*/ 0, name.as_ptr())
};
let result = if handle.is_null() {
Err(io::Error::last_os_error())
} else {
Ok(unsafe { OwnedHandle::from_raw_handle(handle as _) })
};
unsafe { LocalFree(descriptor as HLOCAL) };
let handle = result.context("open sandbox setup mutex")?;
match unsafe { WaitForSingleObject(handle.as_raw_handle() as HANDLE, timeout_ms) } {
// A crashed owner releases the lock; setup still repairs any incomplete account changes.
WAIT_OBJECT_0 | WAIT_ABANDONED => Ok(SandboxSetupLock {
handle,
_thread_bound: PhantomData,
}),
WAIT_TIMEOUT => bail!("timed out waiting for sandbox setup mutex after {timeout_ms} ms"),
_ => Err(io::Error::last_os_error()).context("wait for sandbox setup mutex"),
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,202 @@
use super::DELETE;
use super::DaclInheritance;
use super::FILE_GENERIC_EXECUTE;
use super::FILE_GENERIC_READ;
use super::FILE_GENERIC_WRITE;
use super::GRANT_ACCESS;
use super::Payload;
use super::SETUP_VERSION;
use super::SetupMode;
use super::SetupRuntime;
use super::WRITE_DAC;
use super::convert_string_sid_to_sid;
use super::lock_sandbox_bin_dir;
use super::lock_sandbox_dir;
use super::resolve_sid;
use super::sid_bytes_to_psid;
use crate::ensure_allow_write_aces;
use crate::extract_setup_failure;
use crate::path_mask_allows;
use crate::read_setup_error_report;
use crate::workspace_write_cap_sid_for_root;
use crate::write_setup_error_report;
use pretty_assertions::assert_eq;
use std::fs;
use windows_sys::Win32::Foundation::ERROR_PATH_NOT_FOUND;
use windows_sys::Win32::Foundation::HLOCAL;
use windows_sys::Win32::Foundation::LocalFree;
#[test]
fn bin_lock_report_retains_native_open_error() {
let temp = tempfile::tempdir().expect("tempdir");
let mut payload: Payload =
serde_json::from_value(super::tests::payload_json()).expect("fixture payload");
// The no-reparse open cannot create a bin whose parent does not exist.
// It fails before resolving account SIDs or changing any permissions.
payload.codex_home = temp.path().join("missing-home");
payload.mode = SetupMode::ProvisionOnly;
let bin = super::sandbox_bin_dir(&payload.codex_home);
let error = lock_sandbox_bin_dir(&payload, &[]).expect_err("missing bin parent");
let failure = extract_setup_failure(&error).expect("structured lock failure");
let expected = crate::SetupFailure::new(
crate::SetupErrorCode::HelperSandboxLockFailed,
format!(
"lock sandbox bin dir {0} failed: open directory {0}: NtCreateFile: {1}",
bin.display(),
std::io::Error::from_raw_os_error(ERROR_PATH_NOT_FOUND as i32),
),
);
assert_eq!(failure, &expected);
write_setup_error_report(
temp.path(),
&crate::SetupErrorReport {
code: failure.code,
message: failure.message.clone(),
},
)
.expect("write structured failure");
let report = read_setup_error_report(temp.path())
.expect("read structured failure")
.expect("failure report");
assert_eq!(crate::SetupFailure::from_report(report), expected);
assert!(!payload.codex_home.exists());
}
#[test]
fn provision_only_locks_plain_directory_via_handle() {
let temp = tempfile::tempdir().expect("tempdir");
let sandbox_bin = temp.path().join(".sandbox-bin");
let real_user = std::env::var("USERNAME").unwrap_or_else(|_| "Administrators".to_string());
let real_sid = resolve_sid(&real_user).expect("resolve real user SID");
lock_sandbox_dir(
&sandbox_bin,
&real_user,
&real_sid,
GRANT_ACCESS,
FILE_GENERIC_READ | FILE_GENERIC_EXECUTE,
FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE | DELETE,
DaclInheritance::Protected,
SetupMode::ProvisionOnly,
)
.expect("lock sandbox bin via no-reparse handle");
assert!(sandbox_bin.is_dir());
}
#[test]
fn lock_sandbox_dir_blocks_inherited_write_for_runner_files() {
for setup_mode in [SetupMode::Full, SetupMode::ProvisionOnly] {
let temp = tempfile::tempdir().expect("tempdir");
let workspace = temp.path().join("workspace");
let sandbox_bin = workspace.join(".sandbox-bin");
fs::create_dir(&workspace).expect("create workspace");
let workspace_sid = workspace_write_cap_sid_for_root(temp.path(), temp.path(), temp.path())
.expect("workspace SID");
let workspace_psid =
unsafe { convert_string_sid_to_sid(&workspace_sid).expect("convert workspace SID") };
let sandbox_group_sid =
resolve_sid("Authenticated Users").expect("resolve sandbox group SID");
let sandbox_group_psid =
sid_bytes_to_psid(&sandbox_group_sid).expect("convert sandbox group SID");
unsafe { ensure_allow_write_aces(&workspace, &[workspace_psid]) }
.expect("grant inherited workspace write access");
fs::create_dir(&sandbox_bin).expect("create sandbox bin");
let existing_runner = sandbox_bin.join("existing-runner.exe");
fs::write(&existing_runner, b"existing").expect("create existing runner");
assert!(
path_mask_allows(
&existing_runner,
&[workspace_psid],
FILE_GENERIC_WRITE | DELETE,
/*require_all_bits*/ true,
)
.expect("check inherited runner write and delete access")
);
let real_user = std::env::var("USERNAME").unwrap_or_else(|_| "Administrators".to_string());
let payload = Payload {
version: SETUP_VERSION,
offline_username: String::new(),
online_username: String::new(),
codex_home: workspace.clone(),
command_cwd: workspace.clone(),
read_roots: Vec::new(),
write_roots: Vec::new(),
deny_read_paths: Vec::new(),
deny_write_paths: Vec::new(),
proxy_ports: Vec::new(),
allow_local_binding: false,
otel: None,
real_user,
user_profile: None,
mode: setup_mode,
runtime: SetupRuntime::Legacy,
refresh_only: false,
};
lock_sandbox_bin_dir(&payload, &sandbox_group_sid).expect("lock sandbox bin");
let real_sid = resolve_sid(&payload.real_user).expect("resolve real owner SID");
let real_psid = sid_bytes_to_psid(&real_sid).expect("convert real owner SID");
assert!(
path_mask_allows(
&sandbox_bin,
&[real_psid],
WRITE_DAC,
/*require_all_bits*/ true
)
.expect("owner ACE permits refreshing the bin DACL")
);
assert!(
!path_mask_allows(
&sandbox_bin,
&[sandbox_group_psid],
WRITE_DAC,
/*require_all_bits*/ true,
)
.expect("sandbox cannot change the bin DACL")
);
let system_sid = resolve_sid("SYSTEM").expect("resolve SYSTEM SID");
let system_psid = sid_bytes_to_psid(&system_sid).expect("convert SYSTEM SID");
let new_runner = sandbox_bin.join("new-runner.exe");
fs::write(&new_runner, b"new").expect("create new runner");
for path in [&sandbox_bin, &existing_runner, &new_runner] {
assert!(
path_mask_allows(
path,
&[system_psid],
WRITE_DAC,
/*require_all_bits*/ true
)
.expect("SYSTEM can reapply the bin policy")
);
assert!(
!path_mask_allows(
path,
&[workspace_psid],
FILE_GENERIC_WRITE | DELETE,
/*require_all_bits*/ false,
)
.expect("check protected path write and delete access")
);
assert!(
path_mask_allows(
path,
&[sandbox_group_psid],
FILE_GENERIC_READ | FILE_GENERIC_EXECUTE,
/*require_all_bits*/ true,
)
.expect("check protected path read and execute access")
);
}
unsafe {
LocalFree(real_psid as HLOCAL);
LocalFree(workspace_psid as HLOCAL);
LocalFree(sandbox_group_psid as HLOCAL);
}
}
}

View File

@@ -0,0 +1,643 @@
use anyhow::Result;
use std::io::Write;
use windows::Win32::Foundation::RPC_E_CHANGED_MODE;
use windows::Win32::Foundation::S_OK;
use windows::Win32::Foundation::VARIANT_TRUE;
use windows::Win32::NetworkManagement::WindowsFirewall::INetFwPolicy2;
use windows::Win32::NetworkManagement::WindowsFirewall::INetFwRule3;
use windows::Win32::NetworkManagement::WindowsFirewall::INetFwRules;
use windows::Win32::NetworkManagement::WindowsFirewall::NET_FW_ACTION_BLOCK;
use windows::Win32::NetworkManagement::WindowsFirewall::NET_FW_IP_PROTOCOL_ANY;
use windows::Win32::NetworkManagement::WindowsFirewall::NET_FW_IP_PROTOCOL_TCP;
use windows::Win32::NetworkManagement::WindowsFirewall::NET_FW_IP_PROTOCOL_UDP;
use windows::Win32::NetworkManagement::WindowsFirewall::NET_FW_MODIFY_STATE;
use windows::Win32::NetworkManagement::WindowsFirewall::NET_FW_MODIFY_STATE_OK;
use windows::Win32::NetworkManagement::WindowsFirewall::NET_FW_PROFILE2_ALL;
use windows::Win32::NetworkManagement::WindowsFirewall::NET_FW_RULE_DIR_IN;
use windows::Win32::NetworkManagement::WindowsFirewall::NET_FW_RULE_DIR_OUT;
use windows::Win32::NetworkManagement::WindowsFirewall::NET_FW_RULE_DIRECTION;
use windows::Win32::NetworkManagement::WindowsFirewall::NetFwPolicy2;
use windows::Win32::NetworkManagement::WindowsFirewall::NetFwRule;
use windows::Win32::System::Com::CLSCTX_INPROC_SERVER;
use windows::Win32::System::Com::COINIT_APARTMENTTHREADED;
use windows::Win32::System::Com::CoCreateInstance;
use windows::Win32::System::Com::CoInitializeEx;
use windows::Win32::System::Com::CoUninitialize;
use windows::core::BSTR;
use windows::core::Interface;
use crate::SetupErrorCode;
use crate::SetupFailure;
// This is the stable identifier we use to find/update the rule idempotently.
// It intentionally does not change between installs.
const OFFLINE_BLOCK_RULE_NAME: &str = "codex_sandbox_offline_block_outbound";
const OFFLINE_BLOCK_INBOUND_RULE_NAME: &str = "codex_sandbox_offline_block_inbound";
const OFFLINE_BLOCK_LOOPBACK_TCP_RULE_NAME: &str = "codex_sandbox_offline_block_loopback_tcp";
const OFFLINE_BLOCK_LOOPBACK_UDP_RULE_NAME: &str = "codex_sandbox_offline_block_loopback_udp";
// Friendly text shown in the firewall UI.
const OFFLINE_BLOCK_RULE_FRIENDLY: &str = "Codex Sandbox Offline - Block Non-Loopback Outbound";
const OFFLINE_BLOCK_INBOUND_RULE_FRIENDLY: &str =
"Codex Sandbox Offline - Block Non-Loopback Inbound";
const OFFLINE_BLOCK_LOOPBACK_TCP_RULE_FRIENDLY: &str =
"Codex Sandbox Offline - Block Loopback TCP (Except Proxy)";
const OFFLINE_BLOCK_LOOPBACK_UDP_RULE_FRIENDLY: &str = "Codex Sandbox Offline - Block Loopback UDP";
const OFFLINE_PROXY_ALLOW_RULE_NAME: &str = "codex_sandbox_offline_allow_loopback_proxy";
const LOOPBACK_REMOTE_ADDRESSES: &str = "127.0.0.0/8,::/127";
const NON_LOOPBACK_REMOTE_ADDRESSES: &str = "0.0.0.0-126.255.255.255,128.0.0.0-255.255.255.255,::,::2-ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff";
struct BlockRuleSpec<'a> {
internal_name: &'a str,
friendly_desc: &'a str,
direction: NET_FW_RULE_DIRECTION,
protocol: i32,
local_user_spec: &'a str,
offline_sid: &'a str,
remote_addresses: Option<&'a str>,
remote_ports: Option<&'a str>,
}
// Firewall COM also supports the service's existing MTA. Balance only our own initialization.
struct FirewallComApartment {
initialized: bool,
}
impl FirewallComApartment {
fn initialize() -> Result<Self> {
let hr = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) };
if hr.is_err() && hr != RPC_E_CHANGED_MODE {
return Err(anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperFirewallComInitFailed,
format!("CoInitializeEx failed: {hr:?}"),
)));
}
Ok(Self {
initialized: hr.is_ok(),
})
}
}
impl Drop for FirewallComApartment {
fn drop(&mut self) {
if self.initialized {
unsafe { CoUninitialize() };
}
}
}
pub fn ensure_offline_proxy_allowlist(
offline_sid: &str,
proxy_ports: &[u16],
allow_local_binding: bool,
log: &mut dyn Write,
) -> Result<()> {
let local_user_spec = format!("O:LSD:(A;;CC;;;{offline_sid})");
let _apartment = FirewallComApartment::initialize()?;
unsafe {
(|| -> Result<()> {
let policy: INetFwPolicy2 = CoCreateInstance(&NetFwPolicy2, None, CLSCTX_INPROC_SERVER)
.map_err(|err| {
anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperFirewallPolicyAccessFailed,
format!("CoCreateInstance NetFwPolicy2 failed: {err:?}"),
))
})?;
ensure_local_policy_rules_take_effect(&policy)?;
let rules = policy.Rules().map_err(|err| {
anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperFirewallPolicyAccessFailed,
format!("INetFwPolicy2::Rules failed: {err:?}"),
))
})?;
if allow_local_binding {
// Remove the legacy overlapping allow rule before returning to the local-binding
// mode so stale proxy exceptions do not linger.
remove_rule_if_present(&rules, OFFLINE_PROXY_ALLOW_RULE_NAME, log)?;
remove_rule_if_present(&rules, OFFLINE_BLOCK_LOOPBACK_UDP_RULE_NAME, log)?;
remove_rule_if_present(&rules, OFFLINE_BLOCK_LOOPBACK_TCP_RULE_NAME, log)?;
return Ok(());
}
ensure_block_rule(
&rules,
&BlockRuleSpec {
internal_name: OFFLINE_BLOCK_LOOPBACK_UDP_RULE_NAME,
friendly_desc: OFFLINE_BLOCK_LOOPBACK_UDP_RULE_FRIENDLY,
direction: NET_FW_RULE_DIR_OUT,
protocol: NET_FW_IP_PROTOCOL_UDP.0,
local_user_spec: &local_user_spec,
offline_sid,
remote_addresses: Some(LOOPBACK_REMOTE_ADDRESSES),
remote_ports: None,
},
log,
)?;
// Install a broad TCP loopback block before narrowing it to the allowed proxy port
// complement. If the narrowing update fails, the sandbox remains fail-closed.
ensure_block_rule(
&rules,
&BlockRuleSpec {
internal_name: OFFLINE_BLOCK_LOOPBACK_TCP_RULE_NAME,
friendly_desc: OFFLINE_BLOCK_LOOPBACK_TCP_RULE_FRIENDLY,
direction: NET_FW_RULE_DIR_OUT,
protocol: NET_FW_IP_PROTOCOL_TCP.0,
local_user_spec: &local_user_spec,
offline_sid,
remote_addresses: Some(LOOPBACK_REMOTE_ADDRESSES),
remote_ports: None,
},
log,
)?;
// Remove the legacy overlapping allow rule only after the explicit block rules are in
// place so transitions back to proxy-only mode do not fail open.
remove_rule_if_present(&rules, OFFLINE_PROXY_ALLOW_RULE_NAME, log)?;
if let Some(blocked_remote_ports) = blocked_loopback_tcp_remote_ports(proxy_ports) {
ensure_block_rule(
&rules,
&BlockRuleSpec {
internal_name: OFFLINE_BLOCK_LOOPBACK_TCP_RULE_NAME,
friendly_desc: OFFLINE_BLOCK_LOOPBACK_TCP_RULE_FRIENDLY,
direction: NET_FW_RULE_DIR_OUT,
protocol: NET_FW_IP_PROTOCOL_TCP.0,
local_user_spec: &local_user_spec,
offline_sid,
remote_addresses: Some(LOOPBACK_REMOTE_ADDRESSES),
remote_ports: Some(&blocked_remote_ports),
},
log,
)?;
}
Ok(())
})()
}
}
pub fn ensure_offline_network_blocks(offline_sid: &str, log: &mut dyn Write) -> Result<()> {
let local_user_spec = format!("O:LSD:(A;;CC;;;{offline_sid})");
let _apartment = FirewallComApartment::initialize()?;
unsafe {
(|| -> Result<()> {
let policy: INetFwPolicy2 = CoCreateInstance(&NetFwPolicy2, None, CLSCTX_INPROC_SERVER)
.map_err(|err| {
anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperFirewallPolicyAccessFailed,
format!("CoCreateInstance NetFwPolicy2 failed: {err:?}"),
))
})?;
ensure_local_policy_rules_take_effect(&policy)?;
let rules = policy.Rules().map_err(|err| {
anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperFirewallPolicyAccessFailed,
format!("INetFwPolicy2::Rules failed: {err:?}"),
))
})?;
// Block all outbound IP protocols for this user.
ensure_block_rule(
&rules,
&BlockRuleSpec {
internal_name: OFFLINE_BLOCK_RULE_NAME,
friendly_desc: OFFLINE_BLOCK_RULE_FRIENDLY,
direction: NET_FW_RULE_DIR_OUT,
protocol: NET_FW_IP_PROTOCOL_ANY.0,
local_user_spec: &local_user_spec,
offline_sid,
remote_addresses: Some(NON_LOOPBACK_REMOTE_ADDRESSES),
remote_ports: None,
},
log,
)?;
ensure_block_rule(
&rules,
&BlockRuleSpec {
internal_name: OFFLINE_BLOCK_INBOUND_RULE_NAME,
friendly_desc: OFFLINE_BLOCK_INBOUND_RULE_FRIENDLY,
direction: NET_FW_RULE_DIR_IN,
protocol: NET_FW_IP_PROTOCOL_ANY.0,
local_user_spec: &local_user_spec,
offline_sid,
remote_addresses: Some(NON_LOOPBACK_REMOTE_ADDRESSES),
remote_ports: None,
},
log,
)?;
Ok(())
})()
}
}
fn remove_rule_if_present(
rules: &INetFwRules,
internal_name: &str,
log: &mut dyn Write,
) -> Result<()> {
let name = BSTR::from(internal_name);
if unsafe { rules.Item(&name) }.is_ok() {
unsafe { rules.Remove(&name) }.map_err(|err| {
anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperFirewallRuleCreateOrAddFailed,
format!("Rules::Remove failed for {internal_name}: {err:?}"),
))
})?;
log_line(log, &format!("firewall rule removed name={internal_name}"))?;
}
Ok(())
}
fn ensure_local_policy_rules_take_effect(policy: &INetFwPolicy2) -> Result<()> {
let mut modify_state = NET_FW_MODIFY_STATE::default();
let result = unsafe {
(Interface::vtable(policy).LocalPolicyModifyState)(
Interface::as_raw(policy),
&mut modify_state,
)
};
validate_local_policy_modify_result(result, modify_state)
}
fn validate_local_policy_modify_result(
result: windows::core::HRESULT,
modify_state: NET_FW_MODIFY_STATE,
) -> Result<()> {
if result.is_err() {
// The COM query itself failed, so Windows never gave us a policy answer.
return Err(anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperFirewallPolicyAccessFailed,
format!("INetFwPolicy2::LocalPolicyModifyState failed: {result:?}"),
)));
}
if result != S_OK {
// S_FALSE means the answer only holds for some active profiles, not all of them.
return Err(anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperFirewallPolicyIneffective,
format!(
"local firewall policy modifications do not apply to every current profile: LocalPolicyModifyState result={result:?}"
),
)));
}
if modify_state == NET_FW_MODIFY_STATE_OK {
return Ok(());
}
// Windows answered uniformly, and that answer says local rule edits are ineffective.
Err(anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperFirewallPolicyIneffective,
format!(
"local firewall policy modifications will not take effect: LocalPolicyModifyState={modify_state:?}"
),
)))
}
fn ensure_block_rule(
rules: &INetFwRules,
spec: &BlockRuleSpec<'_>,
log: &mut dyn Write,
) -> Result<()> {
let name = BSTR::from(spec.internal_name);
let rule: INetFwRule3 = match unsafe { rules.Item(&name) } {
Ok(existing) => existing.cast().map_err(|err| {
anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperFirewallRuleCreateOrAddFailed,
format!("cast existing firewall rule to INetFwRule3 failed: {err:?}"),
))
})?,
Err(_) => {
let new_rule: INetFwRule3 =
unsafe { CoCreateInstance(&NetFwRule, None, CLSCTX_INPROC_SERVER) }.map_err(
|err| {
anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperFirewallRuleCreateOrAddFailed,
format!("CoCreateInstance NetFwRule failed: {err:?}"),
))
},
)?;
unsafe { new_rule.SetName(&name) }.map_err(|err| {
anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperFirewallRuleCreateOrAddFailed,
format!("SetName failed: {err:?}"),
))
})?;
// Set all properties before adding the rule so we don't leave half-configured rules.
configure_rule(&new_rule, spec)?;
unsafe { rules.Add(&new_rule) }.map_err(|err| {
anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperFirewallRuleCreateOrAddFailed,
format!("Rules::Add failed: {err:?}"),
))
})?;
new_rule
}
};
// Always re-apply fields to keep the setup idempotent.
configure_rule(&rule, spec)?;
let remote_addresses_log = spec.remote_addresses.unwrap_or("*");
let remote_ports_log = spec.remote_ports.unwrap_or("*");
log_line(
log,
&format!(
"firewall rule configured name={} protocol={} RemoteAddresses={remote_addresses_log} RemotePorts={remote_ports_log} LocalUserAuthorizedList={}",
spec.internal_name, spec.protocol, spec.local_user_spec
),
)?;
Ok(())
}
fn configure_rule(rule: &INetFwRule3, spec: &BlockRuleSpec<'_>) -> Result<()> {
unsafe {
rule.SetDescription(&BSTR::from(spec.friendly_desc))
.map_err(|err| {
anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperFirewallRuleCreateOrAddFailed,
format!("SetDescription failed: {err:?}"),
))
})?;
rule.SetDirection(spec.direction).map_err(|err| {
anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperFirewallRuleCreateOrAddFailed,
format!("SetDirection failed: {err:?}"),
))
})?;
rule.SetAction(NET_FW_ACTION_BLOCK).map_err(|err| {
anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperFirewallRuleCreateOrAddFailed,
format!("SetAction failed: {err:?}"),
))
})?;
rule.SetEnabled(VARIANT_TRUE).map_err(|err| {
anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperFirewallRuleCreateOrAddFailed,
format!("SetEnabled failed: {err:?}"),
))
})?;
rule.SetProfiles(NET_FW_PROFILE2_ALL.0).map_err(|err| {
anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperFirewallRuleCreateOrAddFailed,
format!("SetProfiles failed: {err:?}"),
))
})?;
configure_rule_network_scope(rule, spec)?;
rule.SetLocalUserAuthorizedList(&BSTR::from(spec.local_user_spec))
.map_err(|err| {
anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperFirewallRuleCreateOrAddFailed,
format!("SetLocalUserAuthorizedList failed: {err:?}"),
))
})?;
}
// Read-back verification: ensure we actually wrote the expected SID scope.
let actual = unsafe { rule.LocalUserAuthorizedList() }.map_err(|err| {
anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperFirewallRuleVerifyFailed,
format!("LocalUserAuthorizedList (read-back) failed: {err:?}"),
))
})?;
let actual_str = actual.to_string();
if !actual_str.contains(spec.offline_sid) {
return Err(anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperFirewallRuleVerifyFailed,
format!(
"offline firewall rule user scope mismatch: expected SID {}, got {actual_str}",
spec.offline_sid
),
)));
}
Ok(())
}
fn configure_rule_network_scope(rule: &INetFwRule3, spec: &BlockRuleSpec<'_>) -> Result<()> {
unsafe {
rule.SetProtocol(spec.protocol).map_err(|err| {
anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperFirewallRuleCreateOrAddFailed,
format!("SetProtocol failed: {err:?}"),
))
})?;
let remote_addresses = spec.remote_addresses.unwrap_or("*");
rule.SetRemoteAddresses(&BSTR::from(remote_addresses))
.map_err(|err| {
anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperFirewallRuleCreateOrAddFailed,
format!("SetRemoteAddresses failed: {err:?}"),
))
})?;
if let Some(remote_ports) = spec.remote_ports {
rule.SetRemotePorts(&BSTR::from(remote_ports))
.map_err(|err| {
anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperFirewallRuleCreateOrAddFailed,
format!("SetRemotePorts failed: {err:?}"),
))
})?;
}
}
Ok(())
}
fn blocked_loopback_tcp_remote_ports(proxy_ports: &[u16]) -> Option<String> {
let mut allowed_ports = proxy_ports
.iter()
.copied()
.filter(|port| *port != 0)
.collect::<Vec<_>>();
allowed_ports.sort_unstable();
allowed_ports.dedup();
let mut blocked_ranges = Vec::new();
let mut start = 1_u32;
for port in allowed_ports {
let port = u32::from(port);
if port < start {
continue;
}
if port > start {
blocked_ranges.push(port_range_string(start, port - 1));
}
start = port + 1;
}
if start <= u32::from(u16::MAX) {
blocked_ranges.push(port_range_string(start, u32::from(u16::MAX)));
}
if blocked_ranges.is_empty() {
None
} else {
Some(blocked_ranges.join(","))
}
}
fn port_range_string(start: u32, end: u32) -> String {
if start == end {
start.to_string()
} else {
format!("{start}-{end}")
}
}
fn log_line(log: &mut dyn Write, msg: &str) -> Result<()> {
let ts = chrono::Utc::now().to_rfc3339();
writeln!(log, "[{ts}] {msg}")?;
Ok(())
}
#[cfg(test)]
#[path = "firewall_apartment_tests.rs"]
mod apartment_tests;
#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
use windows::Win32::Foundation::S_FALSE;
use windows::Win32::NetworkManagement::WindowsFirewall::NET_FW_MODIFY_STATE_GP_OVERRIDE;
use super::*;
#[test]
fn configured_remote_address_literals_are_accepted_by_firewall_com() {
let hr = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) };
assert!(hr.is_ok(), "CoInitializeEx failed: {hr:?}");
let candidates = [
LOOPBACK_REMOTE_ADDRESSES,
NON_LOOPBACK_REMOTE_ADDRESSES,
"*",
];
let results = candidates.map(|remote_addresses| unsafe {
let rule: windows::core::Result<INetFwRule3> =
CoCreateInstance(&NetFwRule, None, CLSCTX_INPROC_SERVER);
rule.and_then(|rule| {
rule.SetRemoteAddresses(&BSTR::from(remote_addresses))?;
rule.RemoteAddresses()
})
.map(|stored| stored.to_string())
});
unsafe {
CoUninitialize();
}
for (remote_addresses, result) in candidates.into_iter().zip(results) {
assert!(
result.is_ok(),
"firewall rejected RemoteAddresses={remote_addresses:?}: {result:?}"
);
}
}
#[test]
fn production_firewall_rule_network_scopes_are_accepted_by_firewall_com() {
let hr = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) };
assert!(hr.is_ok(), "CoInitializeEx failed: {hr:?}");
let local_user_spec = "O:LSD:(A;;CC;;;S-1-5-18)";
let offline_sid = "S-1-5-18";
let blocked_remote_ports =
blocked_loopback_tcp_remote_ports(&[8080]).expect("proxy-port complement should exist");
let specs = [
BlockRuleSpec {
internal_name: OFFLINE_BLOCK_LOOPBACK_UDP_RULE_NAME,
friendly_desc: OFFLINE_BLOCK_LOOPBACK_UDP_RULE_FRIENDLY,
direction: NET_FW_RULE_DIR_OUT,
protocol: NET_FW_IP_PROTOCOL_UDP.0,
local_user_spec,
offline_sid,
remote_addresses: Some(LOOPBACK_REMOTE_ADDRESSES),
remote_ports: None,
},
BlockRuleSpec {
internal_name: OFFLINE_BLOCK_LOOPBACK_TCP_RULE_NAME,
friendly_desc: OFFLINE_BLOCK_LOOPBACK_TCP_RULE_FRIENDLY,
direction: NET_FW_RULE_DIR_OUT,
protocol: NET_FW_IP_PROTOCOL_TCP.0,
local_user_spec,
offline_sid,
remote_addresses: Some(LOOPBACK_REMOTE_ADDRESSES),
remote_ports: Some(&blocked_remote_ports),
},
BlockRuleSpec {
internal_name: OFFLINE_BLOCK_RULE_NAME,
friendly_desc: OFFLINE_BLOCK_RULE_FRIENDLY,
direction: NET_FW_RULE_DIR_OUT,
protocol: NET_FW_IP_PROTOCOL_ANY.0,
local_user_spec,
offline_sid,
remote_addresses: Some(NON_LOOPBACK_REMOTE_ADDRESSES),
remote_ports: None,
},
];
let results = specs.each_ref().map(|spec| unsafe {
let rule: windows::core::Result<INetFwRule3> =
CoCreateInstance(&NetFwRule, None, CLSCTX_INPROC_SERVER);
match rule {
Ok(rule) => configure_rule_network_scope(&rule, spec),
Err(err) => Err(err.into()),
}
});
unsafe {
CoUninitialize();
}
for (spec, result) in specs.into_iter().zip(results) {
assert!(
result.is_ok(),
"firewall rejected network scope for rule={} protocol={} remote_addresses={:?} remote_ports={:?}: {result:?}",
spec.internal_name,
spec.protocol,
spec.remote_addresses,
spec.remote_ports
);
}
}
#[test]
fn local_policy_modify_state_accepts_effective_policy() {
assert!(validate_local_policy_modify_result(S_OK, NET_FW_MODIFY_STATE_OK).is_ok());
}
#[test]
fn local_policy_modify_state_rejects_ineffective_policy() {
let err = validate_local_policy_modify_result(S_OK, NET_FW_MODIFY_STATE_GP_OVERRIDE)
.expect_err("group-policy override should fail sandbox firewall setup");
let failure = err
.downcast_ref::<SetupFailure>()
.expect("expected setup failure");
assert_eq!(
failure.code,
SetupErrorCode::HelperFirewallPolicyIneffective
);
}
#[test]
fn local_policy_modify_state_rejects_partial_profile_coverage() {
let err = validate_local_policy_modify_result(S_FALSE, NET_FW_MODIFY_STATE_OK)
.expect_err("partial profile coverage should fail sandbox firewall setup");
let failure = err
.downcast_ref::<SetupFailure>()
.expect("expected setup failure");
assert_eq!(
failure.code,
SetupErrorCode::HelperFirewallPolicyIneffective
);
}
}

View File

@@ -0,0 +1,40 @@
//! Verifies firewall COM access preserves a service thread's existing apartment.
use super::CLSCTX_INPROC_SERVER;
use super::CoCreateInstance;
use super::FirewallComApartment;
use super::INetFwPolicy2;
use super::NetFwPolicy2;
use pretty_assertions::assert_eq;
use windows::Win32::Foundation::RPC_E_CHANGED_MODE;
use windows::Win32::System::Com::COINIT_APARTMENTTHREADED;
use windows::Win32::System::Com::COINIT_MULTITHREADED;
use windows::Win32::System::Com::CoInitializeEx;
use windows::Win32::System::Com::CoUninitialize;
#[test]
fn firewall_access_preserves_the_services_existing_mta() {
std::thread::spawn(|| {
let initialized = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) };
assert!(initialized.is_ok(), "initialize MTA: {initialized:?}");
// Open the rules collection without adding, changing, or deleting a rule.
let result = (|| -> anyhow::Result<()> {
let _apartment = FirewallComApartment::initialize()?;
let policy: INetFwPolicy2 =
unsafe { CoCreateInstance(&NetFwPolicy2, None, CLSCTX_INPROC_SERVER)? };
let _rules = unsafe { policy.Rules()? };
Ok(())
})();
let apartment = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) };
unsafe { CoUninitialize() };
assert_eq!(
apartment, RPC_E_CHANGED_MODE,
"caller's MTA must remain initialized"
);
result.expect("read firewall rules from the existing MTA");
})
.join()
.expect("firewall COM test thread");
}

View File

@@ -0,0 +1,61 @@
use crate::to_wide;
use anyhow::Result;
use std::ffi::OsStr;
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::Foundation::ERROR_ALREADY_EXISTS;
use windows_sys::Win32::Foundation::ERROR_FILE_NOT_FOUND;
use windows_sys::Win32::Foundation::GetLastError;
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::System::Threading::CreateMutexW;
use windows_sys::Win32::System::Threading::MUTEX_ALL_ACCESS;
use windows_sys::Win32::System::Threading::OpenMutexW;
use windows_sys::Win32::System::Threading::ReleaseMutex;
const READ_ACL_MUTEX_NAME: &str = "Local\\CodexSandboxReadAcl";
pub(super) struct ReadAclMutexGuard {
handle: HANDLE,
}
impl Drop for ReadAclMutexGuard {
fn drop(&mut self) {
unsafe {
let _ = ReleaseMutex(self.handle);
CloseHandle(self.handle);
}
}
}
pub(super) fn read_acl_mutex_exists() -> Result<bool> {
let name = to_wide(OsStr::new(READ_ACL_MUTEX_NAME));
let handle = unsafe { OpenMutexW(MUTEX_ALL_ACCESS, 0, name.as_ptr()) };
if handle.is_null() {
let err = unsafe { GetLastError() };
if err == ERROR_FILE_NOT_FOUND {
return Ok(false);
}
return Err(anyhow::anyhow!("OpenMutexW failed: {err}"));
}
unsafe {
CloseHandle(handle);
}
Ok(true)
}
pub(super) fn acquire_read_acl_mutex() -> Result<Option<ReadAclMutexGuard>> {
let name = to_wide(OsStr::new(READ_ACL_MUTEX_NAME));
let handle = unsafe { CreateMutexW(std::ptr::null_mut(), 1, name.as_ptr()) };
if handle.is_null() {
return Err(anyhow::anyhow!("CreateMutexW failed: {}", unsafe {
GetLastError()
}));
}
let err = unsafe { GetLastError() };
if err == ERROR_ALREADY_EXISTS {
unsafe {
CloseHandle(handle);
}
return Ok(None);
}
Ok(Some(ReadAclMutexGuard { handle }))
}

View File

@@ -0,0 +1,91 @@
//! Registration-specific setup serialization and legacy-materialization boundaries.
use super::Payload;
use super::tests::payload_json;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::fs;
#[test]
fn payload_runtime_wire_normalization_preserves_opt_in() {
let mut payload: Payload = serde_json::from_value(payload_json()).unwrap();
assert_eq!(payload.runtime, super::SetupRuntime::Legacy);
let legacy = serde_json::to_value(&payload).unwrap();
assert!(legacy.get("runtime").is_none());
let mut explicit = legacy.clone();
explicit["runtime"] = serde_json::json!("legacy");
let decoded: Payload = serde_json::from_value(explicit).unwrap();
assert_eq!(serde_json::to_value(decoded).unwrap(), legacy);
payload.runtime = super::SetupRuntime::Registered;
let mut registered = legacy.clone();
registered["runtime"] = serde_json::json!("registered");
assert_eq!(serde_json::to_value(&payload).unwrap(), registered);
let decoded: Payload = serde_json::from_value(registered.clone()).unwrap();
assert_eq!(serde_json::to_value(decoded).unwrap(), registered);
for invalid in [
serde_json::Value::Null,
serde_json::json!(true),
serde_json::json!("unverified"),
] {
let mut malformed = legacy.clone();
malformed["runtime"] = invalid;
assert!(serde_json::from_value::<Payload>(malformed).is_err());
}
}
#[test]
fn registered_payload_never_creates_or_locks_legacy_bin() {
let tmp = tempfile::tempdir().expect("tempdir");
let mut json = payload_json();
json["codex_home"] = json!(tmp.path());
json["runtime"] = json!("registered");
let payload: Payload = serde_json::from_value(json).expect("registered payload");
// An empty SID would fail any ACL operation; Registered must not attempt one.
super::lock_sandbox_bin_dir(&payload, &[]).expect("no legacy bin work");
let bin = super::sandbox_bin_dir(tmp.path());
assert!(!bin.exists());
fs::create_dir(&bin).expect("existing legacy bin");
let sentinel = bin.join("sentinel");
fs::write(&sentinel, b"unchanged").expect("existing content");
super::lock_sandbox_bin_dir(&payload, &[]).expect("leave existing bin alone");
assert_eq!(fs::read(sentinel).expect("read sentinel"), b"unchanged");
}
#[test]
fn unverified_payload_cannot_create_legacy_bin() {
let tmp = tempfile::tempdir().expect("tempdir");
let mut json = payload_json();
json["codex_home"] = json!(tmp.path());
json["runtime"] = json!("unverified");
assert!(serde_json::from_value::<Payload>(json).is_err());
assert!(!super::sandbox_bin_dir(tmp.path()).exists());
}
#[test]
fn helper_account_gate_covers_actual_provisioning_modes() {
for (mode, expected) in [
(super::SetupMode::Full, [true, false]),
(super::SetupMode::InteractiveProvision, [true, true]),
(super::SetupMode::ProvisionOnly, [true, true]),
(super::SetupMode::ReadAclsOnly, [false, false]),
] {
assert_eq!(
[false, true].map(|refresh_only| mode.provisions_accounts(refresh_only)),
expected
);
}
}
#[test]
fn parsed_provision_only_cannot_claim_the_private_service_entry() {
let mut json = payload_json();
json["mode"] = json!("provision-only");
json["runtime"] = json!("registered");
json["refresh_only"] = json!(true);
json["service_admitted"] = json!(true);
let payload: Payload = serde_json::from_value(json).expect("payload");
assert!(payload.mode.provisions_accounts(payload.refresh_only));
assert_ne!(payload.runtime, super::SetupRuntime::Legacy);
}

View File

@@ -0,0 +1,518 @@
use anyhow::Result;
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use rand::RngCore;
use rand::SeedableRng;
use rand::rngs::SmallRng;
use serde::Serialize;
use std::ffi::OsStr;
use std::ffi::c_void;
use std::fs::File;
use std::io::Write;
use std::os::windows::io::FromRawHandle;
use std::path::Path;
use std::path::PathBuf;
use windows_sys::Win32::Foundation::ERROR_INSUFFICIENT_BUFFER;
use windows_sys::Win32::Foundation::GENERIC_WRITE;
use windows_sys::Win32::Foundation::GetLastError;
use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
use windows_sys::Win32::Foundation::LocalFree;
use windows_sys::Win32::NetworkManagement::NetManagement::LOCALGROUP_MEMBERS_INFO_3;
use windows_sys::Win32::NetworkManagement::NetManagement::NERR_Success;
use windows_sys::Win32::NetworkManagement::NetManagement::NetLocalGroupAddMembers;
use windows_sys::Win32::NetworkManagement::NetManagement::NetUserAdd;
use windows_sys::Win32::NetworkManagement::NetManagement::NetUserSetInfo;
use windows_sys::Win32::NetworkManagement::NetManagement::UF_DONT_EXPIRE_PASSWD;
use windows_sys::Win32::NetworkManagement::NetManagement::UF_SCRIPT;
use windows_sys::Win32::NetworkManagement::NetManagement::USER_INFO_1;
use windows_sys::Win32::NetworkManagement::NetManagement::USER_INFO_1003;
use windows_sys::Win32::NetworkManagement::NetManagement::USER_PRIV_USER;
use windows_sys::Win32::Security::Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW;
use windows_sys::Win32::Security::Authorization::ConvertStringSidToSidW;
use windows_sys::Win32::Security::Authorization::SDDL_REVISION_1;
use windows_sys::Win32::Security::LookupAccountSidW;
use windows_sys::Win32::Security::PSECURITY_DESCRIPTOR;
use windows_sys::Win32::Security::SECURITY_ATTRIBUTES;
use windows_sys::Win32::Security::SID_NAME_USE;
use windows_sys::Win32::Storage::FileSystem::CREATE_NEW;
use windows_sys::Win32::Storage::FileSystem::CreateFileW;
use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_NORMAL;
use crate::SANDBOX_USERS_GROUP;
use crate::SETUP_VERSION;
use crate::SetupErrorCode;
use crate::SetupFailure;
use crate::dpapi_protect;
use crate::ensure_sandbox_users_group;
use crate::resolve_sid;
use crate::sandbox_dir;
use crate::sandbox_secrets_dir;
use crate::string_from_sid_bytes;
use crate::to_wide;
use crate::write_file_atomically;
use super::SetupMode;
#[cfg(test)]
#[path = "sandbox_users_tests.rs"]
mod tests;
const SID_USERS: &str = "S-1-5-32-545";
pub fn resolve_sandbox_users_group_sid() -> Result<Vec<u8>> {
resolve_sid(SANDBOX_USERS_GROUP)
}
pub(super) fn provision_sandbox_users(
codex_home: &Path,
offline_username: &str,
online_username: &str,
new_user_flags: u32,
log: &mut dyn Write,
mode: SetupMode,
) -> Result<()> {
if let Err(err) = ensure_sandbox_users_group() {
let message = format!("failed to create local group {SANDBOX_USERS_GROUP}: {err}");
super::log_line(log, &message)?;
return Err(anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperUsersGroupCreateFailed,
message,
)));
}
super::log_line(
log,
&format!("ensuring sandbox users offline={offline_username} online={online_username}"),
)?;
let offline_password = random_password();
let online_password = random_password();
ensure_sandbox_user(offline_username, &offline_password, new_user_flags, log)?;
ensure_sandbox_user(online_username, &online_password, new_user_flags, log)?;
write_secrets(
codex_home,
offline_username,
&offline_password,
online_username,
&online_password,
mode,
)?;
Ok(())
}
pub fn ensure_sandbox_user(
username: &str,
password: &str,
new_user_flags: u32,
log: &mut dyn Write,
) -> Result<()> {
ensure_local_user(username, password, new_user_flags, log)?;
ensure_local_group_member(SANDBOX_USERS_GROUP, username)?;
Ok(())
}
pub fn ensure_local_user(
name: &str,
password: &str,
new_user_flags: u32,
log: &mut dyn Write,
) -> Result<()> {
let name_w = to_wide(OsStr::new(name));
let pwd_w = to_wide(OsStr::new(password));
unsafe {
let info = USER_INFO_1 {
usri1_name: name_w.as_ptr() as *mut u16,
usri1_password: pwd_w.as_ptr() as *mut u16,
usri1_password_age: 0,
usri1_priv: USER_PRIV_USER,
usri1_home_dir: std::ptr::null_mut(),
usri1_comment: std::ptr::null_mut(),
usri1_flags: UF_SCRIPT | UF_DONT_EXPIRE_PASSWD | new_user_flags,
usri1_script_path: std::ptr::null_mut(),
};
let status = NetUserAdd(
std::ptr::null(),
1,
&info as *const _ as *mut u8,
std::ptr::null_mut(),
);
if status != NERR_Success {
// Reset only the password, preserving account flags owned by enterprise policy.
// A separate flag update could fail after the reset but before credentials are saved.
let pw_info = USER_INFO_1003 {
usri1003_password: pwd_w.as_ptr() as *mut u16,
};
let upd = NetUserSetInfo(
std::ptr::null(),
name_w.as_ptr(),
1003,
&pw_info as *const _ as *mut u8,
std::ptr::null_mut(),
);
if upd != NERR_Success {
super::log_line(log, &format!("NetUserSetInfo failed for {name} code {upd}"))?;
return Err(anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperUserCreateOrUpdateFailed,
format!("failed to create/update user {name}, code {status}/{upd}"),
)));
}
}
// Ensure the principal is a regular local user account.
if let Ok(group_name) = lookup_account_name_for_sid(SID_USERS) {
let group = to_wide(OsStr::new(&group_name));
let member = LOCALGROUP_MEMBERS_INFO_3 {
lgrmi3_domainandname: name_w.as_ptr() as *mut u16,
};
let _ = NetLocalGroupAddMembers(
std::ptr::null(),
group.as_ptr(),
3,
&member as *const _ as *mut u8,
1,
);
} else {
super::log_line(
log,
"LookupAccountSidW failed for Users SID; skipping Users group membership",
)?;
}
}
Ok(())
}
pub fn ensure_local_group_member(group_name: &str, member_name: &str) -> Result<()> {
// If the member is already in the group, NetLocalGroupAddMembers may
// return an error code. We don't care.
let group_w = to_wide(OsStr::new(group_name));
let member_w = to_wide(OsStr::new(member_name));
unsafe {
let member = LOCALGROUP_MEMBERS_INFO_3 {
lgrmi3_domainandname: member_w.as_ptr() as *mut u16,
};
let _ = NetLocalGroupAddMembers(
std::ptr::null(),
group_w.as_ptr(),
3,
&member as *const _ as *mut u8,
1,
);
}
Ok(())
}
fn lookup_account_name_for_sid(sid_str: &str) -> Result<String> {
let sid_w = to_wide(OsStr::new(sid_str));
let mut psid: *mut c_void = std::ptr::null_mut();
if unsafe { ConvertStringSidToSidW(sid_w.as_ptr(), &mut psid) } == 0 {
return Err(anyhow::anyhow!(
"ConvertStringSidToSidW failed for {sid_str}: {}",
unsafe { GetLastError() }
));
}
let mut name_len: u32 = 0;
let mut domain_len: u32 = 0;
let mut use_type: SID_NAME_USE = 0;
let ok = unsafe {
LookupAccountSidW(
std::ptr::null(),
psid,
std::ptr::null_mut(),
&mut name_len,
std::ptr::null_mut(),
&mut domain_len,
&mut use_type,
)
};
if ok == 0 {
let err = unsafe { GetLastError() };
if err != ERROR_INSUFFICIENT_BUFFER {
unsafe {
LocalFree(psid as _);
}
return Err(anyhow::anyhow!(
"LookupAccountSidW preflight failed for {sid_str}: {err}"
));
}
}
let mut name_buf: Vec<u16> = vec![0u16; name_len as usize];
let mut domain_buf: Vec<u16> = vec![0u16; domain_len as usize];
let ok = unsafe {
LookupAccountSidW(
std::ptr::null(),
psid,
name_buf.as_mut_ptr(),
&mut name_len,
domain_buf.as_mut_ptr(),
&mut domain_len,
&mut use_type,
)
};
unsafe {
LocalFree(psid as _);
}
if ok == 0 {
return Err(anyhow::anyhow!(
"LookupAccountSidW failed for {sid_str}: {}",
unsafe { GetLastError() }
));
}
let name = String::from_utf16_lossy(&name_buf);
Ok(name.trim_end_matches('\0').to_string())
}
pub fn sid_bytes_to_psid(sid: &[u8]) -> Result<*mut c_void> {
let sid_str = string_from_sid_bytes(sid).map_err(anyhow::Error::msg)?;
let sid_w = to_wide(OsStr::new(&sid_str));
let mut psid: *mut c_void = std::ptr::null_mut();
if unsafe { ConvertStringSidToSidW(sid_w.as_ptr(), &mut psid) } == 0 {
return Err(anyhow::anyhow!(
"ConvertStringSidToSidW failed: {}",
unsafe { GetLastError() }
));
}
Ok(psid)
}
fn random_password() -> String {
const CHARS: &[u8] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_=+";
let mut rng = SmallRng::from_entropy();
let mut buf = [0u8; 24];
rng.fill_bytes(&mut buf);
buf.iter()
.map(|b| {
let idx = (*b as usize) % CHARS.len();
CHARS[idx] as char
})
.collect()
}
#[derive(Serialize)]
struct SandboxUserRecord {
username: String,
password: String,
}
#[derive(Serialize)]
struct SandboxUsersFile {
version: u32,
offline: SandboxUserRecord,
online: SandboxUserRecord,
}
#[derive(Serialize)]
struct SetupMarker {
version: u32,
offline_username: String,
online_username: String,
created_at: String,
proxy_ports: Vec<u16>,
allow_local_binding: bool,
read_roots: Vec<PathBuf>,
write_roots: Vec<PathBuf>,
}
fn write_secrets(
codex_home: &Path,
offline_user: &str,
offline_pwd: &str,
online_user: &str,
online_pwd: &str,
mode: SetupMode,
) -> Result<()> {
let secrets_dir = sandbox_secrets_dir(codex_home);
std::fs::create_dir_all(&secrets_dir).map_err(|err| {
anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperUsersFileWriteFailed,
format!(
"failed to create secrets dir {}: {err}",
secrets_dir.display()
),
))
})?;
let offline_blob = dpapi_protect(offline_pwd.as_bytes()).map_err(|err| {
anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperDpapiProtectFailed,
format!("dpapi protect failed for offline user: {err}"),
))
})?;
let online_blob = dpapi_protect(online_pwd.as_bytes()).map_err(|err| {
anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperDpapiProtectFailed,
format!("dpapi protect failed for online user: {err}"),
))
})?;
let users = SandboxUsersFile {
version: SETUP_VERSION,
offline: SandboxUserRecord {
username: offline_user.to_string(),
password: BASE64.encode(offline_blob),
},
online: SandboxUserRecord {
username: online_user.to_string(),
password: BASE64.encode(online_blob),
},
};
let users_path = secrets_dir.join("sandbox_users.json");
let users_json = serde_json::to_vec_pretty(&users).map_err(|err| {
anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperUsersFileWriteFailed,
format!("serialize sandbox users failed: {err}"),
))
})?;
let write_result = match mode {
SetupMode::ProvisionOnly => write_file_atomically(&users_path, &users_json),
SetupMode::Full | SetupMode::InteractiveProvision | SetupMode::ReadAclsOnly => {
std::fs::write(&users_path, users_json).map_err(anyhow::Error::from)
}
};
write_result.map_err(|err| {
anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperUsersFileWriteFailed,
format!(
"write sandbox users file {} failed: {err}",
users_path.display()
),
))
})?;
Ok(())
}
/// Service provisioning retains the marker's exclusive handle; legacy setup reopens it at commit.
pub(super) enum PreparedSetupMarker {
Retained(File),
Reopen,
}
// Create the final marker with its protected ACL. The empty file intentionally fails readiness
// checks until setup succeeds. Only service provisioning pins it for the entire operation.
pub(super) fn prepare_setup_marker(
codex_home: &Path,
real_user: &str,
mode: SetupMode,
) -> Result<PreparedSetupMarker> {
let marker_path = sandbox_dir(codex_home).join("setup_marker.json");
match std::fs::remove_file(&marker_path) {
Ok(()) => {}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
Err(err) => {
return Err(anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperSetupMarkerWriteFailed,
format!(
"remove setup marker file {} failed: {err}",
marker_path.display()
),
)));
}
}
let real_user_sid = resolve_sid(real_user)
.and_then(|sid| string_from_sid_bytes(&sid).map_err(anyhow::Error::msg))
.map_err(|err| {
anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperSetupMarkerWriteFailed,
format!("resolve real user SID for setup marker failed: {err}"),
))
})?;
let sddl = to_wide(format!(
"D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;{real_user_sid})"
));
let mut security_descriptor: PSECURITY_DESCRIPTOR = std::ptr::null_mut();
let converted = unsafe {
ConvertStringSecurityDescriptorToSecurityDescriptorW(
sddl.as_ptr(),
SDDL_REVISION_1,
&mut security_descriptor,
std::ptr::null_mut(),
)
};
if converted == 0 {
return Err(anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperSetupMarkerWriteFailed,
format!(
"create setup marker security descriptor failed: {}",
unsafe { GetLastError() }
),
)));
}
let security_attributes = SECURITY_ATTRIBUTES {
nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
lpSecurityDescriptor: security_descriptor,
bInheritHandle: 0,
};
let marker_path_wide = to_wide(marker_path.as_os_str());
let marker_handle = unsafe {
CreateFileW(
marker_path_wide.as_ptr(),
GENERIC_WRITE,
/*dwsharemode*/ 0,
&security_attributes,
CREATE_NEW,
FILE_ATTRIBUTE_NORMAL,
std::ptr::null_mut(),
)
};
let create_error = unsafe { GetLastError() };
unsafe {
LocalFree(security_descriptor as _);
}
if marker_handle == INVALID_HANDLE_VALUE {
return Err(anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperSetupMarkerWriteFailed,
format!(
"create protected setup marker file {} failed: {}",
marker_path.display(),
create_error
),
)));
}
let file = unsafe { File::from_raw_handle(marker_handle) };
match mode {
SetupMode::ProvisionOnly => Ok(PreparedSetupMarker::Retained(file)),
SetupMode::Full | SetupMode::InteractiveProvision | SetupMode::ReadAclsOnly => {
drop(file);
Ok(PreparedSetupMarker::Reopen)
}
}
}
pub(super) fn commit_setup_marker(
file: PreparedSetupMarker,
codex_home: &Path,
offline_user: &str,
online_user: &str,
proxy_ports: &[u16],
allow_local_binding: bool,
) -> Result<()> {
let marker = SetupMarker {
version: SETUP_VERSION,
offline_username: offline_user.to_string(),
online_username: online_user.to_string(),
created_at: chrono::Utc::now().to_rfc3339(),
proxy_ports: proxy_ports.to_vec(),
allow_local_binding,
read_roots: Vec::new(),
write_roots: Vec::new(),
};
let marker_path = sandbox_dir(codex_home).join("setup_marker.json");
let marker_json = serde_json::to_vec_pretty(&marker).map_err(|err| {
anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperSetupMarkerWriteFailed,
format!("serialize setup marker failed: {err}"),
))
})?;
let write_result = match file {
PreparedSetupMarker::Retained(mut file) => file.write_all(&marker_json),
PreparedSetupMarker::Reopen => std::fs::write(&marker_path, marker_json),
};
write_result.map_err(|err| {
anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperSetupMarkerWriteFailed,
format!(
"write setup marker file {} failed: {err}",
marker_path.display()
),
))
})?;
Ok(())
}

View File

@@ -0,0 +1,82 @@
//! Native account repair regression; uses a disposable account and requires elevation.
use super::ensure_local_user;
use crate::local_user_flags;
use crate::set_local_user_flags;
use crate::to_wide;
use anyhow::Result;
use pretty_assertions::assert_eq;
use windows_sys::Win32::NetworkManagement::NetManagement::NetApiBufferFree;
use windows_sys::Win32::NetworkManagement::NetManagement::NetUserDel;
use windows_sys::Win32::NetworkManagement::NetManagement::NetUserGetInfo;
use windows_sys::Win32::NetworkManagement::NetManagement::NetUserSetInfo;
use windows_sys::Win32::NetworkManagement::NetManagement::UF_ACCOUNTDISABLE;
use windows_sys::Win32::NetworkManagement::NetManagement::UF_DONT_EXPIRE_PASSWD;
use windows_sys::Win32::NetworkManagement::NetManagement::UF_PASSWORD_EXPIRED;
use windows_sys::Win32::NetworkManagement::NetManagement::USER_INFO_4;
struct TestAccount(String);
impl Drop for TestAccount {
fn drop(&mut self) {
unsafe { NetUserDel(std::ptr::null(), to_wide(&self.0).as_ptr()) };
}
}
#[test]
#[ignore = "requires administrator rights to create and remove a disposable local account"]
fn repairs_existing_account_password_without_changing_account_policy() -> Result<()> {
let name = format!("CdxExpiry{}", std::process::id());
anyhow::ensure!(
local_user_flags(&name)?.is_none(),
"test account already exists"
);
// Setup can create the account before returning an error.
let account = TestAccount(name.clone());
let mut log = Vec::new();
ensure_local_user(&name, "Old-Test-Password-93!", UF_ACCOUNTDISABLE, &mut log)?;
let initial_flags = local_user_flags(&account.0)?.unwrap();
set_local_user_flags(&account.0, initial_flags & !UF_DONT_EXPIRE_PASSWD)?;
// A level-1008 flags write does not set the dedicated must-change field.
// https://learn.microsoft.com/windows/win32/api/lmaccess/ns-lmaccess-user_info_4
let mut buffer = std::ptr::null_mut();
let status = unsafe {
NetUserGetInfo(
std::ptr::null(),
to_wide(&account.0).as_ptr(),
/*level*/ 4,
&mut buffer,
)
};
anyhow::ensure!(status == 0, "read USER_INFO_4 failed: {status}");
let status = unsafe {
(*buffer.cast::<USER_INFO_4>()).usri4_password_expired = 1;
let status = NetUserSetInfo(
std::ptr::null(),
to_wide(&account.0).as_ptr(),
/*level*/ 4,
buffer,
std::ptr::null_mut(),
);
NetApiBufferFree(buffer.cast());
status
};
anyhow::ensure!(status == 0, "expire test account password failed: {status}");
let expired_flags = local_user_flags(&account.0)?.unwrap();
assert_eq!(expired_flags & UF_PASSWORD_EXPIRED, UF_PASSWORD_EXPIRED);
ensure_local_user(
&account.0,
"New-Test-Password-94!",
/*new_user_flags*/ 0,
&mut log,
)?;
assert_eq!(
local_user_flags(&account.0)?.unwrap(),
expired_flags & !UF_PASSWORD_EXPIRED
);
drop(account);
assert_eq!(local_user_flags(&name)?, None);
Ok(())
}

View File

@@ -0,0 +1,49 @@
//! Adapts authenticated service provisioning to the existing setup transaction.
//! The caller owns admission, directory pins, and the setup mutex.
use super::Payload;
use super::SetupMode;
use super::run_payload;
use crate::SETUP_VERSION;
use crate::SetupRuntime;
use crate::logging::log_note;
use crate::sandbox_dir;
use anyhow::Result;
use std::path::Path;
/// Runs the existing ProvisionOnly setup transaction without launching a helper process.
/// The caller authenticates the owner, retains directory protections, and holds the setup mutex
/// on this thread across registration. Firewall setup preserves the caller's COM apartment.
pub fn provision_sandbox_in_process(
codex_home: &Path,
real_user: &str,
settings: crate::WindowsSandboxProvisioningSettings,
runtime: SetupRuntime,
) -> Result<()> {
let payload = Payload {
version: SETUP_VERSION,
offline_username: crate::setup::OFFLINE_USERNAME.to_string(),
online_username: crate::setup::ONLINE_USERNAME.to_string(),
codex_home: codex_home.to_path_buf(),
command_cwd: codex_home.to_path_buf(),
read_roots: Vec::new(),
write_roots: Vec::new(),
deny_read_paths: Vec::new(),
deny_write_paths: Vec::new(),
proxy_ports: settings.proxy_ports,
allow_local_binding: settings.allow_local_binding,
real_user: real_user.to_string(),
user_profile: None,
mode: SetupMode::ProvisionOnly,
runtime,
refresh_only: false,
};
run_payload(&payload)?;
if let Err(err) = crate::setup_error::clear_setup_error_report(codex_home) {
log_note(
&format!("setup orchestrator: failed to clear setup_error.json after success: {err}"),
Some(&sandbox_dir(codex_home)),
);
}
Ok(())
}

View File

@@ -0,0 +1,211 @@
use std::ffi::c_void;
use std::io::Write;
use std::os::windows::fs::MetadataExt as _;
use std::path::Path;
use std::path::PathBuf;
use crate::acl::grant_read_execute_aces;
use crate::path_mask_allows;
use anyhow::Context;
use anyhow::Result;
use anyhow::ensure;
use windows_sys::Win32::Security::CONTAINER_INHERIT_ACE;
use windows_sys::Win32::Security::OBJECT_INHERIT_ACE;
use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT;
use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_EXECUTE;
use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_READ;
#[cfg(test)]
#[path = "setup_runtime_bin_tests.rs"]
mod tests;
#[cfg(test)]
#[path = "setup_runtime_long_paths_tests.rs"]
mod long_paths_tests;
pub(super) fn ensure_codex_app_runtime_paths_readable(
sandbox_group_psid: *mut c_void,
refresh_errors: &mut Vec<String>,
log: &mut dyn Write,
) -> Result<()> {
let read_execute_mask = FILE_GENERIC_READ | FILE_GENERIC_EXECUTE;
let local_app_data = local_app_data_root();
let runtime_paths = runtime_paths(
local_app_data.clone(),
std::env::var_os("USERPROFILE").map(PathBuf::from),
);
for runtime_path in runtime_paths {
if !std::fs::symlink_metadata(&runtime_path).is_ok_and(|metadata| {
metadata.is_dir() && (metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT) == 0
}) {
continue;
}
let has_access = match path_mask_allows(
&runtime_path,
&[sandbox_group_psid],
read_execute_mask,
/*require_all_bits*/ true,
) {
Ok(has_access) => has_access,
Err(err) => {
refresh_errors.push(format!(
"runtime read/execute mask check failed on {} for sandbox_group: {err}",
runtime_path.display()
));
super::log_line(
log,
&format!(
"runtime read/execute mask check failed on {} for sandbox_group: {err}; continuing",
runtime_path.display()
),
)?;
false
}
};
if has_access {
continue;
}
super::log_line(
log,
&format!(
"granting read/execute ACE to {} for sandbox users",
runtime_path.display()
),
)?;
let result = unsafe {
grant_read_execute_aces(
&runtime_path,
&[sandbox_group_psid],
OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE,
)
};
if let Err(err) = result {
refresh_errors.push(format!(
"grant read/execute ACE failed on {} for sandbox_group: {err}",
runtime_path.display()
));
super::log_line(
log,
&format!(
"grant read/execute ACE failed on {} for sandbox_group: {err}",
runtime_path.display()
),
)?;
}
}
if let Some(local_app_data) = local_app_data {
let runtime_root = local_app_data.join("OpenAI").join("Codex").join("runtimes");
if let Err(err) = ensure_runtime_tree_readable(&runtime_root, sandbox_group_psid) {
let message = format!("runtime read/execute validation failed: {err:#}");
super::log_line(log, &message)?;
refresh_errors.push(message);
}
}
Ok(())
}
fn ensure_runtime_tree_readable(
runtime_root: &Path,
sandbox_group_psid: *mut c_void,
) -> Result<()> {
for ancestor in runtime_root.ancestors() {
let metadata = match std::fs::symlink_metadata(ancestor) {
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(()),
result => result
.with_context(|| format!("inspect runtime ancestor {}", ancestor.display()))?,
};
if !metadata.is_dir() || metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
return Ok(());
}
}
let read_execute_mask = FILE_GENERIC_READ | FILE_GENERIC_EXECUTE;
let mut paths = vec![runtime_root.to_path_buf()];
while let Some(path) = paths.pop() {
let metadata = match std::fs::symlink_metadata(&path) {
Err(err) if err.kind() == std::io::ErrorKind::NotFound => continue,
result => result.with_context(|| format!("inspect runtime path {}", path.display()))?,
};
if metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
continue;
}
// A readable parent does not prove that existing runtime children inherited its ACL.
let access_result = unsafe {
grant_read_execute_aces(
&path,
&[sandbox_group_psid],
if metadata.is_dir() {
OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE
} else {
0
},
)
}
.and_then(|changed| {
if changed {
ensure!(
path_mask_allows(
&path,
&[sandbox_group_psid],
read_execute_mask,
/*require_all_bits*/ true,
)?,
"runtime read/execute access still missing"
);
}
Ok(())
});
if let Err(err) = access_result {
if std::fs::symlink_metadata(&path)
.is_err_and(|err| err.kind() == std::io::ErrorKind::NotFound)
{
continue;
}
return Err(err).with_context(|| {
format!("validate runtime read/execute access on {}", path.display())
});
}
if metadata.is_dir() {
let entries = match std::fs::read_dir(&path) {
Err(err) if err.kind() == std::io::ErrorKind::NotFound => continue,
result => result
.with_context(|| format!("enumerate runtime directory {}", path.display()))?,
};
for entry in entries {
match entry {
Err(err) if err.kind() == std::io::ErrorKind::NotFound => continue,
result => paths.push(result?.path()),
}
}
}
}
Ok(())
}
fn runtime_paths(local_app_data: Option<PathBuf>, user_profile: Option<PathBuf>) -> Vec<PathBuf> {
let mut runtime_paths = Vec::new();
if let Some(local_app_data) = local_app_data {
let codex_root = local_app_data.join("OpenAI").join("Codex");
runtime_paths.push(codex_root);
}
// The managed primary runtime is installed outside the LocalAppData runtime roots.
if let Some(user_profile) = user_profile {
runtime_paths.push(user_profile.join(".cache").join("codex-runtimes"));
}
runtime_paths
}
fn local_app_data_root() -> Option<PathBuf> {
std::env::var_os("LOCALAPPDATA")
.map(PathBuf::from)
.or_else(|| {
std::env::var_os("USERPROFILE")
.map(PathBuf::from)
.map(|profile| profile.join("AppData").join("Local"))
})
}

View File

@@ -0,0 +1,249 @@
use super::ensure_runtime_tree_readable;
use super::runtime_paths;
use crate::LocalSid;
use crate::add_deny_read_ace;
use crate::add_deny_write_ace;
use crate::ensure_allow_mask_aces_with_inheritance;
use crate::path_mask_allows;
use pretty_assertions::assert_eq;
use std::fs;
use std::os::windows::fs::OpenOptionsExt;
use std::path::PathBuf;
use windows_sys::Win32::Foundation::HLOCAL;
use windows_sys::Win32::Foundation::LocalFree;
use windows_sys::Win32::Security::Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW;
use windows_sys::Win32::Security::Authorization::SDDL_REVISION_1;
use windows_sys::Win32::Security::CheckTokenMembership;
use windows_sys::Win32::Security::DACL_SECURITY_INFORMATION;
use windows_sys::Win32::Security::PROTECTED_DACL_SECURITY_INFORMATION;
use windows_sys::Win32::Security::SetFileSecurityW;
use windows_sys::Win32::Storage::FileSystem::DELETE;
use windows_sys::Win32::Storage::FileSystem::FILE_APPEND_DATA;
use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_EXECUTE;
use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_READ;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;
use windows_sys::Win32::Storage::FileSystem::FILE_WRITE_DATA;
use windows_sys::Win32::Storage::FileSystem::WRITE_DAC;
#[test]
fn runtime_repair_preserves_other_trustees_inherited_file_denial() {
for (denied_trustee, granted_sid) in [("WD", "S-1-5-11"), ("S-1-5-32-545", "S-1-1-0")] {
let ancestor = tempfile::tempdir().expect("runtime ancestor");
let granted_sid = LocalSid::from_string(granted_sid).expect("grant SID");
let mut member = 0;
assert_ne!(
unsafe {
CheckTokenMembership(std::ptr::null_mut(), granted_sid.as_ptr(), &mut member)
},
0,
);
assert_ne!(member, 0, "the real read must exercise the added grant");
unsafe {
let mut descriptor = std::ptr::null_mut();
assert_ne!(
ConvertStringSecurityDescriptorToSecurityDescriptorW(
crate::winutil::to_wide(format!(
"D:P(D;OIIO;0x1;;;{denied_trustee})(A;OICI;FA;;;OW)"
))
.as_ptr(),
SDDL_REVISION_1,
&mut descriptor,
std::ptr::null_mut(),
),
0,
);
let set = SetFileSecurityW(
crate::winutil::to_wide(ancestor.path()).as_ptr(),
DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
descriptor,
);
LocalFree(descriptor as HLOCAL);
assert_ne!(set, 0, "install an inheritable file-data denial");
}
let runtime = ancestor.path().join("runtimes");
fs::create_dir(&runtime).expect("runtime directory");
let module = runtime.join("private.js");
fs::write(&module, b"private runtime content").expect("runtime file");
for repair in [false, true] {
if repair {
ensure_runtime_tree_readable(&runtime, granted_sid.as_ptr())
.expect("repair must preserve inherited denies");
}
assert_eq!(
fs::read(&module)
.expect_err("file-data denial must remain effective")
.kind(),
std::io::ErrorKind::PermissionDenied,
);
}
}
}
#[test]
fn runtime_repair_does_not_follow_directory_junctions() {
let runtime = tempfile::tempdir().expect("runtime directory");
let external = tempfile::tempdir().expect("external directory");
let external_file = external.path().join("private.js");
fs::write(&external_file, b"external content").expect("external file");
let alias = runtime.path().join("linked-runtime");
let output = std::process::Command::new("cmd")
.args(["/C", "mklink", "/J"])
.arg(&alias)
.arg(external.path())
.output()
.expect("create directory junction");
assert!(output.status.success(), "mklink failed: {output:?}");
let sandbox_sid = LocalSid::from_string("S-1-5-21-10-20-30-40").expect("test SID");
for root in [runtime.path(), alias.as_path()] {
ensure_runtime_tree_readable(root, sandbox_sid.as_ptr()).expect("repair runtimes");
for path in [external.path(), external_file.as_path()] {
assert!(
!path_mask_allows(
path,
&[sandbox_sid.as_ptr()],
FILE_GENERIC_READ | FILE_GENERIC_EXECUTE,
/*require_all_bits*/ false,
)
.expect("external ACL must remain untouched")
);
}
}
fs::remove_dir(&alias).expect("remove junction");
}
#[test]
fn repairs_children_when_runtime_root_already_has_read_execute_access() {
let runtime = tempfile::tempdir().expect("runtime directory");
let node = runtime.path().join("bin/node.exe");
let module = runtime.path().join("sky/dist/project/index.js");
for path in [&node, &module] {
fs::create_dir_all(path.parent().expect("parent")).expect("runtime subdirectory");
fs::write(path, b"runtime content").expect("runtime file");
}
let sandbox_sid = LocalSid::from_string("S-1-5-21-10-20-30-40").expect("test SID");
let read_execute_mask = FILE_GENERIC_READ | FILE_GENERIC_EXECUTE;
unsafe {
ensure_allow_mask_aces_with_inheritance(
runtime.path(),
&[sandbox_sid.as_ptr()],
read_execute_mask,
/*inheritance*/ 0,
)
}
.expect("grant root-only read/execute access");
assert!(
path_mask_allows(
runtime.path(),
&[sandbox_sid.as_ptr()],
read_execute_mask,
/*require_all_bits*/ true,
)
.expect("root access")
);
for path in [&node, &module] {
assert!(
!path_mask_allows(
path,
&[sandbox_sid.as_ptr()],
read_execute_mask,
/*require_all_bits*/ true,
)
.expect("child access before repair")
);
}
let denied_directory = runtime.path().join("denied");
fs::create_dir(&denied_directory).expect("denied directory");
assert!(
unsafe { add_deny_read_ace(&denied_directory, sandbox_sid.as_ptr()) }
.expect("deny directory reads")
);
let denied_child = denied_directory.join("private.js");
fs::write(&denied_child, b"private runtime content").expect("denied child");
let write_denied_file = runtime.path().join("read-only.js");
fs::write(&write_denied_file, b"read-only runtime content").expect("write-denied file");
assert!(
unsafe { add_deny_write_ace(&write_denied_file, sandbox_sid.as_ptr()) }
.expect("deny runtime writes")
);
// Keep data-write and delete opens blocked throughout repair and revalidation.
let _reader = fs::OpenOptions::new()
.read(true)
.share_mode(FILE_SHARE_READ)
.open(&node)
.expect("hold runtime file open for reading");
for _ in 0..2 {
ensure_runtime_tree_readable(runtime.path(), sandbox_sid.as_ptr())
.expect("repair runtimes");
for path in [&denied_directory, &denied_child] {
assert!(
!unsafe { add_deny_read_ace(path, sandbox_sid.as_ptr()) }
.expect("read denial must survive repair")
);
assert!(
!path_mask_allows(
path,
&[sandbox_sid.as_ptr()],
read_execute_mask,
/*require_all_bits*/ false,
)
.expect("repair must not add an allow ahead of inherited denial")
);
}
assert!(
!unsafe { add_deny_write_ace(&write_denied_file, sandbox_sid.as_ptr()) }
.expect("write denial must survive repair")
);
for path in [
node.as_path(),
module.as_path(),
module.parent().expect("module directory"),
] {
assert!(
path_mask_allows(
path,
&[sandbox_sid.as_ptr()],
read_execute_mask,
/*require_all_bits*/ true,
)
.expect("child access after repair")
);
assert!(
!path_mask_allows(
path,
&[sandbox_sid.as_ptr()],
FILE_WRITE_DATA | FILE_APPEND_DATA | DELETE | WRITE_DAC,
/*require_all_bits*/ false,
)
.expect("repair must not grant write or ACL management")
);
}
}
}
#[test]
fn runtime_paths_include_desktop_parent_and_primary_runtime_roots() {
let local_app_data = PathBuf::from(r"C:\Users\user\AppData\Local");
let user_profile = PathBuf::from(r"C:\Users\user");
assert_eq!(
runtime_paths(Some(local_app_data), Some(user_profile)),
vec![
PathBuf::from(r"C:\Users\user\AppData\Local\OpenAI\Codex"),
PathBuf::from(r"C:\Users\user\.cache\codex-runtimes"),
]
);
}
#[test]
fn primary_runtime_path_does_not_depend_on_local_app_data() {
let user_profile = PathBuf::from(r"C:\Users\user");
assert_eq!(
runtime_paths(/*local_app_data*/ None, Some(user_profile)),
vec![PathBuf::from(r"C:\Users\user\.cache\codex-runtimes")]
);
}

View File

@@ -0,0 +1,80 @@
//! Exercises runtime ACL repair beyond the legacy Windows path limit while preserving read-only grants.
use super::ensure_runtime_tree_readable;
use crate::LocalSid;
use crate::acl::grant_read_execute_aces;
use crate::path_mask_allows;
use std::fs;
use std::os::windows::ffi::OsStrExt;
use windows_sys::Win32::Storage::FileSystem::DELETE;
use windows_sys::Win32::Storage::FileSystem::FILE_APPEND_DATA;
use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_EXECUTE;
use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_READ;
use windows_sys::Win32::Storage::FileSystem::FILE_WRITE_DATA;
use windows_sys::Win32::Storage::FileSystem::WRITE_DAC;
#[test]
fn runtime_repair_handles_long_directory_and_file_paths() {
let runtime = tempfile::tempdir().expect("runtime directory");
let mut directory = runtime.path().join("dependency-cache");
while directory.as_os_str().encode_wide().count() <= 280 {
directory.push("a".repeat(60));
}
fs::create_dir_all(&directory).expect("long runtime directory");
let module = directory.join("module.js");
fs::write(&module, b"runtime content").expect("long runtime file");
let short = runtime.path().join("short.js");
fs::write(&short, b"short-path control").expect("short runtime file");
let sandbox_sid = LocalSid::from_string("S-1-5-21-10-20-30-40").expect("test SID");
for path in [&directory, &module, &short] {
assert!(
!path_mask_allows(
path,
&[sandbox_sid.as_ptr()],
FILE_GENERIC_READ | FILE_GENERIC_EXECUTE,
/*require_all_bits*/ true,
)
.expect("read ACL before repair")
);
// Exercise the write even for the nested file: a parent grant during
// traversal could otherwise make its inherited ACL a read-only no-op.
assert!(
unsafe {
grant_read_execute_aces(path, &[sandbox_sid.as_ptr()], /*inheritance*/ 0)
}
.expect("grant read/execute on the existing path")
);
}
for _ in 0..2 {
ensure_runtime_tree_readable(runtime.path(), sandbox_sid.as_ptr())
.expect("repair the full runtime tree");
for path in [&directory, &module, &short] {
assert!(
path_mask_allows(
path,
&[sandbox_sid.as_ptr()],
FILE_GENERIC_READ | FILE_GENERIC_EXECUTE,
/*require_all_bits*/ true,
)
.expect("read repaired ACL")
);
assert!(
!path_mask_allows(
path,
&[sandbox_sid.as_ptr()],
FILE_WRITE_DATA | FILE_APPEND_DATA | DELETE | WRITE_DAC,
/*require_all_bits*/ false,
)
.expect("repair must not grant write or ACL management")
);
assert!(
!unsafe {
grant_read_execute_aces(path, &[sandbox_sid.as_ptr()], /*inheritance*/ 0)
}
.expect("an already-correct ACL is a no-op")
);
}
}
}

View File

@@ -0,0 +1,64 @@
//! Verifies refresh helpers stay console-free when launched by a detached daemon.
use std::fs;
use std::os::windows::process::CommandExt;
use std::path::PathBuf;
use std::process::Command;
use anyhow::Result;
use pretty_assertions::assert_eq;
use windows_sys::Win32::System::Console::GetConsoleWindow;
use windows_sys::Win32::System::Threading::DETACHED_PROCESS;
use super::run_setup_refresh_payload;
const DETACHED_TEST: &str = "setup::refresh_tests::refresh_helper_has_no_console";
const HELPER_TEST: &str = "setup::refresh_tests::refresh_console_probe";
const HOME_ENV: &str = "AKODE_TEST_REFRESH_CONSOLE_HOME";
#[test]
fn refresh_helper_has_no_console() -> Result<()> {
if let Some(home) = std::env::var_os(HOME_ENV).map(PathBuf::from) {
assert!(unsafe { GetConsoleWindow() }.is_null());
run_setup_refresh_payload(HELPER_TEST, &home)?;
assert_eq!(fs::read(home.join("probe"))?, b"no console");
return Ok(());
}
// Re-execute detached with a disposable fake setup helper beside it. This
// exercises the production refresh launch without provisioning sandbox users.
let temporary = tempfile::tempdir()?;
let executable = std::env::current_exe()?;
let detached = temporary.path().join("detached.exe");
akode_utils_cargo_bin::copy_executable(&executable, &detached)?;
akode_utils_cargo_bin::copy_executable(
&executable,
&temporary.path().join("akode-windows-sandbox-setup.exe"),
)?;
let output = Command::new(detached)
.args(["--exact", DETACHED_TEST, "--nocapture"])
.env(HOME_ENV, temporary.path())
.creation_flags(DETACHED_PROCESS)
.output()?;
assert!(
output.status.success(),
"detached refresh probe failed:\n{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
);
assert_eq!(fs::read(temporary.path().join("probe"))?, b"no console");
Ok(())
}
#[test]
fn refresh_console_probe() -> Result<()> {
// The setup launcher supplies this test name as its single payload argument.
// Ordinary test runs must not require their own parent to be console-free.
if std::env::args().nth(1).as_deref() != Some(HELPER_TEST) {
return Ok(());
}
let home = PathBuf::from(std::env::var_os(HOME_ENV).expect("detached probe home"));
assert!(unsafe { GetConsoleWindow() }.is_null());
fs::write(home.join("probe"), b"no console")?;
Ok(())
}

View File

@@ -0,0 +1,719 @@
use crate::acl::add_allow_ace;
use crate::acl::add_deny_write_ace;
use crate::acl::allow_null_device;
use crate::acl::ensure_allow_write_aces;
use crate::allow::AllowDenyPaths;
use crate::allow::compute_allow_paths_for_permissions;
use crate::cap::load_or_create_cap_sids;
use crate::cap::workspace_write_cap_sid_for_root;
use crate::cap::workspace_write_root_contains_path;
use crate::cap::workspace_write_root_overlaps_path;
use crate::cap::workspace_write_root_specificity;
use crate::deny_read_state::sync_persistent_deny_read_acls;
use crate::env::apply_no_network_to_env;
use crate::env::ensure_non_interactive_pager;
use crate::env::inherit_path_env;
use crate::env::normalize_null_device_env;
use crate::identity::SandboxCreds;
use crate::identity::require_logon_sandbox_creds;
use crate::logging::log_start;
use crate::path_normalization::canonicalize_path;
use crate::resolved_permissions::ResolvedWindowsSandboxPermissions;
use crate::sandbox_utils::ensure_codex_home_exists;
use crate::sandbox_utils::inject_git_safe_directory;
use crate::setup::effective_write_roots_for_permissions;
use crate::token::LocalSid;
use crate::token::create_readonly_token_with_cap;
use crate::token::create_workspace_write_token_with_caps_from;
use crate::token::get_current_token_for_restriction;
use crate::token::get_logon_sid_bytes;
use crate::workspace_acl::is_command_cwd_root;
use crate::workspace_acl::protect_workspace_agents_dir;
use crate::workspace_acl::protect_workspace_codex_dir;
use anyhow::Context;
use anyhow::Result;
use akode_protocol::models::PermissionProfile;
use akode_utils_absolute_path::AbsolutePathBuf;
use std::collections::HashMap;
use std::ffi::c_void;
use std::path::Path;
use std::path::PathBuf;
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::Foundation::HANDLE;
pub(crate) struct SpawnContext {
pub(crate) permissions: ResolvedWindowsSandboxPermissions,
pub(crate) current_dir: PathBuf,
pub(crate) logs_base_dir: Option<PathBuf>,
pub(crate) uses_write_capabilities: bool,
}
pub(crate) struct ElevatedSpawnContext {
pub(crate) sandbox_base: PathBuf,
pub(crate) logs_base_dir: Option<PathBuf>,
pub(crate) sandbox_creds: SandboxCreds,
pub(crate) cap_sids: Vec<String>,
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct SpawnPrepOptions {
pub(crate) inherit_path: bool,
pub(crate) add_git_safe_directory: bool,
}
pub(crate) struct LegacySessionSecurity {
pub(crate) h_token: HANDLE,
pub(crate) readonly_sid: Option<LocalSid>,
pub(crate) readonly_sid_str: Option<String>,
pub(crate) write_root_sids: Vec<RootCapabilitySid>,
}
pub(crate) struct RootCapabilitySid {
pub(crate) root: PathBuf,
pub(crate) sid: LocalSid,
pub(crate) sid_str: String,
}
pub(crate) struct LegacyAclSids<'a> {
pub(crate) readonly_sid: Option<&'a LocalSid>,
pub(crate) readonly_sid_str: Option<&'a str>,
pub(crate) write_root_sids: &'a [RootCapabilitySid],
}
pub(crate) fn prepare_spawn_context_common(
permission_profile: &PermissionProfile,
workspace_roots: &[AbsolutePathBuf],
codex_home: &Path,
cwd: &Path,
env_map: &mut HashMap<String, String>,
command: &[String],
options: SpawnPrepOptions,
) -> Result<SpawnContext> {
let permissions =
ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots(
permission_profile,
workspace_roots,
)?;
normalize_null_device_env(env_map);
ensure_non_interactive_pager(env_map);
if options.inherit_path {
inherit_path_env(env_map);
}
if options.add_git_safe_directory {
inject_git_safe_directory(env_map, cwd);
}
ensure_codex_home_exists(codex_home)?;
let sandbox_base = codex_home.join(".sandbox");
std::fs::create_dir_all(&sandbox_base)?;
let logs_base_dir = Some(sandbox_base);
log_start(command, logs_base_dir.as_deref());
let uses_write_capabilities = permissions.uses_write_capabilities_for_cwd(cwd, env_map);
Ok(SpawnContext {
permissions,
current_dir: cwd.to_path_buf(),
logs_base_dir,
uses_write_capabilities,
})
}
pub(crate) fn prepare_legacy_spawn_context(
permission_profile: &PermissionProfile,
workspace_roots: &[AbsolutePathBuf],
codex_home: &Path,
cwd: &Path,
env_map: &mut HashMap<String, String>,
command: &[String],
options: SpawnPrepOptions,
) -> Result<SpawnContext> {
let common = prepare_spawn_context_common(
permission_profile,
workspace_roots,
codex_home,
cwd,
env_map,
command,
options,
)?;
if common.permissions.should_apply_network_block() {
apply_no_network_to_env(env_map)?;
}
Ok(common)
}
pub(crate) fn prepare_legacy_session_security(
uses_write_capabilities: bool,
codex_home: &Path,
cwd: &Path,
capability_roots: impl IntoIterator<Item = PathBuf>,
) -> Result<LegacySessionSecurity> {
let caps = load_or_create_cap_sids(codex_home)?;
let (h_token, readonly_sid, readonly_sid_str, write_root_sids) = unsafe {
if uses_write_capabilities {
let write_root_sids = root_capability_sids(codex_home, cwd, capability_roots)?;
if write_root_sids.is_empty() {
anyhow::bail!("workspace-write sandbox has no writable root capability SIDs");
}
let base = get_current_token_for_restriction()?;
let cap_ptrs: Vec<*mut c_void> = write_root_sids
.iter()
.map(|root| root.sid.as_ptr())
.collect();
let h_token = create_workspace_write_token_with_caps_from(base, cap_ptrs.as_slice());
CloseHandle(base);
let h_token = h_token?;
(h_token, None, None, write_root_sids)
} else {
let psid = LocalSid::from_string(&caps.readonly)?;
let (h_token, _psid) = create_readonly_token_with_cap(psid.as_ptr())?;
(h_token, Some(psid), Some(caps.readonly), Vec::new())
}
};
Ok(LegacySessionSecurity {
h_token,
readonly_sid,
readonly_sid_str,
write_root_sids,
})
}
pub(crate) fn legacy_session_capability_roots(
permissions: &ResolvedWindowsSandboxPermissions,
current_dir: &Path,
env_map: &HashMap<String, String>,
codex_home: &Path,
) -> Vec<PathBuf> {
let allow_paths = compute_allow_paths_for_permissions(permissions, current_dir, env_map)
.allow
.into_iter()
.collect::<Vec<_>>();
if permissions.uses_write_capabilities_for_cwd(current_dir, env_map) {
effective_write_roots_for_permissions(
permissions,
current_dir,
env_map,
codex_home,
Some(allow_paths.as_slice()),
)
} else {
allow_paths
}
}
pub(crate) fn root_capability_sids(
codex_home: &Path,
cwd: &Path,
allow_paths: impl IntoIterator<Item = PathBuf>,
) -> Result<Vec<RootCapabilitySid>> {
let mut roots: Vec<PathBuf> = allow_paths.into_iter().collect();
roots.sort_by_key(|root| canonicalize_path(root.as_path()));
roots.dedup_by(|a, b| canonicalize_path(a.as_path()) == canonicalize_path(b.as_path()));
let mut out = Vec::with_capacity(roots.len());
for root in roots {
let sid_str = workspace_write_cap_sid_for_root(codex_home, cwd, &root)?;
let sid = LocalSid::from_string(&sid_str)?;
out.push(RootCapabilitySid { root, sid, sid_str });
}
Ok(out)
}
fn matching_root_capability<'a>(
path: &Path,
root_sids: &'a [RootCapabilitySid],
) -> Option<&'a RootCapabilitySid> {
root_sids
.iter()
.filter(|root_sid| workspace_write_root_contains_path(&root_sid.root, path))
.max_by_key(|root_sid| workspace_write_root_specificity(&root_sid.root))
}
fn deny_root_capabilities_for_path<'a>(
path: &Path,
root_sids: &'a [RootCapabilitySid],
) -> Vec<&'a RootCapabilitySid> {
let matching_root_sids = root_sids
.iter()
.filter(|root_sid| workspace_write_root_overlaps_path(&root_sid.root, path))
.collect::<Vec<_>>();
if matching_root_sids.is_empty() {
root_sids.iter().collect()
} else {
matching_root_sids
}
}
pub(crate) fn allow_null_device_for_workspace_write(is_workspace_write: bool) {
if !is_workspace_write {
return;
}
unsafe {
if let Ok(base) = get_current_token_for_restriction() {
if let Ok(bytes) = get_logon_sid_bytes(base) {
let mut tmp = bytes;
let psid = tmp.as_mut_ptr() as *mut c_void;
allow_null_device(psid);
}
CloseHandle(base);
}
}
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn apply_legacy_session_acl_rules(
permissions: &ResolvedWindowsSandboxPermissions,
codex_home: &Path,
current_dir: &Path,
env_map: &HashMap<String, String>,
additional_deny_read_paths: &[PathBuf],
additional_deny_write_paths: &[PathBuf],
acl_sids: LegacyAclSids<'_>,
) -> Result<()> {
let AllowDenyPaths { allow, mut deny } =
compute_allow_paths_for_permissions(permissions, current_dir, env_map);
unsafe {
for path in additional_deny_write_paths {
// Explicit carveouts must exist before the command starts so the
// sandbox cannot create them under a writable parent first.
if !path.exists() {
std::fs::create_dir_all(path)
.with_context(|| format!("create deny-write path {}", path.display()))?;
}
deny.insert(path.clone());
}
if let Some(readonly_sid) = acl_sids.readonly_sid {
for p in &allow {
let _ = add_allow_ace(p, readonly_sid.as_ptr());
}
} else {
for p in &allow {
let Some(root_sid) = matching_root_capability(p, acl_sids.write_root_sids) else {
continue;
};
let _ = ensure_allow_write_aces(p, &[root_sid.sid.as_ptr()]);
}
}
for p in &deny {
for root_sid in deny_root_capabilities_for_path(p, acl_sids.write_root_sids) {
let _ = add_deny_write_ace(p, root_sid.sid.as_ptr());
}
}
if !additional_deny_read_paths.is_empty() {
if let Some(readonly_sid) = acl_sids.readonly_sid {
let Some(readonly_sid_str) = acl_sids.readonly_sid_str else {
anyhow::bail!("readonly capability SID string missing");
};
sync_persistent_deny_read_acls(
codex_home,
readonly_sid_str,
additional_deny_read_paths,
readonly_sid.as_ptr(),
)?;
} else {
for root_sid in acl_sids.write_root_sids {
sync_persistent_deny_read_acls(
codex_home,
&root_sid.sid_str,
additional_deny_read_paths,
root_sid.sid.as_ptr(),
)?;
}
}
}
for root_sid in acl_sids.write_root_sids {
allow_null_device(root_sid.sid.as_ptr());
}
if let Some(readonly_sid) = acl_sids.readonly_sid {
allow_null_device(readonly_sid.as_ptr());
}
if !acl_sids.write_root_sids.is_empty()
&& let Some(workspace_sid) =
matching_root_capability(current_dir, acl_sids.write_root_sids)
{
let canonical_cwd = canonicalize_path(current_dir);
if is_command_cwd_root(&workspace_sid.root, &canonical_cwd) {
let _ = protect_workspace_codex_dir(current_dir, workspace_sid.sid.as_ptr());
let _ = protect_workspace_agents_dir(current_dir, workspace_sid.sid.as_ptr());
}
}
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn prepare_elevated_spawn_context_for_permissions(
permissions: ResolvedWindowsSandboxPermissions,
codex_home: &Path,
cwd: &Path,
env_map: &mut HashMap<String, String>,
command: &[String],
read_roots_override: Option<&[PathBuf]>,
read_roots_include_platform_defaults: bool,
write_roots_override: Option<&[PathBuf]>,
deny_read_paths_override: &[PathBuf],
deny_write_paths_override: &[PathBuf],
proxy_enforced: bool,
proxy_settings_mode: crate::WindowsSandboxProxySettingsMode,
) -> Result<ElevatedSpawnContext> {
normalize_null_device_env(env_map);
ensure_non_interactive_pager(env_map);
inherit_path_env(env_map);
inject_git_safe_directory(env_map, cwd);
// Use a temp-based log dir that the sandbox user can write.
let sandbox_base = codex_home.join(".sandbox");
ensure_codex_home_exists(&sandbox_base)?;
let logs_base_dir = Some(sandbox_base.clone());
log_start(command, logs_base_dir.as_deref());
let uses_write_capabilities = permissions.uses_write_capabilities_for_cwd(cwd, env_map);
let AllowDenyPaths { allow, deny } =
compute_allow_paths_for_permissions(&permissions, cwd, env_map);
let write_roots: Vec<PathBuf> = allow.into_iter().collect();
let deny_write_paths: Vec<PathBuf> = deny.into_iter().collect();
let computed_write_roots_override = if uses_write_capabilities {
Some(write_roots.as_slice())
} else {
None
};
let write_roots_for_setup = write_roots_override.or(computed_write_roots_override);
let effective_write_roots = if uses_write_capabilities {
effective_write_roots_for_permissions(
&permissions,
cwd,
env_map,
codex_home,
write_roots_for_setup,
)
} else {
Vec::new()
};
let setup_write_roots_override = if uses_write_capabilities {
Some(effective_write_roots.as_slice())
} else {
write_roots_override
};
let sandbox_creds = require_logon_sandbox_creds(
&permissions,
cwd,
env_map,
codex_home,
read_roots_override,
read_roots_include_platform_defaults,
setup_write_roots_override,
deny_read_paths_override,
if deny_write_paths_override.is_empty() {
&deny_write_paths
} else {
deny_write_paths_override
},
proxy_enforced,
proxy_settings_mode,
)?;
let caps = load_or_create_cap_sids(codex_home)?;
let (psid_to_use, cap_sids) = if uses_write_capabilities {
let cap_sids = root_capability_sids(codex_home, cwd, effective_write_roots)?
.into_iter()
.map(|root_sid| root_sid.sid_str)
.collect::<Vec<_>>();
if cap_sids.is_empty() {
anyhow::bail!("workspace-write sandbox has no writable root capability SIDs");
}
(LocalSid::from_string(&cap_sids[0])?, cap_sids)
} else {
(
LocalSid::from_string(&caps.readonly)?,
vec![caps.readonly.clone()],
)
};
unsafe {
allow_null_device(psid_to_use.as_ptr());
}
Ok(ElevatedSpawnContext {
sandbox_base,
logs_base_dir,
sandbox_creds,
cap_sids,
})
}
#[cfg(test)]
mod tests {
use super::SpawnPrepOptions;
use super::deny_root_capabilities_for_path;
use super::legacy_session_capability_roots;
use super::prepare_legacy_spawn_context;
use super::prepare_spawn_context_common;
use super::root_capability_sids;
use crate::cap::load_or_create_cap_sids;
use crate::cap::workspace_write_cap_sid_for_root;
use crate::resolved_permissions::ResolvedWindowsSandboxPermissions;
use akode_protocol::models::PermissionProfile;
use akode_protocol::permissions::NetworkSandboxPolicy;
use akode_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use std::collections::HashMap;
use std::path::Path;
use tempfile::TempDir;
fn workspace_profile(
network_policy: NetworkSandboxPolicy,
writable_roots: &[AbsolutePathBuf],
exclude_tmpdir_env_var: bool,
exclude_slash_tmp: bool,
) -> PermissionProfile {
PermissionProfile::workspace_write_with(
writable_roots,
network_policy,
exclude_tmpdir_env_var,
exclude_slash_tmp,
)
}
fn workspace_roots_for(root: &Path) -> Vec<AbsolutePathBuf> {
vec![AbsolutePathBuf::from_absolute_path(root).expect("absolute workspace root")]
}
fn should_apply_network_block(permission_profile: &PermissionProfile) -> bool {
ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots(
permission_profile,
&[],
)
.expect("managed permission profile")
.should_apply_network_block()
}
#[test]
fn no_network_env_rewrite_applies_for_workspace_write() {
assert!(should_apply_network_block(
&PermissionProfile::workspace_write()
));
}
#[test]
fn no_network_env_rewrite_skips_when_network_access_is_allowed() {
assert!(!should_apply_network_block(&workspace_profile(
NetworkSandboxPolicy::Enabled,
&[],
/*exclude_tmpdir_env_var*/ false,
/*exclude_slash_tmp*/ false,
)));
}
#[test]
fn legacy_spawn_env_applies_offline_network_rewrite() {
let codex_home = TempDir::new().expect("tempdir");
let cwd = TempDir::new().expect("tempdir");
let mut env_map = HashMap::new();
let workspace_roots = workspace_roots_for(cwd.path());
let _context = prepare_legacy_spawn_context(
&PermissionProfile::workspace_write(),
workspace_roots.as_slice(),
codex_home.path(),
cwd.path(),
&mut env_map,
&["cmd.exe".to_string()],
SpawnPrepOptions {
inherit_path: true,
add_git_safe_directory: false,
},
)
.expect("legacy env prep");
assert_eq!(env_map.get("SBX_NONET_ACTIVE"), Some(&"1".to_string()));
assert_eq!(
env_map.get("HTTP_PROXY"),
Some(&"http://127.0.0.1:9".to_string())
);
}
#[test]
fn common_spawn_env_keeps_network_env_unchanged() {
let codex_home = TempDir::new().expect("tempdir");
let cwd = TempDir::new().expect("tempdir");
let mut env_map = HashMap::from([(
"HTTP_PROXY".to_string(),
"http://user.proxy:8080".to_string(),
)]);
let workspace_roots = workspace_roots_for(cwd.path());
let context = prepare_spawn_context_common(
&PermissionProfile::workspace_write(),
workspace_roots.as_slice(),
codex_home.path(),
cwd.path(),
&mut env_map,
&["cmd.exe".to_string()],
SpawnPrepOptions {
inherit_path: true,
add_git_safe_directory: true,
},
)
.expect("preserve existing env prep");
assert!(context.uses_write_capabilities);
assert_eq!(env_map.get("SBX_NONET_ACTIVE"), None);
assert_eq!(
env_map.get("HTTP_PROXY"),
Some(&"http://user.proxy:8080".to_string())
);
}
#[test]
fn legacy_session_capability_roots_use_runtime_workspace_roots_for_workspace_root() {
let tmp = TempDir::new().expect("tempdir");
let codex_home = tmp.path().join("akode-home");
let workspace_root = tmp.path().join("workspace");
let command_cwd = workspace_root.join("subdir");
std::fs::create_dir_all(&codex_home).expect("create codex home");
std::fs::create_dir_all(&command_cwd).expect("create command cwd");
let permission_profile = workspace_profile(
NetworkSandboxPolicy::Restricted,
&[],
/*exclude_tmpdir_env_var*/ true,
/*exclude_slash_tmp*/ true,
);
let workspace_roots = workspace_roots_for(workspace_root.as_path());
let permissions =
ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots(
&permission_profile,
workspace_roots.as_slice(),
)
.expect("managed permission profile");
let roots = legacy_session_capability_roots(
&permissions,
&command_cwd,
&HashMap::new(),
&codex_home,
);
assert_eq!(
roots,
vec![dunce::canonicalize(&workspace_root).expect("canonical workspace root")]
);
}
#[test]
fn root_capability_sids_only_include_active_roots() {
let temp = TempDir::new().expect("tempdir");
let codex_home = temp.path().join("akode-home");
let workspace = temp.path().join("workspace");
let active_root = temp.path().join("active-root");
let stale_root = temp.path().join("stale-root");
std::fs::create_dir_all(&codex_home).expect("create codex home");
std::fs::create_dir_all(&workspace).expect("create workspace");
std::fs::create_dir_all(&active_root).expect("create active root");
std::fs::create_dir_all(&stale_root).expect("create stale root");
let stale_sid = workspace_write_cap_sid_for_root(&codex_home, &workspace, &stale_root)
.expect("stale sid");
let active_sid = workspace_write_cap_sid_for_root(&codex_home, &workspace, &active_root)
.expect("active sid");
let workspace_sid = workspace_write_cap_sid_for_root(&codex_home, &workspace, &workspace)
.expect("workspace sid");
let caps = load_or_create_cap_sids(&codex_home).expect("load caps");
let sid_strs = root_capability_sids(
&codex_home,
&workspace,
vec![workspace.clone(), active_root],
)
.expect("root capabilities")
.into_iter()
.map(|root_sid| root_sid.sid_str)
.collect::<Vec<_>>();
assert_eq!(sid_strs.len(), 2);
assert!(sid_strs.contains(&workspace_sid));
assert!(sid_strs.contains(&active_sid));
assert!(!sid_strs.contains(&stale_sid));
assert!(!sid_strs.contains(&caps.workspace));
}
#[test]
fn legacy_deny_path_includes_nested_active_root_sid() {
let temp = TempDir::new().expect("tempdir");
let codex_home = temp.path().join("akode-home");
let workspace = temp.path().join("workspace");
let protected_dir = workspace.join(".akode");
let nested_root = protected_dir.join("nested-root");
let unrelated_root = temp.path().join("unrelated-root");
std::fs::create_dir_all(&codex_home).expect("create codex home");
std::fs::create_dir_all(&workspace).expect("create workspace");
std::fs::create_dir_all(&nested_root).expect("create nested root");
std::fs::create_dir_all(&unrelated_root).expect("create unrelated root");
let workspace_sid = workspace_write_cap_sid_for_root(&codex_home, &workspace, &workspace)
.expect("workspace sid");
let nested_sid = workspace_write_cap_sid_for_root(&codex_home, &workspace, &nested_root)
.expect("nested sid");
let unrelated_sid =
workspace_write_cap_sid_for_root(&codex_home, &workspace, &unrelated_root)
.expect("unrelated sid");
let root_sids = root_capability_sids(
&codex_home,
&workspace,
vec![workspace.clone(), nested_root, unrelated_root],
)
.expect("root capabilities");
let deny_sid_strs = deny_root_capabilities_for_path(&protected_dir, &root_sids)
.into_iter()
.map(|root_sid| root_sid.sid_str.clone())
.collect::<Vec<_>>();
assert_eq!(deny_sid_strs, vec![workspace_sid, nested_sid]);
assert!(!deny_sid_strs.contains(&unrelated_sid));
}
#[test]
fn legacy_capability_roots_use_effective_write_roots() {
let temp = TempDir::new().expect("tempdir");
let codex_home = temp.path().join("akode-home");
let workspace = temp.path().join("workspace");
let active_root = temp.path().join("active-root");
let sandbox_root = codex_home.join(".sandbox");
std::fs::create_dir_all(&codex_home).expect("create codex home");
std::fs::create_dir_all(&workspace).expect("create workspace");
std::fs::create_dir_all(&active_root).expect("create active root");
std::fs::create_dir_all(&sandbox_root).expect("create sandbox root");
let writable_roots = vec![
AbsolutePathBuf::try_from(active_root.as_path()).expect("active root"),
AbsolutePathBuf::try_from(codex_home.as_path()).expect("codex home"),
AbsolutePathBuf::try_from(sandbox_root.as_path()).expect("sandbox root"),
];
let permission_profile = workspace_profile(
NetworkSandboxPolicy::Restricted,
&writable_roots,
/*exclude_tmpdir_env_var*/ true,
/*exclude_slash_tmp*/ true,
);
let workspace_roots = workspace_roots_for(workspace.as_path());
let permissions =
ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots(
&permission_profile,
workspace_roots.as_slice(),
)
.expect("managed permission profile");
let roots =
legacy_session_capability_roots(&permissions, &workspace, &HashMap::new(), &codex_home);
assert!(roots.contains(&dunce::canonicalize(&workspace).expect("workspace")));
assert!(roots.contains(&dunce::canonicalize(&active_root).expect("active root")));
assert!(!roots.contains(&dunce::canonicalize(&codex_home).expect("codex home")));
assert!(!roots.contains(&dunce::canonicalize(&sandbox_root).expect("sandbox root")));
}
}

View File

@@ -0,0 +1,249 @@
use std::collections::HashSet;
use std::path::Path;
use std::path::PathBuf;
const SSH_PROFILE_PATH_DIRECTIVES: &[&str] = &[
"certificatefile",
"controlpath",
"globalknownhostsfile",
"identityagent",
"identityfile",
"revokedhostkeys",
"userknownhostsfile",
];
pub(crate) fn ssh_config_dependency_paths(user_profile: &Path) -> Vec<PathBuf> {
let ssh_dir = user_profile.join(".ssh");
let mut paths = vec![ssh_dir.join("config")];
visit_config(
&ssh_dir.join("config"),
user_profile,
&ssh_dir,
&mut HashSet::new(),
&mut paths,
/*depth*/ 0,
);
paths
}
fn visit_config(
path: &Path,
user_profile: &Path,
ssh_dir: &Path,
visited: &mut HashSet<PathBuf>,
paths: &mut Vec<PathBuf>,
depth: usize,
) {
if depth == 32 {
return;
}
let key = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
if !visited.insert(key) {
return;
}
let Ok(contents) = std::fs::read_to_string(path) else {
return;
};
for (key, args) in contents.lines().filter_map(directive) {
match key.to_ascii_lowercase().as_str() {
"include" => {
for arg in args {
for include in include_paths(&arg, user_profile, ssh_dir) {
paths.push(include.clone());
visit_config(&include, user_profile, ssh_dir, visited, paths, depth + 1);
}
}
}
key if SSH_PROFILE_PATH_DIRECTIVES.contains(&key) => {
for arg in args {
if let Some(path) =
profile_path_arg(&arg, user_profile, /*relative_base*/ None)
{
paths.push(path);
}
}
}
_ => {}
}
}
}
fn include_paths(arg: &str, user_profile: &Path, ssh_dir: &Path) -> Vec<PathBuf> {
let Some(pattern_path) = profile_path_arg(arg, user_profile, Some(ssh_dir)) else {
return Vec::new();
};
let pattern = pattern_path.to_string_lossy().replace('\\', "/");
let Ok(paths) = glob::glob(&pattern) else {
return Vec::new();
};
paths.filter_map(Result::ok).collect()
}
fn directive(line: &str) -> Option<(String, Vec<String>)> {
let mut words = words(line);
let first = words.first()?.to_string();
if let Some((key, value)) = first.split_once('=')
&& !key.is_empty()
{
let mut args = Vec::new();
if !value.is_empty() {
args.push(value.to_string());
}
args.extend(words.drain(1..));
Some((key.to_string(), args))
} else {
let key = words.remove(0);
if let Some(arg) = words.first_mut()
&& let Some(value) = arg.strip_prefix('=')
{
*arg = value.to_string();
}
words.retain(|arg| !arg.is_empty());
Some((key, words))
}
}
fn words(line: &str) -> Vec<String> {
let mut out = Vec::new();
let mut word = String::new();
let mut quote = None;
let mut chars = line.chars().peekable();
while let Some(ch) = chars.next() {
match ch {
'#' if quote.is_none() => break,
'\'' | '"' if quote == Some(ch) => quote = None,
'\'' | '"' if quote.is_none() => quote = Some(ch),
'\\' => {
if let Some(&next) = chars.peek() {
if matches!(next, '\'' | '"' | '\\') || (quote.is_none() && next == ' ') {
if let Some(escaped) = chars.next() {
word.push(escaped);
}
} else {
word.push(ch);
}
} else {
word.push(ch);
}
}
ch if ch.is_whitespace() && quote.is_none() => {
if !word.is_empty() {
out.push(std::mem::take(&mut word));
}
}
ch => word.push(ch),
}
}
if !word.is_empty() {
out.push(word);
}
out
}
fn profile_path_arg(
arg: &str,
user_profile: &Path,
relative_base: Option<&Path>,
) -> Option<PathBuf> {
if arg.eq_ignore_ascii_case("none") {
return None;
}
if arg == "~" || arg == "%d" || arg == "${HOME}" {
return Some(user_profile.to_path_buf());
}
if let Some(rest) = arg
.strip_prefix("~/")
.or_else(|| arg.strip_prefix(r"~\"))
.or_else(|| arg.strip_prefix("%d/"))
.or_else(|| arg.strip_prefix(r"%d\"))
.or_else(|| arg.strip_prefix("${HOME}/"))
.or_else(|| arg.strip_prefix(r"${HOME}\"))
{
return Some(user_profile.join(rest));
}
let path = PathBuf::from(arg);
if path.is_absolute() {
Some(path)
} else {
relative_base.map(|base| base.join(path))
}
}
#[cfg(test)]
mod tests {
use super::ssh_config_dependency_paths;
use pretty_assertions::assert_eq;
use std::fs;
use std::path::PathBuf;
use tempfile::TempDir;
#[test]
fn collects_path_directive_profile_entries() {
let tmp = TempDir::new().expect("tempdir");
let home = tmp.path();
fs::create_dir_all(home.join(".ssh")).expect("create .ssh");
fs::write(
home.join(".ssh/config"),
r#"
Host devbox
IdentityFile ~/.keys/id_ed25519
IdentityFile '~/.keys/quoted key'
CertificateFile = %d/.certs/devbox-cert.pub
UserKnownHostsFile ${HOME}/.known_hosts_custom
GlobalKnownHostsFile ~/.global_known_hosts
ControlPath ~/.control/%h-%p-%r
IdentityAgent=%d/.agent/socket
RevokedHostKeys ~/.revoked/keys
"#,
)
.expect("write config");
assert_eq!(
vec![
home.join(".ssh/config"),
home.join(".keys/id_ed25519"),
home.join(".keys/quoted key"),
home.join(".certs/devbox-cert.pub"),
home.join(".known_hosts_custom"),
home.join(".global_known_hosts"),
home.join(".control/%h-%p-%r"),
home.join(".agent/socket"),
home.join(".revoked/keys"),
],
slash_paths(ssh_config_dependency_paths(home))
);
}
#[test]
fn recursively_collects_include_dependencies() {
let tmp = TempDir::new().expect("tempdir");
let home = tmp.path();
let ssh_dir = home.join(".ssh");
fs::create_dir_all(ssh_dir.join("conf.d")).expect("create conf.d");
fs::write(ssh_dir.join("config"), "Include conf.d/*.conf\n").expect("write config");
fs::write(
ssh_dir.join("conf.d/devbox.conf"),
"CertificateFile ~/.included/devbox-cert.pub\n",
)
.expect("write include");
assert_eq!(
vec![
home.join(".ssh/config"),
ssh_dir.join("conf.d/devbox.conf"),
home.join(".included/devbox-cert.pub"),
],
slash_paths(ssh_config_dependency_paths(home))
);
}
fn slash_paths(paths: Vec<PathBuf>) -> Vec<PathBuf> {
paths
.into_iter()
.map(|path| PathBuf::from(path.to_string_lossy().replace('\\', "/")))
.collect()
}
}

View File

@@ -0,0 +1,126 @@
use std::io::Read;
use std::io::Write;
use std::sync::Arc;
use std::time::Duration;
use akode_utils_pty::SpawnedProcess;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
/// Forwards this process' stdio to a Windows sandbox session and returns the
/// session exit code.
pub async fn forward_sandbox_session_stdio(spawned: SpawnedProcess) -> i32 {
let session = Arc::new(spawned.session);
let tokio_runtime = tokio::runtime::Handle::current();
// Give large or slow tail output a better chance to finish draining without
// letting rare EOF issues hang the wrapper indefinitely.
let output_drain_timeout = Duration::from_secs(5);
// A helper thread watches our stdin. When the input source closes it, the
// thread tells the main async code so we can also close stdin for the
// sandboxed child process.
let (stdin_eof_tx, stdin_eof_rx) = oneshot::channel();
// Start background threads that copy stdin/stdout/stderr. We intentionally
// do not keep their JoinHandles; dropping the handle does not stop the
// thread, it just means we are not going to wait on it later.
drop(spawn_input_forwarder(
std::io::stdin(),
session.writer_sender(),
stdin_eof_tx,
));
let (stdout_forwarder, stdout_forwarder_done_rx) =
spawn_output_forwarder(tokio_runtime.clone(), spawned.stdout_rx, std::io::stdout());
drop(stdout_forwarder);
let (stderr_forwarder, stderr_forwarder_done_rx) =
spawn_output_forwarder(tokio_runtime.clone(), spawned.stderr_rx, std::io::stderr());
drop(stderr_forwarder);
let stdin_close_task = tokio::spawn({
let session = Arc::clone(&session);
async move {
let _ = stdin_eof_rx.await;
session.close_stdin();
}
});
let mut exit_rx = spawned.exit_rx;
let exit_code = tokio::select! {
res = &mut exit_rx => res.unwrap_or(-1),
res = tokio::signal::ctrl_c() => {
if let Ok(()) = res {
session.request_terminate();
}
exit_rx.await.unwrap_or(-1)
}
};
stdin_close_task.abort();
let _ = tokio::time::timeout(output_drain_timeout, async {
let _ = stdout_forwarder_done_rx.await;
let _ = stderr_forwarder_done_rx.await;
})
.await;
exit_code
}
fn spawn_input_forwarder<R>(
mut input: R,
writer_tx: mpsc::Sender<Vec<u8>>,
stdin_eof_tx: oneshot::Sender<()>,
) -> std::thread::JoinHandle<()>
where
R: Read + Send + 'static,
{
const STDIN_FORWARD_CHUNK_SIZE: usize = 8 * 1024;
std::thread::spawn(move || {
let mut buffer = [0_u8; STDIN_FORWARD_CHUNK_SIZE];
loop {
match input.read(&mut buffer) {
Ok(0) => break,
Ok(n) => {
if writer_tx.blocking_send(buffer[..n].to_vec()).is_err() {
break;
}
}
Err(err) if err.kind() == std::io::ErrorKind::Interrupted => continue,
Err(err) => {
eprintln!("windows sandbox stdin forwarder failed: {err}");
break;
}
}
}
let _ = stdin_eof_tx.send(());
})
}
fn spawn_output_forwarder<W>(
tokio_runtime: tokio::runtime::Handle,
output_rx: mpsc::Receiver<Vec<u8>>,
mut writer: W,
) -> (std::thread::JoinHandle<()>, oneshot::Receiver<()>)
where
W: Write + Send + 'static,
{
let (done_tx, done_rx) = oneshot::channel();
// The sandbox session emits output on Tokio channels, but writing to the
// caller's stdio is simplest from a dedicated blocking thread.
let handle = std::thread::spawn(move || {
let mut output_rx = output_rx;
while let Some(chunk) = tokio_runtime.block_on(output_rx.recv()) {
if let Err(err) = writer.write_all(&chunk) {
eprintln!("windows sandbox output forwarder failed to write: {err}");
break;
}
if let Err(err) = writer.flush() {
eprintln!("windows sandbox output forwarder failed to flush: {err}");
break;
}
}
let _ = done_tx.send(());
});
(handle, done_rx)
}
#[cfg(test)]
#[path = "stdio_bridge_tests.rs"]
mod tests;

View File

@@ -0,0 +1,63 @@
use std::sync::Mutex;
use pretty_assertions::assert_eq;
use super::*;
#[tokio::test]
async fn input_forwarder_sends_chunks_and_reports_eof() -> anyhow::Result<()> {
let (writer_tx, mut writer_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(4);
let (stdin_closed_tx, stdin_closed_rx) = tokio::sync::oneshot::channel();
let input = std::io::Cursor::new(b"first\nsecond\n".to_vec());
let forwarder = spawn_input_forwarder(input, writer_tx, stdin_closed_tx);
let mut received = Vec::new();
while let Some(chunk) = writer_rx.recv().await {
received.extend_from_slice(&chunk);
}
stdin_closed_rx.await?;
forwarder.join().expect("stdin forwarder should finish");
assert_eq!(received, b"first\nsecond\n".to_vec());
Ok(())
}
#[tokio::test]
async fn output_forwarder_writes_all_chunks() -> anyhow::Result<()> {
#[derive(Clone, Default)]
struct SharedWriter(std::sync::Arc<Mutex<Vec<u8>>>);
impl std::io::Write for SharedWriter {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
let mut guard = self
.0
.lock()
.map_err(|_| std::io::Error::other("writer poisoned"))?;
guard.extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
let runtime = tokio::runtime::Handle::current();
let (output_tx, output_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(4);
let writer = SharedWriter::default();
let sink = std::sync::Arc::clone(&writer.0);
let (forwarder, done_rx) = spawn_output_forwarder(runtime, output_rx, writer);
output_tx.send(b"alpha".to_vec()).await?;
output_tx.send(b"beta".to_vec()).await?;
drop(output_tx);
forwarder.join().expect("output forwarder should finish");
done_rx.await?;
let output = sink
.lock()
.map_err(|_| anyhow::anyhow!("writer poisoned"))?
.clone();
assert_eq!(output, b"alphabeta".to_vec());
Ok(())
}

View File

@@ -0,0 +1,533 @@
use crate::winutil::to_wide;
use anyhow::Result;
use anyhow::anyhow;
use anyhow::ensure;
use std::ffi::c_void;
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::Foundation::ERROR_SUCCESS;
use windows_sys::Win32::Foundation::GetLastError;
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::Foundation::HLOCAL;
use windows_sys::Win32::Foundation::LUID;
use windows_sys::Win32::Foundation::LocalFree;
use windows_sys::Win32::Security::AdjustTokenPrivileges;
use windows_sys::Win32::Security::Authorization::EXPLICIT_ACCESS_W;
use windows_sys::Win32::Security::Authorization::GRANT_ACCESS;
use windows_sys::Win32::Security::Authorization::SetEntriesInAclW;
use windows_sys::Win32::Security::Authorization::TRUSTEE_IS_SID;
use windows_sys::Win32::Security::Authorization::TRUSTEE_IS_UNKNOWN;
use windows_sys::Win32::Security::Authorization::TRUSTEE_W;
use windows_sys::Win32::Security::CopySid;
use windows_sys::Win32::Security::CreateRestrictedToken;
use windows_sys::Win32::Security::CreateWellKnownSid;
use windows_sys::Win32::Security::GetTokenInformation;
use windows_sys::Win32::Security::IsValidSid;
use windows_sys::Win32::Security::LookupPrivilegeValueW;
use windows_sys::Win32::Security::SetTokenInformation;
use windows_sys::Win32::Security::ACL;
use windows_sys::Win32::Security::SID_AND_ATTRIBUTES;
use windows_sys::Win32::Security::TOKEN_ADJUST_DEFAULT;
use windows_sys::Win32::Security::TOKEN_ADJUST_PRIVILEGES;
use windows_sys::Win32::Security::TOKEN_ADJUST_SESSIONID;
use windows_sys::Win32::Security::TOKEN_ASSIGN_PRIMARY;
use windows_sys::Win32::Security::TOKEN_DUPLICATE;
use windows_sys::Win32::Security::TOKEN_GROUPS;
use windows_sys::Win32::Security::TOKEN_PRIVILEGES;
use windows_sys::Win32::Security::TOKEN_QUERY;
use windows_sys::Win32::Security::TokenDefaultDacl;
use windows_sys::Win32::Security::TokenGroups;
use windows_sys::Win32::System::Threading::GetCurrentProcess;
const DISABLE_MAX_PRIVILEGE: u32 = 0x01;
const LUA_TOKEN: u32 = 0x04;
const WRITE_RESTRICTED: u32 = 0x08;
const GENERIC_ALL: u32 = 0x1000_0000;
const WIN_WORLD_SID: i32 = 1;
const SE_GROUP_LOGON_ID: u32 = 0xC0000000;
#[repr(C)]
struct TokenDefaultDaclInfo {
default_dacl: *mut ACL,
}
/// Keep child-process and IPC access within the runner's logon session.
/// Elevated runners have distinct logon SIDs even when they use the same account.
unsafe fn set_default_dacl(h_token: HANDLE, logon_sid: *mut c_void) -> Result<()> {
let owner_rights = LocalSid::from_string("S-1-3-4")?;
// The shared account also owns these objects. An OWNER RIGHTS ACE suppresses
// its implicit WRITE_DAC grant, which would otherwise let a different logon
// rewrite this DACL. The creating logon retains full access explicitly.
let entries = [
(logon_sid, GENERIC_ALL),
(
owner_rights.as_ptr(),
windows_sys::Win32::Storage::FileSystem::READ_CONTROL,
),
]
.map(|(sid, access)| EXPLICIT_ACCESS_W {
grfAccessPermissions: access,
grfAccessMode: GRANT_ACCESS,
grfInheritance: 0,
Trustee: TRUSTEE_W {
pMultipleTrustee: std::ptr::null_mut(),
MultipleTrusteeOperation: 0,
TrusteeForm: TRUSTEE_IS_SID,
TrusteeType: TRUSTEE_IS_UNKNOWN,
ptstrName: sid as *mut u16,
},
});
let mut p_new_dacl: *mut ACL = std::ptr::null_mut();
let res = SetEntriesInAclW(
entries.len() as u32,
entries.as_ptr(),
std::ptr::null_mut(),
&mut p_new_dacl,
);
if res != ERROR_SUCCESS {
return Err(anyhow!("SetEntriesInAclW failed: {res}"));
}
let mut info = TokenDefaultDaclInfo {
default_dacl: p_new_dacl,
};
let ok = SetTokenInformation(
h_token,
TokenDefaultDacl,
&mut info as *mut _ as *mut c_void,
std::mem::size_of::<TokenDefaultDaclInfo>() as u32,
);
if ok == 0 {
let err = GetLastError();
if !p_new_dacl.is_null() {
LocalFree(p_new_dacl as HLOCAL);
}
return Err(anyhow!(
"SetTokenInformation(TokenDefaultDacl) failed: {err}",
));
}
if !p_new_dacl.is_null() {
LocalFree(p_new_dacl as HLOCAL);
}
Ok(())
}
pub unsafe fn world_sid() -> Result<Vec<u8>> {
let mut size: u32 = 0;
CreateWellKnownSid(
WIN_WORLD_SID,
std::ptr::null_mut(),
std::ptr::null_mut(),
&mut size,
);
let mut buf: Vec<u8> = vec![0u8; size as usize];
let ok = CreateWellKnownSid(
WIN_WORLD_SID,
std::ptr::null_mut(),
buf.as_mut_ptr() as *mut c_void,
&mut size,
);
if ok == 0 {
return Err(anyhow!("CreateWellKnownSid failed: {}", GetLastError()));
}
Ok(buf)
}
/// # Safety
/// Caller is responsible for freeing the returned SID with `LocalFree`.
pub unsafe fn convert_string_sid_to_sid(s: &str) -> Option<*mut c_void> {
#[link(name = "advapi32")]
unsafe extern "system" {
fn ConvertStringSidToSidW(StringSid: *const u16, Sid: *mut *mut c_void) -> i32;
}
let mut psid: *mut c_void = std::ptr::null_mut();
let ok = unsafe { ConvertStringSidToSidW(to_wide(s).as_ptr(), &mut psid) };
if ok != 0 { Some(psid) } else { None }
}
/// Owns a SID allocated by `ConvertStringSidToSidW` and releases it with `LocalFree`.
pub struct LocalSid {
psid: *mut c_void,
}
impl LocalSid {
pub fn from_string(sid: &str) -> Result<Self> {
let psid = unsafe { convert_string_sid_to_sid(sid) }
.ok_or_else(|| anyhow!("invalid SID string: {sid}"))?;
Ok(Self { psid })
}
pub fn as_ptr(&self) -> *mut c_void {
self.psid
}
}
impl Drop for LocalSid {
fn drop(&mut self) {
if !self.psid.is_null() {
unsafe {
LocalFree(self.psid as HLOCAL);
}
}
}
}
/// # Safety
/// Caller must close the returned token handle.
pub unsafe fn get_current_token_for_restriction() -> Result<HANDLE> {
let desired = TOKEN_DUPLICATE
| TOKEN_QUERY
| TOKEN_ASSIGN_PRIMARY
| TOKEN_ADJUST_DEFAULT
| TOKEN_ADJUST_SESSIONID
| TOKEN_ADJUST_PRIVILEGES;
let mut h: HANDLE = std::ptr::null_mut();
#[link(name = "advapi32")]
unsafe extern "system" {
fn OpenProcessToken(
ProcessHandle: HANDLE,
DesiredAccess: u32,
TokenHandle: *mut HANDLE,
) -> i32;
}
let ok = unsafe { OpenProcessToken(GetCurrentProcess(), desired, &mut h) };
if ok == 0 {
return Err(anyhow!("OpenProcessToken failed: {}", GetLastError()));
}
Ok(h)
}
/// An owned token group, including attributes such as enabled and deny-only.
#[derive(Debug, PartialEq, Eq)]
pub struct TokenGroup {
pub sid: Vec<u8>,
pub attributes: u32,
}
/// Queries groups without filtering membership or retaining pointers into Windows' buffer.
///
/// # Safety
/// `token` must remain a valid token handle with `TOKEN_QUERY` access during this call.
pub unsafe fn token_groups(token: HANDLE, max_bytes: u32) -> Result<Vec<TokenGroup>> {
let mut needed = 0;
GetTokenInformation(token, TokenGroups, std::ptr::null_mut(), 0, &mut needed);
ensure!(
needed > 0 && needed <= max_bytes,
"invalid token group size"
);
let mut buffer = vec![0u8; needed as usize];
if GetTokenInformation(
token,
TokenGroups,
buffer.as_mut_ptr().cast(),
needed,
&mut needed,
) == 0
{
return Err(anyhow!(
"GetTokenInformation(TokenGroups) failed: {}",
GetLastError()
));
}
ensure!(
needed as usize <= buffer.len(),
"invalid token group result size"
);
decode_token_groups(&buffer[..needed as usize])
}
fn decode_token_groups(buffer: &[u8]) -> Result<Vec<TokenGroup>> {
let offset = std::mem::offset_of!(TOKEN_GROUPS, Groups);
let stride = std::mem::size_of::<SID_AND_ATTRIBUTES>();
ensure!(buffer.len() >= offset, "truncated token group header");
let count = unsafe { std::ptr::read_unaligned(buffer.as_ptr().cast::<u32>()) } as usize;
ensure!(
count <= (buffer.len() - offset) / stride,
"truncated token groups"
);
let mut groups = Vec::with_capacity(count);
for index in 0..count {
let entry = unsafe {
std::ptr::read_unaligned(
buffer
.as_ptr()
.add(offset + index * stride)
.cast::<SID_AND_ATTRIBUTES>(),
)
};
// Bound the header and every subauthority before calling a SID API.
let sid_offset = (entry.Sid as usize).wrapping_sub(buffer.as_ptr() as usize);
ensure!(
sid_offset <= buffer.len().saturating_sub(8),
"invalid token group SID pointer"
);
ensure!(buffer[sid_offset] == 1, "invalid token group SID revision");
let sid_len = 8 + usize::from(buffer[sid_offset + 1]) * 4;
ensure!(
sid_len <= 68 && sid_len <= buffer.len() - sid_offset,
"invalid token group SID size"
);
ensure!(
unsafe { IsValidSid(entry.Sid) } != 0,
"invalid token group SID"
);
let mut sid = vec![0u8; sid_len];
ensure!(
unsafe { CopySid(sid_len as u32, sid.as_mut_ptr().cast(), entry.Sid) } != 0,
"invalid token group SID"
);
groups.push(TokenGroup {
sid,
attributes: entry.Attributes,
});
}
Ok(groups)
}
pub unsafe fn get_logon_sid_bytes(h_token: HANDLE) -> Result<Vec<u8>> {
unsafe fn scan_token_groups_for_logon(h: HANDLE) -> Option<Vec<u8>> {
token_groups(h, u32::MAX)
.ok()?
.into_iter()
.find(|group| group.attributes & SE_GROUP_LOGON_ID == SE_GROUP_LOGON_ID)
.map(|group| group.sid)
}
if let Some(v) = scan_token_groups_for_logon(h_token) {
return Ok(v);
}
#[repr(C)]
struct TOKEN_LINKED_TOKEN {
linked_token: HANDLE,
}
const TOKEN_LINKED_TOKEN_CLASS: i32 = 19; // TokenLinkedToken
let mut ln_needed: u32 = 0;
GetTokenInformation(
h_token,
TOKEN_LINKED_TOKEN_CLASS,
std::ptr::null_mut(),
0,
&mut ln_needed,
);
if ln_needed >= std::mem::size_of::<TOKEN_LINKED_TOKEN>() as u32 {
let mut ln_buf: Vec<u8> = vec![0u8; ln_needed as usize];
let ok = GetTokenInformation(
h_token,
TOKEN_LINKED_TOKEN_CLASS,
ln_buf.as_mut_ptr() as *mut c_void,
ln_needed,
&mut ln_needed,
);
if ok != 0 {
let lt: TOKEN_LINKED_TOKEN =
std::ptr::read_unaligned(ln_buf.as_ptr() as *const TOKEN_LINKED_TOKEN);
if !lt.linked_token.is_null() {
let res = scan_token_groups_for_logon(lt.linked_token);
CloseHandle(lt.linked_token);
if let Some(v) = res {
return Ok(v);
}
}
}
}
Err(anyhow!("Logon SID not present on token"))
}
pub(crate) use crate::token_user::get_user_sid_bytes;
unsafe fn enable_single_privilege(h_token: HANDLE, name: &str) -> Result<()> {
let mut luid = LUID {
LowPart: 0,
HighPart: 0,
};
let ok = LookupPrivilegeValueW(std::ptr::null(), to_wide(name).as_ptr(), &mut luid);
if ok == 0 {
return Err(anyhow!("LookupPrivilegeValueW failed: {}", GetLastError()));
}
let mut tp: TOKEN_PRIVILEGES = std::mem::zeroed();
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = 0x00000002; // SE_PRIVILEGE_ENABLED
let ok2 = AdjustTokenPrivileges(
h_token,
0,
&tp,
0,
std::ptr::null_mut(),
std::ptr::null_mut(),
);
if ok2 == 0 {
return Err(anyhow!("AdjustTokenPrivileges failed: {}", GetLastError()));
}
let err = GetLastError();
if err != 0 {
return Err(anyhow!("AdjustTokenPrivileges error {err}"));
}
Ok(())
}
/// # Safety
/// Caller must close the returned token handle.
pub unsafe fn create_readonly_token_with_cap(
psid_capability: *mut c_void,
) -> Result<(HANDLE, *mut c_void)> {
let base = get_current_token_for_restriction()?;
let res = create_readonly_token_with_cap_from(base, psid_capability);
CloseHandle(base);
res
}
/// # Safety
/// Caller must close the returned token handle; base_token must be a valid primary token.
/// # Safety
/// Caller must close the returned token handle; base_token must be a valid primary token.
pub unsafe fn create_readonly_token_with_cap_from(
base_token: HANDLE,
psid_capability: *mut c_void,
) -> Result<(HANDLE, *mut c_void)> {
let new_token = create_token_with_caps_from(base_token, &[psid_capability], &[])?;
Ok((new_token, psid_capability))
}
/// Create a restricted token that includes all provided capability SIDs.
///
/// # Safety
/// Caller must close the returned token handle; base_token must be a valid primary token.
pub unsafe fn create_workspace_write_token_with_caps_from(
base_token: HANDLE,
psid_capabilities: &[*mut c_void],
) -> Result<HANDLE> {
create_token_with_caps_from(base_token, psid_capabilities, &[])
}
/// Create a restricted token that includes all provided capability SIDs, the token user SID, and
/// any additional restricting SIDs.
///
/// This is intended for the elevated sandbox backend, where the token user is the dedicated
/// sandbox account rather than the real signed-in user.
///
/// # Safety
/// Caller must close the returned token handle; base_token must be a valid primary token.
pub unsafe fn create_workspace_write_token_with_caps_and_user_from(
base_token: HANDLE,
psid_capabilities: &[*mut c_void],
additional_restricting_sids: &[*mut c_void],
) -> Result<HANDLE> {
create_token_with_caps_user_and_additional_restrictions_from(
base_token,
psid_capabilities,
additional_restricting_sids,
)
}
/// Create a restricted token that includes all provided capability SIDs.
///
/// # Safety
/// Caller must close the returned token handle; base_token must be a valid primary token.
pub unsafe fn create_readonly_token_with_caps_from(
base_token: HANDLE,
psid_capabilities: &[*mut c_void],
) -> Result<HANDLE> {
create_token_with_caps_from(base_token, psid_capabilities, &[])
}
/// Create a restricted token that includes all provided capability SIDs, the token user SID, and
/// any additional restricting SIDs.
///
/// This is intended for the elevated sandbox backend, where the token user is the dedicated
/// sandbox account rather than the real signed-in user.
///
/// # Safety
/// Caller must close the returned token handle; base_token must be a valid primary token.
pub unsafe fn create_readonly_token_with_caps_and_user_from(
base_token: HANDLE,
psid_capabilities: &[*mut c_void],
additional_restricting_sids: &[*mut c_void],
) -> Result<HANDLE> {
create_token_with_caps_user_and_additional_restrictions_from(
base_token,
psid_capabilities,
additional_restricting_sids,
)
}
unsafe fn create_token_with_caps_user_and_additional_restrictions_from(
base_token: HANDLE,
psid_capabilities: &[*mut c_void],
additional_restricting_sids: &[*mut c_void],
) -> Result<HANDLE> {
let mut user_sid_bytes = get_user_sid_bytes(base_token)?;
let psid_user = user_sid_bytes.as_mut_ptr() as *mut c_void;
let mut extra_restricting_sids = Vec::with_capacity(additional_restricting_sids.len() + 1);
extra_restricting_sids.push(psid_user);
extra_restricting_sids.extend_from_slice(additional_restricting_sids);
create_token_with_caps_from(base_token, psid_capabilities, &extra_restricting_sids)
}
unsafe fn create_token_with_caps_from(
base_token: HANDLE,
psid_capabilities: &[*mut c_void],
extra_restricting_sids: &[*mut c_void],
) -> Result<HANDLE> {
if psid_capabilities.is_empty() {
return Err(anyhow!("no capability SIDs provided"));
}
let mut logon_sid_bytes = get_logon_sid_bytes(base_token)?;
let psid_logon = logon_sid_bytes.as_mut_ptr() as *mut c_void;
let mut everyone = world_sid()?;
let psid_everyone = everyone.as_mut_ptr() as *mut c_void;
// Exact order: Capabilities..., ExtraRestricting..., Logon, Everyone
let mut entries: Vec<SID_AND_ATTRIBUTES> =
vec![std::mem::zeroed(); psid_capabilities.len() + extra_restricting_sids.len() + 2];
for (i, psid) in psid_capabilities.iter().enumerate() {
entries[i].Sid = *psid;
entries[i].Attributes = 0;
}
let extras_idx = psid_capabilities.len();
for (i, psid) in extra_restricting_sids.iter().enumerate() {
entries[extras_idx + i].Sid = *psid;
entries[extras_idx + i].Attributes = 0;
}
let logon_idx = extras_idx + extra_restricting_sids.len();
entries[logon_idx].Sid = psid_logon;
entries[logon_idx].Attributes = 0;
entries[logon_idx + 1].Sid = psid_everyone;
entries[logon_idx + 1].Attributes = 0;
let mut new_token: HANDLE = std::ptr::null_mut();
let flags = DISABLE_MAX_PRIVILEGE | LUA_TOKEN | WRITE_RESTRICTED;
let ok = CreateRestrictedToken(
base_token,
flags,
0,
std::ptr::null(),
0,
std::ptr::null(),
entries.len() as u32,
entries.as_mut_ptr(),
&mut new_token,
);
if ok == 0 {
return Err(anyhow!("CreateRestrictedToken failed: {}", GetLastError()));
}
// Filesystem and route capabilities may be shared between launches. They
// must not grant access to another launch's processes, threads, or IPC.
if let Err(error) = set_default_dacl(new_token, psid_logon)
.and_then(|()| enable_single_privilege(new_token, "SeChangeNotifyPrivilege"))
{
CloseHandle(new_token);
return Err(error);
}
Ok(new_token)
}
#[cfg(test)]
#[path = "token_tests.rs"]
mod tests;
#[cfg(test)]
#[path = "token_groups_tests.rs"]
mod token_groups_tests;

View File

@@ -0,0 +1,118 @@
//! Exercises owned group decoding and bounded queries without changing token privileges.
use super::*;
use pretty_assertions::assert_eq;
use std::os::windows::io::FromRawHandle;
use std::os::windows::io::OwnedHandle;
use windows_sys::Win32::System::Threading::OpenProcessToken;
fn group_buffer(groups: &[TokenGroup]) -> Vec<u8> {
let offset = std::mem::offset_of!(TOKEN_GROUPS, Groups);
let stride = std::mem::size_of::<SID_AND_ATTRIBUTES>();
let mut sid_offset = offset + groups.len() * stride;
let mut buffer =
vec![0u8; sid_offset + groups.iter().map(|group| group.sid.len()).sum::<usize>()];
unsafe { std::ptr::write_unaligned(buffer.as_mut_ptr().cast::<u32>(), groups.len() as u32) };
for (index, group) in groups.iter().enumerate() {
buffer[sid_offset..sid_offset + group.sid.len()].copy_from_slice(&group.sid);
let entry = SID_AND_ATTRIBUTES {
Sid: unsafe { buffer.as_mut_ptr().add(sid_offset).cast() },
Attributes: group.attributes,
};
unsafe {
std::ptr::write_unaligned(
buffer
.as_mut_ptr()
.add(offset + index * stride)
.cast::<SID_AND_ATTRIBUTES>(),
entry,
)
};
sid_offset += group.sid.len();
}
buffer
}
#[test]
fn owns_sids_and_preserves_duplicate_order_and_attributes() -> Result<()> {
let expected = [0x4, 0x10, SE_GROUP_LOGON_ID]
.into_iter()
.map(|attributes| TokenGroup {
sid: unsafe { world_sid().expect("world SID") },
attributes,
})
.collect::<Vec<_>>();
let actual = {
let buffer = group_buffer(&expected);
decode_token_groups(&buffer)?
};
assert_eq!(actual, expected);
Ok(())
}
#[test]
fn rejects_truncated_group_layout() {
assert!(decode_token_groups(&[]).is_err());
let mut buffer = group_buffer(&[]);
assert_eq!(
decode_token_groups(&buffer).unwrap(),
Vec::<TokenGroup>::new()
);
unsafe { std::ptr::write_unaligned(buffer.as_mut_ptr().cast::<u32>(), u32::MAX) };
assert!(decode_token_groups(&buffer).is_err());
}
#[test]
fn rejects_malformed_and_out_of_buffer_sids() {
let group = TokenGroup {
sid: unsafe { world_sid().expect("world SID") },
attributes: 4,
};
let mut buffer = group_buffer(&[group]);
let offset = std::mem::offset_of!(TOKEN_GROUPS, Groups);
let entry = unsafe {
std::ptr::read_unaligned(buffer.as_ptr().add(offset).cast::<SID_AND_ATTRIBUTES>())
};
let sid_offset = (entry.Sid as usize) - (buffer.as_ptr() as usize);
buffer[sid_offset] = 2;
assert!(decode_token_groups(&buffer).is_err());
buffer[sid_offset] = 1;
buffer[sid_offset + 1] = 15;
assert!(decode_token_groups(&buffer).is_err());
for sid in [std::ptr::null_mut(), unsafe {
buffer.as_mut_ptr().add(buffer.len() - 1).cast()
}] {
unsafe {
std::ptr::write_unaligned(
buffer.as_mut_ptr().add(offset).cast::<SID_AND_ATTRIBUTES>(),
SID_AND_ATTRIBUTES {
Sid: sid,
Attributes: 4,
},
)
};
assert!(decode_token_groups(&buffer).is_err());
}
}
#[test]
fn queries_current_token_with_a_caller_size_limit() -> Result<()> {
let mut raw = std::ptr::null_mut();
ensure!(unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut raw) } != 0);
let _token = unsafe { OwnedHandle::from_raw_handle(raw as _) };
assert!(
unsafe {
token_groups(raw, /*max_bytes*/ 0)
}
.is_err()
);
let groups = unsafe { token_groups(raw, u32::MAX) }?;
assert!(!groups.is_empty());
if let Some(logon) = groups
.iter()
.find(|group| group.attributes & SE_GROUP_LOGON_ID == SE_GROUP_LOGON_ID)
{
assert_eq!(unsafe { get_logon_sid_bytes(raw) }?, logon.sid);
}
Ok(())
}

View File

@@ -0,0 +1,231 @@
use super::*;
use pretty_assertions::assert_eq;
use windows_sys::Win32::Security::EqualSid;
use windows_sys::Win32::Security::TokenRestrictedSids;
unsafe fn token_has_restricting_sid(token: HANDLE, expected_sid: *mut c_void) -> Result<bool> {
let mut needed = 0;
GetTokenInformation(
token,
TokenRestrictedSids,
std::ptr::null_mut(),
0,
&mut needed,
);
if needed == 0 {
return Err(anyhow!(
"GetTokenInformation(TokenRestrictedSids) size query failed: {}",
GetLastError()
));
}
let mut buffer = vec![0_u8; needed as usize];
if GetTokenInformation(
token,
TokenRestrictedSids,
buffer.as_mut_ptr().cast(),
needed,
&mut needed,
) == 0
{
return Err(anyhow!(
"GetTokenInformation(TokenRestrictedSids) failed: {}",
GetLastError()
));
}
let group_count = std::ptr::read_unaligned(buffer.as_ptr().cast::<u32>()) as usize;
let after_count = buffer.as_ptr().add(std::mem::size_of::<u32>()) as usize;
let align = std::mem::align_of::<SID_AND_ATTRIBUTES>();
let entries_addr = (after_count + (align - 1)) & !(align - 1);
let restricting_sids =
std::slice::from_raw_parts(entries_addr as *const SID_AND_ATTRIBUTES, group_count);
Ok(restricting_sids
.iter()
.any(|entry| EqualSid(entry.Sid, expected_sid) != 0))
}
#[test]
fn elevated_token_includes_network_proxy_restricting_sid() -> Result<()> {
let capability_sid = LocalSid::from_string("S-1-5-21-10-20-30-40")?;
let network_proxy_sid = LocalSid::from_string("S-1-5-21-50-60-70-80")?;
let base_token = unsafe { get_current_token_for_restriction()? };
let restricted_token = unsafe {
create_readonly_token_with_caps_and_user_from(
base_token,
&[capability_sid.as_ptr()],
&[network_proxy_sid.as_ptr()],
)?
};
let has_network_proxy_sid =
unsafe { token_has_restricting_sid(restricted_token, network_proxy_sid.as_ptr()) };
unsafe {
CloseHandle(restricted_token);
CloseHandle(base_token);
}
assert!(has_network_proxy_sid?);
Ok(())
}
#[test]
fn default_objects_deny_other_logons_even_with_the_same_owner() -> Result<()> {
use std::os::windows::io::AsRawHandle;
use std::os::windows::io::FromRawHandle;
use std::os::windows::io::OwnedHandle;
use windows_sys::Win32::Security::ACCESS_ALLOWED_ACE;
use windows_sys::Win32::Security::AccessCheck;
use windows_sys::Win32::Security::DuplicateToken;
use windows_sys::Win32::Security::GENERIC_MAPPING;
use windows_sys::Win32::Security::GetAce;
use windows_sys::Win32::Security::InitializeSecurityDescriptor;
use windows_sys::Win32::Security::MapGenericMask;
use windows_sys::Win32::Security::SECURITY_DESCRIPTOR;
use windows_sys::Win32::Security::SecurityImpersonation;
use windows_sys::Win32::Security::SetSecurityDescriptorDacl;
use windows_sys::Win32::Security::SetSecurityDescriptorGroup;
use windows_sys::Win32::Security::SetSecurityDescriptorOwner;
use windows_sys::Win32::Storage::FileSystem::READ_CONTROL;
use windows_sys::Win32::Storage::FileSystem::WRITE_DAC;
use windows_sys::Win32::System::Threading::PROCESS_ALL_ACCESS;
use windows_sys::Win32::System::Threading::PROCESS_CREATE_THREAD;
use windows_sys::Win32::System::Threading::PROCESS_QUERY_INFORMATION;
use windows_sys::Win32::System::Threading::PROCESS_TERMINATE;
use windows_sys::Win32::System::Threading::PROCESS_VM_OPERATION;
use windows_sys::Win32::System::Threading::PROCESS_VM_READ;
use windows_sys::Win32::System::Threading::PROCESS_VM_WRITE;
unsafe {
let base = OwnedHandle::from_raw_handle(get_current_token_for_restriction()? as _);
let base_raw = base.as_raw_handle() as HANDLE;
let capability = LocalSid::from_string("S-1-5-21-10-20-30-40")?;
let victim =
OwnedHandle::from_raw_handle(create_workspace_write_token_with_caps_and_user_from(
base_raw,
&[capability.as_ptr()],
&[],
)? as _);
let mut needed = 0;
GetTokenInformation(
victim.as_raw_handle() as _,
TokenDefaultDacl,
std::ptr::null_mut(),
0,
&mut needed,
);
let mut buffer = vec![0u8; needed as usize];
ensure!(
GetTokenInformation(
victim.as_raw_handle() as _,
TokenDefaultDacl,
buffer.as_mut_ptr().cast(),
needed,
&mut needed
) != 0,
"GetTokenInformation(TokenDefaultDacl) failed: {}",
GetLastError()
);
let default_dacl = std::ptr::read_unaligned(buffer.as_ptr().cast::<TokenDefaultDaclInfo>());
let mapping = GENERIC_MAPPING {
GenericRead: READ_CONTROL | PROCESS_VM_READ | PROCESS_QUERY_INFORMATION,
GenericWrite: READ_CONTROL | PROCESS_VM_WRITE | PROCESS_VM_OPERATION,
GenericExecute: READ_CONTROL,
GenericAll: PROCESS_ALL_ACCESS,
};
// Object creation maps the token default DACL's generic ACE masks to
// object-specific rights. AccessCheck expects that mapping already done.
for index in 0..u32::from((*default_dacl.default_dacl).AceCount) {
let mut ace = std::ptr::null_mut();
ensure!(GetAce(default_dacl.default_dacl, index, &mut ace) != 0);
MapGenericMask(&mut (*ace.cast::<ACCESS_ALLOWED_ACE>()).Mask, &mapping);
}
let mut owner = get_user_sid_bytes(base_raw)?;
let mut descriptor: SECURITY_DESCRIPTOR = std::mem::zeroed();
let sd = std::ptr::addr_of_mut!(descriptor).cast();
ensure!(InitializeSecurityDescriptor(sd, 1) != 0);
ensure!(SetSecurityDescriptorOwner(sd, owner.as_mut_ptr().cast(), 0) != 0);
ensure!(SetSecurityDescriptorGroup(sd, owner.as_mut_ptr().cast(), 0) != 0);
ensure!(SetSecurityDescriptorDacl(sd, 1, default_dacl.default_dacl, 0) != 0);
// Model another logon of the same account without the victim's logon
// SID. Build from the base token, retaining the shared user, Everyone,
// and filesystem capability in the write-restricting SID set.
let mut logon = get_logon_sid_bytes(base_raw)?;
let mut everyone = world_sid()?;
let disabled = SID_AND_ATTRIBUTES {
Sid: logon.as_mut_ptr().cast(),
Attributes: 0,
};
let restricting = [
capability.as_ptr(),
owner.as_mut_ptr().cast(),
everyone.as_mut_ptr().cast(),
]
.map(|sid| SID_AND_ATTRIBUTES {
Sid: sid,
Attributes: 0,
});
let mut other = std::ptr::null_mut();
ensure!(
CreateRestrictedToken(
base_raw,
DISABLE_MAX_PRIVILEGE | LUA_TOKEN | WRITE_RESTRICTED,
1,
&disabled,
0,
std::ptr::null(),
restricting.len() as u32,
restricting.as_ptr(),
&mut other
) != 0,
"CreateRestrictedToken(other logon) failed: {}",
GetLastError()
);
let other = OwnedHandle::from_raw_handle(other as _);
for (token, same_logon) in [(&victim, true), (&other, false)] {
let mut impersonation = std::ptr::null_mut();
ensure!(
DuplicateToken(
token.as_raw_handle() as _,
SecurityImpersonation,
&mut impersonation
) != 0,
"DuplicateToken failed: {}",
GetLastError()
);
let impersonation = OwnedHandle::from_raw_handle(impersonation as _);
for access in [
PROCESS_VM_READ,
PROCESS_VM_WRITE,
PROCESS_VM_OPERATION,
PROCESS_CREATE_THREAD,
PROCESS_TERMINATE,
PROCESS_QUERY_INFORMATION,
WRITE_DAC,
0x43a,
] {
let mut privileges = [0u64; 128];
let mut privilege_bytes = std::mem::size_of_val(&privileges) as u32;
let mut granted = 0;
let mut allowed = 0;
ensure!(
AccessCheck(
sd,
impersonation.as_raw_handle() as _,
access,
&mapping,
privileges.as_mut_ptr().cast(),
&mut privilege_bytes,
&mut granted,
&mut allowed
) != 0,
"AccessCheck failed: {}",
GetLastError()
);
assert_eq!(allowed != 0, same_logon, "access {access:#x}");
}
}
}
Ok(())
}

View File

@@ -0,0 +1,74 @@
//! Copies token user identities with bounded Windows queries and owned SID storage.
use anyhow::Result;
use anyhow::anyhow;
use anyhow::ensure;
use std::ffi::c_void;
use windows_sys::Win32::Foundation::GetLastError;
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::Security::GetTokenInformation;
use windows_sys::Win32::Security::IsValidSid;
use windows_sys::Win32::Security::TOKEN_USER;
use windows_sys::Win32::Security::TokenUser;
/// Copies a token's user SID into owned storage after a bounded TokenUser query.
///
/// # Safety
/// The caller must keep a token handle with TOKEN_QUERY access valid during this call.
pub unsafe fn get_user_sid_bytes(h_token: HANDLE) -> Result<Vec<u8>> {
let mut needed: u32 = 0;
GetTokenInformation(h_token, TokenUser, std::ptr::null_mut(), 0, &mut needed);
ensure!(
needed as usize >= std::mem::size_of::<TOKEN_USER>() && needed <= 4096,
"invalid TokenUser query size"
);
let mut user_buf: Vec<u8> = vec![0u8; needed as usize];
let ok = GetTokenInformation(
h_token,
TokenUser,
user_buf.as_mut_ptr() as *mut c_void,
needed,
&mut needed,
);
if ok == 0 {
return Err(anyhow!(
"GetTokenInformation(TokenUser) failed: {}",
GetLastError()
));
}
ensure!(
needed as usize <= user_buf.len(),
"invalid TokenUser result size"
);
decode_token_user(&user_buf[..needed as usize])
}
fn decode_token_user(buffer: &[u8]) -> Result<Vec<u8>> {
ensure!(
buffer.len() >= std::mem::size_of::<TOKEN_USER>(),
"truncated TokenUser"
);
let user = unsafe { std::ptr::read_unaligned(buffer.as_ptr().cast::<TOKEN_USER>()) };
copy_token_sid(buffer, user.User.Sid)
}
fn copy_token_sid(buffer: &[u8], pointer: *mut c_void) -> Result<Vec<u8>> {
// Bound the header and every subauthority before calling a SID API.
let offset = (pointer as usize).wrapping_sub(buffer.as_ptr() as usize);
ensure!(
buffer.len() >= 8 && offset <= buffer.len() - 8,
"invalid token SID pointer"
);
ensure!(buffer[offset] == 1, "invalid token SID revision");
let length = 8 + usize::from(buffer[offset + 1]) * 4;
ensure!(
length <= 68 && length <= buffer.len() - offset,
"invalid token SID size"
);
ensure!(unsafe { IsValidSid(pointer) } != 0, "invalid token SID");
Ok(buffer[offset..offset + length].to_vec())
}
#[cfg(test)]
#[path = "token_user_tests.rs"]
mod tests;

View File

@@ -0,0 +1,78 @@
//! Verifies owned token-user SID results and rejects malformed query buffers.
use super::*;
use crate::token::world_sid;
use pretty_assertions::assert_eq;
use std::os::windows::io::FromRawHandle;
use std::os::windows::io::OwnedHandle;
use windows_sys::Win32::Security::SID_AND_ATTRIBUTES;
use windows_sys::Win32::Security::TOKEN_QUERY;
use windows_sys::Win32::System::Threading::GetCurrentProcess;
use windows_sys::Win32::System::Threading::OpenProcessToken;
fn user_buffer(sid: &[u8]) -> Vec<u8> {
let offset = std::mem::size_of::<TOKEN_USER>();
let mut buffer = vec![0; offset + sid.len()];
buffer[offset..].copy_from_slice(sid);
unsafe {
let user = TOKEN_USER {
User: SID_AND_ATTRIBUTES {
Sid: buffer.as_mut_ptr().add(offset).cast(),
Attributes: 0,
},
};
std::ptr::write_unaligned(buffer.as_mut_ptr().cast::<TOKEN_USER>(), user);
}
buffer
}
#[test]
fn user_sid_is_owned_after_the_query_buffer_is_dropped() -> Result<()> {
let expected = unsafe { world_sid() }?;
let actual = {
let buffer = user_buffer(&expected);
decode_token_user(&buffer)?
};
assert_eq!(actual, expected);
Ok(())
}
#[test]
fn rejects_truncated_user_and_malformed_sid() -> Result<()> {
assert!(decode_token_user(&[]).is_err());
let mut buffer = user_buffer(&unsafe { world_sid() }?);
let offset = std::mem::size_of::<TOKEN_USER>();
buffer[offset] = 2;
assert!(decode_token_user(&buffer).is_err());
buffer[offset] = 1;
buffer[offset + 1] = 15;
assert!(decode_token_user(&buffer).is_err());
for pointer in [std::ptr::null_mut(), unsafe {
buffer.as_mut_ptr().add(buffer.len() - 1).cast()
}] {
unsafe {
std::ptr::write_unaligned(
buffer.as_mut_ptr().cast::<TOKEN_USER>(),
TOKEN_USER {
User: SID_AND_ATTRIBUTES {
Sid: pointer,
Attributes: 0,
},
},
);
}
assert!(decode_token_user(&buffer).is_err());
}
Ok(())
}
#[test]
fn queries_current_user_and_rejects_invalid_token() -> Result<()> {
let mut raw = std::ptr::null_mut();
ensure!(unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut raw) } != 0);
let _token = unsafe { OwnedHandle::from_raw_handle(raw as _) };
let user = unsafe { get_user_sid_bytes(raw) }?;
assert!(unsafe { IsValidSid(user.as_ptr() as _) } != 0);
assert!(unsafe { get_user_sid_bytes(std::ptr::null_mut()) }.is_err());
Ok(())
}

View File

@@ -0,0 +1,282 @@
use super::windows_common::finish_driver_spawn;
use super::windows_common::make_runner_resizer;
use super::windows_common::start_runner_pipe_writer;
use super::windows_common::start_runner_stdin_writer;
use super::windows_common::start_runner_stdout_reader;
use crate::desktop::DesktopPolicy;
use crate::identity::SandboxCreds;
use crate::identity::refresh_logon_sandbox_creds;
use crate::ipc_framed::EmptyPayload;
use crate::ipc_framed::FramedMessage;
use crate::ipc_framed::IPC_PROTOCOL_VERSION;
use crate::ipc_framed::Message;
use crate::ipc_framed::SpawnRequest;
use crate::resolved_permissions::ResolvedWindowsSandboxPermissions;
use crate::runner_client::RunnerTransport;
use crate::runner_client::retry_runner_spawn_once;
use crate::runner_client::spawn_runner_transport;
use crate::spawn_prep::prepare_elevated_spawn_context_for_permissions;
use anyhow::Result;
use akode_protocol::models::PermissionProfile;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_pty::ProcessDriver;
use akode_utils_pty::SpawnedProcess;
use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;
use tokio::sync::broadcast;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
struct RunnerTransportRequest {
permissions: ResolvedWindowsSandboxPermissions,
codex_home: PathBuf,
cwd: PathBuf,
env_map: HashMap<String, String>,
logs_base_dir: Option<PathBuf>,
spawn_request: SpawnRequest,
read_roots_override: Option<Vec<PathBuf>>,
read_roots_include_platform_defaults: bool,
write_roots_override: Option<Vec<PathBuf>>,
deny_read_paths_override: Vec<PathBuf>,
deny_write_paths_override: Vec<PathBuf>,
proxy_enforced: bool,
proxy_settings_mode: crate::WindowsSandboxProxySettingsMode,
}
fn spawn_runner_transport_with_retry<T>(
sandbox_creds: SandboxCreds,
request: &RunnerTransportRequest,
mut spawn: impl FnMut(&Path, &Path, &SandboxCreds, Option<&Path>, SpawnRequest) -> Result<T>,
refresh: impl FnOnce(
&ResolvedWindowsSandboxPermissions,
&Path,
&HashMap<String, String>,
&Path,
Option<&[PathBuf]>,
bool,
Option<&[PathBuf]>,
&[PathBuf],
&[PathBuf],
bool,
crate::WindowsSandboxProxySettingsMode,
) -> Result<SandboxCreds>,
) -> Result<T> {
retry_runner_spawn_once(
sandbox_creds,
&request.spawn_request.command,
|sandbox_creds| {
spawn(
&request.codex_home,
&request.cwd,
&sandbox_creds,
request.logs_base_dir.as_deref(),
request.spawn_request.clone(),
)
},
|| {
refresh(
&request.permissions,
&request.cwd,
&request.env_map,
&request.codex_home,
request.read_roots_override.as_deref(),
request.read_roots_include_platform_defaults,
request.write_roots_override.as_deref(),
&request.deny_read_paths_override,
&request.deny_write_paths_override,
request.proxy_enforced,
request.proxy_settings_mode,
)
},
)
}
async fn spawn_runner_transport_task(
sandbox_creds: SandboxCreds,
request: RunnerTransportRequest,
) -> Result<RunnerTransport> {
tokio::task::spawn_blocking(move || -> Result<_> {
let desktop_policy = request
.spawn_request
.private_desktop_name
.is_none()
.then(|| {
DesktopPolicy::elevated(
crate::setup::SandboxSetupRequest {
permissions: &request.permissions,
command_cwd: &request.cwd,
env_map: &request.env_map,
codex_home: &request.codex_home,
proxy_enforced: request.proxy_enforced,
},
crate::setup::SetupRootOverrides {
read_roots: request.read_roots_override.clone(),
read_roots_include_platform_defaults: request
.read_roots_include_platform_defaults,
write_roots: request.write_roots_override.clone(),
deny_read_paths: Some(request.deny_read_paths_override.clone()),
deny_write_paths: Some(request.deny_write_paths_override.clone()),
},
&request.spawn_request.cap_sids,
request
.spawn_request
.network_proxy_restricting_sid
.as_deref(),
)
})
.transpose()?;
spawn_runner_transport_with_retry(
sandbox_creds,
&request,
|codex_home, cwd, sandbox_creds, log_dir, spawn_request| {
spawn_runner_transport(
codex_home,
cwd,
sandbox_creds,
log_dir,
spawn_request,
desktop_policy.as_ref(),
)
},
refresh_logon_sandbox_creds,
)
})
.await
.map_err(|err| anyhow::anyhow!("runner handshake task failed: {err}"))?
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn spawn_windows_sandbox_session_elevated_for_permission_profile(
permission_profile: &PermissionProfile,
workspace_roots: &[AbsolutePathBuf],
codex_home: &Path,
command: Vec<String>,
cwd: &Path,
mut env_map: HashMap<String, String>,
proxy_enforced: bool,
network_proxy_restricting_sid: Option<String>,
proxy_settings_mode: crate::WindowsSandboxProxySettingsMode,
timeout_ms: Option<u64>,
read_roots_override: Option<&[PathBuf]>,
read_roots_include_platform_defaults: bool,
write_roots_override: Option<&[PathBuf]>,
deny_read_paths_override: &[AbsolutePathBuf],
deny_write_paths_override: &[AbsolutePathBuf],
tty: bool,
stdin_open: bool,
private_desktop_name: Option<String>,
) -> Result<SpawnedProcess> {
let deny_read_paths_override = deny_read_paths_override
.iter()
.map(AbsolutePathBuf::to_path_buf)
.collect::<Vec<_>>();
let deny_write_paths_override = deny_write_paths_override
.iter()
.map(AbsolutePathBuf::to_path_buf)
.collect::<Vec<_>>();
let permissions =
ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots(
permission_profile,
workspace_roots,
)?;
let elevated = prepare_elevated_spawn_context_for_permissions(
permissions.clone(),
codex_home,
cwd,
&mut env_map,
&command,
read_roots_override,
read_roots_include_platform_defaults,
write_roots_override,
&deny_read_paths_override,
&deny_write_paths_override,
proxy_enforced,
proxy_settings_mode,
)?;
let sandbox_creds = elevated.sandbox_creds;
let request = RunnerTransportRequest {
permissions,
codex_home: codex_home.to_path_buf(),
cwd: cwd.to_path_buf(),
env_map: env_map.clone(),
logs_base_dir: elevated.logs_base_dir,
spawn_request: SpawnRequest {
command,
cwd: cwd.to_path_buf(),
env: env_map,
permission_profile: permission_profile.clone(),
workspace_roots: workspace_roots.to_vec(),
codex_home: elevated.sandbox_base,
real_codex_home: codex_home.to_path_buf(),
cap_sids: elevated.cap_sids,
network_proxy_restricting_sid,
timeout_ms,
tty,
stdin_open,
private_desktop_name,
},
read_roots_override: read_roots_override.map(<[PathBuf]>::to_vec),
read_roots_include_platform_defaults,
write_roots_override: write_roots_override.map(<[PathBuf]>::to_vec),
deny_read_paths_override,
deny_write_paths_override,
proxy_enforced,
proxy_settings_mode,
};
let transport = spawn_runner_transport_task(sandbox_creds, request).await?;
let (pipe_write, pipe_read) = transport.into_files();
let (writer_tx, writer_rx) = mpsc::channel::<Vec<u8>>(128);
let (stdout_tx, stdout_rx) = broadcast::channel::<Vec<u8>>(256);
let stderr_rx = if tty {
None
} else {
Some(broadcast::channel::<Vec<u8>>(256))
};
let (exit_tx, exit_rx) = oneshot::channel::<i32>();
let outbound_tx = start_runner_pipe_writer(pipe_write);
let writer_handle = start_runner_stdin_writer(writer_rx, outbound_tx.clone(), tty, stdin_open);
let terminator = {
let outbound_tx = outbound_tx.clone();
Some(Box::new(move || {
let _ = outbound_tx.send(FramedMessage {
version: IPC_PROTOCOL_VERSION,
message: Message::Terminate {
payload: EmptyPayload::default(),
},
});
}) as Box<dyn FnMut() + Send + Sync>)
};
start_runner_stdout_reader(
pipe_read,
stdout_tx,
stderr_rx.as_ref().map(|(tx, _rx)| tx.clone()),
exit_tx,
);
Ok(finish_driver_spawn(
ProcessDriver {
writer_tx,
stdout_rx,
stderr_rx: stderr_rx.map(|(_tx, rx)| rx),
exit_rx,
terminator,
writer_handle: Some(writer_handle),
resizer: if tty {
Some(make_runner_resizer(outbound_tx))
} else {
None
},
tty,
},
stdin_open,
))
}
#[cfg(test)]
#[path = "elevated_tests.rs"]
mod tests;

View File

@@ -0,0 +1,260 @@
use super::RunnerTransportRequest;
use super::spawn_runner_transport_with_retry;
use crate::WindowsSandboxProxySettingsMode;
use crate::identity::SandboxCreds;
use crate::ipc_framed::ErrorPayload;
use crate::ipc_framed::ErrorStage;
use crate::ipc_framed::SpawnRequest;
use crate::resolved_permissions::ResolvedWindowsSandboxPermissions;
use crate::runner_client::RunnerLogonError;
use crate::runner_client::RunnerStartupError;
use akode_protocol::models::PermissionProfile;
use akode_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use serde_json::Value;
use std::cell::Cell;
use std::cell::RefCell;
use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
use tempfile::tempdir;
use windows_sys::Win32::Foundation::ERROR_NO_SUCH_LOGON_SESSION;
use windows_sys::Win32::Foundation::ERROR_SERVICE_ALREADY_RUNNING;
#[derive(Debug, Clone, PartialEq, Eq)]
struct SpawnObservation {
codex_home: PathBuf,
cwd: PathBuf,
username: String,
password: String,
logs_base_dir: Option<PathBuf>,
spawn_request: Value,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct RefreshObservation {
permissions: ResolvedWindowsSandboxPermissions,
cwd: PathBuf,
env_map: HashMap<String, String>,
codex_home: PathBuf,
read_roots_override: Option<Vec<PathBuf>>,
read_roots_include_platform_defaults: bool,
write_roots_override: Option<Vec<PathBuf>>,
deny_read_paths_override: Vec<PathBuf>,
deny_write_paths_override: Vec<PathBuf>,
proxy_enforced: bool,
proxy_settings_mode: WindowsSandboxProxySettingsMode,
}
fn runner_transport_request() -> RunnerTransportRequest {
let workspace_root = AbsolutePathBuf::from_absolute_path(PathBuf::from(r"C:\workspace"))
.expect("absolute workspace root");
let permission_profile = PermissionProfile::workspace_write();
let permissions =
ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots(
&permission_profile,
std::slice::from_ref(&workspace_root),
)
.expect("resolved permissions");
let env_map = HashMap::from([
("Path".to_string(), r"C:\tools".to_string()),
(
"HTTPS_PROXY".to_string(),
"http://localhost:1234".to_string(),
),
]);
RunnerTransportRequest {
permissions,
codex_home: PathBuf::from(r"C:\Users\codex"),
cwd: PathBuf::from(r"C:\workspace"),
env_map: env_map.clone(),
logs_base_dir: Some(PathBuf::from(r"C:\Users\codex\.sandbox")),
spawn_request: SpawnRequest {
command: vec!["pwsh.exe".to_string(), "-NoProfile".to_string()],
cwd: PathBuf::from(r"C:\workspace"),
env: env_map,
permission_profile,
workspace_roots: vec![workspace_root],
codex_home: PathBuf::from(r"C:\Users\codex\.sandbox"),
real_codex_home: PathBuf::from(r"C:\Users\codex"),
cap_sids: vec!["S-1-15-3-1024-1".to_string()],
network_proxy_restricting_sid: Some("S-1-5-21-100-200-300-400".to_string()),
timeout_ms: Some(5_000),
tty: true,
stdin_open: true,
private_desktop_name: None,
},
read_roots_override: Some(vec![PathBuf::from(r"C:\workspace\read")]),
read_roots_include_platform_defaults: true,
write_roots_override: Some(vec![PathBuf::from(r"C:\workspace\write")]),
deny_read_paths_override: vec![PathBuf::from(r"C:\secrets")],
deny_write_paths_override: vec![PathBuf::from(r"C:\workspace\.akode")],
proxy_enforced: true,
proxy_settings_mode: WindowsSandboxProxySettingsMode::Preserve,
}
}
#[test]
fn retry_uses_original_unified_exec_request_and_stops_after_second_failure() {
let request = runner_transport_request();
let expected_spawn_request =
serde_json::to_value(&request.spawn_request).expect("serialize spawn request");
let expected_refresh = RefreshObservation {
permissions: request.permissions.clone(),
cwd: request.cwd.clone(),
env_map: request.env_map.clone(),
codex_home: request.codex_home.clone(),
read_roots_override: request.read_roots_override.clone(),
read_roots_include_platform_defaults: true,
write_roots_override: request.write_roots_override.clone(),
deny_read_paths_override: request.deny_read_paths_override.clone(),
deny_write_paths_override: request.deny_write_paths_override.clone(),
proxy_enforced: true,
proxy_settings_mode: WindowsSandboxProxySettingsMode::Preserve,
};
let spawn_observations = RefCell::new(Vec::new());
let refresh_observations = RefCell::new(Vec::new());
let spawn_attempts = Cell::new(0);
let result = spawn_runner_transport_with_retry(
SandboxCreds {
username: "stale".to_string(),
password: "old".to_string(),
},
&request,
|codex_home, cwd, sandbox_creds, logs_base_dir, spawn_request| {
spawn_observations.borrow_mut().push(SpawnObservation {
codex_home: codex_home.to_path_buf(),
cwd: cwd.to_path_buf(),
username: sandbox_creds.username.clone(),
password: sandbox_creds.password.clone(),
logs_base_dir: logs_base_dir.map(Path::to_path_buf),
spawn_request: serde_json::to_value(spawn_request)
.expect("serialize spawn request"),
});
spawn_attempts.set(spawn_attempts.get() + 1);
Err::<(), _>(anyhow::Error::new(RunnerStartupError::new(ErrorPayload {
message: format!("spawn attempt {} failed", spawn_attempts.get()),
stage: ErrorStage::SpawnChild,
windows_error_code: Some(ERROR_NO_SUCH_LOGON_SESSION),
})))
},
|permissions,
cwd,
env_map,
codex_home,
read_roots_override,
read_roots_include_platform_defaults,
write_roots_override,
deny_read_paths_override,
deny_write_paths_override,
proxy_enforced,
proxy_settings_mode| {
refresh_observations.borrow_mut().push(RefreshObservation {
permissions: permissions.clone(),
cwd: cwd.to_path_buf(),
env_map: env_map.clone(),
codex_home: codex_home.to_path_buf(),
read_roots_override: read_roots_override.map(<[PathBuf]>::to_vec),
read_roots_include_platform_defaults,
write_roots_override: write_roots_override.map(<[PathBuf]>::to_vec),
deny_read_paths_override: deny_read_paths_override.to_vec(),
deny_write_paths_override: deny_write_paths_override.to_vec(),
proxy_enforced,
proxy_settings_mode,
});
Ok(SandboxCreds {
username: "refreshed".to_string(),
password: "new".to_string(),
})
},
);
let err = result.expect_err("second spawn should fail");
assert_eq!(
"runner failed during SpawnChild: spawn attempt 2 failed (Windows error 1312)",
err.to_string()
);
assert_eq!(
vec![
SpawnObservation {
codex_home: request.codex_home.clone(),
cwd: request.cwd.clone(),
username: "stale".to_string(),
password: "old".to_string(),
logs_base_dir: request.logs_base_dir.clone(),
spawn_request: expected_spawn_request.clone(),
},
SpawnObservation {
codex_home: request.codex_home.clone(),
cwd: request.cwd.clone(),
username: "refreshed".to_string(),
password: "new".to_string(),
logs_base_dir: request.logs_base_dir,
spawn_request: expected_spawn_request,
},
],
*spawn_observations.borrow()
);
assert_eq!(vec![expected_refresh], *refresh_observations.borrow());
}
#[test]
fn unified_exec_logon_1056_retries_original_request_and_runs_command_once() {
let workspace = tempdir().expect("temporary workspace");
let mut request = runner_transport_request();
request.cwd = workspace.path().to_path_buf();
request.spawn_request.cwd = request.cwd.clone();
request.spawn_request.command = vec![
std::env::var("COMSPEC").expect("Windows command interpreter"),
"/d".into(),
"/c".into(),
"echo launched>>command-launches.txt".into(),
];
let expected = SpawnObservation {
codex_home: request.codex_home.clone(),
cwd: request.cwd.clone(),
username: "sandbox".into(),
password: "unchanged-test-password".into(),
logs_base_dir: request.logs_base_dir.clone(),
spawn_request: serde_json::to_value(&request.spawn_request).expect("serialize request"),
};
let mut attempts = Vec::new();
let status = spawn_runner_transport_with_retry(
SandboxCreds {
username: expected.username.clone(),
password: expected.password.clone(),
},
&request,
|codex_home, cwd, creds, logs_base_dir, spawn_request| {
attempts.push(SpawnObservation {
codex_home: codex_home.to_path_buf(),
cwd: cwd.to_path_buf(),
username: creds.username.clone(),
password: creds.password.clone(),
logs_base_dir: logs_base_dir.map(Path::to_path_buf),
spawn_request: serde_json::to_value(&spawn_request).expect("serialize request"),
});
if attempts.len() == 1 {
return Err(RunnerLogonError {
code: ERROR_SERVICE_ALREADY_RUNNING,
}
.into());
}
Ok(Command::new(&spawn_request.command[0])
.args(&spawn_request.command[1..])
.current_dir(&spawn_request.cwd)
.status()?)
},
|_, _, _, _, _, _, _, _, _, _, _| panic!("1056 must never refresh credentials"),
)
.expect("unified exec should recover from runner logon 1056");
assert!(status.success());
assert_eq!(attempts, vec![expected.clone(), expected]);
assert_eq!(
std::fs::read_to_string(workspace.path().join("command-launches.txt"))
.expect("read command launch marker"),
"launched\r\n"
);
}

View File

@@ -0,0 +1,505 @@
use super::windows_common::finish_driver_spawn;
use crate::conpty::ConptyInstance;
use crate::conpty::spawn_conpty_process_as_user;
use crate::desktop::LaunchDesktop;
use crate::logging::log_failure;
use crate::logging::log_note;
use crate::logging::log_success;
use crate::process::ConsoleMode;
use crate::process::StderrMode;
use crate::process::StdinMode;
use crate::process::read_handle_loop;
use crate::process::spawn_process_with_pipes;
use crate::resolved_permissions::ResolvedWindowsSandboxPermissions;
use crate::spawn_prep::LegacyAclSids;
use crate::spawn_prep::LegacySessionSecurity;
use crate::spawn_prep::SpawnPrepOptions;
use crate::spawn_prep::allow_null_device_for_workspace_write;
use crate::spawn_prep::apply_legacy_session_acl_rules;
use crate::spawn_prep::legacy_session_capability_roots;
use crate::spawn_prep::prepare_legacy_session_security;
use crate::spawn_prep::prepare_legacy_spawn_context;
use anyhow::Result;
use akode_protocol::models::PermissionProfile;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_pty::JobObject;
use akode_utils_pty::ProcessDriver;
use akode_utils_pty::SpawnedProcess;
use akode_utils_pty::TerminalSize;
use akode_utils_pty::WindowsTtyInputNormalizer;
use std::collections::HashMap;
use std::os::windows::io::AsRawHandle;
use std::os::windows::io::BorrowedHandle;
use std::os::windows::io::FromRawHandle;
use std::os::windows::io::OwnedHandle;
use std::path::Path;
use std::ptr;
use std::sync::Arc;
use std::sync::Mutex as StdMutex;
use tokio::sync::broadcast;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::Foundation::GetLastError;
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::Storage::FileSystem::WriteFile;
use windows_sys::Win32::System::Console::COORD;
use windows_sys::Win32::System::Console::HPCON;
use windows_sys::Win32::System::Console::ResizePseudoConsole;
use windows_sys::Win32::System::Threading::GetExitCodeProcess;
use windows_sys::Win32::System::Threading::INFINITE;
use windows_sys::Win32::System::Threading::PROCESS_INFORMATION;
use windows_sys::Win32::System::Threading::TerminateProcess;
use windows_sys::Win32::System::Threading::WaitForSingleObject;
const WAIT_TIMEOUT: u32 = 0x0000_0102;
struct NonOwningProcessHandle(HANDLE);
// SAFETY: Process handles are opaque process-wide tokens that may be used from
// any thread. This wrapper does not own the handle or extend its lifetime.
unsafe impl Send for NonOwningProcessHandle {}
impl NonOwningProcessHandle {
fn raw(&self) -> HANDLE {
self.0
}
}
struct LegacyProcessHandles {
process: PROCESS_INFORMATION,
job: Arc<JobObject>,
output_join: std::thread::JoinHandle<()>,
writer_handle: tokio::task::JoinHandle<()>,
hpc: Option<HPCON>,
conpty_owner: Option<ConptyInstance>,
token_handle: HANDLE,
desktop: Option<LaunchDesktop>,
}
#[allow(clippy::too_many_arguments)]
fn spawn_legacy_process(
security: &LegacySessionSecurity,
permissions: &ResolvedWindowsSandboxPermissions,
additional_deny_write_paths: &[std::path::PathBuf],
command: &[String],
cwd: &Path,
env_map: &HashMap<String, String>,
private_desktop_name: Option<&str>,
tty: bool,
stdin_open: bool,
stdout_tx: broadcast::Sender<Vec<u8>>,
stderr_tx: Option<broadcast::Sender<Vec<u8>>>,
writer_rx: mpsc::Receiver<Vec<u8>>,
logs_base_dir: Option<&Path>,
) -> Result<LegacyProcessHandles> {
let h_token = security.h_token;
// SAFETY: The caller keeps security.h_token open throughout this synchronous spawn.
let token = unsafe { BorrowedHandle::borrow_raw(h_token) };
let launch_desktop = match private_desktop_name {
Some(name) => LaunchDesktop::open_private(name)?,
None => LaunchDesktop::prepare_legacy(
permissions,
cwd,
env_map,
security,
additional_deny_write_paths,
logs_base_dir,
)?,
};
let (pi, job, output_join, writer_handle, hpc, conpty_owner, desktop) = if tty {
let (pi, mut conpty) =
spawn_conpty_process_as_user(token, command, cwd, env_map, launch_desktop)?;
let job = conpty
.job()
.ok_or_else(|| anyhow::anyhow!("spawned ConPTY is missing its process job"))?;
let hpc = conpty.raw_handle();
let output_join = spawn_output_reader(conpty.take_output_read(), stdout_tx);
let writer_handle = spawn_input_writer(
Some(conpty.take_input_write()),
writer_rx,
/*normalize_newlines*/ true,
);
(pi, job, output_join, writer_handle, hpc, Some(conpty), None)
} else {
let pipe_handles = spawn_process_with_pipes(
token,
command,
cwd,
env_map,
if stdin_open {
StdinMode::Open
} else {
StdinMode::Closed
},
StderrMode::Separate,
ConsoleMode::NoWindow,
launch_desktop,
logs_base_dir,
)?;
let stdout_join = spawn_output_reader(pipe_handles.stdout_read, stdout_tx);
let Some(stderr_read) = pipe_handles.stderr_read else {
anyhow::bail!("separate stderr handle should be present");
};
let Some(stderr_tx) = stderr_tx else {
anyhow::bail!("separate stderr channel should be present");
};
let stderr_join = spawn_output_reader(stderr_read, stderr_tx);
let output_join = std::thread::spawn(move || {
let _ = stdout_join.join();
let _ = stderr_join.join();
});
let writer_handle = spawn_input_writer(
pipe_handles.stdin_write,
writer_rx,
/*normalize_newlines*/ false,
);
(
pipe_handles.process,
pipe_handles.job(),
output_join,
writer_handle,
None,
None,
Some(pipe_handles.desktop),
)
};
Ok(LegacyProcessHandles {
process: pi,
job,
output_join,
writer_handle,
hpc,
conpty_owner,
token_handle: h_token,
desktop,
})
}
fn spawn_output_reader(
output_read: HANDLE,
output_tx: broadcast::Sender<Vec<u8>>,
) -> std::thread::JoinHandle<()> {
// SAFETY: The spawn path transfers this pipe's read end to the reader.
let output_read = unsafe { OwnedHandle::from_raw_handle(output_read) };
read_handle_loop(output_read, move |chunk| {
let _ = output_tx.send(chunk.to_vec());
})
}
fn spawn_input_writer(
input_write: Option<HANDLE>,
mut writer_rx: mpsc::Receiver<Vec<u8>>,
normalize_newlines: bool,
) -> tokio::task::JoinHandle<()> {
// SAFETY: The spawn path transfers the pipe's write end to this writer.
let input_write = input_write.map(|handle| unsafe { OwnedHandle::from_raw_handle(handle) });
tokio::task::spawn_blocking(move || {
let mut windows_input = WindowsTtyInputNormalizer::default();
while let Some(bytes) = writer_rx.blocking_recv() {
let Some(handle) = &input_write else {
continue;
};
let bytes = if normalize_newlines {
windows_input.normalize(&bytes)
} else {
bytes
};
if write_all_handle(handle.as_raw_handle(), &bytes).is_err() {
break;
}
}
})
}
fn terminate_job_or_process(
job: &JobObject,
process_handle: &Arc<StdMutex<Option<NonOwningProcessHandle>>>,
logs_base_dir: Option<&Path>,
) {
if let Err(job_err) = job.terminate() {
log_note(
&format!("legacy spawn failed to terminate process tree: {job_err}"),
logs_base_dir,
);
if let Ok(guard) = process_handle.lock()
&& let Some(handle) = guard.as_ref()
&& unsafe { TerminateProcess(handle.raw(), 1) } == 0
{
log_note(
&format!(
"legacy spawn failed to terminate root process: {}",
unsafe { GetLastError() }
),
logs_base_dir,
);
}
}
}
fn write_all_handle(handle: HANDLE, mut bytes: &[u8]) -> Result<()> {
while !bytes.is_empty() {
let mut written = 0u32;
let ok = unsafe {
WriteFile(
handle,
bytes.as_ptr() as *const _,
bytes.len() as u32,
&mut written,
ptr::null_mut(),
)
};
if ok == 0 {
let err = unsafe { GetLastError() } as i32;
return Err(anyhow::anyhow!("WriteFile failed: {err}"));
}
if written == 0 {
anyhow::bail!("WriteFile returned success but wrote 0 bytes");
}
bytes = &bytes[written as usize..];
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn finalize_exit(
exit_tx: oneshot::Sender<i32>,
process_handle: Arc<StdMutex<Option<NonOwningProcessHandle>>>,
thread_handle: OwnedHandle,
output_join: std::thread::JoinHandle<()>,
logs_base_dir: Option<&Path>,
command: Vec<String>,
) {
let exit_code = {
let mut raw_exit = 1u32;
if let Ok(guard) = process_handle.lock()
&& let Some(handle) = guard.as_ref()
{
unsafe {
WaitForSingleObject(handle.raw(), INFINITE);
GetExitCodeProcess(handle.raw(), &mut raw_exit);
}
}
raw_exit as i32
};
let _ = output_join.join();
let _ = exit_tx.send(exit_code);
drop(thread_handle);
if let Ok(mut guard) = process_handle.lock()
&& let Some(handle) = guard.take()
{
unsafe {
CloseHandle(handle.raw());
}
}
if exit_code == 0 {
log_success(&command, logs_base_dir);
} else {
log_failure(&command, &format!("exit code {exit_code}"), logs_base_dir);
}
}
fn resize_conpty_handle(hpc: &Arc<StdMutex<Option<HPCON>>>, size: TerminalSize) -> Result<()> {
let guard = hpc
.lock()
.map_err(|_| anyhow::anyhow!("failed to lock ConPTY handle"))?;
let hpc = guard
.as_ref()
.copied()
.ok_or_else(|| anyhow::anyhow!("process is not attached to a PTY"))?;
let result = unsafe {
ResizePseudoConsole(
hpc,
COORD {
X: size.cols as i16,
Y: size.rows as i16,
},
)
};
if result == 0 {
Ok(())
} else {
Err(anyhow::anyhow!(
"failed to resize console: HRESULT {result}"
))
}
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn spawn_windows_sandbox_session_legacy(
permission_profile: &PermissionProfile,
workspace_roots: &[AbsolutePathBuf],
codex_home: &Path,
command: Vec<String>,
cwd: &Path,
mut env_map: HashMap<String, String>,
timeout_ms: Option<u64>,
additional_deny_read_paths: &[AbsolutePathBuf],
additional_deny_write_paths: &[AbsolutePathBuf],
tty: bool,
stdin_open: bool,
private_desktop_name: Option<String>,
) -> Result<SpawnedProcess> {
let common = prepare_legacy_spawn_context(
permission_profile,
workspace_roots,
codex_home,
cwd,
&mut env_map,
&command,
SpawnPrepOptions {
inherit_path: false,
add_git_safe_directory: false,
},
)?;
if !common.permissions.has_full_disk_read_access() {
anyhow::bail!("Restricted read-only access requires the elevated Windows sandbox backend");
}
// WRITE_RESTRICTED tokens consult restricting SIDs only for writes, so this
// backend cannot make capability-SID deny-read ACLs authoritative.
if !additional_deny_read_paths.is_empty() {
anyhow::bail!("deny-read overrides require the elevated Windows sandbox backend");
}
let additional_deny_write_paths = additional_deny_write_paths
.iter()
.map(AbsolutePathBuf::to_path_buf)
.collect::<Vec<_>>();
let capability_roots = legacy_session_capability_roots(
&common.permissions,
&common.current_dir,
&env_map,
codex_home,
);
let security = prepare_legacy_session_security(
common.uses_write_capabilities,
codex_home,
cwd,
capability_roots,
)?;
allow_null_device_for_workspace_write(common.uses_write_capabilities);
apply_legacy_session_acl_rules(
&common.permissions,
codex_home,
&common.current_dir,
&env_map,
&[],
&additional_deny_write_paths,
LegacyAclSids {
readonly_sid: security.readonly_sid.as_ref(),
readonly_sid_str: security.readonly_sid_str.as_deref(),
write_root_sids: &security.write_root_sids,
},
)?;
let (writer_tx, writer_rx) = mpsc::channel::<Vec<u8>>(128);
let (stdout_tx, stdout_rx) = broadcast::channel::<Vec<u8>>(256);
let stderr_rx = if tty {
None
} else {
Some(broadcast::channel::<Vec<u8>>(256))
};
let (exit_tx, exit_rx) = oneshot::channel::<i32>();
let LegacyProcessHandles {
process: pi,
job,
output_join,
writer_handle,
hpc,
mut conpty_owner,
token_handle,
desktop,
} = match spawn_legacy_process(
&security,
&common.permissions,
&additional_deny_write_paths,
&command,
cwd,
&env_map,
private_desktop_name.as_deref(),
tty,
stdin_open,
stdout_tx,
stderr_rx.as_ref().map(|(tx, _rx)| tx.clone()),
writer_rx,
common.logs_base_dir.as_deref(),
) {
Ok(handles) => handles,
Err(err) => {
unsafe {
CloseHandle(security.h_token);
}
return Err(err);
}
};
let hpc_handle = hpc.map(|hpc| Arc::new(StdMutex::new(Some(hpc))));
let process_handle = Arc::new(StdMutex::new(Some(NonOwningProcessHandle(pi.hProcess))));
let wait_handle = Arc::clone(&process_handle);
let wait_process_handle = NonOwningProcessHandle(pi.hProcess);
// SAFETY: Successful process creation transfers this thread handle to the wait path.
let thread_handle = unsafe { OwnedHandle::from_raw_handle(pi.hThread) };
// SAFETY: spawn_legacy_process transfers the restricted token on success.
let token_handle = unsafe { OwnedHandle::from_raw_handle(token_handle) };
let job_for_wait = Arc::clone(&job);
let command_for_wait = command.clone();
let hpc_for_wait = hpc_handle.clone();
let wait_logs_base_dir = common.logs_base_dir.clone();
std::thread::spawn(move || {
let _desktop = desktop;
let timeout = timeout_ms.map(|ms| ms as u32).unwrap_or(INFINITE);
let wait_res = unsafe { WaitForSingleObject(wait_process_handle.raw(), timeout) };
if wait_res == WAIT_TIMEOUT {
terminate_job_or_process(&job_for_wait, &wait_handle, wait_logs_base_dir.as_deref());
} else if let Err(err) = job_for_wait.preserve_descendants() {
log_note(
&format!("legacy spawn failed to preserve descendants after root exit: {err}"),
wait_logs_base_dir.as_deref(),
);
}
if let Some(hpc) = hpc_for_wait
&& let Ok(mut guard) = hpc.lock()
{
let _ = guard.take();
}
drop(conpty_owner.take());
drop(token_handle);
finalize_exit(
exit_tx,
wait_handle,
thread_handle,
output_join,
wait_logs_base_dir.as_deref(),
command_for_wait,
);
});
let terminator = {
let job = Arc::clone(&job);
let process_handle = Arc::clone(&process_handle);
let logs_base_dir = common.logs_base_dir;
Some(Box::new(move || {
terminate_job_or_process(&job, &process_handle, logs_base_dir.as_deref());
}) as Box<dyn FnMut() + Send + Sync>)
};
let driver = ProcessDriver {
writer_tx,
stdout_rx,
stderr_rx: stderr_rx.map(|(_tx, rx)| rx),
exit_rx,
terminator,
writer_handle: Some(writer_handle),
resizer: hpc_handle.map(|hpc| {
Box::new(move |size| resize_conpty_handle(&hpc, size))
as Box<dyn FnMut(TerminalSize) -> Result<()> + Send>
}),
tty,
};
Ok(finish_driver_spawn(driver, stdin_open))
}

View File

@@ -0,0 +1,3 @@
pub(crate) mod elevated;
pub(crate) mod legacy;
pub(crate) mod windows_common;

View File

@@ -0,0 +1,178 @@
use crate::ipc_framed::EmptyPayload;
use crate::ipc_framed::FramedMessage;
use crate::ipc_framed::IPC_PROTOCOL_VERSION;
use crate::ipc_framed::Message;
use crate::ipc_framed::OutputStream;
use crate::ipc_framed::ResizePayload;
use crate::ipc_framed::StdinPayload;
use crate::ipc_framed::decode_bytes;
use crate::ipc_framed::encode_bytes;
use anyhow::Result;
use akode_utils_pty::ProcessDriver;
use akode_utils_pty::SpawnedProcess;
use akode_utils_pty::TerminalSize;
use akode_utils_pty::WindowsTtyInputNormalizer;
use akode_utils_pty::spawn_from_driver;
use std::fs::File;
use tokio::sync::broadcast;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
pub(crate) fn finish_driver_spawn(driver: ProcessDriver, stdin_open: bool) -> SpawnedProcess {
let spawned = spawn_from_driver(driver);
if !stdin_open {
spawned.session.close_stdin();
}
spawned
}
pub(crate) fn start_runner_pipe_writer(
mut pipe_write: File,
) -> std::sync::mpsc::Sender<FramedMessage> {
let (outbound_tx, outbound_rx) = std::sync::mpsc::channel::<FramedMessage>();
tokio::task::spawn_blocking(move || {
while let Ok(msg) = outbound_rx.recv() {
if crate::ipc_framed::write_frame(&mut pipe_write, &msg).is_err() {
break;
}
}
});
outbound_tx
}
pub(crate) fn start_runner_stdin_writer(
mut writer_rx: mpsc::Receiver<Vec<u8>>,
outbound_tx: std::sync::mpsc::Sender<FramedMessage>,
normalize_newlines: bool,
stdin_open: bool,
) -> tokio::task::JoinHandle<()> {
tokio::task::spawn_blocking(move || {
let mut windows_input = WindowsTtyInputNormalizer::default();
while let Some(bytes) = writer_rx.blocking_recv() {
let bytes = if normalize_newlines {
windows_input.normalize(&bytes)
} else {
bytes
};
let msg = FramedMessage {
version: IPC_PROTOCOL_VERSION,
message: Message::Stdin {
payload: StdinPayload {
data_b64: encode_bytes(&bytes),
},
},
};
if outbound_tx.send(msg).is_err() {
break;
}
}
if stdin_open {
let _ = outbound_tx.send(FramedMessage {
version: IPC_PROTOCOL_VERSION,
message: Message::CloseStdin {
payload: EmptyPayload::default(),
},
});
}
})
}
pub(crate) fn start_runner_stdout_reader(
mut pipe_read: File,
stdout_tx: broadcast::Sender<Vec<u8>>,
stderr_tx: Option<broadcast::Sender<Vec<u8>>>,
exit_tx: oneshot::Sender<i32>,
) {
std::thread::spawn(move || {
let exit = loop {
let msg = match crate::ipc_framed::read_frame(&mut pipe_read) {
Ok(Some(v)) => v,
Ok(None) => {
send_runner_error(
"runner pipe closed before exit",
&stdout_tx,
stderr_tx.as_ref(),
);
break None;
}
Err(err) => {
send_runner_error(
&format!("runner read failed: {err}"),
&stdout_tx,
stderr_tx.as_ref(),
);
break None;
}
};
match msg.message {
Message::Output { payload } => {
if let Ok(data) = decode_bytes(&payload.data_b64) {
match payload.stream {
OutputStream::Stdout => {
let _ = stdout_tx.send(data);
}
OutputStream::Stderr => {
if let Some(stderr_tx) = stderr_tx.as_ref() {
let _ = stderr_tx.send(data);
} else {
let _ = stdout_tx.send(data);
}
}
}
}
}
Message::Exit { payload } => {
break Some((payload.exit_code, payload.timed_out));
}
Message::Error { payload } => {
send_runner_error(&payload.message, &stdout_tx, stderr_tx.as_ref());
break None;
}
Message::SpawnReady { .. }
| Message::Stdin { .. }
| Message::CloseStdin { .. }
| Message::Resize { .. }
| Message::SpawnRequest { .. }
| Message::Terminate { .. } => {}
}
};
crate::elevated::runner_metrics::record_command(exit);
let _ = exit_tx.send(exit.map_or(-1, |(code, _)| code));
});
}
pub(crate) fn make_runner_resizer(
outbound_tx: std::sync::mpsc::Sender<FramedMessage>,
) -> Box<dyn FnMut(TerminalSize) -> Result<()> + Send> {
Box::new(move |size: TerminalSize| {
outbound_tx
.send(FramedMessage {
version: IPC_PROTOCOL_VERSION,
message: Message::Resize {
payload: ResizePayload {
rows: size.rows,
cols: size.cols,
},
},
})
.map_err(|_| anyhow::anyhow!("runner resize pipe closed"))
})
}
fn send_runner_error(
message: &str,
stdout_tx: &broadcast::Sender<Vec<u8>>,
stderr_tx: Option<&broadcast::Sender<Vec<u8>>>,
) {
let formatted = format!("runner error: {message}\n").into_bytes();
if let Some(stderr_tx) = stderr_tx {
let _ = stderr_tx.send(formatted);
} else {
let _ = stdout_tx.send(formatted);
}
}
#[cfg(test)]
#[path = "windows_common_tests.rs"]
mod tests;

View File

@@ -0,0 +1,34 @@
//! The result-metric hook must preserve terminal exit codes and pipe-failure behavior.
use super::*;
use crate::ipc_framed::ExitPayload;
use crate::ipc_framed::write_frame;
use pretty_assertions::assert_eq;
use std::io::Seek;
#[test]
fn runner_result_reporting_preserves_exit_and_closed_pipe_results() -> Result<()> {
for exit_code in [Some(0), Some(23), None] {
let mut frames = tempfile::tempfile()?;
if let Some(exit_code) = exit_code {
write_frame(
&mut frames,
&FramedMessage {
version: IPC_PROTOCOL_VERSION,
message: Message::Exit {
payload: ExitPayload {
exit_code,
timed_out: false,
},
},
},
)?;
}
frames.rewind()?;
let (stdout_tx, _stdout_rx) = broadcast::channel(1);
let (exit_tx, exit_rx) = oneshot::channel();
start_runner_stdout_reader(frames, stdout_tx, /*stderr_tx*/ None, exit_tx);
assert_eq!(exit_rx.blocking_recv()?, exit_code.unwrap_or(-1));
}
Ok(())
}

Some files were not shown because too many files have changed in this diff Show More