Compare commits
No commits in common. "15b69f524db6d13be4e03bfcab7f8b679db8b53a" and "7c5d4c5ca6bf109dffaf50696f7912c474927843" have entirely different histories.
15b69f524d
...
7c5d4c5ca6
20 changed files with 5245 additions and 5532 deletions
|
|
@ -3,42 +3,6 @@
|
|||
All notable changes are recorded here. The authoritative history is `git log`;
|
||||
this file is the curated, human-readable summary.
|
||||
|
||||
## 2026-09-26 — Code quality pass: boxed ExecError, warning-free Clippy, service/gui_bridge splits
|
||||
|
||||
Structural work only; no behavior, wire-format, or serialized-plan change.
|
||||
|
||||
- `ExecError::Command` now carries a boxed `CommandFailure` payload, so
|
||||
`ExecError` shrinks from 128 to 96 bytes and `Result<T, ExecError>` passes
|
||||
Clippy's `result_large_err` gate (all 57 warnings gone). The display text,
|
||||
the redacted stdout/stderr capture, and the stderr tail used for update
|
||||
failures are preserved; the constructor and every match site were updated,
|
||||
with regression tests for the error text, the captured output, and a 96-byte
|
||||
size bound.
|
||||
- The remaining Clippy warnings are fixed without blanket allows: a type alias
|
||||
for the Snap-entry tuple (`actions.rs`), a `CommandRecord` params struct for
|
||||
`Logger::command` (`log.rs`), and `DiskPhase` variant renames
|
||||
(`gui_bridge.rs`). `cargo clippy --workspace --all-targets -- -D warnings`
|
||||
is clean.
|
||||
- `service.rs` (4218 lines) is split into `service/mod.rs` (types, render,
|
||||
shared helpers, explicit re-exports), `plan.rs`, `validation.rs`,
|
||||
`execution.rs`, and `tests.rs`. Every `phoebus_installer::service::*` path,
|
||||
the serialized plan format, approval digests, replay protection, and the
|
||||
privileged validation boundary are unchanged.
|
||||
- `gui_bridge.rs` (2763 lines) is split into `gui_bridge/mod.rs`,
|
||||
`protocol.rs` (protocol version 1, wire types, JSON observer, disk phase,
|
||||
newline-delimited JSON writer), `bridge.rs` (the single `Bridge` owning the
|
||||
installer, dispatch, installation support, secret handling), and `tests.rs`.
|
||||
No UI or wire-format change.
|
||||
- `cargo test --workspace` passes 692/692 before and after each split
|
||||
(including the 4 new `ExecError` regression tests). Release and static-pie
|
||||
builds pass.
|
||||
- The disposable VM re-ran the current `sys` acceptance matrix against the new
|
||||
static `sys` (`70f0a72b…`, fetched to `/tmp/sys` on an overlay of the
|
||||
pristine installed image): guest `PASS=38 FAIL=0` (the full 38-case matrix,
|
||||
run as the non-root user with no mutations), driver `PASS=41 FAIL=0`
|
||||
(`serial-boot-20260926T014746Z-3089a820`). Recovery boot, strict Snap
|
||||
confinement, and a revision-changing Snap update remain unverified.
|
||||
|
||||
## 2026-09-25 — Make first-use Snap setup reviewable and fix Portage target selection
|
||||
|
||||
- The normal Snap install now explains the separate, reviewed Portage install of
|
||||
|
|
|
|||
|
|
@ -3,26 +3,6 @@
|
|||
Rolling note between work sessions. **Update this file before you finish**, then
|
||||
commit it. It should be short and current; use `git log` for detail.
|
||||
|
||||
- **Quality pass (2026-09-26):** boxed `ExecError::Command` details
|
||||
(`CommandFailure`, 128 → 96 bytes, measured with a path-dependent probe crate;
|
||||
constructor + all match sites updated, error text/redaction/stderr-tail
|
||||
preserved, 4 regression tests), cleared `cargo clippy --workspace --all-targets
|
||||
-- -D warnings` with no blanket allows (type alias, `CommandRecord` params
|
||||
struct, `DiskPhase` renames), and split `service.rs` (4218 lines →
|
||||
`service/mod,plan,validation,execution,tests`) and `gui_bridge.rs`
|
||||
(2763 lines → `gui_bridge/mod,protocol,bridge,tests`) as structural refactors
|
||||
with explicit re-exports and `pub(super)` seams — no `service.rs` left
|
||||
alongside `service/mod.rs`. `make test` green (692/692, unchanged across the
|
||||
splits). Release + static-pie builds pass. The disposable VM re-ran the
|
||||
current 38-case `sys` acceptance matrix against the new static `sys`
|
||||
(`70f0a72b…`): guest `PASS=38 FAIL=0`, driver `PASS=41 FAIL=0`
|
||||
(`serial-boot-20260926T014746Z-3089a820`, overlay
|
||||
`sys-acceptance-refactor.qcow2`). Commits `e69bfb9`, `1bf31c5`, `2dd48d1`.
|
||||
- **Interface contract (unchanged):** ordinary requests use AI; only explicit
|
||||
`--legacy` selects deterministic handling; source flags constrain the AI and
|
||||
never bypass it; a missing model stops the workflow and offers the exact
|
||||
`--legacy` command without executing it.
|
||||
|
||||
- **Snap first-use follow-up (2026-09-25):** the previous "no snapd" note was a
|
||||
real integration gap. The normal `sys install … --legacy --snap` resolver needs
|
||||
snapd to confirm a Store candidate before approval, while a raw typed
|
||||
|
|
|
|||
|
|
@ -216,16 +216,12 @@ still not VM-verified.
|
|||
- **The installed `sys` binary and desktop assistant (`phoebus-assistant`)**: The
|
||||
installer provisions `sys` into `/usr/local/bin/sys` and configures the desktop
|
||||
assistant Quickshell application (`phoebus-assistant`) launched via desktop
|
||||
entries and keybindings. On the installed system, all 38 acceptance test cases
|
||||
in `installer/tests/vm/sys-acceptance.sh` pass cleanly (`PASS=38 FAIL=0`),
|
||||
entries and keybindings. On the installed system, all 34 acceptance test cases
|
||||
in `installer/tests/vm/sys-acceptance.sh` pass cleanly (`PASS=34 FAIL=0`),
|
||||
verifying the unified AI-first CLI/GUI interface, deterministic `--legacy`
|
||||
mode, the package catalogue (search/inventory/information/update-check),
|
||||
fail-closed source requirements, audited `--broker`/`--legacy` gates,
|
||||
proactive system monitors, and offline fallback guidance. The matrix was
|
||||
re-run on 2026-09-26 against the refactored static `sys` (`70f0a72b…`,
|
||||
fetched to `/tmp/sys` on a disposable overlay of the pristine installed
|
||||
image, non-root user, no mutations): guest `PASS=38 FAIL=0`, driver
|
||||
`PASS=41 FAIL=0` (`serial-boot-20260926T014746Z-3089a820`).
|
||||
proactive system monitors, and offline fallback guidance.
|
||||
- **UKI** is deferred; the dracut UKI generator did not embed the kernel
|
||||
command line, so BLS is used (and verified).
|
||||
- **Rollback (`sys undo`) is NOT VM-verified.** It is implemented and
|
||||
|
|
|
|||
|
|
@ -711,30 +711,6 @@ detached boot verification with the live ISO removed.
|
|||
(`serial-boot-20260926T010605Z-e6193c3a`) also passed 11/11, with another
|
||||
`hello-world` install, refresh, removal and clean poweroff.
|
||||
|
||||
## 2026-09-26 — `sys` acceptance re-run against the refactored static binary
|
||||
|
||||
- Target: `sys-acceptance-refactor.qcow2`, a disposable overlay (absolute
|
||||
backing path, satisfying the harness disk-safety gate) of the pristine
|
||||
installed `fresh-install-1.qcow2` image. QEMU/OVMF booted the installed
|
||||
system detached; no physical disk was attached or modified.
|
||||
- Purpose: prove the quality-pass refactor (boxed `ExecError`, Clippy fixes,
|
||||
`service/` and `gui_bridge/` module splits) changed no behavior. The guest
|
||||
fetched the new static-pie `sys` (`SHA-256
|
||||
70f0a72b9ca4534250c2ee27417efffc0681da88ba4d2633da932813b0c0e044`,
|
||||
built from the post-split tree) to `/tmp/sys` and ran the current
|
||||
`installer/tests/vm/sys-acceptance.sh` with `SYS_BIN=/tmp/sys` as the
|
||||
non-root `phoebus` user with no mutations — so the matrix exercised the new
|
||||
binary, not the image's provisioned one.
|
||||
- Result `serial-boot-20260926T014746Z-3089a820`: guest
|
||||
`===SYS-ACC-END=== SUMMARY PASS=38 FAIL=0` (the full 38-case matrix:
|
||||
version/history/undo, failure cases, offline/model-free behavior, source
|
||||
selection, AI-first read-only workflow, catalogue including the
|
||||
`rdeps-legacy` regression, and non-root privilege refusals), driver
|
||||
`PASS=41 FAIL=0` (38 cases + login + `systemd is-system-running` +
|
||||
disposable-disk), exit 0.
|
||||
- Not covered by this run: the mutate group (`SYS_ACCEPTANCE_MUTATE=1`),
|
||||
recovery boot, strict Snap confinement, and a revision-changing Snap update.
|
||||
|
||||
## Known remaining work
|
||||
|
||||
- The graphical session was verified with the **headless** wlroots backend
|
||||
|
|
|
|||
|
|
@ -459,10 +459,9 @@ pub(crate) fn flatpak_update_transactions(
|
|||
/// revision is the immutable identity and the tracking channel is the scope.
|
||||
pub(crate) fn parse_snap_transactions(refresh: &str, installed: &str) -> Vec<UpdateTransaction> {
|
||||
use std::collections::BTreeMap;
|
||||
/// Installed snap entry: (version, revision, tracking, notes).
|
||||
type InstalledSnapEntry = (Option<String>, Option<String>, Option<String>, String);
|
||||
// name -> (version, revision, tracking, notes)
|
||||
let mut current: BTreeMap<String, InstalledSnapEntry> = BTreeMap::new();
|
||||
let mut current: BTreeMap<String, (Option<String>, Option<String>, Option<String>, String)> =
|
||||
BTreeMap::new();
|
||||
for line in installed.lines().skip(1) {
|
||||
let cols: Vec<&str> = line.split_whitespace().collect();
|
||||
if cols.len() < 4 || cols[0].is_empty() {
|
||||
|
|
@ -1743,7 +1742,7 @@ Total: 1 package (1 new), Size of downloads: 512 KiB
|
|||
Path::new(&exec.root),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, ExecError::Command(_)), "got {err}");
|
||||
assert!(matches!(err, ExecError::Command { .. }), "got {err}");
|
||||
// The mutation must not run, and no snapshot may be recorded as
|
||||
// committed when creation failed.
|
||||
assert!(!runner.programs().iter().any(|p| p == "emerge"));
|
||||
|
|
|
|||
|
|
@ -7,33 +7,17 @@ use phoebus_core::CoreError;
|
|||
|
||||
pub type Result<T> = std::result::Result<T, ExecError>;
|
||||
|
||||
/// Heap-allocated command failure details. Kept on the heap so `ExecError`
|
||||
/// stays small enough for `Result<T, ExecError>` to pass `result_large_err`
|
||||
/// (128-byte threshold) without boxing at every call site.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CommandFailure {
|
||||
pub stage: String,
|
||||
pub operation: String,
|
||||
pub program: String,
|
||||
pub status: i32,
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for CommandFailure {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"[{}] {} failed (exit {}): {}",
|
||||
self.stage, self.operation, self.status, self.program
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ExecError {
|
||||
#[error("{0}")]
|
||||
Command(Box<CommandFailure>),
|
||||
#[error("[{stage}] {operation} failed (exit {status}): {program}")]
|
||||
Command {
|
||||
stage: String,
|
||||
operation: String,
|
||||
program: String,
|
||||
status: i32,
|
||||
stdout: String,
|
||||
stderr: String,
|
||||
},
|
||||
|
||||
#[error("[{stage}] {operation}: {message}")]
|
||||
Operation {
|
||||
|
|
@ -67,17 +51,6 @@ pub enum ExecError {
|
|||
}
|
||||
|
||||
impl ExecError {
|
||||
pub fn command(details: CommandFailure) -> Self {
|
||||
ExecError::Command(Box::new(details))
|
||||
}
|
||||
|
||||
pub fn command_details(&self) -> Option<&CommandFailure> {
|
||||
match self {
|
||||
ExecError::Command(details) => Some(details),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn io(path: impl Into<PathBuf>, source: std::io::Error) -> Self {
|
||||
ExecError::Io {
|
||||
path: path.into(),
|
||||
|
|
@ -93,54 +66,3 @@ impl ExecError {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn sample_failure() -> CommandFailure {
|
||||
CommandFailure {
|
||||
stage: "storage_prepare".into(),
|
||||
operation: "create GPT".into(),
|
||||
program: "sgdisk".into(),
|
||||
status: 2,
|
||||
stdout: "partial output".into(),
|
||||
stderr: "line1\nline2\nline3\nline4\nline5\nline6".into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_error_text_preserves_stage_operation_status_and_program() {
|
||||
let err = ExecError::command(sample_failure());
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"[storage_prepare] create GPT failed (exit 2): sgdisk"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_error_preserves_captured_stdout_and_stderr() {
|
||||
let err = ExecError::command(sample_failure());
|
||||
let details = err.command_details().expect("command details");
|
||||
assert_eq!(details.stdout, "partial output");
|
||||
assert_eq!(details.stderr, "line1\nline2\nline3\nline4\nline5\nline6");
|
||||
assert_eq!(details.status, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_error_stays_small_enough_for_result_large_err() {
|
||||
// Clippy's `result_large_err` fires at 128 bytes. The boxed details
|
||||
// must keep the whole enum comfortably below that.
|
||||
assert!(
|
||||
std::mem::size_of::<ExecError>() <= 96,
|
||||
"ExecError is {} bytes",
|
||||
std::mem::size_of::<ExecError>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_command_errors_have_no_command_details() {
|
||||
let err = ExecError::operation("stage", "op", "message");
|
||||
assert!(err.command_details().is_none());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -61,15 +61,15 @@ impl Exec {
|
|||
stdin_hidden,
|
||||
);
|
||||
let output = self.runner.execute(&spec)?;
|
||||
self.logger.command(crate::log::CommandRecord {
|
||||
stage: &spec.stage,
|
||||
operation: &spec.operation,
|
||||
program: &spec.program,
|
||||
args: &spec.args,
|
||||
status: output.status,
|
||||
duration: output.duration,
|
||||
self.logger.command(
|
||||
&spec.stage,
|
||||
&spec.operation,
|
||||
&spec.program,
|
||||
&spec.args,
|
||||
output.status,
|
||||
output.duration,
|
||||
stdin_hidden,
|
||||
});
|
||||
);
|
||||
if !self.runner.is_streaming() {
|
||||
if !output.stdout.is_empty() {
|
||||
self.logger.output(&output.stdout);
|
||||
|
|
@ -79,14 +79,14 @@ impl Exec {
|
|||
}
|
||||
}
|
||||
if !output.success {
|
||||
return Err(ExecError::command(crate::error::CommandFailure {
|
||||
return Err(ExecError::Command {
|
||||
stage: spec.stage.clone(),
|
||||
operation: spec.operation.clone(),
|
||||
program: spec.program.clone(),
|
||||
status: output.status,
|
||||
stdout: self.redactor().redact(&output.stdout_lossy()),
|
||||
stderr: self.redactor().redact(&output.stderr_lossy()),
|
||||
}));
|
||||
});
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -46,6 +46,6 @@ pub use auth::{authorize, AutoConfirm, Confirmation, DenyConfirm, DestructiveAut
|
|||
pub use command::{
|
||||
CommandOutput, CommandSpec, NeverRunner, ProcessRunner, RealRunner, RecordingRunner,
|
||||
};
|
||||
pub use error::{CommandFailure, ExecError, Result};
|
||||
pub use error::{ExecError, Result};
|
||||
pub use exec::Exec;
|
||||
pub use log::{CommandRecord, Logger};
|
||||
pub use log::Logger;
|
||||
|
|
|
|||
|
|
@ -35,18 +35,6 @@ use std::sync::Arc;
|
|||
|
||||
pub type LogListener = Arc<dyn Fn(&str) + Send + Sync>;
|
||||
|
||||
/// Parameters for [`Logger::command`], grouped so the call stays within the
|
||||
/// argument-count lint while keeping every field explicit at the call site.
|
||||
pub struct CommandRecord<'a> {
|
||||
pub stage: &'a str,
|
||||
pub operation: &'a str,
|
||||
pub program: &'a str,
|
||||
pub args: &'a [String],
|
||||
pub status: i32,
|
||||
pub duration: Duration,
|
||||
pub stdin_hidden: bool,
|
||||
}
|
||||
|
||||
struct LoggerInner {
|
||||
path: PathBuf,
|
||||
file: Mutex<Option<File>>,
|
||||
|
|
@ -164,22 +152,27 @@ impl Logger {
|
|||
}
|
||||
|
||||
/// Log a command with its exit status and duration (all redacted).
|
||||
pub fn command(&self, record: CommandRecord<'_>) {
|
||||
let mut line = format!(
|
||||
"[{}] {} :: {}",
|
||||
record.stage, record.operation, record.program
|
||||
);
|
||||
for arg in record.args {
|
||||
pub fn command(
|
||||
&self,
|
||||
stage: &str,
|
||||
operation: &str,
|
||||
program: &str,
|
||||
args: &[String],
|
||||
status: i32,
|
||||
duration: Duration,
|
||||
stdin_hidden: bool,
|
||||
) {
|
||||
let mut line = format!("[{stage}] {operation} :: {program}");
|
||||
for arg in args {
|
||||
line.push(' ');
|
||||
line.push_str(&shell_quote(arg));
|
||||
}
|
||||
if record.stdin_hidden {
|
||||
if stdin_hidden {
|
||||
line.push_str(" (stdin hidden)");
|
||||
}
|
||||
line.push_str(&format!(
|
||||
" :: exit {} in {:.3}s",
|
||||
record.status,
|
||||
record.duration.as_secs_f64()
|
||||
" :: exit {status} in {:.3}s",
|
||||
duration.as_secs_f64()
|
||||
));
|
||||
self.write_line(Level::Info, &line);
|
||||
}
|
||||
|
|
@ -291,15 +284,15 @@ mod tests {
|
|||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("install.log");
|
||||
let logger = Logger::open(&path, Redactor::new(), false);
|
||||
logger.command(CommandRecord {
|
||||
stage: "storage_prepare",
|
||||
operation: "create GPT",
|
||||
program: "sgdisk",
|
||||
args: &["--zap-all".into(), "/dev/vda".into()],
|
||||
status: 0,
|
||||
duration: Duration::from_millis(12),
|
||||
stdin_hidden: false,
|
||||
});
|
||||
logger.command(
|
||||
"storage_prepare",
|
||||
"create GPT",
|
||||
"sgdisk",
|
||||
&["--zap-all".into(), "/dev/vda".into()],
|
||||
0,
|
||||
Duration::from_millis(12),
|
||||
false,
|
||||
);
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
assert!(text.contains("[storage_prepare] create GPT :: sgdisk"));
|
||||
assert!(text.contains("/dev/vda"));
|
||||
|
|
|
|||
|
|
@ -144,8 +144,8 @@ pub fn prepare(exec: &Exec, root: &Path, cores: u32, force: bool) -> Result<Prep
|
|||
/// explains *why* preparation failed instead of only the exit status.
|
||||
fn describe_failure(error: &ExecError) -> String {
|
||||
match error {
|
||||
ExecError::Command(details) if !details.stderr.trim().is_empty() => {
|
||||
let lines: Vec<&str> = details.stderr.lines().collect();
|
||||
ExecError::Command { stderr, .. } if !stderr.trim().is_empty() => {
|
||||
let lines: Vec<&str> = stderr.lines().collect();
|
||||
let tail = lines[lines.len().saturating_sub(5)..].join("\n");
|
||||
format!("{error}: {tail}")
|
||||
}
|
||||
|
|
@ -422,7 +422,7 @@ mod tests {
|
|||
let exec = make_exec(runner);
|
||||
let root = Path::new(&exec.root);
|
||||
let err = prepare(&exec, root, 8, true).unwrap_err();
|
||||
assert!(matches!(err, ExecError::Command(_)));
|
||||
assert!(matches!(err, ExecError::Command { .. }));
|
||||
let state = load_state(root);
|
||||
assert_eq!(state.status, PrepareStatus::Failed);
|
||||
assert!(
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -1,29 +0,0 @@
|
|||
//! Typed graphical frontend bridge.
|
||||
//!
|
||||
//! The Quickshell/QML installer never parses terminal output and never touches
|
||||
//! disks: it speaks newline-delimited JSON to this bridge over stdin/stdout.
|
||||
//! The bridge owns one [`Installer`] and is the only thing that can reach the
|
||||
//! deterministic backend. It reuses `InstallConfig`, validation, the plan, the
|
||||
//! audited [`DestructiveAuthorization`] flow and `Installer::install_observed`,
|
||||
//! so the graphical path cannot diverge from the TUI/CLI path.
|
||||
//!
|
||||
//! Secrets arrive over the stdin pipe (never argv, logs, config files or model
|
||||
//! context) and are registered with the redactor immediately. Progress events
|
||||
//! report the real backend stages; categories name the kind of work, and no
|
||||
//! percentage is ever invented.
|
||||
//!
|
||||
//! Run with `phoebus-installer --gui-bridge`.
|
||||
//!
|
||||
//! Module layout (structural split, no protocol or behavior change):
|
||||
//! - [`protocol`]: wire types, the JSON observer, disk-change phase, and the
|
||||
//! newline-delimited JSON writer (protocol version 1).
|
||||
//! - [`bridge`]: the single [`Bridge`] owning the installer, request dispatch,
|
||||
//! installation support, and the stdio entry point.
|
||||
|
||||
pub mod bridge;
|
||||
pub mod protocol;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
pub use bridge::{run_stdio, Bridge};
|
||||
pub use protocol::PROTOCOL_VERSION;
|
||||
|
|
@ -1,189 +0,0 @@
|
|||
//! Bridge wire protocol (version 1): request types, the progress observer,
|
||||
//! the disk-change phase, and the newline-delimited JSON writer.
|
||||
//!
|
||||
//! The [`Bridge`](super::bridge::Bridge) owns the only [`Installer`] and is the
|
||||
//! sole consumer of these types.
|
||||
|
||||
use std::io::{self, Write};
|
||||
|
||||
use crate::InstallObserver;
|
||||
use phoebus_core::InstallStep;
|
||||
use phoebus_executor::auth::Confirmation;
|
||||
use phoebus_executor::Result as ExecResult;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
/// The version of the bridge protocol understood by the QML frontend.
|
||||
pub const PROTOCOL_VERSION: u32 = 1;
|
||||
|
||||
pub(super) const MAX_LOG_TAIL: usize = 200;
|
||||
/// Upper bound on one request line. The frontend sends small, typed requests;
|
||||
/// anything larger is refused before parsing rather than buffered blindly.
|
||||
pub(super) const MAX_LINE_BYTES: usize = 256 * 1024;
|
||||
/// Upper bound on a single secret value (passwords/passphrases/API keys).
|
||||
pub(super) const MAX_SECRET_BYTES: usize = 16 * 1024;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Protocol types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(super) struct Request {
|
||||
pub(super) id: u64,
|
||||
pub(super) op: String,
|
||||
#[serde(default)]
|
||||
pub(super) config: Option<Value>,
|
||||
#[serde(default)]
|
||||
pub(super) secrets: Option<SecretsPatch>,
|
||||
#[serde(default)]
|
||||
pub(super) erase: Option<String>,
|
||||
#[serde(default)]
|
||||
pub(super) final_confirm: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub(super) plan_digest: Option<String>,
|
||||
#[serde(default)]
|
||||
pub(super) lines: Option<usize>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(super) struct SecretsPatch {
|
||||
#[serde(default)]
|
||||
pub(super) luks: Option<String>,
|
||||
#[serde(default)]
|
||||
pub(super) user_password: Option<String>,
|
||||
#[serde(default)]
|
||||
pub(super) root_password: Option<String>,
|
||||
#[serde(default)]
|
||||
pub(super) ai_api_key: Option<String>,
|
||||
/// The OpenCode server password (basic auth). Distinct from a model
|
||||
/// provider API key and never stored in the configuration.
|
||||
#[serde(default)]
|
||||
pub(super) opencode_password: Option<String>,
|
||||
}
|
||||
|
||||
/// A `Confirmation` whose answers come from an explicit GUI request. The ERASE
|
||||
/// phrase is checked here, so the audited [`authorize`] flow is unchanged.
|
||||
pub(super) struct BridgeConfirm {
|
||||
pub(super) erase: bool,
|
||||
pub(super) final_ok: bool,
|
||||
}
|
||||
|
||||
impl Confirmation for BridgeConfirm {
|
||||
fn confirm_erase(&self, _preview: &str) -> ExecResult<bool> {
|
||||
Ok(self.erase)
|
||||
}
|
||||
fn confirm_final(&self, _message: &str) -> ExecResult<bool> {
|
||||
Ok(self.final_ok)
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes progress events for the real backend stages and records the coarse
|
||||
/// disk-change phase so a failure can be explained accurately.
|
||||
pub(super) struct JsonObserver {
|
||||
pub(super) tx: std::sync::mpsc::Sender<Value>,
|
||||
pub(super) id: u64,
|
||||
pub(super) phase: std::rc::Rc<std::cell::Cell<DiskPhase>>,
|
||||
pub(super) last_stage: std::rc::Rc<std::cell::Cell<Option<InstallStep>>>,
|
||||
}
|
||||
|
||||
impl JsonObserver {
|
||||
fn emit(&mut self, step: InstallStep, status: &str, error: Option<&str>) {
|
||||
let (category, label) = step_meta(step);
|
||||
let event = json!({
|
||||
"event": "progress",
|
||||
"id": self.id,
|
||||
"op": "start_install",
|
||||
"stage": step.name(),
|
||||
"category": category,
|
||||
"label": label,
|
||||
"status": status,
|
||||
"error": error,
|
||||
});
|
||||
let _ = self.tx.send(event);
|
||||
}
|
||||
}
|
||||
|
||||
impl InstallObserver for JsonObserver {
|
||||
fn stage_started(&mut self, step: InstallStep) {
|
||||
self.last_stage.set(Some(step));
|
||||
if step == InstallStep::StoragePrepare {
|
||||
self.phase.set(DiskPhase::During);
|
||||
}
|
||||
self.emit(step, "started", None);
|
||||
}
|
||||
fn stage_finished(&mut self, step: InstallStep, error: Option<&str>) {
|
||||
if step == InstallStep::StoragePrepare && error.is_none() {
|
||||
self.phase.set(DiskPhase::After);
|
||||
}
|
||||
self.emit(
|
||||
step,
|
||||
if error.is_some() {
|
||||
"failed"
|
||||
} else {
|
||||
"finished"
|
||||
},
|
||||
error,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Category + human label for a backend stage. Categories are the four the
|
||||
/// product distinguishes (download, compile, configure, verify) plus prepare.
|
||||
pub(super) fn step_meta(step: InstallStep) -> (&'static str, &'static str) {
|
||||
match step {
|
||||
InstallStep::StoragePrepare => ("prepare", "Preparing the target disk"),
|
||||
InstallStep::StageInstall => ("download", "Downloading the Gentoo stage3"),
|
||||
InstallStep::FstabGenerate => ("configure", "Writing filesystem tables"),
|
||||
InstallStep::PortageConfigure => ("download", "Configuring and syncing Portage"),
|
||||
InstallStep::PackagesBase => ("compile", "Installing base packages"),
|
||||
InstallStep::KernelInstall => ("compile", "Building and installing the kernel"),
|
||||
InstallStep::NvidiaDrivers => ("compile", "Installing the NVIDIA driver"),
|
||||
InstallStep::BootInstall => ("configure", "Installing the boot loader"),
|
||||
InstallStep::UsersConfigure => ("configure", "Creating your account"),
|
||||
InstallStep::ServicesConfigure => ("configure", "Enabling system services"),
|
||||
InstallStep::DesktopInstall => ("compile", "Installing the desktop"),
|
||||
InstallStep::Finalize => ("verify", "Finalising and verifying"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Coarse phase of the last reported progress event, used to explain whether
|
||||
/// disk changes occurred. Updated by the observer from the real stage order.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum DiskPhase {
|
||||
Before,
|
||||
During,
|
||||
After,
|
||||
}
|
||||
|
||||
pub(super) fn disk_change_report(phase: DiskPhase) -> (&'static str, Vec<&'static str>) {
|
||||
match phase {
|
||||
DiskPhase::Before => (
|
||||
"none",
|
||||
vec!["Review the installer log, then retry the installation."],
|
||||
),
|
||||
DiskPhase::During => (
|
||||
"partial",
|
||||
vec![
|
||||
"The target disk may have been partially modified.",
|
||||
"Review the installer log before retrying.",
|
||||
],
|
||||
),
|
||||
DiskPhase::After => (
|
||||
"yes",
|
||||
vec![
|
||||
"The target disk was re-partitioned.",
|
||||
"Review the installer log, then restart the installation (the disk is re-created from scratch).",
|
||||
],
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Write one newline-delimited JSON value (the wire format).
|
||||
pub(super) fn write_json(out: &mut dyn Write, value: &Value) -> io::Result<()> {
|
||||
serde_json::to_writer(&mut *out, value)?;
|
||||
out.write_all(b"\n")?;
|
||||
out.flush()
|
||||
}
|
||||
|
|
@ -1,775 +0,0 @@
|
|||
//! GUI bridge regression tests (moved verbatim from `gui_bridge.rs`).
|
||||
|
||||
use super::bridge::{
|
||||
connection_error_kind, humanize_keymap, humanize_locale, humanize_timezone, models_url,
|
||||
parse_model_ids,
|
||||
};
|
||||
use super::protocol::{MAX_LINE_BYTES, MAX_SECRET_BYTES};
|
||||
use super::{Bridge, PROTOCOL_VERSION};
|
||||
use crate::Installer;
|
||||
use phoebus_ai::provider::TestTransport;
|
||||
use phoebus_core::{Disk, DiskKind, Redactor};
|
||||
use phoebus_core::{InstallConfig, SecretString};
|
||||
use phoebus_executor::Exec;
|
||||
use phoebus_executor::{Logger, RecordingRunner};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
fn test_bridge() -> Bridge {
|
||||
let runner = RecordingRunner::new();
|
||||
let dir = tempfile::tempdir().unwrap().keep();
|
||||
let logger = Logger::open(dir.join("install.log"), Redactor::new(), false);
|
||||
let mut config = InstallConfig::default();
|
||||
// The bridge preserves the backend's dry-run flag; set it on the
|
||||
// installer so the whole staged flow runs without touching a disk.
|
||||
config.runtime.dry_run = true;
|
||||
config.system.hostname = "phoebus".into();
|
||||
config.system.timezone = "UTC".into();
|
||||
config.user.username = "tester".into();
|
||||
config.storage.disk = "/dev/vda".into();
|
||||
let exec = Exec::new(
|
||||
Box::new(runner),
|
||||
logger,
|
||||
true,
|
||||
dir.join("root"),
|
||||
dir.clone(),
|
||||
);
|
||||
let mut installer = Installer::new(config, exec);
|
||||
installer.disks.push(Disk {
|
||||
path: "/dev/vda".into(),
|
||||
model: Some("QEMU HARDDISK".into()),
|
||||
size_bytes: 30 * 1024 * 1024 * 1024,
|
||||
transport: Some("virtio".into()),
|
||||
removable: false,
|
||||
read_only: false,
|
||||
mounted: false,
|
||||
is_block_device: true,
|
||||
kind: DiskKind::Physical,
|
||||
live_media: false,
|
||||
});
|
||||
Bridge::with_installer(installer)
|
||||
}
|
||||
|
||||
fn call(bridge: &mut Bridge, request: &str) -> Vec<Value> {
|
||||
let mut out: Vec<u8> = Vec::new();
|
||||
bridge.handle_line(request, &mut out).unwrap();
|
||||
String::from_utf8(out)
|
||||
.unwrap()
|
||||
.lines()
|
||||
.filter(|l| !l.trim().is_empty())
|
||||
.map(|l| serde_json::from_str(l).expect("json line"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn response(lines: &[Value]) -> Value {
|
||||
lines
|
||||
.iter()
|
||||
.find(|v| v.get("ok").is_some())
|
||||
.cloned()
|
||||
.expect("a response line")
|
||||
}
|
||||
|
||||
fn config_json(bridge: &Bridge) -> Value {
|
||||
serde_json::to_value(&bridge.installer.config).unwrap()
|
||||
}
|
||||
|
||||
fn set_valid_config(bridge: &mut Bridge) -> Value {
|
||||
let mut c = config_json(bridge);
|
||||
c["system"]["hostname"] = json!("phoebus-box");
|
||||
c["user"]["username"] = json!("tester");
|
||||
c["storage"]["disk"] = json!("/dev/vda");
|
||||
let req = json!({ "id": 2, "op": "set_config", "config": c });
|
||||
let lines = call(bridge, &req.to_string());
|
||||
response(&lines)
|
||||
}
|
||||
|
||||
fn approve(bridge: &mut Bridge) -> (String, Value) {
|
||||
let req = json!({
|
||||
"id": 90,
|
||||
"op": "approve",
|
||||
"erase": "ERASE",
|
||||
"final_confirm": true
|
||||
});
|
||||
let lines = call(bridge, &req.to_string());
|
||||
let resp = response(&lines);
|
||||
let digest = resp["data"]["plan_digest"].as_str().unwrap().to_string();
|
||||
(digest, resp)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handshake_reports_protocol_and_readiness() {
|
||||
let mut bridge = test_bridge();
|
||||
let lines = call(&mut bridge, r#"{"id":1,"op":"handshake"}"#);
|
||||
let resp = response(&lines);
|
||||
assert_eq!(resp["ok"], json!(true));
|
||||
assert_eq!(resp["data"]["protocol"], json!(PROTOCOL_VERSION));
|
||||
assert!(resp["data"]["readiness"]["memory_mib"].is_number());
|
||||
assert_eq!(
|
||||
resp["data"]["defaults"]["desktop"]["profile"],
|
||||
json!("mango")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_reports_missing_user_and_disk() {
|
||||
let mut bridge = test_bridge();
|
||||
// Strip the valid user/disk to prove validation is wired through.
|
||||
let mut c = config_json(&bridge);
|
||||
c["user"]["username"] = json!("");
|
||||
c["storage"]["disk"] = json!("");
|
||||
let _ = call(
|
||||
&mut bridge,
|
||||
&json!({ "id": 2, "op": "set_config", "config": c }).to_string(),
|
||||
);
|
||||
let lines = call(&mut bridge, r#"{"id":3,"op":"validate"}"#);
|
||||
let resp = response(&lines);
|
||||
assert_eq!(resp["data"]["complete"], json!(false));
|
||||
let fields: Vec<&str> = resp["data"]["issues"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|i| i["field"].as_str().unwrap())
|
||||
.collect();
|
||||
assert!(fields.contains(&"username"));
|
||||
assert!(fields.contains(&"target_disk"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plan_review_carries_the_backend_facts() {
|
||||
let mut bridge = test_bridge();
|
||||
set_valid_config(&mut bridge);
|
||||
let lines = call(&mut bridge, r#"{"id":4,"op":"plan"}"#);
|
||||
let resp = response(&lines);
|
||||
assert_eq!(resp["ok"], json!(true));
|
||||
assert_eq!(resp["data"]["review"]["target_disk"], json!("/dev/vda"));
|
||||
assert_eq!(resp["data"]["review"]["encryption"], json!("luks2"));
|
||||
assert_eq!(resp["data"]["review"]["desktop"], json!("mango"));
|
||||
let subsystems = resp["data"]["review"]["subsystems"].as_array().unwrap();
|
||||
for want in ["systemd", "pipewire", "flatpak", "nix"] {
|
||||
assert!(
|
||||
subsystems.iter().any(|s| s == want),
|
||||
"review is missing subsystem {want}"
|
||||
);
|
||||
}
|
||||
assert!(resp["data"]["human"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("Installation plan"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn destructive_preview_matches_the_plan_digest() {
|
||||
let mut bridge = test_bridge();
|
||||
set_valid_config(&mut bridge);
|
||||
let lines = call(&mut bridge, r#"{"id":5,"op":"destructive_preview"}"#);
|
||||
let resp = response(&lines);
|
||||
let digest = resp["data"]["plan_digest"].as_str().unwrap().to_string();
|
||||
assert_eq!(digest, bridge.plan_digest());
|
||||
assert!(resp["data"]["text"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("ALL DATA ON THIS DEVICE WILL BE DESTROYED."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn approval_requires_erase_and_final_confirmation() {
|
||||
let mut bridge = test_bridge();
|
||||
set_valid_config(&mut bridge);
|
||||
let wrong = call(
|
||||
&mut bridge,
|
||||
r#"{"id":6,"op":"approve","erase":"erase","final_confirm":true}"#,
|
||||
);
|
||||
assert_eq!(response(&wrong)["ok"], json!(false));
|
||||
let no_final = call(
|
||||
&mut bridge,
|
||||
r#"{"id":7,"op":"approve","erase":"ERASE","final_confirm":false}"#,
|
||||
);
|
||||
assert_eq!(response(&no_final)["ok"], json!(false));
|
||||
let (_, ok) = approve(&mut bridge);
|
||||
assert_eq!(ok["ok"], json!(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn start_install_requires_a_matching_approval() {
|
||||
let mut bridge = test_bridge();
|
||||
set_valid_config(&mut bridge);
|
||||
// No approval at all.
|
||||
let none = call(
|
||||
&mut bridge,
|
||||
r#"{"id":8,"op":"start_install","erase":"ERASE","final_confirm":true}"#,
|
||||
);
|
||||
assert_eq!(response(&none)["ok"], json!(false));
|
||||
|
||||
// A stale digest (the plan changed after approval) is refused.
|
||||
let (digest, _) = approve(&mut bridge);
|
||||
let mut c = config_json(&bridge);
|
||||
c["system"]["hostname"] = json!("changed-after-approval");
|
||||
let _ = call(
|
||||
&mut bridge,
|
||||
&json!({ "id": 9, "op": "set_config", "config": c }).to_string(),
|
||||
);
|
||||
let stale = call(
|
||||
&mut bridge,
|
||||
&json!({
|
||||
"id": 10, "op": "start_install", "erase": "ERASE",
|
||||
"final_confirm": true, "plan_digest": digest
|
||||
})
|
||||
.to_string(),
|
||||
);
|
||||
assert_eq!(response(&stale)["ok"], json!(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn approved_dry_run_completes_and_reports_real_stages() {
|
||||
let mut bridge = test_bridge();
|
||||
set_valid_config(&mut bridge);
|
||||
let (digest, _) = approve(&mut bridge);
|
||||
let lines = call(
|
||||
&mut bridge,
|
||||
&json!({
|
||||
"id": 11, "op": "start_install", "erase": "ERASE",
|
||||
"final_confirm": true, "plan_digest": digest
|
||||
})
|
||||
.to_string(),
|
||||
);
|
||||
let resp = response(&lines);
|
||||
assert_eq!(resp["ok"], json!(true), "response: {resp}");
|
||||
assert_eq!(resp["data"]["complete"], json!(true));
|
||||
assert_eq!(resp["data"]["dry_run"], json!(true));
|
||||
|
||||
// The real stage sequence was emitted with categories, not percentages.
|
||||
let events: Vec<&Value> = lines
|
||||
.iter()
|
||||
.filter(|v| v.get("event") == Some(&json!("progress")))
|
||||
.collect();
|
||||
let started: Vec<&str> = events
|
||||
.iter()
|
||||
.filter(|e| e["status"] == json!("started"))
|
||||
.map(|e| e["stage"].as_str().unwrap())
|
||||
.collect();
|
||||
assert_eq!(started.first(), Some(&"storage_prepare"));
|
||||
assert_eq!(started.last(), Some(&"finalize"));
|
||||
assert!(events.iter().all(|e| e["category"].is_string()));
|
||||
assert!(
|
||||
events.iter().all(|e| e.get("percent").is_none()),
|
||||
"no invented percentage may appear"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_check_applies_a_reviewed_proposal_and_voids_approval() {
|
||||
let mut bridge = test_bridge();
|
||||
set_valid_config(&mut bridge);
|
||||
let (_, _) = approve(&mut bridge);
|
||||
let mut c = config_json(&bridge);
|
||||
c["ai"]["provider"] = json!("deepseek");
|
||||
c["ai"]["model"] = json!("deepseek-chat");
|
||||
let _ = call(
|
||||
&mut bridge,
|
||||
&json!({ "id": 12, "op": "set_config", "config": c }).to_string(),
|
||||
);
|
||||
let _ = call(
|
||||
&mut bridge,
|
||||
r#"{"id":19,"op":"set_secrets","secrets":{"ai_api_key":"test-key"}}"#,
|
||||
);
|
||||
let proposal = r#"{"version":1,"changes":[{"action":"set_kernel_profile","value":"safe"}],"rationale":[{"action":"set_kernel_profile","reason":"stability","evidence":["proven boot"]}]}"#;
|
||||
let transport = TestTransport::proposal(proposal);
|
||||
let value = bridge.ai_check_with(&transport).unwrap();
|
||||
assert_eq!(value["connected"], json!(true));
|
||||
assert_eq!(
|
||||
value["applied"][0]["description"],
|
||||
json!("kernel profile = safe")
|
||||
);
|
||||
assert_eq!(
|
||||
bridge.installer.config.kernel.profile,
|
||||
phoebus_core::KernelProfile::Safe
|
||||
);
|
||||
assert!(bridge.approved_digest.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_check_fails_closed_without_a_provider() {
|
||||
let mut bridge = test_bridge();
|
||||
let transport = TestTransport::proposal(r#"{"version":1,"changes":[]}"#);
|
||||
assert!(bridge.ai_check_with(&transport).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn secrets_never_appear_in_responses_and_the_log() {
|
||||
let mut bridge = test_bridge();
|
||||
set_valid_config(&mut bridge);
|
||||
let secret = "correct-horse-battery-staple";
|
||||
let req = json!({
|
||||
"id": 13, "op": "set_secrets",
|
||||
"secrets": { "luks": secret, "user_password": secret }
|
||||
});
|
||||
let lines = call(&mut bridge, &req.to_string());
|
||||
assert_eq!(response(&lines)["data"]["luks_set"], json!(true));
|
||||
// Presence only, never the value.
|
||||
assert!(!lines.iter().any(|v| v.to_string().contains(secret)));
|
||||
|
||||
// A log tail is redacted too.
|
||||
let tail = call(&mut bridge, r#"{"id":14,"op":"log_tail","lines":100}"#);
|
||||
assert!(!response(&tail).to_string().contains(secret));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_ops_and_unknown_fields_fail_closed() {
|
||||
let mut bridge = test_bridge();
|
||||
assert_eq!(
|
||||
response(&call(&mut bridge, r#"{"id":15,"op":"nope"}"#))["ok"],
|
||||
json!(false)
|
||||
);
|
||||
assert_eq!(
|
||||
response(&call(
|
||||
&mut bridge,
|
||||
r#"{"id":16,"op":"handshake","surprise":true}"#
|
||||
))["ok"],
|
||||
json!(false)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_may_not_smuggle_a_secret() {
|
||||
let mut bridge = test_bridge();
|
||||
let mut c = config_json(&bridge);
|
||||
c["system"]["distro_name"] = json!("passphrase is hunter2");
|
||||
let lines = call(
|
||||
&mut bridge,
|
||||
&json!({ "id": 17, "op": "set_config", "config": c }).to_string(),
|
||||
);
|
||||
assert_eq!(response(&lines)["ok"], json!(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quit_is_reported() {
|
||||
let mut bridge = test_bridge();
|
||||
let lines = call(&mut bridge, r#"{"id":18,"op":"quit"}"#);
|
||||
assert_eq!(response(&lines)["data"]["bye"], json!(true));
|
||||
assert!(bridge.should_quit());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn start_install_cannot_be_replayed_after_success() {
|
||||
let mut bridge = test_bridge();
|
||||
set_valid_config(&mut bridge);
|
||||
let (digest, _) = approve(&mut bridge);
|
||||
let first = call(
|
||||
&mut bridge,
|
||||
&json!({
|
||||
"id": 20, "op": "start_install", "erase": "ERASE",
|
||||
"final_confirm": true, "plan_digest": digest
|
||||
})
|
||||
.to_string(),
|
||||
);
|
||||
assert_eq!(response(&first)["ok"], json!(true));
|
||||
assert!(bridge.installed);
|
||||
|
||||
// A second frontend (or a retry) re-approves and tries again: refused.
|
||||
let (digest2, _) = approve(&mut bridge);
|
||||
let second = call(
|
||||
&mut bridge,
|
||||
&json!({
|
||||
"id": 21, "op": "start_install", "erase": "ERASE",
|
||||
"final_confirm": true, "plan_digest": digest2
|
||||
})
|
||||
.to_string(),
|
||||
);
|
||||
assert_eq!(response(&second)["ok"], json!(false));
|
||||
assert!(
|
||||
response(&second)["error"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("already installed"),
|
||||
"unexpected error: {}",
|
||||
response(&second)["error"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_request_line_is_refused() {
|
||||
let mut bridge = test_bridge();
|
||||
let huge = format!(
|
||||
r#"{{"id":1,"op":"handshake","pad":"{}"}}"#,
|
||||
"x".repeat(MAX_LINE_BYTES)
|
||||
);
|
||||
let lines = call(&mut bridge, &huge);
|
||||
let resp = response(&lines);
|
||||
assert_eq!(resp["ok"], json!(false));
|
||||
assert!(resp["error"].as_str().unwrap().contains("too large"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_secret_is_refused() {
|
||||
let mut bridge = test_bridge();
|
||||
let secret = "x".repeat(MAX_SECRET_BYTES + 1);
|
||||
let lines = call(
|
||||
&mut bridge,
|
||||
&json!({ "id": 22, "op": "set_secrets", "secrets": { "luks": secret } }).to_string(),
|
||||
);
|
||||
assert_eq!(response(&lines)["ok"], json!(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deeply_nested_json_is_rejected_without_panicking() {
|
||||
let mut bridge = test_bridge();
|
||||
let depth = 300;
|
||||
let nested = format!("{}{}{}", "[".repeat(depth), "0", "]".repeat(depth));
|
||||
let line = format!(r#"{{"id":23,"op":"handshake","config":{nested}}}"#);
|
||||
let lines = call(&mut bridge, &line);
|
||||
assert_eq!(response(&lines)["ok"], json!(false));
|
||||
}
|
||||
|
||||
/// A non-dry bridge whose runner reports `/dev/vda`, so revalidation and
|
||||
/// the install stages run against the fake runner (never a real disk).
|
||||
fn test_bridge_non_dry() -> Bridge {
|
||||
let runner = RecordingRunner::new();
|
||||
runner.set_response(
|
||||
"lsblk",
|
||||
phoebus_executor::CommandOutput {
|
||||
status: 0,
|
||||
success: true,
|
||||
stdout: b"NAME=\"vda\" MODEL=\"QEMU HARDDISK\" SIZE=\"32212254720\" TRAN=\"virtio\" RM=\"0\" RO=\"0\"\n".to_vec(),
|
||||
stderr: Vec::new(),
|
||||
duration: std::time::Duration::from_millis(1),
|
||||
},
|
||||
);
|
||||
let dir = tempfile::tempdir().unwrap().keep();
|
||||
let logger = Logger::open(dir.join("install.log"), Redactor::new(), false);
|
||||
let mut config = InstallConfig::default();
|
||||
config.runtime.dry_run = false;
|
||||
config.system.hostname = "phoebus".into();
|
||||
config.system.timezone = "UTC".into();
|
||||
config.user.username = "tester".into();
|
||||
config.storage.disk = "/dev/vda".into();
|
||||
let exec = Exec::new(
|
||||
Box::new(runner),
|
||||
logger,
|
||||
false,
|
||||
dir.join("root"),
|
||||
dir.clone(),
|
||||
);
|
||||
let mut installer = Installer::new(config, exec);
|
||||
installer.disks.push(Disk {
|
||||
path: "/dev/vda".into(),
|
||||
model: Some("QEMU HARDDISK".into()),
|
||||
size_bytes: 30 * 1024 * 1024 * 1024,
|
||||
transport: Some("virtio".into()),
|
||||
removable: false,
|
||||
read_only: false,
|
||||
mounted: false,
|
||||
is_block_device: true,
|
||||
kind: DiskKind::Physical,
|
||||
live_media: false,
|
||||
});
|
||||
Bridge::with_installer(installer)
|
||||
}
|
||||
|
||||
fn arm_ai(bridge: &mut Bridge) -> Value {
|
||||
let mut c = config_json(bridge);
|
||||
c["ai"]["provider"] = json!("deepseek");
|
||||
c["ai"]["model"] = json!("deepseek-chat");
|
||||
let _ = call(
|
||||
bridge,
|
||||
&json!({ "id": 30, "op": "set_config", "config": c }).to_string(),
|
||||
);
|
||||
bridge.api_key = Some(SecretString::new("test-key"));
|
||||
let proposal = r#"{"version":1,"changes":[{"action":"set_kernel_profile","value":"safe"}],"rationale":[{"action":"set_kernel_profile","reason":"stability","evidence":["x"]}]}"#;
|
||||
bridge
|
||||
.ai_check_with(&TestTransport::proposal(proposal))
|
||||
.expect("ai_check")
|
||||
}
|
||||
|
||||
fn start(bridge: &mut Bridge, digest: &str) -> Value {
|
||||
let lines = call(
|
||||
bridge,
|
||||
&json!({
|
||||
"id": 31, "op": "start_install", "erase": "ERASE",
|
||||
"final_confirm": true, "plan_digest": digest
|
||||
})
|
||||
.to_string(),
|
||||
);
|
||||
response(&lines)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_provider_name_alone_does_not_satisfy_the_ai_requirement() {
|
||||
let mut bridge = test_bridge_non_dry();
|
||||
set_valid_config(&mut bridge);
|
||||
// Provider configured and key present, but no validated interaction.
|
||||
let mut c = config_json(&bridge);
|
||||
c["ai"]["provider"] = json!("deepseek");
|
||||
let _ = call(
|
||||
&mut bridge,
|
||||
&json!({ "id": 40, "op": "set_config", "config": c }).to_string(),
|
||||
);
|
||||
bridge.api_key = Some(SecretString::new("test-key"));
|
||||
let (digest, _) = approve(&mut bridge);
|
||||
let resp = start(&mut bridge, &digest);
|
||||
assert_eq!(resp["ok"], json!(false));
|
||||
assert!(
|
||||
resp["error"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("validated AI interaction"),
|
||||
"unexpected error: {}",
|
||||
resp["error"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_validated_interaction_satisfies_the_ai_requirement() {
|
||||
let mut bridge = test_bridge_non_dry();
|
||||
set_valid_config(&mut bridge);
|
||||
arm_ai(&mut bridge);
|
||||
let (digest, _) = approve(&mut bridge);
|
||||
let resp = start(&mut bridge, &digest);
|
||||
// It may fail later in the fake storage stage, but never on the AI gate.
|
||||
assert!(
|
||||
!resp["error"]
|
||||
.as_str()
|
||||
.unwrap_or("")
|
||||
.contains("validated AI interaction"),
|
||||
"the AI gate wrongly rejected a validated interaction: {}",
|
||||
resp["error"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_config_change_invalidates_the_validated_interaction() {
|
||||
let mut bridge = test_bridge_non_dry();
|
||||
set_valid_config(&mut bridge);
|
||||
arm_ai(&mut bridge);
|
||||
// Change the model after validation.
|
||||
let mut c = config_json(&bridge);
|
||||
c["ai"]["model"] = json!("deepseek-reasoner");
|
||||
let _ = call(
|
||||
&mut bridge,
|
||||
&json!({ "id": 41, "op": "set_config", "config": c }).to_string(),
|
||||
);
|
||||
let (digest, _) = approve(&mut bridge);
|
||||
let resp = start(&mut bridge, &digest);
|
||||
assert_eq!(resp["ok"], json!(false));
|
||||
assert!(resp["error"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("validated AI interaction"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_ai_config_change_keeps_the_validated_interaction() {
|
||||
// Choosing a disk or editing the account must not discard a successful
|
||||
// model interaction: this was the bug that refused a fully-validated
|
||||
// install at the final step.
|
||||
let mut bridge = test_bridge_non_dry();
|
||||
set_valid_config(&mut bridge);
|
||||
arm_ai(&mut bridge);
|
||||
let mut c = config_json(&bridge);
|
||||
c["system"]["hostname"] = json!("renamed-box");
|
||||
let _ = call(
|
||||
&mut bridge,
|
||||
&json!({ "id": 60, "op": "set_config", "config": c }).to_string(),
|
||||
);
|
||||
let (digest, _) = approve(&mut bridge);
|
||||
let resp = start(&mut bridge, &digest);
|
||||
assert!(
|
||||
!resp["error"]
|
||||
.as_str()
|
||||
.unwrap_or("")
|
||||
.contains("validated AI interaction"),
|
||||
"a non-AI change wrongly invalidated the interaction: {}",
|
||||
resp["error"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_account_secret_does_not_invalidate_but_an_ai_key_does() {
|
||||
let mut bridge = test_bridge_non_dry();
|
||||
set_valid_config(&mut bridge);
|
||||
arm_ai(&mut bridge);
|
||||
let _ = call(
|
||||
&mut bridge,
|
||||
r#"{"id":61,"op":"set_secrets","secrets":{"user_password":"secret-pass-1","luks":"luks-pass-1234"}}"#,
|
||||
);
|
||||
let (digest, _) = approve(&mut bridge);
|
||||
let resp = start(&mut bridge, &digest);
|
||||
assert!(
|
||||
!resp["error"]
|
||||
.as_str()
|
||||
.unwrap_or("")
|
||||
.contains("validated AI interaction"),
|
||||
"an account secret wrongly invalidated the interaction: {}",
|
||||
resp["error"]
|
||||
);
|
||||
|
||||
// A changed AI credential must invalidate it.
|
||||
let mut bridge = test_bridge_non_dry();
|
||||
set_valid_config(&mut bridge);
|
||||
arm_ai(&mut bridge);
|
||||
let _ = call(
|
||||
&mut bridge,
|
||||
r#"{"id":62,"op":"set_secrets","secrets":{"ai_api_key":"a-different-key"}}"#,
|
||||
);
|
||||
let (digest, _) = approve(&mut bridge);
|
||||
let resp = start(&mut bridge, &digest);
|
||||
assert!(resp["error"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("validated AI interaction"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_secret_change_invalidates_the_validated_interaction() {
|
||||
let mut bridge = test_bridge_non_dry();
|
||||
set_valid_config(&mut bridge);
|
||||
arm_ai(&mut bridge);
|
||||
let _ = call(
|
||||
&mut bridge,
|
||||
r#"{"id":42,"op":"set_secrets","secrets":{"ai_api_key":"new-key"}}"#,
|
||||
);
|
||||
let (digest, _) = approve(&mut bridge);
|
||||
let resp = start(&mut bridge, &digest);
|
||||
assert_eq!(resp["ok"], json!(false));
|
||||
assert!(resp["error"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("validated AI interaction"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_are_available_for_the_region_pickers() {
|
||||
let mut bridge = test_bridge();
|
||||
let lines = call(&mut bridge, r#"{"id":50,"op":"options"}"#);
|
||||
let data = &response(&lines)["data"];
|
||||
assert!(!data["timezones"].as_array().unwrap().is_empty());
|
||||
assert!(!data["locales"].as_array().unwrap().is_empty());
|
||||
assert!(!data["keymaps"].as_array().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn models_url_is_derived_from_the_chat_endpoint() {
|
||||
assert_eq!(
|
||||
models_url("https://api.deepseek.com/chat/completions"),
|
||||
"https://api.deepseek.com/models"
|
||||
);
|
||||
assert_eq!(
|
||||
models_url("https://api.openai.com/v1/chat/completions"),
|
||||
"https://api.openai.com/v1/models"
|
||||
);
|
||||
assert_eq!(
|
||||
models_url("http://127.0.0.1:11434/v1/chat/completions"),
|
||||
"http://127.0.0.1:11434/v1/models"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_model_ids_reads_common_shapes() {
|
||||
assert_eq!(
|
||||
parse_model_ids(r#"{"data":[{"id":"b"},{"id":"a"},{"id":"a"}]}"#),
|
||||
vec!["a", "b"]
|
||||
);
|
||||
assert_eq!(parse_model_ids(r#"{"models":[{"name":"m"}]}"#), vec!["m"]);
|
||||
assert!(parse_model_ids("<html>").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_test_is_a_known_operation_and_fails_without_a_provider() {
|
||||
let mut bridge = test_bridge();
|
||||
let lines = call(&mut bridge, r#"{"id":43,"op":"ai_test"}"#);
|
||||
let resp = response(&lines);
|
||||
// Not "unknown op": the operation exists and reports the configuration
|
||||
// problem instead.
|
||||
assert_eq!(resp["ok"], json!(false));
|
||||
assert!(
|
||||
!resp["error"].as_str().unwrap().contains("unknown op"),
|
||||
"{}",
|
||||
resp["error"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connection_error_kind_classifies_common_failures() {
|
||||
assert_eq!(
|
||||
connection_error_kind("server requires authentication (HTTP 401)"),
|
||||
"authentication_required"
|
||||
);
|
||||
assert_eq!(
|
||||
connection_error_kind("server rejected the supplied authentication (HTTP 403)"),
|
||||
"authentication_rejected"
|
||||
);
|
||||
assert_eq!(
|
||||
connection_error_kind("model list returned HTTP 401"),
|
||||
"authentication_rejected"
|
||||
);
|
||||
assert_eq!(
|
||||
connection_error_kind("plain http to a non-loopback address is refused"),
|
||||
"insecure_transport"
|
||||
);
|
||||
assert_eq!(
|
||||
connection_error_kind("could not connect to the model server"),
|
||||
"unreachable"
|
||||
);
|
||||
assert_eq!(
|
||||
connection_error_kind("transport response had no status"),
|
||||
"unreachable"
|
||||
);
|
||||
assert_eq!(connection_error_kind("something unexpected"), "error");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn humanized_labels_keep_the_identifier_and_add_a_name() {
|
||||
assert!(humanize_locale("en_US.UTF-8").contains("English"));
|
||||
assert!(humanize_locale("de_DE.UTF-8").contains("German"));
|
||||
assert!(humanize_locale("en_US.UTF-8").contains("en_US.UTF-8"));
|
||||
assert_eq!(humanize_locale("xx_YY.UTF-8"), "xx_YY.UTF-8");
|
||||
assert!(humanize_keymap("de").contains("German"));
|
||||
assert!(humanize_keymap("de-nodeadkeys").contains("German"));
|
||||
assert!(humanize_keymap("us").contains("English (US)"));
|
||||
assert_eq!(humanize_keymap("zzz"), "zzz");
|
||||
assert!(humanize_timezone("Europe/Berlin").contains("Europe"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_carry_labels_and_the_live_keymap() {
|
||||
let mut bridge = test_bridge();
|
||||
let lines = call(&mut bridge, r#"{"id":70,"op":"options"}"#);
|
||||
let data = &response(&lines)["data"];
|
||||
for key in ["timezones", "locales", "keymaps"] {
|
||||
let entries = data[key].as_array().unwrap();
|
||||
assert!(!entries.is_empty(), "{key} was empty");
|
||||
assert!(
|
||||
entries
|
||||
.iter()
|
||||
.all(|o| o.get("value").is_some() && o.get("label").is_some()),
|
||||
"{key} entries need a value and a label"
|
||||
);
|
||||
}
|
||||
assert!(data["keymap_live"].is_string());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn readiness_reports_link_and_service_reachability_separately() {
|
||||
let mut bridge = test_bridge();
|
||||
let lines = call(&mut bridge, r#"{"id":71,"op":"readiness"}"#);
|
||||
let resp = response(&lines);
|
||||
assert_eq!(resp["ok"], json!(true), "response: {resp}");
|
||||
let data = &resp["data"];
|
||||
assert!(data["network"].is_boolean());
|
||||
assert!(
|
||||
data["network_services"].is_boolean(),
|
||||
"service reachability must be its own fact, not inferred from the link"
|
||||
);
|
||||
assert!(data["network_detail"].is_string());
|
||||
assert!(data["keymap_live"].is_string());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_catalog_errors_are_machine_readable() {
|
||||
let mut bridge = test_bridge();
|
||||
let lines = call(&mut bridge, r#"{"id":72,"op":"ai_catalog"}"#);
|
||||
let resp = response(&lines);
|
||||
assert_eq!(resp["ok"], json!(false));
|
||||
assert!(
|
||||
resp["error_kind"].is_string(),
|
||||
"an AI connection error must carry a kind: {resp}"
|
||||
);
|
||||
}
|
||||
4218
installer-rs/crates/phoebus-installer/src/service.rs
Normal file
4218
installer-rs/crates/phoebus-installer/src/service.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -1,529 +0,0 @@
|
|||
//! 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
|
||||
}
|
||||
|
|
@ -1,329 +0,0 @@
|
|||
//! 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};
|
||||
|
|
@ -1,872 +0,0 @@
|
|||
//! 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)
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,451 +0,0 @@
|
|||
//! 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