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
This commit is contained in:
zm-oai authored and copyberry committed 2026-09-13 04:59:49 +00:00
1 parent a592c38c16
commit dfaf451426
17 files changed
+301 -243

No files matched your search

-2
View File
@@ -5220,8 +5220,6 @@ dependencies = [
"codex-config", "codex-config",
"codex-core", "codex-core",
"codex-windows-sandbox", "codex-windows-sandbox",
"serde",
"serde_json",
"tokio", "tokio",
"toml 0.9.11+spec-1.1.0", "toml 0.9.11+spec-1.1.0",
"windows 0.58.0", "windows 0.58.0",
@@ -1,9 +1,6 @@
#[cfg(target_os = "windows")]
mod win;
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
fn main() -> anyhow::Result<()> { fn main() -> anyhow::Result<()> {
win::main() codex_windows_sandbox::setup_helper_main()
} }
#[cfg(not(target_os = "windows"))] #[cfg(not(target_os = "windows"))]
@@ -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<DesktopInstallation>,
}
pub fn load() -> 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(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::<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 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::<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")
}
}
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"),
}
}
+20
View File
@@ -79,6 +79,8 @@ mod hide_users;
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
mod identity; mod identity;
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
mod installation_record;
#[cfg(target_os = "windows")]
mod logging; mod logging;
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
mod no_reparse_dir; mod no_reparse_dir;
@@ -134,6 +136,13 @@ mod setup_launch;
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
mod setup_mutex; 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")] #[cfg(target_os = "windows")]
mod spawn_prep; mod spawn_prep;
@@ -154,6 +163,17 @@ pub(crate) use elevated::runner_client;
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
pub(crate) use elevated::runner_pipe; 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")] #[cfg(target_os = "windows")]
pub use acl::add_deny_read_ace; pub use acl::add_deny_read_ace;
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
@@ -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 firewall;
mod read_acl_mutex; 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::Context;
use anyhow::Result; use anyhow::Result;
use base64::Engine; use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64; use base64::engine::general_purpose::STANDARD as BASE64;
use codex_otel::StatsigMetricsSettings; 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::Deserialize;
use serde::Serialize; use serde::Serialize;
use std::collections::HashSet; use std::collections::HashSet;
@@ -1117,7 +1120,7 @@ fn run_setup_full(payload: &Payload, log: &mut dyn Write, sbx_dir: &Path) -> Res
} }
#[cfg(test)] #[cfg(test)]
#[path = "win_acl_tests.rs"] #[path = "setup_provisioning/acl_tests.rs"]
mod acl_tests; mod acl_tests;
#[cfg(test)] #[cfg(test)]
@@ -1127,13 +1130,13 @@ mod tests {
use super::WRITE_ROOT_ALLOW_MASK; use super::WRITE_ROOT_ALLOW_MASK;
use super::convert_string_sid_to_sid; use super::convert_string_sid_to_sid;
use super::workspace_write_cap_sids_for_path; 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_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 pretty_assertions::assert_eq;
use serde_json::json; use serde_json::json;
use std::fs; use std::fs;
@@ -12,9 +12,9 @@ use super::lock_sandbox_bin_dir;
use super::lock_sandbox_dir; use super::lock_sandbox_dir;
use super::resolve_sid; use super::resolve_sid;
use super::sid_bytes_to_psid; use super::sid_bytes_to_psid;
use codex_windows_sandbox::ensure_allow_write_aces; use crate::ensure_allow_write_aces;
use codex_windows_sandbox::path_mask_allows; use crate::path_mask_allows;
use codex_windows_sandbox::workspace_write_cap_sid_for_root; use crate::workspace_write_cap_sid_for_root;
use std::fs; use std::fs;
use windows_sys::Win32::Foundation::HLOCAL; use windows_sys::Win32::Foundation::HLOCAL;
use windows_sys::Win32::Foundation::LocalFree; use windows_sys::Win32::Foundation::LocalFree;
@@ -26,8 +26,8 @@ use windows::Win32::System::Com::CoUninitialize;
use windows::core::BSTR; use windows::core::BSTR;
use windows::core::Interface; use windows::core::Interface;
use codex_windows_sandbox::SetupErrorCode; use crate::SetupErrorCode;
use codex_windows_sandbox::SetupFailure; use crate::SetupFailure;
// This is the stable identifier we use to find/update the rule idempotently. // This is the stable identifier we use to find/update the rule idempotently.
// It intentionally does not change between installs. // It intentionally does not change between installs.
@@ -1,5 +1,5 @@
use crate::to_wide;
use anyhow::Result; use anyhow::Result;
use codex_windows_sandbox::to_wide;
use std::ffi::OsStr; use std::ffi::OsStr;
use windows_sys::Win32::Foundation::CloseHandle; use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::Foundation::ERROR_ALREADY_EXISTS; use windows_sys::Win32::Foundation::ERROR_ALREADY_EXISTS;
@@ -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::CreateFileW;
use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_NORMAL; use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_NORMAL;
use codex_windows_sandbox::SANDBOX_USERS_GROUP; use crate::SANDBOX_USERS_GROUP;
use codex_windows_sandbox::SETUP_VERSION; use crate::SETUP_VERSION;
use codex_windows_sandbox::SetupErrorCode; use crate::SetupErrorCode;
use codex_windows_sandbox::SetupFailure; use crate::SetupFailure;
use codex_windows_sandbox::dpapi_protect; use crate::dpapi_protect;
use codex_windows_sandbox::ensure_sandbox_users_group; use crate::ensure_sandbox_users_group;
use codex_windows_sandbox::resolve_sid; use crate::resolve_sid;
use codex_windows_sandbox::sandbox_dir; use crate::sandbox_dir;
use codex_windows_sandbox::sandbox_secrets_dir; use crate::sandbox_secrets_dir;
use codex_windows_sandbox::string_from_sid_bytes; use crate::string_from_sid_bytes;
use codex_windows_sandbox::to_wide; use crate::to_wide;
use codex_windows_sandbox::write_file_atomically; use crate::write_file_atomically;
use super::SetupMode; use super::SetupMode;
@@ -3,9 +3,9 @@ use std::io::Write;
use std::os::windows::fs::MetadataExt as _; use std::os::windows::fs::MetadataExt as _;
use std::path::PathBuf; use std::path::PathBuf;
use crate::ensure_allow_mask_aces_with_inheritance;
use crate::path_mask_allows;
use anyhow::Result; 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::CONTAINER_INHERIT_ACE;
use windows_sys::Win32::Security::OBJECT_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_ATTRIBUTE_REPARSE_POINT;
@@ -22,8 +22,6 @@ codex-cloud-config = { workspace = true }
codex-config = { workspace = true } codex-config = { workspace = true }
codex-core = { workspace = true } codex-core = { workspace = true }
codex-windows-sandbox = { workspace = true } codex-windows-sandbox = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt", "sync", "time"] } tokio = { workspace = true, features = ["macros", "rt", "sync", "time"] }
toml = { workspace = true } toml = { workspace = true }
@@ -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::ffi::OsString;
use std::io; use std::io;
use std::mem::size_of;
use std::os::windows::ffi::OsStringExt; use std::os::windows::ffi::OsStringExt;
use std::path::Path; use std::path::Path;
use std::path::PathBuf; use std::path::PathBuf;
@@ -10,36 +9,17 @@ use std::ptr;
use anyhow::Context; use anyhow::Context;
use anyhow::Result; use anyhow::Result;
use anyhow::ensure; pub(crate) use codex_windows_sandbox::DesktopInstallation;
use codex_windows_sandbox::to_wide; 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 codex_windows_sandbox::validate_local_directory_path;
use serde::Deserialize;
use serde::Serialize;
use windows_sys::Win32::Foundation as foundation; use windows_sys::Win32::Foundation as foundation;
use windows_sys::Win32::System::Registry as registry;
use windows_sys::Win32::UI::Shell::GetUserProfileDirectoryW; 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"; 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<DesktopInstallation>,
}
// Read this app-owned marker while impersonating the authenticated user. The // 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. // desktop writes it only when creating the home. Cache cleanup does not need ownership.
pub(crate) fn read_desktop_installation( pub(crate) fn read_desktop_installation(
@@ -60,80 +40,3 @@ pub(crate) fn read_desktop_installation(
cache_home, cache_home,
}) })
} }
pub(crate) fn load() -> 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(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::<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(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::<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")
}
}
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"),
}
}
+2 -64
View File
@@ -10,14 +10,13 @@ mod request;
use anyhow::Context; use anyhow::Context;
use anyhow::Result; use anyhow::Result;
use anyhow::bail; use anyhow::bail;
pub(crate) use authentication::ClientIdentity;
use authentication::authenticate_client; use authentication::authenticate_client;
use codex_windows_sandbox::FramedProvisioningMessage; use codex_windows_sandbox::FramedProvisioningMessage;
use codex_windows_sandbox::PROVISIONING_PROTOCOL_VERSION; use codex_windows_sandbox::PROVISIONING_PROTOCOL_VERSION;
use codex_windows_sandbox::ProvisioningMessage; use codex_windows_sandbox::ProvisioningMessage;
use codex_windows_sandbox::SandboxProvisioningResponse; use codex_windows_sandbox::SandboxProvisioningResponse;
use codex_windows_sandbox::ensure_sandbox_users_group; 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::string_from_sid_bytes;
use codex_windows_sandbox::to_wide; use codex_windows_sandbox::to_wide;
use codex_windows_sandbox::write_provisioning_frame; use codex_windows_sandbox::write_provisioning_frame;
@@ -27,8 +26,6 @@ pub(crate) use home::pin_existing_ancestors;
use request::ProvisioningRequest; use request::ProvisioningRequest;
use request::validate_request; use request::validate_request;
use std::mem::size_of; use std::mem::size_of;
use std::os::windows::fs::MetadataExt;
use std::os::windows::io::BorrowedHandle;
use std::ptr; use std::ptr;
use std::sync::Arc; use std::sync::Arc;
use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicBool;
@@ -338,66 +335,7 @@ fn handle_request(
return Err(error) return Err(error)
.context("requested sandbox settings violate administrator-controlled machine policy"); .context("requested sandbox settings violate administrator-controlled machine policy");
} }
// A policy-rejected request must not choose the uninstall owner. Use the crate::provisioning::run(identity, request.settings, on_authenticated_user)
// 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::<Vec<_>>();
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")
}
}
} }
fn is_config_parse_error(error: &anyhow::Error) -> bool { fn is_config_parse_error(error: &anyhow::Error) -> bool {
@@ -18,15 +18,15 @@ use super::home::OwnedHandle;
use super::home::prepare_codex_home; use super::home::prepare_codex_home;
use super::request::ProvisioningRequest; use super::request::ProvisioningRequest;
pub(super) struct ClientIdentity { pub(crate) struct ClientIdentity {
pub(super) account: String, pub(crate) account: String,
pub(super) codex_home: PathBuf, pub(crate) codex_home: PathBuf,
pub(super) user_sid: String, pub(crate) user_sid: String,
pub(super) session_id: u32, pub(crate) session_id: u32,
pub(super) token: OwnedHandle, pub(crate) token: OwnedHandle,
pub(super) desktop_installation: Option<crate::installation_record::DesktopInstallation>, pub(crate) desktop_installation: Option<crate::installation_record::DesktopInstallation>,
// Retained by both the service and helper throughout provisioning. // Retained by both the service and helper throughout provisioning.
pub(super) directory_handles: Vec<OwnedHandle>, pub(crate) directory_handles: Vec<OwnedHandle>,
} }
pub(super) fn authenticate_client( pub(super) fn authenticate_client(
@@ -11,6 +11,8 @@ mod package_identity;
#[cfg(windows)] #[cfg(windows)]
mod package_lifecycle; mod package_lifecycle;
#[cfg(windows)] #[cfg(windows)]
mod provisioning;
#[cfg(windows)]
mod service; mod service;
#[derive(Clone, Copy, Debug, Eq, PartialEq)] #[derive(Clone, Copy, Debug, Eq, PartialEq)]
@@ -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<SandboxProvisioningResponse> {
// 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::<Vec<_>>();
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")
}
}
}