Refactor Windows sandbox setup and service helpers (#45455)

## What changed

- Extract helper copying, token-user SID queries, provisioning pipe ownership, and service runtime lifecycle into dedicated modules.
- Simplify command-runner resolution and extract setup configuration loading, payload execution, provisioning request exchange, and response handling into helpers.
- Parameterize installation-record registry access and return the saved installation record from authenticated user registration.

## Testing

Add tests for explicit setup `cwd` selection and effective workspace roots, plus valid and invalid token-user SID queries. Move existing helper-copy and freshness tests alongside the extracted copy implementation.

GitOrigin-RevId: ffb39adae7611baa95e85c89f9a31ef7a779e217
This commit is contained in:
zm-oai authored and copyberry committed 2026-09-14 16:05:40 +00:00
1 parent 7a48b95c6c
commit 1a02867bd1
19 files changed
+640 -486

No files matched your search

+76 -110
View File
@@ -5,6 +5,7 @@
mod authentication;
mod home;
mod listener;
mod request;
use anyhow::Context;
@@ -16,8 +17,6 @@ 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::string_from_sid_bytes;
use codex_windows_sandbox::to_wide;
use codex_windows_sandbox::write_provisioning_frame;
pub(crate) use home::OwnedHandle;
@@ -36,8 +35,6 @@ use std::time::Duration;
use std::time::Instant;
use windows_sys::Win32::Foundation as foundation;
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::Security as security;
use windows_sys::Win32::Security::Authorization as authorization;
use windows_sys::Win32::Storage::FileSystem as filesystem;
use windows_sys::Win32::System::Pipes as pipes;
@@ -62,14 +59,6 @@ impl std::fmt::Display for ServiceUnavailable {
impl std::error::Error for ServiceUnavailable {}
struct SecurityDescriptor(security::PSECURITY_DESCRIPTOR);
impl Drop for SecurityDescriptor {
fn drop(&mut self) {
unsafe { foundation::LocalFree(self.0 as foundation::HLOCAL) };
}
}
#[derive(Debug, Eq, PartialEq)]
enum PipeConnection {
Connected,
@@ -79,54 +68,14 @@ enum PipeConnection {
pub(crate) fn run(
shutdown: Arc<AtomicBool>,
on_ready: impl FnOnce() -> Result<()>,
register_installation: impl Fn(InstallationRecord, OwnedHandle) -> Result<()>,
register_installation: impl Fn(InstallationRecord, OwnedHandle) -> Result<InstallationRecord>,
on_session_change: impl Fn() -> Result<()>,
) -> Result<()> {
let sandbox_sid = ensure_sandbox_users_group()?;
let sid_string = string_from_sid_bytes(&sandbox_sid).map_err(anyhow::Error::msg)?;
let sddl = pipe_security_descriptor(&sid_string);
let mut descriptor: security::PSECURITY_DESCRIPTOR = ptr::null_mut();
if unsafe {
authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW(
to_wide(sddl).as_ptr(),
authorization::SDDL_REVISION_1,
&mut descriptor,
ptr::null_mut(),
)
} == 0
{
return Err(std::io::Error::last_os_error()).context("create provisioning pipe DACL");
}
let descriptor = SecurityDescriptor(descriptor);
let attributes = security::SECURITY_ATTRIBUTES {
nLength: size_of::<security::SECURITY_ATTRIBUTES>() as u32,
lpSecurityDescriptor: descriptor.0,
bInheritHandle: 0,
};
let pipe = unsafe {
pipes::CreateNamedPipeW(
to_wide(PIPE_NAME).as_ptr(),
filesystem::PIPE_ACCESS_DUPLEX | filesystem::FILE_FLAG_FIRST_PIPE_INSTANCE,
pipes::PIPE_TYPE_BYTE
| pipes::PIPE_READMODE_BYTE
| pipes::PIPE_WAIT
| pipes::PIPE_REJECT_REMOTE_CLIENTS,
1,
1024,
MAX_REQUEST_BYTES as u32,
0,
&attributes,
)
};
if pipe == foundation::INVALID_HANDLE_VALUE {
return Err(std::io::Error::last_os_error()).context("create provisioning pipe");
}
let pipe = OwnedHandle(pipe);
let listener = listener::ProvisioningListener::open()?;
on_ready().context("publish provisioning listener readiness")?;
while !shutdown.load(Ordering::Acquire) {
let connection = accept_pipe_connection(pipe.0)?;
let connection = accept_pipe_connection(listener.pipe.0)?;
if shutdown.load(Ordering::Acquire) {
break;
}
@@ -136,17 +85,18 @@ pub(crate) fn run(
continue;
}
let authorized_process = match crate::package_identity::authorize_client_process(pipe.0) {
Ok(process) => process,
Err(_) => {
unsafe { pipes::DisconnectNamedPipe(pipe.0) };
continue;
}
};
let authorized_process =
match crate::package_identity::authorize_client_process(listener.pipe.0) {
Ok(process) => process,
Err(_) => {
unsafe { pipes::DisconnectNamedPipe(listener.pipe.0) };
continue;
}
};
let result = handle_request(
pipe.0,
listener.pipe.0,
&authorized_process,
&sandbox_sid,
&listener.sandbox_sid,
&shutdown,
&register_installation,
);
@@ -158,62 +108,78 @@ pub(crate) fn run(
}
Err(error) => {
eprintln!("sandbox provisioning request failed: {error}");
let mut message = String::new();
for character in error.to_string().chars() {
let character = if character.is_control() {
' '
} else {
character
};
if message.len() + character.len_utf8() > MAX_RESPONSE_MESSAGE_BYTES {
break;
}
message.push(character);
SandboxProvisioningResponse::Error {
message: response_error_message(&error),
}
SandboxProvisioningResponse::Error { message }
}
};
let response = FramedProvisioningMessage {
version: PROVISIONING_PROTOCOL_VERSION,
message: ProvisioningMessage::ProvisionSandboxResponse { payload: response },
};
let mut frame = Vec::new();
write_provisioning_frame(&mut frame, &response)
.context("serialize sandbox provisioning response")?;
let mut written = 0;
let sent = unsafe {
filesystem::WriteFile(
pipe.0,
frame.as_ptr(),
frame.len() as u32,
&mut written,
ptr::null_mut(),
)
};
if sent != 0 {
let deadline = Instant::now() + Duration::from_secs(1);
while !shutdown.load(Ordering::Acquire) && Instant::now() < deadline {
if unsafe {
pipes::PeekNamedPipe(
pipe.0,
ptr::null_mut(),
0,
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
)
} == 0
{
break;
}
std::thread::sleep(Duration::from_millis(10));
}
}
unsafe { pipes::DisconnectNamedPipe(pipe.0) };
write_response(&listener.pipe, &response, &shutdown)?;
unsafe { pipes::DisconnectNamedPipe(listener.pipe.0) };
}
Ok(())
}
/// Sends one frame, then waits briefly for the client to close before disconnecting.
fn write_response(
pipe: &OwnedHandle,
response: &FramedProvisioningMessage,
shutdown: &AtomicBool,
) -> Result<()> {
let mut frame = Vec::new();
write_provisioning_frame(&mut frame, response)
.context("serialize sandbox provisioning response")?;
let mut written = 0;
let sent = unsafe {
filesystem::WriteFile(
pipe.0,
frame.as_ptr(),
frame.len() as u32,
&mut written,
ptr::null_mut(),
)
};
if sent != 0 {
let deadline = Instant::now() + Duration::from_secs(1);
while !shutdown.load(Ordering::Acquire) && Instant::now() < deadline {
if unsafe {
pipes::PeekNamedPipe(
pipe.0,
ptr::null_mut(),
0,
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
)
} == 0
{
break;
}
std::thread::sleep(Duration::from_millis(10));
}
}
Ok(())
}
fn response_error_message(error: &anyhow::Error) -> String {
let mut message = String::new();
for character in error.to_string().chars() {
let character = if character.is_control() {
' '
} else {
character
};
if message.len() + character.len_utf8() > MAX_RESPONSE_MESSAGE_BYTES {
break;
}
message.push(character);
}
message
}
fn accept_pipe_connection(pipe: HANDLE) -> Result<PipeConnection> {
if unsafe { pipes::ConnectNamedPipe(pipe, ptr::null_mut()) } != 0 {
return Ok(PipeConnection::Connected);
@@ -268,7 +234,7 @@ fn handle_request(
authorized_process: &crate::package_identity::AuthorizedClientProcess,
sandbox_sid: &[u8],
shutdown: &AtomicBool,
register_installation: &dyn Fn(InstallationRecord, OwnedHandle) -> Result<()>,
register_installation: &dyn Fn(InstallationRecord, OwnedHandle) -> Result<InstallationRecord>,
) -> Result<SandboxProvisioningResponse> {
let deadline = Instant::now() + REQUEST_IDLE_TIMEOUT;
let mut request = [0_u8; MAX_REQUEST_BYTES];
@@ -0,0 +1,91 @@
//! Owns the provisioning pipe and its security descriptor for the listener lifetime.
use anyhow::Context;
use anyhow::Result;
use codex_windows_sandbox::ensure_sandbox_users_group;
use codex_windows_sandbox::string_from_sid_bytes;
use codex_windows_sandbox::to_wide;
use std::mem::size_of;
use std::ptr;
use windows_sys::Win32::Foundation as foundation;
use windows_sys::Win32::Security as security;
use windows_sys::Win32::Security::Authorization as authorization;
use windows_sys::Win32::Storage::FileSystem as filesystem;
use windows_sys::Win32::System::Pipes as pipes;
use super::MAX_REQUEST_BYTES;
use super::OwnedHandle;
use super::pipe_security_descriptor;
pub(super) struct ProvisioningListener {
pub(super) pipe: OwnedHandle,
pub(super) sandbox_sid: Vec<u8>,
_descriptor: SecurityDescriptor,
}
impl ProvisioningListener {
pub(super) fn open() -> Result<Self> {
let sandbox_sid = ensure_sandbox_users_group()?;
let (descriptor, pipe) = create_provisioning_pipe(super::PIPE_NAME, &sandbox_sid)?;
Ok(Self {
pipe,
sandbox_sid,
_descriptor: descriptor,
})
}
}
struct SecurityDescriptor(security::PSECURITY_DESCRIPTOR);
impl Drop for SecurityDescriptor {
fn drop(&mut self) {
unsafe { foundation::LocalFree(self.0 as foundation::HLOCAL) };
}
}
/// Preserves the existing listener and descriptor lifetimes.
fn create_provisioning_pipe(
pipe_name: &str,
sandbox_sid: &[u8],
) -> Result<(SecurityDescriptor, OwnedHandle)> {
let sid_string = string_from_sid_bytes(sandbox_sid).map_err(anyhow::Error::msg)?;
let sddl = pipe_security_descriptor(&sid_string);
let mut descriptor: security::PSECURITY_DESCRIPTOR = ptr::null_mut();
if unsafe {
authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW(
to_wide(sddl).as_ptr(),
authorization::SDDL_REVISION_1,
&mut descriptor,
ptr::null_mut(),
)
} == 0
{
return Err(std::io::Error::last_os_error()).context("create provisioning pipe DACL");
}
let descriptor = SecurityDescriptor(descriptor);
let attributes = security::SECURITY_ATTRIBUTES {
nLength: size_of::<security::SECURITY_ATTRIBUTES>() as u32,
lpSecurityDescriptor: descriptor.0,
bInheritHandle: 0,
};
let pipe = unsafe {
pipes::CreateNamedPipeW(
to_wide(pipe_name).as_ptr(),
filesystem::PIPE_ACCESS_DUPLEX | filesystem::FILE_FLAG_FIRST_PIPE_INSTANCE,
pipes::PIPE_TYPE_BYTE
| pipes::PIPE_READMODE_BYTE
| pipes::PIPE_WAIT
| pipes::PIPE_REJECT_REMOTE_CLIENTS,
1,
1024,
MAX_REQUEST_BYTES as u32,
0,
&attributes,
)
};
if pipe == foundation::INVALID_HANDLE_VALUE {
return Err(std::io::Error::last_os_error()).context("create provisioning pipe");
}
Ok((descriptor, OwnedHandle(pipe)))
}
@@ -68,7 +68,7 @@ impl PackageLifecycle {
&self,
mut record: InstallationRecord,
user_token: OwnedHandle,
) -> Result<()> {
) -> Result<InstallationRecord> {
let mut active = self.installation.borrow_mut();
let previous = match active.as_ref() {
Some(installation) => Some(installation.record.clone()),
@@ -91,10 +91,11 @@ impl PackageLifecycle {
&& installation.codex_home.is_some()
{
// A restored watcher must immediately use newly registered desktop ownership.
installation.record = record;
return Ok(());
installation.record = record.clone();
return Ok(record);
}
let saved_record = record.clone();
with_owner_impersonation(user_token.0, || {
let mut directory_handles = Vec::new();
let codex_home = match crate::ipc::pin_existing_ancestors(
@@ -163,7 +164,8 @@ impl PackageLifecycle {
token,
});
Ok(())
})
})?;
Ok(saved_record)
}
pub(crate) fn restore_logged_in_owner(&self, recorded_session_id: u32) -> Result<()> {
@@ -231,6 +233,7 @@ impl PackageLifecycle {
},
token,
)
.map(|_| ())
}
pub(crate) fn clean_up(&self) -> Result<()> {
@@ -20,7 +20,7 @@ use crate::ipc::ServiceRequest;
pub(crate) fn run(
identity: ClientIdentity,
request: ServiceRequest,
register_installation: &dyn Fn(InstallationRecord, OwnedHandle) -> Result<()>,
register_installation: &dyn Fn(InstallationRecord, OwnedHandle) -> Result<InstallationRecord>,
) -> Result<SandboxProvisioningResponse> {
// A policy-rejected request must not choose the uninstall owner. Use the
// token already authenticated above instead of impersonating the pipe again.
+16 -51
View File
@@ -40,6 +40,8 @@ use windows_sys::Win32::System::Services::SERVICE_WIN32_OWN_PROCESS;
use windows_sys::Win32::System::Services::SetServiceStatus;
use windows_sys::Win32::System::Services::StartServiceCtrlDispatcherW;
mod runtime_lifecycle;
pub(crate) const SERVICE_NAME: &str = "CodexSandboxService";
const EVENT_SERVICE_STARTED: u32 = 1000;
const EVENT_SERVICE_STOP_REQUESTED: u32 = 1001;
@@ -109,7 +111,7 @@ pub(crate) fn run_foreground() -> Result<()> {
eprintln!("{SERVICE_NAME} listening on {}", crate::ipc::PIPE_NAME);
Ok(())
},
|_, _| Ok(()),
|installation, _| Ok(installation),
|| Ok(()),
)
}
@@ -156,46 +158,7 @@ fn service_main_inner(state: &ServiceState) -> Result<()> {
state.report_status(SERVICE_START_PENDING, NO_ERROR)?;
let package_lifecycle =
crate::package_lifecycle::PackageLifecycle::new(Arc::clone(&state.uninstalling))?;
crate::ipc::run(
Arc::clone(&state.shutdown),
|| {
state.report_status(SERVICE_RUNNING, NO_ERROR)?;
if let Some(record) = crate::installation_record::load()?
&& let Err(error) = package_lifecycle.restore_logged_in_owner(record.session_id)
{
log_error(
EVENT_SERVICE_FAILED,
&format!("unable to restore package uninstall listener: {error:#}"),
);
}
log_information(
EVENT_SERVICE_STARTED,
"The Codex sandbox service is running.",
);
Ok(())
},
|installation, user_token| {
package_lifecycle.register_authenticated_user(installation, user_token)
},
|| {
let session = state.changed_session.swap(u32::MAX, Ordering::AcqRel);
if session == u32::MAX {
return Ok(());
}
if let Err(error) = package_lifecycle.restore_authenticated_user(session) {
log_error(
EVENT_SERVICE_FAILED,
&format!("unable to restore package uninstall listener: {error:#}"),
);
}
Ok(())
},
)
.context("run the sandbox provisioning broker")?;
if state.stop_requested.load(Ordering::Acquire) && state.uninstalling.load(Ordering::Acquire) {
package_lifecycle.clean_up()?;
}
runtime_lifecycle::run(state, &package_lifecycle)?;
log_information(
EVENT_SERVICE_STOPPED,
"The Codex sandbox service has stopped.",
@@ -226,11 +189,7 @@ unsafe extern "system" fn service_control_handler(
EVENT_SERVICE_STOP_REQUESTED,
"The Codex sandbox service was asked to stop.",
);
std::thread::spawn(move || {
crate::ipc::wake(crate::ipc::PIPE_NAME, || {
state.current_status.load(Ordering::Acquire) == SERVICE_STOPPED
});
});
wake_listener();
}
NO_ERROR
}
@@ -252,11 +211,7 @@ unsafe extern "system" fn service_control_handler(
state
.changed_session
.store(event.dwSessionId, Ordering::Release);
std::thread::spawn(move || {
crate::ipc::wake(crate::ipc::PIPE_NAME, || {
state.current_status.load(Ordering::Acquire) == SERVICE_STOPPED
});
});
wake_listener();
}
}
NO_ERROR
@@ -265,6 +220,16 @@ unsafe extern "system" fn service_control_handler(
}
}
fn wake_listener() {
if let Some(state) = SERVICE_STATE.get() {
std::thread::spawn(move || {
crate::ipc::wake(crate::ipc::PIPE_NAME, || {
state.current_status.load(Ordering::Acquire) == SERVICE_STOPPED
});
});
}
}
pub(crate) fn log_information(event_id: u32, message: &str) {
log_event(EVENTLOG_INFORMATION_TYPE, event_id, message);
}
@@ -0,0 +1,60 @@
//! Connects the provisioning broker to the existing package owner and uninstall listener.
use std::sync::Arc;
use std::sync::atomic::Ordering;
use anyhow::Context;
use anyhow::Result;
use windows_sys::Win32::Foundation::NO_ERROR;
use windows_sys::Win32::System::Services::SERVICE_RUNNING;
use super::EVENT_SERVICE_FAILED;
use super::EVENT_SERVICE_STARTED;
use super::ServiceState;
use super::log_error;
use super::log_information;
use crate::package_lifecycle::PackageLifecycle;
pub(super) fn run(state: &ServiceState, package_lifecycle: &PackageLifecycle) -> Result<()> {
crate::ipc::run(
Arc::clone(&state.shutdown),
|| {
state.report_status(SERVICE_RUNNING, NO_ERROR)?;
if let Some(record) = crate::installation_record::load()?
&& let Err(error) = package_lifecycle.restore_logged_in_owner(record.session_id)
{
log_error(
EVENT_SERVICE_FAILED,
&format!("unable to restore package uninstall listener: {error:#}"),
);
}
log_information(
EVENT_SERVICE_STARTED,
"The Codex sandbox service is running.",
);
Ok(())
},
|installation, user_token| {
package_lifecycle.register_authenticated_user(installation, user_token)
},
|| {
let session = state.changed_session.swap(u32::MAX, Ordering::AcqRel);
if session == u32::MAX {
return Ok(());
}
if let Err(error) = package_lifecycle.restore_authenticated_user(session) {
log_error(
EVENT_SERVICE_FAILED,
&format!("unable to restore package uninstall listener: {error:#}"),
);
}
Ok(())
},
)
.context("run the sandbox provisioning broker")?;
if state.stop_requested.load(Ordering::Acquire) && state.uninstalling.load(Ordering::Acquire) {
package_lifecycle.clean_up()?;
}
Ok(())
}