Select the OpenCode adapter from canonical config in ai_check/ai_test; add --ai-backend/--opencode-* flags to the installer and sys. Require a validated interaction (not a provider name) for the mandatory-AI gate in both the bridge and the CLI, invalidated by config, model or credential changes. Tests cover the gate, invalidation and the OpenCode backend.
1633 lines
59 KiB
Rust
1633 lines
59 KiB
Rust
//! 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`.
|
|
|
|
use std::io::{self, BufRead, Write};
|
|
|
|
use crate::{ai_guide, InstallObserver, Installer};
|
|
use phoebus_ai::provider::{ModelTransport, ProviderKind, SystemFacts};
|
|
use phoebus_core::{AiBackend, InstallConfig, InstallStep, SecretString};
|
|
use phoebus_executor::ai::CurlTransport;
|
|
use phoebus_executor::auth::{authorize, Confirmation};
|
|
use phoebus_executor::opencode_client::ExecOpenCodeTransport;
|
|
use phoebus_executor::{Exec, 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;
|
|
|
|
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.
|
|
const MAX_LINE_BYTES: usize = 256 * 1024;
|
|
/// Upper bound on a single secret value (passwords/passphrases/API keys).
|
|
const MAX_SECRET_BYTES: usize = 16 * 1024;
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Protocol types
|
|
// ---------------------------------------------------------------------------
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct Request {
|
|
id: u64,
|
|
op: String,
|
|
#[serde(default)]
|
|
config: Option<Value>,
|
|
#[serde(default)]
|
|
secrets: Option<SecretsPatch>,
|
|
#[serde(default)]
|
|
erase: Option<String>,
|
|
#[serde(default)]
|
|
final_confirm: Option<bool>,
|
|
#[serde(default)]
|
|
plan_digest: Option<String>,
|
|
#[serde(default)]
|
|
lines: Option<usize>,
|
|
}
|
|
|
|
#[derive(Debug, Default, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct SecretsPatch {
|
|
#[serde(default)]
|
|
luks: Option<String>,
|
|
#[serde(default)]
|
|
user_password: Option<String>,
|
|
#[serde(default)]
|
|
root_password: Option<String>,
|
|
#[serde(default)]
|
|
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)]
|
|
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.
|
|
struct BridgeConfirm {
|
|
erase: bool,
|
|
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.
|
|
struct JsonObserver<'a> {
|
|
out: &'a mut dyn Write,
|
|
id: u64,
|
|
phase: std::rc::Rc<std::cell::Cell<DiskPhase>>,
|
|
}
|
|
|
|
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 _ = write_json(self.out, &event);
|
|
}
|
|
}
|
|
|
|
impl InstallObserver for JsonObserver<'_> {
|
|
fn stage_started(&mut self, step: InstallStep) {
|
|
if step == InstallStep::StoragePrepare {
|
|
self.phase.set(DiskPhase::InStorage);
|
|
}
|
|
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::AfterStorage);
|
|
}
|
|
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.
|
|
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::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"),
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Bridge
|
|
// ---------------------------------------------------------------------------
|
|
|
|
pub struct Bridge {
|
|
installer: Installer,
|
|
luks: Option<SecretString>,
|
|
user_password: Option<SecretString>,
|
|
root_password: Option<SecretString>,
|
|
api_key: Option<SecretString>,
|
|
opencode_password: Option<SecretString>,
|
|
approved_digest: Option<String>,
|
|
/// Set only after a real, validated AI interaction (a proposal reviewed for
|
|
/// the direct path, or a validated model response for OpenCode). A mere
|
|
/// provider name never satisfies the mandatory-AI gate.
|
|
validated_ai: Option<String>,
|
|
phase: std::rc::Rc<std::cell::Cell<DiskPhase>>,
|
|
/// One destructive transaction at a time. An approval is single-use: it is
|
|
/// consumed when the install starts so a replay, a second frontend or a
|
|
/// reconnected client cannot start a second overlapping installation.
|
|
installing: bool,
|
|
installed: bool,
|
|
quit: bool,
|
|
}
|
|
|
|
impl Bridge {
|
|
pub fn new(config: InstallConfig, exec: Exec) -> Self {
|
|
let installer = Installer::new(config, exec);
|
|
Self {
|
|
installer,
|
|
luks: None,
|
|
user_password: None,
|
|
root_password: None,
|
|
api_key: None,
|
|
opencode_password: None,
|
|
approved_digest: None,
|
|
validated_ai: None,
|
|
phase: std::rc::Rc::new(std::cell::Cell::new(DiskPhase::BeforeStorage)),
|
|
installing: false,
|
|
installed: false,
|
|
quit: false,
|
|
}
|
|
}
|
|
|
|
/// Build directly on an installer (tests, embedded callers).
|
|
pub fn with_installer(installer: Installer) -> Self {
|
|
Self {
|
|
installer,
|
|
luks: None,
|
|
user_password: None,
|
|
root_password: None,
|
|
api_key: None,
|
|
opencode_password: None,
|
|
approved_digest: None,
|
|
validated_ai: None,
|
|
phase: std::rc::Rc::new(std::cell::Cell::new(DiskPhase::BeforeStorage)),
|
|
installing: false,
|
|
installed: false,
|
|
quit: false,
|
|
}
|
|
}
|
|
|
|
/// Whether the caller asked the bridge to stop.
|
|
pub fn should_quit(&self) -> bool {
|
|
self.quit
|
|
}
|
|
|
|
/// Parse and dispatch one request line, writing events/responses to `out`.
|
|
pub fn handle_line(&mut self, line: &str, out: &mut dyn Write) -> io::Result<()> {
|
|
let line = line.trim();
|
|
if line.is_empty() {
|
|
return Ok(());
|
|
}
|
|
if line.len() > MAX_LINE_BYTES {
|
|
return write_json(
|
|
out,
|
|
&json!({
|
|
"ok": false,
|
|
"error": format!("request too large ({} bytes)", line.len()),
|
|
}),
|
|
);
|
|
}
|
|
let request: Request = match serde_json::from_str(line) {
|
|
Ok(request) => request,
|
|
Err(e) => {
|
|
return write_json(
|
|
out,
|
|
&json!({ "ok": false, "error": format!("bad request: {e}") }),
|
|
)
|
|
}
|
|
};
|
|
self.dispatch(request, out)
|
|
}
|
|
|
|
fn dispatch(&mut self, request: Request, out: &mut dyn Write) -> io::Result<()> {
|
|
let id = request.id;
|
|
let op = request.op.clone();
|
|
let result = match request.op.as_str() {
|
|
"handshake" => self.handshake(),
|
|
"disks" => self.disks(),
|
|
"set_config" => self.set_config(&request),
|
|
"set_secrets" => self.set_secrets(&request),
|
|
"validate" => self.validate(),
|
|
"plan" => self.plan(),
|
|
"destructive_preview" => self.destructive_preview(),
|
|
"ai_check" => self.ai_check(),
|
|
"ai_test" => self.ai_test(),
|
|
"approve" => self.approve(&request),
|
|
"start_install" => return self.start_install(id, &request, out),
|
|
"log_tail" => self.log_tail(&request),
|
|
"quit" => {
|
|
self.quit = true;
|
|
Ok(json!({ "bye": true }))
|
|
}
|
|
other => Err(format!("unknown op `{other}`")),
|
|
};
|
|
|
|
match result {
|
|
Ok(data) => write_json(
|
|
out,
|
|
&json!({ "id": id, "ok": true, "op": op, "data": data }),
|
|
),
|
|
Err(error) => write_json(
|
|
out,
|
|
&json!({ "id": id, "ok": false, "op": op, "error": error }),
|
|
),
|
|
}
|
|
}
|
|
|
|
// -- read-only ops ------------------------------------------------------
|
|
|
|
fn handshake(&self) -> Result<Value, String> {
|
|
let facts = self.installer.system_facts();
|
|
let network = network_ready();
|
|
Ok(json!({
|
|
"protocol": PROTOCOL_VERSION,
|
|
"version": phoebus_core::VERSION,
|
|
"iso_version": iso_version(),
|
|
"build_id": std::env::var("PHOEBUS_BUILD_ID").unwrap_or_else(|_| "dev".into()),
|
|
"live": std::path::Path::new("/etc/phoebus/live").exists(),
|
|
"defaults": self.installer.config,
|
|
"readiness": {
|
|
"network": network,
|
|
"firmware": self.installer.hardware.firmware_str(),
|
|
"memory_mib": self.installer.hardware.memory_mib,
|
|
"cpu_cores": self.installer.hardware.cpu.cores,
|
|
"cpu_model": self.installer.hardware.cpu.model,
|
|
"desktop": self.installer.config.desktop.profile.as_str(),
|
|
},
|
|
"facts": facts,
|
|
}))
|
|
}
|
|
|
|
fn disks(&mut self) -> Result<Value, String> {
|
|
self.installer.disks =
|
|
phoebus_executor::probe::probe_disks(self.installer.exec.runner.as_ref());
|
|
let runner = self.installer.exec.runner.as_ref();
|
|
let disks: Vec<Value> = self
|
|
.installer
|
|
.disks
|
|
.iter()
|
|
.map(|d| {
|
|
let partitions = phoebus_executor::probe::disk_partitions(runner, &d.path);
|
|
json!({
|
|
"path": d.path,
|
|
"identifier": d.path,
|
|
"model": d.model.clone().unwrap_or_else(|| "Unknown disk".into()),
|
|
"size_bytes": d.size_bytes,
|
|
"size_human": d.size_human(),
|
|
"transport": d.transport.clone().unwrap_or_else(|| "unknown".into()),
|
|
"removable": d.removable,
|
|
"protected": d.is_protected(),
|
|
"protection": d.protection().map(|r| r.describe()),
|
|
"live_medium": d.live_media,
|
|
"kind": format!("{:?}", d.kind).to_lowercase(),
|
|
"partitions": partitions,
|
|
})
|
|
})
|
|
.collect();
|
|
Ok(json!({ "disks": disks }))
|
|
}
|
|
|
|
fn validate(&self) -> Result<Value, String> {
|
|
let issues = self.installer.validate();
|
|
let complete = issues.is_empty();
|
|
Ok(json!({
|
|
"complete": complete,
|
|
"issues": issues.iter().map(|i| json!({
|
|
"field": i.field,
|
|
"message": i.message,
|
|
})).collect::<Vec<_>>(),
|
|
}))
|
|
}
|
|
|
|
fn plan(&self) -> Result<Value, String> {
|
|
let issues = self.installer.validate();
|
|
let plan = self.installer.plan();
|
|
Ok(json!({
|
|
"human": self.installer.render_plan(),
|
|
"plan_digest": self.plan_digest(),
|
|
"steps": plan.steps.iter().map(|s| json!({
|
|
"stage": s.name(),
|
|
"category": step_meta(*s).0,
|
|
"label": step_meta(*s).1,
|
|
})).collect::<Vec<_>>(),
|
|
"validation": issues.iter().map(|i| json!({
|
|
"field": i.field,
|
|
"message": i.message,
|
|
})).collect::<Vec<_>>(),
|
|
"review": self.review(),
|
|
}))
|
|
}
|
|
|
|
fn destructive_preview(&self) -> Result<Value, String> {
|
|
Ok(json!({
|
|
"text": self.installer.destructive_preview(),
|
|
"plan_digest": self.plan_digest(),
|
|
}))
|
|
}
|
|
|
|
fn log_tail(&self, request: &Request) -> Result<Value, String> {
|
|
let path = self.installer.exec.log_path().to_path_buf();
|
|
let text = std::fs::read_to_string(&path).unwrap_or_default();
|
|
let want = request.lines.unwrap_or(40).min(MAX_LOG_TAIL);
|
|
// The logger already redacted, but re-redact on read so a rotated or
|
|
// externally-written file can never leak a registered secret.
|
|
let redacted = self.installer.exec.redactor().redact(&text);
|
|
let lines: Vec<&str> = redacted.lines().rev().take(want).collect();
|
|
let tail: Vec<&str> = lines.into_iter().rev().collect();
|
|
Ok(json!({
|
|
"path": path.display().to_string(),
|
|
"lines": tail,
|
|
}))
|
|
}
|
|
|
|
// -- configuration ------------------------------------------------------
|
|
|
|
fn set_config(&mut self, request: &Request) -> Result<Value, String> {
|
|
let mut config: InstallConfig = serde_json::from_value(
|
|
request
|
|
.config
|
|
.clone()
|
|
.ok_or_else(|| "set_config requires a `config` object".to_string())?,
|
|
)
|
|
.map_err(|e| format!("invalid configuration: {e}"))?;
|
|
|
|
// Secrets never live in the configuration. Reject an attempt to smuggle
|
|
// one in, rather than silently persisting it.
|
|
if config
|
|
.to_toml_string()
|
|
.map(|t| contains_secret_marker(&t))
|
|
.unwrap_or(false)
|
|
{
|
|
return Err("configuration must not contain secret material".into());
|
|
}
|
|
// The bridge is an installer for this machine; the dry-run/log paths are
|
|
// backend concerns and not user-selectable from the GUI.
|
|
config.runtime.dry_run = self.installer.config.runtime.dry_run;
|
|
|
|
self.installer.reconfigure(config);
|
|
self.approved_digest = None;
|
|
// A configuration change (provider, model, endpoint, server) invalidates
|
|
// any previous AI validation.
|
|
self.validated_ai = None;
|
|
let issues = self.installer.validate();
|
|
Ok(json!({
|
|
"accepted": true,
|
|
"plan_digest": self.plan_digest(),
|
|
"complete": issues.is_empty(),
|
|
"issues": issues.iter().map(|i| json!({
|
|
"field": i.field,
|
|
"message": i.message,
|
|
})).collect::<Vec<_>>(),
|
|
}))
|
|
}
|
|
|
|
fn set_secrets(&mut self, request: &Request) -> Result<Value, String> {
|
|
let patch = request
|
|
.secrets
|
|
.as_ref()
|
|
.ok_or_else(|| "set_secrets requires a `secrets` object".to_string())?;
|
|
for value in [
|
|
&patch.luks,
|
|
&patch.user_password,
|
|
&patch.root_password,
|
|
&patch.ai_api_key,
|
|
&patch.opencode_password,
|
|
]
|
|
.into_iter()
|
|
.flatten()
|
|
{
|
|
if value.len() > MAX_SECRET_BYTES {
|
|
return Err("secret value is too large".into());
|
|
}
|
|
}
|
|
if let Some(v) = &patch.luks {
|
|
let s = SecretString::new(v.clone());
|
|
self.installer.exec.register_secret(&s);
|
|
self.luks = Some(s);
|
|
}
|
|
if let Some(v) = &patch.user_password {
|
|
let s = SecretString::new(v.clone());
|
|
self.installer.exec.register_secret(&s);
|
|
self.user_password = Some(s);
|
|
}
|
|
if let Some(v) = &patch.root_password {
|
|
let s = SecretString::new(v.clone());
|
|
self.installer.exec.register_secret(&s);
|
|
self.root_password = Some(s);
|
|
}
|
|
if let Some(v) = &patch.ai_api_key {
|
|
let s = SecretString::new(v.clone());
|
|
self.installer.exec.register_secret(&s);
|
|
self.api_key = Some(s);
|
|
}
|
|
if let Some(v) = &patch.opencode_password {
|
|
let s = SecretString::new(v.clone());
|
|
self.installer.exec.register_secret(&s);
|
|
self.opencode_password = Some(s);
|
|
}
|
|
// A credential change invalidates any previous AI validation.
|
|
self.validated_ai = None;
|
|
// Report only presence, never values.
|
|
Ok(json!({
|
|
"luks_set": self.luks.is_some(),
|
|
"user_password_set": self.user_password.is_some(),
|
|
"root_password_set": self.root_password.is_some(),
|
|
"ai_api_key_set": self.api_key.is_some(),
|
|
"opencode_password_set": self.opencode_password.is_some(),
|
|
}))
|
|
}
|
|
|
|
// -- AI -----------------------------------------------------------------
|
|
|
|
fn ai_check(&mut self) -> Result<Value, String> {
|
|
let facts = self.installer.system_facts();
|
|
let backend = self.installer.config.ai.backend;
|
|
let api_key = self.api_key.clone();
|
|
let opencode_password = self.opencode_password.clone();
|
|
let value = {
|
|
let Installer { exec, config, .. } = &mut self.installer;
|
|
let redactor = exec.redactor();
|
|
match backend {
|
|
AiBackend::OpenCode => {
|
|
let transport = opencode_transport(exec, config, opencode_password)?;
|
|
review_opencode(config, redactor, facts, &transport)?
|
|
}
|
|
AiBackend::Direct => {
|
|
let transport = CurlTransport::new(exec, api_key.clone());
|
|
review_proposal(config, redactor, facts, api_key.is_some(), &transport)?
|
|
}
|
|
}
|
|
};
|
|
self.approved_digest = None;
|
|
// Bind the validated interaction to the exact configuration it was
|
|
// validated against; any later change clears it.
|
|
self.validated_ai = Some(self.plan_digest());
|
|
Ok(value)
|
|
}
|
|
|
|
/// A real, minimal model interaction that obtains and validates a JSON model
|
|
/// response without changing the configuration. This is "Test connection".
|
|
fn ai_test(&mut self) -> Result<Value, String> {
|
|
use phoebus_ai::provider::{build_request, extract_content};
|
|
let backend = self.installer.config.ai.backend;
|
|
let facts = self.installer.system_facts();
|
|
let redactor = self.installer.exec.redactor();
|
|
let (kind, endpoint, model, label) = match backend {
|
|
AiBackend::OpenCode => {
|
|
let (server, provider, model) = opencode_parts(&self.installer.config)?;
|
|
(ProviderKind::Local, server, model, provider)
|
|
}
|
|
AiBackend::Direct => {
|
|
let raw = self.installer.config.ai.provider.clone();
|
|
let provider = ProviderKind::parse(&raw)
|
|
.ok_or_else(|| format!("unknown AI provider `{raw}`"))?;
|
|
if provider == ProviderKind::None {
|
|
return Err("no AI provider selected".into());
|
|
}
|
|
let endpoint = if self.installer.config.ai.endpoint.is_empty() {
|
|
provider.endpoint().to_string()
|
|
} else {
|
|
self.installer.config.ai.endpoint.clone()
|
|
};
|
|
let model = if self.installer.config.ai.model.is_empty() {
|
|
provider.default_model().to_string()
|
|
} else {
|
|
self.installer.config.ai.model.clone()
|
|
};
|
|
(provider, endpoint, model, provider.as_str().to_string())
|
|
}
|
|
};
|
|
let request = build_request(kind, &model, &facts);
|
|
let body = serde_json::to_string(&request)
|
|
.map_err(|e| format!("could not build the test request: {e}"))?;
|
|
let response = match backend {
|
|
AiBackend::OpenCode => {
|
|
let (server, provider, model) = opencode_parts(&self.installer.config)?;
|
|
let transport =
|
|
ExecOpenCodeTransport::new(&self.installer.exec, server, provider, model)
|
|
.with_auth(self.opencode_password.clone());
|
|
transport.send(kind, &endpoint, &body)
|
|
}
|
|
AiBackend::Direct => {
|
|
let transport = CurlTransport::new(&self.installer.exec, self.api_key.clone());
|
|
transport.send(kind, &endpoint, &body)
|
|
}
|
|
}
|
|
.map_err(|e| format!("connection failed: {}", redactor.redact(&e.to_string())))?;
|
|
let content = extract_content(&response).map_err(|e| {
|
|
format!(
|
|
"model response was not usable: {}",
|
|
redactor.redact(&e.to_string())
|
|
)
|
|
})?;
|
|
serde_json::from_str::<serde_json::Value>(&content)
|
|
.map_err(|_| "model response was not JSON".to_string())?;
|
|
Ok(json!({
|
|
"connected": true,
|
|
"backend": backend.as_str(),
|
|
"provider": label,
|
|
"model": model,
|
|
"response": content,
|
|
}))
|
|
}
|
|
|
|
/// Validate the provider connection and review the proposal (fail-closed).
|
|
/// Exposed so tests can drive it with a canned transport.
|
|
pub fn ai_check_with(&mut self, transport: &dyn ModelTransport) -> Result<Value, String> {
|
|
let facts = self.installer.system_facts();
|
|
let api_key_present = self.api_key.is_some();
|
|
let value = {
|
|
let Installer { exec, config, .. } = &mut self.installer;
|
|
review_proposal(config, exec.redactor(), facts, api_key_present, transport)?
|
|
};
|
|
self.approved_digest = None;
|
|
self.validated_ai = Some(self.plan_digest());
|
|
Ok(value)
|
|
}
|
|
|
|
// -- authorization and install ------------------------------------------
|
|
|
|
fn approve(&mut self, request: &Request) -> Result<Value, String> {
|
|
let phrase = request.erase.clone().unwrap_or_default();
|
|
if phrase != "ERASE" {
|
|
return Err("type ERASE exactly to authorize disk changes".into());
|
|
}
|
|
if request.final_confirm != Some(true) {
|
|
return Err("the final confirmation is required".into());
|
|
}
|
|
let digest = self.plan_digest();
|
|
self.approved_digest = Some(digest.clone());
|
|
Ok(json!({ "approved": true, "plan_digest": digest }))
|
|
}
|
|
|
|
fn start_install(&mut self, id: u64, request: &Request, out: &mut dyn Write) -> io::Result<()> {
|
|
let result = self.run_install(id, request, out);
|
|
match result {
|
|
Ok(data) => write_json(
|
|
out,
|
|
&json!({ "id": id, "ok": true, "op": "start_install", "data": data }),
|
|
),
|
|
Err(error) => write_json(
|
|
out,
|
|
&json!({ "id": id, "ok": false, "op": "start_install", "error": error }),
|
|
),
|
|
}
|
|
}
|
|
|
|
fn run_install(
|
|
&mut self,
|
|
id: u64,
|
|
request: &Request,
|
|
out: &mut dyn Write,
|
|
) -> Result<Value, String> {
|
|
if self.installing {
|
|
return Err("an installation is already in progress".into());
|
|
}
|
|
if self.installed {
|
|
return Err(
|
|
"this session has already installed Phoebus; start a new session to \
|
|
install again"
|
|
.into(),
|
|
);
|
|
}
|
|
// The plan may not have changed since the user approved it.
|
|
let current = self.plan_digest();
|
|
match (&self.approved_digest, &request.plan_digest) {
|
|
(Some(approved), Some(presented)) if approved == presented && presented == ¤t => {
|
|
}
|
|
_ => {
|
|
return Err(
|
|
"the installation plan is not approved (or changed since approval); \
|
|
review the plan and confirm ERASE again"
|
|
.into(),
|
|
)
|
|
}
|
|
}
|
|
|
|
// AI is mandatory to install unless this is a dry run or an explicit
|
|
// break-glass. A validated interaction is required: merely naming a
|
|
// provider is not enough. The validation is bound to the current
|
|
// configuration, so a change since validation invalidates it.
|
|
let dry_run = self.installer.config.runtime.dry_run;
|
|
if !dry_run {
|
|
let break_glass = std::env::var("PHOEBUS_NO_AI")
|
|
.map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "yes" | "true"))
|
|
.unwrap_or(false);
|
|
let validated = self.validated_ai.as_deref() == Some(current.as_str());
|
|
if !validated && !break_glass {
|
|
return Err(
|
|
"installing Phoebus requires a successful, validated AI interaction for \
|
|
the current configuration; connect and validate a model, or set \
|
|
PHOEBUS_NO_AI=1 for a deterministic install"
|
|
.into(),
|
|
);
|
|
}
|
|
}
|
|
|
|
let issues = self.installer.validate();
|
|
if !issues.is_empty() {
|
|
let text = issues
|
|
.iter()
|
|
.map(|i| i.to_string())
|
|
.collect::<Vec<_>>()
|
|
.join("; ");
|
|
return Err(format!("configuration is incomplete: {text}"));
|
|
}
|
|
|
|
let preview = self.installer.destructive_preview();
|
|
let confirm = BridgeConfirm {
|
|
erase: request.erase.as_deref() == Some("ERASE"),
|
|
final_ok: request.final_confirm == Some(true),
|
|
};
|
|
let auth = authorize(&confirm, &preview, "Start the installation now?")
|
|
.map_err(|e| self.installer.exec.redactor().redact(&e.to_string()))?;
|
|
|
|
let mut observer = JsonObserver {
|
|
out,
|
|
id,
|
|
phase: self.phase.clone(),
|
|
};
|
|
self.phase.set(DiskPhase::BeforeStorage);
|
|
// Consume the approval and mark the session busy before any destructive
|
|
// work: a replay or a second frontend can never reach storage_prepare.
|
|
self.approved_digest = None;
|
|
self.validated_ai = None;
|
|
self.installing = true;
|
|
let outcome = self.installer.install_observed(
|
|
&auth,
|
|
self.luks.as_ref(),
|
|
self.user_password.as_ref(),
|
|
self.root_password.as_ref(),
|
|
&mut observer,
|
|
);
|
|
self.installing = false;
|
|
|
|
match outcome {
|
|
Ok(()) => {
|
|
self.installed = true;
|
|
Ok(json!({
|
|
"complete": true,
|
|
"dry_run": dry_run,
|
|
"log_path": self.installer.exec.log_path().display().to_string(),
|
|
"next_actions": [
|
|
"Remove the installation medium.",
|
|
"Restart the computer and boot Phoebus OS.",
|
|
],
|
|
}))
|
|
}
|
|
Err(e) => {
|
|
let message = self.installer.exec.redactor().redact(&e.to_string());
|
|
let (disk_changed, next_actions) = disk_change_report(self.phase.get());
|
|
Err(format!(
|
|
"installation failed: {message}\n\
|
|
disk_changed: {disk_changed}\n\
|
|
next: {}",
|
|
next_actions.join(" ")
|
|
))
|
|
}
|
|
}
|
|
}
|
|
|
|
// -- helpers ------------------------------------------------------------
|
|
|
|
/// A stable digest binding an approval to the exact plan shown. Any change
|
|
/// to the configuration (including AI-applied changes) changes it.
|
|
fn plan_digest(&self) -> String {
|
|
config_digest(&self.installer.config)
|
|
}
|
|
|
|
fn review(&self) -> Value {
|
|
let c = &self.installer.config;
|
|
let mut subsystems = vec![c.system.init_system.clone()];
|
|
if c.desktop.profile.is_desktop() {
|
|
subsystems.push(c.desktop.audio_stack.clone());
|
|
if c.desktop.flatpak {
|
|
subsystems.push("flatpak".into());
|
|
}
|
|
}
|
|
if c.packages.nix {
|
|
subsystems.push("nix".into());
|
|
}
|
|
if c.storage.filesystem == phoebus_core::Filesystem::Btrfs {
|
|
subsystems.push("btrfs snapshots".into());
|
|
}
|
|
json!({
|
|
"target_disk": c.storage.disk,
|
|
"erase": self.installer.destructive_preview(),
|
|
"filesystem": c.storage.filesystem.as_str(),
|
|
"encryption": c.encryption.mode.as_str(),
|
|
"desktop": c.desktop.profile.as_str(),
|
|
"subvolumes": c.storage.subvols,
|
|
"subsystems": subsystems,
|
|
"hostname": c.system.hostname,
|
|
"username": c.user.username,
|
|
"timezone": c.system.timezone,
|
|
"locale": c.system.locale,
|
|
"keymap": c.system.keymap,
|
|
})
|
|
}
|
|
}
|
|
|
|
fn contains_secret_marker(toml: &str) -> bool {
|
|
let lower = toml.to_ascii_lowercase();
|
|
["passphrase", "password", "api_key", "secret"]
|
|
.iter()
|
|
.any(|m| lower.contains(m))
|
|
}
|
|
|
|
/// 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)]
|
|
enum DiskPhase {
|
|
BeforeStorage,
|
|
InStorage,
|
|
AfterStorage,
|
|
}
|
|
|
|
fn disk_change_report(phase: DiskPhase) -> (&'static str, Vec<&'static str>) {
|
|
match phase {
|
|
DiskPhase::BeforeStorage => (
|
|
"none",
|
|
vec!["Review the installer log, then retry the installation."],
|
|
),
|
|
DiskPhase::InStorage => (
|
|
"partial",
|
|
vec![
|
|
"The target disk may have been partially modified.",
|
|
"Review the installer log before retrying.",
|
|
],
|
|
),
|
|
DiskPhase::AfterStorage => (
|
|
"yes",
|
|
vec![
|
|
"The target disk was re-partitioned.",
|
|
"Review the installer log, then restart the installation (the disk is re-created from scratch).",
|
|
],
|
|
),
|
|
}
|
|
}
|
|
|
|
/// True when a default route exists. Read-only, no privileges.
|
|
fn network_ready() -> bool {
|
|
let Ok(text) = std::fs::read_to_string("/proc/net/route") else {
|
|
return false;
|
|
};
|
|
text.lines().skip(1).any(|line| {
|
|
let mut fields = line.split_whitespace();
|
|
let _iface = fields.next();
|
|
matches!(fields.next(), Some("00000000"))
|
|
})
|
|
}
|
|
|
|
fn iso_version() -> String {
|
|
if let Ok(text) = std::fs::read_to_string("/etc/phoebus/version") {
|
|
let t = text.trim();
|
|
if !t.is_empty() {
|
|
return t.to_string();
|
|
}
|
|
}
|
|
phoebus_core::VERSION.to_string()
|
|
}
|
|
|
|
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()
|
|
}
|
|
|
|
/// A deterministic digest of the configuration plus the step sequence. Any
|
|
/// material change to the plan changes the digest, invalidating an approval.
|
|
fn config_digest(config: &InstallConfig) -> String {
|
|
use sha2::{Digest, Sha256};
|
|
let mut hasher = Sha256::new();
|
|
hasher.update(config.to_toml_string().unwrap_or_default().as_bytes());
|
|
for step in InstallStep::sequence() {
|
|
hasher.update(step.name().as_bytes());
|
|
}
|
|
format!("{:x}", hasher.finalize())
|
|
}
|
|
|
|
/// The OpenCode server URL, provider id and model id, validated for presence.
|
|
fn opencode_parts(config: &InstallConfig) -> Result<(String, String, String), String> {
|
|
let server = config.ai.opencode_server.trim().to_string();
|
|
let provider = config.ai.opencode_provider.trim().to_string();
|
|
let model = config.ai.opencode_model.trim().to_string();
|
|
if server.is_empty() {
|
|
return Err("OpenCode requires a server URL".into());
|
|
}
|
|
if provider.is_empty() {
|
|
return Err("OpenCode requires a provider".into());
|
|
}
|
|
if model.is_empty() {
|
|
return Err("OpenCode requires a model".into());
|
|
}
|
|
// Fail fast on an unsafe endpoint, before any request is attempted.
|
|
phoebus_executor::opencode_server::Endpoint::parse(&server)
|
|
.map_err(|e| format!("invalid OpenCode endpoint: {e}"))?;
|
|
Ok((server, provider, model))
|
|
}
|
|
|
|
fn opencode_transport<'a>(
|
|
exec: &'a Exec,
|
|
config: &InstallConfig,
|
|
password: Option<SecretString>,
|
|
) -> Result<phoebus_executor::opencode_client::ExecOpenCodeTransport<'a>, String> {
|
|
let (server, provider, model) = opencode_parts(config)?;
|
|
Ok(
|
|
phoebus_executor::opencode_client::ExecOpenCodeTransport::new(
|
|
exec, server, provider, model,
|
|
)
|
|
.with_auth(password),
|
|
)
|
|
}
|
|
|
|
#[allow(clippy::too_many_arguments)]
|
|
fn finish_review(
|
|
config: &mut InstallConfig,
|
|
redactor: &phoebus_core::Redactor,
|
|
facts: SystemFacts,
|
|
kind: ProviderKind,
|
|
endpoint: &str,
|
|
provider_label: &str,
|
|
model: &str,
|
|
transport: &dyn ModelTransport,
|
|
backend: &str,
|
|
) -> Result<Value, String> {
|
|
let outcome =
|
|
ai_guide::generate_and_review_at(config, &facts, kind, endpoint, model, transport)
|
|
.map_err(|e| {
|
|
// Error messages are redacted before they reach the GUI.
|
|
format!(
|
|
"connection or proposal failed: {}",
|
|
redactor.redact(&e.to_string())
|
|
)
|
|
})?;
|
|
let applied: Vec<Value> = outcome
|
|
.applied
|
|
.iter()
|
|
.map(|c| {
|
|
json!({
|
|
"description": c.description,
|
|
"reason": c.reason,
|
|
"evidence": c.evidence,
|
|
})
|
|
})
|
|
.collect();
|
|
Ok(json!({
|
|
"connected": true,
|
|
"backend": backend,
|
|
"provider": provider_label,
|
|
"model": model,
|
|
"endpoint": endpoint,
|
|
"applied": applied,
|
|
"config": config,
|
|
"plan_digest": config_digest(config),
|
|
}))
|
|
}
|
|
|
|
/// OpenCode proposal review: the adapter talks the agent protocol and the
|
|
/// shared strict proposal parser/review applies the accepted changes.
|
|
fn review_opencode(
|
|
config: &mut InstallConfig,
|
|
redactor: &phoebus_core::Redactor,
|
|
facts: SystemFacts,
|
|
transport: &dyn ModelTransport,
|
|
) -> Result<Value, String> {
|
|
let (server, provider_id, model) = opencode_parts(config)?;
|
|
finish_review(
|
|
config,
|
|
redactor,
|
|
facts,
|
|
ProviderKind::Local,
|
|
&server,
|
|
&provider_id,
|
|
&model,
|
|
transport,
|
|
"opencode",
|
|
)
|
|
}
|
|
|
|
/// Parse the direct provider from the configuration, validate the connection
|
|
/// and apply the reviewed proposal. This is the same `ai_guide` path the TUI
|
|
/// uses.
|
|
fn review_proposal(
|
|
config: &mut InstallConfig,
|
|
redactor: &phoebus_core::Redactor,
|
|
facts: SystemFacts,
|
|
api_key_present: bool,
|
|
transport: &dyn ModelTransport,
|
|
) -> Result<Value, String> {
|
|
let raw = config.ai.provider.clone();
|
|
let provider =
|
|
ProviderKind::parse(&raw).ok_or_else(|| format!("unknown AI provider `{raw}`"))?;
|
|
if provider == ProviderKind::None {
|
|
return Err("no AI provider selected".into());
|
|
}
|
|
let endpoint = if config.ai.endpoint.is_empty() {
|
|
provider.endpoint().to_string()
|
|
} else {
|
|
config.ai.endpoint.clone()
|
|
};
|
|
let model = if config.ai.model.is_empty() {
|
|
provider.default_model().to_string()
|
|
} else {
|
|
config.ai.model.clone()
|
|
};
|
|
if provider.requires_key() && !api_key_present {
|
|
return Err(format!(
|
|
"provider `{}` requires an API key",
|
|
provider.as_str()
|
|
));
|
|
}
|
|
finish_review(
|
|
config,
|
|
redactor,
|
|
facts,
|
|
provider,
|
|
&endpoint,
|
|
provider.as_str(),
|
|
&model,
|
|
transport,
|
|
"direct",
|
|
)
|
|
}
|
|
|
|
/// The stdio entry point used by `--gui-bridge`.
|
|
pub fn run_stdio() -> io::Result<()> {
|
|
let mut config = InstallConfig::default();
|
|
// Test/automation hook: a dry run is non-destructive, so it is safe to
|
|
// expose through the environment for the harness. It never changes the
|
|
// authorization requirements.
|
|
if std::env::var("PHOEBUS_DRY_RUN")
|
|
.map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "yes" | "true"))
|
|
.unwrap_or(false)
|
|
{
|
|
config.runtime.dry_run = true;
|
|
}
|
|
let mut state_dir = std::path::PathBuf::from(&config.runtime.state_dir);
|
|
if std::fs::create_dir_all(&state_dir).is_err() {
|
|
state_dir = std::path::PathBuf::from("/tmp/phoebus-installer");
|
|
std::fs::create_dir_all(&state_dir).ok();
|
|
}
|
|
let logger = phoebus_executor::Logger::open(
|
|
state_dir.join("install.log"),
|
|
phoebus_core::Redactor::new(),
|
|
false,
|
|
);
|
|
let exec = Exec::new(
|
|
Box::new(phoebus_executor::RealRunner),
|
|
logger,
|
|
config.runtime.dry_run,
|
|
config.storage.install_root.clone(),
|
|
state_dir,
|
|
);
|
|
let mut bridge = Bridge::new(config, exec);
|
|
|
|
let stdin = io::stdin();
|
|
let stdout = io::stdout();
|
|
let mut out = stdout.lock();
|
|
for line in stdin.lock().lines() {
|
|
let line = line?;
|
|
bridge.handle_line(&line, &mut out)?;
|
|
if bridge.should_quit() {
|
|
break;
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use phoebus_ai::provider::TestTransport;
|
|
use phoebus_core::{Disk, DiskKind, Redactor};
|
|
use phoebus_executor::{Logger, RecordingRunner};
|
|
|
|
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_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 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"]
|
|
);
|
|
}
|
|
}
|