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:
andrea.difonzo
2026-11-11 11:06:46 +01:00
parent df99318392
commit 86e7c72e5f
10383 changed files with 749164 additions and 749170 deletions

View File

@@ -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(())
}

View 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)
}

View File

@@ -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(())
}