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,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);
}

View File

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