A fully-validated OpenCode install was refused at the final step because selecting a disk or setting the account/LUKS secrets cleared the AI validation. Bind the validation to a digest of only the AI connection settings: non-AI config changes preserve it, while an AI provider/model/ endpoint/server or AI-credential change invalidates it. Add regression tests and password-length placeholder hints.
2101 lines
75 KiB
Rust
2101 lines
75 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(),
|
|
"options" => self.options(),
|
|
"ai_catalog" => self.ai_catalog(),
|
|
"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,
|
|
}))
|
|
}
|
|
|
|
/// Selectable options for the language/region step. Reading these from the
|
|
/// live system means the user picks from the real timezones, locales and
|
|
/// keymaps instead of typing them from memory.
|
|
fn options(&self) -> Result<Value, String> {
|
|
Ok(json!({
|
|
"timezones": system_timezones(),
|
|
"locales": system_locales(),
|
|
"keymaps": system_keymaps(),
|
|
}))
|
|
}
|
|
|
|
/// The providers and models the configured AI connection actually offers:
|
|
/// the OpenCode catalog, or an OpenAI-compatible `/models` list. Read-only;
|
|
/// never returns provider credentials.
|
|
fn ai_catalog(&self) -> Result<Value, String> {
|
|
use phoebus_executor::opencode_client::{CurlHttpClient, HttpClient, OpenCodeClient};
|
|
use phoebus_executor::opencode_server::Endpoint;
|
|
|
|
let redact = self.installer.exec.redactor();
|
|
match self.installer.config.ai.backend {
|
|
AiBackend::OpenCode => {
|
|
// The catalog only needs the server; the model is optional.
|
|
let server = self.installer.config.ai.opencode_server.trim().to_string();
|
|
if server.is_empty() {
|
|
return Err("OpenCode requires a server URL".into());
|
|
}
|
|
let provider = self
|
|
.installer
|
|
.config
|
|
.ai
|
|
.opencode_provider
|
|
.trim()
|
|
.to_string();
|
|
let model = self.installer.config.ai.opencode_model.trim().to_string();
|
|
let endpoint = Endpoint::parse(&server)
|
|
.map_err(|e| format!("invalid OpenCode endpoint: {e}"))?;
|
|
let target = endpoint
|
|
.checked_target()
|
|
.map_err(|e| redact.redact(&e.to_string()))?;
|
|
let http = CurlHttpClient::new(&self.installer.exec);
|
|
// The provider catalog can be several MiB on a busy server.
|
|
let client = OpenCodeClient::new(&http, endpoint.base(), &provider, &model)
|
|
.with_auth(self.opencode_password.clone())
|
|
.with_max_body(16 * 1024 * 1024)
|
|
.with_resolve(Some((endpoint.host.clone(), endpoint.port, target.ip())));
|
|
match client.catalog() {
|
|
Ok(catalog) => {
|
|
let providers: Vec<Value> = catalog
|
|
.providers
|
|
.iter()
|
|
.map(
|
|
|p| json!({ "id": p.id, "name": p.name, "connected": p.connected }),
|
|
)
|
|
.collect();
|
|
let models = catalog
|
|
.providers
|
|
.iter()
|
|
.find(|p| p.id == provider)
|
|
.or_else(|| catalog.providers.iter().find(|p| !p.models.is_empty()))
|
|
.map(|p| p.models.clone())
|
|
.unwrap_or_default();
|
|
Ok(json!({
|
|
"backend": "opencode",
|
|
"providers": providers,
|
|
"models": models,
|
|
}))
|
|
}
|
|
Err(e) => Err(redact.redact(&e.to_string())),
|
|
}
|
|
}
|
|
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 url = models_url(&endpoint);
|
|
let mut request = phoebus_executor::opencode_client::HttpRequest::get(url);
|
|
request.auth_user = String::new(); // OpenAI-compatible: Bearer
|
|
request.auth = self.api_key.clone();
|
|
let http = CurlHttpClient::new(&self.installer.exec);
|
|
match http.request(&request) {
|
|
Ok(response) if response.is_success() => {
|
|
let models = parse_model_ids(&response.body);
|
|
Ok(json!({
|
|
"backend": "direct",
|
|
"providers": [ { "id": provider.as_str(), "name": provider.as_str(), "connected": true } ],
|
|
"models": models,
|
|
}))
|
|
}
|
|
Ok(response) => Err(format!("model list returned HTTP {}", response.status)),
|
|
Err(e) => Err(redact.redact(&e.to_string())),
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
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;
|
|
|
|
let ai_before = ai_digest(&self.installer.config);
|
|
self.installer.reconfigure(config);
|
|
self.approved_digest = None;
|
|
// Only a change to the AI connection settings invalidates the AI
|
|
// validation. Choosing a disk, typing a hostname or similar must not
|
|
// throw away a successful model interaction.
|
|
if ai_digest(&self.installer.config) != ai_before {
|
|
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);
|
|
}
|
|
let mut ai_credential_changed = false;
|
|
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);
|
|
ai_credential_changed = true;
|
|
}
|
|
if let Some(v) = &patch.opencode_password {
|
|
let s = SecretString::new(v.clone());
|
|
self.installer.exec.register_secret(&s);
|
|
self.opencode_password = Some(s);
|
|
ai_credential_changed = true;
|
|
}
|
|
// Only an AI credential change invalidates the AI validation; account
|
|
// and disk secrets do not.
|
|
if ai_credential_changed {
|
|
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(ai_digest(&self.installer.config));
|
|
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(ai_digest(&self.installer.config));
|
|
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(ai_digest(&self.installer.config).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))
|
|
}
|
|
|
|
/// Time zones offered by the live system, from the zoneinfo database.
|
|
fn system_timezones() -> Vec<String> {
|
|
let mut zones: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
|
|
if let Ok(text) = std::fs::read_to_string("/usr/share/zoneinfo/zone.tab") {
|
|
for line in text.lines() {
|
|
let line = line.trim();
|
|
if line.is_empty() || line.starts_with('#') {
|
|
continue;
|
|
}
|
|
if let Some(tz) = line.split_whitespace().nth(2) {
|
|
zones.insert(tz.to_string());
|
|
}
|
|
}
|
|
}
|
|
if zones.is_empty() {
|
|
for zone in [
|
|
"UTC",
|
|
"Europe/London",
|
|
"Europe/Berlin",
|
|
"Europe/Paris",
|
|
"America/New_York",
|
|
"America/Chicago",
|
|
"America/Denver",
|
|
"America/Los_Angeles",
|
|
"Asia/Tokyo",
|
|
"Asia/Shanghai",
|
|
"Asia/Kolkata",
|
|
"Australia/Sydney",
|
|
] {
|
|
zones.insert(zone.to_string());
|
|
}
|
|
}
|
|
zones.into_iter().take(2000).collect()
|
|
}
|
|
|
|
/// Locales from the system's i18n database (or a common fallback set).
|
|
fn system_locales() -> Vec<String> {
|
|
let mut locales: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
|
|
if let Ok(text) = std::fs::read_to_string("/usr/share/i18n/SUPPORTED") {
|
|
for line in text.lines() {
|
|
let line = line.trim();
|
|
if line.is_empty() || line.starts_with('#') {
|
|
continue;
|
|
}
|
|
if let Some(locale) = line.split_whitespace().next() {
|
|
// Prefer UTF-8 variants; keep the rest too.
|
|
locales.insert(locale.to_string());
|
|
}
|
|
}
|
|
}
|
|
if locales.is_empty() {
|
|
for locale in [
|
|
"en_US.UTF-8",
|
|
"en_GB.UTF-8",
|
|
"de_DE.UTF-8",
|
|
"fr_FR.UTF-8",
|
|
"es_ES.UTF-8",
|
|
"it_IT.UTF-8",
|
|
"pt_BR.UTF-8",
|
|
"ja_JP.UTF-8",
|
|
"zh_CN.UTF-8",
|
|
] {
|
|
locales.insert(locale.to_string());
|
|
}
|
|
}
|
|
locales.into_iter().take(2000).collect()
|
|
}
|
|
|
|
/// Console keymaps from the system's keymap trees.
|
|
fn system_keymaps() -> Vec<String> {
|
|
let mut keymaps: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
|
|
for root in ["/usr/share/keymaps", "/usr/share/kbd/keymaps"] {
|
|
collect_keymaps(std::path::Path::new(root), &mut keymaps, 0);
|
|
}
|
|
if keymaps.is_empty() {
|
|
// The live medium does not always ship the kbd keymap tree, so fall
|
|
// back to the common console keymaps. The combo still accepts a
|
|
// custom value.
|
|
for name in [
|
|
"us",
|
|
"us-acentos",
|
|
"uk",
|
|
"gb",
|
|
"de",
|
|
"de-latin1",
|
|
"de-latin1-nodeadkeys",
|
|
"de-nodeadkeys",
|
|
"fr",
|
|
"fr-latin9",
|
|
"fr-latin1",
|
|
"fr-pc",
|
|
"es",
|
|
"es-cp850",
|
|
"it",
|
|
"it2",
|
|
"pt",
|
|
"pt-latin1",
|
|
"nl",
|
|
"nl2",
|
|
"be",
|
|
"dk",
|
|
"dk-latin1",
|
|
"no",
|
|
"no-latin1",
|
|
"se",
|
|
"fi",
|
|
"is",
|
|
"ie",
|
|
"ie-Gaelic",
|
|
"pl",
|
|
"pl2",
|
|
"cz",
|
|
"cz-us-qwertz",
|
|
"sk",
|
|
"hu",
|
|
"hu101",
|
|
"ro",
|
|
"bg",
|
|
"gr",
|
|
"gr-pc",
|
|
"ru",
|
|
"ruwin_alt-UTF-8",
|
|
"ua-utf",
|
|
"tr",
|
|
"trq",
|
|
"il",
|
|
"ara",
|
|
"in",
|
|
"jp106",
|
|
"kr",
|
|
"kr-utf",
|
|
"cn",
|
|
"tw",
|
|
"br-abnt2",
|
|
"latam",
|
|
"ca",
|
|
"cf",
|
|
"ch",
|
|
"ch-fr",
|
|
"at",
|
|
"si",
|
|
"hr",
|
|
"ee",
|
|
"lt",
|
|
"lv",
|
|
"mk",
|
|
"rs",
|
|
"by",
|
|
"kz",
|
|
"us-dvorak",
|
|
"dvorak",
|
|
"colemak",
|
|
"mac-us",
|
|
"sun-pl",
|
|
"sg",
|
|
"th",
|
|
"vn",
|
|
"fa",
|
|
"az",
|
|
"ge",
|
|
"am",
|
|
] {
|
|
keymaps.insert(name.to_string());
|
|
}
|
|
}
|
|
keymaps.into_iter().take(2000).collect()
|
|
}
|
|
|
|
fn collect_keymaps(
|
|
dir: &std::path::Path,
|
|
out: &mut std::collections::BTreeSet<String>,
|
|
depth: usize,
|
|
) {
|
|
if depth > 6 {
|
|
return;
|
|
}
|
|
let Ok(entries) = std::fs::read_dir(dir) else {
|
|
return;
|
|
};
|
|
for entry in entries.flatten() {
|
|
let path = entry.path();
|
|
if path.is_dir() {
|
|
collect_keymaps(&path, out, depth + 1);
|
|
} else if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
|
|
for suffix in [".map.gz", ".map"] {
|
|
if let Some(stem) = name.strip_suffix(suffix) {
|
|
out.insert(stem.to_string());
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The OpenAI-compatible model-list URL for a chat-completions endpoint.
|
|
fn models_url(endpoint: &str) -> String {
|
|
let trimmed = endpoint.trim().trim_end_matches('/');
|
|
if let Some(base) = trimmed.strip_suffix("/chat/completions") {
|
|
format!("{base}/models")
|
|
} else {
|
|
format!("{trimmed}/models")
|
|
}
|
|
}
|
|
|
|
/// Extract model ids from an OpenAI-compatible `/models` response.
|
|
fn parse_model_ids(body: &str) -> Vec<String> {
|
|
let mut ids: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
|
|
if let Ok(value) = serde_json::from_str::<Value>(body) {
|
|
if let Some(data) = value.get("data").and_then(|d| d.as_array()) {
|
|
for item in data {
|
|
if let Some(id) = item.get("id").and_then(|v| v.as_str()) {
|
|
ids.insert(id.to_string());
|
|
}
|
|
}
|
|
}
|
|
if ids.is_empty() {
|
|
if let Some(models) = value.get("models").and_then(|m| m.as_array()) {
|
|
for item in models {
|
|
if let Some(id) = item
|
|
.get("id")
|
|
.and_then(|v| v.as_str())
|
|
.or_else(|| item.get("name").and_then(|v| v.as_str()))
|
|
{
|
|
ids.insert(id.to_string());
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
ids.into_iter().collect()
|
|
}
|
|
|
|
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",
|
|
)
|
|
}
|
|
|
|
/// A deterministic digest of only the AI connection settings. The mandatory-AI
|
|
/// validation is bound to this, so choosing a disk or typing an account
|
|
/// password does not discard a successful model interaction, while changing the
|
|
/// provider, model, endpoint or server does.
|
|
fn ai_digest(config: &InstallConfig) -> String {
|
|
use sha2::{Digest, Sha256};
|
|
let ai = &config.ai;
|
|
let mut hasher = Sha256::new();
|
|
for field in [
|
|
ai.backend.as_str(),
|
|
ai.provider.as_str(),
|
|
ai.model.as_str(),
|
|
ai.endpoint.as_str(),
|
|
ai.opencode_server.as_str(),
|
|
ai.opencode_provider.as_str(),
|
|
ai.opencode_model.as_str(),
|
|
] {
|
|
hasher.update(field.as_bytes());
|
|
hasher.update([0u8]);
|
|
}
|
|
format!("{:x}", hasher.finalize())
|
|
}
|
|
|
|
/// 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_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"]
|
|
);
|
|
}
|
|
}
|