From ec148aefe6708408497baeae1d33123a366074bf Mon Sep 17 00:00:00 2001 From: Pavel Isaev Date: Fri, 6 Nov 2026 19:46:31 +0300 Subject: [PATCH] Preserve support for repository extensions with source-aware customization --- EXTENSIONS.md | 15 +++++++++ adapters/host.sh | 4 --- src/extensions.rs | 86 ++++++++++++++++++++++++++++++++++++++--------- src/updates.rs | 34 ++++++++++++++++--- 4 files changed, 115 insertions(+), 24 deletions(-) diff --git a/EXTENSIONS.md b/EXTENSIONS.md index 2581649..41ae347 100644 --- a/EXTENSIONS.md +++ b/EXTENSIONS.md @@ -1,5 +1,20 @@ # Repository-backed Host Extensions (experimental implementation) +D-088 adds `extension remove NAME...` and separates support from customization. +Repository-name additions retain support on a distribution-signed base; `customed` +lists sorted effective additions (including dependencies), ten names then +`… +N packages`. Custom overlays, local files and unknown legacy provenance do not +gain support. Base signature verification uses a separate cache and the embedded +distribution key; unavailable verification yields `unknown`, not `supported`. + +Metadata v2 retains `requested` names and a `request_sources` mapping. Old metadata +is read conservatively as unknown provenance, never inferred from names. The current +repository adapter refuses to replay local/unknown sources; remove those requests +explicitly before composing a repository-only set. Removing the final request stages +the original managed base, preserving history and user data. Update plan v3 retains +the mapping; earlier plans must be recreated. Booted and pending are reported +separately. Out-of-band mutation detection remains outside this private adapter. + The CLI accepts `extension add NAME...`. This implements the D-037 requested-set model: resolve against the base image's retained sync databases; download exact packages; compose the entire explicit set against the immutable base and its ALPM diff --git a/adapters/host.sh b/adapters/host.sh index 2c16b98..f35d6af 100644 --- a/adapters/host.sh +++ b/adapters/host.sh @@ -14,10 +14,6 @@ fi if [[ $1 == status ]]; then ostree admin status printf 'Experimental Core; public release gates not yet satisfied\n' - if [[ -f /usr/lib/archipelago/host-extensions ]]; then - printf 'Booted support status: unsupported\nHost Extensions: ' - cat /usr/lib/archipelago/host-extensions - fi if [[ -f /usr/lib/archipelago/overlays ]]; then cat /usr/lib/archipelago/overlays; fi exit 0 fi diff --git a/src/extensions.rs b/src/extensions.rs index ad86765..611cd56 100644 --- a/src/extensions.rs +++ b/src/extensions.rs @@ -1,11 +1,12 @@ //! Experimental requested-set lifecycle. pacman and OSTree remain the engines. use serde_json::{Value, json}; -use std::{collections::BTreeSet, fs::{self, File}, os::unix::fs::DirBuilderExt, +use std::{collections::{BTreeMap, BTreeSet}, fs::{self, File}, os::unix::fs::DirBuilderExt, path::Path, process::Command, time::{SystemTime, UNIX_EPOCH}}; const REPO: &str = "--repo=/sysroot/ostree/repo"; const STATE: &str = "/var/lib/archipelago/host-extensions/generations"; const METADATA: &str = "/usr/lib/archipelago/extensions.json"; +pub(crate) type Requests = BTreeMap; fn output(program: &str, args: &[&str]) -> Result { let out = Command::new(program).args(args).output().map_err(|e| e.to_string())?; @@ -57,24 +58,32 @@ fn cat(commit: &str, path: &str) -> Result { output("ostree", &[REPO, "cat", commit, path]) } -pub(crate) fn intent(commit: &str) -> Result<(String, BTreeSet), String> { +pub(crate) fn intent(commit: &str) -> Result<(String, Requests), String> { // Listing first distinguishes an absent metadata file from malformed metadata. let listing = output("ostree", &[REPO, "ls", commit, "/usr/lib/archipelago"])?; if listing.lines().any(|line| line.ends_with("/extensions.json")) { let data: Value = serde_json::from_str(&cat(commit, METADATA)?).map_err(|e| e.to_string())?; - if data["version"] != 1 { return Err("unsupported extension metadata version".into()); } + if data["version"] != 1 && data["version"] != 2 { return Err("unsupported extension metadata version".into()); } let requested = data["requested"].as_array().ok_or("missing requested set")?.iter() .map(|v| v.as_str().map(str::to_string).ok_or("invalid request".to_string())) .collect::, _>>()?; - return Ok((checksum(data["base"].as_str().ok_or("missing extension base")?)?, names(&requested)?)); + let requested = names(&requested)?; + let origins: Requests = if data["version"] == 2 { + serde_json::from_value(data["request_sources"].clone()).map_err(|e| e.to_string())? + } else { requested.iter().map(|n| (n.clone(), "unknown".into())).collect() }; + if origins.keys().cloned().collect::>() != requested || + origins.values().any(|v| !["repository", "local-file", "unknown"].contains(&v.as_str())) { + return Err("invalid extension request provenance".into()); + } + return Ok((checksum(data["base"].as_str().ok_or("missing extension base")?)?, origins)); } if listing.lines().any(|line| line.ends_with("/host-extensions")) { // Migrate the single-generation nano fixture used by Core ISO 01–10. let requested: Vec<_> = cat(commit, "/usr/lib/archipelago/host-extensions")?.lines().map(str::to_string).collect(); let base = output("ostree", &[REPO, "show", "--print-metadata-key=archipelago.base", commit])?; - return Ok((checksum(base.trim().trim_matches('\''))?, names(&requested)?)); + return Ok((checksum(base.trim().trim_matches('\''))?, names(&requested)?.into_iter().map(|n| (n, "unknown".into())).collect())); } - Ok((commit.to_string(), BTreeSet::new())) + Ok((commit.to_string(), Requests::new())) } pub fn describe() -> Result<(), String> { @@ -85,7 +94,28 @@ pub fn describe() -> Result<(), String> { let commit = checksum(deployment["checksum"].as_str().ok_or("missing checksum")?)?; let (base, requested) = intent(&commit)?; let role = if deployment["booted"] == true { "Booted" } else { "Pending" }; - println!("{role} base: {base}\n{role} requested extensions: {}", requested.into_iter().collect::>().join(" ")); + println!("{role} deployment: {commit}\n{role} base: {base}"); + println!("{role} requested extensions: {}", requested.iter().map(|(n, s)| format!("{n} ({s})")).collect::>().join(", ")); + let files = output("ostree", &[REPO, "ls", &base, "/usr/lib/archipelago"])?; + let custom_overlay = files.lines().any(|l| l.ends_with("/overlays")); + let repo_only = requested.values().all(|s| s == "repository"); + if custom_overlay || !repo_only { + println!("{role} support status: unsupported"); + } else { + match crate::updates::verify_supported_base(&base) { + Ok(()) => println!("{role} support status: supported"), + Err(error) => println!("{role} support status: unknown (base not verified: {error})"), + } + } + if !requested.is_empty() && repo_only { + let original: BTreeSet<_> = cat(&base, "/usr/lib/archipelago/packages.txt")?.lines() + .filter_map(|l| l.split_whitespace().next().map(str::to_string)).collect(); + let effective: BTreeSet<_> = cat(&commit, "/usr/lib/archipelago/packages.txt")?.lines() + .filter_map(|l| l.split_whitespace().next().map(str::to_string)).filter(|n| !original.contains(n)).collect(); + let mut label = effective.iter().take(10).cloned().collect::>().join(", "); + if effective.len() > 10 { label.push_str(&format!(", … +{} packages", effective.len() - 10)); } + println!("{role} customization: customed ({label})"); + } } Ok(()) } @@ -95,6 +125,14 @@ fn write(path: impl AsRef, data: impl AsRef<[u8]>) -> Result<(), String> { } pub fn add(packages: &[String]) -> Result<(), String> { + change(packages, false) +} + +pub fn remove(packages: &[String]) -> Result<(), String> { + change(packages, true) +} + +fn change(packages: &[String], remove: bool) -> Result<(), String> { let additions = names(packages)?; if output("id", &["-u"])?.trim() != "0" { return Err("Run as root".into()); } if !Path::new("/run/ostree-booted").exists() || !Path::new("/etc/archipelago/provisioned").exists() { @@ -107,7 +145,10 @@ pub fn add(packages: &[String]) -> Result<(), String> { let (source, pending) = select(&initial)?; let (base, mut requested) = intent(&source)?; let previous = requested.clone(); - requested.extend(additions); + for name in additions { + if remove { requested.remove(&name); } + else { requested.entry(name).or_insert_with(|| "repository".into()); } + } if requested == previous { println!("Already requested in {} deployment; no changes.", if pending { "pending" } else { "booted" }); return Ok(()); @@ -119,7 +160,8 @@ pub fn add(packages: &[String]) -> Result<(), String> { write(generation.join("base"), format!("{base}\n"))?; write(generation.join("source"), format!("{source}\n"))?; write(generation.join("snapshot"), &snapshot)?; - write(generation.join("requested"), requested.iter().map(|n| format!("{n}\n")).collect::())?; + write(generation.join("requested"), requested.keys().map(|n| format!("{n}\n")).collect::())?; + write(generation.join("request-sources.json"), serde_json::to_vec_pretty(&requested).map_err(|e| e.to_string())?)?; let result = compose(&generation, &id, &base, &snapshot, &requested, &initial); if let Err(error) = &result { let _ = write(generation.join("failure"), error); @@ -128,7 +170,7 @@ pub fn add(packages: &[String]) -> Result<(), String> { result } -pub(crate) fn reapply(base: &str, requested: &BTreeSet, initial: &Value) -> Result<(), String> { +pub(crate) fn reapply(base: &str, requested: &Requests, initial: &Value) -> Result<(), String> { // Caller holds the same host mutation lock as extension add. let id = format!("update-{}-{}", SystemTime::now().duration_since(UNIX_EPOCH) .map_err(|e| e.to_string())?.as_nanos(), std::process::id()); @@ -137,14 +179,26 @@ pub(crate) fn reapply(base: &str, requested: &BTreeSet, initial: &Value) let snapshot = cat(base, "/usr/lib/archipelago/snapshot")?; write(generation.join("base"), format!("{base}\n"))?; write(generation.join("snapshot"), &snapshot)?; - write(generation.join("requested"), requested.iter().map(|n| format!("{n}\n")).collect::())?; + write(generation.join("requested"), requested.keys().map(|n| format!("{n}\n")).collect::())?; + write(generation.join("request-sources.json"), serde_json::to_vec_pretty(requested).map_err(|e| e.to_string())?)?; let result = compose(&generation, &id, base, &snapshot, requested, initial); if let Err(error) = &result { let _ = write(generation.join("failure"), error); } result } fn compose(generation: &Path, id: &str, base: &str, snapshot: &str, - requested: &BTreeSet, initial: &Value) -> Result<(), String> { + requested: &Requests, initial: &Value) -> Result<(), String> { + if requested.values().any(|s| s != "repository") { + return Err("Local/legacy request provenance cannot be replayed by the repository adapter; explicitly remove those requests first. Inputs and deployments preserved.".into()); + } + if requested.is_empty() { + if status()? != *initial { return Err("deployment selection changed; retry".into()); } + crate::updates::stage_deployment(base)?; + write(generation.join("result"), format!("{base}\n"))?; + write(generation.join("staged"), b"success\n")?; + println!("Prepared managed base {base}; activate with an explicit reboot."); + return Ok(()); + } let root = generation.join("root"); let rootstr = root.to_str().ok_or("invalid workspace path")?; run("ostree", &[REPO, "refs", &format!("--create=extensions/bases/{id}"), base])?; @@ -156,10 +210,10 @@ fn compose(generation: &Path, id: &str, base: &str, snapshot: &str, .arg(generation).status().map_err(|e| e.to_string())?; if !transaction.success() { return Err(format!("package transaction/finalization failed: {transaction}")); } write(root.join("usr/lib/archipelago/extensions.json"), serde_json::to_vec_pretty(&json!({ - "version": 1, "base": base, "snapshot": snapshot.trim(), "generation": id, - "requested": requested, + "version": 2, "base": base, "snapshot": snapshot.trim(), "generation": id, + "requested": requested.keys().collect::>(), "request_sources": requested, })).map_err(|e| e.to_string())?)?; - write(root.join("usr/lib/archipelago/host-extensions"), requested.iter().map(|n| format!("{n}\n")).collect::())?; + write(root.join("usr/lib/archipelago/host-extensions"), requested.keys().map(|n| format!("{n}\n")).collect::())?; let commit = checksum(output("ostree", &[REPO, "commit", "-b", &format!("extensions/results/{id}"), &format!("--tree=dir={rootstr}"), &format!("--add-metadata-string=archipelago.base={base}"), &format!("--add-metadata-string=archipelago.snapshot={}", snapshot.trim())])?.trim())?; @@ -176,7 +230,7 @@ fn compose(generation: &Path, id: &str, base: &str, snapshot: &str, eprintln!("Deployment staged; retained disposable workspace: {error}"); } println!("Prepared {commit}\nRequested: {}\nActivate with an explicit reboot. Current /usr unchanged.\nHistory: {}", - requested.iter().cloned().collect::>().join(" "), generation.display()); + requested.keys().cloned().collect::>().join(" "), generation.display()); Ok(()) } diff --git a/src/updates.rs b/src/updates.rs index 999239a..ac010cf 100644 --- a/src/updates.rs +++ b/src/updates.rs @@ -1,11 +1,37 @@ //! Temporary hardware-test update adapter: signed OSTree, pinned plans, no reboot. use serde_json::{json, Value}; -use std::{collections::BTreeSet, fs::{self, File}, os::unix::fs::DirBuilderExt, +use std::{fs::{self, File}, os::unix::fs::DirBuilderExt, path::{Path, PathBuf}, process::Command, time::{SystemTime, UNIX_EPOCH}}; const STATE: &str = "/var/lib/archipelago/updates"; const REMOTE: &str = "archipelago-hardware-test"; +// Support identity is independent of a locally overridden update binding. Only +// a base signed by the distribution key qualifies; no ref movement is needed. +pub(crate) fn verify_supported_base(base: &str) -> Result<(), String> { + if !digest(base) { return Err("invalid base checksum".into()); } + let dir = "/var/lib/archipelago/support"; + fs::DirBuilder::new().recursive(true).mode(0o700).create(dir).map_err(|e| e.to_string())?; + let lock = File::options().create(true).truncate(false).write(true) + .open(format!("{dir}/lock")).map_err(|e| e.to_string())?; + lock.try_lock().map_err(|e| e.to_string())?; + let repository = format!("--repo={dir}/repo"); + if !Path::new(dir).join("repo/config").exists() { + output("ostree", &[&repository, "init", "--mode=archive"])?; + } + let key = format!("{dir}/distribution.asc"); + fs::write(&key, include_bytes!("../archipelago-stable.asc")).map_err(|e| e.to_string())?; + output("ostree", &[&repository, "remote", "delete", "--if-exists", "distribution"])?; + output("ostree", &[&repository, "remote", "add", &format!("--gpg-import={key}"), + "--set=gpg-verify=true", "distribution", "https://mirror.nw-sys.ru/archipelago/ostree/images"])?; + if let Ok(verified) = output("ostree", &[&repository, "show", "--gpg-verify-remote=distribution", base]) { + if verified.contains("Good signature from") { return Ok(()); } + } + output("timeout", &["30", "ostree", &repository, "pull", "--commit-metadata-only", + "--depth=0", "distribution", base])?; + Ok(()) +} + fn output(program: &str, args: &[&str]) -> Result { let result = Command::new(program).args(args).env("LC_ALL", "C").env("TZ", "UTC").output().map_err(|e| e.to_string())?; if !result.status.success() { return Err(format!("{program}: {}", String::from_utf8_lossy(&result.stderr))); } @@ -150,7 +176,7 @@ fn plan_output(save: bool, json_output: bool, include_diff: bool) -> Result<(), let reference = binding["reference"].as_str().ok_or("missing reference")?; let target = summary_commit(&repo(&["remote", "summary", REMOTE])?, &reference)?; require_newer(&base, &target)?; - let mut plan = json!({"version":2,"binding":binding,"variant":variant(),"reference":reference, + let mut plan = json!({"version":3,"binding":binding,"variant":variant(),"reference":reference, "target":target,"base":base,"requested":requested,"initial":state}); if include_diff { let inventory = "/usr/lib/archipelago/packages.txt"; @@ -191,7 +217,7 @@ pub fn apply(id: &str) -> Result<(), String> { } fn apply_plan(plan: &Value) -> Result<(), String> { let binding = binding()?; - if plan["version"] != 2 || plan["binding"] != binding || plan["variant"] != variant() { return Err("unsupported plan or infrastructure binding changed; create a new plan".into()); } + if plan["version"] != 3 || plan["binding"] != binding || plan["variant"] != variant() { return Err("unsupported plan or infrastructure binding changed; create a new plan".into()); } let initial = crate::extensions::status()?; booted(&initial)?; if initial != plan["initial"] { return Err("deployment state changed; create a new plan".into()); } @@ -208,7 +234,7 @@ fn apply_plan(plan: &Value) -> Result<(), String> { if output("uname", &["-m"])?.trim() != "x86_64" { return Err("only x86_64 is implemented".into()); } repo(&["cat", target, "/usr/lib/archipelago/snapshot"])?; output("ostree", &["--repo=/sysroot/ostree/repo", "pull-local", &format!("{STATE}/repo"), target])?; - let requested: BTreeSet = serde_json::from_value(plan["requested"].clone()).map_err(|e| e.to_string())?; + let requested: crate::extensions::Requests = serde_json::from_value(plan["requested"].clone()).map_err(|e| e.to_string())?; if crate::extensions::status()? != initial { return Err("deployment state changed during download".into()); } if requested.is_empty() { stage_deployment(target)?;