refactor(installer): split gui_bridge.rs into protocol/bridge/tests modules
Move the 2763-line typed GUI bridge into focused modules with no UI or
wire-format change: mod.rs keeps the docs and re-exports so
gui_bridge::{Bridge, run_stdio, PROTOCOL_VERSION} paths are unchanged;
protocol.rs holds protocol version 1, the request/secret types, the JSON
progress observer, the disk-change phase, and the newline-delimited JSON
writer; bridge.rs holds the single Bridge owning the installer, request
dispatch, installation support, secret handling, and progress events;
tests.rs holds the regression suite verbatim. Items shared across the
boundary are pub(super) with explicit imports; no glob re-exports and no
service.rs-style leftover file.
cargo fmt clean; cargo clippy --workspace --all-targets -- -D warnings
clean; cargo test --workspace passes (692 passed, 0 failed, identical
to the pre-split baseline).
This commit is contained in:
parent
1bf31c5a72
commit
2dd48d1fe8
4 changed files with 1013 additions and 970 deletions
File diff suppressed because it is too large
Load diff
29
installer-rs/crates/phoebus-installer/src/gui_bridge/mod.rs
Normal file
29
installer-rs/crates/phoebus-installer/src/gui_bridge/mod.rs
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
//! 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;
|
||||
189
installer-rs/crates/phoebus-installer/src/gui_bridge/protocol.rs
Normal file
189
installer-rs/crates/phoebus-installer/src/gui_bridge/protocol.rs
Normal file
|
|
@ -0,0 +1,189 @@
|
|||
//! 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()
|
||||
}
|
||||
775
installer-rs/crates/phoebus-installer/src/gui_bridge/tests.rs
Normal file
775
installer-rs/crates/phoebus-installer/src/gui_bridge/tests.rs
Normal file
|
|
@ -0,0 +1,775 @@
|
|||
//! 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}"
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue