//! 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, ) -> Result { // 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, mut registered_packages: impl FnMut(&str, &str) -> Result>, ) -> Result { 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::() => 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) }