From 67fddf12995fb06b912d6aa4f90504967f62842d Mon Sep 17 00:00:00 2001 From: Phoebus Date: Sat, 3 Oct 2026 15:06:34 -0700 Subject: [PATCH] feat(sys): review and enable scoped external overlays --- docs/CHANGELOG.md | 13 + docs/HANDOFF.md | 21 + docs/STATUS.md | 19 + docs/SYS.md | 24 +- installer-rs/Cargo.lock | 7 + .../crates/phoebus-core/src/action.rs | 81 +++ .../crates/phoebus-executor/Cargo.toml | 1 + .../crates/phoebus-executor/src/actions.rs | 20 + .../crates/phoebus-executor/src/lib.rs | 1 + .../crates/phoebus-executor/src/overlay.rs | 525 ++++++++++++++++++ .../crates/phoebus-executor/src/portage.rs | 1 + .../phoebus-installer/src/assistant_bridge.rs | 93 ++-- .../crates/phoebus-installer/src/bin/sys.rs | 97 +++- .../phoebus-installer/src/service/mod.rs | 18 +- .../phoebus-installer/src/service/plan.rs | 78 ++- .../phoebus-installer/src/service/tests.rs | 46 +- .../phoebus-assistant/AssistantBridge.qml | 4 + .../live/desktop/phoebus-assistant/shell.qml | 62 ++- 18 files changed, 1064 insertions(+), 47 deletions(-) create mode 100644 installer-rs/crates/phoebus-executor/src/overlay.rs diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index beed0ea..a4c0b6c 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -5,6 +5,19 @@ this file is the curated, human-readable summary. ## Unreleased — Fast defaults with user-controlled source builds +- **Reviewed external overlay registration (2026-10-03).** `sys overlay + review ` resolves GPO leads through Gentoo's overlay + registry and inspects each live Git repository, exact ebuild hash, amd64 + keywords and Manifest. `sys overlay enable ` + stages a revision-bound approval and the privileged broker rechecks it before + cloning. Portage policy masks the rest of the overlay, scopes `~amd64` to the + chosen atom, and registers normal auto-sync. The Assistant's exact GPO-link + path now presents selectable options and a registration plan. Package + installation remains a separate review. The registry and hashes are factual + evidence, not a guarantee of publisher trust. The read-only CLI discovery and + Assistant option/plan flow were checked in a disposable VM; privileged + repository registration has not yet been VM-verified. + - **GPO link handling (2026-10-03).** The Assistant now recognizes a GPO package URL, checks whether Portage can resolve that exact atom locally, and reports the external listing as an unverified lead when it cannot. diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index 5c030a6..1fd922b 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -3,6 +3,27 @@ Rolling note between work sessions. **Update this file before you finish**, then commit it. It should be short and current; use `git log` for detail. +- **External overlay registration (2026-10-03):** The next user request asked + `sys` to discover compatible third-party repositories, offer a choice, then + add and keep the accepted repository synced. A deterministic review now + intersects GPO leads with the Gentoo registry and inspects each repository's + actual Git name, commit, exact ebuild SHA-256, amd64 keywords and Manifest. + `sys overlay review` lists options; `sys overlay enable` stages an approval + that the privileged broker revalidates before cloning. Portage configuration + masks all packages from that repository except the selected atom and scopes + `~amd64` if needed; `auto-sync = yes` makes normal Portage syncs refresh it. + The Assistant's exact GPO link now shows selectable options and stages the + same approved plan. Host and disposable VM read-only discovery found gentoo-zh, + nest and ruizhi-overlay for `app-misc/chatgpt-desktop`. The VM Assistant + displayed all three, staged a ruizhi-overlay plan with distinct details, and + canceled it. No repository or package was installed. VM testing used a + user-local static `sys` and test-only Assistant bridge path override because + the system-installed bridge still targets `/usr/local/bin/sys`. The first VM + lookup timed out; retry succeeded. `make check` and the dynamic/static release + builds passed. Privileged registration remains unverified; use only a + disposable VM if testing that path. A listing and hash do not establish + publisher trust or future update safety. + - **GPO link and read-only approval correction (2026-10-03):** The user's `https://gpo.zugaina.org/app-misc/chatgpt-desktop` follow-up was handled by the model as a general administration plan that offered approval to inspect diff --git a/docs/STATUS.md b/docs/STATUS.md index 8c1c64b..fbe587f 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -48,6 +48,25 @@ disposable VM; `serial-driver.py recovery` now automates the same check. ## Matrix +External overlay registration (2026-10-03): `sys overlay review` now performs +bounded GPO and Gentoo registry lookups, clones candidate Git repositories into +temporary review directories, and reports exact revisions, ebuild SHA-256, +keywords and Manifest presence. `sys overlay enable` stages a digest-bound +plan; the broker rechecks the live source and refuses drift before adding the +repository. The policy masks all other overlay packages and scopes any +`~amd64` allowance to the selected atom. Assistant GPO links now display +selectable options. **Implemented, unit tested, and reviewed in the disposable +VM through the non-mutating CLI and graphical selection/plan path. Privileged +repository registration remains unverified.** In the VM, the read-only CLI and +Assistant found gentoo-zh, nest and ruizhi-overlay for +`app-misc/chatgpt-desktop`, all registry-listed as experimental/unofficial; +gentoo-zh offered `26.930.31730` at commit `9232e69f…`. The Assistant displayed +the three choices, staged a ruizhi-overlay plan with distinct details, and +canceled it. No overlay or package was enabled on the host or VM. The first VM +lookup hit a three-second connection timeout; retry succeeded. The guest used +a user-local `sys` binary and a test-only Assistant bridge path override; +the system-installed binary has not been replaced. + GPO package links and read-only Assistant results (2026-10-03): a GPO URL now triggers an exact Portage resolution check and a bounded external GPO lookup. If the atom is only an external lead, the Assistant explains that a diff --git a/docs/SYS.md b/docs/SYS.md index 11fb3c9..3d8837a 100644 --- a/docs/SYS.md +++ b/docs/SYS.md @@ -366,6 +366,8 @@ sys search firefox --legacy # every source sys search firefox --legacy --flatpak # one source sys search firefox --legacy --appimage # managed images + community catalog leads sys search chatgpt --legacy --overlays --portage # configured Portage + external GPO leads +sys overlay review app-misc/chatgpt-desktop # inspect listed repos and current ebuilds +sys overlay enable app-misc/chatgpt-desktop gentoo-zh # stage, review, approve, register sys list --legacy # installed inventory, all lanes sys list vim --legacy --portage # inventory, source + text filter sys info firefox --legacy # version/source/status/deps/size @@ -386,10 +388,26 @@ first, and accept `~amd64` only for a specific package if needed. The external lookup has an eight-second limit; a network failure leaves local results available. `--overlays` is restricted to deterministic `search --legacy` and cannot be combined with a non-Portage source flag. +`sys overlay review category/package` follows each GPO lead to Gentoo's +repository registry, then inspects the live Git repository name, commit, exact +ebuild SHA-256, `amd64` keywords, and package Manifest. It presents only options +that pass these checks. The registry explicitly calls many repositories +**unofficial** and **experimental**; listing and hashes do not prove publisher +trust. `sys overlay enable category/package repository` repeats discovery and +stages an exact revision-bound plan. After approval, the broker rechecks the +registry, commit and ebuild, clones the repository, masks every package in it +except the selected atom, adds a package-scoped `~amd64` allowance when needed, +and registers it with `auto-sync = yes`. A normal `emerge --sync` refreshes the +repository; `sys updates` still checks the last synced metadata. Installing or +updating the package itself requires a separate reviewed Portage plan. If the +source changes between review and execution, the broker refuses the stale plan. +Only the running system (`/`) supports this external review and registration. + In the desktop Assistant, pasting a `https://gpo.zugaina.org/category/package` -link checks that exact atom against configured Portage sources and the GPO -index. An external-only match is reported as information, with no install -approval: a reviewed repository must be registered and synced first. +link checks that exact atom against configured Portage sources. If absent, it +shows eligible overlay options with their source, revision and ebuild digest. +Selecting one stages its registration plan; it never installs the package from +the GPO listing. The same broker handles the Assistant approval and CLI plan. AppImage searches include Phoebus-managed images and read-only leads from the AppImage project's community catalog when online. Leads show a catalog page diff --git a/installer-rs/Cargo.lock b/installer-rs/Cargo.lock index 30d314a..3720937 100644 --- a/installer-rs/Cargo.lock +++ b/installer-rs/Cargo.lock @@ -510,6 +510,7 @@ version = "0.1.0" dependencies = [ "phoebus-ai", "phoebus-core", + "roxmltree", "serde", "serde_json", "sha2", @@ -611,6 +612,12 @@ dependencies = [ "bitflags", ] +[[package]] +name = "roxmltree" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" + [[package]] name = "rustix" version = "0.38.44" diff --git a/installer-rs/crates/phoebus-core/src/action.rs b/installer-rs/crates/phoebus-core/src/action.rs index 52da4ee..30f94df 100644 --- a/installer-rs/crates/phoebus-core/src/action.rs +++ b/installer-rs/crates/phoebus-core/src/action.rs @@ -25,6 +25,23 @@ pub enum Risk { High, } +/// Exact external repository and ebuild selected during an overlay review. +/// The broker rediscovers this tuple before any mutation. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct OverlayReview { + pub atom: String, + pub repository: String, + pub source: String, + pub commit: String, + pub ebuild: String, + pub ebuild_sha256: String, + pub keywords: String, + pub needs_keyword: bool, + pub registry_quality: String, + pub manifest_present: bool, +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)] pub enum SystemAction { @@ -67,6 +84,10 @@ pub enum SystemAction { #[serde(default, skip_serializing_if = "Option::is_none")] backend: Option, }, + /// Enable one reviewed external repository for one exact package only. + EnableOverlay { + review: OverlayReview, + }, /// Install a sandboxed Flatpak application from flathub. FlatpakInstall { app_id: String, @@ -362,6 +383,10 @@ impl SystemAction { Some(backend) => format!("search {} for `{query}`", backend.as_str()), None => format!("search all package sources for `{query}`"), }, + SystemAction::EnableOverlay { review } => format!( + "enable external overlay {} for {} at {}", + review.repository, review.atom, review.commit + ), SystemAction::FlatpakInstall { app_id } => { format!("install Flatpak app {app_id} from flathub") } @@ -592,6 +617,7 @@ impl SystemAction { | SystemAction::AppImageUpdate { .. } | SystemAction::AppImageRemove { .. } | SystemAction::UpdateSystem + | SystemAction::EnableOverlay { .. } | SystemAction::ApplyUpdates { .. } | SystemAction::Depclean | SystemAction::Undo { .. } @@ -670,6 +696,7 @@ impl SystemAction { | SystemAction::InspectPackage { .. } | SystemAction::RemovePackage { .. } | SystemAction::UpdateSystem + | SystemAction::EnableOverlay { .. } | SystemAction::PrepareUpdates | SystemAction::InspectUpdates | SystemAction::PackageOwners { .. } @@ -742,6 +769,60 @@ impl SystemAction { Err(format!("invalid search query: {query}")) } } + SystemAction::EnableOverlay { review } => { + let Some((category, package)) = review.atom.split_once('/') else { + return Err("invalid overlay package atom".into()); + }; + let valid_name = |s: &str| { + !s.is_empty() + && s.len() <= 80 + && !s.starts_with('-') + && !s.contains("..") + && s.bytes().all(|b| { + b.is_ascii_lowercase() || b.is_ascii_digit() || b"+_.-".contains(&b) + }) + }; + if !valid_name(category) + || !valid_name(package) + || !valid_name(&review.repository) + || !review.source.starts_with("https://") + || review.source.len() > 256 + || review + .source + .contains(['@', '?', '#', '\n', '\r', ' ', '\\']) + || review.source.contains("..") + || !review.source[8..].contains('/') + || review.commit.len() != 40 + || !review.commit.bytes().all(|b| b.is_ascii_hexdigit()) + || review.ebuild_sha256.len() != 64 + || !review.ebuild_sha256.bytes().all(|b| b.is_ascii_hexdigit()) + || !review + .ebuild + .starts_with(&format!("{}/{}-", review.atom, package)) + || !review.ebuild.ends_with(".ebuild") + || !review.ebuild.bytes().all(|b| { + b.is_ascii_lowercase() || b.is_ascii_digit() || b"/+_.-".contains(&b) + }) + || review.keywords.len() > 128 + || !review.keywords.bytes().all(|b| { + b.is_ascii_lowercase() || b.is_ascii_digit() || b"~*-_ ".contains(&b) + }) + || !review + .registry_quality + .bytes() + .all(|b| b.is_ascii_lowercase()) + || review.registry_quality.len() > 32 + { + return Err("invalid external overlay review".into()); + } + let words: Vec<&str> = review.keywords.split_whitespace().collect(); + if (review.needs_keyword && !words.contains(&"~amd64")) + || (!review.needs_keyword && !words.contains(&"amd64")) + { + return Err("overlay architecture review does not match keywords".into()); + } + Ok(()) + } SystemAction::FlatpakInstall { app_id } | SystemAction::FlatpakRemove { app_id } => { if valid_flatpak_app_id(app_id) { Ok(()) diff --git a/installer-rs/crates/phoebus-executor/Cargo.toml b/installer-rs/crates/phoebus-executor/Cargo.toml index 337cc81..f088f23 100644 --- a/installer-rs/crates/phoebus-executor/Cargo.toml +++ b/installer-rs/crates/phoebus-executor/Cargo.toml @@ -15,6 +15,7 @@ zeroize.workspace = true toml.workspace = true tempfile.workspace = true sha2 = "0.10" +roxmltree = "0.20" [dev-dependencies] tempfile.workspace = true diff --git a/installer-rs/crates/phoebus-executor/src/actions.rs b/installer-rs/crates/phoebus-executor/src/actions.rs index 8372257..6cb2ae5 100644 --- a/installer-rs/crates/phoebus-executor/src/actions.rs +++ b/installer-rs/crates/phoebus-executor/src/actions.rs @@ -62,6 +62,20 @@ pub fn preview(action: &SystemAction) -> String { // (exact packages, expected time, temporary disk, power/network, // proposed changes) so the explicit approval step is informed. match action { + SystemAction::EnableOverlay { review } => { + out.push_str(&format!( + " source: {}\n commit: {}\n ebuild: {}\n ebuild SHA-256: {}\n keywords: {}\n registry quality: {} (unofficial)\n scope: only {} from {}\n", + review.source, + review.commit, + review.ebuild, + review.ebuild_sha256, + review.keywords, + review.registry_quality, + review.atom, + review.repository + )); + out.push_str(" Source listing and hash do not prove publisher trust.\n"); + } SystemAction::ConvertToSource { app } => { if let Some(conv) = phoebus_core::fastinstall::source_conversion(app) { out.push('\n'); @@ -1406,6 +1420,12 @@ pub fn execute_inner( )?; format!("removed {atom} (Portage)") } + SystemAction::EnableOverlay { review } => crate::overlay::enable( + exec, + auth.ok_or_else(|| ExecError::NotAuthorized(action.describe()))?, + root, + review, + )?, SystemAction::SearchPackages { query, backend } => { crate::query::search(exec, root, query, *backend).render() } diff --git a/installer-rs/crates/phoebus-executor/src/lib.rs b/installer-rs/crates/phoebus-executor/src/lib.rs index 457cc0f..7a2ec20 100644 --- a/installer-rs/crates/phoebus-executor/src/lib.rs +++ b/installer-rs/crates/phoebus-executor/src/lib.rs @@ -28,6 +28,7 @@ pub mod nix; pub mod opencode; pub mod opencode_client; pub mod opencode_server; +pub mod overlay; pub mod personal; pub mod portage; pub mod proactive; diff --git a/installer-rs/crates/phoebus-executor/src/overlay.rs b/installer-rs/crates/phoebus-executor/src/overlay.rs new file mode 100644 index 0000000..df19631 --- /dev/null +++ b/installer-rs/crates/phoebus-executor/src/overlay.rs @@ -0,0 +1,525 @@ +//! Review and registration of one package from an external Portage repository. +//! GPO supplies leads; Gentoo's repository registry supplies the source URL. +//! Neither listing is an endorsement or a substitute for reviewing the ebuild. + +use std::path::Path; + +use phoebus_core::action::OverlayReview; +use phoebus_core::TargetRoot; +use sha2::{Digest, Sha256}; + +use crate::command::{CommandOutput, CommandSpec}; +use crate::error::{ExecError, Result}; +use crate::exec::Exec; + +const REGISTRY: &str = "https://api.gentoo.org/overlays/repositories.xml"; +const MAX_REGISTRY: usize = 512 * 1024; +const MAX_GPO: usize = 512 * 1024; + +fn error(operation: &str, reason: impl Into) -> ExecError { + ExecError::operation("overlay", operation, reason.into()) +} + +pub fn valid_atom(atom: &str) -> bool { + let Some((category, package)) = atom.split_once('/') else { + return false; + }; + [category, package].iter().all(|part| { + !part.is_empty() + && part.len() <= 80 + && !part.starts_with('-') + && !part.contains("..") + && part + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"+_.-".contains(&b)) + }) +} + +fn valid_repository(name: &str) -> bool { + !name.is_empty() + && name.len() <= 80 + && !name.starts_with('-') + && !name.contains("..") + && name + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"+_.-".contains(&b)) +} + +fn valid_source(source: &str) -> bool { + source.starts_with("https://") + && source.len() <= 256 + && !source.contains(['@', '?', '#', '\n', '\r', ' ', '\\']) + && !source.contains("..") + && source[8..].contains('/') +} + +fn capture(exec: &Exec, operation: &str, program: &str, args: &[&str]) -> Result { + exec.run_capture(CommandSpec::new("overlay", operation, program).args(args.iter().copied())) +} + +fn fetch(exec: &Exec, url: &str, limit: usize) -> Result { + let limit_text = limit.to_string(); + let out = capture( + exec, + "read external overlay metadata", + "curl", + &[ + "--fail", + "--silent", + "--show-error", + "--proto", + "=https", + "--proto-redir", + "=https", + "--connect-timeout", + "3", + "--max-time", + "12", + "--max-filesize", + &limit_text, + url, + ], + )?; + if !out.success || out.stdout.len() > limit { + return Err(error( + "fetch", + "external metadata could not be read within limits", + )); + } + String::from_utf8(out.stdout).map_err(|_| error("fetch", "external metadata is not UTF-8")) +} + +fn gpo_repositories(html: &str) -> Vec { + let mut names: Vec = html + .split("href=\"/Overlays/") + .skip(1) + .filter_map(|part| part.split_once('"').map(|(name, _)| name.to_string())) + .filter(|name| valid_repository(name)) + .collect(); + names.sort(); + names.dedup(); + names.truncate(12); + names +} + +fn registry_source(xml: &str, name: &str) -> Result<(String, String)> { + // Gentoo declares an external DTD for this file. We need no DTD features; + // remove only that exact declaration and keep entity processing disabled. + let without_dtd = xml.replace( + "", + "", + ); + let document = roxmltree::Document::parse(&without_dtd) + .map_err(|e| error("parse Gentoo overlay registry", e.to_string()))?; + for repo in document.descendants().filter(|n| n.has_tag_name("repo")) { + if repo + .children() + .find(|n| n.has_tag_name("name")) + .and_then(|n| n.text()) + != Some(name) + { + continue; + } + let source = repo + .children() + .filter(|n| n.has_tag_name("source") && n.attribute("type") == Some("git")) + .filter_map(|n| n.text()) + .find(|s| valid_source(s)) + .ok_or_else(|| error("registry lookup", "no HTTPS Git source in registry"))?; + return Ok(( + source.to_string(), + repo.attribute("quality").unwrap_or("unrated").to_string(), + )); + } + Err(error( + "registry lookup", + format!("{name} is absent from Gentoo's overlay registry"), + )) +} + +fn git_capture(exec: &Exec, operation: &str, args: &[&str]) -> Result { + let spec = CommandSpec::new("overlay", operation, "timeout") + .args(["40s", "git"]) + .args(args.iter().copied()) + .env("GIT_TERMINAL_PROMPT", "0") + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_CONFIG_SYSTEM", "/dev/null") + .env("GIT_LFS_SKIP_SMUDGE", "1") + .env("GIT_HTTP_LOW_SPEED_LIMIT", "1024") + .env("GIT_HTTP_LOW_SPEED_TIME", "10"); + let out = exec.run_capture(spec)?; + if !out.success || out.stdout.len() > 256 * 1024 { + return Err(error( + operation, + "Git inspection failed or returned too much data", + )); + } + String::from_utf8(out.stdout).map_err(|_| error(operation, "Git output is not UTF-8")) +} + +fn inspect_repository( + exec: &Exec, + atom: &str, + repository: &str, + source: &str, + quality: &str, +) -> Result { + let temporary = tempfile::tempdir().map_err(|e| error("temporary review", e.to_string()))?; + let path = temporary.path().join("repository"); + let path_text = path.to_string_lossy().to_string(); + git_capture( + exec, + "clone repository for review", + &[ + "-c", + "protocol.file.allow=never", + "-c", + "http.followRedirects=false", + "clone", + "--quiet", + "--depth=1", + "--filter=blob:none", + "--no-checkout", + "--", + source, + &path_text, + ], + )?; + let commit = git_capture( + exec, + "read repository revision", + &["-C", &path_text, "rev-parse", "HEAD"], + )? + .trim() + .to_string(); + if commit.len() != 40 || !commit.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err(error("read repository revision", "invalid Git commit")); + } + let repo_name = git_capture( + exec, + "check repository identity", + &["-C", &path_text, "show", "HEAD:profiles/repo_name"], + )?; + if repo_name.trim() != repository { + return Err(error( + "check repository identity", + "repository name differs from registry name", + )); + } + let paths = git_capture( + exec, + "find exact package ebuilds", + &[ + "-C", + &path_text, + "ls-tree", + "-r", + "--name-only", + "HEAD", + atom, + ], + )?; + let prefix = format!("{atom}/"); + let package = atom.rsplit('/').next().unwrap_or(""); + let ebuilds: Vec<&str> = paths + .lines() + .filter(|p| p.starts_with(&prefix) && p.ends_with(".ebuild")) + .filter(|p| { + p.rsplit('/') + .next() + .unwrap_or("") + .starts_with(&format!("{package}-")) + }) + .filter(|p| !p.ends_with("-9999.ebuild")) + .filter(|p| { + p.bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"/+_.-".contains(&b)) + }) + .collect(); + let sorted = exec.run_capture( + CommandSpec::new("overlay", "choose latest non-live ebuild", "sort") + .arg("-V") + .stdin(ebuilds.join("\n")), + )?; + let sorted = String::from_utf8(sorted.stdout) + .map_err(|_| error("choose ebuild", "version sort output is not UTF-8"))?; + let ebuild = sorted + .lines() + .last() + .ok_or_else(|| { + error( + "find package", + format!("{atom} has no ebuild in {repository}"), + ) + })? + .to_string(); + let content = git_capture( + exec, + "inspect exact ebuild", + &["-C", &path_text, "show", &format!("HEAD:{ebuild}")], + )?; + let keywords = content + .lines() + .find_map(|line| line.trim().strip_prefix("KEYWORDS=")) + .map(|s| s.trim().trim_matches(['\'', '"']).to_string()) + .ok_or_else(|| error("check architecture", "ebuild has no static KEYWORDS line"))?; + let supported: Vec<&str> = keywords.split_whitespace().collect(); + let needs_keyword = if supported.contains(&"amd64") { + false + } else if supported.contains(&"~amd64") { + true + } else { + return Err(error("check architecture", "ebuild does not keyword amd64")); + }; + let hash = format!("{:x}", Sha256::digest(content.as_bytes())); + let manifest_present = paths.lines().any(|p| p == format!("{atom}/Manifest")); + if !manifest_present { + return Err(error( + "check Manifest", + "package has no Manifest for distfile checks", + )); + } + Ok(OverlayReview { + atom: atom.to_string(), + repository: repository.to_string(), + source: source.to_string(), + commit, + ebuild, + ebuild_sha256: hash, + keywords, + needs_keyword, + registry_quality: quality.to_string(), + manifest_present, + }) +} + +/// Discover exact, architecture-compatible options. Each repository is +/// inspected independently; one broken lead cannot hide a usable option. +pub fn discover(exec: &Exec, root: &Path, atom: &str) -> Result> { + if root != Path::new("/") { + return Err(error( + "discover", + "external overlay review requires the running system", + )); + } + if !valid_atom(atom) { + return Err(error("discover", "expected an exact category/package atom")); + } + let gpo = fetch(exec, &format!("https://gpo.zugaina.org/{atom}"), MAX_GPO)?; + let names = gpo_repositories(&gpo); + if names.is_empty() { + return Err(error("discover", "GPO lists no repositories for this atom")); + } + let registry = fetch(exec, REGISTRY, MAX_REGISTRY)?; + let mut reviews = Vec::new(); + let mut rejected = Vec::new(); + for name in names { + match registry_source(®istry, &name) + .and_then(|(source, quality)| inspect_repository(exec, atom, &name, &source, &quality)) + { + Ok(review) => reviews.push(review), + Err(reason) => rejected.push(format!("{name}: {reason}")), + } + } + if reviews.is_empty() { + return Err(error( + "discover", + format!( + "no listed repository passed identity, ebuild and amd64 checks: {}", + rejected.join("; ") + ), + )); + } + reviews.sort_by(|a, b| a.repository.cmp(&b.repository)); + Ok(reviews) +} + +/// Re-discover at the privileged boundary and refuse a changed source or +/// ebuild. The selected option is bound by the approved plan digest. +pub fn enable( + exec: &Exec, + _auth: &crate::auth::DestructiveAuthorization, + root: &Path, + selected: &OverlayReview, +) -> Result { + if root != Path::new("/") { + return Err(error( + "enable", + "external overlays can only be enabled on the running system", + )); + } + let current = discover(exec, root, &selected.atom)? + .into_iter() + .find(|r| r.repository == selected.repository) + .ok_or_else(|| error("enable", "reviewed repository is no longer available"))?; + if ¤t != selected { + return Err(error( + "enable", + "repository or ebuild changed since approval; review again", + )); + } + let target = TargetRoot::new(root); + let repo_rel = format!("var/db/repos/{}", selected.repository); + let repo_path = target.resolve(&repo_rel)?; + let conf_rel = format!( + "etc/portage/repos.conf/phoebus-{}.conf", + selected.repository + ); + let conf_path = target.resolve(&conf_rel)?; + if repo_path.exists() || conf_path.exists() { + return Err(error( + "enable", + "repository or Phoebus configuration already exists", + )); + } + target.ensure_dir("var/db/repos")?; + let repo_path_text = repo_path.to_string_lossy().to_string(); + git_capture( + exec, + "add reviewed repository", + &[ + "-c", + "protocol.file.allow=never", + "-c", + "http.followRedirects=false", + "clone", + "--quiet", + "--depth=1", + "--filter=blob:none", + "--", + &selected.source, + &repo_path_text, + ], + )?; + let actual = git_capture( + exec, + "verify added revision", + &["-C", &repo_path_text, "rev-parse", "HEAD"], + )?; + if actual.trim() != selected.commit { + return Err(error( + "enable", + "repository changed while cloning; configuration was not written", + )); + } + write_policy(&target, selected)?; + crate::portage::normalize_config_permissions(root); + Ok(format!( + "enabled {} at {} for {} only; normal Portage syncs will update the repository. Install the package through a separate reviewed `sys install` plan.", + selected.repository, selected.commit, selected.atom + )) +} + +fn write_policy(target: &TargetRoot, selected: &OverlayReview) -> Result<()> { + // The entire repository is masked; only the approved atom can be selected. + // Normal Portage syncs update this repository because auto-sync is enabled. + let conf = format!( + "[{}]\nlocation = /var/db/repos/{}\nsync-type = git\nsync-uri = {}\nauto-sync = yes\n", + selected.repository, selected.repository, selected.source + ); + target.write( + &format!("etc/portage/package.mask/phoebus-{}", selected.repository), + format!( + "# Only the reviewed {} may be selected from this repository.\n*/*::{}\n", + selected.atom, selected.repository + ), + )?; + target.write( + &format!("etc/portage/package.unmask/phoebus-{}", selected.repository), + format!("{}::{}\n", selected.atom, selected.repository), + )?; + if selected.needs_keyword { + target.write( + &format!( + "etc/portage/package.accept_keywords/phoebus-{}", + selected.repository + ), + format!("{}::{} ~amd64\n", selected.atom, selected.repository), + )?; + } + // Register last. An interruption before this write leaves inert policy + // files; it cannot expose an unrestricted external repository to Portage. + target.write( + &format!( + "etc/portage/repos.conf/phoebus-{}.conf", + selected.repository + ), + conf, + )?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rejects_unsafe_identity_and_source() { + assert!(valid_atom("app-misc/chatgpt-desktop")); + assert!(!valid_atom("app-misc/../../evil")); + assert!(!valid_repository("../evil")); + assert!(valid_source("https://github.com/gentoo-zh/overlay.git")); + assert!(!valid_source("https://user@host/repo.git")); + } + + #[test] + fn parses_registry_and_gpo_leads() { + let xml = r#"gentoo-zhhttps://github.com/gentoo-zh/overlay.git"#; + assert_eq!( + registry_source(xml, "gentoo-zh").unwrap(), + ( + "https://github.com/gentoo-zh/overlay.git".into(), + "experimental".into() + ) + ); + assert_eq!( + gpo_repositories( + "xy" + ), + vec!["gentoo-zh"] + ); + } + + #[test] + fn policy_masks_the_repository_and_scopes_testing_keyword() { + let temp = tempfile::tempdir().unwrap(); + let target = TargetRoot::new(temp.path()); + let review = OverlayReview { + atom: "app-misc/chatgpt-desktop".into(), + repository: "gentoo-zh".into(), + source: "https://github.com/gentoo-zh/overlay.git".into(), + commit: "a".repeat(40), + ebuild: "app-misc/chatgpt-desktop/chatgpt-desktop-1.ebuild".into(), + ebuild_sha256: "b".repeat(64), + keywords: "-* ~amd64".into(), + needs_keyword: true, + registry_quality: "experimental".into(), + manifest_present: true, + }; + write_policy(&target, &review).unwrap(); + let mask = std::fs::read_to_string( + temp.path() + .join("etc/portage/package.mask/phoebus-gentoo-zh"), + ) + .unwrap(); + let unmask = std::fs::read_to_string( + temp.path() + .join("etc/portage/package.unmask/phoebus-gentoo-zh"), + ) + .unwrap(); + let keywords = std::fs::read_to_string( + temp.path() + .join("etc/portage/package.accept_keywords/phoebus-gentoo-zh"), + ) + .unwrap(); + let conf = std::fs::read_to_string( + temp.path() + .join("etc/portage/repos.conf/phoebus-gentoo-zh.conf"), + ) + .unwrap(); + assert!(mask.contains("*/*::gentoo-zh")); + assert_eq!(unmask, "app-misc/chatgpt-desktop::gentoo-zh\n"); + assert_eq!(keywords, "app-misc/chatgpt-desktop::gentoo-zh ~amd64\n"); + assert!(conf.contains("auto-sync = yes")); + } +} diff --git a/installer-rs/crates/phoebus-executor/src/portage.rs b/installer-rs/crates/phoebus-executor/src/portage.rs index 0f6c69e..89f33fd 100644 --- a/installer-rs/crates/phoebus-executor/src/portage.rs +++ b/installer-rs/crates/phoebus-executor/src/portage.rs @@ -114,6 +114,7 @@ pub fn normalize_config_permissions(root: &Path) { "binrepos.conf", "package.use", "package.mask", + "package.unmask", "package.accept_keywords", "package.license", "package.env", diff --git a/installer-rs/crates/phoebus-installer/src/assistant_bridge.rs b/installer-rs/crates/phoebus-installer/src/assistant_bridge.rs index f4e36fb..f64bcfa 100644 --- a/installer-rs/crates/phoebus-installer/src/assistant_bridge.rs +++ b/installer-rs/crates/phoebus-installer/src/assistant_bridge.rs @@ -23,7 +23,7 @@ use phoebus_executor::proactive; use phoebus_executor::probe; use phoebus_executor::transaction; use phoebus_executor::update::check_unified_updates; -use phoebus_executor::{actions, query, Exec}; +use phoebus_executor::{actions, overlay, Exec}; use crate::ai_setup; use crate::conversation::{self, ConversationTurn, FollowupResolution}; @@ -44,6 +44,8 @@ pub struct BridgeRequest { #[serde(default)] pub application: Option, #[serde(default)] + pub repository: Option, + #[serde(default)] pub backend: Option, #[serde(default)] pub phrase: Option, @@ -329,47 +331,47 @@ fn gpo_atom_in(query: &str) -> Option<&str> { fn gpo_reference_response(exec: &Exec, root: &Path, id: u64, atom: &str) -> BridgeResponse { let local = chooser::resolve_for_backend(exec, root, Backend::PortageSource, atom); - let summary = if local + if local .candidates .iter() .any(|candidate| candidate.id == atom && candidate.available) { - format!( + let summary = format!( "{atom} is available in a configured Portage repository. Ask to install {atom} \ through Portage to review the exact candidate and source before approval." - ) - } else { - let phase = exec.progress_phase("Checking the external Portage overlay index"); - let lead = query::search_external_overlays(exec, root, atom); - if lead.is_ok() { - phase.complete(); + ); + return BridgeResponse::ok( + id, + json!({ + "kind": "info", "state": "info", "summary": summary, "recommendation": summary + }), + ); + } + let phase = exec.progress_phase("Reviewing external repositories and exact ebuilds"); + let reviews = overlay::discover(exec, root, atom); + if reviews.is_ok() { + phase.complete(); + } + match reviews { + Ok(reviews) => BridgeResponse::ok( + id, + json!({ + "kind": "overlay_options", "state": "review", "application": atom, + "summary": format!("Found {} external repository option(s) for {atom} that pass repository, ebuild and amd64 checks. Dependency resolution follows in a separate install plan. Each is unofficial; no repository or package was added.", reviews.len()), + "recommendation": format!("Found {} external repository option(s) for {atom}. Choose one to review its exact registration plan; package dependencies are checked before installation.", reviews.len()), + "options": reviews, + }), + ), + Err(reason) => { + let summary = format!("Portage cannot resolve {atom} locally. External overlay review did not find an eligible option: {reason}. Nothing was installed."); + BridgeResponse::ok( + id, + json!({ + "kind": "info", "state": "info", "summary": summary, "recommendation": summary + }), + ) } - match lead { - Ok(leads) if leads.iter().any(|lead| lead.atom == atom) => format!( - "GPO lists {atom} as an external overlay lead. `sys search {atom} --legacy \ - --overlays --portage` can find it, but Portage cannot resolve it under \ - the current repository and keyword settings. The GPO page does not \ - identify a trusted install source by itself. Choose and review a \ - repository and its ebuild, register and sync it if needed, and accept \ - ~amd64 only for this package if required before requesting a Portage \ - install. Nothing was installed." - ), - Ok(_) => format!( - "Portage cannot resolve {atom} under its current settings, and the \ - external GPO search did not confirm this listing. Nothing was installed." - ), - Err(reason) => format!( - "Portage cannot resolve {atom} under its current settings. The \ - external GPO lookup failed: {reason}. Nothing was installed." - ), - } - }; - BridgeResponse::ok( - id, - json!({ - "kind": "info", "state": "info", "summary": summary, "recommendation": summary - }), - ) + } } pub fn handle_request( @@ -384,6 +386,24 @@ pub fn handle_request( // so the CLI and GUI see the same preferences. let storage = UserStorage::for_initiating_user(); match req.op.as_str() { + "overlay_prepare" => { + let atom = req.application.unwrap_or_default(); + let repository = req.repository.unwrap_or_default(); + if !overlay::valid_atom(&atom) || repository.is_empty() { + return BridgeResponse::err(id, "select an exact package and repository"); + } + let reviews = match overlay::discover(exec, root, &atom) { + Ok(reviews) => reviews, + Err(e) => return BridgeResponse::err(id, e.to_string()), + }; + let Some(review) = reviews.into_iter().find(|r| r.repository == repository) else { + return BridgeResponse::err(id, "selected repository no longer passes review"); + }; + match service::plan_overlay(plans, root, review) { + Ok(plan) => plan_response(id, "overlay", &plan), + Err(e) => BridgeResponse::err(id, e.to_string()), + } + } "handshake" => { let ai_conf = load_installed_ai_config(root); let prefs = chooser::load_preferences(root); @@ -1016,6 +1036,7 @@ mod tests { op: op.into(), request: None, application: None, + repository: None, backend: None, phrase: None, plan_id: None, @@ -1155,6 +1176,7 @@ mod tests { op: "handshake".into(), request: None, application: None, + repository: None, backend: None, phrase: None, plan_id: None, @@ -1182,6 +1204,7 @@ mod tests { op: "history".into(), request: None, application: None, + repository: None, backend: None, phrase: None, plan_id: None, diff --git a/installer-rs/crates/phoebus-installer/src/bin/sys.rs b/installer-rs/crates/phoebus-installer/src/bin/sys.rs index c3c181c..4017b60 100644 --- a/installer-rs/crates/phoebus-installer/src/bin/sys.rs +++ b/installer-rs/crates/phoebus-installer/src/bin/sys.rs @@ -19,8 +19,8 @@ use phoebus_core::transaction::{TransactionOutcome, TransactionRecord}; use phoebus_core::{AiBackend, InstallConfig, Redactor}; use phoebus_executor::install::{AiInstall, ExecutorSession, InstallRequest}; use phoebus_executor::{ - actions, authorize, chooser, install, probe, query, transaction, AutoConfirm, Confirmation, - DestructiveAuthorization, Exec, Logger, RealRunner, Result, + actions, authorize, chooser, install, overlay, probe, query, transaction, AutoConfirm, + Confirmation, DestructiveAuthorization, Exec, Logger, RealRunner, Result, }; use phoebus_installer::approval; use phoebus_installer::conversation::{self, ConversationTurn, FollowupResolution}; @@ -38,7 +38,9 @@ mod progress; administration that never contacts a model.\n\n\ Examples (AI default -> deterministic equivalent):\n \ sys search chrome -> sys search chrome --legacy\n \ -sys search chatgpt --legacy --overlays -> include external overlay leads\n \ + sys search chatgpt --legacy --overlays -> include external overlay leads\n \ + sys overlay review app-misc/chatgpt-desktop -> inspect live overlay options\n \ + sys overlay enable app-misc/chatgpt-desktop gentoo-zh -> approve and register one\n \ sys list -> sys list --legacy\n \ sys info firefox -> sys info firefox --legacy\n \ sys updates -> sys updates --legacy\n \ @@ -364,6 +366,12 @@ fn run() -> std::result::Result<(), Box> { let backend = backend_flag(&cli); let mut full_phrase = cli.text.join(" "); + // External repositories are always handled by deterministic review. A + // model cannot invent a source URL or skip the exact approval boundary. + if cli.text.first().map(String::as_str) == Some("overlay") { + return run_overlay_command(&cli, &exec, &plans); + } + // Check for "propose " or "please propose " prefix for userspace agent workflow let mut cli = cli; { @@ -538,6 +546,89 @@ fn run() -> std::result::Result<(), Box> { run_ask(&cli, &exec, &plans, &full_phrase, backend) } +fn run_overlay_command( + cli: &Cli, + exec: &Exec, + plans: &service::PlanStore, +) -> std::result::Result<(), Box> { + if backend_flag(cli).is_some() || cli.overlays { + return Err("overlay review/enable does not use a package lane flag".into()); + } + let Some(verb) = cli.text.get(1).map(String::as_str) else { + return Err("usage: sys overlay review | sys overlay enable ".into()); + }; + let Some(atom) = cli.text.get(2) else { + return Err("overlay command requires an exact category/package atom".into()); + }; + if !overlay::valid_atom(atom) { + return Err("overlay command requires an exact category/package atom".into()); + } + let expected_len = if verb == "enable" { 4 } else { 3 }; + if !["review", "enable"].contains(&verb) || cli.text.len() != expected_len { + return Err("usage: sys overlay review | sys overlay enable ".into()); + } + let phase = exec.progress_phase("Reviewing listed repositories and exact ebuilds"); + let reviews = overlay::discover(exec, &cli.root, atom)?; + phase.complete(); + if verb == "review" { + println!("Reviewed external overlay options for {atom}:"); + for review in &reviews { + println!("\n repository: {}", review.repository); + println!(" source: {}", review.source); + println!(" revision: {}", review.commit); + println!(" ebuild: {}", review.ebuild); + println!(" SHA-256: {}", review.ebuild_sha256); + println!(" keywords: {}", review.keywords); + println!( + " Manifest: {}", + if review.manifest_present { + "present" + } else { + "absent" + } + ); + println!(" registry: {} (unofficial)", review.registry_quality); + println!( + " select: sys overlay enable {atom} {}", + review.repository + ); + } + println!("\nThese options pass repository, ebuild and amd64 checks. Dependency resolution happens in the separate install plan. A listing or hash does not prove publisher trust. Enabling one option adds its repository for the selected package only."); + return Ok(()); + } + let repository = &cli.text[3]; + let review = reviews + .into_iter() + .find(|r| &r.repository == repository) + .ok_or("the named repository did not pass review for this package")?; + let plan = service::plan_overlay(plans, &cli.root, review)?; + println!( + "{}", + progress::wrap_text(&plan.render(), progress::terminal_columns()) + ); + if cli.propose { + println!("\nPlan ID: {}\nDigest: {}", plan.id, plan.digest); + return Ok(()); + } + if !cli.yes { + let confirmation = SysConfirm { + action: plan.actions[0].clone(), + assume_yes: false, + }; + authorize(&confirmation, &plan.summary, "execute")?; + } + let phase = exec.progress_phase("Adding the approved repository and checking its revision"); + let outcome = service::execute_plan(exec, &cli.root, plans, &plan.id, &plan.digest, true)?; + phase.complete(); + for line in outcome.output { + if !line.trim().is_empty() { + println!("{line}"); + } + } + println!("{}", outcome.verification); + Ok(()) +} + fn run_overlay_search( cli: &Cli, exec: &Exec, diff --git a/installer-rs/crates/phoebus-installer/src/service/mod.rs b/installer-rs/crates/phoebus-installer/src/service/mod.rs index f6f1eb3..218b4dd 100644 --- a/installer-rs/crates/phoebus-installer/src/service/mod.rs +++ b/installer-rs/crates/phoebus-installer/src/service/mod.rs @@ -221,10 +221,24 @@ impl PreparedPlan { out.push_str(&format!("Approval digest: {}\n", self.digest)); } _ => { - out.push_str(&format!("Assistant Plan:\n {}\n", self.summary)); + let title = if matches!( + self.actions.first(), + Some(SystemAction::EnableOverlay { .. }) + ) { + "Overlay registration plan" + } else { + "Assistant Plan" + }; + out.push_str(&format!("{title}:\n {}\n", self.summary)); for a in &self.actions { out.push_str(&format!(" - {}\n", a.describe())); } + for reason in &self.rationale { + out.push_str(&format!(" why: {reason}\n")); + } + for warning in &self.warnings { + out.push_str(&format!(" caution: {warning}\n")); + } if self.effects.established && !self.effects.effects.is_empty() { out.push_str(&self.effects.render()); } @@ -328,6 +342,6 @@ pub mod validation; pub use execution::{execute_plan, execute_plan_privileged}; pub use plan::{ build_removal_plan, format_recommendation, plan_general, plan_install, plan_legacy_install, - plan_removal, plan_removal_with_ai, select_removal_copy, PlanStore, + plan_overlay, plan_removal, plan_removal_with_ai, select_removal_copy, PlanStore, }; pub use validation::{compute_plan_digest, seal_plan, validate_prepared_plan}; diff --git a/installer-rs/crates/phoebus-installer/src/service/plan.rs b/installer-rs/crates/phoebus-installer/src/service/plan.rs index 86ea15a..5f7838a 100644 --- a/installer-rs/crates/phoebus-installer/src/service/plan.rs +++ b/installer-rs/crates/phoebus-installer/src/service/plan.rs @@ -7,7 +7,7 @@ use std::path::{Path, PathBuf}; use phoebus_ai::assistant::{complete_plan, run_assistant, AssistantPlan}; use phoebus_ai::install::Evidence; use phoebus_ai::provider::SystemFacts; -use phoebus_core::action::SystemAction; +use phoebus_core::action::{OverlayReview, SystemAction}; use phoebus_core::effects::ResolvedPlan; use phoebus_core::selection::{Backend, Candidate, SandboxLevel}; use phoebus_executor::actions; @@ -22,6 +22,79 @@ use super::{ PlanClaim, PlanKind, PreparedPlan, DEFAULT_PLAN_TTL_SECONDS, }; +/// Stage a deterministic, approval-bound repository registration. Discovery +/// and package compatibility inspection happen before this builder; the broker +/// repeats them and rejects any changed source or ebuild. +pub fn plan_overlay( + plans: &super::PlanStore, + root: &Path, + review: OverlayReview, +) -> Result { + let action = SystemAction::EnableOverlay { + review: review.clone(), + }; + action + .validate() + .map_err(|reason| ExecError::operation("overlay", "validate review", reason))?; + let consequences = vec![ + format!("clone {} at commit {}", review.source, review.commit), + format!("enable only {} from {}", review.atom, review.repository), + "allow future repository syncs; package installation remains a separate review".into(), + ]; + let mut step = ResolvedPlan { + established: true, + consequences: consequences.clone(), + ..Default::default() + }; + step.recompute_digest(); + let mut effects = step.clone(); + effects.recompute_digest(); + let actions = vec![action]; + let steps = vec![step]; + let now = now_unix(); + let mut plan = PreparedPlan { + id: fresh_plan_id("ovl"), + created_unix: now, + expires_unix: now + DEFAULT_PLAN_TTL_SECONDS, + kind: PlanKind::General, + summary: format!( + "Enable {} for {} from {} at {}", + review.repository, review.atom, review.source, review.commit + ), + recommendation: format!( + "Enable {} for {} at reviewed revision {}. Portage will keep the repository synced; package installation is a separate approval.", + review.repository, review.atom, review.commit + ), + application: Some(review.atom.clone()), + candidate: None, + alternatives: Vec::new(), + rationale: vec![ + format!("ebuild: {} (SHA-256 {})", review.ebuild, review.ebuild_sha256), + format!("amd64 keywords: {}", review.keywords), + format!("Gentoo registry quality: {} (unofficial repository)", review.registry_quality), + format!("package Manifest present: {}", review.manifest_present), + ], + warnings: vec![ + "Registry listing, Git revision and Manifest do not prove publisher trust; the ebuild runs with Portage privileges when installed.".into(), + "Future syncs can change this ebuild. Review package updates before installing them.".into(), + ], + actions, + effects, + step_effects: steps, + digest: String::new(), + verification: "verify repository revision, scoped mask/unmask, and auto-sync configuration".into(), + requires_root: true, + source: "Gentoo overlay registry and live Git repository".into(), + executed: false, + target_root: canonical_root(root), + initiator_uid: effective_uid(), + integrity: String::new(), + }; + plan.digest = compute_plan_digest(&plan.actions, None, &plan.effects, &plan.step_effects); + plans.save(&mut plan)?; + Ok(plan) +} + /// Produce an honest, evidence-based human recommendation for an application candidate. pub fn format_recommendation(candidate: &Candidate, application: &str) -> String { let source_name = match candidate.backend { @@ -822,6 +895,7 @@ pub fn plan_general( matches!( action, SystemAction::InstallPackage { .. } + | SystemAction::EnableOverlay { .. } | SystemAction::FlatpakInstall { .. } | SystemAction::SnapInstall { .. } | SystemAction::NixPrepare { .. } @@ -835,7 +909,7 @@ pub fn plan_general( return Err(ExecError::operation( "service", "source health review", - "package installation requires the dedicated `sys install` workflow; request an install by application name and source so sys can inspect it before approval", + "package installation or overlay registration requires its dedicated `sys install` or `sys overlay` workflow so sys can inspect the source before approval", )); } diff --git a/installer-rs/crates/phoebus-installer/src/service/tests.rs b/installer-rs/crates/phoebus-installer/src/service/tests.rs index 993bf06..8287720 100644 --- a/installer-rs/crates/phoebus-installer/src/service/tests.rs +++ b/installer-rs/crates/phoebus-installer/src/service/tests.rs @@ -5,7 +5,7 @@ use super::validation::{plan_integrity, reviewed_steps, validate_effect_bindings use super::*; use crate::approval::{ApprovalIdentity, ApprovalLedger}; use phoebus_ai::provider::SystemFacts; -use phoebus_core::action::SystemAction; +use phoebus_core::action::{OverlayReview, SystemAction}; use phoebus_core::effects::parse_emerge_pretend; use phoebus_core::effects::ResolvedPlan; use phoebus_core::selection::Capability; @@ -32,6 +32,50 @@ fn make_test_exec(root: &Path) -> Exec { ) } +#[test] +fn overlay_approval_binds_the_exact_repository_and_ebuild() { + let root = tempdir().unwrap(); + let plans = PlanStore::with_dir(tempdir().unwrap().keep()); + let exec = make_test_exec(root.path()); + let review = OverlayReview { + atom: "app-misc/chatgpt-desktop".into(), + repository: "gentoo-zh".into(), + source: "https://github.com/gentoo-zh/overlay.git".into(), + commit: "a".repeat(40), + ebuild: "app-misc/chatgpt-desktop/chatgpt-desktop-1.ebuild".into(), + ebuild_sha256: "b".repeat(64), + keywords: "-* ~amd64".into(), + needs_keyword: true, + registry_quality: "experimental".into(), + manifest_present: true, + }; + let plan = plan_overlay(&plans, root.path(), review).unwrap(); + assert!(plan.requires_root); + assert_eq!(plan.actions.len(), 1); + assert!(plan.render().contains("unofficial repository")); + super::validation::validate_prepared_plan( + &exec, + root.path(), + &plan, + Some(&plan.digest), + effective_uid(), + ) + .unwrap(); + let mut substituted = plan.clone(); + if let SystemAction::EnableOverlay { review } = &mut substituted.actions[0] { + review.repository = "other".into(); + } + super::validation::seal_plan(&mut substituted); + assert!(super::validation::validate_prepared_plan( + &exec, + root.path(), + &substituted, + Some(&plan.digest), + effective_uid(), + ) + .is_err()); +} + #[test] fn an_environment_variable_cannot_forge_root() { // Privilege is derived from the process identity, never from the diff --git a/installer/live/desktop/phoebus-assistant/AssistantBridge.qml b/installer/live/desktop/phoebus-assistant/AssistantBridge.qml index 75e407f..e01601f 100644 --- a/installer/live/desktop/phoebus-assistant/AssistantBridge.qml +++ b/installer/live/desktop/phoebus-assistant/AssistantBridge.qml @@ -97,6 +97,10 @@ Singleton { call("ask", { request: query, backend: backend }, cb, onProgress); } + function prepareOverlay(atom, repository, cb, onProgress) { + call("overlay_prepare", { application: atom, repository: repository }, cb, onProgress); + } + function execute(planId, digest, yes, cb, onProgress) { call("execute", { plan_id: planId, digest: digest, yes: yes }, cb, onProgress); } diff --git a/installer/live/desktop/phoebus-assistant/shell.qml b/installer/live/desktop/phoebus-assistant/shell.qml index 5e3d892..e3c964d 100644 --- a/installer/live/desktop/phoebus-assistant/shell.qml +++ b/installer/live/desktop/phoebus-assistant/shell.qml @@ -262,6 +262,25 @@ ShellRoot { }, progress => shell.recordActivity(index, progress)); } + function chooseOverlay(index, atom, repository) { + if (shell.busy) + return; + shell.busy = true; + shell.statusText = "Preparing reviewed overlay plan..."; + shell.updateMessage(index, { state: "preparing" }); + AssistantBridge.prepareOverlay(atom, repository, reply => { + shell.busy = false; + if (!reply.ok) { + shell.statusText = "Overlay review failed"; + shell.updateMessage(index, { state: "failed", error: reply.error || "Review failed" }); + return; + } + const result = reply.result || {}; + shell.statusText = "Overlay plan ready for approval"; + shell.finishMessage(index, result.recommendation || result.summary || "Review this overlay", result); + }, progress => shell.recordActivity(index, progress)); + } + function cancelPlan(index) { // Cancelling is purely local: nothing reaches the privileged broker. shell.updateMessage(index, { state: "cancelled" }); @@ -582,6 +601,7 @@ ShellRoot { delegate: Rectangle { id: messageCard + property int messageIndex: index width: chatList.width height: msgCol.height + 16 radius: 8 @@ -640,6 +660,8 @@ ShellRoot { : d.kind === "removal" ? "Removal plan" : d.kind === "confirm" ? "Confirmation required" : d.kind === "plan" ? "Administration plan" + : d.kind === "overlay" ? "Overlay plan" + : d.kind === "overlay_options" ? "Overlay options" : d.kind === "info" ? "Information" : d.kind === "progress" ? "Working" : d.kind === "error" ? "Error" : "Result"; @@ -653,6 +675,42 @@ ShellRoot { } } + Repeater { + model: modelData.data && modelData.data.kind === "overlay_options" + ? (modelData.data.options || []) : [] + delegate: ColumnLayout { + required property var modelData + Layout.fillWidth: true + spacing: 3 + Label { + Layout.fillWidth: true + text: modelData.repository + " • " + modelData.keywords + color: Theme.text + font.bold: true + wrapMode: Text.Wrap + } + Label { + Layout.fillWidth: true + text: modelData.source + "\nRevision: " + modelData.commit + + "\nEbuild: " + modelData.ebuild + + "\nSHA-256: " + modelData.ebuild_sha256 + + "\nManifest: " + (modelData.manifest_present ? "present" : "absent") + + "\nRegistry: " + modelData.registry_quality + " (unofficial)" + color: Theme.muted + font.pixelSize: 11 + textFormat: Text.PlainText + wrapMode: Text.WrapAnywhere + } + PhoebusButton { + label: "Review " + modelData.repository + actionEnabled: !shell.busy + onClicked: shell.chooseOverlay(messageCard.messageIndex, + shell.conversation[messageCard.messageIndex].data.application, + modelData.repository) + } + } + } + ColumnLayout { Layout.fillWidth: true visible: !!(modelData.data && @@ -712,7 +770,9 @@ ShellRoot { spacing: 8 PhoebusButton { - label: modelData.data && modelData.data.kind === "removal" ? "Approve & Remove" : "Approve & Execute" + label: modelData.data && modelData.data.kind === "removal" ? "Approve & Remove" + : modelData.data && modelData.data.kind === "overlay" ? "Approve & Enable" + : "Approve & Execute" primary: true actionEnabled: !shell.busy onClicked: shell.executePlan(index)