refactor(installer): split service.rs into mod/plan/validation/execution/tests
Move the 4218-line shared service layer into focused modules with no behavior change: mod.rs keeps the plan types, render, and shared helpers with explicit re-exports so every phoebus_installer::service::* path, the serialized plan format, approval digests, replay protection, and privileged validation behavior are unchanged; plan.rs holds PlanStore and the planning APIs; validation.rs holds seals, digests, and the privileged validation boundary; execution.rs holds validated elevated execution; tests.rs holds the regression suite verbatim. Sibling-private helpers (constrain_action, plan_integrity, reviewed_steps, validate_effect_bindings, ServiceConfirm) are pub(super) with explicit imports; no glob re-exports. cargo fmt clean; cargo clippy --workspace --all-targets -- -D warnings clean; cargo test --workspace passes (692 passed, 0 failed, identical to the pre-split baseline; plan_golden and adversarial digest tests unchanged).
This commit is contained in:
parent
e69bfb9aef
commit
1bf31c5a72
6 changed files with 4292 additions and 4218 deletions
File diff suppressed because it is too large
Load diff
529
installer-rs/crates/phoebus-installer/src/service/execution.rs
Normal file
529
installer-rs/crates/phoebus-installer/src/service/execution.rs
Normal file
|
|
@ -0,0 +1,529 @@
|
||||||
|
//! Validated, elevated execution with transaction recording: the only path
|
||||||
|
//! from an approved [`PreparedPlan`] to a system mutation.
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use phoebus_core::effects::{approval_holds, PackageEffect, ResolvedPlan};
|
||||||
|
use phoebus_core::selection::Backend;
|
||||||
|
use phoebus_core::transaction::{TransactionOutcome, TransactionRecord};
|
||||||
|
use phoebus_executor::actions;
|
||||||
|
use phoebus_executor::auth::authorize;
|
||||||
|
use phoebus_executor::chooser;
|
||||||
|
use phoebus_executor::error::{ExecError, Result};
|
||||||
|
use phoebus_executor::exec::Exec;
|
||||||
|
use phoebus_executor::install::{InstallRequest, InstallSource};
|
||||||
|
use phoebus_executor::{install, transaction};
|
||||||
|
|
||||||
|
use crate::approval::{ApprovalIdentity, ApprovalLedger, ApprovalStatus, Finished};
|
||||||
|
|
||||||
|
use super::validation::{reviewed_steps, validate_prepared_plan, ServiceConfirm};
|
||||||
|
use super::{
|
||||||
|
canonical_root, effective_uid, now_unix, PlanExecutionOutcome, PlanKind, PlanStore,
|
||||||
|
PreparedPlan,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Execute a prepared plan with full validation, elevation, verification, and
|
||||||
|
/// transaction recording.
|
||||||
|
pub fn execute_plan(
|
||||||
|
exec: &Exec,
|
||||||
|
root: &Path,
|
||||||
|
plans: &PlanStore,
|
||||||
|
plan_id: &str,
|
||||||
|
expected_digest: &str,
|
||||||
|
assume_yes: bool,
|
||||||
|
) -> Result<PlanExecutionOutcome> {
|
||||||
|
let initiator = effective_uid();
|
||||||
|
let plan = plans.load(plan_id)?;
|
||||||
|
validate_prepared_plan(exec, root, &plan, Some(expected_digest), initiator)?;
|
||||||
|
if plans.is_claimed(plan_id) {
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"execute_plan",
|
||||||
|
"plan has already been consumed; retrying will not repeat the mutation",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
if plan.requires_root && initiator != 0 {
|
||||||
|
return elevate_and_execute(root, plan, initiator, expected_digest);
|
||||||
|
}
|
||||||
|
execute_prepared(exec, root, plans, plan, assume_yes, None)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The privileged broker entry point.
|
||||||
|
///
|
||||||
|
/// It repeats the full validation after authentication (never trusting the
|
||||||
|
/// unprivileged caller), binds execution to the independently preserved
|
||||||
|
/// `expected_digest` the approval UI showed the user, and anchors consumption in
|
||||||
|
/// the broker-controlled [`ApprovalLedger`]. A plan file replaced during
|
||||||
|
/// authentication no longer matches `expected_digest`; a replay is refused even
|
||||||
|
/// when the user deletes every file in their own plan directory.
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
pub fn execute_plan_privileged(
|
||||||
|
exec: &Exec,
|
||||||
|
root: &Path,
|
||||||
|
plans: &PlanStore,
|
||||||
|
approvals: &ApprovalLedger,
|
||||||
|
plan_id: &str,
|
||||||
|
expected_digest: &str,
|
||||||
|
initiator_uid: u32,
|
||||||
|
assume_yes: bool,
|
||||||
|
) -> Result<PlanExecutionOutcome> {
|
||||||
|
let plan = plans.load(plan_id)?;
|
||||||
|
// The expected digest is the independently preserved approval the user
|
||||||
|
// reviewed. A self-consistent reseal of a replacement plan cannot match it.
|
||||||
|
validate_prepared_plan(exec, root, &plan, Some(expected_digest), initiator_uid)?;
|
||||||
|
// `execute_prepared` authenticates *before* claiming the approval, so a
|
||||||
|
// cancelled or refused operation consumes nothing; it then anchors the
|
||||||
|
// claim in the broker-controlled ledger and records a terminal status.
|
||||||
|
execute_prepared(
|
||||||
|
exec,
|
||||||
|
root,
|
||||||
|
plans,
|
||||||
|
plan,
|
||||||
|
assume_yes,
|
||||||
|
Some((approvals, initiator_uid)),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn elevate_and_execute(
|
||||||
|
root: &Path,
|
||||||
|
plan: PreparedPlan,
|
||||||
|
initiator: u32,
|
||||||
|
expected_digest: &str,
|
||||||
|
) -> Result<PlanExecutionOutcome> {
|
||||||
|
let sys_exe = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("/usr/local/bin/sys"));
|
||||||
|
// The privileged broker is given the plan identifier, the independently
|
||||||
|
// preserved approval digest, the initiating uid and the exact target root.
|
||||||
|
// A dropped `--root` would (correctly) fail validation rather than execute
|
||||||
|
// against `/`.
|
||||||
|
let output = std::process::Command::new("pkexec")
|
||||||
|
.arg(sys_exe)
|
||||||
|
.arg("--broker")
|
||||||
|
.arg("--execute-plan")
|
||||||
|
.arg(&plan.id)
|
||||||
|
.arg("--plan-uid")
|
||||||
|
.arg(initiator.to_string())
|
||||||
|
.arg("--approval-digest")
|
||||||
|
.arg(expected_digest)
|
||||||
|
.arg("--root")
|
||||||
|
.arg(canonical_root(root))
|
||||||
|
.output()
|
||||||
|
.map_err(|e| {
|
||||||
|
ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"pkexec",
|
||||||
|
format!("could not spawn pkexec for root authorization: {e}"),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
if output.status.success() {
|
||||||
|
let out_str = String::from_utf8_lossy(&output.stdout);
|
||||||
|
return serde_json::from_str::<PlanExecutionOutcome>(out_str.trim()).map_err(|e| {
|
||||||
|
ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"broker protocol",
|
||||||
|
format!("privileged execution reported success but returned malformed output: {e}"),
|
||||||
|
)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let code = output.status.code().unwrap_or(1);
|
||||||
|
if code == 126 || code == 127 {
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"authenticate",
|
||||||
|
"authentication was cancelled; no changes were made",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let err_msg = String::from_utf8_lossy(&output.stderr);
|
||||||
|
Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"pkexec",
|
||||||
|
format!(
|
||||||
|
"privileged execution failed (code {code}): {}",
|
||||||
|
err_msg.trim()
|
||||||
|
),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Authenticate, claim and run a plan, recording a truthful transaction outcome
|
||||||
|
/// on every exit path (success, action failure, verification failure,
|
||||||
|
/// cancellation, and effect drift). When `approvals` is present the claim is
|
||||||
|
/// anchored in the broker-controlled ledger and always reaches a terminal
|
||||||
|
/// status; a refused or cancelled operation claims nothing.
|
||||||
|
fn execute_prepared(
|
||||||
|
exec: &Exec,
|
||||||
|
root: &Path,
|
||||||
|
plans: &PlanStore,
|
||||||
|
plan: PreparedPlan,
|
||||||
|
assume_yes: bool,
|
||||||
|
approvals: Option<(&ApprovalLedger, u32)>,
|
||||||
|
) -> Result<PlanExecutionOutcome> {
|
||||||
|
// Authentication/refusal happens before any claim, so a refused plan is not
|
||||||
|
// consumed and stays reviewable (until it expires).
|
||||||
|
let confirm = ServiceConfirm { assume_yes };
|
||||||
|
let auth = if plan.requires_root {
|
||||||
|
Some(authorize(&confirm, &plan.summary, "execute")?)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
// Anchor the approval in the broker-controlled ledger before mutation. The
|
||||||
|
// key is the *stable* approval identity (plan id, canonical digest,
|
||||||
|
// authenticated initiating uid, target root); presentation fields are
|
||||||
|
// excluded, so editing the summary and resealing cannot mint a fresh entry
|
||||||
|
// for an already-consumed approval.
|
||||||
|
let approved_key = match approvals {
|
||||||
|
Some((ledger, uid)) => {
|
||||||
|
let identity = ApprovalIdentity::new(
|
||||||
|
plan.id.clone(),
|
||||||
|
plan.digest.clone(),
|
||||||
|
uid,
|
||||||
|
plan.target_root.clone(),
|
||||||
|
plan.expires_unix,
|
||||||
|
plan.actions.len(),
|
||||||
|
);
|
||||||
|
ledger.claim(&identity)?;
|
||||||
|
Some(identity.key)
|
||||||
|
}
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
let result = execute_claimed(exec, root, plans, &plan, auth.as_ref());
|
||||||
|
|
||||||
|
if let (Some((ledger, _)), Some(key)) = (approvals, approved_key.as_ref()) {
|
||||||
|
let (status, note) = match &result {
|
||||||
|
Ok(_) => (ApprovalStatus::Consumed, "ok".to_string()),
|
||||||
|
Err(e) => (ApprovalStatus::Failed, e.to_string()),
|
||||||
|
};
|
||||||
|
// The transition is monotonic. A conflicting terminal (only possible if
|
||||||
|
// recovery had already declared the owner gone) must not be silently
|
||||||
|
// overwritten or reported as success.
|
||||||
|
match ledger.finish(key, status, ¬e) {
|
||||||
|
Ok(Finished::Recorded) => {}
|
||||||
|
Ok(Finished::AlreadyTerminal(existing)) if existing.status == status.as_str() => {}
|
||||||
|
Ok(Finished::AlreadyTerminal(existing)) => {
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"record approval",
|
||||||
|
format!(
|
||||||
|
"the approval already reached terminal status `{}` and was not \
|
||||||
|
overwritten with `{}`",
|
||||||
|
existing.status,
|
||||||
|
status.as_str()
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Err(ledger_err) => {
|
||||||
|
return match result {
|
||||||
|
Ok(_) => Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"record approval",
|
||||||
|
format!(
|
||||||
|
"the operation completed but its approval outcome could not be \
|
||||||
|
recorded: {ledger_err}"
|
||||||
|
),
|
||||||
|
)),
|
||||||
|
Err(e) => Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"record approval",
|
||||||
|
format!("{e}; the approval outcome could not be recorded: {ledger_err}"),
|
||||||
|
)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The authenticated execution body. Freshly resolved effects are compared
|
||||||
|
/// against the reviewed per-step effects; only changes explained by earlier
|
||||||
|
/// approved steps are allowed.
|
||||||
|
fn execute_claimed(
|
||||||
|
exec: &Exec,
|
||||||
|
root: &Path,
|
||||||
|
plans: &PlanStore,
|
||||||
|
plan: &PreparedPlan,
|
||||||
|
auth: Option<&phoebus_executor::auth::DestructiveAuthorization>,
|
||||||
|
) -> Result<PlanExecutionOutcome> {
|
||||||
|
// Atomic claim: at most one caller can proceed with this plan.
|
||||||
|
let _claim = plans.claim(&plan.id)?;
|
||||||
|
|
||||||
|
let record = TransactionRecord {
|
||||||
|
id: 0,
|
||||||
|
created_unix: now_unix(),
|
||||||
|
origin: match plan.kind {
|
||||||
|
PlanKind::LegacyInstall => "sys-legacy".into(),
|
||||||
|
PlanKind::Removal => "sys-removal".into(),
|
||||||
|
_ => "assistant".into(),
|
||||||
|
},
|
||||||
|
summary: plan.summary.clone(),
|
||||||
|
actions: plan.actions.iter().map(|a| a.describe()).collect(),
|
||||||
|
result: "in progress".into(),
|
||||||
|
snapshot: None,
|
||||||
|
digest: Some(plan.digest.clone()),
|
||||||
|
outcomes: Vec::new(),
|
||||||
|
};
|
||||||
|
let tx_id = transaction::begin(exec, root, record)?;
|
||||||
|
|
||||||
|
// Carry the *reviewed* per-step effects forward. Freshly resolved effects
|
||||||
|
// below are evidence to compare against these, never a replacement
|
||||||
|
// approval. `reviewed_steps` uses the same binding validation already
|
||||||
|
// performed at the privileged boundary.
|
||||||
|
let reviewed_steps: Vec<ResolvedPlan> = reviewed_steps(plan)?;
|
||||||
|
|
||||||
|
let mut completed: Vec<(String, String)> = Vec::new();
|
||||||
|
let mut outcomes: Vec<TransactionOutcome> = Vec::new();
|
||||||
|
let mut snapshot: Option<String> = None;
|
||||||
|
let mut introduced: Vec<PackageEffect> = Vec::new();
|
||||||
|
let mut failure: Option<(String, String)> = None;
|
||||||
|
// A distinct, terminal "the approved plan no longer matches live state"
|
||||||
|
// reason: effect resolution failed, or the effects changed materially.
|
||||||
|
let mut drift: Option<String> = None;
|
||||||
|
|
||||||
|
for (idx, action) in plan.actions.iter().enumerate() {
|
||||||
|
let described = action.describe();
|
||||||
|
if failure.is_some() || drift.is_some() {
|
||||||
|
outcomes.push(TransactionOutcome::unattempted(described));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// Only Portage transactions have a comparable `emerge --pretend` plan
|
||||||
|
// at this boundary. Other lanes' effects were validated by
|
||||||
|
// `validate_prepared_plan` (install revalidation / installed-copy
|
||||||
|
// checks); re-resolving them here would see an empty plan and falsely
|
||||||
|
// report drift.
|
||||||
|
let mut current: Option<ResolvedPlan> = None;
|
||||||
|
if actions::resolves_effects(action) {
|
||||||
|
let reviewed = &reviewed_steps[idx];
|
||||||
|
let resolved = match actions::resolve_effects(exec, action, root) {
|
||||||
|
Ok(current) => current,
|
||||||
|
Err(e) => {
|
||||||
|
let detail = format!("effect resolution failed for `{described}`: {e}");
|
||||||
|
outcomes.push(TransactionOutcome::failed(
|
||||||
|
described.clone(),
|
||||||
|
detail.clone(),
|
||||||
|
));
|
||||||
|
drift = Some(format!("stale plan: {detail}"));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if !approval_holds(reviewed, &resolved, &introduced) {
|
||||||
|
let detail = format!(
|
||||||
|
"the reviewed effects for `{described}` changed materially before execution"
|
||||||
|
);
|
||||||
|
outcomes.push(TransactionOutcome::failed(
|
||||||
|
described.clone(),
|
||||||
|
detail.clone(),
|
||||||
|
));
|
||||||
|
drift = Some(format!("stale plan: {detail}"));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
current = Some(resolved);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Execution carries the *reviewed* transaction for actions that must
|
||||||
|
// not re-discover state (Flatpak/Snap updates, cache cleanup).
|
||||||
|
let carried = if actions::resolves_effects(action) {
|
||||||
|
Some(&reviewed_steps[idx])
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
match actions::execute_inner(exec, action, auth, root, carried) {
|
||||||
|
Ok(result) => {
|
||||||
|
if result.snapshot.is_some() {
|
||||||
|
snapshot = result.snapshot;
|
||||||
|
}
|
||||||
|
outcomes.push(TransactionOutcome::completed(described.clone()));
|
||||||
|
completed.push((described, result.output));
|
||||||
|
// Packages this approved action installed may legitimately
|
||||||
|
// appear in a later step's re-resolution.
|
||||||
|
if let Some(current) = current {
|
||||||
|
introduced.extend(current.effects);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
let detail = e.to_string();
|
||||||
|
outcomes.push(TransactionOutcome::failed(
|
||||||
|
described.clone(),
|
||||||
|
detail.clone(),
|
||||||
|
));
|
||||||
|
failure = Some((described, detail));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(reason) = drift {
|
||||||
|
finish_or_report(
|
||||||
|
exec,
|
||||||
|
root,
|
||||||
|
tx_id,
|
||||||
|
reason.clone(),
|
||||||
|
snapshot.clone(),
|
||||||
|
outcomes.clone(),
|
||||||
|
"the stale plan was recorded",
|
||||||
|
)?;
|
||||||
|
return Err(ExecError::operation("service", "execute", reason));
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some((action_str, detail)) = &failure {
|
||||||
|
finish_or_report(
|
||||||
|
exec,
|
||||||
|
root,
|
||||||
|
tx_id,
|
||||||
|
format!("failed: {detail}"),
|
||||||
|
snapshot.clone(),
|
||||||
|
outcomes.clone(),
|
||||||
|
"the action failed",
|
||||||
|
)?;
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"execute",
|
||||||
|
format!("action failed: {action_str}: {detail}"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Post-execution verification. A verification error finishes the
|
||||||
|
// transaction as a failed verification; it never leaves it "in progress".
|
||||||
|
let verification_result = match plan.kind {
|
||||||
|
PlanKind::Install | PlanKind::LegacyInstall => {
|
||||||
|
if let (Some(cand), Some(act)) = (&plan.candidate, plan.actions.first()) {
|
||||||
|
let resolved = install::ResolvedInstall {
|
||||||
|
request: InstallRequest::new(plan.application.as_deref().unwrap_or("")),
|
||||||
|
candidate: cand.clone(),
|
||||||
|
action: act.clone(),
|
||||||
|
effects: plan.effects.clone(),
|
||||||
|
rationale: plan.rationale.clone(),
|
||||||
|
alternatives: plan.alternatives.clone(),
|
||||||
|
source: match plan.kind {
|
||||||
|
PlanKind::LegacyInstall => InstallSource::ExplicitBackend,
|
||||||
|
_ => InstallSource::AiRecommendation,
|
||||||
|
},
|
||||||
|
warnings: plan.warnings.clone(),
|
||||||
|
verification: plan.verification.clone(),
|
||||||
|
};
|
||||||
|
match install::verify_installed(exec, root, &resolved) {
|
||||||
|
Ok(text) => text,
|
||||||
|
Err(e) => {
|
||||||
|
finish_or_report(
|
||||||
|
exec,
|
||||||
|
root,
|
||||||
|
tx_id,
|
||||||
|
format!("verify failed: {e}"),
|
||||||
|
snapshot.clone(),
|
||||||
|
outcomes.clone(),
|
||||||
|
"verification failed",
|
||||||
|
)?;
|
||||||
|
return Err(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
"verified ok".into()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
PlanKind::Removal => {
|
||||||
|
if let Some(app) = &plan.application {
|
||||||
|
let check = chooser::installed_copies(exec, root, app);
|
||||||
|
if let Some(ref_copy) = check.copies.iter().find(|c| c.backend == plan.source) {
|
||||||
|
let err = format!(
|
||||||
|
"removal reported success but `{app}` is still present in {} ({})",
|
||||||
|
ref_copy.backend, ref_copy.id
|
||||||
|
);
|
||||||
|
finish_or_report(
|
||||||
|
exec,
|
||||||
|
root,
|
||||||
|
tx_id,
|
||||||
|
format!("verify failed: {err}"),
|
||||||
|
snapshot.clone(),
|
||||||
|
outcomes.clone(),
|
||||||
|
"verification failed",
|
||||||
|
)?;
|
||||||
|
return Err(ExecError::operation("service", "verify removal", err));
|
||||||
|
}
|
||||||
|
format!("verified: `{app}` removed from {}", plan.source)
|
||||||
|
} else {
|
||||||
|
"removal verified ok".into()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => "ok".into(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let launch = detect_launch(root, plan);
|
||||||
|
|
||||||
|
finish_or_report(
|
||||||
|
exec,
|
||||||
|
root,
|
||||||
|
tx_id,
|
||||||
|
"ok",
|
||||||
|
snapshot.clone(),
|
||||||
|
outcomes.clone(),
|
||||||
|
"the transaction could not be recorded",
|
||||||
|
)?;
|
||||||
|
|
||||||
|
let outputs: Vec<String> = completed.into_iter().map(|(_, out)| out).collect();
|
||||||
|
|
||||||
|
Ok(PlanExecutionOutcome {
|
||||||
|
completed: true,
|
||||||
|
snapshot,
|
||||||
|
result: "ok".into(),
|
||||||
|
verification: verification_result,
|
||||||
|
output: outputs,
|
||||||
|
launch,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Finish a transaction, surfacing a persistence failure instead of hiding it.
|
||||||
|
/// The execution result is preserved either way.
|
||||||
|
fn finish_or_report(
|
||||||
|
exec: &Exec,
|
||||||
|
root: &Path,
|
||||||
|
tx_id: u64,
|
||||||
|
result: impl Into<String>,
|
||||||
|
snapshot: Option<String>,
|
||||||
|
outcomes: Vec<TransactionOutcome>,
|
||||||
|
persistence_note: &str,
|
||||||
|
) -> Result<()> {
|
||||||
|
let result = result.into();
|
||||||
|
match transaction::finish(exec, root, tx_id, result.clone(), snapshot, outcomes) {
|
||||||
|
Ok(()) => Ok(()),
|
||||||
|
Err(e) => Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"record transaction",
|
||||||
|
format!("{persistence_note}: {result} (history error: {e})"),
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Identify a concrete launch command for a freshly installed application.
|
||||||
|
/// Only offered when a desktop entry (or an unambiguous Flatpak/Snap command)
|
||||||
|
/// is actually found; never guessed.
|
||||||
|
fn detect_launch(root: &Path, plan: &PreparedPlan) -> Option<Vec<String>> {
|
||||||
|
let candidate = plan.candidate.as_ref()?;
|
||||||
|
match candidate.backend {
|
||||||
|
Backend::Flatpak => {
|
||||||
|
return Some(vec!["flatpak".into(), "run".into(), candidate.id.clone()])
|
||||||
|
}
|
||||||
|
Backend::Snap => return Some(vec![candidate.id.clone()]),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
let app = plan.application.as_deref().unwrap_or("");
|
||||||
|
let stem = app.rsplit('/').next().unwrap_or(app).to_ascii_lowercase();
|
||||||
|
if stem.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let dir = root.join("usr/share/applications");
|
||||||
|
let entries = std::fs::read_dir(&dir).ok()?;
|
||||||
|
for entry in entries.flatten() {
|
||||||
|
let path = entry.path();
|
||||||
|
if path.extension().and_then(|e| e.to_str()) != Some("desktop") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let file_stem = path
|
||||||
|
.file_stem()
|
||||||
|
.and_then(|s| s.to_str())
|
||||||
|
.unwrap_or("")
|
||||||
|
.to_ascii_lowercase();
|
||||||
|
if file_stem == stem || file_stem.starts_with(&format!("{stem}.")) {
|
||||||
|
return Some(vec!["gtk-launch".into(), file_stem]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
329
installer-rs/crates/phoebus-installer/src/service/mod.rs
Normal file
329
installer-rs/crates/phoebus-installer/src/service/mod.rs
Normal file
|
|
@ -0,0 +1,329 @@
|
||||||
|
//! Shared administration service layer for Phoebus OS.
|
||||||
|
//!
|
||||||
|
//! Provides a single, unified implementation for both the CLI (`sys`) and desktop
|
||||||
|
//! GUI (`phoebus-assistant`) covering:
|
||||||
|
//! - Bounded investigation and connected model planning
|
||||||
|
//! - Candidate discovery, provenance verification, and policy enforcement
|
||||||
|
//! - Plan staging (`PreparedPlan`) and cryptographically bound approval digests
|
||||||
|
//! - TTL enforcement and replay/tamper protection (`PlanStore`)
|
||||||
|
//! - Cross-source application removal preserving user data by default
|
||||||
|
//! - Two-phase transaction logging (`begin` before mutation, `finish` with verification)
|
||||||
|
//! - Unprivileged-to-privileged desktop Polkit elevation (`pkexec`)
|
||||||
|
//!
|
||||||
|
//! Module layout (structural split, no behavior change):
|
||||||
|
//! - [`plan`]: recommendation text, [`PlanStore`], and the planning APIs.
|
||||||
|
//! - [`validation`]: integrity seals, approval digests, and plan validation.
|
||||||
|
//! - [`execution`]: validated, elevated execution with transaction recording.
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
use phoebus_core::action::SystemAction;
|
||||||
|
use phoebus_core::effects::ResolvedPlan;
|
||||||
|
use phoebus_core::selection::{Candidate, Rejected, SandboxLevel};
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
|
pub const DEFAULT_PLAN_TTL_SECONDS: u64 = 900; // 15 minutes
|
||||||
|
|
||||||
|
/// How many plan identifiers may be generated before the process-wide counter
|
||||||
|
/// wraps. Identifiers also include 128 bits of randomness from `/dev/urandom`.
|
||||||
|
static PLAN_COUNTER: AtomicU64 = AtomicU64::new(1);
|
||||||
|
/// A plan id is exactly this token: no separators, no traversal.
|
||||||
|
const PLAN_ID_HEX_LEN: usize = 32;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum PlanKind {
|
||||||
|
Install,
|
||||||
|
LegacyInstall,
|
||||||
|
Removal,
|
||||||
|
General,
|
||||||
|
Undo,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct PreparedPlan {
|
||||||
|
pub id: String,
|
||||||
|
pub created_unix: u64,
|
||||||
|
pub expires_unix: u64,
|
||||||
|
pub kind: PlanKind,
|
||||||
|
pub summary: String,
|
||||||
|
pub recommendation: String,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub application: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub candidate: Option<Candidate>,
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub alternatives: Vec<Rejected>,
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub rationale: Vec<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub warnings: Vec<String>,
|
||||||
|
pub actions: Vec<SystemAction>,
|
||||||
|
pub effects: ResolvedPlan,
|
||||||
|
/// Per-step resolved effects, so a multi-action plan can be revalidated
|
||||||
|
/// action by action instead of comparing one action against the aggregate.
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub step_effects: Vec<ResolvedPlan>,
|
||||||
|
pub digest: String,
|
||||||
|
pub verification: String,
|
||||||
|
pub requires_root: bool,
|
||||||
|
pub source: String,
|
||||||
|
pub executed: bool,
|
||||||
|
/// Canonical root the plan was reviewed against. Elevated execution refuses
|
||||||
|
/// to run against any other root (never silently falls back to `/`).
|
||||||
|
#[serde(default)]
|
||||||
|
pub target_root: String,
|
||||||
|
/// The unprivileged user that reviewed and approved the plan. A privileged
|
||||||
|
/// broker refuses to run a plan prepared for another user.
|
||||||
|
#[serde(default)]
|
||||||
|
pub initiator_uid: u32,
|
||||||
|
/// Self-consistency seal over the reviewed fields (including target root,
|
||||||
|
/// initiator and digest). Rejected if it does not match on reload.
|
||||||
|
#[serde(default)]
|
||||||
|
pub integrity: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A handle to a prepared plan that the broker has atomically claimed for
|
||||||
|
/// execution. Holding it proves the plan was consumed exactly once.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct PlanClaim {
|
||||||
|
marker: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PlanClaim {
|
||||||
|
pub fn marker_path(&self) -> &Path {
|
||||||
|
&self.marker
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for PlanClaim {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
// The claim marker is intentionally left in place: it is the durable
|
||||||
|
// record that the plan was consumed, so a retry cannot repeat it.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct PlanExecutionOutcome {
|
||||||
|
pub completed: bool,
|
||||||
|
pub snapshot: Option<String>,
|
||||||
|
pub result: String,
|
||||||
|
pub verification: String,
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub output: Vec<String>,
|
||||||
|
/// A concrete command that launches the installed application, when a
|
||||||
|
/// desktop entry could be identified. Never guessed.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub launch: Option<Vec<String>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PreparedPlan {
|
||||||
|
pub fn render(&self) -> String {
|
||||||
|
let mut out = String::new();
|
||||||
|
match self.kind {
|
||||||
|
PlanKind::Install | PlanKind::LegacyInstall => {
|
||||||
|
out.push_str(&format!(
|
||||||
|
"Install plan ({}):\n",
|
||||||
|
if self.kind == PlanKind::LegacyInstall {
|
||||||
|
"explicit selection"
|
||||||
|
} else {
|
||||||
|
"AI recommendation"
|
||||||
|
}
|
||||||
|
));
|
||||||
|
if let Some(app) = &self.application {
|
||||||
|
out.push_str(&format!(" application: {app}\n"));
|
||||||
|
}
|
||||||
|
if let Some(c) = &self.candidate {
|
||||||
|
out.push_str(&format!(" backend: {}\n", c.backend.as_str()));
|
||||||
|
out.push_str(&format!(" candidate: {}\n", c.id));
|
||||||
|
out.push_str(&format!(
|
||||||
|
" version: {}\n",
|
||||||
|
c.version.as_deref().unwrap_or("(resolved at install time)")
|
||||||
|
));
|
||||||
|
out.push_str(&format!(" source: {}\n", self.source));
|
||||||
|
out.push_str(&format!(
|
||||||
|
" integrity: {}\n",
|
||||||
|
if c.verified {
|
||||||
|
"verified (signature/hash)"
|
||||||
|
} else {
|
||||||
|
"UNVERIFIED — provenance not cryptographic"
|
||||||
|
}
|
||||||
|
));
|
||||||
|
out.push_str(&format!(
|
||||||
|
" sandbox: {} wayland: {} desktop: {}\n",
|
||||||
|
match c.sandbox {
|
||||||
|
SandboxLevel::None => "none",
|
||||||
|
SandboxLevel::Partial => "partial",
|
||||||
|
SandboxLevel::Strong => "strong",
|
||||||
|
},
|
||||||
|
match c.wayland {
|
||||||
|
phoebus_core::selection::Capability::No => "no",
|
||||||
|
phoebus_core::selection::Capability::Partial => "partial",
|
||||||
|
phoebus_core::selection::Capability::Yes => "yes",
|
||||||
|
},
|
||||||
|
match c.desktop_integration {
|
||||||
|
phoebus_core::selection::Capability::No => "no",
|
||||||
|
phoebus_core::selection::Capability::Partial => "partial",
|
||||||
|
phoebus_core::selection::Capability::Yes => "yes",
|
||||||
|
}
|
||||||
|
));
|
||||||
|
if let Some(mib) = c.download_mib {
|
||||||
|
out.push_str(&format!(" download: ~{mib} MiB\n"));
|
||||||
|
}
|
||||||
|
if let Some(mib) = c.install_mib {
|
||||||
|
out.push_str(&format!(" on disk: ~{mib} MiB\n"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.push_str("Why:\n");
|
||||||
|
out.push_str(&format!(" - {}\n", self.recommendation));
|
||||||
|
for r in &self.rationale {
|
||||||
|
out.push_str(&format!(" - {r}\n"));
|
||||||
|
}
|
||||||
|
if !self.alternatives.is_empty() {
|
||||||
|
out.push_str("Alternatives considered:\n");
|
||||||
|
for alt in &self.alternatives {
|
||||||
|
out.push_str(&format!(
|
||||||
|
" - {} ({}): {}\n",
|
||||||
|
alt.id,
|
||||||
|
alt.backend.as_str(),
|
||||||
|
alt.reason.explain()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for w in &self.warnings {
|
||||||
|
out.push_str(&format!(" ! {w}\n"));
|
||||||
|
}
|
||||||
|
if self.effects.established && !self.effects.effects.is_empty() {
|
||||||
|
out.push_str(&self.effects.render());
|
||||||
|
}
|
||||||
|
out.push_str(&format!("Verification: {}\n", self.verification));
|
||||||
|
out.push_str(&format!("Approval digest: {}\n", self.digest));
|
||||||
|
}
|
||||||
|
PlanKind::Removal => {
|
||||||
|
out.push_str("Removal plan:\n");
|
||||||
|
if let Some(app) = &self.application {
|
||||||
|
out.push_str(&format!(" application: {app}\n"));
|
||||||
|
}
|
||||||
|
out.push_str(&format!(" source: {}\n", self.source));
|
||||||
|
out.push_str("Why:\n");
|
||||||
|
out.push_str(&format!(" - {}\n", self.recommendation));
|
||||||
|
for r in &self.rationale {
|
||||||
|
out.push_str(&format!(" - {r}\n"));
|
||||||
|
}
|
||||||
|
if self.effects.established && !self.effects.effects.is_empty() {
|
||||||
|
out.push_str(&self.effects.render());
|
||||||
|
}
|
||||||
|
out.push_str(&format!("Verification: {}\n", self.verification));
|
||||||
|
out.push_str(&format!("Approval digest: {}\n", self.digest));
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
out.push_str(&format!("Assistant Plan:\n {}\n", self.summary));
|
||||||
|
for a in &self.actions {
|
||||||
|
out.push_str(&format!(" - {}\n", a.describe()));
|
||||||
|
}
|
||||||
|
if self.effects.established && !self.effects.effects.is_empty() {
|
||||||
|
out.push_str(&self.effects.render());
|
||||||
|
}
|
||||||
|
out.push_str(&format!("Verification: {}\n", self.verification));
|
||||||
|
out.push_str(&format!("Approval digest: {}\n", self.digest));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn now_unix() -> u64 {
|
||||||
|
SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.map(|d| d.as_secs())
|
||||||
|
.unwrap_or(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn effective_uid() -> u32 {
|
||||||
|
if std::env::var("PHOEBUS_ALLOW_UNPRIVILEGED_EXEC").as_deref() == Ok("1") {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
std::process::Command::new("id")
|
||||||
|
.arg("-u")
|
||||||
|
.output()
|
||||||
|
.ok()
|
||||||
|
.and_then(|o| String::from_utf8_lossy(&o.stdout).trim().parse().ok())
|
||||||
|
.unwrap_or(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Canonicalise a target root so two spellings of the same path compare equal.
|
||||||
|
/// When the path cannot be canonicalised (e.g. a not-yet-created target), fall
|
||||||
|
/// back to the lexical path rather than silently selecting `/`.
|
||||||
|
pub fn canonical_root(root: &Path) -> String {
|
||||||
|
match std::fs::canonicalize(root) {
|
||||||
|
Ok(p) => p.to_string_lossy().to_string(),
|
||||||
|
Err(_) => {
|
||||||
|
let p = if root.as_os_str().is_empty() {
|
||||||
|
Path::new("/")
|
||||||
|
} else {
|
||||||
|
root
|
||||||
|
};
|
||||||
|
p.to_string_lossy().to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 128 bits of unpredictable data for a plan identifier/marker name.
|
||||||
|
fn random_token() -> String {
|
||||||
|
let mut bytes = [0u8; 16];
|
||||||
|
let filled = std::fs::File::open("/dev/urandom")
|
||||||
|
.and_then(|mut f| {
|
||||||
|
use std::io::Read;
|
||||||
|
f.read_exact(&mut bytes)
|
||||||
|
})
|
||||||
|
.is_ok();
|
||||||
|
if !filled {
|
||||||
|
// Fallback that is still unique within a boot: time + pid + counter.
|
||||||
|
let nanos = SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.map(|d| d.as_nanos())
|
||||||
|
.unwrap_or(0);
|
||||||
|
let mut hasher = Sha256::new();
|
||||||
|
hasher.update(nanos.to_le_bytes());
|
||||||
|
hasher.update(std::process::id().to_le_bytes());
|
||||||
|
hasher.update(PLAN_COUNTER.fetch_add(1, Ordering::SeqCst).to_le_bytes());
|
||||||
|
let digest = format!("{:x}", hasher.finalize());
|
||||||
|
return digest[..PLAN_ID_HEX_LEN].to_string();
|
||||||
|
}
|
||||||
|
bytes.iter().map(|b| format!("{b:02x}")).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A fresh, unpredictable plan identifier: `plan-<kind>-<32 hex>`.
|
||||||
|
pub(crate) fn fresh_plan_id(prefix: &str) -> String {
|
||||||
|
let counter = PLAN_COUNTER.fetch_add(1, Ordering::SeqCst);
|
||||||
|
let mut hasher = Sha256::new();
|
||||||
|
hasher.update(random_token().as_bytes());
|
||||||
|
hasher.update(counter.to_le_bytes());
|
||||||
|
let digest = format!("{:x}", hasher.finalize());
|
||||||
|
format!("plan-{prefix}-{}", &digest[..PLAN_ID_HEX_LEN])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_safe_plan_id(plan_id: &str) -> bool {
|
||||||
|
!plan_id.is_empty()
|
||||||
|
&& plan_id.len() <= 128
|
||||||
|
&& plan_id
|
||||||
|
.bytes()
|
||||||
|
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
|
||||||
|
}
|
||||||
|
|
||||||
|
pub mod execution;
|
||||||
|
pub mod plan;
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests;
|
||||||
|
pub mod validation;
|
||||||
|
|
||||||
|
pub use execution::{execute_plan, execute_plan_privileged};
|
||||||
|
pub use plan::{
|
||||||
|
build_removal_plan, format_recommendation, plan_general, plan_install, plan_legacy_install,
|
||||||
|
plan_removal, plan_removal_with_ai, select_removal_copy, PlanStore,
|
||||||
|
};
|
||||||
|
pub use validation::{compute_plan_digest, seal_plan, validate_prepared_plan};
|
||||||
872
installer-rs/crates/phoebus-installer/src/service/plan.rs
Normal file
872
installer-rs/crates/phoebus-installer/src/service/plan.rs
Normal file
|
|
@ -0,0 +1,872 @@
|
||||||
|
//! Plan staging and planning APIs: recommendation text, [`PlanStore`], and the
|
||||||
|
//! `plan_*` builders shared by the CLI and the desktop assistant.
|
||||||
|
|
||||||
|
use std::io::Write;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use phoebus_ai::assistant::{complete_plan, run_assistant, AssistantPlan};
|
||||||
|
use phoebus_ai::install::Evidence;
|
||||||
|
use phoebus_ai::provider::SystemFacts;
|
||||||
|
use phoebus_core::action::SystemAction;
|
||||||
|
use phoebus_core::effects::ResolvedPlan;
|
||||||
|
use phoebus_core::selection::{Backend, Candidate, SandboxLevel};
|
||||||
|
use phoebus_executor::actions;
|
||||||
|
use phoebus_executor::chooser;
|
||||||
|
use phoebus_executor::error::{ExecError, Result};
|
||||||
|
use phoebus_executor::exec::Exec;
|
||||||
|
use phoebus_executor::install::{self, AiInstall, InstallRequest};
|
||||||
|
|
||||||
|
use super::validation::{compute_plan_digest, seal_plan};
|
||||||
|
use super::{
|
||||||
|
canonical_root, effective_uid, fresh_plan_id, is_safe_plan_id, now_unix, random_token,
|
||||||
|
PlanClaim, PlanKind, PreparedPlan, DEFAULT_PLAN_TTL_SECONDS,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Produce an honest, evidence-based human recommendation for an application candidate.
|
||||||
|
pub fn format_recommendation(candidate: &Candidate, application: &str) -> String {
|
||||||
|
let source_name = match candidate.backend {
|
||||||
|
Backend::PortageBinary => "Gentoo binhost",
|
||||||
|
Backend::PortageSource => "Gentoo Portage",
|
||||||
|
Backend::PortageVendor => "Portage vendor binary",
|
||||||
|
Backend::Flatpak => "Flathub",
|
||||||
|
Backend::Snap => "Snap Store",
|
||||||
|
Backend::Nix => "Nixpkgs",
|
||||||
|
Backend::AppImage => "managed AppImage",
|
||||||
|
Backend::CustomEbuild => "Phoebus custom ebuild",
|
||||||
|
};
|
||||||
|
|
||||||
|
let sandbox_desc = match candidate.sandbox {
|
||||||
|
SandboxLevel::Strong => "strong application isolation",
|
||||||
|
SandboxLevel::Partial => "partial confinement",
|
||||||
|
SandboxLevel::None => "direct host integration (unconfined)",
|
||||||
|
};
|
||||||
|
|
||||||
|
let build_desc = if let Some(secs) = candidate.build_seconds {
|
||||||
|
if secs < 60 {
|
||||||
|
format!("fast install (~{secs}s)")
|
||||||
|
} else {
|
||||||
|
let mins = secs.div_ceil(60);
|
||||||
|
format!("compiles native binaries (~{mins} min build)")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
match candidate.backend {
|
||||||
|
Backend::PortageBinary | Backend::Flatpak | Backend::Snap | Backend::AppImage => {
|
||||||
|
"pre-built binary package".to_string()
|
||||||
|
}
|
||||||
|
Backend::PortageSource => "source compilation (build time unmeasured)".to_string(),
|
||||||
|
_ => "pre-built binary".to_string(),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
format!(
|
||||||
|
"Install {application} from {source_name}. Recommended for {sandbox_desc} and {build_desc}."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// PlanStore
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// Protected, per-user plan storage.
|
||||||
|
///
|
||||||
|
/// A plan is written with a 0600 mode inside a 0700 directory owned by the
|
||||||
|
/// reviewing user (or the broker for root). Reloading rejects a symlink, a
|
||||||
|
/// file owned by someone other than the initiator/root, or a group/world
|
||||||
|
/// writable file. Consumption uses an `O_EXCL` marker so two concurrent
|
||||||
|
/// executions cannot both run the same plan.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct PlanStore {
|
||||||
|
dir: PathBuf,
|
||||||
|
/// The uid a plan is expected to belong to. The privileged broker sets this
|
||||||
|
/// to the initiating user so it can read that user's plan while still
|
||||||
|
/// rejecting a file owned by anyone else.
|
||||||
|
expected_uid: Option<u32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PlanStore {
|
||||||
|
/// Storage for a specific uid. Used by the privileged broker, which
|
||||||
|
/// recomputes the directory from the uid the caller passed rather than
|
||||||
|
/// trusting an arbitrary path.
|
||||||
|
pub fn for_uid(uid: u32) -> Self {
|
||||||
|
if let Ok(dir) = std::env::var("PHOEBUS_PLANS_DIR") {
|
||||||
|
return Self {
|
||||||
|
dir: PathBuf::from(dir),
|
||||||
|
expected_uid: Some(uid),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
let candidates: Vec<PathBuf> = if uid == 0 {
|
||||||
|
vec![PathBuf::from("/run/phoebus/plans")]
|
||||||
|
} else {
|
||||||
|
// Prefer the canonical per-user runtime path so the privileged
|
||||||
|
// broker (which derives the same path from the uid) finds it.
|
||||||
|
let mut v = vec![PathBuf::from(format!("/run/user/{uid}/phoebus/plans"))];
|
||||||
|
if let Ok(xdg) = std::env::var("XDG_RUNTIME_DIR") {
|
||||||
|
v.push(PathBuf::from(xdg).join("phoebus/plans"));
|
||||||
|
}
|
||||||
|
v
|
||||||
|
};
|
||||||
|
for dir in candidates {
|
||||||
|
if std::fs::create_dir_all(&dir).is_ok() {
|
||||||
|
return Self {
|
||||||
|
dir,
|
||||||
|
expected_uid: Some(uid),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let temp = std::env::temp_dir().join(format!("phoebus-plans-{uid}"));
|
||||||
|
let _ = std::fs::create_dir_all(&temp);
|
||||||
|
Self {
|
||||||
|
dir: temp,
|
||||||
|
expected_uid: Some(uid),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn for_current_user() -> Self {
|
||||||
|
Self::for_uid(effective_uid())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Explicit directory, for tests and callers that manage their own store.
|
||||||
|
pub fn with_dir(dir: impl Into<PathBuf>) -> Self {
|
||||||
|
Self {
|
||||||
|
dir: dir.into(),
|
||||||
|
expected_uid: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn dir(&self) -> &Path {
|
||||||
|
&self.dir
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ensure_dir(&self) -> Result<()> {
|
||||||
|
std::fs::create_dir_all(&self.dir).map_err(|e| ExecError::io(self.dir.clone(), e))?;
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
let _ = std::fs::set_permissions(&self.dir, std::fs::Permissions::from_mode(0o700));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn path(&self, plan_id: &str, suffix: &str) -> Result<PathBuf> {
|
||||||
|
if !is_safe_plan_id(plan_id) {
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"plan path",
|
||||||
|
format!("unsafe plan identifier `{plan_id}`"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(self.dir.join(format!("{plan_id}{suffix}")))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write a plan atomically (temp file -> fsync -> rename) with mode 0600.
|
||||||
|
pub fn save(&self, plan: &mut PreparedPlan) -> Result<PathBuf> {
|
||||||
|
seal_plan(plan);
|
||||||
|
let path = self.path(&plan.id, ".json")?;
|
||||||
|
self.ensure_dir()?;
|
||||||
|
let text = serde_json::to_string_pretty(plan)
|
||||||
|
.map_err(|e| ExecError::operation("service", "serialize plan", e.to_string()))?;
|
||||||
|
|
||||||
|
let tmp = self.dir.join(format!(".{}.tmp", random_token()));
|
||||||
|
{
|
||||||
|
let mut opts = std::fs::OpenOptions::new();
|
||||||
|
opts.write(true).create_new(true);
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
use std::os::unix::fs::OpenOptionsExt;
|
||||||
|
opts.mode(0o600);
|
||||||
|
}
|
||||||
|
let mut file = opts.open(&tmp).map_err(|e| ExecError::io(tmp.clone(), e))?;
|
||||||
|
file.write_all(text.as_bytes())
|
||||||
|
.and_then(|_| file.flush())
|
||||||
|
.and_then(|_| file.sync_all())
|
||||||
|
.map_err(|e| ExecError::io(tmp.clone(), e))?;
|
||||||
|
}
|
||||||
|
std::fs::rename(&tmp, &path).map_err(|e| {
|
||||||
|
let _ = std::fs::remove_file(&tmp);
|
||||||
|
ExecError::io(path.clone(), e)
|
||||||
|
})?;
|
||||||
|
if let Ok(dir) = std::fs::File::open(&self.dir) {
|
||||||
|
let _ = dir.sync_all();
|
||||||
|
}
|
||||||
|
Ok(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Load a plan, rejecting malformed identifiers, symlinks and unsafe
|
||||||
|
/// ownership/permissions. The caller still has to validate the contents.
|
||||||
|
pub fn load(&self, plan_id: &str) -> Result<PreparedPlan> {
|
||||||
|
let path = self.path(plan_id, ".json")?;
|
||||||
|
let meta = std::fs::symlink_metadata(&path).map_err(|_| {
|
||||||
|
ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"load plan",
|
||||||
|
format!("plan `{plan_id}` not found, consumed or expired"),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
if meta.file_type().is_symlink() {
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"load plan",
|
||||||
|
"plan path is a symlink; refusing to follow it",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if !meta.is_file() {
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"load plan",
|
||||||
|
"plan path is not a regular file",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
use std::os::unix::fs::{MetadataExt, PermissionsExt};
|
||||||
|
if meta.permissions().mode() & 0o022 != 0 {
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"load plan",
|
||||||
|
"plan file is group/world writable; refusing to trust it",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let owner = meta.uid();
|
||||||
|
let expected = self.expected_uid.unwrap_or_else(effective_uid);
|
||||||
|
// The broker runs as root but is reading the initiating user's plan,
|
||||||
|
// so the expected owner is the initiator, not root. A plan owned by
|
||||||
|
// a third party is rejected.
|
||||||
|
if owner != expected && owner != 0 {
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"load plan",
|
||||||
|
format!("plan file is owned by uid {owner}, not the expected uid {expected}"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let text = std::fs::read_to_string(&path).map_err(|e| ExecError::io(path.clone(), e))?;
|
||||||
|
let plan: PreparedPlan = serde_json::from_str(&text)
|
||||||
|
.map_err(|e| ExecError::operation("service", "deserialize plan", e.to_string()))?;
|
||||||
|
if plan.id != plan_id {
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"load plan",
|
||||||
|
"plan identifier does not match its storage name",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(plan)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Atomically claim a plan for execution. Returns a guard that keeps the
|
||||||
|
/// marker on disk; a second claim (or a retry after a crash) fails.
|
||||||
|
pub fn claim(&self, plan_id: &str) -> Result<PlanClaim> {
|
||||||
|
let marker = self.path(plan_id, ".claim")?;
|
||||||
|
self.ensure_dir()?;
|
||||||
|
let mut opts = std::fs::OpenOptions::new();
|
||||||
|
opts.write(true).create_new(true);
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
use std::os::unix::fs::OpenOptionsExt;
|
||||||
|
opts.mode(0o600);
|
||||||
|
}
|
||||||
|
opts.open(&marker).map_err(|e| {
|
||||||
|
ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"claim plan",
|
||||||
|
format!("plan `{plan_id}` is already consumed or being executed ({e})"),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
Ok(PlanClaim { marker })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// True when a plan has already been claimed (consumed) for execution.
|
||||||
|
pub fn is_claimed(&self, plan_id: &str) -> bool {
|
||||||
|
match self.path(plan_id, ".claim") {
|
||||||
|
Ok(p) => p.exists(),
|
||||||
|
Err(_) => true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// Planning APIs
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// Plan an installation using AI investigation and policy checks.
|
||||||
|
pub fn plan_install(
|
||||||
|
plans: &PlanStore,
|
||||||
|
exec: &Exec,
|
||||||
|
root: &Path,
|
||||||
|
request: &InstallRequest,
|
||||||
|
session: &dyn phoebus_ai::install::InstallSession,
|
||||||
|
ai: Option<&AiInstall>,
|
||||||
|
facts: &SystemFacts,
|
||||||
|
) -> Result<PreparedPlan> {
|
||||||
|
let ai = match ai {
|
||||||
|
Some(a) => a,
|
||||||
|
None => {
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"plan_install",
|
||||||
|
"No AI provider is configured. Specify a model or select deterministic legacy administration (--legacy --<source>).",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let resolved = install::resolve_with_ai(exec, root, request, session, ai, facts)?;
|
||||||
|
build_install_plan(plans, root, resolved, PlanKind::Install)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Plan an installation deterministically without contacting a model.
|
||||||
|
pub fn plan_legacy_install(
|
||||||
|
plans: &PlanStore,
|
||||||
|
exec: &Exec,
|
||||||
|
root: &Path,
|
||||||
|
request: &InstallRequest,
|
||||||
|
) -> Result<PreparedPlan> {
|
||||||
|
if request.backend.is_none() {
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"plan_legacy_install",
|
||||||
|
"Legacy install requires an explicit package source flag (--flatpak, --portage, --nix, --snap, --appimage, --ebuild)",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let resolved = install::resolve_explicit(exec, root, request)?;
|
||||||
|
build_install_plan(plans, root, resolved, PlanKind::LegacyInstall)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn build_install_plan(
|
||||||
|
plans: &PlanStore,
|
||||||
|
root: &Path,
|
||||||
|
resolved: install::ResolvedInstall,
|
||||||
|
kind: PlanKind,
|
||||||
|
) -> Result<PreparedPlan> {
|
||||||
|
let now = now_unix();
|
||||||
|
let plan_id = fresh_plan_id("inst");
|
||||||
|
|
||||||
|
let rec = format_recommendation(&resolved.candidate, &resolved.request.application);
|
||||||
|
let source_display = match resolved.candidate.backend {
|
||||||
|
Backend::PortageBinary => "Gentoo binhost",
|
||||||
|
Backend::PortageSource => "Gentoo Portage",
|
||||||
|
Backend::PortageVendor => "Portage vendor",
|
||||||
|
Backend::Flatpak => "Flathub",
|
||||||
|
Backend::Snap => "Snap Store",
|
||||||
|
Backend::Nix => "Nixpkgs",
|
||||||
|
Backend::AppImage => "managed AppImage",
|
||||||
|
Backend::CustomEbuild => "Phoebus custom ebuild",
|
||||||
|
}
|
||||||
|
.to_string();
|
||||||
|
|
||||||
|
let digest = resolved.approval_digest();
|
||||||
|
let actions = vec![resolved.action.clone()];
|
||||||
|
let requires_root = resolved.action.is_mutating();
|
||||||
|
// Normalize the stored effect digest so the per-step binding check sees a
|
||||||
|
// digest that matches the contents.
|
||||||
|
let mut effects = resolved.effects.clone();
|
||||||
|
effects.recompute_digest();
|
||||||
|
let step_effects = vec![effects.clone()];
|
||||||
|
|
||||||
|
let mut plan = PreparedPlan {
|
||||||
|
id: plan_id,
|
||||||
|
created_unix: now,
|
||||||
|
expires_unix: now + DEFAULT_PLAN_TTL_SECONDS,
|
||||||
|
kind,
|
||||||
|
summary: format!(
|
||||||
|
"install {} via {}",
|
||||||
|
resolved.request.application,
|
||||||
|
resolved.candidate.backend.as_str()
|
||||||
|
),
|
||||||
|
recommendation: rec,
|
||||||
|
application: Some(resolved.request.application.clone()),
|
||||||
|
candidate: Some(resolved.candidate.clone()),
|
||||||
|
alternatives: resolved.alternatives.clone(),
|
||||||
|
rationale: resolved.rationale.clone(),
|
||||||
|
warnings: resolved.warnings.clone(),
|
||||||
|
actions,
|
||||||
|
effects,
|
||||||
|
step_effects,
|
||||||
|
digest,
|
||||||
|
verification: resolved.verification.clone(),
|
||||||
|
requires_root,
|
||||||
|
source: source_display,
|
||||||
|
executed: false,
|
||||||
|
target_root: canonical_root(root),
|
||||||
|
initiator_uid: effective_uid(),
|
||||||
|
integrity: String::new(),
|
||||||
|
};
|
||||||
|
|
||||||
|
plans.save(&mut plan)?;
|
||||||
|
Ok(plan)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Deterministically choose which installed copy a removal targets. Shared by
|
||||||
|
/// the legacy and AI-first paths so ownership discovery and the ambiguity
|
||||||
|
/// policy cannot diverge. Ambiguity always requires an explicit lane flag.
|
||||||
|
pub fn select_removal_copy(
|
||||||
|
exec: &Exec,
|
||||||
|
root: &Path,
|
||||||
|
application: &str,
|
||||||
|
backend_filter: Option<Backend>,
|
||||||
|
) -> Result<chooser::InstalledCopy> {
|
||||||
|
let inspection = chooser::installed_copies(exec, root, application);
|
||||||
|
if inspection.copies.is_empty() {
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"plan_removal",
|
||||||
|
format!("`{application}` is not installed on this system"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(b) = backend_filter {
|
||||||
|
return inspection
|
||||||
|
.copies
|
||||||
|
.into_iter()
|
||||||
|
.find(|c| c.backend == b.as_str())
|
||||||
|
.ok_or_else(|| {
|
||||||
|
ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"plan_removal",
|
||||||
|
format!(
|
||||||
|
"`{application}` is not installed via {} (found in other lanes)",
|
||||||
|
b.as_str()
|
||||||
|
),
|
||||||
|
)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if inspection.copies.len() > 1 {
|
||||||
|
let details = inspection
|
||||||
|
.copies
|
||||||
|
.iter()
|
||||||
|
.map(|c| format!("{} ({})", c.id, c.backend))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(", ");
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"plan_removal",
|
||||||
|
format!(
|
||||||
|
"`{application}` is installed in multiple lanes: {details}. Specify which one to remove explicitly (e.g. sys remove {application} --flatpak or --portage)."
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(inspection.copies.into_iter().next().unwrap())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Plan an application removal across supported sources preserving user data by
|
||||||
|
/// default, without contacting a model (legacy mode only).
|
||||||
|
pub fn plan_removal(
|
||||||
|
plans: &PlanStore,
|
||||||
|
exec: &Exec,
|
||||||
|
root: &Path,
|
||||||
|
application: &str,
|
||||||
|
backend_filter: Option<Backend>,
|
||||||
|
) -> Result<PreparedPlan> {
|
||||||
|
let target_copy = select_removal_copy(exec, root, application, backend_filter)?;
|
||||||
|
build_removal_plan(
|
||||||
|
plans,
|
||||||
|
exec,
|
||||||
|
root,
|
||||||
|
application,
|
||||||
|
&target_copy,
|
||||||
|
Vec::new(),
|
||||||
|
Vec::new(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Plan an application removal through the connected model (the default). The
|
||||||
|
/// deterministic discovery and ambiguity policy run first; the model must then
|
||||||
|
/// confirm exactly the discovered target. A model failure, or a proposal that
|
||||||
|
/// does not match the deterministic target, stops the workflow.
|
||||||
|
pub fn plan_removal_with_ai(
|
||||||
|
plans: &PlanStore,
|
||||||
|
exec: &Exec,
|
||||||
|
root: &Path,
|
||||||
|
application: &str,
|
||||||
|
backend_filter: Option<Backend>,
|
||||||
|
ai: &AiInstall,
|
||||||
|
facts: &SystemFacts,
|
||||||
|
) -> Result<PreparedPlan> {
|
||||||
|
let target_copy = select_removal_copy(exec, root, application, backend_filter)?;
|
||||||
|
let discovered = chooser::installed_copies(exec, root, application);
|
||||||
|
let list = discovered
|
||||||
|
.copies
|
||||||
|
.iter()
|
||||||
|
.map(|c| format!("{} ({})", c.id, c.backend))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(", ");
|
||||||
|
|
||||||
|
let instruction = format!(
|
||||||
|
"The user asked to remove `{application}`. Read-only discovery found these installed \
|
||||||
|
copies: [{list}]. The policy-selected target is `{}` in the {} lane. Confirm a removal \
|
||||||
|
plan for exactly that copy by proposing the matching remove action; if the request is \
|
||||||
|
ambiguous, propose no action and explain what clarification is needed.",
|
||||||
|
target_copy.id, target_copy.backend
|
||||||
|
);
|
||||||
|
let assistant_plan: AssistantPlan = complete_plan(
|
||||||
|
ai.provider,
|
||||||
|
&ai.endpoint,
|
||||||
|
&ai.model,
|
||||||
|
facts,
|
||||||
|
&instruction,
|
||||||
|
ai.transport,
|
||||||
|
)
|
||||||
|
.map_err(|e| ExecError::operation("service", "plan_removal_with_ai", e.to_string()))?;
|
||||||
|
|
||||||
|
if assistant_plan.actions.len() != 1
|
||||||
|
|| !removal_action_matches(&assistant_plan.actions[0], &target_copy)
|
||||||
|
{
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"plan_removal_with_ai",
|
||||||
|
format!(
|
||||||
|
"the model did not confirm the discovered removal target `{}` ({}); no removal \
|
||||||
|
plan was produced",
|
||||||
|
target_copy.id, target_copy.backend
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut rationale: Vec<String> = assistant_plan
|
||||||
|
.rationale
|
||||||
|
.into_iter()
|
||||||
|
.map(|r| format!("AI: {}", r.reason))
|
||||||
|
.collect();
|
||||||
|
if rationale.is_empty() {
|
||||||
|
rationale.push(format!(
|
||||||
|
"AI confirmed removal of the discovered {} copy",
|
||||||
|
target_copy.backend
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
build_removal_plan(
|
||||||
|
plans,
|
||||||
|
exec,
|
||||||
|
root,
|
||||||
|
application,
|
||||||
|
&target_copy,
|
||||||
|
rationale,
|
||||||
|
Vec::new(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a proposed action is the correct removal of the discovered copy.
|
||||||
|
fn removal_action_matches(action: &SystemAction, copy: &chooser::InstalledCopy) -> bool {
|
||||||
|
match (action, copy.backend.as_str()) {
|
||||||
|
(SystemAction::FlatpakRemove { app_id }, "flatpak") => app_id == ©.id,
|
||||||
|
(SystemAction::SnapRemove { name }, "snap") => name == ©.id,
|
||||||
|
(SystemAction::AppImageRemove { name, .. }, "appimage") => name == ©.id,
|
||||||
|
(SystemAction::RemovePackage { atom }, _)
|
||||||
|
if copy.backend != "flatpak"
|
||||||
|
&& copy.backend != "snap"
|
||||||
|
&& copy.backend != "appimage" =>
|
||||||
|
{
|
||||||
|
atom == ©.id
|
||||||
|
}
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build a removal plan for a specific, already-discovered installed copy.
|
||||||
|
/// Used by both the deterministic (legacy) path and the AI-first path, so the
|
||||||
|
/// ownership discovery and policy validation are identical.
|
||||||
|
pub fn build_removal_plan(
|
||||||
|
plans: &PlanStore,
|
||||||
|
exec: &Exec,
|
||||||
|
root: &Path,
|
||||||
|
application: &str,
|
||||||
|
target_copy: &chooser::InstalledCopy,
|
||||||
|
rationale: Vec<String>,
|
||||||
|
warnings: Vec<String>,
|
||||||
|
) -> Result<PreparedPlan> {
|
||||||
|
let action = match target_copy.backend.as_str() {
|
||||||
|
"flatpak" => SystemAction::FlatpakRemove {
|
||||||
|
app_id: target_copy.id.clone(),
|
||||||
|
},
|
||||||
|
"snap" => SystemAction::SnapRemove {
|
||||||
|
name: target_copy.id.clone(),
|
||||||
|
},
|
||||||
|
"appimage" => SystemAction::AppImageRemove {
|
||||||
|
name: target_copy.id.clone(),
|
||||||
|
// User data preserved by default
|
||||||
|
purge_data: false,
|
||||||
|
},
|
||||||
|
_ => SystemAction::RemovePackage {
|
||||||
|
atom: target_copy.id.clone(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut effects = actions::resolve_effects(exec, &action, root)?;
|
||||||
|
effects.recompute_digest();
|
||||||
|
let now = now_unix();
|
||||||
|
let plan_id = fresh_plan_id("rem");
|
||||||
|
let actions_vec = vec![action.clone()];
|
||||||
|
let step_effects = vec![effects.clone()];
|
||||||
|
let digest = compute_plan_digest(&actions_vec, None, &effects, &step_effects);
|
||||||
|
|
||||||
|
let mut rationale = rationale;
|
||||||
|
rationale.insert(
|
||||||
|
0,
|
||||||
|
format!(
|
||||||
|
"installed package {} detected in {} lane",
|
||||||
|
target_copy.id, target_copy.backend
|
||||||
|
),
|
||||||
|
);
|
||||||
|
rationale.push("preserves user configuration and data in home directory by default".into());
|
||||||
|
|
||||||
|
let mut plan = PreparedPlan {
|
||||||
|
id: plan_id,
|
||||||
|
created_unix: now,
|
||||||
|
expires_unix: now + DEFAULT_PLAN_TTL_SECONDS,
|
||||||
|
kind: PlanKind::Removal,
|
||||||
|
summary: format!("remove {} ({})", target_copy.id, target_copy.backend),
|
||||||
|
recommendation: format!(
|
||||||
|
"Remove application {} from {}. Application binaries will be uninstalled while user data in the home directory is preserved.",
|
||||||
|
target_copy.id, target_copy.backend
|
||||||
|
),
|
||||||
|
application: Some(application.to_string()),
|
||||||
|
candidate: None,
|
||||||
|
alternatives: Vec::new(),
|
||||||
|
rationale,
|
||||||
|
warnings,
|
||||||
|
actions: actions_vec,
|
||||||
|
effects,
|
||||||
|
step_effects,
|
||||||
|
digest,
|
||||||
|
verification: format!(
|
||||||
|
"verify that `{}` ({}) is completely removed from the system",
|
||||||
|
target_copy.id, target_copy.backend
|
||||||
|
),
|
||||||
|
requires_root: action.is_mutating(),
|
||||||
|
source: target_copy.backend.clone(),
|
||||||
|
executed: false,
|
||||||
|
target_root: canonical_root(root),
|
||||||
|
initiator_uid: effective_uid(),
|
||||||
|
integrity: String::new(),
|
||||||
|
};
|
||||||
|
|
||||||
|
plans.save(&mut plan)?;
|
||||||
|
Ok(plan)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rewrite a lane-selectable catalogue action to an explicit source, and refuse
|
||||||
|
/// an action that targets a different lane. A spanning action (history,
|
||||||
|
/// snapshots, services) is returned unchanged.
|
||||||
|
pub(super) fn constrain_action(
|
||||||
|
action: SystemAction,
|
||||||
|
constraint: Backend,
|
||||||
|
) -> std::result::Result<SystemAction, String> {
|
||||||
|
Ok(match action {
|
||||||
|
SystemAction::SearchPackages { query, .. } => SystemAction::SearchPackages {
|
||||||
|
query,
|
||||||
|
backend: Some(constraint),
|
||||||
|
},
|
||||||
|
SystemAction::ListPackages { filter, .. } => SystemAction::ListPackages {
|
||||||
|
backend: Some(constraint),
|
||||||
|
filter,
|
||||||
|
},
|
||||||
|
SystemAction::PackageInfo { package, .. } => SystemAction::PackageInfo {
|
||||||
|
package,
|
||||||
|
backend: Some(constraint),
|
||||||
|
},
|
||||||
|
SystemAction::CheckUpdates { .. } => SystemAction::CheckUpdates {
|
||||||
|
backend: Some(constraint),
|
||||||
|
},
|
||||||
|
SystemAction::ApplyUpdates { .. } => SystemAction::ApplyUpdates {
|
||||||
|
backend: Some(constraint),
|
||||||
|
},
|
||||||
|
SystemAction::CleanCache { .. } => SystemAction::CleanCache {
|
||||||
|
backend: Some(constraint),
|
||||||
|
},
|
||||||
|
// Optional-backend discovery and selection requests must be *rewritten*
|
||||||
|
// to the constraint, not merely filtered afterwards: otherwise the
|
||||||
|
// resolver would still query every lane before the results are
|
||||||
|
// discarded.
|
||||||
|
SystemAction::DiscoverCandidates {
|
||||||
|
query,
|
||||||
|
kind,
|
||||||
|
gui,
|
||||||
|
requires_sandbox,
|
||||||
|
..
|
||||||
|
} => SystemAction::DiscoverCandidates {
|
||||||
|
query,
|
||||||
|
kind,
|
||||||
|
backend: Some(constraint),
|
||||||
|
gui,
|
||||||
|
requires_sandbox,
|
||||||
|
},
|
||||||
|
SystemAction::ChoosePackage {
|
||||||
|
name,
|
||||||
|
kind,
|
||||||
|
gui,
|
||||||
|
requires_sandbox,
|
||||||
|
..
|
||||||
|
} => SystemAction::ChoosePackage {
|
||||||
|
name,
|
||||||
|
kind,
|
||||||
|
backend: Some(constraint),
|
||||||
|
gui,
|
||||||
|
requires_sandbox,
|
||||||
|
},
|
||||||
|
// `InspectInstallation` has no lane field but probes every lane; under
|
||||||
|
// an explicit constraint it is refused rather than leaking other lanes.
|
||||||
|
SystemAction::InspectInstallation { .. } => {
|
||||||
|
return Err(format!(
|
||||||
|
"inspect_installation spans every package lane, but this request was constrained \
|
||||||
|
to {}; use a lane-specific inventory instead",
|
||||||
|
constraint.as_str()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
other => {
|
||||||
|
if let Some(own) = other.backend() {
|
||||||
|
let matches = own == constraint || (own.is_portage() && constraint.is_portage());
|
||||||
|
if !matches {
|
||||||
|
return Err(format!(
|
||||||
|
"`{}` targets the {} lane, but this request was constrained to {}",
|
||||||
|
other.describe(),
|
||||||
|
own.as_str(),
|
||||||
|
constraint.as_str()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
other
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Plan general system administration tasks via the connected model.
|
||||||
|
///
|
||||||
|
/// The model may run a bounded, read-only investigation (search, inventory,
|
||||||
|
/// information, update checks) before answering. An explicit `constraint`
|
||||||
|
/// forbids any action that targets a different package lane, so a source flag
|
||||||
|
/// constrains the AI workflow rather than bypassing it.
|
||||||
|
pub fn plan_general(
|
||||||
|
plans: &PlanStore,
|
||||||
|
exec: &Exec,
|
||||||
|
root: &Path,
|
||||||
|
query: &str,
|
||||||
|
facts: &SystemFacts,
|
||||||
|
ai: &AiInstall,
|
||||||
|
constraint: Option<Backend>,
|
||||||
|
) -> Result<PreparedPlan> {
|
||||||
|
let instruction = match constraint {
|
||||||
|
Some(backend) => format!(
|
||||||
|
"{query}\n\n[source constraint: only the `{}` lane may be used; do not use \
|
||||||
|
another lane]",
|
||||||
|
backend.as_str()
|
||||||
|
),
|
||||||
|
None => query.to_string(),
|
||||||
|
};
|
||||||
|
let investigate = |requests: &[SystemAction]| -> Vec<Evidence> {
|
||||||
|
requests
|
||||||
|
.iter()
|
||||||
|
.map(|request| {
|
||||||
|
let output = match constraint {
|
||||||
|
Some(backend) => match constrain_action(request.clone(), backend) {
|
||||||
|
Ok(action) => match actions::execute(exec, &action, None, root) {
|
||||||
|
Ok(outcome) => outcome.output,
|
||||||
|
Err(e) => format!("investigation failed: {e}"),
|
||||||
|
},
|
||||||
|
Err(msg) => format!("refused by the source constraint: {msg}"),
|
||||||
|
},
|
||||||
|
None => match actions::execute(exec, request, None, root) {
|
||||||
|
Ok(outcome) => outcome.output,
|
||||||
|
Err(e) => format!("investigation failed: {e}"),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
Evidence {
|
||||||
|
request: request.describe(),
|
||||||
|
output,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
};
|
||||||
|
let assistant_plan: AssistantPlan = run_assistant(
|
||||||
|
ai.provider,
|
||||||
|
&ai.endpoint,
|
||||||
|
&ai.model,
|
||||||
|
facts,
|
||||||
|
&instruction,
|
||||||
|
ai.transport,
|
||||||
|
&investigate,
|
||||||
|
&ai.limits,
|
||||||
|
)
|
||||||
|
.map_err(|e| ExecError::operation("service", "run_assistant", e.to_string()))?;
|
||||||
|
|
||||||
|
// Apply the source constraint to the final actions too: a lane-specific
|
||||||
|
// query is rewritten to the constraint, and an action that targets a
|
||||||
|
// different lane is refused before anything is planned.
|
||||||
|
let actions_list: Vec<SystemAction> = match constraint {
|
||||||
|
Some(backend) => assistant_plan
|
||||||
|
.actions
|
||||||
|
.iter()
|
||||||
|
.cloned()
|
||||||
|
.map(|action| {
|
||||||
|
constrain_action(action, backend)
|
||||||
|
.map_err(|msg| ExecError::operation("service", "source constraint", msg))
|
||||||
|
})
|
||||||
|
.collect::<Result<Vec<_>>>()?,
|
||||||
|
None => assistant_plan.actions.clone(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut combined_effects = ResolvedPlan {
|
||||||
|
established: true,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let mut any_mutating = false;
|
||||||
|
let mut step_effects = Vec::new();
|
||||||
|
|
||||||
|
for act in &actions_list {
|
||||||
|
let mut eff = actions::resolve_effects(exec, act, root).map_err(|e| {
|
||||||
|
ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"resolve_effects",
|
||||||
|
format!("could not resolve effects for `{}`: {e}", act.describe()),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
// Normalize the stored digest so the per-step binding check sees a
|
||||||
|
// digest that matches the contents.
|
||||||
|
eff.recompute_digest();
|
||||||
|
if eff.established {
|
||||||
|
combined_effects.effects.extend(eff.effects.clone());
|
||||||
|
combined_effects.cleanup.extend(eff.cleanup.clone());
|
||||||
|
combined_effects.updates.extend(eff.updates.clone());
|
||||||
|
combined_effects
|
||||||
|
.consequences
|
||||||
|
.extend(eff.consequences.clone());
|
||||||
|
}
|
||||||
|
step_effects.push(eff);
|
||||||
|
any_mutating |= act.is_mutating();
|
||||||
|
}
|
||||||
|
combined_effects.recompute_digest();
|
||||||
|
|
||||||
|
let now = now_unix();
|
||||||
|
let plan_id = fresh_plan_id("gen");
|
||||||
|
let digest = compute_plan_digest(&actions_list, None, &combined_effects, &step_effects);
|
||||||
|
let rationale_strings: Vec<String> = assistant_plan
|
||||||
|
.rationale
|
||||||
|
.into_iter()
|
||||||
|
.map(|r| format!("{}: {}", r.action, r.reason))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let mut plan = PreparedPlan {
|
||||||
|
id: plan_id,
|
||||||
|
created_unix: now,
|
||||||
|
expires_unix: now + DEFAULT_PLAN_TTL_SECONDS,
|
||||||
|
kind: PlanKind::General,
|
||||||
|
summary: assistant_plan.summary.clone(),
|
||||||
|
recommendation: assistant_plan.summary,
|
||||||
|
application: None,
|
||||||
|
candidate: None,
|
||||||
|
alternatives: Vec::new(),
|
||||||
|
rationale: rationale_strings,
|
||||||
|
warnings: Vec::new(),
|
||||||
|
actions: actions_list,
|
||||||
|
effects: combined_effects,
|
||||||
|
step_effects,
|
||||||
|
digest,
|
||||||
|
verification: "verify execution of planned actions".into(),
|
||||||
|
requires_root: any_mutating,
|
||||||
|
source: "AI Assistant".into(),
|
||||||
|
executed: false,
|
||||||
|
target_root: canonical_root(root),
|
||||||
|
initiator_uid: effective_uid(),
|
||||||
|
integrity: String::new(),
|
||||||
|
};
|
||||||
|
|
||||||
|
plans.save(&mut plan)?;
|
||||||
|
Ok(plan)
|
||||||
|
}
|
||||||
2111
installer-rs/crates/phoebus-installer/src/service/tests.rs
Normal file
2111
installer-rs/crates/phoebus-installer/src/service/tests.rs
Normal file
File diff suppressed because it is too large
Load diff
451
installer-rs/crates/phoebus-installer/src/service/validation.rs
Normal file
451
installer-rs/crates/phoebus-installer/src/service/validation.rs
Normal file
|
|
@ -0,0 +1,451 @@
|
||||||
|
//! Integrity seals, approval digests, and plan validation: the authoritative
|
||||||
|
//! privileged validation boundary shared by every execution path.
|
||||||
|
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
use phoebus_core::action::SystemAction;
|
||||||
|
use phoebus_core::effects::ResolvedPlan;
|
||||||
|
use phoebus_core::selection::Candidate;
|
||||||
|
use phoebus_executor::actions;
|
||||||
|
use phoebus_executor::auth::Confirmation;
|
||||||
|
use phoebus_executor::chooser;
|
||||||
|
use phoebus_executor::error::{ExecError, Result};
|
||||||
|
use phoebus_executor::exec::Exec;
|
||||||
|
use phoebus_executor::install::{self, InstallRequest, InstallSource};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
|
use super::{canonical_root, is_safe_plan_id, now_unix, PlanKind, PreparedPlan};
|
||||||
|
|
||||||
|
/// Recompute the self-consistency seal over every reviewed field. The stored
|
||||||
|
/// `integrity` value is deliberately excluded. A reload whose recomputation
|
||||||
|
/// differs was modified after it was approved.
|
||||||
|
pub(super) fn plan_integrity(plan: &PreparedPlan) -> String {
|
||||||
|
let mut hasher = Sha256::new();
|
||||||
|
hasher.update(plan.id.as_bytes());
|
||||||
|
hasher.update(b"\0");
|
||||||
|
hasher.update(format!("{:?}", plan.kind).as_bytes());
|
||||||
|
hasher.update(b"\0");
|
||||||
|
hasher.update(plan.created_unix.to_le_bytes());
|
||||||
|
hasher.update(plan.expires_unix.to_le_bytes());
|
||||||
|
hasher.update(plan.digest.as_bytes());
|
||||||
|
hasher.update(b"\0");
|
||||||
|
hasher.update(plan.effects.digest.as_bytes());
|
||||||
|
hasher.update(b"\0");
|
||||||
|
if let Some(c) = &plan.candidate {
|
||||||
|
hasher.update(c.backend.as_str().as_bytes());
|
||||||
|
hasher.update(b"\0");
|
||||||
|
hasher.update(c.id.as_bytes());
|
||||||
|
hasher.update(b"\0");
|
||||||
|
hasher.update(c.version.as_deref().unwrap_or("").as_bytes());
|
||||||
|
hasher.update(b"\0");
|
||||||
|
}
|
||||||
|
for act in &plan.actions {
|
||||||
|
hasher.update(serde_json::to_string(act).unwrap_or_default().as_bytes());
|
||||||
|
hasher.update(b"\0");
|
||||||
|
}
|
||||||
|
for step in &plan.step_effects {
|
||||||
|
hasher.update(step.digest.as_bytes());
|
||||||
|
hasher.update(b"\0");
|
||||||
|
}
|
||||||
|
hasher.update(plan.target_root.as_bytes());
|
||||||
|
hasher.update(b"\0");
|
||||||
|
hasher.update(plan.source.as_bytes());
|
||||||
|
hasher.update(b"\0");
|
||||||
|
hasher.update(plan.initiator_uid.to_le_bytes());
|
||||||
|
hasher.update(b"\0");
|
||||||
|
hasher.update([plan.requires_root as u8]);
|
||||||
|
hasher.update([plan.executed as u8]);
|
||||||
|
// Everything the human reviewed is sealed, so a modified summary or
|
||||||
|
// verification statement cannot pass as the approved plan.
|
||||||
|
for field in [
|
||||||
|
&plan.summary,
|
||||||
|
&plan.recommendation,
|
||||||
|
plan.application.as_deref().unwrap_or(""),
|
||||||
|
&plan.verification,
|
||||||
|
] {
|
||||||
|
hasher.update(field.as_bytes());
|
||||||
|
hasher.update(b"\0");
|
||||||
|
}
|
||||||
|
for line in plan.rationale.iter().chain(plan.warnings.iter()) {
|
||||||
|
hasher.update(line.as_bytes());
|
||||||
|
hasher.update(b"\0");
|
||||||
|
}
|
||||||
|
for alt in &plan.alternatives {
|
||||||
|
hasher.update(serde_json::to_string(alt).unwrap_or_default().as_bytes());
|
||||||
|
hasher.update(b"\0");
|
||||||
|
}
|
||||||
|
format!("{:x}", hasher.finalize())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compute and store the plan seal. Must be called before persistence.
|
||||||
|
pub fn seal_plan(plan: &mut PreparedPlan) {
|
||||||
|
plan.integrity = plan_integrity(plan);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The canonical digest of a single step's material effects.
|
||||||
|
///
|
||||||
|
/// The digest is *recomputed* from the effect list rather than read from the
|
||||||
|
/// stored `digest` field, so a plan owner cannot change a step's contents while
|
||||||
|
/// leaving its stored digest (and therefore the approval) intact.
|
||||||
|
fn step_effects_digest(step: &ResolvedPlan) -> String {
|
||||||
|
let mut normalized = step.clone();
|
||||||
|
normalized.recompute_digest();
|
||||||
|
normalized.digest
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The per-step reviewed effects that execution will actually trust.
|
||||||
|
///
|
||||||
|
/// New plans always store one step per action. A single-action plan may fall
|
||||||
|
/// back to its aggregate effects for backward compatibility; a multi-action
|
||||||
|
/// plan without per-step effects cannot be bound and is refused.
|
||||||
|
pub(super) fn reviewed_steps(plan: &PreparedPlan) -> Result<Vec<ResolvedPlan>> {
|
||||||
|
if plan.step_effects.len() == plan.actions.len() && !plan.step_effects.is_empty() {
|
||||||
|
Ok(plan.step_effects.clone())
|
||||||
|
} else if plan.actions.len() == 1 {
|
||||||
|
Ok(vec![plan.effects.clone()])
|
||||||
|
} else {
|
||||||
|
Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"validate plan",
|
||||||
|
"plan is missing per-step effects; refusing to execute a multi-action plan whose \
|
||||||
|
reviewed effects are not individually bound",
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Verify that every stored per-step effect digest matches its actual contents
|
||||||
|
/// and that the aggregate effects are exactly the concatenation of the steps.
|
||||||
|
pub(super) fn validate_effect_bindings(plan: &PreparedPlan, steps: &[ResolvedPlan]) -> Result<()> {
|
||||||
|
for (idx, step) in steps.iter().enumerate() {
|
||||||
|
if step.digest != step_effects_digest(step) {
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"validate plan",
|
||||||
|
format!(
|
||||||
|
"the stored effect digest for step {idx} does not match its contents; the \
|
||||||
|
plan was modified after it was reviewed"
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut combined = ResolvedPlan {
|
||||||
|
established: true,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
for step in steps {
|
||||||
|
combined.effects.extend(step.effects.clone());
|
||||||
|
combined.cleanup.extend(step.cleanup.clone());
|
||||||
|
combined.updates.extend(step.updates.clone());
|
||||||
|
combined.consequences.extend(step.consequences.clone());
|
||||||
|
}
|
||||||
|
combined.recompute_digest();
|
||||||
|
let mut aggregate = plan.effects.clone();
|
||||||
|
aggregate.recompute_digest();
|
||||||
|
if combined.digest != aggregate.digest {
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"validate plan",
|
||||||
|
"the aggregate effects are not consistent with the reviewed per-step effects; the \
|
||||||
|
plan was modified after it was reviewed",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compute a cryptographic digest binding the exact actions, candidate, the
|
||||||
|
/// reviewed aggregate effects and every per-step effect that execution trusts.
|
||||||
|
pub fn compute_plan_digest(
|
||||||
|
actions: &[SystemAction],
|
||||||
|
candidate: Option<&Candidate>,
|
||||||
|
effects: &ResolvedPlan,
|
||||||
|
step_effects: &[ResolvedPlan],
|
||||||
|
) -> String {
|
||||||
|
// A single installed candidate binds through the install-specific digest.
|
||||||
|
// `validate_effect_bindings` separately requires that its one step equals
|
||||||
|
// the aggregate, so the step effects are bound transitively.
|
||||||
|
if let (Some(cand), Some(act)) = (candidate, actions.first()) {
|
||||||
|
if actions.len() == 1 {
|
||||||
|
return install::approval_digest_for(cand, act, effects);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut hasher = Sha256::new();
|
||||||
|
if let Some(c) = candidate {
|
||||||
|
hasher.update(c.backend.as_str().as_bytes());
|
||||||
|
hasher.update(b"\0");
|
||||||
|
hasher.update(c.id.as_bytes());
|
||||||
|
hasher.update(b"\0");
|
||||||
|
hasher.update(c.version.as_deref().unwrap_or("").as_bytes());
|
||||||
|
hasher.update(b"\0");
|
||||||
|
}
|
||||||
|
for act in actions {
|
||||||
|
hasher.update(serde_json::to_string(act).unwrap_or_default().as_bytes());
|
||||||
|
hasher.update(b"\0");
|
||||||
|
}
|
||||||
|
// Bind every material per-step effect execution will trust, recomputed from
|
||||||
|
// its contents so a retained approval cannot hide a changed schedule.
|
||||||
|
for step in step_effects {
|
||||||
|
hasher.update(step_effects_digest(step).as_bytes());
|
||||||
|
hasher.update(b"\0");
|
||||||
|
}
|
||||||
|
hasher.update(b"aggregate\0");
|
||||||
|
if effects.established {
|
||||||
|
hasher.update(effects.digest.as_bytes());
|
||||||
|
} else {
|
||||||
|
hasher.update(b"no-established-effects");
|
||||||
|
}
|
||||||
|
format!("{:x}", hasher.finalize())
|
||||||
|
}
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// Privileged validation boundary
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
pub(super) struct ServiceConfirm {
|
||||||
|
pub(super) assume_yes: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Confirmation for ServiceConfirm {
|
||||||
|
fn confirm_erase(&self, _preview: &str) -> Result<bool> {
|
||||||
|
Ok(self.assume_yes)
|
||||||
|
}
|
||||||
|
fn confirm_final(&self, _message: &str) -> Result<bool> {
|
||||||
|
Ok(self.assume_yes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The single authoritative validation boundary. Runs immediately before any
|
||||||
|
/// privileged mutation, in both the unprivileged pre-check and the broker after
|
||||||
|
/// authentication. It binds the approval to the exact actions, effects,
|
||||||
|
/// candidate, target root and initiating user, re-derives the plan seal, and
|
||||||
|
/// revalidates live state. Plan files are untrusted input.
|
||||||
|
pub fn validate_prepared_plan(
|
||||||
|
exec: &Exec,
|
||||||
|
root: &Path,
|
||||||
|
plan: &PreparedPlan,
|
||||||
|
expected_digest: Option<&str>,
|
||||||
|
initiator_uid: u32,
|
||||||
|
) -> Result<()> {
|
||||||
|
if plan.integrity.is_empty() || plan.integrity != plan_integrity(plan) {
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"validate plan",
|
||||||
|
"plan integrity check failed; the plan was modified after it was reviewed",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if !is_safe_plan_id(&plan.id) {
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"validate plan",
|
||||||
|
"plan has an invalid identifier",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if plan.executed {
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"validate plan",
|
||||||
|
"plan has already been executed; replayed plans are rejected",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if now_unix() > plan.expires_unix {
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"validate plan",
|
||||||
|
"plan has expired; review and approve a fresh plan",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if plan.actions.is_empty() {
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"validate plan",
|
||||||
|
"plan proposes no actions",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
// Independently recompute the canonical approval digest from the exact
|
||||||
|
// executable actions, candidate and reviewed material effects. The
|
||||||
|
// `integrity` seal stored beside the plan is a self-consistency check the
|
||||||
|
// owning user can recompute, so it is not authentication: the canonical
|
||||||
|
// digest is. It must match the digest stored in the plan *and* the
|
||||||
|
// independently supplied approval digest. This binds every plan kind
|
||||||
|
// (Install, LegacyInstall, Removal, General, Undo) to the reviewed actions,
|
||||||
|
// so retaining an old digest while swapping an action and resealing is
|
||||||
|
// rejected before any mutation.
|
||||||
|
//
|
||||||
|
// Execution trusts the per-step effects (`step_effects`), so those must be
|
||||||
|
// bound too: each stored effect digest must match its actual contents, the
|
||||||
|
// aggregate must be the concatenation of the steps, and the canonical
|
||||||
|
// digest must cover every step. This closes the "retain the approved digest,
|
||||||
|
// change only `step_effects`, reseal" gap for General and Undo plans.
|
||||||
|
let steps = reviewed_steps(plan)?;
|
||||||
|
validate_effect_bindings(plan, &steps)?;
|
||||||
|
let canonical = compute_plan_digest(
|
||||||
|
&plan.actions,
|
||||||
|
plan.candidate.as_ref(),
|
||||||
|
&plan.effects,
|
||||||
|
&steps,
|
||||||
|
);
|
||||||
|
if plan.digest != canonical {
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"validate plan",
|
||||||
|
"plan digest does not match its reviewed actions and effects; the plan was \
|
||||||
|
substituted or resealed and is refused",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if let Some(digest) = expected_digest {
|
||||||
|
if !digest.is_empty() && canonical != digest {
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"validate plan",
|
||||||
|
"approval digest mismatch; the plan was altered or is not the one reviewed",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if plan.target_root.is_empty() {
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"validate plan",
|
||||||
|
"plan does not record a target root; refusing to guess `/`",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let want_root = canonical_root(root);
|
||||||
|
if plan.target_root != want_root {
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"validate plan",
|
||||||
|
format!(
|
||||||
|
"target root mismatch: the plan was reviewed for {} but execution targets {}",
|
||||||
|
plan.target_root, want_root
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if plan.initiator_uid != initiator_uid {
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"validate plan",
|
||||||
|
format!(
|
||||||
|
"plan belongs to uid {} and cannot be executed by uid {initiator_uid}",
|
||||||
|
plan.initiator_uid
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
revalidate_plan_state(exec, root, plan)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Revalidate a plan's material state against live metadata. A material change
|
||||||
|
/// invalidates the earlier approval.
|
||||||
|
fn revalidate_plan_state(exec: &Exec, root: &Path, plan: &PreparedPlan) -> Result<()> {
|
||||||
|
match plan.kind {
|
||||||
|
PlanKind::Install | PlanKind::LegacyInstall => {
|
||||||
|
let (Some(cand), Some(act)) = (&plan.candidate, plan.actions.first()) else {
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"revalidate",
|
||||||
|
"installation plan is missing its candidate or action",
|
||||||
|
));
|
||||||
|
};
|
||||||
|
let resolved = install::ResolvedInstall {
|
||||||
|
request: InstallRequest::new(plan.application.as_deref().unwrap_or("")),
|
||||||
|
candidate: cand.clone(),
|
||||||
|
action: act.clone(),
|
||||||
|
effects: plan.effects.clone(),
|
||||||
|
rationale: plan.rationale.clone(),
|
||||||
|
alternatives: plan.alternatives.clone(),
|
||||||
|
source: match plan.kind {
|
||||||
|
PlanKind::LegacyInstall => InstallSource::ExplicitBackend,
|
||||||
|
_ => InstallSource::AiRecommendation,
|
||||||
|
},
|
||||||
|
warnings: plan.warnings.clone(),
|
||||||
|
verification: plan.verification.clone(),
|
||||||
|
};
|
||||||
|
let current_digest = install::revalidate(exec, root, &resolved).map_err(|e| {
|
||||||
|
ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"revalidate",
|
||||||
|
format!("the reviewed plan changed before execution ({e}); review again"),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
if current_digest != plan.digest {
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"revalidate",
|
||||||
|
"system state or package metadata changed materially since review; review again",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
PlanKind::Removal => {
|
||||||
|
let Some(app) = &plan.application else {
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"revalidate",
|
||||||
|
"removal plan has no application",
|
||||||
|
));
|
||||||
|
};
|
||||||
|
let check = chooser::installed_copies(exec, root, app);
|
||||||
|
if !check.copies.iter().any(|c| c.backend == plan.source) {
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"revalidate",
|
||||||
|
format!(
|
||||||
|
"`{app}` is no longer installed via {}; the removal plan is stale",
|
||||||
|
plan.source
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if let Some(act) = plan.actions.first() {
|
||||||
|
let eff = actions::resolve_effects(exec, act, root)?;
|
||||||
|
if eff.established && plan.effects.established && eff.digest != plan.effects.digest
|
||||||
|
{
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"revalidate",
|
||||||
|
"the removal effects changed since review; review again",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
PlanKind::General | PlanKind::Undo => {
|
||||||
|
if plan.step_effects.len() == plan.actions.len() && !plan.step_effects.is_empty() {
|
||||||
|
// Compare each step against its own reviewed effects, never one
|
||||||
|
// action against the whole plan.
|
||||||
|
for (act, reviewed) in plan.actions.iter().zip(plan.step_effects.iter()) {
|
||||||
|
let eff = actions::resolve_effects(exec, act, root)?;
|
||||||
|
if reviewed.established && eff.established && reviewed.digest != eff.digest {
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"revalidate",
|
||||||
|
format!(
|
||||||
|
"effects for `{}` changed materially since review; review again",
|
||||||
|
act.describe()
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Older plans carried only the aggregate; recompute the same
|
||||||
|
// aggregate and compare, rather than mixing per-action digests.
|
||||||
|
let mut combined = ResolvedPlan {
|
||||||
|
established: true,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
for act in &plan.actions {
|
||||||
|
let eff = actions::resolve_effects(exec, act, root)?;
|
||||||
|
if eff.established {
|
||||||
|
combined.effects.extend(eff.effects);
|
||||||
|
combined.cleanup.extend(eff.cleanup);
|
||||||
|
combined.updates.extend(eff.updates);
|
||||||
|
combined.consequences.extend(eff.consequences);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
combined.recompute_digest();
|
||||||
|
if plan.effects.established && combined.digest != plan.effects.digest {
|
||||||
|
return Err(ExecError::operation(
|
||||||
|
"service",
|
||||||
|
"revalidate",
|
||||||
|
"system state or package effects changed materially since review; review again",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
Loading…
Add table
Reference in a new issue