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

@@ -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"))]
@@ -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")]
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")]
@@ -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;
@@ -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;
@@ -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.
@@ -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;
@@ -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;
@@ -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;