From dfaf451426868c22e6859f5494150fd6338c3257 Mon Sep 17 00:00:00 2001 From: zm-oai Date: Sun, 13 Sep 2026 04:49:45 +0000 Subject: [PATCH] Extract Windows sandbox setup and installation storage into the library (#45169) ## What changed - Move the setup helper implementation and its existing tests into `codex-windows-sandbox`, with the binary delegating to `setup_helper_main`. - Expose installation record types and storage operations from the library, preserving the registry key, size limit, and serialization format. Reuse them in the service and remove its direct `serde` dependencies. - Extract service provisioning from IPC handling into a dedicated module, preserving authentication and machine-policy checks before provisioning and retaining directory handles through helper execution. GitOrigin-RevId: dd1ea015aff901d5dfe39b395de1971ee0f2d33f --- codex-rs/Cargo.lock | 2 - .../src/bin/setup_main/main.rs | 5 +- .../src/installation_record.rs | 114 ++++++++++++++++++ codex-rs/windows-sandbox-rs/src/lib.rs | 20 +++ .../win.rs => setup_provisioning.rs} | 83 +++++++------ .../acl_tests.rs} | 6 +- .../win => setup_provisioning}/firewall.rs | 4 +- .../read_acl_mutex.rs | 2 +- .../sandbox_users.rs | 24 ++-- .../setup_runtime_bin.rs | 4 +- .../setup_runtime_bin_tests.rs | 0 codex-rs/windows-sandbox-service/Cargo.toml | 2 - .../src/installation_record.rs | 109 +---------------- codex-rs/windows-sandbox-service/src/ipc.rs | 66 +--------- .../src/ipc/authentication.rs | 16 +-- codex-rs/windows-sandbox-service/src/lib.rs | 2 + .../src/provisioning.rs | 85 +++++++++++++ 17 files changed, 301 insertions(+), 243 deletions(-) create mode 100644 codex-rs/windows-sandbox-rs/src/installation_record.rs rename codex-rs/windows-sandbox-rs/src/{bin/setup_main/win.rs => setup_provisioning.rs} (96%) rename codex-rs/windows-sandbox-rs/src/{bin/setup_main/win_acl_tests.rs => setup_provisioning/acl_tests.rs} (96%) rename codex-rs/windows-sandbox-rs/src/{bin/setup_main/win => setup_provisioning}/firewall.rs (99%) rename codex-rs/windows-sandbox-rs/src/{bin/setup_main/win => setup_provisioning}/read_acl_mutex.rs (98%) rename codex-rs/windows-sandbox-rs/src/{bin/setup_main/win => setup_provisioning}/sandbox_users.rs (96%) rename codex-rs/windows-sandbox-rs/src/{bin/setup_main/win => setup_provisioning}/setup_runtime_bin.rs (97%) rename codex-rs/windows-sandbox-rs/src/{bin/setup_main/win => setup_provisioning}/setup_runtime_bin_tests.rs (100%) create mode 100644 codex-rs/windows-sandbox-service/src/provisioning.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 36b8370e30..1743ce5901 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -5220,8 +5220,6 @@ dependencies = [ "codex-config", "codex-core", "codex-windows-sandbox", - "serde", - "serde_json", "tokio", "toml 0.9.11+spec-1.1.0", "windows 0.58.0", diff --git a/codex-rs/windows-sandbox-rs/src/bin/setup_main/main.rs b/codex-rs/windows-sandbox-rs/src/bin/setup_main/main.rs index 262460775e..0f2ff98dee 100644 --- a/codex-rs/windows-sandbox-rs/src/bin/setup_main/main.rs +++ b/codex-rs/windows-sandbox-rs/src/bin/setup_main/main.rs @@ -1,9 +1,6 @@ -#[cfg(target_os = "windows")] -mod win; - #[cfg(target_os = "windows")] fn main() -> anyhow::Result<()> { - win::main() + codex_windows_sandbox::setup_helper_main() } #[cfg(not(target_os = "windows"))] diff --git a/codex-rs/windows-sandbox-rs/src/installation_record.rs b/codex-rs/windows-sandbox-rs/src/installation_record.rs new file mode 100644 index 0000000000..3a065cd615 --- /dev/null +++ b/codex-rs/windows-sandbox-rs/src/installation_record.rs @@ -0,0 +1,114 @@ +//! 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::winutil::to_wide; + +// Package updates can replace the service key, so keep this record outside it. +const INSTALLATION_KEY: &str = r"SOFTWARE\OpenAI\Codex\WindowsSandboxService"; +const INSTALLATION_VALUE: &str = "ProvisionedInstallation"; +const MAX_VALUE_UNITS: usize = 4096; + +#[derive(Clone, Deserialize, Serialize)] +pub struct DesktopInstallation { + pub created_codex_home: bool, + pub cache_home: PathBuf, +} + +#[derive(Clone, Deserialize, Serialize)] +pub struct InstallationRecord { + pub user_sid: String, + pub codex_home: PathBuf, + pub session_id: u32, + #[serde(default)] + pub desktop_installation: Option, +} + +pub fn load() -> Result> { + 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(INSTALLATION_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::() as u32), + "sandbox installation record has an invalid length" + ); + let value = value[..value_length as usize / size_of::()] + .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 fn save(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(INSTALLATION_KEY).as_ptr(), + to_wide(INSTALLATION_VALUE).as_ptr(), + registry::REG_SZ, + value.as_ptr().cast(), + (value.len() * size_of::()) 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") + } +} + +pub fn remove() -> Result<()> { + let status = unsafe { + registry::RegDeleteKeyW( + registry::HKEY_LOCAL_MACHINE, + to_wide(INSTALLATION_KEY).as_ptr(), + ) + }; + match status { + foundation::ERROR_SUCCESS + | foundation::ERROR_FILE_NOT_FOUND + | foundation::ERROR_PATH_NOT_FOUND => Ok(()), + status => Err(io::Error::from_raw_os_error(status as i32)) + .context("remove protected sandbox installation record"), + } +} diff --git a/codex-rs/windows-sandbox-rs/src/lib.rs b/codex-rs/windows-sandbox-rs/src/lib.rs index e83a42a59f..d943182790 100644 --- a/codex-rs/windows-sandbox-rs/src/lib.rs +++ b/codex-rs/windows-sandbox-rs/src/lib.rs @@ -79,6 +79,8 @@ mod hide_users; #[cfg(target_os = "windows")] mod identity; #[cfg(target_os = "windows")] +mod installation_record; +#[cfg(target_os = "windows")] mod logging; #[cfg(target_os = "windows")] mod no_reparse_dir; @@ -134,6 +136,13 @@ mod setup_launch; #[cfg(target_os = "windows")] mod setup_mutex; +#[cfg(target_os = "windows")] +mod setup_provisioning; + +#[cfg(target_os = "windows")] +#[doc(hidden)] +pub use setup_provisioning::main as setup_helper_main; + #[cfg(target_os = "windows")] mod spawn_prep; @@ -154,6 +163,17 @@ pub(crate) use elevated::runner_client; #[cfg(target_os = "windows")] pub(crate) use elevated::runner_pipe; +#[cfg(target_os = "windows")] +pub use installation_record::DesktopInstallation; +#[cfg(target_os = "windows")] +pub use installation_record::InstallationRecord; +#[cfg(target_os = "windows")] +pub use installation_record::load as load_sandbox_installation; +#[cfg(target_os = "windows")] +pub use installation_record::remove as remove_sandbox_installation; +#[cfg(target_os = "windows")] +pub use installation_record::save as save_sandbox_installation; + #[cfg(target_os = "windows")] pub use acl::add_deny_read_ace; #[cfg(target_os = "windows")] diff --git a/codex-rs/windows-sandbox-rs/src/bin/setup_main/win.rs b/codex-rs/windows-sandbox-rs/src/setup_provisioning.rs similarity index 96% rename from codex-rs/windows-sandbox-rs/src/bin/setup_main/win.rs rename to codex-rs/windows-sandbox-rs/src/setup_provisioning.rs index 93fe742006..2f7c0c9542 100644 --- a/codex-rs/windows-sandbox-rs/src/bin/setup_main/win.rs +++ b/codex-rs/windows-sandbox-rs/src/setup_provisioning.rs @@ -1,44 +1,47 @@ +//! Implements the Windows setup helper behind its shared library entrypoint. +//! Payload validation and all provisioning modes retain the helper contract. + mod firewall; mod read_acl_mutex; +use crate::DirectoryOpenDisposition; +use crate::SETUP_VERSION; +use crate::SetupErrorCode; +use crate::SetupErrorReport; +use crate::SetupFailure; +use crate::acquire_sandbox_setup_lock; +use crate::add_deny_write_ace; +use crate::convert_string_sid_to_sid; +use crate::ensure_allow_mask_aces_with_inheritance; +use crate::ensure_allow_write_aces; +use crate::extract_setup_failure; +use crate::hide_newly_created_users; +use crate::install_wfp_filters; +use crate::local_user_flags; +use crate::log_note; +use crate::log_writer; +use crate::open_directory_no_reparse; +use crate::path_mask_allows; +use crate::path_write_aces_need_refresh; +use crate::resolve_sid; +use crate::sandbox_bin_dir; +use crate::sandbox_dir; +use crate::sandbox_secrets_dir; +use crate::set_local_user_flags; +use crate::setup_error_path; +use crate::setup_log_writer; +use crate::string_from_sid_bytes; +use crate::sync_persistent_deny_read_acls; +use crate::to_wide; +use crate::workspace_write_cap_sid_for_root; +use crate::workspace_write_root_overlaps_path; +use crate::write_file_atomically; +use crate::write_setup_error_report; use anyhow::Context; use anyhow::Result; use base64::Engine; use base64::engine::general_purpose::STANDARD as BASE64; use codex_otel::StatsigMetricsSettings; -use codex_windows_sandbox::DirectoryOpenDisposition; -use codex_windows_sandbox::SETUP_VERSION; -use codex_windows_sandbox::SetupErrorCode; -use codex_windows_sandbox::SetupErrorReport; -use codex_windows_sandbox::SetupFailure; -use codex_windows_sandbox::acquire_sandbox_setup_lock; -use codex_windows_sandbox::add_deny_write_ace; -use codex_windows_sandbox::convert_string_sid_to_sid; -use codex_windows_sandbox::ensure_allow_mask_aces_with_inheritance; -use codex_windows_sandbox::ensure_allow_write_aces; -use codex_windows_sandbox::extract_setup_failure; -use codex_windows_sandbox::hide_newly_created_users; -use codex_windows_sandbox::install_wfp_filters; -use codex_windows_sandbox::local_user_flags; -use codex_windows_sandbox::log_note; -use codex_windows_sandbox::log_writer; -use codex_windows_sandbox::open_directory_no_reparse; -use codex_windows_sandbox::path_mask_allows; -use codex_windows_sandbox::path_write_aces_need_refresh; -use codex_windows_sandbox::resolve_sid; -use codex_windows_sandbox::sandbox_bin_dir; -use codex_windows_sandbox::sandbox_dir; -use codex_windows_sandbox::sandbox_secrets_dir; -use codex_windows_sandbox::set_local_user_flags; -use codex_windows_sandbox::setup_error_path; -use codex_windows_sandbox::setup_log_writer; -use codex_windows_sandbox::string_from_sid_bytes; -use codex_windows_sandbox::sync_persistent_deny_read_acls; -use codex_windows_sandbox::to_wide; -use codex_windows_sandbox::workspace_write_cap_sid_for_root; -use codex_windows_sandbox::workspace_write_root_overlaps_path; -use codex_windows_sandbox::write_file_atomically; -use codex_windows_sandbox::write_setup_error_report; use serde::Deserialize; use serde::Serialize; use std::collections::HashSet; @@ -1117,7 +1120,7 @@ fn run_setup_full(payload: &Payload, log: &mut dyn Write, sbx_dir: &Path) -> Res } #[cfg(test)] -#[path = "win_acl_tests.rs"] +#[path = "setup_provisioning/acl_tests.rs"] mod acl_tests; #[cfg(test)] @@ -1127,13 +1130,13 @@ mod tests { use super::WRITE_ROOT_ALLOW_MASK; use super::convert_string_sid_to_sid; use super::workspace_write_cap_sids_for_path; + use crate::ensure_allow_mask_aces; + use crate::ensure_allow_write_aces; + use crate::load_or_create_cap_sids; + use crate::path_mask_allows; + use crate::path_write_aces_need_refresh; + use crate::workspace_write_cap_sid_for_root; use codex_otel::StatsigMetricsSettings; - use codex_windows_sandbox::ensure_allow_mask_aces; - use codex_windows_sandbox::ensure_allow_write_aces; - use codex_windows_sandbox::load_or_create_cap_sids; - use codex_windows_sandbox::path_mask_allows; - use codex_windows_sandbox::path_write_aces_need_refresh; - use codex_windows_sandbox::workspace_write_cap_sid_for_root; use pretty_assertions::assert_eq; use serde_json::json; use std::fs; diff --git a/codex-rs/windows-sandbox-rs/src/bin/setup_main/win_acl_tests.rs b/codex-rs/windows-sandbox-rs/src/setup_provisioning/acl_tests.rs similarity index 96% rename from codex-rs/windows-sandbox-rs/src/bin/setup_main/win_acl_tests.rs rename to codex-rs/windows-sandbox-rs/src/setup_provisioning/acl_tests.rs index df39cfdd18..3ed99ad927 100644 --- a/codex-rs/windows-sandbox-rs/src/bin/setup_main/win_acl_tests.rs +++ b/codex-rs/windows-sandbox-rs/src/setup_provisioning/acl_tests.rs @@ -12,9 +12,9 @@ use super::lock_sandbox_bin_dir; use super::lock_sandbox_dir; use super::resolve_sid; use super::sid_bytes_to_psid; -use codex_windows_sandbox::ensure_allow_write_aces; -use codex_windows_sandbox::path_mask_allows; -use codex_windows_sandbox::workspace_write_cap_sid_for_root; +use crate::ensure_allow_write_aces; +use crate::path_mask_allows; +use crate::workspace_write_cap_sid_for_root; use std::fs; use windows_sys::Win32::Foundation::HLOCAL; use windows_sys::Win32::Foundation::LocalFree; diff --git a/codex-rs/windows-sandbox-rs/src/bin/setup_main/win/firewall.rs b/codex-rs/windows-sandbox-rs/src/setup_provisioning/firewall.rs similarity index 99% rename from codex-rs/windows-sandbox-rs/src/bin/setup_main/win/firewall.rs rename to codex-rs/windows-sandbox-rs/src/setup_provisioning/firewall.rs index a2e3b27fac..bb7c0fced0 100644 --- a/codex-rs/windows-sandbox-rs/src/bin/setup_main/win/firewall.rs +++ b/codex-rs/windows-sandbox-rs/src/setup_provisioning/firewall.rs @@ -26,8 +26,8 @@ use windows::Win32::System::Com::CoUninitialize; use windows::core::BSTR; use windows::core::Interface; -use codex_windows_sandbox::SetupErrorCode; -use codex_windows_sandbox::SetupFailure; +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. diff --git a/codex-rs/windows-sandbox-rs/src/bin/setup_main/win/read_acl_mutex.rs b/codex-rs/windows-sandbox-rs/src/setup_provisioning/read_acl_mutex.rs similarity index 98% rename from codex-rs/windows-sandbox-rs/src/bin/setup_main/win/read_acl_mutex.rs rename to codex-rs/windows-sandbox-rs/src/setup_provisioning/read_acl_mutex.rs index a96b6a5024..7954826bd4 100644 --- a/codex-rs/windows-sandbox-rs/src/bin/setup_main/win/read_acl_mutex.rs +++ b/codex-rs/windows-sandbox-rs/src/setup_provisioning/read_acl_mutex.rs @@ -1,5 +1,5 @@ +use crate::to_wide; use anyhow::Result; -use codex_windows_sandbox::to_wide; use std::ffi::OsStr; use windows_sys::Win32::Foundation::CloseHandle; use windows_sys::Win32::Foundation::ERROR_ALREADY_EXISTS; diff --git a/codex-rs/windows-sandbox-rs/src/bin/setup_main/win/sandbox_users.rs b/codex-rs/windows-sandbox-rs/src/setup_provisioning/sandbox_users.rs similarity index 96% rename from codex-rs/windows-sandbox-rs/src/bin/setup_main/win/sandbox_users.rs rename to codex-rs/windows-sandbox-rs/src/setup_provisioning/sandbox_users.rs index 698d7e1cc7..fbc9e1d30a 100644 --- a/codex-rs/windows-sandbox-rs/src/bin/setup_main/win/sandbox_users.rs +++ b/codex-rs/windows-sandbox-rs/src/setup_provisioning/sandbox_users.rs @@ -38,18 +38,18 @@ 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 codex_windows_sandbox::SANDBOX_USERS_GROUP; -use codex_windows_sandbox::SETUP_VERSION; -use codex_windows_sandbox::SetupErrorCode; -use codex_windows_sandbox::SetupFailure; -use codex_windows_sandbox::dpapi_protect; -use codex_windows_sandbox::ensure_sandbox_users_group; -use codex_windows_sandbox::resolve_sid; -use codex_windows_sandbox::sandbox_dir; -use codex_windows_sandbox::sandbox_secrets_dir; -use codex_windows_sandbox::string_from_sid_bytes; -use codex_windows_sandbox::to_wide; -use codex_windows_sandbox::write_file_atomically; +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; diff --git a/codex-rs/windows-sandbox-rs/src/bin/setup_main/win/setup_runtime_bin.rs b/codex-rs/windows-sandbox-rs/src/setup_provisioning/setup_runtime_bin.rs similarity index 97% rename from codex-rs/windows-sandbox-rs/src/bin/setup_main/win/setup_runtime_bin.rs rename to codex-rs/windows-sandbox-rs/src/setup_provisioning/setup_runtime_bin.rs index 176ef07504..f2c16a8705 100644 --- a/codex-rs/windows-sandbox-rs/src/bin/setup_main/win/setup_runtime_bin.rs +++ b/codex-rs/windows-sandbox-rs/src/setup_provisioning/setup_runtime_bin.rs @@ -3,9 +3,9 @@ use std::io::Write; use std::os::windows::fs::MetadataExt as _; use std::path::PathBuf; +use crate::ensure_allow_mask_aces_with_inheritance; +use crate::path_mask_allows; use anyhow::Result; -use codex_windows_sandbox::ensure_allow_mask_aces_with_inheritance; -use codex_windows_sandbox::path_mask_allows; 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; diff --git a/codex-rs/windows-sandbox-rs/src/bin/setup_main/win/setup_runtime_bin_tests.rs b/codex-rs/windows-sandbox-rs/src/setup_provisioning/setup_runtime_bin_tests.rs similarity index 100% rename from codex-rs/windows-sandbox-rs/src/bin/setup_main/win/setup_runtime_bin_tests.rs rename to codex-rs/windows-sandbox-rs/src/setup_provisioning/setup_runtime_bin_tests.rs diff --git a/codex-rs/windows-sandbox-service/Cargo.toml b/codex-rs/windows-sandbox-service/Cargo.toml index 29deeddfb5..12595b9a8f 100644 --- a/codex-rs/windows-sandbox-service/Cargo.toml +++ b/codex-rs/windows-sandbox-service/Cargo.toml @@ -22,8 +22,6 @@ codex-cloud-config = { workspace = true } codex-config = { workspace = true } codex-core = { workspace = true } codex-windows-sandbox = { workspace = true } -serde = { workspace = true } -serde_json = { workspace = true } tokio = { workspace = true, features = ["macros", "rt", "sync", "time"] } toml = { workspace = true } diff --git a/codex-rs/windows-sandbox-service/src/installation_record.rs b/codex-rs/windows-sandbox-service/src/installation_record.rs index 769626bab8..bd77701cf3 100644 --- a/codex-rs/windows-sandbox-service/src/installation_record.rs +++ b/codex-rs/windows-sandbox-service/src/installation_record.rs @@ -1,8 +1,7 @@ -//! Persists the authenticated sandbox owner across service restarts and package updates. +//! Finds desktop-created directory ownership; storage is shared with sandbox setup. use std::ffi::OsString; use std::io; -use std::mem::size_of; use std::os::windows::ffi::OsStringExt; use std::path::Path; use std::path::PathBuf; @@ -10,36 +9,17 @@ use std::ptr; use anyhow::Context; use anyhow::Result; -use anyhow::ensure; -use codex_windows_sandbox::to_wide; +pub(crate) use codex_windows_sandbox::DesktopInstallation; +pub(crate) use codex_windows_sandbox::InstallationRecord; +pub(crate) use codex_windows_sandbox::load_sandbox_installation as load; +pub(crate) use codex_windows_sandbox::remove_sandbox_installation as remove; +pub(crate) use codex_windows_sandbox::save_sandbox_installation as save; use codex_windows_sandbox::validate_local_directory_path; -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::GetUserProfileDirectoryW; -// Package updates can replace the service key, so keep this record outside it. -const INSTALLATION_KEY: &str = r"SOFTWARE\OpenAI\Codex\WindowsSandboxService"; -const INSTALLATION_VALUE: &str = "ProvisionedInstallation"; -const MAX_VALUE_UNITS: usize = 4096; const DESKTOP_INSTALLATION_MARKER: &str = ".desktop-created"; -#[derive(Clone, Deserialize, Serialize)] -pub(crate) struct DesktopInstallation { - pub(crate) created_codex_home: bool, - pub(crate) cache_home: PathBuf, -} - -#[derive(Clone, Deserialize, Serialize)] -pub(crate) struct InstallationRecord { - pub(crate) user_sid: String, - pub(crate) codex_home: PathBuf, - pub(crate) session_id: u32, - #[serde(default)] - pub(crate) desktop_installation: Option, -} - // Read this app-owned marker while impersonating the authenticated user. The // desktop writes it only when creating the home. Cache cleanup does not need ownership. pub(crate) fn read_desktop_installation( @@ -60,80 +40,3 @@ pub(crate) fn read_desktop_installation( cache_home, }) } - -pub(crate) fn load() -> Result> { - 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(INSTALLATION_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::() as u32), - "sandbox installation record has an invalid length" - ); - let value = value[..value_length as usize / size_of::()] - .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(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(INSTALLATION_KEY).as_ptr(), - to_wide(INSTALLATION_VALUE).as_ptr(), - registry::REG_SZ, - value.as_ptr().cast(), - (value.len() * size_of::()) 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") - } -} - -pub(crate) fn remove() -> Result<()> { - let status = unsafe { - registry::RegDeleteKeyW( - registry::HKEY_LOCAL_MACHINE, - to_wide(INSTALLATION_KEY).as_ptr(), - ) - }; - match status { - foundation::ERROR_SUCCESS - | foundation::ERROR_FILE_NOT_FOUND - | foundation::ERROR_PATH_NOT_FOUND => Ok(()), - status => Err(io::Error::from_raw_os_error(status as i32)) - .context("remove protected sandbox installation record"), - } -} diff --git a/codex-rs/windows-sandbox-service/src/ipc.rs b/codex-rs/windows-sandbox-service/src/ipc.rs index 22c34ece14..59f4437acc 100644 --- a/codex-rs/windows-sandbox-service/src/ipc.rs +++ b/codex-rs/windows-sandbox-service/src/ipc.rs @@ -10,14 +10,13 @@ mod request; use anyhow::Context; use anyhow::Result; use anyhow::bail; +pub(crate) use authentication::ClientIdentity; use authentication::authenticate_client; use codex_windows_sandbox::FramedProvisioningMessage; use codex_windows_sandbox::PROVISIONING_PROTOCOL_VERSION; use codex_windows_sandbox::ProvisioningMessage; use codex_windows_sandbox::SandboxProvisioningResponse; use codex_windows_sandbox::ensure_sandbox_users_group; -use codex_windows_sandbox::run_elevated_provisioning_setup_with_retained_handles; -use codex_windows_sandbox::sandbox_setup_is_complete_with_settings; use codex_windows_sandbox::string_from_sid_bytes; use codex_windows_sandbox::to_wide; use codex_windows_sandbox::write_provisioning_frame; @@ -27,8 +26,6 @@ pub(crate) use home::pin_existing_ancestors; use request::ProvisioningRequest; use request::validate_request; use std::mem::size_of; -use std::os::windows::fs::MetadataExt; -use std::os::windows::io::BorrowedHandle; use std::ptr; use std::sync::Arc; use std::sync::atomic::AtomicBool; @@ -338,66 +335,7 @@ fn handle_request( return Err(error) .context("requested sandbox settings violate administrator-controlled machine policy"); } - // A policy-rejected request must not choose the uninstall owner. Use the - // token already authenticated above instead of impersonating the pipe again. - let previous = crate::installation_record::load()?.filter(|record| { - record.user_sid == identity.user_sid && record.codex_home == identity.codex_home - }); - let installation = InstallationRecord { - codex_home: identity.codex_home.clone(), - user_sid: identity.user_sid, - session_id: identity.session_id, - desktop_installation: previous - .and_then(|record| record.desktop_installation) - .or(identity.desktop_installation), - }; - on_authenticated_user(&installation, identity.token)?; - if sandbox_setup_is_complete_with_settings(&identity.codex_home, &request.settings) { - crate::service::record_provisioned_user(&installation)?; - return Ok(SandboxProvisioningResponse::Ok); - } - let helper = std::env::current_exe() - .context("locate the provisioning service executable")? - .with_file_name("codex-windows-sandbox-setup.exe"); - let helper_metadata = helper - .symlink_metadata() - .with_context(|| format!("inspect packaged setup helper {}", helper.display()))?; - if !helper_metadata.is_file() - || helper_metadata.file_attributes() & filesystem::FILE_ATTRIBUTE_REPARSE_POINT != 0 - { - bail!( - "refusing invalid packaged setup helper {}", - helper.display() - ); - } - let retained_handles = identity - .directory_handles - .iter() - // The identity owns these handles through the synchronous helper launch and wait. - .map(|handle| unsafe { BorrowedHandle::borrow_raw(handle.0 as _) }) - .collect::>(); - match run_elevated_provisioning_setup_with_retained_handles( - &identity.codex_home, - &identity.account, - request.settings, - &retained_handles, - ) { - Ok(()) => { - crate::service::record_provisioned_user(&installation)?; - crate::service::log_information( - crate::service::EVENT_PROVISIONING_SUCCEEDED, - "Codex sandbox provisioning completed successfully.", - ); - Ok(SandboxProvisioningResponse::Ok) - } - Err(error) => { - crate::service::log_error( - crate::service::EVENT_PROVISIONING_FAILED, - &format!("Codex sandbox provisioning failed: {error}"), - ); - Err(error).context("sandbox provisioning failed") - } - } + crate::provisioning::run(identity, request.settings, on_authenticated_user) } fn is_config_parse_error(error: &anyhow::Error) -> bool { diff --git a/codex-rs/windows-sandbox-service/src/ipc/authentication.rs b/codex-rs/windows-sandbox-service/src/ipc/authentication.rs index ca7c761d53..6ffd837130 100644 --- a/codex-rs/windows-sandbox-service/src/ipc/authentication.rs +++ b/codex-rs/windows-sandbox-service/src/ipc/authentication.rs @@ -18,15 +18,15 @@ use super::home::OwnedHandle; use super::home::prepare_codex_home; use super::request::ProvisioningRequest; -pub(super) struct ClientIdentity { - pub(super) account: String, - pub(super) codex_home: PathBuf, - pub(super) user_sid: String, - pub(super) session_id: u32, - pub(super) token: OwnedHandle, - pub(super) desktop_installation: Option, +pub(crate) struct ClientIdentity { + pub(crate) account: String, + pub(crate) codex_home: PathBuf, + pub(crate) user_sid: String, + pub(crate) session_id: u32, + pub(crate) token: OwnedHandle, + pub(crate) desktop_installation: Option, // Retained by both the service and helper throughout provisioning. - pub(super) directory_handles: Vec, + pub(crate) directory_handles: Vec, } pub(super) fn authenticate_client( diff --git a/codex-rs/windows-sandbox-service/src/lib.rs b/codex-rs/windows-sandbox-service/src/lib.rs index 67177a3783..dab4992ced 100644 --- a/codex-rs/windows-sandbox-service/src/lib.rs +++ b/codex-rs/windows-sandbox-service/src/lib.rs @@ -11,6 +11,8 @@ mod package_identity; #[cfg(windows)] mod package_lifecycle; #[cfg(windows)] +mod provisioning; +#[cfg(windows)] mod service; #[derive(Clone, Copy, Debug, Eq, PartialEq)] diff --git a/codex-rs/windows-sandbox-service/src/provisioning.rs b/codex-rs/windows-sandbox-service/src/provisioning.rs new file mode 100644 index 0000000000..4ed8e7190e --- /dev/null +++ b/codex-rs/windows-sandbox-service/src/provisioning.rs @@ -0,0 +1,85 @@ +//! Runs provisioning after IPC has authenticated the owner and checked machine policy. +//! The authenticated token and directory pins retain their existing helper lifetimes. + +use std::os::windows::fs::MetadataExt; +use std::os::windows::io::BorrowedHandle; + +use anyhow::Context; +use anyhow::Result; +use anyhow::bail; +use codex_windows_sandbox::SandboxProvisioningResponse; +use codex_windows_sandbox::WindowsSandboxProvisioningSettings; +use codex_windows_sandbox::run_elevated_provisioning_setup_with_retained_handles; +use codex_windows_sandbox::sandbox_setup_is_complete_with_settings; +use windows_sys::Win32::Storage::FileSystem as filesystem; + +use crate::installation_record::InstallationRecord; +use crate::ipc::ClientIdentity; +use crate::ipc::OwnedHandle; + +pub(crate) fn run( + identity: ClientIdentity, + settings: WindowsSandboxProvisioningSettings, + on_authenticated_user: &dyn Fn(&InstallationRecord, OwnedHandle) -> Result<()>, +) -> Result { + // A policy-rejected request must not choose the uninstall owner. Use the + // token already authenticated above instead of impersonating the pipe again. + let previous = crate::installation_record::load()?.filter(|record| { + record.user_sid == identity.user_sid && record.codex_home == identity.codex_home + }); + let installation = InstallationRecord { + codex_home: identity.codex_home.clone(), + user_sid: identity.user_sid, + session_id: identity.session_id, + desktop_installation: previous + .and_then(|record| record.desktop_installation) + .or(identity.desktop_installation), + }; + on_authenticated_user(&installation, identity.token)?; + if sandbox_setup_is_complete_with_settings(&identity.codex_home, &settings) { + crate::service::record_provisioned_user(&installation)?; + return Ok(SandboxProvisioningResponse::Ok); + } + let helper = std::env::current_exe() + .context("locate the provisioning service executable")? + .with_file_name("codex-windows-sandbox-setup.exe"); + let helper_metadata = helper + .symlink_metadata() + .with_context(|| format!("inspect packaged setup helper {}", helper.display()))?; + if !helper_metadata.is_file() + || helper_metadata.file_attributes() & filesystem::FILE_ATTRIBUTE_REPARSE_POINT != 0 + { + bail!( + "refusing invalid packaged setup helper {}", + helper.display() + ); + } + let retained_handles = identity + .directory_handles + .iter() + // The identity owns these handles through the synchronous helper launch and wait. + .map(|handle| unsafe { BorrowedHandle::borrow_raw(handle.0 as _) }) + .collect::>(); + match run_elevated_provisioning_setup_with_retained_handles( + &identity.codex_home, + &identity.account, + settings, + &retained_handles, + ) { + Ok(()) => { + crate::service::record_provisioned_user(&installation)?; + crate::service::log_information( + crate::service::EVENT_PROVISIONING_SUCCEEDED, + "Codex sandbox provisioning completed successfully.", + ); + Ok(SandboxProvisioningResponse::Ok) + } + Err(error) => { + crate::service::log_error( + crate::service::EVENT_PROVISIONING_FAILED, + &format!("Codex sandbox provisioning failed: {error}"), + ); + Err(error).context("sandbox provisioning failed") + } + } +}