aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
14
akode-rs/windows-sandbox-service/BUILD.bazel
Normal file
14
akode-rs/windows-sandbox-service/BUILD.bazel
Normal file
@@ -0,0 +1,14 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
load("//bazel/rules:runtime_package.bzl", "release_binary")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "windows-sandbox-service",
|
||||
binary_test_target_compatible_with = ["@platforms//os:windows"],
|
||||
compile_data = ["src/registered_runtime/removal.ps1"],
|
||||
crate_name = "akode_windows_sandbox_service",
|
||||
)
|
||||
|
||||
release_binary(
|
||||
binary = ":akode-windows-sandbox-service",
|
||||
target_compatible_with = ["@platforms//os:windows"],
|
||||
)
|
||||
65
akode-rs/windows-sandbox-service/Cargo.toml
Normal file
65
akode-rs/windows-sandbox-service/Cargo.toml
Normal file
@@ -0,0 +1,65 @@
|
||||
[package]
|
||||
name = "akode-windows-sandbox-service"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lib]
|
||||
name = "akode_windows_sandbox_service"
|
||||
path = "src/lib.rs"
|
||||
doctest = false
|
||||
|
||||
[[bin]]
|
||||
name = "akode-windows-sandbox-service"
|
||||
path = "src/main.rs"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow = { workspace = true }
|
||||
akode-config = { workspace = true }
|
||||
akode-core = { workspace = true }
|
||||
akode-windows-sandbox = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
tokio = { workspace = true, features = ["macros", "rt", "sync", "time"] }
|
||||
toml = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
|
||||
[target.'cfg(windows)'.dependencies.windows]
|
||||
version = "0.58"
|
||||
features = [
|
||||
"ApplicationModel",
|
||||
"Foundation_Collections",
|
||||
"Management_Deployment",
|
||||
"Storage",
|
||||
"Win32_System_WinRT",
|
||||
]
|
||||
|
||||
[target.'cfg(windows)'.dependencies.windows-sys]
|
||||
workspace = true
|
||||
features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_NetworkManagement_NetManagement",
|
||||
"Win32_Security",
|
||||
"Win32_Security_Authorization",
|
||||
"Win32_Storage_FileSystem",
|
||||
"Win32_Storage_Packaging_Appx",
|
||||
"Win32_System_Com",
|
||||
"Win32_System_Environment",
|
||||
"Win32_System_EventLog",
|
||||
"Win32_System_IO",
|
||||
"Win32_System_JobObjects",
|
||||
"Win32_System_Memory",
|
||||
"Win32_System_Pipes",
|
||||
"Win32_System_Registry",
|
||||
"Win32_System_RemoteDesktop",
|
||||
"Win32_System_Services",
|
||||
"Win32_System_SystemServices",
|
||||
"Win32_System_SystemInformation",
|
||||
"Win32_System_Threading",
|
||||
"Win32_UI_Shell",
|
||||
]
|
||||
77
akode-rs/windows-sandbox-service/src/installation_record.rs
Normal file
77
akode-rs/windows-sandbox-service/src/installation_record.rs
Normal file
@@ -0,0 +1,77 @@
|
||||
//! Finds desktop-created directory ownership; storage is shared with sandbox setup.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::io;
|
||||
use std::os::windows::ffi::OsStringExt;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::ptr;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
pub(crate) use akode_windows_sandbox::CORE_INSTALLATION_KEY;
|
||||
pub(crate) use akode_windows_sandbox::DesktopInstallation;
|
||||
pub(crate) use akode_windows_sandbox::INSTALLATION_KEY;
|
||||
pub(crate) use akode_windows_sandbox::INSTALLATION_VALUE;
|
||||
pub(crate) use akode_windows_sandbox::InstallationRecord;
|
||||
pub(crate) use akode_windows_sandbox::RuntimeAccountRegistration;
|
||||
pub(crate) use akode_windows_sandbox::RuntimeRegistration;
|
||||
pub(crate) use akode_windows_sandbox::load_installation as load;
|
||||
pub(crate) use akode_windows_sandbox::remove_installation as remove;
|
||||
pub(crate) use akode_windows_sandbox::save_installation as save_runtime;
|
||||
use akode_windows_sandbox::validate_local_directory_path;
|
||||
use windows_sys::Win32::Foundation as foundation;
|
||||
use windows_sys::Win32::UI::Shell::GetUserProfileDirectoryW;
|
||||
|
||||
const DESKTOP_INSTALLATION_MARKER: &str = ".desktop-created";
|
||||
|
||||
// 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(
|
||||
home: &Path,
|
||||
user_token: foundation::HANDLE,
|
||||
) -> Result<DesktopInstallation> {
|
||||
let mut length = 0;
|
||||
unsafe { GetUserProfileDirectoryW(user_token, ptr::null_mut(), &mut length) };
|
||||
let mut profile = vec![0_u16; length as usize];
|
||||
if unsafe { GetUserProfileDirectoryW(user_token, profile.as_mut_ptr(), &mut length) } == 0 {
|
||||
return Err(io::Error::last_os_error()).context("read sandbox owner's profile directory");
|
||||
}
|
||||
let cache_home =
|
||||
PathBuf::from(OsString::from_wide(&profile[..length as usize - 1])).join(".cache");
|
||||
validate_local_directory_path(&cache_home)?;
|
||||
Ok(DesktopInstallation {
|
||||
created_codex_home: home.join(DESKTOP_INSTALLATION_MARKER).is_file(),
|
||||
cache_home,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn load_runtime() -> Result<Option<InstallationRecord>> {
|
||||
Ok(load()?.filter(|record| record.runtime.is_some()))
|
||||
}
|
||||
|
||||
pub(crate) fn is_current_package_family(record: &InstallationRecord) -> Result<bool> {
|
||||
Ok(record.runtime()?.package_family.eq_ignore_ascii_case(
|
||||
&windows::ApplicationModel::Package::Current()?
|
||||
.Id()?
|
||||
.FamilyName()?
|
||||
.to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn save(mut record: InstallationRecord) -> Result<InstallationRecord> {
|
||||
let _setup_lock = akode_windows_sandbox::acquire_sandbox_setup_lock(/*timeout_ms*/ 5_000)?;
|
||||
|
||||
record.runtime = None;
|
||||
if let Some(current) = load_runtime()? {
|
||||
let family = windows::ApplicationModel::Package::Current()?
|
||||
.Id()?
|
||||
.FamilyName()?;
|
||||
current.admit_owner(&record, &family.to_string())?;
|
||||
// The helper wait may have admitted another account. Preserve fresh Core
|
||||
// state instead of overwriting it with the caller's owner-only snapshot.
|
||||
record.runtime = current.runtime;
|
||||
}
|
||||
save_runtime(&record)?;
|
||||
Ok(record)
|
||||
}
|
||||
392
akode-rs/windows-sandbox-service/src/ipc.rs
Normal file
392
akode-rs/windows-sandbox-service/src/ipc.rs
Normal file
@@ -0,0 +1,392 @@
|
||||
//! Authenticated local IPC for the Windows sandbox provisioning service.
|
||||
//! Expected service limitations defer provisioning to the client's elevated helper;
|
||||
//! authentication and policy rejections remain errors.
|
||||
//! Shutdown wakeups are retried until the listener connects or stops.
|
||||
|
||||
mod authentication;
|
||||
mod home;
|
||||
mod listener;
|
||||
mod request;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
pub(crate) use authentication::ClientIdentity;
|
||||
use authentication::authenticate_client;
|
||||
use akode_windows_sandbox::FramedProvisioningMessage;
|
||||
use akode_windows_sandbox::PROVISIONING_PROTOCOL_VERSION;
|
||||
use akode_windows_sandbox::ProvisioningMessage;
|
||||
use akode_windows_sandbox::SandboxProvisioningResponse;
|
||||
use akode_windows_sandbox::to_wide;
|
||||
use akode_windows_sandbox::write_provisioning_frame;
|
||||
pub(crate) use home::pin_directory;
|
||||
pub(crate) use home::pin_existing_ancestors;
|
||||
pub(crate) use request::ProvisioningRequest;
|
||||
pub(crate) use request::ServiceRequest;
|
||||
use request::validate_request;
|
||||
use std::mem::size_of;
|
||||
use std::os::windows::io::AsHandle;
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::os::windows::io::BorrowedHandle;
|
||||
use std::os::windows::io::OwnedHandle;
|
||||
use std::ptr;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
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::Storage::FileSystem as filesystem;
|
||||
use windows_sys::Win32::System::Pipes as pipes;
|
||||
|
||||
use crate::installation_record::InstallationRecord;
|
||||
|
||||
const MAX_REQUEST_BYTES: usize = 4096;
|
||||
const MAX_RESPONSE_MESSAGE_BYTES: usize = 512;
|
||||
const REQUEST_IDLE_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const PIPE_USER_ACCESS: &str = "0x0012019b";
|
||||
|
||||
/// The service cannot complete this request; the interactive setup helper may still work.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ServiceUnavailable(pub(crate) &'static str);
|
||||
|
||||
impl std::fmt::Display for ServiceUnavailable {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter.write_str(self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ServiceUnavailable {}
|
||||
|
||||
#[derive(Debug, Eq, PartialEq)]
|
||||
enum PipeConnection {
|
||||
Connected,
|
||||
Disconnected,
|
||||
}
|
||||
|
||||
pub(crate) fn run(
|
||||
shutdown: Arc<AtomicBool>,
|
||||
on_ready: impl FnOnce() -> Result<()>,
|
||||
on_authenticated_user: impl Fn(
|
||||
InstallationRecord,
|
||||
OwnedHandle,
|
||||
akode_windows_sandbox::SetupRuntime,
|
||||
) -> Result<InstallationRecord>,
|
||||
on_session_change: impl Fn() -> Result<()>,
|
||||
) -> Result<()> {
|
||||
if shutdown.load(Ordering::Acquire) {
|
||||
return Ok(());
|
||||
}
|
||||
let mut listener = listener::ProvisioningListener::open()?;
|
||||
on_ready().context("publish provisioning listener readiness")?;
|
||||
|
||||
// Refresh before blocking even if a direct setup claim's zero-byte wake was lost.
|
||||
while refresh_session(&shutdown, &on_session_change)
|
||||
.context("refresh the recorded sandbox owner")?
|
||||
{
|
||||
let connection = accept_pipe_connection(listener.pipe.as_raw_handle())?;
|
||||
// A session refresh can finish cleanup. Never dispatch an already accepted
|
||||
// connection after it stops the listener, including a disconnected wakeup.
|
||||
if !refresh_session(&shutdown, &on_session_change)
|
||||
.context("restore the signed-in user's uninstall listener")?
|
||||
{
|
||||
break;
|
||||
}
|
||||
if connection == PipeConnection::Disconnected {
|
||||
continue;
|
||||
}
|
||||
|
||||
let authorized_process = match crate::package_identity::authorize_client_process(
|
||||
listener.pipe.as_raw_handle(),
|
||||
) {
|
||||
Ok(process) => process,
|
||||
Err(_) => {
|
||||
unsafe { pipes::DisconnectNamedPipe(listener.pipe.as_raw_handle()) };
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let result = handle_request(
|
||||
listener.pipe.as_handle(),
|
||||
&authorized_process,
|
||||
&listener.sandbox_sid,
|
||||
&shutdown,
|
||||
&on_authenticated_user,
|
||||
);
|
||||
let response = match result {
|
||||
Ok(response) => response,
|
||||
Err(error) if error.is::<crate::registered_runtime::RegistrationInterrupted>() => {
|
||||
return Err(error);
|
||||
}
|
||||
Err(error) if error.is::<ServiceUnavailable>() => {
|
||||
SandboxProvisioningResponse::Unavailable
|
||||
}
|
||||
Err(error) => {
|
||||
eprintln!("sandbox provisioning request failed: {error}");
|
||||
SandboxProvisioningResponse::Error {
|
||||
message: response_error_message(&error),
|
||||
}
|
||||
}
|
||||
};
|
||||
let response = FramedProvisioningMessage {
|
||||
version: PROVISIONING_PROTOCOL_VERSION,
|
||||
message: ProvisioningMessage::ProvisionSandboxResponse { payload: response },
|
||||
};
|
||||
write_response(&listener.pipe, &response, &shutdown)?;
|
||||
if shutdown.load(Ordering::Acquire) {
|
||||
break;
|
||||
}
|
||||
listener = listener.refresh()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn refresh_session(
|
||||
shutdown: &AtomicBool,
|
||||
on_session_change: impl FnOnce() -> Result<()>,
|
||||
) -> Result<bool> {
|
||||
if shutdown.load(Ordering::Acquire) {
|
||||
return Ok(false);
|
||||
}
|
||||
on_session_change()?;
|
||||
Ok(!shutdown.load(Ordering::Acquire))
|
||||
}
|
||||
|
||||
/// 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.as_raw_handle(),
|
||||
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.as_raw_handle(),
|
||||
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 format!("{error:#}").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);
|
||||
}
|
||||
|
||||
let error = unsafe { foundation::GetLastError() };
|
||||
match error {
|
||||
foundation::ERROR_PIPE_CONNECTED => Ok(PipeConnection::Connected),
|
||||
foundation::ERROR_NO_DATA | foundation::ERROR_BROKEN_PIPE => {
|
||||
if unsafe { pipes::DisconnectNamedPipe(pipe) } == 0 {
|
||||
let reset_error = std::io::Error::last_os_error();
|
||||
if reset_error.raw_os_error() != Some(foundation::ERROR_PIPE_NOT_CONNECTED as i32) {
|
||||
return Err(reset_error).context("reset disconnected provisioning client");
|
||||
}
|
||||
}
|
||||
Ok(PipeConnection::Disconnected)
|
||||
}
|
||||
_ => Err(std::io::Error::from_raw_os_error(error as i32))
|
||||
.context("accept provisioning client"),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn wake(pipe_name: &str, is_stopped: impl Fn() -> bool) {
|
||||
let pipe_name = to_wide(pipe_name);
|
||||
while !is_stopped() {
|
||||
let handle = unsafe {
|
||||
filesystem::CreateFileW(
|
||||
pipe_name.as_ptr(),
|
||||
foundation::GENERIC_WRITE,
|
||||
/*dwsharemode*/ 0,
|
||||
ptr::null(),
|
||||
filesystem::OPEN_EXISTING,
|
||||
/*dwflagsandattributes*/ 0,
|
||||
ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
if handle != foundation::INVALID_HANDLE_VALUE {
|
||||
unsafe { foundation::CloseHandle(handle) };
|
||||
return;
|
||||
}
|
||||
// A disconnected instance cannot accept the wakeup until ConnectNamedPipe runs.
|
||||
std::thread::sleep(Duration::from_millis(25));
|
||||
}
|
||||
}
|
||||
|
||||
fn pipe_security_descriptor(sandbox_sid: &str) -> String {
|
||||
format!("D:P(D;;GA;;;{sandbox_sid})(A;;GA;;;SY)(A;;GA;;;BA)(A;;{PIPE_USER_ACCESS};;;IU)")
|
||||
}
|
||||
|
||||
fn handle_request(
|
||||
pipe: BorrowedHandle<'_>,
|
||||
authorized_process: &crate::package_identity::AuthorizedClientProcess,
|
||||
sandbox_sid: &[u8],
|
||||
shutdown: &AtomicBool,
|
||||
on_authenticated_user: &dyn Fn(
|
||||
InstallationRecord,
|
||||
OwnedHandle,
|
||||
akode_windows_sandbox::SetupRuntime,
|
||||
) -> Result<InstallationRecord>,
|
||||
) -> Result<SandboxProvisioningResponse> {
|
||||
let deadline = Instant::now() + REQUEST_IDLE_TIMEOUT;
|
||||
let mut request = [0_u8; MAX_REQUEST_BYTES];
|
||||
let mut request_length = 0;
|
||||
loop {
|
||||
if shutdown.load(Ordering::Acquire) {
|
||||
bail!("service is stopping");
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
bail!("provisioning request timed out");
|
||||
}
|
||||
let mut available = 0;
|
||||
if unsafe {
|
||||
pipes::PeekNamedPipe(
|
||||
pipe.as_raw_handle(),
|
||||
ptr::null_mut(),
|
||||
0,
|
||||
ptr::null_mut(),
|
||||
&mut available,
|
||||
ptr::null_mut(),
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(std::io::Error::last_os_error()).context("inspect provisioning request");
|
||||
}
|
||||
if available as usize > MAX_REQUEST_BYTES - request_length {
|
||||
bail!("provisioning request exceeds size limit");
|
||||
}
|
||||
if available != 0 {
|
||||
let mut read = 0;
|
||||
if unsafe {
|
||||
filesystem::ReadFile(
|
||||
pipe.as_raw_handle(),
|
||||
request[request_length..].as_mut_ptr(),
|
||||
available,
|
||||
&mut read,
|
||||
ptr::null_mut(),
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(std::io::Error::last_os_error()).context("read provisioning request");
|
||||
}
|
||||
if read == 0 {
|
||||
bail!("provisioning client sent an empty request");
|
||||
}
|
||||
request_length += read as usize;
|
||||
let received = &request[..request_length];
|
||||
if received.len() >= size_of::<u32>() {
|
||||
let payload_length =
|
||||
u32::from_le_bytes([received[0], received[1], received[2], received[3]])
|
||||
as usize;
|
||||
if payload_length > MAX_REQUEST_BYTES - size_of::<u32>() {
|
||||
bail!("provisioning request exceeds size limit");
|
||||
}
|
||||
let frame_length = size_of::<u32>() + payload_length;
|
||||
if request_length > frame_length {
|
||||
bail!("provisioning requests must contain exactly one IPC frame");
|
||||
}
|
||||
if request_length == frame_length {
|
||||
break;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(25));
|
||||
}
|
||||
|
||||
let request = validate_request(&request[..request_length])?;
|
||||
let (identity, policy_result) =
|
||||
authenticate_client(pipe, authorized_process, sandbox_sid, &request)?;
|
||||
if let Err(error) = policy_result {
|
||||
if is_config_parse_error(&error) {
|
||||
return Ok(SandboxProvisioningResponse::Unavailable);
|
||||
}
|
||||
crate::service::log_error(
|
||||
crate::service::EVENT_REQUEST_REJECTED,
|
||||
&policy_rejection_diagnostic(&error),
|
||||
);
|
||||
return Err(error)
|
||||
.context("requested sandbox settings violate administrator-controlled machine policy");
|
||||
}
|
||||
crate::provisioning::run(
|
||||
identity,
|
||||
request,
|
||||
sandbox_sid,
|
||||
shutdown,
|
||||
on_authenticated_user,
|
||||
)
|
||||
}
|
||||
|
||||
fn policy_rejection_diagnostic(error: &anyhow::Error) -> String {
|
||||
// Only service-owned labels and typed codes belong in persistent events.
|
||||
// Parser wrappers can stringify entire config lines, including credentials.
|
||||
let stage = match error.to_string().as_str() {
|
||||
"start managed configuration runtime" => "runtime",
|
||||
"load bootstrap configuration" => "bootstrap",
|
||||
"load managed configuration" => "managed",
|
||||
"enforce managed provisioning requirements" => "enforce",
|
||||
_ => "unknown",
|
||||
};
|
||||
let detail = error.chain().find_map(|cause| {
|
||||
let io = cause.downcast_ref::<std::io::Error>();
|
||||
io.map(|io| format!("io={:?} win32={:?}", io.kind(), io.raw_os_error()))
|
||||
});
|
||||
let detail = detail.unwrap_or_else(|| "cause=unavailable".to_string());
|
||||
format!(
|
||||
"Codex sandbox provisioning was rejected by administrator policy: stage={stage} {detail}"
|
||||
)
|
||||
}
|
||||
|
||||
fn is_config_parse_error(error: &anyhow::Error) -> bool {
|
||||
error.chain().any(|cause| {
|
||||
cause.is::<toml::de::Error>()
|
||||
|| cause
|
||||
.downcast_ref::<std::io::Error>()
|
||||
.and_then(std::io::Error::get_ref)
|
||||
.is_some_and(<dyn std::error::Error + Send + Sync>::is::<toml::de::Error>)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "ipc_tests.rs"]
|
||||
mod tests;
|
||||
224
akode-rs/windows-sandbox-service/src/ipc/authentication.rs
Normal file
224
akode-rs/windows-sandbox-service/src/ipc/authentication.rs
Normal file
@@ -0,0 +1,224 @@
|
||||
//! Authenticates provisioning clients and validates impersonated machine policy.
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
use akode_windows_sandbox::DirectoryOpenDisposition;
|
||||
use akode_windows_sandbox::SetupRuntime;
|
||||
use akode_windows_sandbox::create_directory_guard;
|
||||
use akode_windows_sandbox::string_from_sid_bytes;
|
||||
use std::ffi::OsString;
|
||||
use std::ffi::c_void;
|
||||
use std::mem::size_of;
|
||||
use std::os::windows::ffi::OsStringExt;
|
||||
use std::os::windows::io::AsHandle;
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::os::windows::io::BorrowedHandle;
|
||||
use std::os::windows::io::FromRawHandle;
|
||||
use std::os::windows::io::OwnedHandle;
|
||||
use std::path::PathBuf;
|
||||
use windows_sys::Win32::Security as security;
|
||||
use windows_sys::Win32::Storage::FileSystem as filesystem;
|
||||
use windows_sys::Win32::System::Pipes as pipes;
|
||||
use windows_sys::Win32::System::Threading as threading;
|
||||
|
||||
use super::home::prepare_codex_home;
|
||||
use super::request::ServiceRequest;
|
||||
|
||||
pub(crate) struct ClientIdentity {
|
||||
pub(crate) account: String,
|
||||
pub(crate) codex_home: PathBuf,
|
||||
pub(crate) user_sid: String,
|
||||
pub(crate) session_id: u32,
|
||||
// The requested route, authenticated against the held client's installed image.
|
||||
pub(crate) runtime: SetupRuntime,
|
||||
pub(crate) token: OwnedHandle,
|
||||
pub(crate) desktop_installation: Option<crate::installation_record::DesktopInstallation>,
|
||||
// Pins and guards remain live through registration and the provisioning helper.
|
||||
pub(crate) directory_handles: Vec<OwnedHandle>,
|
||||
}
|
||||
|
||||
pub(super) fn authenticate_client(
|
||||
pipe: BorrowedHandle<'_>,
|
||||
authorized_process: &crate::package_identity::AuthorizedClientProcess,
|
||||
sandbox_sid: &[u8],
|
||||
request: &ServiceRequest,
|
||||
) -> Result<(ClientIdentity, Result<()>)> {
|
||||
std::thread::scope(|scope| {
|
||||
scope
|
||||
.spawn(|| {
|
||||
let identity = authenticate_impersonated_client(
|
||||
pipe,
|
||||
authorized_process,
|
||||
sandbox_sid,
|
||||
request,
|
||||
)?;
|
||||
let policy_result = match request {
|
||||
// Registration does not provision resources or change sandbox policy.
|
||||
ServiceRequest::RegisterInstallation { .. } => Ok(()),
|
||||
ServiceRequest::ProvisionSandbox(request) => {
|
||||
crate::machine_policy::validate_provisioning_request(
|
||||
&identity.codex_home,
|
||||
request,
|
||||
identity.token.as_raw_handle(),
|
||||
)
|
||||
}
|
||||
};
|
||||
Ok((identity, policy_result))
|
||||
})
|
||||
.join()
|
||||
.map_err(|_| anyhow::anyhow!("provisioning client authentication thread panicked"))?
|
||||
})
|
||||
}
|
||||
|
||||
fn authenticate_impersonated_client(
|
||||
pipe: BorrowedHandle<'_>,
|
||||
authorized_process: &crate::package_identity::AuthorizedClientProcess,
|
||||
sandbox_sid: &[u8],
|
||||
request: &ServiceRequest,
|
||||
) -> Result<ClientIdentity> {
|
||||
// Pin the group generation through identity capture.
|
||||
// Release this lock before the provisioning worker checks machine policy.
|
||||
let _setup_lock = akode_windows_sandbox::acquire_sandbox_setup_lock(/*timeout_ms*/ 5_000)?;
|
||||
anyhow::ensure!(
|
||||
akode_windows_sandbox::resolve_sid(akode_windows_sandbox::SANDBOX_USERS_GROUP)
|
||||
.is_ok_and(|current| current == sandbox_sid),
|
||||
akode_windows_sandbox::SANDBOX_GROUP_CHANGED
|
||||
);
|
||||
if unsafe { pipes::ImpersonateNamedPipeClient(pipe.as_raw_handle()) } == 0 {
|
||||
return Err(std::io::Error::last_os_error()).context("impersonate provisioning client");
|
||||
}
|
||||
let mut raw_token = std::ptr::null_mut();
|
||||
if unsafe {
|
||||
threading::OpenThreadToken(
|
||||
threading::GetCurrentThread(),
|
||||
security::TOKEN_QUERY | security::TOKEN_IMPERSONATE,
|
||||
1,
|
||||
&mut raw_token,
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(std::io::Error::last_os_error()).context("open provisioning client token");
|
||||
}
|
||||
// SAFETY: OpenThreadToken transferred this handle on success.
|
||||
let token = unsafe { OwnedHandle::from_raw_handle(raw_token) };
|
||||
crate::package_identity::authorize_client(authorized_process, token.as_raw_handle())
|
||||
.context("authorize the packaged Codex provisioning client")?;
|
||||
let mut session = 0_u32;
|
||||
let mut returned = 0_u32;
|
||||
if unsafe {
|
||||
security::GetTokenInformation(
|
||||
token.as_raw_handle(),
|
||||
security::TokenSessionId,
|
||||
(&raw mut session).cast(),
|
||||
size_of::<u32>() as u32,
|
||||
&mut returned,
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(std::io::Error::last_os_error()).context("read provisioning client session");
|
||||
}
|
||||
if session == 0 {
|
||||
bail!("non-interactive service accounts cannot request provisioning");
|
||||
}
|
||||
|
||||
let mut is_sandbox_member = 0;
|
||||
if unsafe {
|
||||
security::CheckTokenMembership(
|
||||
token.as_raw_handle(),
|
||||
sandbox_sid.as_ptr() as *mut c_void,
|
||||
&mut is_sandbox_member,
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(std::io::Error::last_os_error()).context("check sandbox group membership");
|
||||
}
|
||||
if is_sandbox_member != 0 {
|
||||
bail!("sandbox accounts cannot request provisioning");
|
||||
}
|
||||
|
||||
let user = unsafe { akode_windows_sandbox::get_user_sid_bytes(token.as_raw_handle()) }
|
||||
.context("read provisioning client identity")?;
|
||||
let user_sid = string_from_sid_bytes(&user).map_err(anyhow::Error::msg)?;
|
||||
let account = unsafe { akode_windows_sandbox::account_name_from_sid(user.as_ptr() as _) }
|
||||
.context("resolve provisioning client account")?;
|
||||
let runtime = crate::package_identity::authorize_setup_runtime(authorized_process, request)?;
|
||||
let requested_home = match request {
|
||||
ServiceRequest::RegisterInstallation { codex_home } => codex_home,
|
||||
ServiceRequest::ProvisionSandbox(request) => &request.codex_home,
|
||||
};
|
||||
let (codex_home, handles) = match request {
|
||||
ServiceRequest::ProvisionSandbox(request) => prepare_codex_home(
|
||||
requested_home,
|
||||
runtime,
|
||||
if request.refresh_only {
|
||||
DirectoryOpenDisposition::OpenExisting
|
||||
} else {
|
||||
DirectoryOpenDisposition::OpenOrCreate
|
||||
},
|
||||
)?,
|
||||
ServiceRequest::RegisterInstallation { .. } => {
|
||||
// Registration must not create the sandbox directories or change their ACLs.
|
||||
akode_windows_sandbox::validate_local_directory_path(requested_home)?;
|
||||
let mut handles = Vec::new();
|
||||
super::home::pin_existing_ancestors(requested_home, &mut handles)?;
|
||||
// Uninstall removes sandbox files as SYSTEM; read access cannot grant that authority.
|
||||
let home = super::home::pin_directory(
|
||||
requested_home,
|
||||
filesystem::FILE_ADD_FILE
|
||||
| filesystem::FILE_ADD_SUBDIRECTORY
|
||||
| filesystem::WRITE_DAC,
|
||||
DirectoryOpenDisposition::OpenExisting,
|
||||
)?;
|
||||
// Bind the guard to the authorized directory before resolving its pathname.
|
||||
let guard = create_directory_guard(home.as_handle())?;
|
||||
drop(super::home::pin_directory(
|
||||
requested_home,
|
||||
filesystem::FILE_READ_ATTRIBUTES,
|
||||
DirectoryOpenDisposition::OpenExisting,
|
||||
)?);
|
||||
// Preserve the authorized directory's literal name (including trailing dots).
|
||||
let mut buffer = vec![0_u16; 260];
|
||||
let path = loop {
|
||||
let length = unsafe {
|
||||
filesystem::GetFinalPathNameByHandleW(
|
||||
home.as_raw_handle(),
|
||||
buffer.as_mut_ptr(),
|
||||
buffer.len() as u32,
|
||||
filesystem::FILE_NAME_NORMALIZED | filesystem::VOLUME_NAME_DOS,
|
||||
)
|
||||
};
|
||||
if length == 0 {
|
||||
return Err(std::io::Error::last_os_error())
|
||||
.context("resolve authorized desktop home");
|
||||
}
|
||||
if (length as usize) < buffer.len() {
|
||||
break PathBuf::from(OsString::from_wide(&buffer[..length as usize]));
|
||||
}
|
||||
buffer.resize(length as usize, /*value*/ 0);
|
||||
};
|
||||
handles.push(home);
|
||||
handles.push(guard);
|
||||
(path, handles)
|
||||
}
|
||||
};
|
||||
let desktop_installation =
|
||||
crate::installation_record::read_desktop_installation(&codex_home, token.as_raw_handle())
|
||||
.inspect_err(|_| {
|
||||
crate::service::log_error(
|
||||
crate::service::EVENT_SERVICE_FAILED,
|
||||
"unable to read desktop directory ownership; preserving desktop directories",
|
||||
);
|
||||
})
|
||||
.ok();
|
||||
Ok(ClientIdentity {
|
||||
account,
|
||||
codex_home,
|
||||
user_sid,
|
||||
session_id: session,
|
||||
runtime,
|
||||
token,
|
||||
desktop_installation,
|
||||
directory_handles: handles,
|
||||
})
|
||||
}
|
||||
170
akode-rs/windows-sandbox-service/src/ipc/home.rs
Normal file
170
akode-rs/windows-sandbox-service/src/ipc/home.rs
Normal file
@@ -0,0 +1,170 @@
|
||||
//! Validates and pins local Codex home and sandbox directories, keeping sandbox
|
||||
//! leaves nonempty so they cannot become junctions during provisioning.
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
use akode_windows_sandbox::DirectoryOpenDisposition;
|
||||
use akode_windows_sandbox::SetupRuntime;
|
||||
use akode_windows_sandbox::create_directory_guard;
|
||||
use akode_windows_sandbox::open_directory_no_reparse;
|
||||
use akode_windows_sandbox::to_wide;
|
||||
use akode_windows_sandbox::validate_local_directory_path;
|
||||
use std::os::windows::fs::MetadataExt;
|
||||
use std::os::windows::io::AsHandle;
|
||||
use std::os::windows::io::OwnedHandle;
|
||||
use std::path::Component;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use windows_sys::Win32::Foundation as foundation;
|
||||
use windows_sys::Win32::Storage::FileSystem as filesystem;
|
||||
|
||||
use super::ServiceUnavailable;
|
||||
|
||||
const DRIVE_FIXED: u32 = 3;
|
||||
|
||||
pub(super) fn prepare_codex_home(
|
||||
requested: &Path,
|
||||
runtime: SetupRuntime,
|
||||
disposition: DirectoryOpenDisposition,
|
||||
) -> Result<(PathBuf, Vec<OwnedHandle>)> {
|
||||
let directory_count = match runtime {
|
||||
SetupRuntime::Registered => 3,
|
||||
SetupRuntime::Legacy => 4,
|
||||
};
|
||||
let mut handles = Vec::new();
|
||||
validate_local_directory_path(requested)?;
|
||||
let requested_root = requested
|
||||
.ancestors()
|
||||
.last()
|
||||
.context("find the root of the requested Codex home")?;
|
||||
if unsafe { filesystem::GetDriveTypeW(to_wide(requested_root.as_os_str()).as_ptr()) }
|
||||
!= DRIVE_FIXED
|
||||
{
|
||||
return Err(ServiceUnavailable("Codex home must be located on a fixed local drive").into());
|
||||
}
|
||||
let parent = requested
|
||||
.parent()
|
||||
.context("Codex home must have an existing parent directory")?;
|
||||
pin_existing_ancestors(parent, &mut handles)?;
|
||||
handles.push(pin_directory(
|
||||
requested,
|
||||
filesystem::FILE_READ_ATTRIBUTES,
|
||||
disposition,
|
||||
)?);
|
||||
let home = requested
|
||||
.canonicalize()
|
||||
.with_context(|| format!("canonicalize Codex home {}", requested.display()))?;
|
||||
validate_local_directory_path(&home)?;
|
||||
let root = home
|
||||
.ancestors()
|
||||
.last()
|
||||
.context("find the root of the requested Codex home")?;
|
||||
if unsafe { filesystem::GetDriveTypeW(to_wide(root.as_os_str()).as_ptr()) } != DRIVE_FIXED {
|
||||
return Err(ServiceUnavailable("Codex home must be located on a fixed local drive").into());
|
||||
}
|
||||
if home != requested {
|
||||
pin_existing_ancestors(&home, &mut handles)?;
|
||||
}
|
||||
let sandbox_bin = home.join(".sandbox-bin");
|
||||
for (index, directory) in [
|
||||
home.as_path(),
|
||||
&home.join(".sandbox"),
|
||||
&home.join(".sandbox-secrets"),
|
||||
&sandbox_bin,
|
||||
]
|
||||
.into_iter()
|
||||
.take(directory_count)
|
||||
.enumerate()
|
||||
{
|
||||
let mut access = filesystem::FILE_READ_ATTRIBUTES
|
||||
| filesystem::FILE_ADD_FILE
|
||||
| filesystem::FILE_ADD_SUBDIRECTORY;
|
||||
if index != 0 {
|
||||
access |= filesystem::WRITE_DAC;
|
||||
}
|
||||
let handle = pin_directory(directory, access, disposition)
|
||||
.map_err(|error| {
|
||||
// Older elevated installs omitted WRITE_DAC; let the interactive helper repair it.
|
||||
if directory == sandbox_bin.as_path()
|
||||
&& error.downcast_ref::<std::io::Error>().is_some_and(|error| {
|
||||
error.raw_os_error() == Some(foundation::ERROR_ACCESS_DENIED as i32)
|
||||
})
|
||||
{
|
||||
error.context(ServiceUnavailable("sandbox binary directory needs elevated repair"))
|
||||
} else {
|
||||
error
|
||||
}
|
||||
})
|
||||
.with_context(|| {
|
||||
if index == 0 {
|
||||
format!(
|
||||
"requesting user must be permitted to write Codex home {}",
|
||||
directory.display()
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"requesting user must be permitted to write and modify sandbox directory ACL {}",
|
||||
directory.display()
|
||||
)
|
||||
}
|
||||
})?;
|
||||
if index != 0 {
|
||||
let guard = create_directory_guard(handle.as_handle())?;
|
||||
// Reject conversion before guard creation; after creation the retained
|
||||
// file prevents this directory from becoming empty and being converted.
|
||||
drop(pin_directory(
|
||||
directory,
|
||||
filesystem::FILE_READ_ATTRIBUTES,
|
||||
DirectoryOpenDisposition::OpenExisting,
|
||||
)?);
|
||||
handles.push(guard);
|
||||
}
|
||||
handles.push(handle);
|
||||
if index == 0 {
|
||||
continue;
|
||||
}
|
||||
for entry in std::fs::read_dir(directory)? {
|
||||
let entry = entry?;
|
||||
let metadata = entry.path().symlink_metadata()?;
|
||||
if metadata.file_attributes() & filesystem::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
|
||||
bail!("refusing reparse point {}", entry.path().display());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Pinned parent handles prevent directory replacement, but existing helper file
|
||||
// opens remain pathname-based; hardlink/leaf-file races need a follow-up redesign.
|
||||
Ok((home, handles))
|
||||
}
|
||||
|
||||
pub(crate) fn pin_existing_ancestors(path: &Path, handles: &mut Vec<OwnedHandle>) -> Result<()> {
|
||||
let mut current = PathBuf::new();
|
||||
for component in path.components() {
|
||||
current.push(component.as_os_str());
|
||||
if !matches!(component, Component::Prefix(_)) && current.is_absolute() {
|
||||
handles.push(pin_directory(
|
||||
¤t,
|
||||
filesystem::FILE_READ_ATTRIBUTES,
|
||||
DirectoryOpenDisposition::OpenExisting,
|
||||
)?);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn pin_directory(
|
||||
path: &Path,
|
||||
access: u32,
|
||||
disposition: DirectoryOpenDisposition,
|
||||
) -> Result<OwnedHandle> {
|
||||
let handle = open_directory_no_reparse(
|
||||
path,
|
||||
// Metadata-only access does not enforce no-delete sharing.
|
||||
access | filesystem::FILE_TRAVERSE,
|
||||
filesystem::FILE_SHARE_READ | filesystem::FILE_SHARE_WRITE,
|
||||
disposition,
|
||||
)
|
||||
.with_context(|| format!("pin {}", path.display()))?;
|
||||
Ok(handle)
|
||||
}
|
||||
121
akode-rs/windows-sandbox-service/src/ipc/listener.rs
Normal file
121
akode-rs/windows-sandbox-service/src/ipc/listener.rs
Normal file
@@ -0,0 +1,121 @@
|
||||
//! Owns a provisioning pipe and the sandbox group generation in its deny rule.
|
||||
//! Replaces stale listeners only after a response, closing the old pipe before creating another.
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
use akode_windows_sandbox::ensure_sandbox_users_group;
|
||||
use akode_windows_sandbox::string_from_sid_bytes;
|
||||
use akode_windows_sandbox::to_wide;
|
||||
use std::mem::size_of;
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::os::windows::io::FromRawHandle;
|
||||
use std::os::windows::io::OwnedHandle;
|
||||
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::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 pipe_name = akode_windows_sandbox::windows_sandbox_service_pipe_name()?;
|
||||
let _setup_lock =
|
||||
akode_windows_sandbox::acquire_sandbox_setup_lock(/*timeout_ms*/ 5_000)?;
|
||||
if crate::installation_record::load()?
|
||||
.and_then(|record| record.runtime)
|
||||
.is_some_and(|runtime| runtime.retiring.is_some())
|
||||
{
|
||||
bail!("interrupted sandbox cleanup requires repair");
|
||||
}
|
||||
let sandbox_sid = ensure_sandbox_users_group()?;
|
||||
let (descriptor, pipe) = create_provisioning_pipe(&pipe_name, &sandbox_sid)?;
|
||||
Ok(Self {
|
||||
pipe,
|
||||
sandbox_sid,
|
||||
_descriptor: descriptor,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn refresh(self) -> Result<Self> {
|
||||
let current_group = {
|
||||
let _setup_lock =
|
||||
akode_windows_sandbox::acquire_sandbox_setup_lock(/*timeout_ms*/ 5_000)?;
|
||||
akode_windows_sandbox::resolve_sid(akode_windows_sandbox::SANDBOX_USERS_GROUP)
|
||||
};
|
||||
if current_group.is_ok_and(|current| current == self.sandbox_sid) {
|
||||
unsafe { pipes::DisconnectNamedPipe(self.pipe.as_raw_handle()) };
|
||||
return Ok(self);
|
||||
}
|
||||
// A stale deny SID was refused before dispatch. Close this first-instance
|
||||
// pipe before rebuilding its descriptor for the current group generation.
|
||||
drop(self);
|
||||
Self::open()
|
||||
}
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
// SAFETY: CreateNamedPipeW transferred this pipe handle on success.
|
||||
Ok((descriptor, unsafe { OwnedHandle::from_raw_handle(pipe) }))
|
||||
}
|
||||
97
akode-rs/windows-sandbox-service/src/ipc/request.rs
Normal file
97
akode-rs/windows-sandbox-service/src/ipc/request.rs
Normal file
@@ -0,0 +1,97 @@
|
||||
//! Validates framed provisioning requests and normalizes proxy settings.
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
use akode_windows_sandbox::PROVISIONING_PROTOCOL_VERSION;
|
||||
use akode_windows_sandbox::ProvisioningMessage;
|
||||
use akode_windows_sandbox::WindowsSandboxProvisioningSettings;
|
||||
use akode_windows_sandbox::WindowsSandboxProxyListeners;
|
||||
use akode_windows_sandbox::read_provisioning_frame;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::MAX_REQUEST_BYTES;
|
||||
|
||||
#[derive(Debug, Eq, PartialEq)]
|
||||
pub(crate) enum ServiceRequest {
|
||||
RegisterInstallation { codex_home: PathBuf },
|
||||
ProvisionSandbox(ProvisioningRequest),
|
||||
}
|
||||
|
||||
#[derive(Debug, Eq, PartialEq)]
|
||||
pub(crate) struct ProvisioningRequest {
|
||||
pub(crate) codex_home: PathBuf,
|
||||
pub(crate) registered_core: bool,
|
||||
pub(crate) refresh_only: bool,
|
||||
pub(crate) listeners: WindowsSandboxProxyListeners,
|
||||
pub(crate) settings: WindowsSandboxProvisioningSettings,
|
||||
}
|
||||
|
||||
pub(super) fn validate_request(request: &[u8]) -> Result<ServiceRequest> {
|
||||
if request.len() > MAX_REQUEST_BYTES {
|
||||
bail!("provisioning request exceeds size limit");
|
||||
}
|
||||
let mut reader = request;
|
||||
let frame = read_provisioning_frame(&mut reader)
|
||||
.context("invalid framed provisioning request")?
|
||||
.context("provisioning client sent an empty request")?;
|
||||
if !reader.is_empty() {
|
||||
bail!("provisioning requests must contain exactly one IPC frame");
|
||||
}
|
||||
|
||||
if frame.version != PROVISIONING_PROTOCOL_VERSION {
|
||||
bail!(
|
||||
"unsupported provisioning request version: {}",
|
||||
frame.version
|
||||
);
|
||||
}
|
||||
let request = match frame.message {
|
||||
ProvisioningMessage::RegisterInstallationRequest { codex_home } => {
|
||||
validate_home(&codex_home)?;
|
||||
return Ok(ServiceRequest::RegisterInstallation {
|
||||
codex_home: PathBuf::from(codex_home),
|
||||
});
|
||||
}
|
||||
ProvisioningMessage::ProvisionSandboxRequest { payload } => payload,
|
||||
ProvisioningMessage::ProvisionSandboxResponse { .. } => bail!("expected a service request"),
|
||||
};
|
||||
validate_home(&request.codex_home)?;
|
||||
if request.refresh_only && !request.registered_core {
|
||||
bail!("registration refresh requires registered Core");
|
||||
}
|
||||
let mut settings = request.settings;
|
||||
let mut listeners = request.listeners;
|
||||
for ports in [
|
||||
&mut settings.proxy_ports,
|
||||
&mut listeners.http_ports,
|
||||
&mut listeners.socks_ports,
|
||||
] {
|
||||
if ports.contains(&0) {
|
||||
bail!("provisioning request includes an invalid proxy port");
|
||||
}
|
||||
ports.sort_unstable();
|
||||
ports.dedup();
|
||||
}
|
||||
if listeners
|
||||
.http_ports
|
||||
.iter()
|
||||
.chain(&listeners.socks_ports)
|
||||
.any(|port| !settings.proxy_ports.contains(port))
|
||||
{
|
||||
bail!("provisioning listener is absent from the proxy settings");
|
||||
}
|
||||
Ok(ServiceRequest::ProvisionSandbox(ProvisioningRequest {
|
||||
codex_home: PathBuf::from(request.codex_home),
|
||||
registered_core: request.registered_core,
|
||||
refresh_only: request.refresh_only,
|
||||
listeners,
|
||||
settings,
|
||||
}))
|
||||
}
|
||||
|
||||
fn validate_home(home: &str) -> Result<()> {
|
||||
if home.is_empty() || home.contains(['\0', '\r', '\n']) {
|
||||
bail!("Codex home is empty or contains an invalid control character");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
880
akode-rs/windows-sandbox-service/src/ipc_tests.rs
Normal file
880
akode-rs/windows-sandbox-service/src/ipc_tests.rs
Normal file
@@ -0,0 +1,880 @@
|
||||
use super::MAX_RESPONSE_MESSAGE_BYTES;
|
||||
use super::PipeConnection;
|
||||
use super::ServiceRequest;
|
||||
use super::accept_pipe_connection;
|
||||
use super::home::prepare_codex_home;
|
||||
use super::is_config_parse_error;
|
||||
use super::pin_existing_ancestors;
|
||||
use super::pipe_security_descriptor;
|
||||
use super::policy_rejection_diagnostic;
|
||||
use super::refresh_session;
|
||||
use super::request::ProvisioningRequest;
|
||||
use super::response_error_message;
|
||||
use super::validate_request;
|
||||
use super::wake;
|
||||
use akode_windows_sandbox::DirectoryOpenDisposition;
|
||||
use akode_windows_sandbox::FramedProvisioningMessage;
|
||||
use akode_windows_sandbox::PROVISIONING_PROTOCOL_VERSION;
|
||||
use akode_windows_sandbox::ProvisioningMessage;
|
||||
use akode_windows_sandbox::SandboxProvisioningRequest;
|
||||
use akode_windows_sandbox::SandboxProvisioningResponse;
|
||||
use akode_windows_sandbox::SetupRuntime;
|
||||
use akode_windows_sandbox::WindowsSandboxProvisioningSettings;
|
||||
use akode_windows_sandbox::WindowsSandboxProxyListeners;
|
||||
use akode_windows_sandbox::read_provisioning_frame;
|
||||
use akode_windows_sandbox::to_wide;
|
||||
use akode_windows_sandbox::write_provisioning_frame;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::os::windows::io::FromRawHandle;
|
||||
use std::os::windows::io::OwnedHandle;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::ptr;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
use windows_sys::Win32::Foundation as foundation;
|
||||
use windows_sys::Win32::Storage::FileSystem as filesystem;
|
||||
use windows_sys::Win32::Storage::Packaging::Appx;
|
||||
use windows_sys::Win32::System::Pipes as pipes;
|
||||
|
||||
struct NonOwningPipeHandle(foundation::HANDLE);
|
||||
|
||||
// SAFETY: Pipe handles are opaque process-wide tokens that may be passed between
|
||||
// threads. This wrapper does not own the handle or extend its lifetime.
|
||||
unsafe impl Send for NonOwningPipeHandle {}
|
||||
|
||||
// Run as LocalSystem on a disposable Windows VM. The interactive user seeds both
|
||||
// homes with the legacy DACL, with a SYSTEM WRITE_DAC deny on the second bin.
|
||||
#[test]
|
||||
#[ignore = "requires SYSTEM, an interactive owner, and two user-owned legacy sandbox homes"]
|
||||
fn repair_legacy_bin_as_its_owner() -> anyhow::Result<()> {
|
||||
use std::os::windows::io::AsHandle;
|
||||
use windows_sys::Win32::System::RemoteDesktop::WTSQueryUserToken;
|
||||
|
||||
let session = std::env::var("AKODE_TEST_OWNER_SESSION")?.parse()?;
|
||||
let mut token = std::ptr::null_mut();
|
||||
if unsafe { WTSQueryUserToken(session, &mut token) } == 0 {
|
||||
return Err(std::io::Error::last_os_error().into());
|
||||
}
|
||||
// SAFETY: WTSQueryUserToken transferred this interactive user's token.
|
||||
let owner = unsafe { OwnedHandle::from_raw_handle(token) };
|
||||
for (variable, should_repair) in [
|
||||
("AKODE_TEST_LEGACY_HOME", true),
|
||||
("AKODE_TEST_DENIED_HOME", false),
|
||||
] {
|
||||
let home = std::path::PathBuf::from(std::env::var(variable)?);
|
||||
let (home, _pins) = crate::package_lifecycle::with_owner_impersonation(token, || {
|
||||
prepare_codex_home(
|
||||
&home,
|
||||
SetupRuntime::Legacy,
|
||||
DirectoryOpenDisposition::OpenExisting,
|
||||
)
|
||||
})?;
|
||||
let open = || {
|
||||
super::pin_directory(
|
||||
&home.join(".sandbox-bin"),
|
||||
filesystem::READ_CONTROL | filesystem::WRITE_DAC,
|
||||
DirectoryOpenDisposition::OpenExisting,
|
||||
)
|
||||
};
|
||||
let denied = open().expect_err("the seeded bin must refuse SYSTEM ACL writes");
|
||||
assert_eq!(
|
||||
denied
|
||||
.downcast_ref::<std::io::Error>()
|
||||
.and_then(std::io::Error::raw_os_error),
|
||||
Some(5)
|
||||
);
|
||||
let repair = || crate::provisioning::legacy_bin::prepare(&home, owner.as_handle());
|
||||
if should_repair {
|
||||
repair()?;
|
||||
open()?;
|
||||
repair()?;
|
||||
} else {
|
||||
assert!(repair().is_err());
|
||||
assert!(open().is_err());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provisioning_error_response_preserves_causes_within_message_limits() {
|
||||
let error = anyhow::anyhow!("Windows error\t5\n")
|
||||
.context("load profile")
|
||||
.context("registered sandbox provisioning failed");
|
||||
assert_eq!(
|
||||
response_error_message(&error),
|
||||
"registered sandbox provisioning failed: load profile: Windows error 5 "
|
||||
);
|
||||
|
||||
let error = anyhow::anyhow!("é".repeat(MAX_RESPONSE_MESSAGE_BYTES)).context("setup");
|
||||
let message = response_error_message(&error);
|
||||
assert!(message.starts_with("setup: é"));
|
||||
assert_eq!(message.len(), MAX_RESPONSE_MESSAGE_BYTES - 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_refresh_observes_cleanup_completion_before_dispatch() {
|
||||
let shutdown = AtomicBool::new(false);
|
||||
assert!(
|
||||
!refresh_session(&shutdown, || {
|
||||
shutdown.store(true, Ordering::Release);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_refresh_preserves_authoritative_stop() {
|
||||
let shutdown = AtomicBool::new(true);
|
||||
assert!(!refresh_session(&shutdown, || panic!("stopped listener must not refresh")).unwrap());
|
||||
assert!(shutdown.load(Ordering::Acquire));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_refresh_keeps_admission_open_without_cleanup() {
|
||||
let shutdown = AtomicBool::new(false);
|
||||
assert!(refresh_session(&shutdown, || Ok(())).unwrap());
|
||||
assert!(!shutdown.load(Ordering::Acquire));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_refresh_propagates_cleanup_failure() {
|
||||
let shutdown = AtomicBool::new(false);
|
||||
let error = refresh_session(&shutdown, || anyhow::bail!("cleanup failed")).unwrap_err();
|
||||
assert!(error.to_string().contains("cleanup failed"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provisioning_request_rejects_malformed_registered_flag() {
|
||||
for registered_core in [
|
||||
serde_json::json!("true"),
|
||||
serde_json::json!(1),
|
||||
serde_json::json!(null),
|
||||
] {
|
||||
let bytes = serde_json::to_vec(&serde_json::json!({
|
||||
"version": PROVISIONING_PROTOCOL_VERSION,
|
||||
"type": "provision_sandbox_request",
|
||||
"payload": {
|
||||
"codex_home": "C:\\Users\\owner\\.akode",
|
||||
"registered_core": registered_core,
|
||||
"settings": WindowsSandboxProvisioningSettings::default(),
|
||||
"listeners": WindowsSandboxProxyListeners::default(),
|
||||
},
|
||||
}))
|
||||
.unwrap();
|
||||
let mut frame = (bytes.len() as u32).to_le_bytes().to_vec();
|
||||
frame.extend(bytes);
|
||||
assert!(validate_request(&frame).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_registration_is_an_explicit_wire_opt_in() {
|
||||
let request = SandboxProvisioningRequest {
|
||||
codex_home: r"C:\Users\owner\.akode".to_string(),
|
||||
registered_core: false,
|
||||
refresh_only: false,
|
||||
settings: WindowsSandboxProvisioningSettings::default(),
|
||||
listeners: WindowsSandboxProxyListeners::default(),
|
||||
};
|
||||
let serialized = serde_json::to_value(&request).unwrap();
|
||||
assert_eq!(
|
||||
serialized,
|
||||
serde_json::json!({
|
||||
"codex_home": request.codex_home,
|
||||
"settings": request.settings,
|
||||
"listeners": request.listeners,
|
||||
}),
|
||||
);
|
||||
let legacy: SandboxProvisioningRequest = serde_json::from_value(serialized).unwrap();
|
||||
assert!(matches!(
|
||||
validate_request(&framed_request(legacy)).unwrap(),
|
||||
ServiceRequest::ProvisionSandbox(ProvisioningRequest {
|
||||
registered_core: false,
|
||||
refresh_only: false,
|
||||
..
|
||||
})
|
||||
));
|
||||
let registered = SandboxProvisioningRequest {
|
||||
registered_core: true,
|
||||
refresh_only: false,
|
||||
..request
|
||||
};
|
||||
assert!(matches!(
|
||||
validate_request(&framed_request(registered)).unwrap(),
|
||||
ServiceRequest::ProvisionSandbox(ProvisioningRequest {
|
||||
registered_core: true,
|
||||
refresh_only: false,
|
||||
..
|
||||
})
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registration_refresh_is_explicit_and_requires_registered_core() {
|
||||
let mut request = SandboxProvisioningRequest {
|
||||
codex_home: r"C:\Users\owner\.akode".to_string(),
|
||||
registered_core: false,
|
||||
refresh_only: true,
|
||||
settings: WindowsSandboxProvisioningSettings::default(),
|
||||
listeners: WindowsSandboxProxyListeners::default(),
|
||||
};
|
||||
assert!(validate_request(&framed_request(request.clone())).is_err());
|
||||
request.registered_core = true;
|
||||
assert!(matches!(
|
||||
validate_request(&framed_request(request)).unwrap(),
|
||||
ServiceRequest::ProvisionSandbox(ProvisioningRequest {
|
||||
registered_core: true,
|
||||
refresh_only: true,
|
||||
..
|
||||
})
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_registration_has_no_unpackaged_or_foreground_identity_exemption() {
|
||||
let service = Some("OpenAI.Codex_testpublisher");
|
||||
assert!(crate::package_identity::require_runtime_package_family(service, service).is_ok());
|
||||
for (client, service) in [
|
||||
(None, service),
|
||||
(service, None),
|
||||
(None, None),
|
||||
(Some("OpenAI.CodexBeta_testpublisher"), service),
|
||||
(Some("OpenAI.Codex_otherpublisher"), service),
|
||||
] {
|
||||
assert!(crate::package_identity::require_runtime_package_family(client, service).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
fn framed_request(request: SandboxProvisioningRequest) -> Vec<u8> {
|
||||
let mut frame = Vec::new();
|
||||
write_provisioning_frame(
|
||||
&mut frame,
|
||||
&FramedProvisioningMessage {
|
||||
version: PROVISIONING_PROTOCOL_VERSION,
|
||||
message: ProvisioningMessage::ProvisionSandboxRequest { payload: request },
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
frame
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unavailable_response_round_trips_through_provisioning_frame() {
|
||||
let mut frame = Vec::new();
|
||||
write_provisioning_frame(
|
||||
&mut frame,
|
||||
&FramedProvisioningMessage {
|
||||
version: PROVISIONING_PROTOCOL_VERSION,
|
||||
message: ProvisioningMessage::ProvisionSandboxResponse {
|
||||
payload: SandboxProvisioningResponse::Unavailable,
|
||||
},
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(matches!(
|
||||
read_provisioning_frame(frame.as_slice()).unwrap(),
|
||||
Some(FramedProvisioningMessage {
|
||||
version: PROVISIONING_PROTOCOL_VERSION,
|
||||
message: ProvisioningMessage::ProvisionSandboxResponse {
|
||||
payload: SandboxProvisioningResponse::Unavailable,
|
||||
},
|
||||
})
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_parse_errors_are_distinguished_from_policy_and_io_failures() {
|
||||
let schema_error = akode_core::config::deserialize_config_toml_with_base(
|
||||
toml::from_str(r#"model_verbosity = "future-verbosity""#).unwrap(),
|
||||
Path::new(r"C:\CodexTest"),
|
||||
)
|
||||
.unwrap_err();
|
||||
let contents = "[";
|
||||
let parse_error = toml::from_str::<toml::Value>(contents).unwrap_err();
|
||||
let syntax_error = akode_config::io_error_from_config_error(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
akode_config::config_error_from_toml("config.toml", contents, parse_error.clone()),
|
||||
Some(parse_error),
|
||||
);
|
||||
for error in [schema_error, syntax_error] {
|
||||
assert!(is_config_parse_error(
|
||||
&anyhow::Error::new(error).context("load managed configuration"),
|
||||
));
|
||||
}
|
||||
|
||||
for error in [
|
||||
anyhow::anyhow!("managed policy does not permit the elevated Windows sandbox"),
|
||||
anyhow::Error::new(std::io::Error::from_raw_os_error(
|
||||
foundation::ERROR_ACCESS_DENIED as i32,
|
||||
)),
|
||||
anyhow::Error::new(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
"invalid credentials",
|
||||
)),
|
||||
] {
|
||||
assert!(!is_config_parse_error(
|
||||
&error.context("load managed configuration"),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn policy_event_excludes_real_parser_values_but_retains_safe_codes() {
|
||||
let contents = "Authorization = \"Bearer synthetic-secret";
|
||||
let requirements =
|
||||
akode_config::compose_requirements([akode_config::RequirementsLayerEntry::from_toml(
|
||||
akode_config::RequirementSource::Unknown,
|
||||
contents,
|
||||
)])
|
||||
.unwrap_err();
|
||||
for error in [std::io::Error::from(requirements)] {
|
||||
let error = anyhow::Error::new(error).context("load managed configuration");
|
||||
assert!(format!("{error:#}").contains("synthetic-secret"));
|
||||
assert!(!is_config_parse_error(&error));
|
||||
assert_eq!(
|
||||
policy_rejection_diagnostic(&error),
|
||||
"Codex sandbox provisioning was rejected by administrator policy: stage=managed io=InvalidData win32=None"
|
||||
);
|
||||
}
|
||||
|
||||
for (error, expected) in [
|
||||
(
|
||||
anyhow::Error::new(std::io::Error::from_raw_os_error(5))
|
||||
.context("load bootstrap configuration"),
|
||||
"stage=bootstrap io=PermissionDenied win32=Some(5)",
|
||||
),
|
||||
(
|
||||
anyhow::anyhow!("{contents}"),
|
||||
"stage=unknown cause=unavailable",
|
||||
),
|
||||
] {
|
||||
assert_eq!(
|
||||
policy_rejection_diagnostic(&error),
|
||||
format!("Codex sandbox provisioning was rejected by administrator policy: {expected}")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provisioning_request_preserves_home_spaces_and_unicode() {
|
||||
let request = framed_request(SandboxProvisioningRequest {
|
||||
codex_home: "D:\\Codex Homes\\Jos\u{00e9}\\.akode".to_string(),
|
||||
registered_core: false,
|
||||
refresh_only: false,
|
||||
settings: WindowsSandboxProvisioningSettings::default(),
|
||||
listeners: WindowsSandboxProxyListeners::default(),
|
||||
});
|
||||
assert_eq!(
|
||||
validate_request(&request).unwrap(),
|
||||
ServiceRequest::ProvisionSandbox(ProvisioningRequest {
|
||||
codex_home: PathBuf::from("D:\\Codex Homes\\Jos\u{00e9}\\.akode"),
|
||||
registered_core: false,
|
||||
refresh_only: false,
|
||||
listeners: WindowsSandboxProxyListeners::default(),
|
||||
settings: WindowsSandboxProvisioningSettings::default(),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn structured_provisioning_request_carries_normalized_proxy_settings() {
|
||||
for (http_port, socks_port, proxy_ports) in
|
||||
[(8081, 3128, vec![3128, 8081]), (8081, 8081, vec![8081])]
|
||||
{
|
||||
let request = framed_request(SandboxProvisioningRequest {
|
||||
codex_home: "D:\\Codex Homes\\Jos\u{00e9}\\.akode".to_string(),
|
||||
registered_core: false,
|
||||
refresh_only: false,
|
||||
settings: WindowsSandboxProvisioningSettings {
|
||||
proxy_ports: vec![http_port, socks_port, http_port],
|
||||
allow_local_binding: true,
|
||||
},
|
||||
listeners: WindowsSandboxProxyListeners {
|
||||
http_ports: vec![http_port, http_port],
|
||||
socks_ports: vec![socks_port],
|
||||
},
|
||||
});
|
||||
assert_eq!(
|
||||
validate_request(&request).unwrap(),
|
||||
ServiceRequest::ProvisionSandbox(ProvisioningRequest {
|
||||
codex_home: PathBuf::from("D:\\Codex Homes\\Jos\u{00e9}\\.akode"),
|
||||
registered_core: false,
|
||||
refresh_only: false,
|
||||
listeners: WindowsSandboxProxyListeners {
|
||||
http_ports: vec![http_port],
|
||||
socks_ports: vec![socks_port],
|
||||
},
|
||||
settings: WindowsSandboxProvisioningSettings {
|
||||
proxy_ports,
|
||||
allow_local_binding: true,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn structured_provisioning_request_accepts_independent_and_additional_proxy_ports() {
|
||||
for (http_ports, socks_ports, proxy_ports) in [
|
||||
(vec![3128], vec![], vec![3128]),
|
||||
(vec![], vec![1080], vec![1080]),
|
||||
(vec![3128, 8080], vec![1080], vec![1080, 1082, 3128, 8080]),
|
||||
] {
|
||||
let settings = WindowsSandboxProvisioningSettings {
|
||||
proxy_ports,
|
||||
allow_local_binding: false,
|
||||
};
|
||||
let listeners = WindowsSandboxProxyListeners {
|
||||
http_ports,
|
||||
socks_ports,
|
||||
};
|
||||
let request = framed_request(SandboxProvisioningRequest {
|
||||
codex_home: r"C:\Users\alice\.akode".to_string(),
|
||||
registered_core: false,
|
||||
refresh_only: false,
|
||||
settings: settings.clone(),
|
||||
listeners: listeners.clone(),
|
||||
});
|
||||
assert_eq!(
|
||||
validate_request(&request).unwrap(),
|
||||
ServiceRequest::ProvisionSandbox(ProvisioningRequest {
|
||||
codex_home: PathBuf::from(r"C:\Users\alice\.akode"),
|
||||
registered_core: false,
|
||||
refresh_only: false,
|
||||
settings,
|
||||
listeners,
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn structured_provisioning_request_accepts_disabled_listeners() {
|
||||
let request = framed_request(SandboxProvisioningRequest {
|
||||
codex_home: r"C:\Users\alice\.akode".to_string(),
|
||||
registered_core: false,
|
||||
refresh_only: false,
|
||||
settings: WindowsSandboxProvisioningSettings::default(),
|
||||
listeners: WindowsSandboxProxyListeners::default(),
|
||||
});
|
||||
assert_eq!(
|
||||
validate_request(&request).unwrap(),
|
||||
ServiceRequest::ProvisionSandbox(ProvisioningRequest {
|
||||
codex_home: PathBuf::from(r"C:\Users\alice\.akode"),
|
||||
registered_core: false,
|
||||
refresh_only: false,
|
||||
listeners: WindowsSandboxProxyListeners::default(),
|
||||
settings: WindowsSandboxProvisioningSettings::default(),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn structured_provisioning_request_requires_exact_version_fields_and_framing() {
|
||||
let valid = SandboxProvisioningRequest {
|
||||
codex_home: r"C:\Users\alice\.akode".to_string(),
|
||||
registered_core: false,
|
||||
refresh_only: false,
|
||||
settings: WindowsSandboxProvisioningSettings::default(),
|
||||
listeners: WindowsSandboxProxyListeners::default(),
|
||||
};
|
||||
let mut invalid_version = Vec::new();
|
||||
write_provisioning_frame(
|
||||
&mut invalid_version,
|
||||
&FramedProvisioningMessage {
|
||||
version: PROVISIONING_PROTOCOL_VERSION + 1,
|
||||
message: ProvisioningMessage::ProvisionSandboxRequest {
|
||||
payload: valid.clone(),
|
||||
},
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert!(validate_request(&invalid_version).is_err());
|
||||
|
||||
let mut unexpected_message = Vec::new();
|
||||
write_provisioning_frame(
|
||||
&mut unexpected_message,
|
||||
&FramedProvisioningMessage {
|
||||
version: PROVISIONING_PROTOCOL_VERSION,
|
||||
message: ProvisioningMessage::ProvisionSandboxResponse {
|
||||
payload: SandboxProvisioningResponse::Ok,
|
||||
},
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert!(validate_request(&unexpected_message).is_err());
|
||||
|
||||
let valid = framed_request(valid);
|
||||
assert!(validate_request(&valid[..valid.len() - 1]).is_err());
|
||||
let mut duplicate = valid.clone();
|
||||
duplicate.extend_from_slice(&valid);
|
||||
assert!(validate_request(&duplicate).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn structured_provisioning_request_rejects_invalid_or_inconsistent_ports() {
|
||||
for (proxy_ports, http_ports, socks_ports) in [
|
||||
(vec![0], vec![], vec![]),
|
||||
(vec![3128], vec![0], vec![]),
|
||||
(vec![3128], vec![3128], vec![0]),
|
||||
(vec![3128], vec![3128], vec![8081]),
|
||||
] {
|
||||
let request = framed_request(SandboxProvisioningRequest {
|
||||
codex_home: r"C:\Users\alice\.akode".to_string(),
|
||||
registered_core: false,
|
||||
refresh_only: false,
|
||||
settings: WindowsSandboxProvisioningSettings {
|
||||
proxy_ports,
|
||||
allow_local_binding: false,
|
||||
},
|
||||
listeners: WindowsSandboxProxyListeners {
|
||||
http_ports,
|
||||
socks_ports,
|
||||
},
|
||||
});
|
||||
assert!(validate_request(&request).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provisioning_request_rejects_empty_control_characters_and_invalid_utf8() {
|
||||
for home in ["", "C:\\safe\0evil", "C:\\safe\rmore", "C:\\safe\nmore"] {
|
||||
let request = framed_request(SandboxProvisioningRequest {
|
||||
codex_home: home.to_string(),
|
||||
registered_core: false,
|
||||
refresh_only: false,
|
||||
settings: WindowsSandboxProvisioningSettings::default(),
|
||||
listeners: WindowsSandboxProxyListeners::default(),
|
||||
});
|
||||
assert!(validate_request(&request).is_err());
|
||||
}
|
||||
|
||||
let mut invalid_utf8 = framed_request(SandboxProvisioningRequest {
|
||||
codex_home: r"C:\Users\alice\.akode".to_string(),
|
||||
registered_core: false,
|
||||
refresh_only: false,
|
||||
settings: WindowsSandboxProvisioningSettings::default(),
|
||||
listeners: WindowsSandboxProxyListeners::default(),
|
||||
});
|
||||
invalid_utf8[std::mem::size_of::<u32>()] = 0xff;
|
||||
assert!(validate_request(&invalid_utf8).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unpackaged_pipe_clients_are_rejected_before_sending_a_request() {
|
||||
let mut family_length = 0;
|
||||
let package_status =
|
||||
unsafe { Appx::GetCurrentPackageFamilyName(&mut family_length, ptr::null_mut()) };
|
||||
if package_status != foundation::APPMODEL_ERROR_NO_PACKAGE {
|
||||
assert_eq!(package_status, foundation::ERROR_INSUFFICIENT_BUFFER);
|
||||
return;
|
||||
}
|
||||
|
||||
static NEXT_PIPE_INSTANCE: AtomicU64 = AtomicU64::new(0);
|
||||
let name = to_wide(format!(
|
||||
r"\\.\pipe\OpenAI.CodexSandbox.Tests.{}.{}",
|
||||
std::process::id(),
|
||||
NEXT_PIPE_INSTANCE.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
let server = unsafe {
|
||||
pipes::CreateNamedPipeW(
|
||||
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,
|
||||
1024,
|
||||
0,
|
||||
ptr::null(),
|
||||
)
|
||||
};
|
||||
assert_ne!(server, foundation::INVALID_HANDLE_VALUE);
|
||||
// SAFETY: CreateNamedPipeW returned a valid owned handle.
|
||||
let server = unsafe { OwnedHandle::from_raw_handle(server) };
|
||||
|
||||
let client = unsafe {
|
||||
filesystem::CreateFileW(
|
||||
name.as_ptr(),
|
||||
foundation::GENERIC_READ | foundation::GENERIC_WRITE,
|
||||
0,
|
||||
ptr::null(),
|
||||
filesystem::OPEN_EXISTING,
|
||||
0,
|
||||
ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
assert_ne!(client, foundation::INVALID_HANDLE_VALUE);
|
||||
// SAFETY: CreateFileW returned a valid owned handle.
|
||||
let _client = unsafe { OwnedHandle::from_raw_handle(client) };
|
||||
|
||||
let connected = unsafe { pipes::ConnectNamedPipe(server.as_raw_handle(), ptr::null_mut()) };
|
||||
assert!(
|
||||
connected != 0 || unsafe { foundation::GetLastError() } == foundation::ERROR_PIPE_CONNECTED
|
||||
);
|
||||
|
||||
let error = match crate::package_identity::authorize_client_process(server.as_raw_handle()) {
|
||||
Ok(_) => panic!("an unpackaged client was authorized without sending a request"),
|
||||
Err(error) => error,
|
||||
};
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("installed Codex package identity"),
|
||||
"unexpected package authorization failure: {error:#}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disconnected_pipe_clients_do_not_prevent_subsequent_connections() {
|
||||
let pipe_name = format!(
|
||||
r"\\.\pipe\OpenAI.CodexSandbox.DisconnectTests.{}",
|
||||
std::process::id()
|
||||
);
|
||||
let name = to_wide(&pipe_name);
|
||||
let server = unsafe {
|
||||
pipes::CreateNamedPipeW(
|
||||
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,
|
||||
1024,
|
||||
0,
|
||||
ptr::null(),
|
||||
)
|
||||
};
|
||||
assert_ne!(server, foundation::INVALID_HANDLE_VALUE);
|
||||
// SAFETY: CreateNamedPipeW returned a valid owned handle.
|
||||
let server = unsafe { OwnedHandle::from_raw_handle(server) };
|
||||
|
||||
let first_client = unsafe {
|
||||
filesystem::CreateFileW(
|
||||
name.as_ptr(),
|
||||
foundation::GENERIC_READ | foundation::GENERIC_WRITE,
|
||||
0,
|
||||
ptr::null(),
|
||||
filesystem::OPEN_EXISTING,
|
||||
0,
|
||||
ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
assert_ne!(first_client, foundation::INVALID_HANDLE_VALUE);
|
||||
// SAFETY: CreateFileW returned a valid owned handle.
|
||||
drop(unsafe { OwnedHandle::from_raw_handle(first_client) });
|
||||
|
||||
assert_eq!(
|
||||
accept_pipe_connection(server.as_raw_handle()).unwrap(),
|
||||
PipeConnection::Disconnected
|
||||
);
|
||||
|
||||
let server_handle = NonOwningPipeHandle(server.as_raw_handle());
|
||||
let listener = std::thread::spawn(move || {
|
||||
// Capture the wrapper rather than its raw pointer field.
|
||||
let server_handle = &server_handle;
|
||||
accept_pipe_connection(server_handle.0)
|
||||
});
|
||||
let available = unsafe { pipes::WaitNamedPipeW(name.as_ptr(), 5_000) };
|
||||
assert_ne!(
|
||||
available,
|
||||
0,
|
||||
"wait for replacement named-pipe listener: {}",
|
||||
std::io::Error::last_os_error()
|
||||
);
|
||||
let next_client = unsafe {
|
||||
filesystem::CreateFileW(
|
||||
name.as_ptr(),
|
||||
foundation::GENERIC_READ | foundation::GENERIC_WRITE,
|
||||
0,
|
||||
ptr::null(),
|
||||
filesystem::OPEN_EXISTING,
|
||||
0,
|
||||
ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
assert_ne!(
|
||||
next_client,
|
||||
foundation::INVALID_HANDLE_VALUE,
|
||||
"connect replacement named-pipe client: {}",
|
||||
std::io::Error::last_os_error()
|
||||
);
|
||||
// SAFETY: CreateFileW returned a valid owned handle.
|
||||
let next_client = unsafe { OwnedHandle::from_raw_handle(next_client) };
|
||||
assert_eq!(
|
||||
listener.join().expect("join named-pipe listener").unwrap(),
|
||||
PipeConnection::Connected
|
||||
);
|
||||
|
||||
drop(next_client);
|
||||
assert_ne!(
|
||||
unsafe { pipes::DisconnectNamedPipe(server.as_raw_handle()) },
|
||||
0
|
||||
);
|
||||
|
||||
let timeout = Duration::from_secs(5);
|
||||
let deadline = Instant::now() + timeout;
|
||||
let (checks_tx, checks_rx) = mpsc::channel();
|
||||
let waker = std::thread::spawn(move || {
|
||||
wake(&pipe_name, || {
|
||||
let _ = checks_tx.send(());
|
||||
Instant::now() >= deadline
|
||||
});
|
||||
});
|
||||
checks_rx.recv_timeout(timeout).unwrap();
|
||||
// The second check proves a wake failed before the listener started reconnecting.
|
||||
checks_rx.recv_timeout(timeout).unwrap();
|
||||
|
||||
let (accepted_tx, accepted_rx) = mpsc::channel();
|
||||
let listener = std::thread::spawn(move || {
|
||||
let _ = accepted_tx.send(accept_pipe_connection(server.as_raw_handle()));
|
||||
drop(server);
|
||||
});
|
||||
let accepted = accepted_rx.recv_timeout(timeout);
|
||||
waker.join().expect("join shutdown waker");
|
||||
// The wake handle may close before ConnectNamedPipe observes the connection.
|
||||
assert!(
|
||||
accepted
|
||||
.expect("shutdown wake should unblock the listener")
|
||||
.is_ok()
|
||||
);
|
||||
listener.join().expect("join shutdown listener");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unexpected_pipe_connection_errors_remain_fatal() {
|
||||
let error = accept_pipe_connection(foundation::INVALID_HANDLE_VALUE).unwrap_err();
|
||||
|
||||
assert_eq!(
|
||||
error
|
||||
.downcast_ref::<std::io::Error>()
|
||||
.and_then(std::io::Error::raw_os_error),
|
||||
Some(foundation::ERROR_INVALID_HANDLE as i32)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pin_existing_ancestors_accepts_drive_and_verbatim_drive_roots() {
|
||||
let executable = std::env::current_exe().unwrap().canonicalize().unwrap();
|
||||
let verbatim_root = executable.ancestors().last().unwrap();
|
||||
let ordinary_root = PathBuf::from(
|
||||
verbatim_root
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.strip_prefix(r"\\?\")
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
for root in [ordinary_root.as_path(), verbatim_root] {
|
||||
let mut handles = Vec::new();
|
||||
pin_existing_ancestors(root, &mut handles).unwrap();
|
||||
assert_eq!(handles.len(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pipe_descriptor_denies_sandbox_group_before_interactive_users() {
|
||||
let descriptor = pipe_security_descriptor("S-1-5-21-11-12-13-14");
|
||||
let deny = descriptor.find("(D;;GA;;;S-1-5-21-11-12-13-14)").unwrap();
|
||||
let interactive = descriptor.find("(A;;0x0012019b;;;IU)").unwrap();
|
||||
assert!(deny < interactive);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registered_home_preparation_does_not_touch_the_legacy_bin() -> anyhow::Result<()> {
|
||||
let root = std::env::temp_dir().join(format!(
|
||||
"codex-service-home-{:?}",
|
||||
windows::core::GUID::new()?
|
||||
));
|
||||
std::fs::create_dir(&root)?;
|
||||
let result = (|| -> anyhow::Result<()> {
|
||||
let home = root.join(".akode");
|
||||
std::fs::create_dir(&home)?;
|
||||
let bin = home.join(".sandbox-bin");
|
||||
let marker = b"legacy bin is deliberately not a directory";
|
||||
std::fs::write(&bin, marker)?;
|
||||
|
||||
assert!(
|
||||
prepare_codex_home(
|
||||
&home,
|
||||
SetupRuntime::Registered,
|
||||
DirectoryOpenDisposition::OpenExisting,
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(!home.join(".sandbox").exists());
|
||||
assert!(!home.join(".sandbox-secrets").exists());
|
||||
let (_, handles) = prepare_codex_home(
|
||||
&home,
|
||||
SetupRuntime::Registered,
|
||||
DirectoryOpenDisposition::OpenOrCreate,
|
||||
)?;
|
||||
assert!(home.join(".sandbox").is_dir());
|
||||
assert!(home.join(".sandbox-secrets").is_dir());
|
||||
assert_eq!(std::fs::read(&bin)?.as_slice(), marker.as_slice());
|
||||
drop(handles);
|
||||
|
||||
// Legacy still validates and pins the copied-bin path.
|
||||
let (_, handles) = prepare_codex_home(
|
||||
&home,
|
||||
SetupRuntime::Registered,
|
||||
DirectoryOpenDisposition::OpenExisting,
|
||||
)?;
|
||||
drop(handles);
|
||||
assert!(
|
||||
prepare_codex_home(
|
||||
&home,
|
||||
SetupRuntime::Legacy,
|
||||
DirectoryOpenDisposition::OpenOrCreate,
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(std::fs::read(&bin)?.as_slice(), marker.as_slice());
|
||||
std::fs::remove_file(&bin)?;
|
||||
let (_, handles) = prepare_codex_home(
|
||||
&home,
|
||||
SetupRuntime::Legacy,
|
||||
DirectoryOpenDisposition::OpenOrCreate,
|
||||
)?;
|
||||
assert!(bin.is_dir());
|
||||
drop(handles);
|
||||
|
||||
Ok(())
|
||||
})();
|
||||
std::fs::remove_dir_all(&root)?;
|
||||
result
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installation_registration_requires_no_sandbox_settings() {
|
||||
let mut frame = Vec::new();
|
||||
write_provisioning_frame(
|
||||
&mut frame,
|
||||
&FramedProvisioningMessage {
|
||||
version: PROVISIONING_PROTOCOL_VERSION,
|
||||
message: ProvisioningMessage::RegisterInstallationRequest {
|
||||
codex_home: r"C:\Users\alice\.akode".to_string(),
|
||||
},
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
validate_request(&frame).unwrap(),
|
||||
ServiceRequest::RegisterInstallation {
|
||||
codex_home: PathBuf::from(r"C:\Users\alice\.akode")
|
||||
},
|
||||
);
|
||||
}
|
||||
45
akode-rs/windows-sandbox-service/src/lib.rs
Normal file
45
akode-rs/windows-sandbox-service/src/lib.rs
Normal file
@@ -0,0 +1,45 @@
|
||||
use anyhow::Result;
|
||||
|
||||
#[cfg(windows)]
|
||||
mod installation_record;
|
||||
#[cfg(windows)]
|
||||
mod ipc;
|
||||
|
||||
#[cfg(windows)]
|
||||
mod machine_policy;
|
||||
#[cfg(windows)]
|
||||
mod package_identity;
|
||||
#[cfg(windows)]
|
||||
mod package_lifecycle;
|
||||
#[cfg(windows)]
|
||||
mod provisioning;
|
||||
#[cfg(windows)]
|
||||
mod registered_runtime;
|
||||
#[cfg(windows)]
|
||||
mod service;
|
||||
#[cfg(any(windows, test))]
|
||||
mod uninstall_policy;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum RunMode {
|
||||
Service,
|
||||
#[cfg(debug_assertions)]
|
||||
Foreground,
|
||||
}
|
||||
|
||||
pub fn run(mode: RunMode) -> Result<()> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
match mode {
|
||||
RunMode::Service => service::run(),
|
||||
#[cfg(debug_assertions)]
|
||||
RunMode::Foreground => service::run_foreground(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = mode;
|
||||
anyhow::bail!("the Codex sandbox service is only available on Windows")
|
||||
}
|
||||
}
|
||||
136
akode-rs/windows-sandbox-service/src/machine_policy.rs
Normal file
136
akode-rs/windows-sandbox-service/src/machine_policy.rs
Normal file
@@ -0,0 +1,136 @@
|
||||
//! Validates sandbox provisioning against managed policy; registration-only refresh
|
||||
//! retains the existing sandbox and is admitted by the registered-runtime transaction.
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
use akode_config::ConfigLoadOptions;
|
||||
use akode_config::ConfigRequirements;
|
||||
use akode_config::types::WindowsSandboxModeToml;
|
||||
use akode_core::config::load_config_toml_with_layer_stack;
|
||||
use akode_windows_sandbox::WindowsSandboxProvisioningSettings;
|
||||
use akode_windows_sandbox::WindowsSandboxProxyListeners;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::Notify;
|
||||
use windows_sys::Win32::Foundation::HANDLE;
|
||||
use windows_sys::Win32::Security::ImpersonateLoggedOnUser;
|
||||
|
||||
use crate::ipc::ProvisioningRequest;
|
||||
|
||||
struct NonOwningImpersonationToken(HANDLE);
|
||||
|
||||
// SAFETY: Windows access token handles are opaque process-wide values that may
|
||||
// be shared between threads. This wrapper does not own the token or extend its
|
||||
// lifetime.
|
||||
unsafe impl Send for NonOwningImpersonationToken {}
|
||||
unsafe impl Sync for NonOwningImpersonationToken {}
|
||||
|
||||
pub(crate) fn validate_provisioning_request(
|
||||
codex_home: &Path,
|
||||
request: &ProvisioningRequest,
|
||||
impersonation_token: HANDLE,
|
||||
) -> Result<()> {
|
||||
if request.registered_core && request.refresh_only {
|
||||
// The caller is already authenticated. registered::run checks the existing
|
||||
// owner, accounts and unchanged settings under the setup lock; it cannot
|
||||
// provision or repair a sandbox. Backend use still obeys managed config.
|
||||
// Package maintenance must not require another cloud-policy fetch.
|
||||
return Ok(());
|
||||
}
|
||||
let impersonation_failure = Arc::new(Notify::new());
|
||||
let worker_impersonation_failure = Arc::clone(&impersonation_failure);
|
||||
let impersonation_token = NonOwningImpersonationToken(impersonation_token);
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.on_thread_start(move || {
|
||||
// Capture the wrapper rather than its raw pointer field.
|
||||
let impersonation_token = &impersonation_token;
|
||||
if unsafe { ImpersonateLoggedOnUser(impersonation_token.0) } == 0 {
|
||||
let error = std::io::Error::last_os_error();
|
||||
worker_impersonation_failure.notify_one();
|
||||
panic!(
|
||||
"failed to impersonate provisioning client on configuration runtime thread: {error}"
|
||||
);
|
||||
}
|
||||
})
|
||||
.build()
|
||||
.context("start managed configuration runtime")?;
|
||||
let requirements = runtime.block_on(async {
|
||||
tokio::select! {
|
||||
biased;
|
||||
() = impersonation_failure.notified() => {
|
||||
Err(anyhow::anyhow!("configuration runtime worker failed to impersonate the provisioning client"))
|
||||
},
|
||||
result = async {
|
||||
// aKode only enforces local managed requirements; no cloud bundle is fetched.
|
||||
let config = load_config_toml_with_layer_stack(
|
||||
codex_home,
|
||||
/*cwd*/ None,
|
||||
Vec::new(),
|
||||
ConfigLoadOptions::default(),
|
||||
)
|
||||
.await
|
||||
.context("load managed configuration")?;
|
||||
|
||||
Ok::<_, anyhow::Error>(config.config_layer_stack.requirements().clone())
|
||||
} => result,
|
||||
}
|
||||
})?;
|
||||
|
||||
validate_requirements(&request.settings, &request.listeners, &requirements)
|
||||
.context("enforce managed provisioning requirements")
|
||||
}
|
||||
|
||||
fn validate_requirements(
|
||||
settings: &WindowsSandboxProvisioningSettings,
|
||||
listeners: &WindowsSandboxProxyListeners,
|
||||
requirements: &ConfigRequirements,
|
||||
) -> Result<()> {
|
||||
if requirements
|
||||
.windows_sandbox_mode
|
||||
.can_set(&Some(WindowsSandboxModeToml::Elevated))
|
||||
.is_err()
|
||||
{
|
||||
bail!("managed policy does not permit the elevated Windows sandbox");
|
||||
}
|
||||
|
||||
let Some(network) = requirements.network.as_ref().map(|network| &network.value) else {
|
||||
return Ok(());
|
||||
};
|
||||
if network.enabled == Some(false)
|
||||
&& (settings.allow_local_binding || !settings.proxy_ports.is_empty())
|
||||
{
|
||||
bail!("managed policy disables sandbox network access");
|
||||
}
|
||||
if settings.allow_local_binding && network.allow_local_binding == Some(false) {
|
||||
bail!("managed policy does not permit local network binding");
|
||||
}
|
||||
if let Some(required) = network.http_port
|
||||
&& let Some(actual) = listeners.http_ports.iter().find(|port| **port != required)
|
||||
{
|
||||
bail!("managed policy does not permit HTTP proxy port {actual}");
|
||||
}
|
||||
if let Some(required) = network.socks_port
|
||||
&& let Some(actual) = listeners.socks_ports.iter().find(|port| **port != required)
|
||||
{
|
||||
bail!("managed policy does not permit SOCKS proxy port {actual}");
|
||||
}
|
||||
// Omitting listener identities must not bypass managed port restrictions.
|
||||
if network.http_port.is_some() || network.socks_port.is_some() {
|
||||
for port in &settings.proxy_ports {
|
||||
if !listeners.http_ports.contains(port)
|
||||
&& !listeners.socks_ports.contains(port)
|
||||
&& network.http_port != Some(*port)
|
||||
&& network.socks_port != Some(*port)
|
||||
{
|
||||
bail!("managed policy does not permit unclassified proxy port {port}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "machine_policy_tests.rs"]
|
||||
mod tests;
|
||||
334
akode-rs/windows-sandbox-service/src/machine_policy_tests.rs
Normal file
334
akode-rs/windows-sandbox-service/src/machine_policy_tests.rs
Normal file
@@ -0,0 +1,334 @@
|
||||
use anyhow::Result;
|
||||
use akode_config::ConfigRequirements;
|
||||
use akode_config::ConfigRequirementsWithSources;
|
||||
use akode_config::RequirementSource;
|
||||
use akode_windows_sandbox::WindowsSandboxProvisioningSettings;
|
||||
use akode_windows_sandbox::WindowsSandboxProxyListeners;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use crate::ipc::ProvisioningRequest;
|
||||
|
||||
const NETWORK_TABLES: [&str; 3] = [
|
||||
"network_proxy",
|
||||
"experimental_network",
|
||||
"permissions.network",
|
||||
];
|
||||
|
||||
fn validate_requirements(
|
||||
settings: &WindowsSandboxProvisioningSettings,
|
||||
listeners: WindowsSandboxProxyListeners,
|
||||
contents: &str,
|
||||
) -> Result<()> {
|
||||
let mut requirements_with_sources = ConfigRequirementsWithSources::default();
|
||||
requirements_with_sources
|
||||
.merge_unset_fields(RequirementSource::Unknown, toml::from_str(contents)?);
|
||||
let requirements = ConfigRequirements::try_from(requirements_with_sources)?;
|
||||
super::validate_requirements(settings, &listeners, &requirements)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_registered_refresh_skips_configuration_loading() {
|
||||
for (registered_core, refresh_only) in
|
||||
[(true, true), (true, false), (false, false), (false, true)]
|
||||
{
|
||||
let request = ProvisioningRequest {
|
||||
codex_home: std::env::temp_dir(),
|
||||
registered_core,
|
||||
refresh_only,
|
||||
settings: WindowsSandboxProvisioningSettings::default(),
|
||||
listeners: WindowsSandboxProxyListeners::default(),
|
||||
};
|
||||
// An invalid worker token makes any attempt to load config fail closed.
|
||||
// Refresh must succeed without starting that runtime; setup must not.
|
||||
let result = super::validate_provisioning_request(
|
||||
&request.codex_home,
|
||||
&request,
|
||||
std::ptr::null_mut(),
|
||||
);
|
||||
assert_eq!(result.is_ok(), registered_core && refresh_only);
|
||||
if let Err(error) = result {
|
||||
assert!(error.to_string().contains("failed to impersonate"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unmanaged_policy_allows_default_and_requested_network_settings() -> Result<()> {
|
||||
validate_requirements(
|
||||
&WindowsSandboxProvisioningSettings::default(),
|
||||
WindowsSandboxProxyListeners::default(),
|
||||
"",
|
||||
)?;
|
||||
validate_requirements(
|
||||
&WindowsSandboxProvisioningSettings {
|
||||
proxy_ports: vec![3128, 8080, 9000],
|
||||
allow_local_binding: true,
|
||||
},
|
||||
WindowsSandboxProxyListeners {
|
||||
http_ports: vec![3128],
|
||||
socks_ports: vec![8080],
|
||||
},
|
||||
"allowed_sandbox_modes = [\"read-only\", \"workspace-write\"]",
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn elevated_sandbox_is_allowed_when_included() -> Result<()> {
|
||||
validate_requirements(
|
||||
&WindowsSandboxProvisioningSettings::default(),
|
||||
WindowsSandboxProxyListeners::default(),
|
||||
"[windows]\nallowed_sandbox_implementations = [\"unelevated\", \"elevated\"]",
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn elevated_sandbox_is_rejected_when_prohibited_or_empty() {
|
||||
for implementations in ["[\"unelevated\"]", "[]"] {
|
||||
let policy = format!("[windows]\nallowed_sandbox_implementations = {implementations}");
|
||||
assert!(
|
||||
validate_requirements(
|
||||
&WindowsSandboxProvisioningSettings::default(),
|
||||
WindowsSandboxProxyListeners::default(),
|
||||
&policy,
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forbidden_local_binding_is_rejected() {
|
||||
let settings = WindowsSandboxProvisioningSettings {
|
||||
proxy_ports: Vec::new(),
|
||||
allow_local_binding: true,
|
||||
};
|
||||
for table in NETWORK_TABLES {
|
||||
let policy = format!("[{table}]\nallow_local_binding = false");
|
||||
let error =
|
||||
validate_requirements(&settings, WindowsSandboxProxyListeners::default(), &policy)
|
||||
.expect_err("local binding must be rejected");
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"managed policy does not permit local network binding",
|
||||
"{table}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_network_rejects_proxy_ports_and_local_binding() -> Result<()> {
|
||||
for table in NETWORK_TABLES {
|
||||
let policy = format!("[{table}]\nenabled = false");
|
||||
validate_requirements(
|
||||
&WindowsSandboxProvisioningSettings::default(),
|
||||
WindowsSandboxProxyListeners::default(),
|
||||
&policy,
|
||||
)?;
|
||||
for settings in [
|
||||
WindowsSandboxProvisioningSettings {
|
||||
proxy_ports: vec![3128],
|
||||
allow_local_binding: false,
|
||||
},
|
||||
WindowsSandboxProvisioningSettings {
|
||||
proxy_ports: Vec::new(),
|
||||
allow_local_binding: true,
|
||||
},
|
||||
] {
|
||||
assert!(
|
||||
validate_requirements(&settings, WindowsSandboxProxyListeners::default(), &policy)
|
||||
.is_err(),
|
||||
"{table}"
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enabled_network_allows_unrestricted_proxy_ports() -> Result<()> {
|
||||
validate_requirements(
|
||||
&WindowsSandboxProvisioningSettings {
|
||||
proxy_ports: vec![3128, 8080, 8081, 9000],
|
||||
allow_local_binding: false,
|
||||
},
|
||||
WindowsSandboxProxyListeners {
|
||||
http_ports: vec![3128, 8080],
|
||||
socks_ports: vec![8081],
|
||||
},
|
||||
"[experimental_network]\nenabled = true",
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_local_binding_is_allowed_when_policy_permits_binding() -> Result<()> {
|
||||
validate_requirements(
|
||||
&WindowsSandboxProvisioningSettings::default(),
|
||||
WindowsSandboxProxyListeners::default(),
|
||||
"[experimental_network]\nallow_local_binding = true",
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_proxy_ports_allow_only_configured_ports() -> Result<()> {
|
||||
let allowed = WindowsSandboxProvisioningSettings {
|
||||
proxy_ports: vec![1080, 3128],
|
||||
allow_local_binding: false,
|
||||
};
|
||||
let prohibited = WindowsSandboxProvisioningSettings {
|
||||
proxy_ports: vec![1080, 3128, 8080],
|
||||
allow_local_binding: false,
|
||||
};
|
||||
for table in NETWORK_TABLES {
|
||||
let policy = format!("[{table}]\nhttp_port = 3128\nsocks_port = 1080");
|
||||
for listeners in [
|
||||
WindowsSandboxProxyListeners {
|
||||
http_ports: vec![3128],
|
||||
socks_ports: vec![1080],
|
||||
},
|
||||
WindowsSandboxProxyListeners::default(),
|
||||
] {
|
||||
validate_requirements(&allowed, listeners, &policy)?;
|
||||
}
|
||||
for listeners in [
|
||||
WindowsSandboxProxyListeners {
|
||||
http_ports: vec![3128, 8080],
|
||||
socks_ports: vec![1080],
|
||||
},
|
||||
WindowsSandboxProxyListeners {
|
||||
http_ports: vec![3128],
|
||||
socks_ports: vec![1080, 8080],
|
||||
},
|
||||
WindowsSandboxProxyListeners {
|
||||
http_ports: vec![3128],
|
||||
socks_ports: vec![1080],
|
||||
},
|
||||
WindowsSandboxProxyListeners::default(),
|
||||
] {
|
||||
assert!(
|
||||
validate_requirements(&prohibited, listeners, &policy).is_err(),
|
||||
"{table}"
|
||||
);
|
||||
}
|
||||
validate_requirements(
|
||||
&WindowsSandboxProvisioningSettings::default(),
|
||||
WindowsSandboxProxyListeners::default(),
|
||||
&policy,
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_http_port_does_not_restrict_the_unmanaged_socks_listener() -> Result<()> {
|
||||
validate_requirements(
|
||||
&WindowsSandboxProvisioningSettings {
|
||||
proxy_ports: vec![3128, 8081],
|
||||
allow_local_binding: false,
|
||||
},
|
||||
WindowsSandboxProxyListeners {
|
||||
http_ports: vec![3128],
|
||||
socks_ports: vec![8081],
|
||||
},
|
||||
"[experimental_network]\nhttp_port = 3128",
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_socks_port_does_not_restrict_the_unmanaged_http_listener() -> Result<()> {
|
||||
validate_requirements(
|
||||
&WindowsSandboxProvisioningSettings {
|
||||
proxy_ports: vec![1080, 3128],
|
||||
allow_local_binding: false,
|
||||
},
|
||||
WindowsSandboxProxyListeners {
|
||||
http_ports: vec![3128],
|
||||
socks_ports: vec![1080],
|
||||
},
|
||||
"[experimental_network]\nsocks_port = 1080",
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_proxy_ports_reject_swapped_listener_roles() {
|
||||
assert!(
|
||||
validate_requirements(
|
||||
&WindowsSandboxProvisioningSettings {
|
||||
proxy_ports: vec![1080, 3128],
|
||||
allow_local_binding: false,
|
||||
},
|
||||
WindowsSandboxProxyListeners {
|
||||
http_ports: vec![1080],
|
||||
socks_ports: vec![3128],
|
||||
},
|
||||
"[experimental_network]\nhttp_port = 3128\nsocks_port = 1080",
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_socks_port_rejects_a_mismatched_socks_listener() {
|
||||
assert!(
|
||||
validate_requirements(
|
||||
&WindowsSandboxProvisioningSettings {
|
||||
proxy_ports: vec![1080, 3128, 8081],
|
||||
allow_local_binding: false,
|
||||
},
|
||||
WindowsSandboxProxyListeners {
|
||||
http_ports: vec![3128],
|
||||
socks_ports: vec![1080, 8081],
|
||||
},
|
||||
"[experimental_network]\nhttp_port = 3128\nsocks_port = 1080",
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_socks_port_does_not_require_a_disabled_socks_listener() -> Result<()> {
|
||||
validate_requirements(
|
||||
&WindowsSandboxProvisioningSettings {
|
||||
proxy_ports: vec![3128],
|
||||
allow_local_binding: false,
|
||||
},
|
||||
WindowsSandboxProxyListeners {
|
||||
http_ports: vec![3128],
|
||||
socks_ports: Vec::new(),
|
||||
},
|
||||
"[experimental_network]\nhttp_port = 3128\nsocks_port = 1080",
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_machine_policy_fails_closed() {
|
||||
for table in NETWORK_TABLES {
|
||||
let policy = format!("[{table}]\nhttp_port = \"invalid\"");
|
||||
assert!(
|
||||
validate_requirements(
|
||||
&WindowsSandboxProvisioningSettings::default(),
|
||||
WindowsSandboxProxyListeners::default(),
|
||||
&policy,
|
||||
)
|
||||
.is_err(),
|
||||
"{table}"
|
||||
);
|
||||
}
|
||||
for table in ["network_proxy", "experimental_network"] {
|
||||
assert!(
|
||||
validate_requirements(
|
||||
&WindowsSandboxProvisioningSettings::default(),
|
||||
WindowsSandboxProxyListeners::default(),
|
||||
&format!("[{table}]\nenabled = true\n[permissions.network]\nenabled = true")
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
validate_requirements(
|
||||
&WindowsSandboxProvisioningSettings::default(),
|
||||
WindowsSandboxProxyListeners::default(),
|
||||
"[windows]\nallowed_sandbox_implementations = [\"invalid\"]"
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
22
akode-rs/windows-sandbox-service/src/main.rs
Normal file
22
akode-rs/windows-sandbox-service/src/main.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
use anyhow::Result;
|
||||
use akode_windows_sandbox_service::RunMode;
|
||||
|
||||
fn main() -> Result<()> {
|
||||
akode_windows_sandbox_service::run(parse_mode(std::env::args().skip(1))?)
|
||||
}
|
||||
|
||||
fn parse_mode(arguments: impl Iterator<Item = String>) -> Result<RunMode> {
|
||||
let arguments = arguments.collect::<Vec<_>>();
|
||||
match arguments.as_slice() {
|
||||
[] => Ok(RunMode::Service),
|
||||
[argument] if argument == "--service" => Ok(RunMode::Service),
|
||||
#[cfg(debug_assertions)]
|
||||
[argument] if argument == "--foreground" => Ok(RunMode::Foreground),
|
||||
[argument] => anyhow::bail!("unrecognized service argument {argument:?}"),
|
||||
_ => anyhow::bail!("expected at most one service argument"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "main_tests.rs"]
|
||||
mod tests;
|
||||
44
akode-rs/windows-sandbox-service/src/main_tests.rs
Normal file
44
akode-rs/windows-sandbox-service/src/main_tests.rs
Normal file
@@ -0,0 +1,44 @@
|
||||
use anyhow::Result;
|
||||
|
||||
use super::RunMode;
|
||||
use super::parse_mode;
|
||||
|
||||
#[test]
|
||||
fn defaults_to_service_mode() -> Result<()> {
|
||||
assert_eq!(parse_mode(std::iter::empty())?, RunMode::Service);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_explicit_service_mode() -> Result<()> {
|
||||
let arguments = [String::from("--service")].into_iter();
|
||||
assert_eq!(parse_mode(arguments)?, RunMode::Service);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(debug_assertions)]
|
||||
fn accepts_foreground_mode() -> Result<()> {
|
||||
let arguments = [String::from("--foreground")].into_iter();
|
||||
assert_eq!(parse_mode(arguments)?, RunMode::Foreground);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(debug_assertions))]
|
||||
fn rejects_foreground_mode_in_release_builds() {
|
||||
let arguments = [String::from("--foreground")].into_iter();
|
||||
assert!(parse_mode(arguments).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_unknown_arguments() {
|
||||
let arguments = [String::from("--unknown")].into_iter();
|
||||
assert!(parse_mode(arguments).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_multiple_arguments() {
|
||||
let arguments = [String::from("--service"), String::from("--foreground")].into_iter();
|
||||
assert!(parse_mode(arguments).is_err());
|
||||
}
|
||||
121
akode-rs/windows-sandbox-service/src/package_identity.rs
Normal file
121
akode-rs/windows-sandbox-service/src/package_identity.rs
Normal file
@@ -0,0 +1,121 @@
|
||||
//! Binds provisioning requests to the packaged Codex client and its Windows user.
|
||||
|
||||
use std::io;
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::os::windows::io::FromRawHandle;
|
||||
use std::os::windows::io::OwnedHandle;
|
||||
#[cfg(debug_assertions)]
|
||||
use std::sync::atomic::AtomicBool;
|
||||
#[cfg(debug_assertions)]
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
use windows_sys::Win32::Foundation::HANDLE;
|
||||
use windows_sys::Win32::Security as security;
|
||||
use windows_sys::Win32::System::Pipes;
|
||||
use windows_sys::Win32::System::Threading;
|
||||
|
||||
mod registered;
|
||||
|
||||
pub(crate) use registered::authorize_setup_runtime;
|
||||
#[cfg(test)]
|
||||
pub(crate) use registered::require_runtime_package_family;
|
||||
#[cfg(debug_assertions)]
|
||||
static FOREGROUND_MODE: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
pub(crate) struct AuthorizedClientProcess {
|
||||
handle: OwnedHandle,
|
||||
}
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
pub(crate) fn enable_foreground_mode() {
|
||||
FOREGROUND_MODE.store(true, Ordering::Release);
|
||||
}
|
||||
|
||||
pub(crate) fn authorize_client_process(pipe: HANDLE) -> Result<AuthorizedClientProcess> {
|
||||
let mut process_id = 0;
|
||||
if unsafe { Pipes::GetNamedPipeClientProcessId(pipe, &mut process_id) } == 0 || process_id == 0
|
||||
{
|
||||
return Err(io::Error::last_os_error()).context("identify the provisioning client process");
|
||||
}
|
||||
|
||||
let process = unsafe {
|
||||
Threading::OpenProcess(Threading::PROCESS_QUERY_LIMITED_INFORMATION, 0, process_id)
|
||||
};
|
||||
if process.is_null() {
|
||||
return Err(io::Error::last_os_error()).context("open the provisioning client process");
|
||||
}
|
||||
// SAFETY: OpenProcess transferred this handle on success.
|
||||
let process = unsafe { OwnedHandle::from_raw_handle(process) };
|
||||
|
||||
let client_family =
|
||||
unsafe { akode_windows_sandbox::process_package_family(process.as_raw_handle()) }
|
||||
.context("read provisioning client package identity")?;
|
||||
let service_family =
|
||||
unsafe { akode_windows_sandbox::process_package_family(Threading::GetCurrentProcess()) }
|
||||
.context("read provisioning service package identity")?;
|
||||
match client_family {
|
||||
Some(client_family) => match service_family.as_deref() {
|
||||
Some(service_family) if client_family != service_family => {
|
||||
bail!("provisioning client package does not match the service package")
|
||||
}
|
||||
Some(_) => {}
|
||||
#[cfg(debug_assertions)]
|
||||
None if FOREGROUND_MODE.load(Ordering::Acquire)
|
||||
&& is_known_codex_package_family(&client_family) => {}
|
||||
#[cfg(debug_assertions)]
|
||||
None if FOREGROUND_MODE.load(Ordering::Acquire) => {
|
||||
bail!("provisioning client does not belong to a trusted Codex package family")
|
||||
}
|
||||
None => bail!("provisioning service has no package identity"),
|
||||
},
|
||||
#[cfg(debug_assertions)]
|
||||
None if FOREGROUND_MODE.load(Ordering::Acquire) => {}
|
||||
None => bail!("provisioning clients must run with an installed Codex package identity"),
|
||||
}
|
||||
|
||||
Ok(AuthorizedClientProcess { handle: process })
|
||||
}
|
||||
|
||||
pub(crate) fn authorize_client(
|
||||
process: &AuthorizedClientProcess,
|
||||
client_token: HANDLE,
|
||||
) -> Result<()> {
|
||||
let mut process_token = std::ptr::null_mut();
|
||||
if unsafe {
|
||||
Threading::OpenProcessToken(
|
||||
process.handle.as_raw_handle(),
|
||||
security::TOKEN_QUERY,
|
||||
&mut process_token,
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(io::Error::last_os_error())
|
||||
.context("open the provisioning client process token");
|
||||
}
|
||||
// SAFETY: OpenProcessToken transferred this handle on success.
|
||||
let process_token = unsafe { OwnedHandle::from_raw_handle(process_token) };
|
||||
let process_user =
|
||||
unsafe { akode_windows_sandbox::get_user_sid_bytes(process_token.as_raw_handle()) }
|
||||
.context("read the client process user")?;
|
||||
let impersonated_user = unsafe { akode_windows_sandbox::get_user_sid_bytes(client_token) }
|
||||
.context("read the impersonated client user")?;
|
||||
if process_user != impersonated_user {
|
||||
bail!("provisioning client process does not belong to the impersonated user");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
fn is_known_codex_package_family(package_family: &str) -> bool {
|
||||
matches!(
|
||||
package_family,
|
||||
"OpenAI.Codex_3k8sg7r9htsxt"
|
||||
| "OpenAI.CodexAlpha_3k8sg7r9htsxt"
|
||||
| "OpenAI.CodexBeta_3k8sg7r9htsxt"
|
||||
| "OpenAI.CodexNightly_3k8sg7r9htsxt"
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
//! Admits registered Core only from the service's installed package version and
|
||||
//! prevents legacy setup from replacing accounts owned by a registered runtime.
|
||||
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
use akode_windows_sandbox::SetupRuntime;
|
||||
use windows_sys::Win32::System::Threading;
|
||||
|
||||
use super::AuthorizedClientProcess;
|
||||
use crate::ipc::ServiceRequest;
|
||||
|
||||
pub(crate) fn authorize_setup_runtime(
|
||||
process: &AuthorizedClientProcess,
|
||||
request: &ServiceRequest,
|
||||
) -> Result<SetupRuntime> {
|
||||
match request {
|
||||
ServiceRequest::ProvisionSandbox(request) if request.registered_core => {
|
||||
authorize_runtime_client_process(process)?;
|
||||
Ok(SetupRuntime::Registered)
|
||||
}
|
||||
ServiceRequest::ProvisionSandbox(_) => {
|
||||
anyhow::ensure!(
|
||||
crate::installation_record::load_runtime()?.is_none(),
|
||||
"registered Core owns these sandbox accounts; legacy provisioning is not permitted"
|
||||
);
|
||||
Ok(SetupRuntime::Legacy)
|
||||
}
|
||||
ServiceRequest::RegisterInstallation { .. } => Ok(SetupRuntime::Legacy),
|
||||
}
|
||||
}
|
||||
|
||||
fn authorize_runtime_client_process(process: &AuthorizedClientProcess) -> Result<()> {
|
||||
let client_family =
|
||||
unsafe { akode_windows_sandbox::process_package_family(process.handle.as_raw_handle()) }
|
||||
.context("read runtime registration client package family")?;
|
||||
let service_family =
|
||||
unsafe { akode_windows_sandbox::process_package_family(Threading::GetCurrentProcess()) }
|
||||
.context("read runtime registration service package family")?;
|
||||
require_runtime_package_family(client_family.as_deref(), service_family.as_deref())?;
|
||||
let mut image = [0u16; 32768];
|
||||
let mut length = image.len() as u32;
|
||||
if unsafe {
|
||||
Threading::QueryFullProcessImageNameW(
|
||||
process.handle.as_raw_handle(),
|
||||
0,
|
||||
image.as_mut_ptr(),
|
||||
&mut length,
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(std::io::Error::last_os_error()).context("read provisioning client image");
|
||||
}
|
||||
let image = std::path::PathBuf::from(String::from_utf16(&image[..length as usize])?);
|
||||
let image = image.canonicalize()?;
|
||||
let service = std::env::current_exe()?.canonicalize()?;
|
||||
let directory = service.parent().context("service image has no directory")?;
|
||||
anyhow::ensure!(
|
||||
["akode.exe", "akode-code-mode-host.exe"]
|
||||
.iter()
|
||||
.any(|name| {
|
||||
image
|
||||
.as_os_str()
|
||||
.eq_ignore_ascii_case(directory.join(name).as_os_str())
|
||||
}),
|
||||
"registered Core caller is not from this installed service version"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn require_runtime_package_family(
|
||||
client: Option<&str>,
|
||||
service: Option<&str>,
|
||||
) -> Result<()> {
|
||||
match (client, service) {
|
||||
(Some(client), Some(service)) if client == service => Ok(()),
|
||||
_ => bail!(
|
||||
"runtime registration requires a client in the service's installed package family"
|
||||
),
|
||||
}
|
||||
}
|
||||
322
akode-rs/windows-sandbox-service/src/package_lifecycle.rs
Normal file
322
akode-rs/windows-sandbox-service/src/package_lifecycle.rs
Normal file
@@ -0,0 +1,322 @@
|
||||
//! Restores owner-scoped uninstall notifications and ties file cleanup to pinned directories.
|
||||
//! Registered runtime policy stays in its private module; owner tokens and pins stay here.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::io;
|
||||
use std::os::windows::io::AsHandle;
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::os::windows::io::FromRawHandle;
|
||||
use std::os::windows::io::OwnedHandle;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use akode_windows_sandbox::DirectoryOpenDisposition;
|
||||
use akode_windows_sandbox::PreparedWindowsSandboxCleanup;
|
||||
use akode_windows_sandbox::create_directory_guard;
|
||||
use akode_windows_sandbox::prepare_packaged_windows_sandbox_cleanup;
|
||||
use akode_windows_sandbox::string_from_sid_bytes;
|
||||
use windows::ApplicationModel::Package;
|
||||
use windows::ApplicationModel::PackageCatalog;
|
||||
use windows::ApplicationModel::PackageUninstallingEventArgs;
|
||||
use windows::Foundation::EventRegistrationToken;
|
||||
use windows::Foundation::TypedEventHandler;
|
||||
use windows::Win32::System::WinRT::RO_INIT_MULTITHREADED;
|
||||
use windows::Win32::System::WinRT::RoInitialize;
|
||||
use windows::Win32::System::WinRT::RoUninitialize;
|
||||
use windows::core::HSTRING;
|
||||
use windows_sys::Win32::Foundation::HANDLE;
|
||||
use windows_sys::Win32::Security as security;
|
||||
use windows_sys::Win32::Storage::FileSystem as filesystem;
|
||||
use windows_sys::Win32::System::RemoteDesktop::WTS_CURRENT_SERVER_HANDLE;
|
||||
use windows_sys::Win32::System::RemoteDesktop::WTSEnumerateSessionsW;
|
||||
use windows_sys::Win32::System::RemoteDesktop::WTSFreeMemory;
|
||||
use windows_sys::Win32::System::RemoteDesktop::WTSQueryUserToken;
|
||||
|
||||
use crate::installation_record::InstallationRecord;
|
||||
|
||||
mod cleanup;
|
||||
mod registered;
|
||||
|
||||
pub(crate) use registered::runtime_owner_removed;
|
||||
|
||||
struct UserInstallation {
|
||||
codex_home: Option<PathBuf>,
|
||||
// Ancestors and home remain pinned until owner-scoped cleanup finishes.
|
||||
directory_handles: Vec<OwnedHandle>,
|
||||
directory_guard: Option<OwnedHandle>,
|
||||
record: InstallationRecord,
|
||||
user_token: OwnedHandle,
|
||||
catalog: PackageCatalog,
|
||||
token: EventRegistrationToken,
|
||||
}
|
||||
|
||||
pub(crate) struct PackageLifecycle {
|
||||
package_name: HSTRING,
|
||||
preinstalled: bool,
|
||||
uninstalling: Arc<AtomicBool>,
|
||||
installation: RefCell<Option<UserInstallation>>,
|
||||
}
|
||||
|
||||
impl PackageLifecycle {
|
||||
pub(crate) fn new(uninstalling: Arc<AtomicBool>) -> Result<Self> {
|
||||
unsafe { RoInitialize(RO_INIT_MULTITHREADED) }
|
||||
.context("initialize the sandbox service Windows Runtime apartment")?;
|
||||
let package = Package::Current()?;
|
||||
// Windows removes OEM metadata on uninstall; capture it while the package is installed.
|
||||
let preinstalled = package
|
||||
.InstalledLocation()
|
||||
.and_then(|location| location.Path())
|
||||
.is_ok_and(|path| {
|
||||
PathBuf::from(path.to_os_string())
|
||||
.join("microsoft.system.package.metadata")
|
||||
.join("Custom.data")
|
||||
.is_file()
|
||||
});
|
||||
Ok(Self {
|
||||
package_name: package.Id()?.FullName()?,
|
||||
preinstalled,
|
||||
uninstalling,
|
||||
installation: RefCell::default(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn register_authenticated_user(
|
||||
&self,
|
||||
mut record: InstallationRecord,
|
||||
user_token: OwnedHandle,
|
||||
) -> Result<InstallationRecord> {
|
||||
let mut active = self.installation.borrow_mut();
|
||||
let previous = match active.as_ref() {
|
||||
Some(installation) => Some(installation.record.clone()),
|
||||
None => crate::installation_record::load()?,
|
||||
};
|
||||
if let Some(previous) = previous {
|
||||
// A missing watcher does not retire its owner; other clients can use elevated setup.
|
||||
ensure!(
|
||||
previous.user_sid == record.user_sid && previous.codex_home == record.codex_home,
|
||||
crate::ipc::ServiceUnavailable(
|
||||
"installation is already registered to a different owner or home"
|
||||
)
|
||||
);
|
||||
record.desktop_installation = previous
|
||||
.desktop_installation
|
||||
.or(record.desktop_installation);
|
||||
}
|
||||
record = crate::installation_record::save(record)?;
|
||||
if let Some(installation) = active.as_mut()
|
||||
&& installation.codex_home.is_some()
|
||||
{
|
||||
// A restored watcher must immediately use newly registered desktop ownership.
|
||||
installation.record = record.clone();
|
||||
return Ok(record);
|
||||
}
|
||||
|
||||
let saved_record = record.clone();
|
||||
with_owner_impersonation(user_token.as_raw_handle(), || {
|
||||
let mut directory_handles = Vec::new();
|
||||
let mut directory_guard = None;
|
||||
let codex_home = match crate::ipc::pin_existing_ancestors(
|
||||
&record.codex_home,
|
||||
&mut directory_handles,
|
||||
)
|
||||
.and_then(|()| {
|
||||
let home = directory_handles
|
||||
.last()
|
||||
.context("pin the registered home")?;
|
||||
let guard = create_directory_guard(home.as_handle())?;
|
||||
// Reject a conversion that happened before the handle-relative guard was created.
|
||||
drop(crate::ipc::pin_directory(
|
||||
&record.codex_home,
|
||||
filesystem::FILE_READ_ATTRIBUTES,
|
||||
DirectoryOpenDisposition::OpenExisting,
|
||||
)?);
|
||||
directory_guard = Some(guard);
|
||||
Ok(())
|
||||
}) {
|
||||
Ok(()) => Some(record.codex_home.clone()),
|
||||
Err(error) => {
|
||||
directory_handles.clear();
|
||||
crate::service::log_error(
|
||||
crate::service::EVENT_SERVICE_FAILED,
|
||||
&format!(
|
||||
"skipping sandbox file cleanup because the home could not be pinned: {error:#}"
|
||||
),
|
||||
);
|
||||
None
|
||||
}
|
||||
};
|
||||
if let Some(installation) = active.as_mut() {
|
||||
installation.codex_home = codex_home;
|
||||
installation.directory_handles = directory_handles;
|
||||
installation.directory_guard = directory_guard;
|
||||
installation.record = record;
|
||||
return Ok(());
|
||||
}
|
||||
let catalog = PackageCatalog::OpenForCurrentUser().context(
|
||||
crate::ipc::ServiceUnavailable("open the authenticated user's package catalog"),
|
||||
)?;
|
||||
let package_name = self.package_name.clone();
|
||||
let uninstalling = Arc::clone(&self.uninstalling);
|
||||
let owner_sid = record.user_sid.clone();
|
||||
let token = catalog
|
||||
.PackageUninstalling(&TypedEventHandler::<
|
||||
PackageCatalog,
|
||||
PackageUninstallingEventArgs,
|
||||
>::new(move |_, event| {
|
||||
if let Some(event) = event
|
||||
&& event.Package()?.Id()?.FullName()? == package_name
|
||||
{
|
||||
registered::on_package_uninstalling(event, &owner_sid, &uninstalling)?;
|
||||
}
|
||||
Ok(())
|
||||
}))
|
||||
.context(crate::ipc::ServiceUnavailable(
|
||||
"subscribe to authenticated package uninstall notifications",
|
||||
))?;
|
||||
active.replace(UserInstallation {
|
||||
codex_home,
|
||||
directory_handles,
|
||||
directory_guard,
|
||||
record,
|
||||
user_token,
|
||||
catalog,
|
||||
token,
|
||||
});
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(saved_record)
|
||||
}
|
||||
|
||||
pub(crate) fn restore_logged_in_owner(&self, recorded_session_id: u32) -> Result<()> {
|
||||
let Err(error) = self.restore_authenticated_user(recorded_session_id) else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
// Session IDs can change while the service is stopped; the owner SID is durable.
|
||||
let mut sessions = std::ptr::null_mut();
|
||||
let mut count = 0;
|
||||
if unsafe {
|
||||
WTSEnumerateSessionsW(
|
||||
WTS_CURRENT_SERVER_HANDLE,
|
||||
/*reserved*/ 0,
|
||||
/*version*/ 1,
|
||||
&mut sessions,
|
||||
&mut count,
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(io::Error::last_os_error()).context("list current Windows sessions");
|
||||
}
|
||||
let restored = (0..count).any(|index| {
|
||||
let session_id = unsafe { (*sessions.add(index as usize)).SessionId };
|
||||
session_id != recorded_session_id && self.restore_authenticated_user(session_id).is_ok()
|
||||
});
|
||||
unsafe { WTSFreeMemory(sessions.cast()) };
|
||||
if restored { Ok(()) } else { Err(error) }
|
||||
}
|
||||
|
||||
pub(crate) fn restore_authenticated_user(&self, session_id: u32) -> Result<()> {
|
||||
if self.installation.borrow().is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(record) = crate::installation_record::load()? else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
if record.runtime.is_some()
|
||||
&& !crate::installation_record::is_current_package_family(&record)?
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
let mut raw_token = std::ptr::null_mut();
|
||||
if unsafe { WTSQueryUserToken(session_id, &mut raw_token) } == 0 {
|
||||
return Err(io::Error::last_os_error()).context("open the logged-in user's token");
|
||||
}
|
||||
// SAFETY: WTSQueryUserToken transferred this handle on success.
|
||||
let token = unsafe { OwnedHandle::from_raw_handle(raw_token) };
|
||||
let user = unsafe { akode_windows_sandbox::get_user_sid_bytes(token.as_raw_handle()) }?;
|
||||
let user_sid = string_from_sid_bytes(&user).map_err(anyhow::Error::msg)?;
|
||||
ensure!(
|
||||
user_sid == record.user_sid,
|
||||
"logged-in user does not match the recorded sandbox owner"
|
||||
);
|
||||
|
||||
self.register_authenticated_user(
|
||||
InstallationRecord {
|
||||
session_id,
|
||||
..record
|
||||
},
|
||||
token,
|
||||
)
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
pub(crate) fn clean_up(&self) -> Result<()> {
|
||||
let _setup_lock =
|
||||
akode_windows_sandbox::acquire_sandbox_setup_lock(/*timeout_ms*/ 5_000)?;
|
||||
if let Some(record) = crate::installation_record::load_runtime()? {
|
||||
return registered::clean_up(self, record);
|
||||
}
|
||||
// Preserve the legacy path's ownership retirement before native preparation.
|
||||
crate::installation_record::remove()?;
|
||||
self.clean_up_resources(
|
||||
&prepare_packaged_windows_sandbox_cleanup()?,
|
||||
/*runtime*/ None,
|
||||
)
|
||||
}
|
||||
|
||||
fn clean_up_resources(
|
||||
&self,
|
||||
prepared: &PreparedWindowsSandboxCleanup,
|
||||
runtime: Option<&InstallationRecord>,
|
||||
) -> Result<()> {
|
||||
let mut installation = self.installation.borrow_mut();
|
||||
let installation = installation
|
||||
.as_mut()
|
||||
.context("the authenticated package installation was not recorded")?;
|
||||
cleanup::clean_up(
|
||||
installation,
|
||||
prepared,
|
||||
runtime,
|
||||
&self.uninstalling,
|
||||
/*preinstalled*/ self.preinstalled,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn with_owner_impersonation<T>(
|
||||
user_token: HANDLE,
|
||||
operation: impl FnOnce() -> Result<T>,
|
||||
) -> Result<T> {
|
||||
if unsafe { security::ImpersonateLoggedOnUser(user_token) } == 0 {
|
||||
return Err(io::Error::last_os_error()).context("impersonate the sandbox owner");
|
||||
}
|
||||
let result = operation();
|
||||
if unsafe { security::RevertToSelf() } == 0 {
|
||||
crate::service::log_error(
|
||||
crate::service::EVENT_SERVICE_FAILED,
|
||||
&format!(
|
||||
"unable to revert sandbox-owner impersonation: {}",
|
||||
io::Error::last_os_error()
|
||||
),
|
||||
);
|
||||
// Continuing as the user would make later machine cleanup unsafe.
|
||||
std::process::abort();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
impl Drop for PackageLifecycle {
|
||||
fn drop(&mut self) {
|
||||
if let Some(installation) = self.installation.get_mut().take() {
|
||||
let _ = installation
|
||||
.catalog
|
||||
.RemovePackageUninstalling(installation.token);
|
||||
}
|
||||
unsafe { RoUninitialize() };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
//! Removes one authenticated owner's sandbox resources using prepared native cleanup.
|
||||
//! Owner impersonation, directory pins, and registration-aware cleanup order are preserved.
|
||||
|
||||
use std::io;
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use akode_windows_sandbox::PreparedWindowsSandboxCleanup;
|
||||
use akode_windows_sandbox::resolve_sid;
|
||||
use akode_windows_sandbox::revoke_ace;
|
||||
|
||||
use super::UserInstallation;
|
||||
use super::with_owner_impersonation;
|
||||
use crate::installation_record::InstallationRecord;
|
||||
use crate::service::EVENT_CLEANUP_DETAIL;
|
||||
use crate::service::log_error;
|
||||
use crate::service::log_information;
|
||||
|
||||
pub(super) fn clean_up(
|
||||
installation: &mut UserInstallation,
|
||||
prepared: &PreparedWindowsSandboxCleanup,
|
||||
runtime: Option<&InstallationRecord>,
|
||||
uninstalling: &AtomicBool,
|
||||
preinstalled: bool,
|
||||
) -> Result<()> {
|
||||
crate::service::log_information(
|
||||
crate::service::EVENT_CLEANUP_STARTED,
|
||||
"sandbox uninstall cleanup started",
|
||||
);
|
||||
let codex_home = installation.codex_home.clone();
|
||||
// Remove exact grants from the locked cleanup record before native account deletion.
|
||||
if let Some(record) = runtime {
|
||||
log_cleanup("removing registered runtime metadata");
|
||||
crate::registered_runtime::remove_metadata(
|
||||
installation.user_token.as_raw_handle(),
|
||||
record,
|
||||
)?;
|
||||
}
|
||||
log_cleanup("removing native sandbox resources");
|
||||
let mut prune_codex_home = false;
|
||||
// Once owner-scoped deletion releases the home, retries must not traverse it as SYSTEM.
|
||||
let sandbox_home = codex_home
|
||||
.as_deref()
|
||||
.filter(|_| installation.directory_guard.is_some());
|
||||
let result = prepared.finish(sandbox_home, log_cleanup, || {
|
||||
if let Some(record) = runtime
|
||||
&& !super::registered::owner_allows_cleanup(uninstalling, record)?
|
||||
{
|
||||
// Only the old sandbox resources are repaired on reinstall. Never remove
|
||||
// the reinstalled app's desktop-created home or runtime cache.
|
||||
log_cleanup("skipping desktop directories: owner reinstalled the app");
|
||||
return Ok(());
|
||||
}
|
||||
let Some(desktop) = &installation.record.desktop_installation else {
|
||||
log_cleanup("skipping desktop directories: no desktop installation record");
|
||||
return Ok(());
|
||||
};
|
||||
// The marker is user-writable. It must never authorize deletion as LocalSystem.
|
||||
with_owner_impersonation(installation.user_token.as_raw_handle(), || {
|
||||
let mut errors = Vec::new();
|
||||
let mut record_result = |operation: &str, result: io::Result<()>| match result {
|
||||
Ok(()) => log_cleanup(&format!("{operation}: completed")),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {
|
||||
log_cleanup(&format!("{operation}: skipped, not found"));
|
||||
}
|
||||
Err(error) => {
|
||||
let message = format!("{operation}: failed, {error}");
|
||||
log_error(EVENT_CLEANUP_DETAIL, &message);
|
||||
errors.push(message);
|
||||
}
|
||||
};
|
||||
if let Some(home) = &codex_home {
|
||||
if desktop.created_codex_home
|
||||
&& crate::uninstall_policy::clean_uninstall_enabled(home, preinstalled)
|
||||
{
|
||||
// Release the home itself so it can be deleted; keep its ancestors pinned.
|
||||
if installation.directory_guard.take().is_some() {
|
||||
installation.directory_handles.pop();
|
||||
}
|
||||
record_result(
|
||||
"remove desktop-created codex home",
|
||||
std::fs::remove_dir_all(home),
|
||||
);
|
||||
} else {
|
||||
prune_codex_home = true;
|
||||
log_cleanup("preserving codex home");
|
||||
// Retained data must not keep permissions for the deleted sandbox group.
|
||||
record_result(
|
||||
"remove codex home sandbox permissions",
|
||||
resolve_sid("CodexSandboxUsers")
|
||||
.and_then(|mut sid| unsafe {
|
||||
revoke_ace(home, sid.as_mut_ptr().cast())
|
||||
})
|
||||
.map_err(io::Error::other),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
log_cleanup("skipping codex home: no pinned home");
|
||||
}
|
||||
// The cache may have been created after provisioning. Pin it only for cleanup.
|
||||
let mut cache_directory_handles = Vec::new();
|
||||
if desktop.cache_home.is_dir() {
|
||||
match crate::ipc::pin_existing_ancestors(
|
||||
&desktop.cache_home,
|
||||
&mut cache_directory_handles,
|
||||
) {
|
||||
Ok(()) => {
|
||||
record_result(
|
||||
"remove codex runtime cache",
|
||||
std::fs::remove_dir_all(desktop.cache_home.join("codex-runtimes")),
|
||||
);
|
||||
// Release only the cache root; its ancestors must remain pinned.
|
||||
cache_directory_handles.pop();
|
||||
remove_empty_directory(&desktop.cache_home, "cache home");
|
||||
}
|
||||
Err(error) => {
|
||||
log_error(
|
||||
EVENT_CLEANUP_DETAIL,
|
||||
&format!("skipping runtime cache: could not pin cache home, {error:#}"),
|
||||
);
|
||||
errors.push(error.to_string());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
log_cleanup("skipping cache home: no accessible directory");
|
||||
}
|
||||
ensure!(
|
||||
errors.is_empty(),
|
||||
"remove desktop directories: {}",
|
||||
errors.join("; ")
|
||||
);
|
||||
Ok(())
|
||||
})
|
||||
});
|
||||
result.context("remove packaged Windows sandbox resources")?;
|
||||
if prune_codex_home && let Some(home) = &codex_home {
|
||||
// Keep the home pinned through native retries. Empty-root pruning is best effort
|
||||
// so a failure cannot restart native cleanup through an unpinned home.
|
||||
if let Err(error) =
|
||||
with_owner_impersonation(installation.user_token.as_raw_handle(), || {
|
||||
if installation.directory_guard.take().is_some() {
|
||||
installation.directory_handles.pop();
|
||||
}
|
||||
remove_empty_directory(home, "codex home");
|
||||
Ok(())
|
||||
})
|
||||
{
|
||||
log_error(
|
||||
EVENT_CLEANUP_DETAIL,
|
||||
&format!("remove empty codex home: failed, {error:#}"),
|
||||
);
|
||||
}
|
||||
}
|
||||
crate::service::log_information(
|
||||
if runtime.is_some() {
|
||||
EVENT_CLEANUP_DETAIL
|
||||
} else {
|
||||
crate::service::EVENT_CLEANUP_FINISHED
|
||||
},
|
||||
if runtime.is_some() {
|
||||
"native sandbox cleanup finished; registered runtime cleanup pending"
|
||||
} else {
|
||||
"sandbox uninstall cleanup finished"
|
||||
},
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn remove_empty_directory(path: &Path, target: &str) {
|
||||
match std::fs::remove_dir(path) {
|
||||
Ok(()) => log_cleanup(&format!("removed empty {target}")),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {
|
||||
log_cleanup(&format!("skipping empty {target} removal: not found"));
|
||||
}
|
||||
Err(error) if error.kind() == io::ErrorKind::DirectoryNotEmpty => {
|
||||
log_cleanup(&format!("preserving {target}: directory is not empty"));
|
||||
}
|
||||
Err(error) => {
|
||||
log_error(
|
||||
EVENT_CLEANUP_DETAIL,
|
||||
&format!("remove empty {target}: failed, {error}"),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn log_cleanup(message: &str) {
|
||||
log_information(EVENT_CLEANUP_DETAIL, message);
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
//! Registered runtime ownership and uninstall policy for the shared package watcher.
|
||||
//! Native cleanup stays inside the caller's setup lock and precedes package removal.
|
||||
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use akode_windows_sandbox::prepare_packaged_windows_sandbox_cleanup_with_retained_tokens;
|
||||
use windows::ApplicationModel::Package;
|
||||
use windows::ApplicationModel::PackageUninstallingEventArgs;
|
||||
use windows::Management::Deployment::PackageManager;
|
||||
use windows::core::HSTRING;
|
||||
|
||||
use super::PackageLifecycle;
|
||||
use crate::installation_record::InstallationRecord;
|
||||
|
||||
pub(super) fn on_package_uninstalling(
|
||||
event: &PackageUninstallingEventArgs,
|
||||
owner_sid: &str,
|
||||
uninstalling: &AtomicBool,
|
||||
) -> windows::core::Result<()> {
|
||||
let retention = crate::installation_record::load_runtime().and_then(|record| match record {
|
||||
Some(record) if record.user_sid == owner_sid => {
|
||||
crate::registered_runtime::has_retaining_registration(&record).map(Some)
|
||||
}
|
||||
Some(_) => Ok(None),
|
||||
None => Ok(Some(false)),
|
||||
});
|
||||
match retention {
|
||||
Ok(Some(true)) => {
|
||||
// Removing an old version during update must not remove the
|
||||
// managed user's registration. Check the whole family only
|
||||
// after the owner's uninstall has completed.
|
||||
if event.IsComplete()? {
|
||||
crate::service::wake_listener();
|
||||
}
|
||||
}
|
||||
Ok(None) => {}
|
||||
Ok(Some(false)) => {
|
||||
// No actual managed registration keeps this service installed,
|
||||
// even if a failed attempt left intent. Retain SCM-stop cleanup.
|
||||
uninstalling.store(!event.IsComplete()?, Ordering::Release);
|
||||
}
|
||||
Err(error) => crate::service::log_error(
|
||||
crate::service::EVENT_SERVICE_FAILED,
|
||||
&format!("unable to read registered runtime ownership: {error:#}"),
|
||||
),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The shared cleanup entry holds the setup mutex until this function returns.
|
||||
pub(super) fn clean_up(lifecycle: &PackageLifecycle, record: InstallationRecord) -> Result<()> {
|
||||
if !crate::installation_record::is_current_package_family(&record)? {
|
||||
return Ok(());
|
||||
}
|
||||
ensure!(
|
||||
record.runtime()?.retiring.is_none(),
|
||||
"interrupted runtime cleanup requires repair"
|
||||
);
|
||||
ensure!(
|
||||
owner_allows_cleanup(&lifecycle.uninstalling, &record)?,
|
||||
"registered runtime owner still has the app installed"
|
||||
);
|
||||
ensure!(
|
||||
lifecycle
|
||||
.installation
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.is_some_and(|installation| {
|
||||
installation.record.user_sid == record.user_sid
|
||||
&& installation.codex_home.as_ref() == Some(&record.codex_home)
|
||||
}),
|
||||
"waiting for the authenticated runtime owner and home before sandbox file cleanup"
|
||||
);
|
||||
let mut record = crate::registered_runtime::prepare_cleanup(record)?;
|
||||
let removal = {
|
||||
let installation = lifecycle.installation.borrow();
|
||||
let installation = installation
|
||||
.as_ref()
|
||||
.context("authenticated installation is missing")?;
|
||||
crate::registered_runtime::prepare_removal(
|
||||
installation.user_token.as_raw_handle(),
|
||||
&mut record,
|
||||
)?
|
||||
};
|
||||
let prepared =
|
||||
prepare_packaged_windows_sandbox_cleanup_with_retained_tokens(&removal.tokens())?;
|
||||
// A reinstall before this boundary cancels without retiring resources.
|
||||
ensure!(
|
||||
owner_allows_cleanup(&lifecycle.uninstalling, &record)?,
|
||||
"owner reinstalled before native cleanup started"
|
||||
);
|
||||
crate::installation_record::save_runtime(&record)?;
|
||||
// Retry only in this live invocation, retaining the outer setup lock.
|
||||
// A stored retirement fence is never proof that native cleanup finished.
|
||||
crate::service::retry_cleanup(|| lifecycle.clean_up_resources(&prepared, Some(&record)))?;
|
||||
removal.commit()
|
||||
}
|
||||
|
||||
pub(super) fn owner_allows_cleanup(
|
||||
uninstalling: &AtomicBool,
|
||||
record: &InstallationRecord,
|
||||
) -> Result<bool> {
|
||||
let packages = PackageManager::new()?.FindPackagesByUserSecurityIdPackageFamilyName(
|
||||
&HSTRING::from(&record.user_sid),
|
||||
&HSTRING::from(&record.runtime()?.package_family),
|
||||
)?;
|
||||
let iterator = packages.First()?;
|
||||
let mut has_current = iterator.HasCurrent()?;
|
||||
if !has_current {
|
||||
return Ok(true);
|
||||
}
|
||||
if !uninstalling.load(Ordering::Acquire)
|
||||
|| crate::registered_runtime::has_retaining_registration(record)?
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
// SCM may stop us before this exact package is removed. A successor version
|
||||
// belongs to an update or reinstall and must keep its desktop data.
|
||||
let retiring_package = Package::Current()?.Id()?.FullName()?;
|
||||
while has_current {
|
||||
if iterator.Current()?.Id()?.FullName()? != retiring_package {
|
||||
return Ok(false);
|
||||
}
|
||||
has_current = iterator.MoveNext()?;
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// The managed registration must not keep the package alive after its owner
|
||||
/// uninstalls it, but an update to another version of the family is not uninstall.
|
||||
pub(crate) fn runtime_owner_removed() -> Result<bool> {
|
||||
let Some(record) = crate::installation_record::load_runtime()? else {
|
||||
return Ok(false);
|
||||
};
|
||||
Ok(
|
||||
crate::installation_record::is_current_package_family(&record)?
|
||||
&& !runtime_owner_has_package(&record)?,
|
||||
)
|
||||
}
|
||||
|
||||
// Callers have verified that the record belongs to this service's package family.
|
||||
pub(super) fn runtime_owner_has_package(record: &InstallationRecord) -> Result<bool> {
|
||||
let packages = PackageManager::new()?.FindPackagesByUserSecurityIdPackageFamilyName(
|
||||
&HSTRING::from(&record.user_sid),
|
||||
&HSTRING::from(&record.runtime()?.package_family),
|
||||
)?;
|
||||
Ok(packages.First()?.HasCurrent()?)
|
||||
}
|
||||
146
akode-rs/windows-sandbox-service/src/provisioning.rs
Normal file
146
akode-rs/windows-sandbox-service/src/provisioning.rs
Normal file
@@ -0,0 +1,146 @@
|
||||
//! Provisions an authenticated client's sandbox through its selected setup path.
|
||||
|
||||
pub(crate) mod legacy_bin;
|
||||
mod registered;
|
||||
|
||||
use std::os::windows::fs::MetadataExt;
|
||||
use std::os::windows::io::AsHandle;
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::os::windows::io::OwnedHandle;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
use akode_windows_sandbox::SandboxProvisioningResponse;
|
||||
use akode_windows_sandbox::SetupRuntime;
|
||||
use akode_windows_sandbox::run_elevated_provisioning_setup_with_retained_handles;
|
||||
use windows_sys::Win32::Storage::FileSystem as filesystem;
|
||||
|
||||
use crate::installation_record::InstallationRecord;
|
||||
use crate::ipc::ClientIdentity;
|
||||
use crate::ipc::ServiceRequest;
|
||||
|
||||
// The lifecycle callback validates ownership and returns the canonical saved record.
|
||||
fn register_owner(
|
||||
identity: &ClientIdentity,
|
||||
on_authenticated_user: &dyn Fn(
|
||||
InstallationRecord,
|
||||
OwnedHandle,
|
||||
akode_windows_sandbox::SetupRuntime,
|
||||
) -> Result<InstallationRecord>,
|
||||
) -> Result<InstallationRecord> {
|
||||
let token = identity
|
||||
.token
|
||||
.try_clone()
|
||||
.context("retain authenticated uninstall owner")?;
|
||||
on_authenticated_user(
|
||||
InstallationRecord {
|
||||
codex_home: identity.codex_home.clone(),
|
||||
user_sid: identity.user_sid.clone(),
|
||||
session_id: identity.session_id,
|
||||
desktop_installation: identity.desktop_installation.clone(),
|
||||
runtime: None,
|
||||
},
|
||||
token,
|
||||
identity.runtime,
|
||||
)
|
||||
}
|
||||
|
||||
fn setup_is_complete(
|
||||
identity: &ClientIdentity,
|
||||
settings: &akode_windows_sandbox::WindowsSandboxProvisioningSettings,
|
||||
) -> Result<bool> {
|
||||
crate::package_lifecycle::with_owner_impersonation(identity.token.as_raw_handle(), || {
|
||||
Ok(
|
||||
akode_windows_sandbox::sandbox_setup_is_complete_with_settings(
|
||||
&identity.codex_home,
|
||||
settings,
|
||||
),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn run(
|
||||
identity: ClientIdentity,
|
||||
request: ServiceRequest,
|
||||
sandbox_sid: &[u8],
|
||||
shutdown: &AtomicBool,
|
||||
on_authenticated_user: &dyn Fn(
|
||||
InstallationRecord,
|
||||
OwnedHandle,
|
||||
akode_windows_sandbox::SetupRuntime,
|
||||
) -> Result<InstallationRecord>,
|
||||
) -> Result<SandboxProvisioningResponse> {
|
||||
let request = match request {
|
||||
ServiceRequest::RegisterInstallation { .. } => {
|
||||
let installation = InstallationRecord {
|
||||
codex_home: identity.codex_home,
|
||||
user_sid: identity.user_sid,
|
||||
session_id: identity.session_id,
|
||||
desktop_installation: identity.desktop_installation,
|
||||
runtime: None,
|
||||
};
|
||||
on_authenticated_user(installation, identity.token, identity.runtime)?;
|
||||
return Ok(SandboxProvisioningResponse::Ok);
|
||||
}
|
||||
ServiceRequest::ProvisionSandbox(request) => request,
|
||||
};
|
||||
if identity.runtime == SetupRuntime::Registered {
|
||||
return registered::run(
|
||||
&identity,
|
||||
request,
|
||||
sandbox_sid,
|
||||
shutdown,
|
||||
on_authenticated_user,
|
||||
);
|
||||
}
|
||||
let settings = request.settings;
|
||||
register_owner(&identity, on_authenticated_user)?;
|
||||
if setup_is_complete(&identity, &settings)? {
|
||||
return Ok(SandboxProvisioningResponse::Ok);
|
||||
}
|
||||
let helper = std::env::current_exe()
|
||||
.context("locate the provisioning service executable")?
|
||||
.with_file_name("akode-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()
|
||||
);
|
||||
}
|
||||
legacy_bin::prepare(&identity.codex_home, identity.token.as_handle())?;
|
||||
let retained_handles = identity
|
||||
.directory_handles
|
||||
.iter()
|
||||
// The identity owns these handles through the synchronous helper launch and wait.
|
||||
.map(AsHandle::as_handle)
|
||||
.collect::<Vec<_>>();
|
||||
match run_elevated_provisioning_setup_with_retained_handles(
|
||||
&identity.codex_home,
|
||||
&identity.account,
|
||||
settings,
|
||||
identity.runtime,
|
||||
&retained_handles,
|
||||
) {
|
||||
Ok(()) => {
|
||||
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")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
//! Upgrade the protected ACL written by the old legacy helper before SYSTEM reuses the bin.
|
||||
use std::io;
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::os::windows::io::BorrowedHandle;
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use akode_windows_sandbox::DirectoryOpenDisposition;
|
||||
use windows::Win32::Foundation::BOOL;
|
||||
use windows_sys::Win32::Foundation::ERROR_ACCESS_DENIED;
|
||||
use windows_sys::Win32::Security as security;
|
||||
use windows_sys::Win32::Storage::FileSystem as fs;
|
||||
|
||||
/// Admission has pinned the authenticated user's no-reparse path through the helper call.
|
||||
pub(crate) fn prepare(home: &Path, owner: BorrowedHandle<'_>) -> Result<()> {
|
||||
let bin = home.join(".sandbox-bin");
|
||||
let open = || {
|
||||
akode_windows_sandbox::open_directory_no_reparse(
|
||||
&bin,
|
||||
fs::READ_CONTROL | fs::WRITE_DAC,
|
||||
fs::FILE_SHARE_READ | fs::FILE_SHARE_WRITE | fs::FILE_SHARE_DELETE,
|
||||
DirectoryOpenDisposition::OpenExisting,
|
||||
)
|
||||
};
|
||||
match open() {
|
||||
Ok(_) => return Ok(()),
|
||||
Err(error)
|
||||
if error
|
||||
.downcast_ref::<io::Error>()
|
||||
.is_some_and(|cause| cause.raw_os_error() == Some(ERROR_ACCESS_DENIED as i32)) => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
let directory =
|
||||
crate::package_lifecycle::with_owner_impersonation(owner.as_raw_handle(), open)?;
|
||||
if let Some((mut acl, control)) = crate::registered_runtime::read_acl(&directory)? {
|
||||
upgrade_legacy_system_entry(&mut acl, control)?;
|
||||
crate::registered_runtime::write_acl(&directory, &mut acl, control)?;
|
||||
}
|
||||
open()
|
||||
.map(drop)
|
||||
.context("verify SYSTEM can protect the repaired sandbox bin")
|
||||
}
|
||||
|
||||
// The old helper wrote a protected, allow-only ACL with one inheritable SYSTEM Modify entry.
|
||||
// Alter only that entry in the in-memory ACL. A rejected edit is never written back.
|
||||
fn upgrade_legacy_system_entry(acl: &mut [u32], control: u16) -> Result<()> {
|
||||
ensure!(
|
||||
control & security::SE_DACL_PROTECTED != 0,
|
||||
"expected a protected legacy sandbox bin ACL"
|
||||
);
|
||||
let system = akode_windows_sandbox::resolve_sid("SYSTEM")?;
|
||||
let mut matched = false;
|
||||
let dacl = acl.as_mut_ptr().cast::<security::ACL>();
|
||||
for index in 0..u32::from(unsafe { (*dacl).AceCount }) {
|
||||
let mut ace = std::ptr::null_mut();
|
||||
unsafe { BOOL(security::GetAce(dacl, index, &mut ace)).ok() }
|
||||
.context("read sandbox bin ACE")?;
|
||||
let header = unsafe { &*ace.cast::<security::ACE_HEADER>() };
|
||||
ensure!(
|
||||
header.AceType == 0 && header.AceSize >= 16,
|
||||
"unsupported legacy sandbox bin ACE"
|
||||
);
|
||||
let allow = unsafe { &mut *ace.cast::<security::ACCESS_ALLOWED_ACE>() };
|
||||
let sid = std::ptr::addr_of!(allow.SidStart).cast::<u8>();
|
||||
let sid_len = usize::from(allow.Header.AceSize)
|
||||
- std::mem::offset_of!(security::ACCESS_ALLOWED_ACE, SidStart);
|
||||
if unsafe { std::slice::from_raw_parts(sid, sid_len) } == system {
|
||||
let legacy_mask = fs::FILE_GENERIC_READ
|
||||
| fs::FILE_GENERIC_WRITE
|
||||
| fs::FILE_GENERIC_EXECUTE
|
||||
| fs::DELETE;
|
||||
ensure!(
|
||||
!matched
|
||||
&& allow.Mask == legacy_mask
|
||||
&& u32::from(allow.Header.AceFlags)
|
||||
== (security::OBJECT_INHERIT_ACE | security::CONTAINER_INHERIT_ACE),
|
||||
"unexpected legacy SYSTEM permissions"
|
||||
);
|
||||
allow.Mask |= fs::WRITE_DAC;
|
||||
matched = true;
|
||||
}
|
||||
}
|
||||
ensure!(matched, "missing legacy SYSTEM allow entry");
|
||||
Ok(())
|
||||
}
|
||||
222
akode-rs/windows-sandbox-service/src/provisioning/registered.rs
Normal file
222
akode-rs/windows-sandbox-service/src/provisioning/registered.rs
Normal file
@@ -0,0 +1,222 @@
|
||||
//! The registered-Core setup transaction: admit, provision, register, then publish readiness.
|
||||
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::os::windows::io::OwnedHandle;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use akode_windows_sandbox::SandboxAccountCredentialMismatch;
|
||||
use akode_windows_sandbox::SandboxProvisioningResponse;
|
||||
use akode_windows_sandbox::SandboxRuntimeAccount;
|
||||
use akode_windows_sandbox::logon_existing_sandbox_account;
|
||||
use akode_windows_sandbox::sandbox_secrets_dir;
|
||||
|
||||
use crate::ipc::ProvisioningRequest;
|
||||
use akode_windows_sandbox::string_from_sid_bytes;
|
||||
use windows::ApplicationModel::Package;
|
||||
use windows_sys::Win32::NetworkManagement::NetManagement::UF_ACCOUNTDISABLE;
|
||||
use windows_sys::Win32::NetworkManagement::NetManagement::UF_PASSWORD_EXPIRED;
|
||||
|
||||
use crate::installation_record::InstallationRecord;
|
||||
use crate::installation_record::RuntimeRegistration;
|
||||
use crate::ipc::ClientIdentity;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "registered_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
pub(super) fn run(
|
||||
identity: &ClientIdentity,
|
||||
request: ProvisioningRequest,
|
||||
sandbox_sid: &[u8],
|
||||
shutdown: &AtomicBool,
|
||||
on_authenticated_user: &dyn Fn(
|
||||
InstallationRecord,
|
||||
OwnedHandle,
|
||||
akode_windows_sandbox::SetupRuntime,
|
||||
) -> Result<InstallationRecord>,
|
||||
) -> Result<SandboxProvisioningResponse> {
|
||||
// Keep admission, account provisioning and package registration in one transaction.
|
||||
let _setup_lock = akode_windows_sandbox::acquire_sandbox_setup_lock(/*timeout_ms*/ 5_000)?;
|
||||
ensure!(
|
||||
akode_windows_sandbox::resolve_sid(akode_windows_sandbox::SANDBOX_USERS_GROUP)
|
||||
.is_ok_and(|current| current == sandbox_sid),
|
||||
akode_windows_sandbox::SANDBOX_GROUP_CHANGED
|
||||
);
|
||||
let settings = request.settings;
|
||||
let mut setup_complete = super::setup_is_complete(identity, &settings)?;
|
||||
if request.refresh_only {
|
||||
// Startup may update registrations, but must never create accounts or repair teardown.
|
||||
// Check under the setup lock, before changing ownership or sandbox accounts.
|
||||
let previous = crate::installation_record::load_runtime()?
|
||||
.context("registration refresh requires completed setup")?;
|
||||
let runtime = previous.runtime()?;
|
||||
// Windows may restart this service during registration, after readiness was
|
||||
// revoked. Resume only the same provisioned accounts; never repair setup.
|
||||
ensure!(
|
||||
previous.user_sid == identity.user_sid
|
||||
&& previous.codex_home == identity.codex_home
|
||||
&& crate::installation_record::is_current_package_family(&previous)?
|
||||
&& runtime.can_resume_registration()
|
||||
&& setup_complete,
|
||||
"registration refresh requires unchanged sandbox ownership and settings"
|
||||
);
|
||||
for entry in &runtime.accounts {
|
||||
let account = entry.account.username();
|
||||
ensure!(
|
||||
akode_windows_sandbox::local_user_flags(account)?
|
||||
.is_some_and(|flags| flags & (UF_ACCOUNTDISABLE | UF_PASSWORD_EXPIRED) == 0)
|
||||
&& string_from_sid_bytes(&akode_windows_sandbox::resolve_sid(account)?)
|
||||
.map_err(anyhow::Error::msg)?
|
||||
== entry.user_sid,
|
||||
"registration refresh cannot repair or replace a sandbox account"
|
||||
);
|
||||
}
|
||||
}
|
||||
let mut installation = super::register_owner(identity, on_authenticated_user)?;
|
||||
let result = (|| -> Result<()> {
|
||||
let package = Package::Current()?.Id()?;
|
||||
installation.runtime.get_or_insert(RuntimeRegistration {
|
||||
package_family: package.FamilyName()?.to_string(),
|
||||
accounts: Vec::new(),
|
||||
metadata_roots: Vec::new(),
|
||||
ready_package: None,
|
||||
retiring: None,
|
||||
});
|
||||
// Persist the authenticated owner before setup can rotate shared credentials.
|
||||
crate::installation_record::save_runtime(&installation)
|
||||
.context("persist registered sandbox owner")?;
|
||||
// Missing, disabled, or expired accounts require full setup before runtime logon.
|
||||
for account in [
|
||||
akode_windows_sandbox::OFFLINE_USERNAME,
|
||||
akode_windows_sandbox::ONLINE_USERNAME,
|
||||
] {
|
||||
setup_complete &= akode_windows_sandbox::local_user_flags(account)
|
||||
.with_context(|| format!("inspect registered sandbox account {account}"))?
|
||||
.is_some_and(|flags| flags & (UF_ACCOUNTDISABLE | UF_PASSWORD_EXPIRED) == 0);
|
||||
}
|
||||
if setup_complete && !request.refresh_only {
|
||||
setup_complete = !credentials_need_repair(
|
||||
&installation,
|
||||
|account| {
|
||||
crate::package_lifecycle::with_owner_impersonation(
|
||||
identity.token.as_raw_handle(),
|
||||
|| {
|
||||
let mut pins = Vec::new();
|
||||
crate::ipc::pin_existing_ancestors(
|
||||
&sandbox_secrets_dir(&identity.codex_home),
|
||||
&mut pins,
|
||||
)?;
|
||||
logon_existing_sandbox_account(&identity.codex_home, account)
|
||||
},
|
||||
)
|
||||
.with_context(|| format!("check registered sandbox account {account:?}"))
|
||||
},
|
||||
crate::registered_runtime::registered_packages,
|
||||
)?;
|
||||
}
|
||||
if !setup_complete {
|
||||
// Account state can change outside our setup lock; refresh must never repair it.
|
||||
ensure!(
|
||||
!request.refresh_only,
|
||||
"registration refresh cannot repair sandbox setup"
|
||||
);
|
||||
// Setup resolves this name for ACL trustees; it must still name the held token's user.
|
||||
let setup_owner_sid = akode_windows_sandbox::resolve_sid(&identity.account)
|
||||
.context("resolve registered sandbox setup owner")?;
|
||||
ensure!(
|
||||
string_from_sid_bytes(&setup_owner_sid).map_err(anyhow::Error::msg)?
|
||||
== identity.user_sid,
|
||||
"sandbox setup account no longer matches the authenticated owner"
|
||||
);
|
||||
akode_windows_sandbox::provision_sandbox_in_process(
|
||||
&identity.codex_home,
|
||||
&identity.account,
|
||||
settings,
|
||||
identity.runtime,
|
||||
)
|
||||
.context("provision registered sandbox accounts and permissions")?;
|
||||
}
|
||||
crate::registered_runtime::provision(
|
||||
identity,
|
||||
&mut installation,
|
||||
&package
|
||||
.FullName()
|
||||
.context("read registered sandbox package name")?,
|
||||
shutdown,
|
||||
)
|
||||
.context("prepare registered sandbox runtime")
|
||||
})();
|
||||
result
|
||||
.inspect_err(|error| {
|
||||
crate::service::log_error(
|
||||
crate::service::EVENT_PROVISIONING_FAILED,
|
||||
&format!("Codex sandbox provisioning failed: {error:#}"),
|
||||
);
|
||||
})
|
||||
.context("registered sandbox provisioning failed")?;
|
||||
crate::service::log_information(
|
||||
crate::service::EVENT_PROVISIONING_SUCCEEDED,
|
||||
"Codex sandbox provisioning completed successfully.",
|
||||
);
|
||||
Ok(SandboxProvisioningResponse::Ok)
|
||||
}
|
||||
|
||||
fn credentials_need_repair(
|
||||
installation: &InstallationRecord,
|
||||
mut logon: impl FnMut(SandboxRuntimeAccount) -> Result<OwnedHandle>,
|
||||
mut registered_packages: impl FnMut(&str, &str) -> Result<Vec<windows::core::HSTRING>>,
|
||||
) -> Result<bool> {
|
||||
crate::registered_runtime::validate_record(installation)?;
|
||||
let runtime = installation.runtime()?;
|
||||
let mut needs_repair = false;
|
||||
for account in [
|
||||
SandboxRuntimeAccount::Offline,
|
||||
SandboxRuntimeAccount::Online,
|
||||
] {
|
||||
match logon(account) {
|
||||
Ok(token) => {
|
||||
let expected = runtime
|
||||
.accounts
|
||||
.iter()
|
||||
.find(|entry| entry.account == account);
|
||||
crate::registered_runtime::validate_target(
|
||||
token.as_raw_handle() as _,
|
||||
account,
|
||||
expected.map(|entry| entry.user_sid.as_str()),
|
||||
)?;
|
||||
}
|
||||
Err(error) if error.is::<SandboxAccountCredentialMismatch>() => needs_repair = true,
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
if needs_repair {
|
||||
// Never reset recorded replacement accounts or unrecorded runtime registrations.
|
||||
// An initial migration has no recorded account SIDs yet.
|
||||
for account in [
|
||||
SandboxRuntimeAccount::Offline,
|
||||
SandboxRuntimeAccount::Online,
|
||||
] {
|
||||
let sid = akode_windows_sandbox::resolve_sid(account.username())?;
|
||||
let sid = string_from_sid_bytes(&sid).map_err(anyhow::Error::msg)?;
|
||||
if let Some(entry) = runtime
|
||||
.accounts
|
||||
.iter()
|
||||
.find(|entry| entry.account == account)
|
||||
{
|
||||
ensure!(
|
||||
sid == entry.user_sid,
|
||||
"managed runtime account was replaced"
|
||||
);
|
||||
} else {
|
||||
ensure!(
|
||||
registered_packages(&sid, &runtime.package_family)?.is_empty(),
|
||||
"sandbox account has a runtime registration not owned by this service"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(needs_repair)
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
//! Password-repair admission. Native tokens require the disposable Windows Sandbox fixture.
|
||||
|
||||
use std::os::windows::io::FromRawHandle;
|
||||
use std::os::windows::io::OwnedHandle;
|
||||
|
||||
use super::credentials_need_repair;
|
||||
use crate::registered_runtime::registered_packages;
|
||||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
use akode_windows_sandbox::InstallationRecord;
|
||||
use akode_windows_sandbox::RuntimeAccountRegistration;
|
||||
use akode_windows_sandbox::RuntimeRegistration;
|
||||
use akode_windows_sandbox::SandboxAccountCredentialMismatch;
|
||||
use akode_windows_sandbox::SandboxRuntimeAccount;
|
||||
use akode_windows_sandbox::SandboxRuntimeAccount::Offline;
|
||||
use akode_windows_sandbox::SandboxRuntimeAccount::Online;
|
||||
use akode_windows_sandbox::resolve_sid;
|
||||
use akode_windows_sandbox::string_from_sid_bytes;
|
||||
use akode_windows_sandbox::to_wide;
|
||||
use pretty_assertions::assert_eq;
|
||||
use windows_sys::Win32::Security::LOGON32_LOGON_INTERACTIVE;
|
||||
use windows_sys::Win32::Security::LOGON32_PROVIDER_DEFAULT;
|
||||
use windows_sys::Win32::Security::LogonUserW;
|
||||
|
||||
fn recorded_installation(accounts: &[SandboxRuntimeAccount]) -> InstallationRecord {
|
||||
InstallationRecord {
|
||||
user_sid: "S-1-5-21-0-0-0-1000".into(),
|
||||
codex_home: std::path::PathBuf::from(r"C:\codex-registered-test"),
|
||||
session_id: 0,
|
||||
desktop_installation: None,
|
||||
runtime: Some(RuntimeRegistration {
|
||||
package_family: "Codex.SandboxFixture_8wekyb3d8bbwe".into(),
|
||||
accounts: accounts
|
||||
.iter()
|
||||
.map(|&account| RuntimeAccountRegistration {
|
||||
cleanup_logon_pending: false,
|
||||
account,
|
||||
user_sid: format!("test-{account:?}"),
|
||||
alias_path: None,
|
||||
})
|
||||
.collect(),
|
||||
metadata_roots: Vec::new(),
|
||||
ready_package: None,
|
||||
retiring: None,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unrelated_errors_never_admit_password_repair() {
|
||||
for records in [vec![], vec![Offline], vec![Offline, Online]] {
|
||||
let record = recorded_installation(&records);
|
||||
for policy_failure in [Offline, Online] {
|
||||
let error = credentials_need_repair(
|
||||
&record,
|
||||
|account| {
|
||||
if account == policy_failure {
|
||||
Err(anyhow!("policy"))
|
||||
} else {
|
||||
Err(anyhow!(SandboxAccountCredentialMismatch))
|
||||
}
|
||||
},
|
||||
registered_packages,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.to_string(), "policy");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_records_never_admit_password_repair() {
|
||||
for (accounts, expected) in [
|
||||
(
|
||||
vec![Offline, Offline],
|
||||
"runtime registration record contains duplicate accounts",
|
||||
),
|
||||
(
|
||||
vec![Online, Online],
|
||||
"runtime registration record contains duplicate accounts",
|
||||
),
|
||||
(
|
||||
vec![Offline, Online, Offline],
|
||||
"runtime registration record has too many accounts",
|
||||
),
|
||||
] {
|
||||
let error = credentials_need_repair(
|
||||
&recorded_installation(&accounts),
|
||||
|_| Err(anyhow!(SandboxAccountCredentialMismatch)),
|
||||
registered_packages,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.to_string(), expected);
|
||||
}
|
||||
}
|
||||
|
||||
// Only in a disposable Windows Sandbox with newly created Offline/Online accounts.
|
||||
// The fixture sets SANDBOX_REPAIR_TEST_GROUPS to healthy, administrator, or missing;
|
||||
// never read or modify real credential stores.
|
||||
#[test]
|
||||
#[ignore = "requires disposable Windows Sandbox accounts and group fixture"]
|
||||
fn native_successful_sibling_validation() -> Result<()> {
|
||||
assert_eq!(
|
||||
std::env::var("USERNAME").as_deref(),
|
||||
Ok("WDAGUtilityAccount")
|
||||
);
|
||||
// Match PackageLifecycle::new before making native PackageManager queries.
|
||||
unsafe {
|
||||
windows::Win32::System::WinRT::RoInitialize(
|
||||
windows::Win32::System::WinRT::RO_INIT_MULTITHREADED,
|
||||
)?
|
||||
};
|
||||
let groups = std::env::var("SANDBOX_REPAIR_TEST_GROUPS")?;
|
||||
let mut record = recorded_installation(&[Offline, Online]);
|
||||
for entry in &mut record.runtime_mut()?.accounts {
|
||||
entry.user_sid = string_from_sid_bytes(&resolve_sid(entry.account.username())?)
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
}
|
||||
|
||||
if groups == "healthy" {
|
||||
// The fixture just made these accounts: no logon or LoadUserProfileW has run.
|
||||
// Query both real SIDs, before profiles exist, through the production WinRT API.
|
||||
assert!(credentials_need_repair(
|
||||
&recorded_installation(&[]),
|
||||
|_| Err(anyhow!(SandboxAccountCredentialMismatch)),
|
||||
registered_packages,
|
||||
)?);
|
||||
|
||||
// An absent record must not mask a same-family registration or query error
|
||||
// for either unrecorded account. Don't install packages to induce the failure.
|
||||
for unrecorded in [Offline, Online] {
|
||||
let known = record
|
||||
.runtime()?
|
||||
.accounts
|
||||
.iter()
|
||||
.find(|entry| entry.account == unrecorded)
|
||||
.unwrap();
|
||||
for accounts in [
|
||||
vec![],
|
||||
vec![if unrecorded == Offline {
|
||||
Online
|
||||
} else {
|
||||
Offline
|
||||
}],
|
||||
] {
|
||||
let mut partial = record.clone();
|
||||
partial
|
||||
.runtime_mut()?
|
||||
.accounts
|
||||
.retain(|entry| accounts.contains(&entry.account));
|
||||
for query_failed in [false, true] {
|
||||
let error = credentials_need_repair(
|
||||
&partial,
|
||||
|_| Err(anyhow!(SandboxAccountCredentialMismatch)),
|
||||
|sid, family| {
|
||||
if sid == known.user_sid {
|
||||
assert_eq!(family, record.runtime()?.package_family);
|
||||
if query_failed {
|
||||
Err(anyhow!("fixture PackageManager query failed"))
|
||||
} else {
|
||||
Ok(vec![
|
||||
"Codex.SandboxFixture_1.0.0.0_x64__8wekyb3d8bbwe".into(),
|
||||
])
|
||||
}
|
||||
} else {
|
||||
registered_packages(sid, family)
|
||||
}
|
||||
},
|
||||
)
|
||||
.unwrap_err();
|
||||
let expected = if query_failed {
|
||||
"fixture PackageManager query failed"
|
||||
} else {
|
||||
"sandbox account has a runtime registration not owned by this service"
|
||||
};
|
||||
assert_eq!(error.to_string(), expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let logon = |account: SandboxRuntimeAccount| -> Result<OwnedHandle> {
|
||||
let mut token = std::ptr::null_mut();
|
||||
let succeeded = unsafe {
|
||||
LogonUserW(
|
||||
to_wide(account.username()).as_ptr(),
|
||||
to_wide(".").as_ptr(),
|
||||
to_wide("Codex-fixture-27967!").as_ptr(),
|
||||
LOGON32_LOGON_INTERACTIVE,
|
||||
LOGON32_PROVIDER_DEFAULT,
|
||||
&mut token,
|
||||
)
|
||||
};
|
||||
anyhow::ensure!(
|
||||
succeeded != 0,
|
||||
"fixture logon: {}",
|
||||
std::io::Error::last_os_error()
|
||||
);
|
||||
Ok(unsafe { OwnedHandle::from_raw_handle(token as _) })
|
||||
};
|
||||
if groups == "healthy" {
|
||||
assert!(!credentials_need_repair(
|
||||
&record,
|
||||
logon,
|
||||
registered_packages
|
||||
)?);
|
||||
}
|
||||
for successful in [Offline, Online] {
|
||||
let attempt = |registration: &InstallationRecord| {
|
||||
credentials_need_repair(
|
||||
registration,
|
||||
|account| {
|
||||
if account == successful {
|
||||
logon(account)
|
||||
} else {
|
||||
Err(anyhow!(SandboxAccountCredentialMismatch))
|
||||
}
|
||||
},
|
||||
registered_packages,
|
||||
)
|
||||
.map_err(|error| error.to_string())
|
||||
};
|
||||
match groups.as_str() {
|
||||
"healthy" => {
|
||||
for records in [vec![], vec![Offline], vec![Online], vec![Offline, Online]] {
|
||||
let mut migration = record.clone();
|
||||
migration
|
||||
.runtime_mut()?
|
||||
.accounts
|
||||
.retain(|entry| records.contains(&entry.account));
|
||||
assert_eq!(
|
||||
attempt(&migration),
|
||||
Ok(true),
|
||||
"migration {records:?}, successful {successful:?}"
|
||||
);
|
||||
}
|
||||
for changed_account in [Offline, Online] {
|
||||
let mut changed = record.clone();
|
||||
changed
|
||||
.runtime_mut()?
|
||||
.accounts
|
||||
.iter_mut()
|
||||
.find(|entry| entry.account == changed_account)
|
||||
.unwrap()
|
||||
.user_sid = "S-1-5-21-0-0-0-999".into();
|
||||
let expected = if changed_account == successful {
|
||||
"managed runtime account SID changed"
|
||||
} else {
|
||||
"managed runtime account was replaced"
|
||||
};
|
||||
assert_eq!(attempt(&changed), Err(expected.into()));
|
||||
}
|
||||
}
|
||||
"administrator" => assert_eq!(
|
||||
attempt(&record),
|
||||
Err("managed runtime account is an administrator".into())
|
||||
),
|
||||
"missing" => assert_eq!(
|
||||
attempt(&record),
|
||||
Err("runtime account is not in CodexSandboxUsers".into())
|
||||
),
|
||||
_ => panic!("unknown fixture group state: {groups}"),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
357
akode-rs/windows-sandbox-service/src/registered_runtime.rs
Normal file
357
akode-rs/windows-sandbox-service/src/registered_runtime.rs
Normal file
@@ -0,0 +1,357 @@
|
||||
//! Owns managed-account registration, AppData metadata access, and deferred removal.
|
||||
//! Lifecycle and admission decisions stay with callers. Persist ownership before deployment;
|
||||
//! retain profiles until Windows completes, or pending resources until service exit on shutdown.
|
||||
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::os::windows::io::OwnedHandle;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use akode_windows_sandbox::APP_CORE_RUNNER_ALIAS;
|
||||
use akode_windows_sandbox::SandboxRuntimeAccount;
|
||||
use akode_windows_sandbox::logon_existing_sandbox_account;
|
||||
use akode_windows_sandbox::resolve_sid as lookup_sid;
|
||||
use akode_windows_sandbox::sandbox_secrets_dir;
|
||||
use akode_windows_sandbox::string_from_sid_bytes;
|
||||
use akode_windows_sandbox::to_wide;
|
||||
use akode_windows_sandbox::token_groups;
|
||||
use windows::Foundation::AsyncStatus;
|
||||
use windows::Management::Deployment::DeploymentOptions;
|
||||
use windows::Management::Deployment::PackageManager;
|
||||
use windows::Win32::Foundation::BOOL;
|
||||
use windows::core::HSTRING;
|
||||
use windows_sys::Win32::Foundation::HANDLE;
|
||||
use windows_sys::Win32::Security as security;
|
||||
use windows_sys::Win32::System::SystemServices::SE_GROUP_ENABLED;
|
||||
use windows_sys::Win32::UI::Shell::FOLDERID_LocalAppData;
|
||||
use windows_sys::Win32::UI::Shell::LoadUserProfileW;
|
||||
use windows_sys::Win32::UI::Shell::PROFILEINFOW;
|
||||
use windows_sys::Win32::UI::Shell::UnloadUserProfile;
|
||||
|
||||
use crate::installation_record::InstallationRecord;
|
||||
use crate::installation_record::RuntimeAccountRegistration;
|
||||
use crate::ipc::ClientIdentity;
|
||||
use crate::package_lifecycle::with_owner_impersonation;
|
||||
|
||||
mod known_folder;
|
||||
mod metadata;
|
||||
pub(crate) use metadata::read_acl;
|
||||
pub(crate) use metadata::write_acl;
|
||||
mod registration_result;
|
||||
mod removal;
|
||||
|
||||
pub(crate) use metadata::remove as remove_metadata;
|
||||
pub(crate) use removal::prepare as prepare_removal;
|
||||
pub(crate) use removal::restore_disabled_accounts;
|
||||
|
||||
/// Must escape request handling: pending resources are retained until this service exits.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct RegistrationInterrupted;
|
||||
|
||||
impl std::fmt::Display for RegistrationInterrupted {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter.write_str("runtime setup interrupted; stopping service")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for RegistrationInterrupted {}
|
||||
|
||||
struct AccountProfile {
|
||||
user_sid: String,
|
||||
token: OwnedHandle,
|
||||
profile: HANDLE,
|
||||
}
|
||||
|
||||
impl Drop for AccountProfile {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.unload_profile();
|
||||
}
|
||||
}
|
||||
|
||||
impl AccountProfile {
|
||||
fn unload_profile(&mut self) -> Result<()> {
|
||||
if !self.profile.is_null() {
|
||||
let unloaded =
|
||||
unsafe { UnloadUserProfile(self.token.as_raw_handle() as _, self.profile) };
|
||||
BOOL(unloaded)
|
||||
.ok()
|
||||
.context("unload managed runtime account profile")?;
|
||||
self.profile = std::ptr::null_mut();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The caller holds the setup mutex from owner admission through readiness.
|
||||
/// Provision both users together. No runner launch performs package deployment.
|
||||
pub(crate) fn provision(
|
||||
identity: &ClientIdentity,
|
||||
record: &mut InstallationRecord,
|
||||
full_name: &HSTRING,
|
||||
shutdown: &AtomicBool,
|
||||
) -> Result<()> {
|
||||
let family = record.runtime()?.package_family.clone();
|
||||
validate_record(record)?;
|
||||
let mut profiles = Vec::new();
|
||||
let mut accounts = Vec::new();
|
||||
for account in [
|
||||
SandboxRuntimeAccount::Offline,
|
||||
SandboxRuntimeAccount::Online,
|
||||
] {
|
||||
let token = with_owner_impersonation(identity.token.as_raw_handle(), || {
|
||||
let mut pins = Vec::new();
|
||||
crate::ipc::pin_existing_ancestors(
|
||||
&sandbox_secrets_dir(&identity.codex_home),
|
||||
&mut pins,
|
||||
)?;
|
||||
logon_existing_sandbox_account(&identity.codex_home, account)
|
||||
})
|
||||
.with_context(|| format!("log on managed runtime account {account:?}"))?;
|
||||
let expected = record
|
||||
.runtime()?
|
||||
.accounts
|
||||
.iter()
|
||||
.find(|entry| entry.account == account);
|
||||
let profile = load_profile(
|
||||
token,
|
||||
account,
|
||||
expected.map(|entry| entry.user_sid.as_str()),
|
||||
)
|
||||
.with_context(|| format!("prepare managed runtime profile for {account:?}"))?;
|
||||
let installed = registered_packages(&profile.user_sid, &family)
|
||||
.with_context(|| format!("query existing runtime packages for {account:?}"))?;
|
||||
if expected.is_none() {
|
||||
ensure!(
|
||||
installed.is_empty(),
|
||||
"sandbox account has a runtime registration not owned by this service"
|
||||
);
|
||||
}
|
||||
let alias_path = known_folder::path(
|
||||
profile.token.as_raw_handle() as _,
|
||||
&FOLDERID_LocalAppData,
|
||||
/*flags*/ 0,
|
||||
)
|
||||
.with_context(|| format!("resolve runtime alias location for {account:?}"))?
|
||||
.join(r"Microsoft\WindowsApps")
|
||||
.join(&family)
|
||||
.join(APP_CORE_RUNNER_ALIAS);
|
||||
accounts.push(RuntimeAccountRegistration {
|
||||
cleanup_logon_pending: false,
|
||||
account,
|
||||
user_sid: profile.user_sid.clone(),
|
||||
alias_path: Some(alias_path),
|
||||
});
|
||||
profiles.push((profile, installed.contains(full_name)));
|
||||
}
|
||||
let receipt_current = record.runtime()?.ready_for_package(&full_name.to_string())
|
||||
&& record.runtime()?.accounts == accounts
|
||||
&& profiles.iter().all(|(_, installed)| *installed);
|
||||
// Both exact SIDs are durable before either package registration or metadata grant.
|
||||
// An idempotent setup check must not temporarily revoke a valid launch receipt.
|
||||
record.runtime_mut()?.accounts = accounts;
|
||||
if !receipt_current {
|
||||
record.runtime_mut()?.ready_package = None;
|
||||
crate::installation_record::save_runtime(record)
|
||||
.context("persist managed runtime account registration")?;
|
||||
}
|
||||
for (mut profile, installed) in profiles {
|
||||
if !installed {
|
||||
let operation = with_owner_impersonation(profile.token.as_raw_handle() as _, || {
|
||||
Ok(PackageManager::new()?.RegisterPackageByFullNameAsync(
|
||||
full_name,
|
||||
None,
|
||||
DeploymentOptions::None,
|
||||
)?)
|
||||
})
|
||||
.context("start managed runtime package registration")?;
|
||||
// As with provisioning, retain the request's resources until Windows finishes.
|
||||
// A client timeout or an unreadable status cannot safely release the profile.
|
||||
let mut status_error_logged = false;
|
||||
let status = loop {
|
||||
if shutdown.load(Ordering::Acquire) {
|
||||
// The typed error bypasses all response conversion and cleanup. Keep the
|
||||
// in-flight operation and its profile alive until this own-process service exits.
|
||||
std::mem::forget((operation, profile));
|
||||
return Err(RegistrationInterrupted.into());
|
||||
}
|
||||
match operation.Status() {
|
||||
Ok(AsyncStatus::Started) => {}
|
||||
Ok(
|
||||
status @ (AsyncStatus::Completed
|
||||
| AsyncStatus::Canceled
|
||||
| AsyncStatus::Error),
|
||||
) => {
|
||||
break status;
|
||||
}
|
||||
status => {
|
||||
if !status_error_logged {
|
||||
crate::service::log_error(
|
||||
crate::service::EVENT_SERVICE_FAILED,
|
||||
&format!(
|
||||
"runtime registration status unavailable; retaining request: {status:?}"
|
||||
),
|
||||
);
|
||||
status_error_logged = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
};
|
||||
registration_result::RegistrationResult::read(&operation, status).check()?;
|
||||
ensure!(
|
||||
registered_packages(&profile.user_sid, &family)
|
||||
.context("verify managed runtime package registration")?
|
||||
.contains(full_name),
|
||||
"runtime registration completed without the expected package"
|
||||
);
|
||||
}
|
||||
metadata::grant(identity.token.as_raw_handle(), &profile.user_sid, record)
|
||||
.context("grant managed runtime metadata permissions")?;
|
||||
profile.unload_profile()?;
|
||||
}
|
||||
if !receipt_current {
|
||||
record.runtime_mut()?.ready_package = Some(full_name.to_string());
|
||||
crate::installation_record::save_runtime(record)
|
||||
.context("persist completed managed runtime registration")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validate cleanup ownership under the caller's setup lock before obtaining logons.
|
||||
pub(crate) fn prepare_cleanup(record: InstallationRecord) -> Result<InstallationRecord> {
|
||||
validate_record(&record)?;
|
||||
for account in &record.runtime()?.accounts {
|
||||
if akode_windows_sandbox::local_user_flags(account.account.username())?.is_some() {
|
||||
validate_account_sid(account)?;
|
||||
}
|
||||
}
|
||||
ensure!(
|
||||
record.runtime()?.retiring.is_none(),
|
||||
"interrupted runtime cleanup requires repair"
|
||||
);
|
||||
ensure!(
|
||||
record
|
||||
.runtime()?
|
||||
.accounts
|
||||
.iter()
|
||||
.all(|account| !account.cleanup_logon_pending),
|
||||
"cleanup logon recovery is pending"
|
||||
);
|
||||
Ok(record)
|
||||
}
|
||||
|
||||
fn validate_account_sid(account: &RuntimeAccountRegistration) -> Result<()> {
|
||||
let sid = lookup_sid(account.account.username())?;
|
||||
ensure!(
|
||||
string_from_sid_bytes(&sid).map_err(anyhow::Error::msg)? == account.user_sid,
|
||||
"managed runtime account was replaced before cleanup"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn validate_record(record: &InstallationRecord) -> Result<()> {
|
||||
let runtime = record.runtime()?;
|
||||
ensure!(
|
||||
runtime.accounts.len() <= 2,
|
||||
"runtime registration record has too many accounts"
|
||||
);
|
||||
if runtime.accounts.len() == 2 {
|
||||
ensure!(
|
||||
runtime.accounts[0].account != runtime.accounts[1].account,
|
||||
"runtime registration record contains duplicate accounts"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn registered_packages(user_sid: &str, family: &str) -> Result<Vec<HSTRING>> {
|
||||
let packages = PackageManager::new()?.FindPackagesByUserSecurityIdPackageFamilyName(
|
||||
&HSTRING::from(user_sid),
|
||||
&HSTRING::from(family),
|
||||
)?;
|
||||
// The Rust Iterator adapter suppresses Current/MoveNext errors. Absence must
|
||||
// be authoritative before releasing cleanup ownership or its package anchor.
|
||||
let iterator = packages.First()?;
|
||||
let mut names = Vec::new();
|
||||
let mut has_current = iterator.HasCurrent()?;
|
||||
while has_current {
|
||||
names.push(iterator.Current()?.Id()?.FullName()?);
|
||||
has_current = iterator.MoveNext()?;
|
||||
}
|
||||
Ok(names)
|
||||
}
|
||||
|
||||
/// An intent is not an anchor: failed registration may leave no managed package.
|
||||
pub(crate) fn has_retaining_registration(record: &InstallationRecord) -> Result<bool> {
|
||||
let runtime = record.runtime()?;
|
||||
for account in &runtime.accounts {
|
||||
if !registered_packages(&account.user_sid, &runtime.package_family)?.is_empty() {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
fn load_profile(
|
||||
token: OwnedHandle,
|
||||
account: SandboxRuntimeAccount,
|
||||
expected_sid: Option<&str>,
|
||||
) -> Result<AccountProfile> {
|
||||
let user_sid = validate_target(token.as_raw_handle() as _, account, expected_sid)?;
|
||||
let mut username = to_wide(account.username());
|
||||
let mut profile: PROFILEINFOW = unsafe { std::mem::zeroed() };
|
||||
profile.dwSize = std::mem::size_of::<PROFILEINFOW>() as u32;
|
||||
profile.dwFlags = 1; // PI_NOUI: service operations never prompt interactively.
|
||||
profile.lpUserName = username.as_mut_ptr();
|
||||
unsafe { BOOL(LoadUserProfileW(token.as_raw_handle() as _, &mut profile)).ok() }
|
||||
.context("load managed runtime account profile")?;
|
||||
Ok(AccountProfile {
|
||||
user_sid,
|
||||
token,
|
||||
profile: profile.hProfile,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn validate_target(
|
||||
token: HANDLE,
|
||||
account: SandboxRuntimeAccount,
|
||||
expected_sid: Option<&str>,
|
||||
) -> Result<String> {
|
||||
let user = unsafe { akode_windows_sandbox::get_user_sid_bytes(token) }?;
|
||||
let user_sid = string_from_sid_bytes(&user).map_err(anyhow::Error::msg)?;
|
||||
ensure!(
|
||||
expected_sid.is_none_or(|expected| expected == user_sid),
|
||||
"managed runtime account SID changed"
|
||||
);
|
||||
ensure!(
|
||||
lookup_sid(account.username())? == user,
|
||||
"managed runtime account was replaced"
|
||||
);
|
||||
let groups = unsafe {
|
||||
token_groups(token, /*max_bytes*/ 65_536)
|
||||
}
|
||||
.context("read runtime account groups")?;
|
||||
ensure!(groups.len() <= 256, "invalid runtime account groups");
|
||||
let sandbox_group = lookup_sid(akode_windows_sandbox::SANDBOX_USERS_GROUP)?;
|
||||
let mut sandbox_member = false;
|
||||
for group in groups {
|
||||
ensure!(
|
||||
string_from_sid_bytes(&group.sid).map_err(anyhow::Error::msg)? != "S-1-5-32-544",
|
||||
"managed runtime account is an administrator"
|
||||
);
|
||||
if unsafe { security::EqualSid(group.sid.as_ptr() as _, sandbox_group.as_ptr() as _) } != 0
|
||||
&& group.attributes & SE_GROUP_ENABLED as u32 != 0
|
||||
{
|
||||
sandbox_member = true;
|
||||
}
|
||||
}
|
||||
ensure!(
|
||||
sandbox_member,
|
||||
"runtime account is not in CodexSandboxUsers"
|
||||
);
|
||||
Ok(user_sid)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
//! Resolves Known Folders for an explicit token and caller-selected flags.
|
||||
//! Preserve Windows UTF-16 paths and free the returned allocation on every result.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::os::windows::ffi::OsStringExt;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use windows_sys::Win32::Foundation::HANDLE;
|
||||
use windows_sys::Win32::System::Com::CoTaskMemFree;
|
||||
use windows_sys::Win32::UI::Shell::SHGetKnownFolderPath;
|
||||
use windows_sys::core::GUID;
|
||||
|
||||
pub(super) fn path(token: HANDLE, folder: &GUID, flags: u32) -> Result<PathBuf> {
|
||||
let mut raw = std::ptr::null_mut();
|
||||
let status = unsafe { SHGetKnownFolderPath(folder, flags, token, &mut raw) };
|
||||
let result = (|| {
|
||||
windows::core::HRESULT(status).ok()?;
|
||||
ensure!(!raw.is_null(), "Known Folder path missing");
|
||||
let mut length = 0;
|
||||
while length < 32768 && unsafe { *raw.add(length) } != 0 {
|
||||
length += 1;
|
||||
}
|
||||
ensure!(length < 32768, "Known Folder path exceeds bound");
|
||||
Ok(PathBuf::from(OsString::from_wide(unsafe {
|
||||
std::slice::from_raw_parts(raw, length)
|
||||
})))
|
||||
})();
|
||||
unsafe { CoTaskMemFree(raw.cast()) };
|
||||
result
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
//! Gives registered commands metadata access to the owner's two AppData roots.
|
||||
//! No file contents or descendants are granted. Persist the managed account and
|
||||
//! each owner-authorized root before granting access, so cleanup includes former roots.
|
||||
|
||||
use std::io;
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::os::windows::io::OwnedHandle;
|
||||
use std::path::Path;
|
||||
use std::ptr;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use akode_windows_sandbox::DirectoryOpenDisposition;
|
||||
use akode_windows_sandbox::LocalSid;
|
||||
use akode_windows_sandbox::open_directory_no_reparse;
|
||||
use windows::Win32::Foundation::BOOL;
|
||||
use windows_sys::Win32::Foundation::HANDLE;
|
||||
use windows_sys::Win32::Foundation::LocalFree;
|
||||
use windows_sys::Win32::Foundation::RtlNtStatusToDosError;
|
||||
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::UI::Shell as shell;
|
||||
|
||||
use super::known_folder::path as known_folder;
|
||||
use crate::installation_record::InstallationRecord;
|
||||
use crate::package_lifecycle::with_owner_impersonation;
|
||||
|
||||
const OWNER_FOLDER_FLAGS: u32 =
|
||||
(shell::KF_FLAG_DONT_VERIFY | shell::KF_FLAG_NO_PACKAGE_REDIRECTION) as u32;
|
||||
|
||||
#[link(name = "ntdll")]
|
||||
unsafe extern "system" {
|
||||
fn NtSetSecurityObject(
|
||||
handle: HANDLE,
|
||||
information: u32,
|
||||
descriptor: *const security::SECURITY_DESCRIPTOR,
|
||||
) -> i32;
|
||||
}
|
||||
|
||||
pub(super) fn grant(
|
||||
owner_token: HANDLE,
|
||||
user_sid: &str,
|
||||
record: &mut InstallationRecord,
|
||||
) -> Result<()> {
|
||||
ensure!(
|
||||
record
|
||||
.runtime()?
|
||||
.accounts
|
||||
.iter()
|
||||
.any(|account| account.user_sid == user_sid),
|
||||
"AppData metadata access requires a recorded managed account"
|
||||
);
|
||||
let sid = LocalSid::from_string(user_sid)?;
|
||||
for folder in [shell::FOLDERID_LocalAppData, shell::FOLDERID_RoamingAppData] {
|
||||
let path = known_folder(owner_token, &folder, OWNER_FOLDER_FLAGS)?;
|
||||
edit_root_acl(owner_token, &path, |acl| {
|
||||
// The owner-authorized directory and its ancestors are pinned here.
|
||||
// Commit provenance before any ACE mutation, including a partial grant.
|
||||
if !record.runtime()?.metadata_roots.contains(&path) {
|
||||
record.runtime_mut()?.metadata_roots.push(path.clone());
|
||||
crate::installation_record::save_runtime(record)?;
|
||||
}
|
||||
if metadata_ace(acl, &sid)?.is_some() {
|
||||
return Ok(false);
|
||||
}
|
||||
// Packaged Known Folder APIs verify these directory objects even when
|
||||
// APPDATA is inherited. Do not grant listing, contents, or inheritance.
|
||||
insert_metadata_ace(acl, &sid)?;
|
||||
Ok(true)
|
||||
})?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Removes exact grants from all recorded roots before account deletion.
|
||||
pub(crate) fn remove(token: HANDLE, record: &InstallationRecord) -> Result<()> {
|
||||
let runtime = record.runtime()?;
|
||||
let accounts = &runtime.accounts;
|
||||
if accounts.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut errors = Vec::new();
|
||||
// Every grant records its root before changing permissions, including redirects.
|
||||
for path in &runtime.metadata_roots {
|
||||
let result = edit_root_acl(token, path, |acl| {
|
||||
let mut changed = false;
|
||||
for account in accounts {
|
||||
let sid = LocalSid::from_string(&account.user_sid)?;
|
||||
while let Some(index) = metadata_ace(acl, &sid)? {
|
||||
unsafe { BOOL(security::DeleteAce(acl.as_mut_ptr().cast(), index)).ok() }
|
||||
.context("remove AppData metadata ACE")?;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
Ok(changed)
|
||||
});
|
||||
if let Err(error) = result
|
||||
&& error
|
||||
.downcast_ref::<io::Error>()
|
||||
.is_none_or(|error| error.kind() != io::ErrorKind::NotFound)
|
||||
{
|
||||
errors.push(format!("{error:#}"));
|
||||
}
|
||||
}
|
||||
ensure!(
|
||||
errors.is_empty(),
|
||||
"AppData metadata cleanup: {}",
|
||||
errors.join("; ")
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn edit_root_acl(
|
||||
token: HANDLE,
|
||||
path: &Path,
|
||||
edit: impl FnOnce(&mut Vec<u32>) -> Result<bool>,
|
||||
) -> Result<()> {
|
||||
let (_pins, handle) = with_owner_impersonation(token, || {
|
||||
let mut pins = Vec::new();
|
||||
crate::ipc::pin_existing_ancestors(path, &mut pins)?;
|
||||
let handle = open_directory_no_reparse(
|
||||
path,
|
||||
filesystem::READ_CONTROL
|
||||
| filesystem::WRITE_DAC
|
||||
| filesystem::FILE_READ_ATTRIBUTES
|
||||
| filesystem::FILE_TRAVERSE,
|
||||
filesystem::FILE_SHARE_READ | filesystem::FILE_SHARE_WRITE,
|
||||
DirectoryOpenDisposition::OpenExisting,
|
||||
)?;
|
||||
Ok((pins, handle))
|
||||
})?;
|
||||
let Some((mut acl, control)) = read_acl(&handle)? else {
|
||||
return Ok(()); // A null DACL already allows metadata; never replace it.
|
||||
};
|
||||
if edit(&mut acl)? {
|
||||
write_acl(&handle, &mut acl, control)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn read_acl(handle: &OwnedHandle) -> Result<Option<(Vec<u32>, u16)>> {
|
||||
let mut acl = ptr::null_mut();
|
||||
let mut descriptor = ptr::null_mut();
|
||||
let status = unsafe {
|
||||
authorization::GetSecurityInfo(
|
||||
handle.as_raw_handle() as _,
|
||||
authorization::SE_FILE_OBJECT,
|
||||
security::DACL_SECURITY_INFORMATION,
|
||||
ptr::null_mut(),
|
||||
ptr::null_mut(),
|
||||
&mut acl,
|
||||
ptr::null_mut(),
|
||||
&mut descriptor,
|
||||
)
|
||||
};
|
||||
if status != 0 {
|
||||
return Err(io::Error::from_raw_os_error(status as i32)).context("read directory DACL");
|
||||
}
|
||||
let result = (|| {
|
||||
if acl.is_null() {
|
||||
return Ok(None);
|
||||
}
|
||||
ensure!(
|
||||
unsafe { security::IsValidAcl(acl) } != 0,
|
||||
"invalid directory DACL"
|
||||
);
|
||||
let length = unsafe { (*acl).AclSize } as usize;
|
||||
let mut control = 0;
|
||||
let mut revision = 0;
|
||||
let queried = unsafe {
|
||||
security::GetSecurityDescriptorControl(descriptor, &mut control, &mut revision)
|
||||
};
|
||||
BOOL(queried).ok().context("read directory DACL control")?;
|
||||
let mut buffer = vec![0u32; length.div_ceil(4)];
|
||||
unsafe {
|
||||
ptr::copy_nonoverlapping(acl.cast::<u8>(), buffer.as_mut_ptr().cast(), length);
|
||||
}
|
||||
Ok(Some((buffer, control)))
|
||||
})();
|
||||
unsafe { LocalFree(descriptor as _) };
|
||||
result
|
||||
}
|
||||
|
||||
fn metadata_ace(acl: &mut [u32], sid: &LocalSid) -> Result<Option<u32>> {
|
||||
let acl = acl.as_mut_ptr().cast::<security::ACL>();
|
||||
for index in 0..u32::from(unsafe { (*acl).AceCount }) {
|
||||
let mut raw = ptr::null_mut();
|
||||
unsafe { BOOL(security::GetAce(acl, index, &mut raw)).ok() }.context("read AppData ACE")?;
|
||||
let offset = raw as usize - acl as usize;
|
||||
ensure!(
|
||||
offset + std::mem::size_of::<security::ACE_HEADER>()
|
||||
<= usize::from(unsafe { (*acl).AclSize }),
|
||||
"AppData ACE header exceeds ACL"
|
||||
);
|
||||
let header = unsafe { &*raw.cast::<security::ACE_HEADER>() };
|
||||
ensure!(
|
||||
offset + usize::from(header.AceSize) <= usize::from(unsafe { (*acl).AclSize }),
|
||||
"AppData ACE exceeds ACL"
|
||||
);
|
||||
if header.AceType == 0 && header.AceFlags == 0 {
|
||||
ensure!(header.AceSize >= 16, "AppData allow ACE is truncated");
|
||||
let ace = unsafe { &*raw.cast::<security::ACCESS_ALLOWED_ACE>() };
|
||||
let sid_pointer = ptr::addr_of!(ace.SidStart) as *mut std::ffi::c_void;
|
||||
let subauthorities = unsafe { *sid_pointer.cast::<u8>().add(1) } as usize;
|
||||
ensure!(
|
||||
subauthorities <= 15 && 16 + subauthorities * 4 <= usize::from(header.AceSize),
|
||||
"AppData allow ACE SID is truncated"
|
||||
);
|
||||
ensure!(
|
||||
unsafe { security::IsValidSid(sid_pointer) } != 0,
|
||||
"AppData allow ACE SID is invalid"
|
||||
);
|
||||
if ace.Mask == filesystem::FILE_READ_ATTRIBUTES
|
||||
&& unsafe { security::EqualSid(sid_pointer, sid.as_ptr()) } != 0
|
||||
{
|
||||
return Ok(Some(index));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn insert_metadata_ace(acl: &mut Vec<u32>, sid: &LocalSid) -> Result<()> {
|
||||
let capacity = usize::from(unsafe { (*acl.as_ptr().cast::<security::ACL>()).AclSize })
|
||||
+ 8
|
||||
+ unsafe { security::GetLengthSid(sid.as_ptr()) } as usize;
|
||||
ensure!(capacity <= u16::MAX as usize, "AppData DACL is full");
|
||||
acl.resize(capacity.div_ceil(4), 0);
|
||||
unsafe { (*acl.as_mut_ptr().cast::<security::ACL>()).AclSize = capacity as u16 };
|
||||
let mut single = [0u32; 32];
|
||||
let single_acl = single.as_mut_ptr().cast();
|
||||
unsafe {
|
||||
BOOL(security::InitializeAcl(
|
||||
single_acl,
|
||||
std::mem::size_of_val(&single) as u32,
|
||||
security::ACL_REVISION_DS,
|
||||
))
|
||||
.ok()
|
||||
.context("initialize AppData metadata ACE")?;
|
||||
BOOL(security::AddAccessAllowedAceEx(
|
||||
single_acl,
|
||||
security::ACL_REVISION_DS,
|
||||
0,
|
||||
filesystem::FILE_READ_ATTRIBUTES,
|
||||
sid.as_ptr(),
|
||||
))
|
||||
.ok()
|
||||
.context("construct AppData metadata ACE")?;
|
||||
}
|
||||
let mut added = ptr::null_mut();
|
||||
unsafe { BOOL(security::GetAce(single_acl, 0, &mut added)).ok() }
|
||||
.context("read new AppData metadata ACE")?;
|
||||
let acl = acl.as_mut_ptr().cast::<security::ACL>();
|
||||
let mut position = u32::from(unsafe { (*acl).AceCount });
|
||||
for index in 0..position {
|
||||
let mut raw = ptr::null_mut();
|
||||
unsafe { BOOL(security::GetAce(acl, index, &mut raw)).ok() }
|
||||
.context("read AppData ACE order")?;
|
||||
if unsafe { (*raw.cast::<security::ACE_HEADER>()).AceFlags } & security::INHERITED_ACE as u8
|
||||
!= 0
|
||||
{
|
||||
position = index;
|
||||
break;
|
||||
}
|
||||
}
|
||||
unsafe {
|
||||
BOOL(security::AddAce(
|
||||
acl,
|
||||
security::ACL_REVISION_DS,
|
||||
position,
|
||||
added,
|
||||
u32::from((*added.cast::<security::ACE_HEADER>()).AceSize),
|
||||
))
|
||||
.ok()
|
||||
}
|
||||
.context("insert AppData metadata ACE")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn write_acl(handle: &OwnedHandle, acl: &mut [u32], control: u16) -> Result<()> {
|
||||
let mut descriptor: security::SECURITY_DESCRIPTOR = unsafe { std::mem::zeroed() };
|
||||
let preserved = security::SE_DACL_PROTECTED | security::SE_DACL_AUTO_INHERITED;
|
||||
let raw_descriptor = (&mut descriptor as *mut security::SECURITY_DESCRIPTOR).cast();
|
||||
unsafe {
|
||||
BOOL(security::InitializeSecurityDescriptor(raw_descriptor, 1))
|
||||
.ok()
|
||||
.context("initialize directory security descriptor")?;
|
||||
BOOL(security::SetSecurityDescriptorDacl(
|
||||
raw_descriptor,
|
||||
1,
|
||||
acl.as_mut_ptr().cast(),
|
||||
i32::from(control & security::SE_DACL_DEFAULTED != 0),
|
||||
))
|
||||
.ok()
|
||||
.context("set directory DACL")?;
|
||||
BOOL(security::SetSecurityDescriptorControl(
|
||||
raw_descriptor,
|
||||
preserved,
|
||||
control & preserved,
|
||||
))
|
||||
.ok()
|
||||
.context("preserve directory DACL control")?;
|
||||
}
|
||||
// SetSecurityInfo recursively reapplies existing inheritable ACEs. The native
|
||||
// object setter changes only this retained, owner-authorized directory handle.
|
||||
let status = unsafe {
|
||||
NtSetSecurityObject(
|
||||
handle.as_raw_handle() as _,
|
||||
security::DACL_SECURITY_INFORMATION,
|
||||
&descriptor,
|
||||
)
|
||||
};
|
||||
if status < 0 {
|
||||
return Err(io::Error::from_raw_os_error(
|
||||
unsafe { RtlNtStatusToDosError(status) } as i32,
|
||||
))
|
||||
.context("write directory DACL");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "metadata_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,97 @@
|
||||
//! Tests that metadata ACE edits preserve unrelated, inherited, and broader permissions.
|
||||
|
||||
use super::*;
|
||||
|
||||
fn ace_bytes(acl: &mut [u32]) -> Vec<Vec<u8>> {
|
||||
let acl = acl.as_mut_ptr().cast::<security::ACL>();
|
||||
(0..u32::from(unsafe { (*acl).AceCount }))
|
||||
.map(|index| {
|
||||
let mut raw = ptr::null_mut();
|
||||
assert_ne!(unsafe { security::GetAce(acl, index, &mut raw) }, 0);
|
||||
let length = unsafe { (*raw.cast::<security::ACE_HEADER>()).AceSize } as usize;
|
||||
unsafe { std::slice::from_raw_parts(raw.cast::<u8>(), length) }.to_vec()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn existing_acl(sid: &LocalSid) -> Vec<u32> {
|
||||
let mut acl = vec![0u32; 256];
|
||||
let raw = acl.as_mut_ptr().cast();
|
||||
assert_ne!(
|
||||
unsafe { security::InitializeAcl(raw, 1024, security::ACL_REVISION_DS) },
|
||||
0
|
||||
);
|
||||
assert_ne!(
|
||||
unsafe {
|
||||
security::AddAccessDeniedAceEx(
|
||||
raw,
|
||||
security::ACL_REVISION_DS,
|
||||
0,
|
||||
filesystem::FILE_WRITE_DATA,
|
||||
sid.as_ptr(),
|
||||
)
|
||||
},
|
||||
0
|
||||
);
|
||||
assert_ne!(
|
||||
unsafe {
|
||||
security::AddAccessAllowedAceEx(
|
||||
raw,
|
||||
security::ACL_REVISION_DS,
|
||||
0,
|
||||
filesystem::FILE_READ_DATA | filesystem::FILE_READ_ATTRIBUTES,
|
||||
sid.as_ptr(),
|
||||
)
|
||||
},
|
||||
0
|
||||
);
|
||||
assert_ne!(
|
||||
unsafe {
|
||||
security::AddAccessAllowedAceEx(
|
||||
raw,
|
||||
security::ACL_REVISION_DS,
|
||||
security::INHERITED_ACE,
|
||||
filesystem::FILE_READ_ATTRIBUTES,
|
||||
sid.as_ptr(),
|
||||
)
|
||||
},
|
||||
0
|
||||
);
|
||||
acl
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metadata_grant_and_cleanup_preserve_broader_and_inherited_aces() -> Result<()> {
|
||||
let sid = LocalSid::from_string("S-1-5-21-1-2-3-1001")?;
|
||||
let mut acl = existing_acl(&sid);
|
||||
let before = ace_bytes(&mut acl);
|
||||
assert_eq!(metadata_ace(&mut acl, &sid)?, None);
|
||||
insert_metadata_ace(&mut acl, &sid)?;
|
||||
assert_eq!(metadata_ace(&mut acl, &sid)?, Some(2));
|
||||
assert_ne!(unsafe { security::IsValidAcl(acl.as_mut_ptr().cast()) }, 0);
|
||||
assert_ne!(
|
||||
unsafe { security::DeleteAce(acl.as_mut_ptr().cast(), 2) },
|
||||
0
|
||||
);
|
||||
assert_eq!(ace_bytes(&mut acl), before);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metadata_cleanup_handles_duplicates_without_touching_another_principal() -> Result<()> {
|
||||
let sid = LocalSid::from_string("S-1-5-21-1-2-3-1001")?;
|
||||
let other = LocalSid::from_string("S-1-5-21-1-2-3-1002")?;
|
||||
let mut acl = existing_acl(&sid);
|
||||
let before = ace_bytes(&mut acl);
|
||||
insert_metadata_ace(&mut acl, &sid)?;
|
||||
assert_eq!(metadata_ace(&mut acl, &other)?, None);
|
||||
insert_metadata_ace(&mut acl, &sid)?;
|
||||
while let Some(index) = metadata_ace(&mut acl, &sid)? {
|
||||
assert_ne!(
|
||||
unsafe { security::DeleteAce(acl.as_mut_ptr().cast(), index) },
|
||||
0
|
||||
);
|
||||
}
|
||||
assert_eq!(ace_bytes(&mut acl), before);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
//! Retains the distinct native registration failure codes and deployment activity ID.
|
||||
//! Diagnostic getters never replace the completion error or turn success into failure.
|
||||
//! Free-form Windows ErrorText stays in Windows deployment diagnostics, not this summary.
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use windows::Foundation::AsyncStatus;
|
||||
use windows::Foundation::IAsyncOperationWithProgress;
|
||||
use windows::Management::Deployment::DeploymentProgress;
|
||||
use windows::Management::Deployment::DeploymentResult;
|
||||
use windows::core::GUID;
|
||||
use windows::core::HRESULT;
|
||||
|
||||
pub(super) struct RegistrationResult {
|
||||
status: AsyncStatus,
|
||||
async_error: windows::core::Result<HRESULT>,
|
||||
// Keep GetResults failure separate from failure to read ExtendedErrorCode.
|
||||
result: windows::core::Result<DeploymentDetails>,
|
||||
}
|
||||
|
||||
struct DeploymentDetails {
|
||||
extended_error: windows::core::Result<HRESULT>,
|
||||
activity_id: windows::core::Result<GUID>,
|
||||
}
|
||||
|
||||
impl RegistrationResult {
|
||||
/// The caller must first observe a terminal status while retaining the profile/token.
|
||||
pub(super) fn read(
|
||||
operation: &IAsyncOperationWithProgress<DeploymentResult, DeploymentProgress>,
|
||||
status: AsyncStatus,
|
||||
) -> Self {
|
||||
Self {
|
||||
status,
|
||||
async_error: operation.ErrorCode(),
|
||||
result: operation.GetResults().map(|result| DeploymentDetails {
|
||||
extended_error: result.ExtendedErrorCode(),
|
||||
activity_id: result.ActivityId(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn check(self) -> Result<()> {
|
||||
let Self {
|
||||
status,
|
||||
async_error,
|
||||
result,
|
||||
} = self;
|
||||
let async_error = match async_error {
|
||||
Ok(code) => format!("{code:?}"),
|
||||
Err(error) => format!("unavailable({:?})", error.code()),
|
||||
};
|
||||
let context = format!(
|
||||
"finish managed runtime package registration: status={} async_error={async_error}",
|
||||
status.0,
|
||||
);
|
||||
let details = result.map_err(|error| {
|
||||
let summary = format!("{context} phase=GetResults get_results={:?}", error.code());
|
||||
anyhow::Error::new(error).context(summary)
|
||||
})?;
|
||||
let activity_id = match details.activity_id {
|
||||
Ok(id) => format!("{id:?}"),
|
||||
Err(error) => format!("unavailable({:?})", error.code()),
|
||||
};
|
||||
let context = format!("{context} get_results=0x00000000 activity_id={activity_id}");
|
||||
let extended_error = details.extended_error.map_err(|error| {
|
||||
let summary = format!(
|
||||
"{context} phase=ExtendedErrorCode getter_error={:?}",
|
||||
error.code()
|
||||
);
|
||||
anyhow::Error::new(error).context(summary)
|
||||
})?;
|
||||
extended_error.ok().with_context(|| {
|
||||
format!("{context} phase=deployment extended_error={extended_error:?}")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "registration_result_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,93 @@
|
||||
//! Completion diagnostics preserve native errors without depending on account mutation.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
const ACCESS_DENIED: HRESULT = HRESULT(0x80070005_u32 as i32);
|
||||
const CANCELED: HRESULT = HRESULT(0x800704C7_u32 as i32);
|
||||
const ASYNC_FAILURE: HRESULT = HRESULT(0x80073D19_u32 as i32);
|
||||
const DEPLOYMENT_FAILURE: HRESULT = HRESULT(0x80073D28_u32 as i32);
|
||||
|
||||
#[test]
|
||||
fn retains_different_async_and_deployment_errors_with_activity() {
|
||||
let activity_id = GUID::from_u128(0x1b60fffa_59b3_0002_d8d5_611bb359dd01);
|
||||
let error = RegistrationResult {
|
||||
status: AsyncStatus::Error,
|
||||
async_error: Ok(ASYNC_FAILURE),
|
||||
result: Ok(DeploymentDetails {
|
||||
extended_error: Ok(DEPLOYMENT_FAILURE),
|
||||
activity_id: Ok(activity_id),
|
||||
}),
|
||||
}
|
||||
.check()
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
format!(
|
||||
"finish managed runtime package registration: status=3 async_error={ASYNC_FAILURE:?} get_results=0x00000000 activity_id={activity_id:?} phase=deployment extended_error={DEPLOYMENT_FAILURE:?}"
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
error.downcast_ref::<windows::core::Error>().unwrap().code(),
|
||||
DEPLOYMENT_FAILURE
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_results_errors_keep_original_hresult_and_phase() {
|
||||
for (status, code) in [
|
||||
(AsyncStatus::Error, ACCESS_DENIED),
|
||||
(AsyncStatus::Canceled, CANCELED),
|
||||
] {
|
||||
let error = RegistrationResult {
|
||||
status,
|
||||
async_error: Ok(code),
|
||||
result: Err(windows::core::Error::from_hresult(code)),
|
||||
}
|
||||
.check()
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
format!(
|
||||
"finish managed runtime package registration: status={} async_error={code:?} phase=GetResults get_results={code:?}",
|
||||
status.0
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
error.downcast_ref::<windows::core::Error>().unwrap().code(),
|
||||
code
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagnostic_getter_failures_do_not_mask_completion_or_leak_text() {
|
||||
let private_error = || windows::core::Error::new(ACCESS_DENIED, "private deployment path");
|
||||
for code in [HRESULT(0), CANCELED] {
|
||||
let result = RegistrationResult {
|
||||
status: AsyncStatus::Completed,
|
||||
async_error: Err(private_error()),
|
||||
result: Ok(DeploymentDetails {
|
||||
extended_error: code.ok().map(|()| code),
|
||||
activity_id: Err(private_error()),
|
||||
}),
|
||||
}
|
||||
.check();
|
||||
if code.is_err() {
|
||||
let error = result.unwrap_err();
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
format!(
|
||||
"finish managed runtime package registration: status=1 async_error=unavailable({ACCESS_DENIED:?}) get_results=0x00000000 activity_id=unavailable({ACCESS_DENIED:?}) phase=ExtendedErrorCode getter_error={CANCELED:?}"
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
error.downcast_ref::<windows::core::Error>().unwrap().code(),
|
||||
CANCELED
|
||||
);
|
||||
assert!(!format!("{error:#}").contains("private deployment path"));
|
||||
} else {
|
||||
assert_eq!(result.unwrap(), ());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$PSModuleAutoLoadingPreference = 'None'
|
||||
Import-Module -Name ($PSHOME + '\Modules\Microsoft.PowerShell.Utility\Microsoft.PowerShell.Utility.psd1') -ErrorAction Stop
|
||||
Import-Module -Name ($PSHOME + '\Modules\Appx\Appx.psd1') -ErrorAction Stop
|
||||
Import-Module -Name ($PSHOME + '\Modules\Microsoft.PowerShell.Management\Microsoft.PowerShell.Management.psd1') -ErrorAction Stop
|
||||
if ([Security.Principal.WindowsIdentity]::GetCurrent().User.Value -ne 'S-1-5-18') { throw 'SYSTEM required' }
|
||||
# Rust sends UTF-8 regardless of the machine's console code page. Keep one reader
|
||||
# for the complete protocol so read-ahead cannot consume COMMIT or its EOF fence.
|
||||
$protocolInput = [IO.StreamReader]::new([Console]::OpenStandardInput(), [Text.UTF8Encoding]::new($false, $true), $false)
|
||||
$planJson = $protocolInput.ReadLine()
|
||||
if (!$planJson) { return }
|
||||
$plan = Microsoft.PowerShell.Utility\ConvertFrom-Json -InputObject $planJson
|
||||
if ([string]::IsNullOrEmpty($plan.record.runtime.retiring)) { throw 'Retirement generation required' }
|
||||
if (@($plan.targets).Count -gt 2) { throw 'Too many cleanup tokens' }
|
||||
Add-Type -TypeDefinition @"
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.InteropServices;
|
||||
public static class CleanupNative {
|
||||
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct Profile { public int size,flags; public string user,path,def,server,policy; public IntPtr handle; }
|
||||
[StructLayout(LayoutKind.Sequential)] public struct Luid { public uint lo; public int hi; }
|
||||
[StructLayout(LayoutKind.Sequential)] public struct Priv { public uint count; public Luid luid; public uint attributes; }
|
||||
[DllImport("userenv.dll",CharSet=CharSet.Unicode,SetLastError=true)] public static extern bool LoadUserProfile(IntPtr t,ref Profile p);
|
||||
[DllImport("userenv.dll",SetLastError=true)] public static extern bool UnloadUserProfile(IntPtr t,IntPtr p);
|
||||
[DllImport("userenv.dll",CharSet=CharSet.Unicode,SetLastError=true)] public static extern bool DeleteProfile(string sid,string path,string computer);
|
||||
[StructLayout(LayoutKind.Sequential)] struct User23 { public IntPtr name,fullName,comment; public uint flags; public IntPtr sid; }
|
||||
[DllImport("netapi32.dll",CharSet=CharSet.Unicode)] static extern int NetUserGetInfo(string server,string user,int level,out IntPtr info);
|
||||
[DllImport("netapi32.dll",CharSet=CharSet.Unicode)] static extern int NetUserDel(string server,string user);
|
||||
[DllImport("netapi32.dll")] static extern int NetApiBufferFree(IntPtr info);
|
||||
[DllImport("netapi32.dll",CharSet=CharSet.Unicode)] public static extern int NetLocalGroupDel(string server,string group);
|
||||
[DllImport("advapi32.dll",CharSet=CharSet.Unicode)] static extern IntPtr RegisterEventSource(string server,string source);
|
||||
[DllImport("advapi32.dll",CharSet=CharSet.Unicode)] static extern bool ReportEvent(IntPtr h,ushort type,ushort category,uint id,IntPtr sid,ushort count,uint size,string[] messages,IntPtr data);
|
||||
[DllImport("advapi32.dll")] static extern bool DeregisterEventSource(IntPtr h);
|
||||
public static void Log(string source,ushort type,uint id,string message) { IntPtr h=RegisterEventSource(null,source); if(h==IntPtr.Zero)return; try { ReportEvent(h,type,0,id,IntPtr.Zero,1,0,new[]{message.Substring(0,Math.Min(message.Length,4096))},IntPtr.Zero); } finally { DeregisterEventSource(h); } }
|
||||
public static void DeleteUser(string user,string sid) { IntPtr p; int status=NetUserGetInfo(null,user,23,out p); if(status==2221)return; if(status!=0)throw new Win32Exception(status); try { User23 info=(User23)Marshal.PtrToStructure(p,typeof(User23)); if(new System.Security.Principal.SecurityIdentifier(info.sid).Value!=sid || (info.flags&2)==0)throw new InvalidOperationException("Sandbox account changed or was re-enabled"); } finally { NetApiBufferFree(p); } status=NetUserDel(null,user); if(status!=0 && status!=2221)throw new Win32Exception(status); }
|
||||
[DllImport("advapi32.dll",SetLastError=true)] public static extern bool ImpersonateLoggedOnUser(IntPtr t);
|
||||
[DllImport("advapi32.dll",SetLastError=true)] public static extern bool RevertToSelf();
|
||||
[DllImport("kernel32.dll")] public static extern bool CloseHandle(IntPtr h);
|
||||
[DllImport("kernel32.dll")] public static extern IntPtr GetCurrentProcess();
|
||||
[DllImport("advapi32.dll",SetLastError=true)] static extern bool OpenProcessToken(IntPtr p,uint a,out IntPtr t);
|
||||
[DllImport("advapi32.dll",CharSet=CharSet.Unicode,SetLastError=true)] static extern bool LookupPrivilegeValue(string s,string n,out Luid l);
|
||||
[DllImport("advapi32.dll",SetLastError=true)] static extern bool AdjustTokenPrivileges(IntPtr t,bool d,ref Priv p,int len,IntPtr old,IntPtr ret);
|
||||
public static void Enable(string n) { IntPtr t; Luid l; if(!OpenProcessToken(GetCurrentProcess(),0x28,out t))throw new Win32Exception(); try { if(!LookupPrivilegeValue(null,n,out l))throw new Win32Exception(); Priv p=new Priv{count=1,luid=l,attributes=2}; if(!AdjustTokenPrivileges(t,false,ref p,0,IntPtr.Zero,IntPtr.Zero))throw new Win32Exception(); int e=Marshal.GetLastWin32Error(); if(e!=0)throw new Win32Exception(e); } finally { CloseHandle(t); } }
|
||||
public static void Revert() { if(!RevertToSelf())Environment.FailFast("Cleanup impersonation revert failed"); }
|
||||
}
|
||||
"@
|
||||
Add-Type -AssemblyName System.Runtime.WindowsRuntime
|
||||
$null = [Windows.Management.Deployment.PackageManager,Windows.Management.Deployment,ContentType=WindowsRuntime]
|
||||
$null = [Windows.Management.Deployment.DeploymentResult,Windows.Management.Deployment,ContentType=WindowsRuntime]
|
||||
$null = [Windows.Management.Deployment.DeploymentProgress,Windows.Management.Deployment,ContentType=WindowsRuntime]
|
||||
$asTask = [System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object { $_.Name -eq 'AsTask' -and $_.IsGenericMethod -and $_.GetGenericArguments().Count -eq 2 -and $_.GetParameters().Count -eq 1 } | Select-Object -First 1
|
||||
$await = $asTask.MakeGenericMethod([Windows.Management.Deployment.DeploymentResult],[Windows.Management.Deployment.DeploymentProgress])
|
||||
$profiles = @()
|
||||
$removedRegistrations = @{}
|
||||
try {
|
||||
[CleanupNative]::Enable('SeBackupPrivilege')
|
||||
[CleanupNative]::Enable('SeRestorePrivilege')
|
||||
foreach ($target in $plan.targets) {
|
||||
$token = [IntPtr][long]$target.handle
|
||||
$identity = [Security.Principal.WindowsIdentity]::new($token)
|
||||
try { if ($identity.User.Value -cne $target.sid) { throw 'Cleanup token SID mismatch' } }
|
||||
finally { $identity.Dispose() }
|
||||
$profile = New-Object CleanupNative+Profile
|
||||
$profile.size = [Runtime.InteropServices.Marshal]::SizeOf($profile)
|
||||
$profile.flags = 1
|
||||
$profile.user = $target.username
|
||||
if (![CleanupNative]::LoadUserProfile($token, [ref]$profile)) { throw [ComponentModel.Win32Exception]::new([Runtime.InteropServices.Marshal]::GetLastWin32Error()) }
|
||||
$profiles += @{ token = $token; profile = $profile; sid = $target.sid }
|
||||
}
|
||||
[Console]::Out.WriteLine('READY')
|
||||
# EOF without a successful native-cleanup commit only unloads profiles.
|
||||
if ($protocolInput.ReadLine() -cne 'COMMIT') { return }
|
||||
# Even after COMMIT, removal must wait until the service releases its own package.
|
||||
if ($protocolInput.ReadToEnd().Length -ne 0) { return }
|
||||
$finished = $false
|
||||
while (!$finished) {
|
||||
$mutex = $null; $locked = $false; $key = $null; $legacy = $null
|
||||
try {
|
||||
$security = [Security.AccessControl.MutexSecurity]::new()
|
||||
$security.SetSecurityDescriptorSddlForm('D:P(A;;GA;;;SY)(A;;GA;;;BA)')
|
||||
$created = $false
|
||||
$mutex = [Threading.Mutex]::new($false, 'Global\CodexSandboxSetup', [ref]$created, $security)
|
||||
try { $locked = $mutex.WaitOne(30000) }
|
||||
catch [Threading.AbandonedMutexException] { $locked = $true }
|
||||
if (!$locked) { throw 'Sandbox setup is still active' }
|
||||
$key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($plan.key, $true)
|
||||
if (!$key) { return }
|
||||
$record = Microsoft.PowerShell.Utility\ConvertFrom-Json -InputObject ([string]$key.GetValue($plan.value))
|
||||
if ($record.runtime.retiring -ne $plan.record.runtime.retiring -or
|
||||
$record.user_sid -ne $plan.record.user_sid -or
|
||||
$record.codex_home -ne $plan.record.codex_home -or
|
||||
$record.runtime.package_family -ne $plan.record.runtime.package_family) { return }
|
||||
foreach ($entry in $profiles) {
|
||||
if ($removedRegistrations.ContainsKey($entry.sid)) { continue }
|
||||
foreach ($package in @(Appx\Get-AppxPackage -User $entry.sid -ErrorAction Stop)) {
|
||||
if ($package.PackageFamilyName -ne $record.runtime.package_family) { continue }
|
||||
if (![CleanupNative]::ImpersonateLoggedOnUser($entry.token)) { throw 'Cleanup impersonation failed' }
|
||||
try {
|
||||
if ([Security.Principal.WindowsIdentity]::GetCurrent().User.Value -cne $entry.sid) { throw 'Cleanup identity changed' }
|
||||
# Construct and submit synchronously under the retained user, not SYSTEM.
|
||||
$manager = [Windows.Management.Deployment.PackageManager]::new()
|
||||
$operation = $manager.RemovePackageAsync($package.PackageFullName)
|
||||
} finally { [CleanupNative]::Revert() }
|
||||
# Failure to obtain a waiter is not proof the operation stopped.
|
||||
$task = $null
|
||||
while (!$task) {
|
||||
try { $task = $await.Invoke($null, @($operation)) }
|
||||
catch { Microsoft.PowerShell.Utility\Start-Sleep -Seconds 1 }
|
||||
}
|
||||
while (!$task.IsCompleted) { Microsoft.PowerShell.Utility\Start-Sleep -Milliseconds 50 }
|
||||
$result = $task.GetAwaiter().GetResult()
|
||||
if ($result.ExtendedErrorCode -and $result.ExtendedErrorCode.HResult -ne 0) { throw $result.ErrorText }
|
||||
}
|
||||
}
|
||||
foreach ($account in $plan.record.runtime.accounts) {
|
||||
if ($removedRegistrations.ContainsKey($account.user_sid)) { continue }
|
||||
foreach ($package in @(Appx\Get-AppxPackage -User $account.user_sid -ErrorAction Stop)) {
|
||||
if ($package.PackageFamilyName -eq $record.runtime.package_family) { throw 'Runtime registration remains' }
|
||||
}
|
||||
$removedRegistrations[$account.user_sid] = $true
|
||||
}
|
||||
foreach ($account in $plan.record.runtime.accounts) {
|
||||
$sid = $account.user_sid
|
||||
foreach ($entry in $profiles) {
|
||||
if ($entry.sid -ne $sid -or $entry.profile.handle -eq [IntPtr]::Zero) { continue }
|
||||
if (![CleanupNative]::UnloadUserProfile($entry.token, $entry.profile.handle)) { throw [ComponentModel.Win32Exception]::new([Runtime.InteropServices.Marshal]::GetLastWin32Error()) }
|
||||
$entry.profile.handle = [IntPtr]::Zero
|
||||
}
|
||||
$profileKey = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\$sid")
|
||||
if ($profileKey) {
|
||||
$profileKey.Dispose()
|
||||
# PowerShell converts $null to an empty string; DeleteProfile requires native NULL.
|
||||
if (![CleanupNative]::DeleteProfile($sid, [NullString]::Value, [NullString]::Value)) { throw [ComponentModel.Win32Exception]::new([Runtime.InteropServices.Marshal]::GetLastWin32Error()) }
|
||||
}
|
||||
[CleanupNative]::DeleteUser(('CodexSandbox' + $account.account), $sid)
|
||||
[CleanupNative]::Log($plan.service_name, 4, 3004, "Removed $($account.account) sandbox profile and account")
|
||||
}
|
||||
$groupSid = $null
|
||||
try { if ($plan.group_sid) { $groupSid = ([Security.Principal.NTAccount]::new('CodexSandboxUsers')).Translate([Security.Principal.SecurityIdentifier]).Value } }
|
||||
catch [Security.Principal.IdentityNotMappedException] { }
|
||||
if ($groupSid) {
|
||||
if ($groupSid -cne $plan.group_sid) { throw 'Sandbox group was replaced' }
|
||||
$status = [CleanupNative]::NetLocalGroupDel($null, 'CodexSandboxUsers')
|
||||
if ($status -ne 0 -and $status -ne 2220) { throw [ComponentModel.Win32Exception]::new($status) }
|
||||
}
|
||||
$legacy = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($plan.legacy_key, $true)
|
||||
if (!$legacy) { throw 'Installation parent is missing' }
|
||||
$legacyJson = $legacy.GetValue($plan.value)
|
||||
if ($legacyJson) {
|
||||
$owner = Microsoft.PowerShell.Utility\ConvertFrom-Json -InputObject ([string]$legacyJson)
|
||||
if ($owner.user_sid -eq $plan.record.user_sid -and $owner.codex_home -eq $plan.record.codex_home) { $legacy.DeleteValue($plan.value, $false) }
|
||||
}
|
||||
$key.Dispose(); $key = $null
|
||||
$legacy.Flush()
|
||||
[Microsoft.Win32.Registry]::LocalMachine.DeleteSubKey($plan.key, $false)
|
||||
if ($legacy.SubKeyCount -eq 0 -and $legacy.ValueCount -eq 0) {
|
||||
$legacy.Dispose(); $legacy = $null
|
||||
[Microsoft.Win32.Registry]::LocalMachine.DeleteSubKey($plan.legacy_key, $false)
|
||||
}
|
||||
$finished = $true
|
||||
[CleanupNative]::Log($plan.service_name, 4, 3003, 'Sandbox uninstall cleanup finished, including registered runtimes, profiles, and accounts')
|
||||
} catch { [CleanupNative]::Log($plan.service_name, 1, 3004, "Runtime cleanup deferred: $_") }
|
||||
finally {
|
||||
if ($key) { $key.Dispose() }
|
||||
if ($legacy) { $legacy.Dispose() }
|
||||
if ($locked) { $mutex.ReleaseMutex() }
|
||||
if ($mutex) { $mutex.Dispose() }
|
||||
}
|
||||
if (!$finished) { Microsoft.PowerShell.Utility\Start-Sleep -Seconds 30 }
|
||||
}
|
||||
} finally {
|
||||
foreach ($entry in $profiles) {
|
||||
if ($entry.profile.handle -eq [IntPtr]::Zero) { continue }
|
||||
while (![CleanupNative]::UnloadUserProfile($entry.token, $entry.profile.handle)) {
|
||||
Microsoft.PowerShell.Utility\Start-Sleep -Seconds 1
|
||||
}
|
||||
}
|
||||
foreach ($target in $plan.targets) { $null = [CleanupNative]::CloseHandle([IntPtr][long]$target.handle) }
|
||||
}
|
||||
# A reinstall may have tried to start the service while the retirement fence blocked it.
|
||||
while ($true) {
|
||||
try {
|
||||
foreach ($package in @(Appx\Get-AppxPackage -User $plan.record.user_sid -ErrorAction Stop)) {
|
||||
if ($package.PackageFamilyName -eq $plan.record.runtime.package_family) {
|
||||
Microsoft.PowerShell.Management\Start-Service -Name $plan.service_name -ErrorAction Stop
|
||||
break
|
||||
}
|
||||
}
|
||||
break
|
||||
} catch { Microsoft.PowerShell.Utility\Start-Sleep -Seconds 30 }
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
//! Prepare exact managed logons before native cleanup; authorize removal only after success.
|
||||
//! The child owns loaded profiles and waits for both COMMIT and service-process EOF.
|
||||
|
||||
use std::io::Read;
|
||||
use std::io::Write;
|
||||
use std::os::windows::fs::MetadataExt;
|
||||
use std::os::windows::io::AsHandle;
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::os::windows::io::BorrowedHandle;
|
||||
use std::os::windows::io::OwnedHandle;
|
||||
use std::os::windows::process::CommandExt;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Child;
|
||||
use std::process::Command;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use windows_sys::Win32::Foundation::DUPLICATE_SAME_ACCESS;
|
||||
use windows_sys::Win32::Foundation::DuplicateHandle;
|
||||
use windows_sys::Win32::Foundation::HANDLE;
|
||||
use windows_sys::Win32::NetworkManagement::NetManagement::UF_ACCOUNTDISABLE;
|
||||
use windows_sys::Win32::System::Pipes::PeekNamedPipe;
|
||||
use windows_sys::Win32::System::SystemInformation::GetSystemDirectoryW;
|
||||
use windows_sys::Win32::System::Threading as threading;
|
||||
|
||||
use crate::installation_record::InstallationRecord;
|
||||
use crate::package_lifecycle::with_owner_impersonation;
|
||||
|
||||
pub(crate) struct PreparedRemoval {
|
||||
child: Child,
|
||||
tokens: Vec<OwnedHandle>,
|
||||
}
|
||||
|
||||
impl PreparedRemoval {
|
||||
pub(crate) fn tokens(&self) -> Vec<BorrowedHandle<'_>> {
|
||||
self.tokens.iter().map(AsHandle::as_handle).collect()
|
||||
}
|
||||
|
||||
/// Called only after the native cleanup guard has successfully finished.
|
||||
pub(crate) fn commit(mut self) -> Result<()> {
|
||||
self.child
|
||||
.stdin
|
||||
.as_mut()
|
||||
.context("cleanup input closed")?
|
||||
.write_all(b"COMMIT\n")
|
||||
.context("commit Windows package cleanup")?;
|
||||
// The only pipe writer remains open until this own-process service exits.
|
||||
// Dropping an uncommitted preparation instead sends EOF, which only aborts.
|
||||
std::mem::forget(self.child);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Restore durable temporary-enable intent before owner restoration or IPC admission.
|
||||
pub(crate) fn restore_disabled_accounts() -> Result<()> {
|
||||
let _lock = akode_windows_sandbox::acquire_sandbox_setup_lock(/*timeout_ms*/ 5_000)?;
|
||||
let Some(mut record) = crate::installation_record::load_runtime()? else {
|
||||
return Ok(());
|
||||
};
|
||||
if !crate::installation_record::is_current_package_family(&record)? {
|
||||
return Ok(());
|
||||
}
|
||||
super::validate_record(&record)?;
|
||||
for index in 0..record.runtime()?.accounts.len() {
|
||||
let account = &record.runtime()?.accounts[index];
|
||||
if !account.cleanup_logon_pending {
|
||||
continue;
|
||||
}
|
||||
super::validate_account_sid(account)?;
|
||||
let flags = akode_windows_sandbox::local_user_flags(account.account.username())?
|
||||
.context("cleanup account disappeared before flag restoration")?;
|
||||
akode_windows_sandbox::set_local_user_flags(
|
||||
account.account.username(),
|
||||
flags | UF_ACCOUNTDISABLE,
|
||||
)?;
|
||||
record.runtime_mut()?.accounts[index].cleanup_logon_pending = false;
|
||||
crate::installation_record::save_runtime(&record)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// The cleanup entry checked the service family; prepare_cleanup validated this record
|
||||
// under the same setup lock. Fresh logons below still require exact account-SID checks.
|
||||
pub(crate) fn prepare(
|
||||
owner_token: HANDLE,
|
||||
record: &mut InstallationRecord,
|
||||
) -> Result<PreparedRemoval> {
|
||||
ensure!(
|
||||
record.runtime()?.retiring.is_none(),
|
||||
"runtime is already retiring"
|
||||
);
|
||||
let mut tokens = Vec::new();
|
||||
let mut targets = Vec::new();
|
||||
for index in 0..record.runtime()?.accounts.len() {
|
||||
let account = record.runtime()?.accounts[index].clone();
|
||||
let Some(flags) = akode_windows_sandbox::local_user_flags(account.account.username())?
|
||||
else {
|
||||
ensure!(
|
||||
super::registered_packages(&account.user_sid, &record.runtime()?.package_family)?
|
||||
.is_empty(),
|
||||
"runtime account is missing while its package remains registered"
|
||||
);
|
||||
continue;
|
||||
};
|
||||
// Persist the obligation before changing SAM, so process death cannot lose it.
|
||||
if flags & UF_ACCOUNTDISABLE != 0 {
|
||||
record.runtime_mut()?.accounts[index].cleanup_logon_pending = true;
|
||||
// Older bundled clients also fail closed while account recovery is pending.
|
||||
record.runtime_mut()?.ready_package = None;
|
||||
crate::installation_record::save_runtime(record)?;
|
||||
akode_windows_sandbox::set_local_user_flags(
|
||||
account.account.username(),
|
||||
flags & !UF_ACCOUNTDISABLE,
|
||||
)?;
|
||||
}
|
||||
let token = with_owner_impersonation(owner_token, || {
|
||||
let mut pins = Vec::new();
|
||||
crate::ipc::pin_existing_ancestors(
|
||||
&akode_windows_sandbox::sandbox_secrets_dir(&record.codex_home),
|
||||
&mut pins,
|
||||
)?;
|
||||
akode_windows_sandbox::logon_existing_sandbox_account(
|
||||
&record.codex_home,
|
||||
account.account,
|
||||
)
|
||||
});
|
||||
if flags & UF_ACCOUNTDISABLE != 0 {
|
||||
super::validate_account_sid(&account)?;
|
||||
let current_flags =
|
||||
akode_windows_sandbox::local_user_flags(account.account.username())?
|
||||
.context("cleanup account disappeared before flag restoration")?;
|
||||
akode_windows_sandbox::set_local_user_flags(
|
||||
account.account.username(),
|
||||
current_flags | UF_ACCOUNTDISABLE,
|
||||
)
|
||||
.context("restore disabled sandbox account after cleanup logon")?;
|
||||
record.runtime_mut()?.accounts[index].cleanup_logon_pending = false;
|
||||
crate::installation_record::save_runtime(record)?;
|
||||
}
|
||||
let token = token?;
|
||||
super::validate_target(
|
||||
token.as_raw_handle() as _,
|
||||
account.account,
|
||||
Some(&account.user_sid),
|
||||
)?;
|
||||
targets.push(serde_json::json!({
|
||||
"username": account.account.username(),
|
||||
"sid": account.user_sid,
|
||||
}));
|
||||
tokens.push(token);
|
||||
}
|
||||
// Flag recovery is durable before the in-memory retirement generation exists.
|
||||
record.runtime_mut()?.ready_package = None;
|
||||
record.runtime_mut()?.retiring = Some(format!("{:?}", windows::core::GUID::new()?));
|
||||
let group_sid = if tokens.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(
|
||||
akode_windows_sandbox::string_from_sid_bytes(&akode_windows_sandbox::resolve_sid(
|
||||
akode_windows_sandbox::SANDBOX_USERS_GROUP,
|
||||
)?)
|
||||
.map_err(anyhow::Error::msg)?,
|
||||
)
|
||||
};
|
||||
let mut system = [0u16; 32768];
|
||||
let length = unsafe { GetSystemDirectoryW(system.as_mut_ptr(), system.len() as u32) } as usize;
|
||||
ensure!(
|
||||
length > 0 && length < system.len(),
|
||||
"Windows system directory is unavailable"
|
||||
);
|
||||
let system = PathBuf::from(String::from_utf16(&system[..length])?);
|
||||
let executable = system.join(r"WindowsPowerShell\v1.0\powershell.exe");
|
||||
let metadata = executable
|
||||
.symlink_metadata()
|
||||
.context("inspect Windows PowerShell")?;
|
||||
ensure!(
|
||||
metadata.is_file()
|
||||
&& metadata.file_attributes()
|
||||
& windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT
|
||||
== 0,
|
||||
"invalid Windows PowerShell executable"
|
||||
);
|
||||
let script = include_str!("removal.ps1");
|
||||
ensure!(
|
||||
executable.as_os_str().len() + script.len() * 2 + 64 < 32767,
|
||||
"cleanup command exceeds the Windows command-line limit"
|
||||
);
|
||||
let mut child = Command::new(executable)
|
||||
.args([
|
||||
"-NoLogo",
|
||||
"-NoProfile",
|
||||
"-NonInteractive",
|
||||
"-Command",
|
||||
script,
|
||||
])
|
||||
.current_dir(system)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.creation_flags(threading::CREATE_NO_WINDOW)
|
||||
.spawn()
|
||||
.context("start Windows package cleanup")?;
|
||||
// Do not relax process handle inheritance. Only these validated token handles
|
||||
// are duplicated into the exact child process, with inheritance disabled.
|
||||
for (target, token) in targets.iter_mut().zip(&tokens) {
|
||||
let mut remote = std::ptr::null_mut();
|
||||
let duplicated = unsafe {
|
||||
DuplicateHandle(
|
||||
threading::GetCurrentProcess(),
|
||||
token.as_raw_handle() as _,
|
||||
child.as_raw_handle() as _,
|
||||
&mut remote,
|
||||
/*dwdesiredaccess*/ 0,
|
||||
/*binherithandle*/ 0,
|
||||
DUPLICATE_SAME_ACCESS,
|
||||
)
|
||||
};
|
||||
ensure!(
|
||||
duplicated != 0,
|
||||
"duplicate managed cleanup token: {}",
|
||||
std::io::Error::last_os_error()
|
||||
);
|
||||
target["handle"] = serde_json::json!(remote as usize);
|
||||
}
|
||||
let plan = serde_json::json!({
|
||||
"key": crate::installation_record::CORE_INSTALLATION_KEY,
|
||||
"legacy_key": crate::installation_record::INSTALLATION_KEY,
|
||||
"value": crate::installation_record::INSTALLATION_VALUE,
|
||||
"record": record,
|
||||
"targets": targets,
|
||||
"service_name": akode_windows_sandbox::windows_sandbox_service_name()?,
|
||||
"group_sid": group_sid,
|
||||
});
|
||||
let input = child.stdin.as_mut().context("capture cleanup input")?;
|
||||
serde_json::to_writer(&mut *input, &plan)?;
|
||||
input.write_all(b"\n")?;
|
||||
let output = child.stdout.as_mut().context("capture cleanup readiness")?;
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
let mut ready = Vec::new();
|
||||
while !ready.ends_with(b"\n") {
|
||||
ensure!(
|
||||
Instant::now() < deadline,
|
||||
"timed out preparing Windows package cleanup"
|
||||
);
|
||||
let mut available = 0;
|
||||
let result = unsafe {
|
||||
PeekNamedPipe(
|
||||
output.as_raw_handle() as _,
|
||||
std::ptr::null_mut(),
|
||||
/*nbuffersize*/ 0,
|
||||
std::ptr::null_mut(),
|
||||
&mut available,
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
ensure!(
|
||||
result != 0,
|
||||
"cleanup exited before readiness: {}",
|
||||
std::io::Error::last_os_error()
|
||||
);
|
||||
if available == 0 {
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
continue;
|
||||
}
|
||||
let mut byte = [0];
|
||||
output.read_exact(&mut byte)?;
|
||||
ready.push(byte[0]);
|
||||
ensure!(ready.len() <= 16, "invalid cleanup readiness response");
|
||||
}
|
||||
ensure!(
|
||||
ready == b"READY\r\n" || ready == b"READY\n",
|
||||
"cleanup profiles were not prepared"
|
||||
);
|
||||
Ok(PreparedRemoval { child, tokens })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "removal_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,153 @@
|
||||
//! Exercise the actual finalizer authorization barrier without account or package mutations.
|
||||
|
||||
use std::io::BufRead;
|
||||
use std::io::BufReader;
|
||||
use std::io::Write;
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::os::windows::process::CommandExt;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use std::process::Stdio;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use pretty_assertions::assert_eq;
|
||||
use windows_sys::Win32::Foundation::WAIT_OBJECT_0;
|
||||
use windows_sys::Win32::Foundation::WAIT_TIMEOUT;
|
||||
use windows_sys::Win32::System::SystemInformation::GetSystemDirectoryW;
|
||||
use windows_sys::Win32::System::Threading::CREATE_NO_WINDOW;
|
||||
use windows_sys::Win32::System::Threading::WaitForSingleObject;
|
||||
|
||||
#[test]
|
||||
fn finalizer_script_parses_and_native_bindings_compile() -> Result<()> {
|
||||
let executable =
|
||||
PathBuf::from(std::env::var_os("SystemRoot").context("SystemRoot is missing")?)
|
||||
.join(r"System32\WindowsPowerShell\v1.0\powershell.exe");
|
||||
let script = include_str!("removal.ps1");
|
||||
let native_start = script
|
||||
.find("Add-Type -TypeDefinition @\"")
|
||||
.context("find native bindings")?;
|
||||
let native_end = native_start
|
||||
+ script[native_start..]
|
||||
.find("\n\"@")
|
||||
.context("find binding boundary")?
|
||||
+ 3;
|
||||
let validation = format!(
|
||||
"$ErrorActionPreference = 'Stop'; $tokens = $null; $errors = $null;\n\
|
||||
$null = [Management.Automation.Language.Parser]::ParseInput([Console]::In.ReadToEnd(), [ref]$tokens, [ref]$errors);\n\
|
||||
if ($errors.Count) {{ throw ($errors | Out-String) }}\n{}",
|
||||
&script[native_start..native_end],
|
||||
);
|
||||
let mut child = Command::new(executable)
|
||||
.args([
|
||||
"-NoLogo",
|
||||
"-NoProfile",
|
||||
"-NonInteractive",
|
||||
"-Command",
|
||||
&validation,
|
||||
])
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.spawn()?;
|
||||
child
|
||||
.stdin
|
||||
.take()
|
||||
.context("capture parser input")?
|
||||
.write_all(script.as_bytes())?;
|
||||
let output = child.wait_with_output()?;
|
||||
ensure!(
|
||||
output.status.success(),
|
||||
"finalizer validation failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finalizer_preserves_utf8_plan_and_requires_commit_and_stdin_eof() -> Result<()> {
|
||||
let mut system = [0u16; 32768];
|
||||
let length = unsafe { GetSystemDirectoryW(system.as_mut_ptr(), system.len() as u32) } as usize;
|
||||
ensure!(
|
||||
length > 0 && length < system.len(),
|
||||
"Windows system directory is unavailable"
|
||||
);
|
||||
let executable = PathBuf::from(String::from_utf16(&system[..length])?)
|
||||
.join(r"WindowsPowerShell\v1.0\powershell.exe");
|
||||
// Run the production decoder and protocol in isolation, never the cleanup body.
|
||||
let script = include_str!("removal.ps1");
|
||||
let input_anchor = "throw 'SYSTEM required' }";
|
||||
let input_start = script.find(input_anchor).context("find input setup")? + input_anchor.len();
|
||||
let input_end = script
|
||||
.find("if ([string]::IsNullOrEmpty")
|
||||
.context("find plan validation")?;
|
||||
let input_setup = &script[input_start..input_end];
|
||||
let start = script
|
||||
.find(" # EOF without a successful native-cleanup commit")
|
||||
.context("find commit barrier")?;
|
||||
let end = script[start..]
|
||||
.find(" $finished = $false")
|
||||
.context("find cleanup boundary")?
|
||||
+ start;
|
||||
let home = r"C:\Users\Zoë-東京\.akode";
|
||||
let script = format!(
|
||||
"$ErrorActionPreference = 'Stop';
|
||||
[Console]::InputEncoding = [Text.Encoding]::GetEncoding(437);
|
||||
{input_setup}
|
||||
if ($plan.record.codex_home -cne '{home}') {{ throw 'UTF-8 plan was corrupted' }}
|
||||
[Console]::Out.WriteLine('waiting');\n{}\n[Console]::Out.WriteLine('released')",
|
||||
&script[start..end]
|
||||
);
|
||||
let mut plan = serde_json::to_vec(&serde_json::json!({ "record": { "codex_home": home } }))?;
|
||||
plan.push(b'\n');
|
||||
for (input, expected) in [
|
||||
("", ""),
|
||||
("ABORT\n", ""),
|
||||
("COMMIT\n", "released"),
|
||||
("COMMIT\ntrailing", ""),
|
||||
] {
|
||||
let mut child = Command::new(&executable)
|
||||
.args([
|
||||
"-NoLogo",
|
||||
"-NoProfile",
|
||||
"-NonInteractive",
|
||||
"-Command",
|
||||
&script,
|
||||
])
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.spawn()?;
|
||||
// Batch the plan and command so decoder read-ahead also exercises the shared reader.
|
||||
let mut request = plan.clone();
|
||||
request.extend_from_slice(input.as_bytes());
|
||||
child
|
||||
.stdin
|
||||
.as_mut()
|
||||
.context("capture barrier input")?
|
||||
.write_all(&request)?;
|
||||
let mut output = BufReader::new(child.stdout.take().context("capture barrier output")?);
|
||||
let mut line = String::new();
|
||||
output.read_line(&mut line)?;
|
||||
assert_eq!(line.trim_end(), "waiting");
|
||||
if input.is_empty() || input.starts_with("COMMIT\n") {
|
||||
let before_eof = unsafe {
|
||||
WaitForSingleObject(child.as_raw_handle() as _, /*dwmilliseconds*/ 500)
|
||||
};
|
||||
assert_eq!(before_eof, WAIT_TIMEOUT);
|
||||
}
|
||||
drop(child.stdin.take());
|
||||
let after_eof = unsafe {
|
||||
WaitForSingleObject(child.as_raw_handle() as _, /*dwmilliseconds*/ 10_000)
|
||||
};
|
||||
assert_eq!(after_eof, WAIT_OBJECT_0);
|
||||
line.clear();
|
||||
output.read_line(&mut line)?;
|
||||
assert_eq!(line.trim_end(), expected);
|
||||
ensure!(child.wait()?.success(), "barrier subprocess failed");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
353
akode-rs/windows-sandbox-service/src/service.rs
Normal file
353
akode-rs/windows-sandbox-service/src/service.rs
Normal file
@@ -0,0 +1,353 @@
|
||||
//! Owns Windows SCM registration, service state, and sandbox provisioning event logs.
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::io;
|
||||
use std::ptr;
|
||||
use std::sync::Arc;
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::AtomicU32;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use akode_windows_sandbox::ServiceStopReason;
|
||||
use windows_sys::Win32::Foundation::ERROR_CALL_NOT_IMPLEMENTED;
|
||||
use windows_sys::Win32::Foundation::ERROR_SERVICE_SPECIFIC_ERROR;
|
||||
use windows_sys::Win32::Foundation::NO_ERROR;
|
||||
use windows_sys::Win32::System::EventLog::DeregisterEventSource;
|
||||
use windows_sys::Win32::System::EventLog::EVENTLOG_ERROR_TYPE;
|
||||
use windows_sys::Win32::System::EventLog::EVENTLOG_INFORMATION_TYPE;
|
||||
use windows_sys::Win32::System::EventLog::RegisterEventSourceW;
|
||||
use windows_sys::Win32::System::EventLog::ReportEventW;
|
||||
use windows_sys::Win32::System::Services::RegisterServiceCtrlHandlerExW;
|
||||
use windows_sys::Win32::System::Services::SERVICE_ACCEPT_SESSIONCHANGE;
|
||||
use windows_sys::Win32::System::Services::SERVICE_ACCEPT_SHUTDOWN;
|
||||
use windows_sys::Win32::System::Services::SERVICE_ACCEPT_STOP;
|
||||
use windows_sys::Win32::System::Services::SERVICE_CONTROL_INTERROGATE;
|
||||
use windows_sys::Win32::System::Services::SERVICE_CONTROL_SESSIONCHANGE;
|
||||
use windows_sys::Win32::System::Services::SERVICE_CONTROL_SHUTDOWN;
|
||||
use windows_sys::Win32::System::Services::SERVICE_CONTROL_STOP;
|
||||
use windows_sys::Win32::System::Services::SERVICE_RUNNING;
|
||||
use windows_sys::Win32::System::Services::SERVICE_START_PENDING;
|
||||
use windows_sys::Win32::System::Services::SERVICE_STATUS;
|
||||
use windows_sys::Win32::System::Services::SERVICE_STATUS_HANDLE;
|
||||
use windows_sys::Win32::System::Services::SERVICE_STOP_PENDING;
|
||||
use windows_sys::Win32::System::Services::SERVICE_STOPPED;
|
||||
use windows_sys::Win32::System::Services::SERVICE_TABLE_ENTRYW;
|
||||
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) use runtime_lifecycle::retry_cleanup;
|
||||
|
||||
const EVENT_SERVICE_STARTED: u32 = 1000;
|
||||
const EVENT_SERVICE_STOP_REQUESTED: u32 = 1001;
|
||||
const EVENT_SERVICE_STOPPED: u32 = 1002;
|
||||
pub(crate) const EVENT_SERVICE_FAILED: u32 = 1003;
|
||||
pub(crate) const EVENT_PROVISIONING_SUCCEEDED: u32 = 2000;
|
||||
pub(crate) const EVENT_PROVISIONING_FAILED: u32 = 2001;
|
||||
pub(crate) const EVENT_REQUEST_REJECTED: u32 = 2002;
|
||||
pub(crate) const EVENT_CLEANUP_STARTED: u32 = 3002;
|
||||
pub(crate) const EVENT_CLEANUP_FINISHED: u32 = 3003;
|
||||
pub(crate) const EVENT_CLEANUP_DETAIL: u32 = 3004;
|
||||
const MAX_EVENT_MESSAGE_UNITS: usize = 1024;
|
||||
|
||||
static SERVICE_STATE: OnceLock<ServiceState> = OnceLock::new();
|
||||
|
||||
struct ServiceStatusToken(SERVICE_STATUS_HANDLE);
|
||||
|
||||
// SAFETY: Windows permits threads in the calling process to use this opaque
|
||||
// status token. The token does not need closing; this wrapper only shares it.
|
||||
unsafe impl Send for ServiceStatusToken {}
|
||||
unsafe impl Sync for ServiceStatusToken {}
|
||||
|
||||
struct ServiceState {
|
||||
service_name: String,
|
||||
pipe_name: String,
|
||||
shutdown: Arc<AtomicBool>,
|
||||
uninstalling: Arc<AtomicBool>,
|
||||
status_handle: OnceLock<ServiceStatusToken>,
|
||||
current_status: AtomicU32,
|
||||
stop_requested: AtomicBool,
|
||||
}
|
||||
|
||||
pub(crate) fn run() -> Result<()> {
|
||||
let service_name = akode_windows_sandbox::windows_sandbox_service_name()?;
|
||||
let state = ServiceState {
|
||||
service_name: service_name.clone(),
|
||||
pipe_name: akode_windows_sandbox::windows_sandbox_service_pipe_name()?,
|
||||
shutdown: Arc::new(AtomicBool::new(false)),
|
||||
uninstalling: Arc::new(AtomicBool::new(false)),
|
||||
status_handle: OnceLock::new(),
|
||||
current_status: AtomicU32::new(SERVICE_START_PENDING),
|
||||
stop_requested: AtomicBool::new(false),
|
||||
};
|
||||
SERVICE_STATE
|
||||
.set(state)
|
||||
.map_err(|_| anyhow::anyhow!("the service dispatcher was already initialized"))?;
|
||||
|
||||
let mut service_name = service_name
|
||||
.encode_utf16()
|
||||
.chain(std::iter::once(0))
|
||||
.collect::<Vec<_>>();
|
||||
let service_table = [
|
||||
SERVICE_TABLE_ENTRYW {
|
||||
lpServiceName: service_name.as_mut_ptr(),
|
||||
lpServiceProc: Some(service_main),
|
||||
},
|
||||
SERVICE_TABLE_ENTRYW {
|
||||
lpServiceName: ptr::null_mut(),
|
||||
lpServiceProc: None,
|
||||
},
|
||||
];
|
||||
|
||||
// The table and its service-name buffer remain alive until the dispatcher returns.
|
||||
let dispatched = unsafe { StartServiceCtrlDispatcherW(service_table.as_ptr()) };
|
||||
if dispatched == 0 {
|
||||
return Err(io::Error::last_os_error()).context("start the Windows service dispatcher");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
pub(crate) fn run_foreground() -> Result<()> {
|
||||
crate::package_identity::enable_foreground_mode();
|
||||
crate::ipc::run(
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
|| {
|
||||
eprintln!(
|
||||
"{} listening on {}",
|
||||
akode_windows_sandbox::windows_sandbox_service_name()?,
|
||||
akode_windows_sandbox::windows_sandbox_service_pipe_name()?
|
||||
);
|
||||
Ok(())
|
||||
},
|
||||
runtime_lifecycle::foreground_owner,
|
||||
|| Ok(()),
|
||||
)
|
||||
}
|
||||
|
||||
unsafe extern "system" fn service_main(_argument_count: u32, _arguments: *mut *mut u16) {
|
||||
let Some(state) = SERVICE_STATE.get() else {
|
||||
return;
|
||||
};
|
||||
|
||||
ServiceStopReason::Starting.record(/*hresult*/ 0);
|
||||
if let Err(error) = service_main_inner(state) {
|
||||
let reason = if error.is::<crate::registered_runtime::RegistrationInterrupted>() {
|
||||
ServiceStopReason::RegistrationInterrupted
|
||||
} else if state.current_status.load(Ordering::Acquire) == SERVICE_START_PENDING {
|
||||
ServiceStopReason::StartupFailed
|
||||
} else {
|
||||
ServiceStopReason::BrokerFailed
|
||||
};
|
||||
reason.record(fatal_error_hresult(&error));
|
||||
log_error(
|
||||
EVENT_SERVICE_FAILED,
|
||||
&format!("The Codex sandbox service encountered a fatal error: {error:#}"),
|
||||
);
|
||||
eprintln!("{} failed: {error:#}", state.service_name);
|
||||
if state.status_handle.get().is_some() {
|
||||
let _ = state.report_status(SERVICE_STOPPED, ERROR_SERVICE_SPECIFIC_ERROR);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn service_main_inner(state: &ServiceState) -> Result<()> {
|
||||
let service_name = state
|
||||
.service_name
|
||||
.encode_utf16()
|
||||
.chain(std::iter::once(0))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// The service controller only reads the name during registration.
|
||||
let status_handle = unsafe {
|
||||
RegisterServiceCtrlHandlerExW(
|
||||
service_name.as_ptr(),
|
||||
Some(service_control_handler),
|
||||
ptr::null(),
|
||||
)
|
||||
};
|
||||
if status_handle.is_null() {
|
||||
return Err(io::Error::last_os_error()).context("register the service control handler");
|
||||
}
|
||||
state
|
||||
.status_handle
|
||||
.set(ServiceStatusToken(status_handle))
|
||||
.map_err(|_| anyhow::anyhow!("the service status handle was already registered"))?;
|
||||
|
||||
state.report_status(SERVICE_START_PENDING, NO_ERROR)?;
|
||||
let package_lifecycle =
|
||||
crate::package_lifecycle::PackageLifecycle::new(Arc::clone(&state.uninstalling))?;
|
||||
let reason = runtime_lifecycle::run(state, &package_lifecycle)?;
|
||||
reason.record(/*hresult*/ 0);
|
||||
log_information(
|
||||
EVENT_SERVICE_STOPPED,
|
||||
"The Codex sandbox service has stopped.",
|
||||
);
|
||||
state.report_status(SERVICE_STOPPED, NO_ERROR)
|
||||
}
|
||||
|
||||
fn fatal_error_hresult(error: &anyhow::Error) -> u32 {
|
||||
// Never stringify an error: contexts can contain paths, accounts or credentials.
|
||||
error
|
||||
.chain()
|
||||
.find_map(|cause| {
|
||||
if let Some(error) = cause.downcast_ref::<windows::core::Error>() {
|
||||
return Some(error.code().0 as u32);
|
||||
}
|
||||
cause
|
||||
.downcast_ref::<io::Error>()?
|
||||
.raw_os_error()
|
||||
.map(|code| windows::core::HRESULT::from_win32(code as u32).0 as u32)
|
||||
})
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
unsafe extern "system" fn service_control_handler(
|
||||
control: u32,
|
||||
_event_type: u32,
|
||||
_event_data: *mut c_void,
|
||||
_context: *mut c_void,
|
||||
) -> u32 {
|
||||
let Some(state) = SERVICE_STATE.get() else {
|
||||
return ERROR_CALL_NOT_IMPLEMENTED;
|
||||
};
|
||||
|
||||
match control {
|
||||
SERVICE_CONTROL_STOP | SERVICE_CONTROL_SHUTDOWN => {
|
||||
if control == SERVICE_CONTROL_STOP {
|
||||
state.stop_requested.store(true, Ordering::Release);
|
||||
}
|
||||
if !state.shutdown.swap(true, Ordering::AcqRel) {
|
||||
if let Err(error) = state.report_status(SERVICE_STOP_PENDING, NO_ERROR) {
|
||||
eprintln!("unable to report service shutdown: {error:#}");
|
||||
}
|
||||
log_information(
|
||||
EVENT_SERVICE_STOP_REQUESTED,
|
||||
"The Codex sandbox service was asked to stop.",
|
||||
);
|
||||
wake_listener();
|
||||
}
|
||||
NO_ERROR
|
||||
}
|
||||
SERVICE_CONTROL_INTERROGATE => {
|
||||
let current_status = state.current_status.load(Ordering::Acquire);
|
||||
if let Err(error) = state.report_status(current_status, NO_ERROR) {
|
||||
log_error(
|
||||
EVENT_SERVICE_FAILED,
|
||||
"The Codex sandbox service could not report its current status.",
|
||||
);
|
||||
eprintln!("unable to report the current service status: {error:#}");
|
||||
}
|
||||
NO_ERROR
|
||||
}
|
||||
SERVICE_CONTROL_SESSIONCHANGE => {
|
||||
wake_listener();
|
||||
NO_ERROR
|
||||
}
|
||||
_ => ERROR_CALL_NOT_IMPLEMENTED,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn wake_listener() {
|
||||
if let Some(state) = SERVICE_STATE.get() {
|
||||
std::thread::spawn(move || {
|
||||
crate::ipc::wake(&state.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);
|
||||
}
|
||||
|
||||
pub(crate) fn log_error(event_id: u32, message: &str) {
|
||||
log_event(EVENTLOG_ERROR_TYPE, event_id, message);
|
||||
}
|
||||
|
||||
fn log_event(event_type: u16, event_id: u32, message: &str) {
|
||||
let source = SERVICE_STATE
|
||||
.get()
|
||||
.map_or("CodexSandboxService", |state| state.service_name.as_str())
|
||||
.encode_utf16()
|
||||
.chain(std::iter::once(0))
|
||||
.collect::<Vec<_>>();
|
||||
let event_log = unsafe { RegisterEventSourceW(ptr::null(), source.as_ptr()) };
|
||||
if event_log.is_null() {
|
||||
eprintln!("unable to open the Windows event log: {message}");
|
||||
return;
|
||||
}
|
||||
|
||||
let mut message_units = Vec::with_capacity(MAX_EVENT_MESSAGE_UNITS + 1);
|
||||
for character in message.chars() {
|
||||
let character = if character.is_control() {
|
||||
' '
|
||||
} else {
|
||||
character
|
||||
};
|
||||
let mut buffer = [0_u16; 2];
|
||||
let encoded = character.encode_utf16(&mut buffer);
|
||||
if message_units.len() + encoded.len() > MAX_EVENT_MESSAGE_UNITS {
|
||||
break;
|
||||
}
|
||||
message_units.extend_from_slice(encoded);
|
||||
}
|
||||
message_units.push(0);
|
||||
let strings = [message_units.as_ptr()];
|
||||
let reported = unsafe {
|
||||
ReportEventW(
|
||||
event_log,
|
||||
event_type,
|
||||
0,
|
||||
event_id,
|
||||
ptr::null_mut(),
|
||||
1,
|
||||
0,
|
||||
strings.as_ptr(),
|
||||
ptr::null(),
|
||||
)
|
||||
};
|
||||
if reported == 0 {
|
||||
eprintln!("unable to write a Windows event-log entry (event {event_id})");
|
||||
}
|
||||
unsafe { DeregisterEventSource(event_log) };
|
||||
}
|
||||
|
||||
impl ServiceState {
|
||||
fn report_status(&self, current_status: u32, win32_exit_code: u32) -> Result<()> {
|
||||
let status_handle = self
|
||||
.status_handle
|
||||
.get()
|
||||
.context("the service status handle was not registered")?;
|
||||
let is_pending = matches!(current_status, SERVICE_START_PENDING | SERVICE_STOP_PENDING);
|
||||
let status = SERVICE_STATUS {
|
||||
dwServiceType: SERVICE_WIN32_OWN_PROCESS,
|
||||
dwCurrentState: current_status,
|
||||
dwControlsAccepted: if current_status == SERVICE_RUNNING {
|
||||
SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_SESSIONCHANGE
|
||||
} else {
|
||||
0
|
||||
},
|
||||
dwWin32ExitCode: win32_exit_code,
|
||||
dwServiceSpecificExitCode: u32::from(win32_exit_code == ERROR_SERVICE_SPECIFIC_ERROR),
|
||||
dwCheckPoint: u32::from(is_pending),
|
||||
dwWaitHint: if is_pending { 10_000 } else { 0 },
|
||||
};
|
||||
|
||||
// The SCM synchronously copies the status structure during this call.
|
||||
let updated = unsafe { SetServiceStatus(status_handle.0, &status) };
|
||||
if updated == 0 {
|
||||
return Err(io::Error::last_os_error()).context("update the Windows service status");
|
||||
}
|
||||
self.current_status.store(current_status, Ordering::Release);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
//! Runs owner-aware cleanup in the live provisioning broker before further admission.
|
||||
//! Shutdown means SCM stop until cleanup finishes; retirement fences are never replayed.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use akode_windows_sandbox::ServiceStopReason;
|
||||
use windows_sys::Win32::Foundation::NO_ERROR;
|
||||
use windows_sys::Win32::System::Services::SERVICE_RUNNING;
|
||||
use windows_sys::Win32::System::Services::SERVICE_STOP_PENDING;
|
||||
|
||||
use super::EVENT_SERVICE_FAILED;
|
||||
use super::EVENT_SERVICE_STARTED;
|
||||
use super::SERVICE_STATE;
|
||||
use super::ServiceState;
|
||||
use super::log_error;
|
||||
use super::log_information;
|
||||
use crate::package_lifecycle::PackageLifecycle;
|
||||
|
||||
/// Foreground debugging has no persistent watcher, but must retain the same admission rules.
|
||||
#[cfg(debug_assertions)]
|
||||
pub(super) fn foreground_owner(
|
||||
mut record: crate::installation_record::InstallationRecord,
|
||||
_token: std::os::windows::io::OwnedHandle,
|
||||
runtime: akode_windows_sandbox::SetupRuntime,
|
||||
) -> Result<crate::installation_record::InstallationRecord> {
|
||||
let _lock = akode_windows_sandbox::acquire_sandbox_setup_lock(/*timeout_ms*/ 5_000)?;
|
||||
if let Some(previous) = crate::installation_record::load()? {
|
||||
let same_owner =
|
||||
previous.user_sid == record.user_sid && previous.codex_home == record.codex_home;
|
||||
if previous.runtime.is_some() {
|
||||
let family = windows::ApplicationModel::Package::Current()?
|
||||
.Id()?
|
||||
.FamilyName()?;
|
||||
previous.admit_owner(&record, &family.to_string())?;
|
||||
record.runtime = previous.runtime;
|
||||
} else if runtime == akode_windows_sandbox::SetupRuntime::Registered {
|
||||
anyhow::ensure!(
|
||||
same_owner,
|
||||
"shared sandbox resources belong to a different owner"
|
||||
);
|
||||
}
|
||||
if same_owner {
|
||||
record.desktop_installation = previous
|
||||
.desktop_installation
|
||||
.or(record.desktop_installation);
|
||||
}
|
||||
}
|
||||
Ok(record)
|
||||
}
|
||||
|
||||
pub(super) fn run(
|
||||
state: &ServiceState,
|
||||
package_lifecycle: &PackageLifecycle,
|
||||
) -> Result<ServiceStopReason> {
|
||||
let cleaned = Cell::new(false);
|
||||
let last_cleanup_error = Cell::new(None);
|
||||
let restore_owner = || -> Result<()> {
|
||||
crate::registered_runtime::restore_disabled_accounts()?;
|
||||
let restored = crate::installation_record::load().and_then(|record| {
|
||||
record.map_or(Ok(()), |record| {
|
||||
package_lifecycle.restore_logged_in_owner(record.session_id)
|
||||
})
|
||||
});
|
||||
if let Err(error) = restored {
|
||||
log_error(
|
||||
EVENT_SERVICE_FAILED,
|
||||
&format!("unable to restore package uninstall listener: {error:#}"),
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
crate::ipc::run(
|
||||
Arc::clone(&state.shutdown),
|
||||
|| {
|
||||
restore_owner()?;
|
||||
state.report_status(SERVICE_RUNNING, NO_ERROR)?;
|
||||
log_information(
|
||||
EVENT_SERVICE_STARTED,
|
||||
"The Codex sandbox service is running.",
|
||||
);
|
||||
Ok(())
|
||||
},
|
||||
|installation, user_token, _runtime| {
|
||||
package_lifecycle.register_authenticated_user(installation, user_token)
|
||||
},
|
||||
|| loop {
|
||||
restore_owner()?;
|
||||
if !crate::package_lifecycle::runtime_owner_removed()? {
|
||||
last_cleanup_error.set(None);
|
||||
return Ok(());
|
||||
}
|
||||
let Err(error) = package_lifecycle.clean_up() else {
|
||||
cleaned.set(true);
|
||||
state.shutdown.store(true, Ordering::Release);
|
||||
return state.report_status(SERVICE_STOP_PENDING, NO_ERROR);
|
||||
};
|
||||
if crate::installation_record::load_runtime()?.is_none_or(|record| {
|
||||
record
|
||||
.runtime
|
||||
.is_some_and(|runtime| runtime.retiring.is_some())
|
||||
}) {
|
||||
return Err(error);
|
||||
}
|
||||
log_cleanup_error(&error, &last_cleanup_error);
|
||||
// Keep the pipe available during pre-fence backoff. A reinstall
|
||||
// resumes admission on the next owner check; SCM stops are never reset.
|
||||
if !wait_for_cleanup_retry(state) {
|
||||
return Err(error);
|
||||
}
|
||||
},
|
||||
)
|
||||
.context("run the sandbox provisioning broker")?;
|
||||
if !cleaned.get()
|
||||
&& state.stop_requested.load(Ordering::Acquire)
|
||||
&& (state.uninstalling.load(Ordering::Acquire)
|
||||
|| crate::package_lifecycle::runtime_owner_removed()?)
|
||||
{
|
||||
package_lifecycle.clean_up()?;
|
||||
}
|
||||
Ok(if cleaned.get() {
|
||||
ServiceStopReason::OwnerRemoved
|
||||
} else if state.stop_requested.load(Ordering::Acquire) {
|
||||
ServiceStopReason::StopRequested
|
||||
} else {
|
||||
ServiceStopReason::Shutdown
|
||||
})
|
||||
}
|
||||
|
||||
/// Retries the current teardown step, never a phase recovered from stored intent.
|
||||
pub(crate) fn retry_cleanup(mut operation: impl FnMut() -> Result<()>) -> Result<()> {
|
||||
let mut stop_failures = 0;
|
||||
let last_cleanup_error = Cell::new(None);
|
||||
loop {
|
||||
let Err(error) = operation() else {
|
||||
return Ok(());
|
||||
};
|
||||
let Some(state) = SERVICE_STATE.get() else {
|
||||
return Err(error);
|
||||
};
|
||||
log_cleanup_error(&error, &last_cleanup_error);
|
||||
if state.stop_requested.load(Ordering::Acquire) {
|
||||
// SCM stop initiates uninstall cleanup rather than cancelling it.
|
||||
// Four one-second retry waits fit within the 10-second SCM wait hint.
|
||||
stop_failures += 1;
|
||||
if stop_failures == 5 {
|
||||
return Err(error);
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_secs(1));
|
||||
} else if !wait_for_cleanup_retry(state) && !state.stop_requested.load(Ordering::Acquire) {
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn log_cleanup_error(error: &anyhow::Error, previous: &Cell<Option<String>>) {
|
||||
let message = format!("sandbox cleanup deferred: {error:#}");
|
||||
// Retrying an unchanged failure must not flood the Windows event log.
|
||||
if previous.take().as_deref() != Some(message.as_str()) {
|
||||
log_error(EVENT_SERVICE_FAILED, &message);
|
||||
}
|
||||
previous.set(Some(message));
|
||||
}
|
||||
|
||||
fn wait_for_cleanup_retry(state: &ServiceState) -> bool {
|
||||
for _ in 0..30 {
|
||||
if state.shutdown.load(Ordering::Acquire) {
|
||||
return false;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_secs(1));
|
||||
}
|
||||
!state.shutdown.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "runtime_lifecycle_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,103 @@
|
||||
//! Verifies teardown retries distinguish SCM stop from system shutdown.
|
||||
|
||||
use super::retry_cleanup;
|
||||
use crate::service::SERVICE_STATE;
|
||||
use crate::service::ServiceState;
|
||||
use crate::service::fatal_error_hresult;
|
||||
use crate::service::service_control_handler;
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::io;
|
||||
use std::ptr;
|
||||
use std::sync::Arc;
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::AtomicU32;
|
||||
use std::sync::atomic::Ordering;
|
||||
use windows_sys::Win32::Foundation::ERROR_SHARING_VIOLATION;
|
||||
use windows_sys::Win32::Foundation::NO_ERROR;
|
||||
use windows_sys::Win32::System::Services::SERVICE_CONTROL_SHUTDOWN;
|
||||
use windows_sys::Win32::System::Services::SERVICE_CONTROL_STOP;
|
||||
use windows_sys::Win32::System::Services::SERVICE_STOPPED;
|
||||
|
||||
#[test]
|
||||
fn fatal_diagnostics_keep_typed_codes_without_error_text() {
|
||||
let errors = [
|
||||
(
|
||||
anyhow::Error::new(io::Error::from_raw_os_error(5)),
|
||||
0x80070005,
|
||||
),
|
||||
(
|
||||
anyhow::Error::new(windows::core::Error::from_hresult(windows::core::HRESULT(
|
||||
0x80073cf3_u32 as i32,
|
||||
))),
|
||||
0x80073cf3,
|
||||
),
|
||||
(anyhow::anyhow!("token=private (os error 5)"), 0),
|
||||
];
|
||||
for (error, expected) in errors {
|
||||
assert_eq!(
|
||||
fatal_error_hresult(&error.context("private path/account")),
|
||||
expected
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_retries_after_scm_stop_but_not_system_shutdown() -> Result<()> {
|
||||
// One test owns the process-global state. The pre-set shutdown flag keeps
|
||||
// the real control handler from calling SCM or spawning a pipe wake thread.
|
||||
assert!(
|
||||
SERVICE_STATE
|
||||
.set(ServiceState {
|
||||
service_name: "CodexSandboxServiceTests".into(),
|
||||
pipe_name: r"\\.\pipe\CodexSandboxServiceTests".into(),
|
||||
shutdown: Arc::new(AtomicBool::new(true)),
|
||||
uninstalling: Arc::new(AtomicBool::new(false)),
|
||||
status_handle: OnceLock::new(),
|
||||
current_status: AtomicU32::new(SERVICE_STOPPED),
|
||||
stop_requested: AtomicBool::new(false),
|
||||
})
|
||||
.is_ok()
|
||||
);
|
||||
let state = SERVICE_STATE.get().context("service state is missing")?;
|
||||
for (control, failures, expected_attempts, expected_success) in [
|
||||
(SERVICE_CONTROL_SHUTDOWN, 1, 1, false),
|
||||
(SERVICE_CONTROL_STOP, 1, 2, true),
|
||||
(SERVICE_CONTROL_STOP, usize::MAX, 5, false),
|
||||
] {
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
service_control_handler(
|
||||
control,
|
||||
/*_event_type*/ 0,
|
||||
ptr::null_mut(),
|
||||
ptr::null_mut(),
|
||||
)
|
||||
},
|
||||
NO_ERROR
|
||||
);
|
||||
let mut attempts = 0;
|
||||
let result = retry_cleanup(|| {
|
||||
attempts += 1;
|
||||
if attempts <= failures {
|
||||
return Err(io::Error::from_raw_os_error(ERROR_SHARING_VIOLATION as i32).into());
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
assert_eq!(result.is_ok(), expected_success);
|
||||
assert_eq!(attempts, expected_attempts);
|
||||
assert!(state.shutdown.load(Ordering::Acquire));
|
||||
if let Err(error) = result {
|
||||
assert_eq!(
|
||||
error
|
||||
.downcast_ref::<io::Error>()
|
||||
.context("cleanup did not preserve the I/O error")?
|
||||
.raw_os_error(),
|
||||
Some(ERROR_SHARING_VIOLATION as i32)
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
28
akode-rs/windows-sandbox-service/src/uninstall_policy.rs
Normal file
28
akode-rs/windows-sandbox-service/src/uninstall_policy.rs
Normal file
@@ -0,0 +1,28 @@
|
||||
//! Reads the owner's current home-deletion preference; existing OEM preinstalls retain their default.
|
||||
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
|
||||
use akode_config::AbsolutePathBufGuard;
|
||||
use akode_config::config_toml::ConfigToml;
|
||||
|
||||
pub(crate) fn clean_uninstall_enabled(home: &Path, preinstalled: bool) -> bool {
|
||||
let contents = match std::fs::read_to_string(home.join("config.toml")) {
|
||||
Ok(contents) => contents,
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => return preinstalled,
|
||||
Err(_) => return false,
|
||||
};
|
||||
let _guard = AbsolutePathBufGuard::new(home);
|
||||
let Ok(config) = toml::from_str::<ConfigToml>(&contents) else {
|
||||
return false;
|
||||
};
|
||||
config
|
||||
.desktop
|
||||
.as_ref()
|
||||
.and_then(|desktop| desktop.get("uninstall_codex_home"))
|
||||
.map_or(preinstalled, |value| value.as_bool().unwrap_or(false))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "uninstall_policy_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,74 @@
|
||||
//! Verifies local configuration precedence over the preinstalled cleanup default.
|
||||
|
||||
use anyhow::Result;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::clean_uninstall_enabled;
|
||||
|
||||
/// Existing preinstalls keep clean uninstall when no user preference exists.
|
||||
#[test]
|
||||
fn missing_preference_uses_preinstall_default() -> Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
for preinstalled in [false, true] {
|
||||
assert_eq!(
|
||||
clean_uninstall_enabled(home.path(), preinstalled),
|
||||
preinstalled
|
||||
);
|
||||
}
|
||||
for contents in ["", "log_dir = 'logs'", "[desktop]\ntheme = 'dark'"] {
|
||||
std::fs::write(home.path().join("config.toml"), contents)?;
|
||||
for preinstalled in [false, true] {
|
||||
assert_eq!(
|
||||
clean_uninstall_enabled(home.path(), preinstalled),
|
||||
preinstalled
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A user's explicit choice overrides both ordinary and preinstalled defaults.
|
||||
#[test]
|
||||
fn explicit_preference_overrides_preinstall_default() -> Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
for enabled in [false, true] {
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
format!("log_dir = 'logs'\n[desktop]\nuninstall_codex_home = {enabled}"),
|
||||
)?;
|
||||
for preinstalled in [false, true] {
|
||||
assert_eq!(clean_uninstall_enabled(home.path(), preinstalled), enabled);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Invalid configuration never falls back to destructive cleanup, even on a preload.
|
||||
#[test]
|
||||
fn malformed_or_invalid_preference_preserves_home() -> Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
for contents in [
|
||||
"[desktop",
|
||||
"desktop = false",
|
||||
"[desktop]\nuninstall_codex_home = 'true'",
|
||||
"[desktop]\nuninstall_codex_home = 1",
|
||||
"[desktop]\nuninstall_codex_home = []",
|
||||
] {
|
||||
std::fs::write(home.path().join("config.toml"), contents)?;
|
||||
for preinstalled in [false, true] {
|
||||
assert!(!clean_uninstall_enabled(home.path(), preinstalled));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Failure to read an existing config must not restore the preinstalled deletion default.
|
||||
#[test]
|
||||
fn unreadable_config_preserves_home() -> Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
std::fs::create_dir(home.path().join("config.toml"))?;
|
||||
for preinstalled in [false, true] {
|
||||
assert!(!clean_uninstall_enabled(home.path(), preinstalled));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user