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,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<DesktopInstallation>,
}
// 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<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::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::<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")
}
}
crate::provisioning::run(identity, request.settings, on_authenticated_user)
}
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::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<crate::installation_record::DesktopInstallation>,
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<crate::installation_record::DesktopInstallation>,
// 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(
@@ -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)]
@@ -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")
}
}
}