diff --git a/Cargo.lock b/Cargo.lock index 5ab0e7b..c9718bd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -25,6 +25,21 @@ dependencies = [ "memchr", ] +[[package]] +name = "archipelago-builder" +version = "0.0.0" +dependencies = [ + "archipelago-contracts", +] + +[[package]] +name = "archipelago-composer" +version = "0.0.0" +dependencies = [ + "archipelago-contracts", + "serde_json", +] + [[package]] name = "archipelago-contracts" version = "0.0.0" @@ -40,6 +55,8 @@ dependencies = [ name = "archipelago-system" version = "0.0.0" dependencies = [ + "archipelago-builder", + "archipelago-composer", "archipelago-contracts", "serde", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index 9fa0a91..37ef00b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,6 +9,8 @@ publish = false serde_json = "1.0" serde = { version = "1", features = ["derive"] } archipelago-contracts = { path = "../contracts" } +archipelago-composer = { path = "../composer" } +archipelago-builder = { path = "../builder" } zbus = { version = "=5.12.0", default-features = false, features = ["async-io", "blocking-api"] } # Macro releases use private zbus dispatch APIs; pin the matching family too. zbus_macros = "=5.12.0" diff --git a/DBUS-AUDIT.md b/DBUS-AUDIT.md new file mode 100644 index 0000000..a32c38e --- /dev/null +++ b/DBUS-AUDIT.md @@ -0,0 +1,143 @@ +# D-Bus source audit and Managed Overlay completion + +Scope: current working sources, not the published image. Reference surface: +`../contracts/dbus/org.archipelago.System1.xml`. This is a source audit, not runtime +introspection or Polkit/VM acceptance. No method below has newly acquired runtime +acceptance through this audit. PackageKit is excluded by D-095. + +## Method coverage + +`Present` means an exported handler and the indicated backend exist. It does not +mean the full scenario has passed. Manager handlers are in `src/service/mod.rs`, +transaction handlers in `transactions.rs`, other interfaces in their named files. + +| Interface / method | Source implementation / execution path | Assessment | +|---|---|---| +| Manager.GetCapabilities | Manager advertises durable-transactions and host-extensions | Present; no managed-overlays feature advertised | +| Manager.GetStatus | observation snapshot + transaction projection | Present | +| Manager.Refresh | Runtime worker → updates::managed | Present | +| Manager.GetUpdateDetails | plan_operation → managed::prepare, details-only | Present | +| Manager.PrepareUpdate | plan_operation → managed::prepare | Present; general overlay reapplication unfinished | +| Manager.Download | execute_operation → dispatch by plan intent | Present for update/extensions; overlay executor missing | +| Manager.Stage | same dispatch; plan-derived authorization | Present for update/extensions; overlay executor missing | +| Manager.GetTransaction | runtime exposes retained operation | Present | +| Manager.ListTransactions | journal pagination | Present | +| Manager.ValidatePending | observed pending deployment identity | Present; not a replacement for boot acceptance | +| Transaction.Cancel | initiator-aware authorization → journal cancellation | Present; worker observes cancellation boundaries | +| Transaction.GetSnapshot | durable record → wire snapshot | Present | +| Transaction.GetLog | ReadLogs authorization + bounded journal log | Present | +| HostExtensions.GetState | context-bound package catalog projection | Present | +| HostExtensions.Search | filtered catalog + bound pagination | Present | +| HostExtensions.Resolve | names/context → exact catalog entries | Present | +| HostExtensions.GetPackage | exact entry/context | Present | +| HostExtensions.GetHistory | successful staged generation records | Present | +| HostExtensions.RefreshCatalog | worker → packages::refresh_catalog | Present | +| HostExtensions.PrepareEnable | worker → packages::prepare_enable | Present | +| HostExtensions.ImportPackage | authorized Unix FD import → inputs | Present | +| HostExtensions.PrepareChange | typed changes → packages::prepare_change | Present | +| HostExtensions.PrepareRestore | retained successful generation → prepare_restore | Present | +| ManagedOverlays.GetState | verified catalog state projection | Present; requires catalog | +| ManagedOverlays.ListAvailable | catalog filtering/pagination | Present | +| ManagedOverlays.GetOverlay | exact catalog identity | Present | +| ManagedOverlays.RefreshCatalog | worker → overlays::refresh_catalog | Present; producer/profile not deployed | +| ManagedOverlays.PrepareSet | exported handler → Runtime → overlays::prepare_set | Source implemented after audit; runtime acceptance pending | + +Manager StatusRevision, HostExtensions/ManagedOverlays Revision, Transaction +properties and Finished are declared in source. ObjectManager registers the three +main objects and retained transaction exposure. PropertiesChanged emission exists +for the revisions. Actual signatures, signal timing, owner loss/reconnect and +permission behavior must be checked against runtime introspection in the pipeline. + +## End-to-end client coverage + +- `src/service/client.rs`: CLI status, update check/diff/plan/download/apply, + transaction list/status/log/wait/cancel, extension status/import/add/remove, + local/override/reset, enable/disable/history/restore call the typed service. +- ManagedOverlays CLI now has a separate proxy: status/list, add ID EXACT_COMMIT, + remove ID, order ALL_IDS and clear. Mutations fetch state/context, edit the + complete selection, invoke PrepareSet and then Manager.Stage. The exact commit + chooses the initial authenticated artifact; rebuild-on-update is still missing. +- `integrations/gnome-software/gs-plugin-archipelago.c` and + `integrations/discover/ArchipelagoBackend.cpp` implement native OS-update D-Bus + flows. These are OS clients, not overlay/package installation frontends. +- Existing client fixture/compile results do not prove communication with the + installed daemon, Polkit subjects, restart recovery or successful staging. + +## Concrete integration breaks + +1. PrepareSet now exports strict complete-list parsing, context/catalog checks, + authenticated input loading, composition/DB-accounting preflight and immutable + plan persistence. This is not yet an executable overlay Stage path; ALPM runtime + checks, lifecycle/replacement limits and pipeline acceptance remain open. +2. Manager now dispatches Overlays explicitly to overlays::execute; it validates + the retained plan/commit and calls the shared package Download/Stage executor. +3. PrepareSet now calls compose_tree/finalize, commits private managed output and + resolves retained extensions against it. The plan pins this composed target and + exact extension closure. Runtime validation of this new path is pending. +4. Whole-package replacements are explicitly rejected in composer. +5. Catalog transport expects the configured image remote to contain signed layer + and catalog commits. Producer/ref/profile rollout is unfinished. +6. RefreshCatalog unnecessarily scanned a full base. Removed during this audit; + load_base must instead be called by PrepareSet/Stage. Catalog listing must not + perform an OS composition preflight. Runtime latency remains unmeasured. +7. New lifecycle adapters and final package conformance still need completion; + inherited ALPM preservation alone does not implement new runtime actions. +8. PrepareUpdate now invokes declaration rebuild for retained overlays against the + verified target base, then prepares exact Host Extension reapplication and uses + the overlay executor. This requires the target base's versioned build policy; + policy provisioning, build tools/lifecycle coverage and runtime acceptance are + still incomplete. Capability remains disabled. + +## Hardware enablement goal + +Update semantics clarified by the user: rebuild selected declarations into new +Managed Overlay commits against the new common snapshot, then reapply Host +Extensions. Compatible prepublished layer commits are not a prerequisite for an +update. Source manifests/inputs are intentions; commit/lock identities describe +one resolved build. A generic YAML-overlay builder is still missing from builder; +the existing private Core/GNOME/KDE scripts do not implement this lifecycle. + +The user's target is a reusable foundation for NVIDIA and other proprietary +hardware support. Current architecture models hardware adaptation as Managed +Overlays plus profiles selecting them; this audit does not introduce a fourth +LayerKind or declare a new architecture decision. + +Required before claiming hardware readiness: + +- Finish the generic complete-list PrepareSet → inspectable plan → Stage path, + including remove/reorder, update reapplication and rollback retention. +- Implement verified kernel binding: package archive identity, exact release and + ABI evidence. `artifact::validate_compatibility` currently rejects every kernel + binding. Removing that rejection without an evidence adapter is not a fix. +- Bind binary modules to the exact kernel, or execute reviewed DKMS inputs in + isolated staging; depmod precedes initramfs generation. Required failures abort. +- Carry firmware, userspace libraries and vendor configuration through ordinary + indexed package/file ownership. Version conflicts and file replacements remain + explicit; NVIDIA graphics/multilib integration needs profile-specific checks. +- Validate runtime units/tmpfiles/sysusers declarations and their target lifecycle; + installation must not mutate live /usr or silently reset administrator settings. +- Demonstrate atomic kernel+driver updates and failure preservation in the normal + pipeline. GPU behavior additionally needs relevant hardware or passthrough + evidence; a generic UEFI VM cannot prove NVIDIA acceleration. +- Secure Boot/module signing is outside the currently selected non-Secure-Boot + profile; do not advertise that support without its own implemented contract. + +## Execution order after this audit + +Compatibility requirement: existing installations must update through their +current signed image track without first acquiring new overlay metadata/policy. +Refresh/update age comparisons now use the retained clean upstream identity for +local overlay compositions; hosts without overlay metadata keep their old path. +Clean bases are signature-verified and retained in the sysroot repository. +The pipeline still needs an old-published-image → new-candidate upgrade scenario; +source fixtures and clean-install VM results cannot establish this transition. + +1. Finish generic composition/lifecycle/replacement prerequisites needed by the + PrepareSet plan, with bounded inputs and indexed lookups. +2. Implement exported PrepareSet and immutable context-bound plans, then explicit + Overlays execution dispatch, commit/stage and extension reapplication. +3. Complete CLI/catalog producer/profile and migrate normal acceptance scenarios. +4. Close kernel ABI/module adapters against the hardware goal; retain explicit + unsupported errors until they have real evidence. +5. Run normal source/VM checks and publication workflow; record source SHAs, + signatures, installed behavior and remaining hardware evidence separately. diff --git a/SERVICE.md b/SERVICE.md index e30a12e..52791b1 100644 --- a/SERVICE.md +++ b/SERVICE.md @@ -1,6 +1,6 @@ # archipelagod implementation checkpoint -2026-11-07. D-092/D-093 are accepted; the full service migration is in progress. +2026-11-08. D-092/D-093 are accepted; the full service migration is in progress. **D-095 supersedes the PackageKit work below:** the backend, broker and store adaptations have been removed. Host Extension package installation is through @@ -10,24 +10,39 @@ The older PackageKit build notes below are historical evidence only. ## Current integration work (not yet accepted or published) +Installed-host CLI now exposes `overlay status`, `overlay list [QUERY [CURSOR]]`, +`overlay add ID EXACT_COMMIT`, `overlay remove ID`, `overlay order ALL_IDS...` and +`overlay clear`. Mutations submit a complete list with GetState's context, then +Stage the returned plan. Reordering must name every selected overlay once. +Installed-bus acceptance and declaration rebuild-on-update remain unfinished. + The read-only foundation below describes the last published source slice. The working tree now adds durable asynchronous mutations, worker supervision, -original-subject PackageKit delegation, FD imports, extension planning and native +FD imports, extension planning and native D-Bus clients. Installed-host CLI dispatch uses the service; unsupported workflows fail without falling back to direct mutation. General Managed Overlay execution and the corresponding capability/acceptance migration remain unfinished. -The PackageKit backend is built with pinned upstream 1.4.0 and a narrowly scoped -Sender/transaction-path handoff. Simulation consumes the daemon's added/removed -inventory diff. Additional removals require `allow_deps`; recomposition retains -the surviving explicit requests and never uses autoremove as permission to remove -managed packages. GNOME's pending adaptation queries HostExtensions GetState and -Resolve asynchronously rather than interpreting opaque PackageKit ID data. +ManagedOverlays now registers GetState, ListAvailable, GetOverlay, RefreshCatalog +and Revision with ObjectManager/signals. Refresh resolves the private configured +`overlay_catalog_ref` through signed OSTree summary/commit verification and checks +each indexed layer against its manifest before caching context-bound descriptors. +The profile/catalog producer is not deployed. PrepareSet and the general overlay +capability remain absent. + +The private composition worker connects indexed artifacts to path planning, +materialization and effective ALPM records, with retained original records and +transformation provenance. Its offline finalizer reuses +`adapters/finalize-managed.sh`, also used by Host Extensions. These composition +functions are not yet called by an admitted PrepareSet/Stage workflow. Legacy +Core/Purpose artifact producers, full base indexing/lifecycle adapters, +whole-package replacement and complete overlay/extension update reapplication +remain integration work. Existing test-marker acceptance does not cover this API. Native GNOME and Discover OS clients observe retained transactions through D-Bus. Legacy software-helper and its broad Polkit policy are no longer packaged in the -Desktop assets. Latest native/Rust compilation and normal-pipeline runtime -acceptance are pending; no new release has been started. See the workspace +Desktop assets. Rust system/composer test binaries compile as of 2026-11-08; +normal-pipeline runtime acceptance remains pending and no new release has started. See the workspace `IMPLEMENTATION-PLAN-DBUS.md` for current build handles and remaining work. ## Previously published foundation diff --git a/adapters/extensions.sh b/adapters/extensions.sh index c82986a..b6f4780 100644 --- a/adapters/extensions.sh +++ b/adapters/extensions.sh @@ -137,6 +137,7 @@ systemd-nspawn --settings=no --register=no --private-network --resolv-conf=off " --bind-ro="$generation/transaction-targets:/requested" --bind-ro="$generation/base-packages:/base-packages" \ --bind-ro="$generation/requested:/explicit-requested" \ --bind="$generation/logs:/evidence" --bind-ro="$generation/dkms-finalize.sh:/dkms-finalize.sh" \ + --bind-ro="$generation/finalize-managed.sh:/finalize-managed.sh" \ /bin/bash -euo pipefail -c ' export LC_ALL=C cd /inputs; sha256sum -c SHA256SUMS; cd / @@ -165,30 +166,7 @@ systemd-nspawn --settings=no --register=no --private-network --resolv-conf=off " /bin/bash /dkms-finalize.sh fi pacman -Q > /usr/lib/archipelago/packages.txt - ldconfig - systemd-hwdb update --usr - if command -v glib-compile-schemas >/dev/null; then glib-compile-schemas /usr/share/glib-2.0/schemas; fi - if command -v gio-querymodules >/dev/null; then gio-querymodules /usr/lib/gio/modules; fi - if command -v update-desktop-database >/dev/null; then update-desktop-database /usr/share/applications; fi - if command -v update-mime-database >/dev/null; then update-mime-database /usr/share/mime; fi - if command -v gtk-update-icon-cache >/dev/null; then - for theme in /usr/share/icons/*; do - [[ ! -f $theme/index.theme ]] || gtk-update-icon-cache -q -t -f "$theme" - done - fi - update-ca-trust - for modules in /usr/lib/modules/*; do - [[ -f $modules/vmlinuz ]] || continue - kernel=${modules##*/} - depmod "$kernel" - config=/usr/lib/archipelago/mkinitcpio-core.conf - if [[ -f /usr/lib/archipelago/mkinitcpio-gnome.conf ]]; then - config=/usr/lib/archipelago/mkinitcpio-gnome.conf - elif [[ -f /usr/lib/archipelago/mkinitcpio-kde.conf ]]; then - config=/usr/lib/archipelago/mkinitcpio-kde.conf - fi - mkinitcpio --nocolor -c "$config" -k "$kernel" -g "$modules/initramfs.img" - done + /bin/bash -euo pipefail /finalize-managed.sh ' 2>&1 | tee "$generation/logs/transaction.log" if grep -Ei 'error:|warning:.*(failed|failure)' "$generation/logs/transaction.log"; then echo 'Required package action/finalization failed; no deployment prepared' >&2; exit 1 diff --git a/adapters/finalize-managed.sh b/adapters/finalize-managed.sh new file mode 100644 index 0000000..9548d1d --- /dev/null +++ b/adapters/finalize-managed.sh @@ -0,0 +1,27 @@ +# Shared offline finalization for an already composed private OS tree. +# Run inside the generation's private-network nspawn after package/ABI checks. +export LC_ALL=C +ldconfig +systemd-hwdb update --usr +if command -v glib-compile-schemas >/dev/null; then glib-compile-schemas /usr/share/glib-2.0/schemas; fi +if command -v gio-querymodules >/dev/null; then gio-querymodules /usr/lib/gio/modules; fi +if command -v update-desktop-database >/dev/null; then update-desktop-database /usr/share/applications; fi +if command -v update-mime-database >/dev/null; then update-mime-database /usr/share/mime; fi +if command -v gtk-update-icon-cache >/dev/null; then + for theme in /usr/share/icons/*; do + [[ ! -f $theme/index.theme ]] || gtk-update-icon-cache -q -t -f "$theme" + done +fi +update-ca-trust +for modules in /usr/lib/modules/*; do + [[ -f $modules/vmlinuz ]] || continue + kernel=${modules##*/} + depmod "$kernel" + config=/usr/lib/archipelago/mkinitcpio-core.conf + if [[ -f /usr/lib/archipelago/mkinitcpio-gnome.conf ]]; then + config=/usr/lib/archipelago/mkinitcpio-gnome.conf + elif [[ -f /usr/lib/archipelago/mkinitcpio-kde.conf ]]; then + config=/usr/lib/archipelago/mkinitcpio-kde.conf + fi + mkinitcpio --nocolor -c "$config" -k "$kernel" -g "$modules/initramfs.img" +done diff --git a/src/extensions.rs b/src/extensions.rs index 733c15e..5b6d1f4 100644 --- a/src/extensions.rs +++ b/src/extensions.rs @@ -210,6 +210,7 @@ fn compose(generation: &Path, id: &str, base: &str, snapshot: &str, run("ostree", &[REPO, "checkout", "--force-copy", base, rootstr])?; write(generation.join("dkms-policy.tsv"), include_str!("../adapters/dkms-policy.tsv"))?; write(generation.join("dkms-finalize.sh"), include_str!("../adapters/dkms-finalize.sh"))?; + write(generation.join("finalize-managed.sh"), include_str!("../adapters/finalize-managed.sh"))?; let transaction = Command::new("/bin/bash").args(["-euo", "pipefail", "-c", include_str!("../adapters/extensions.sh"), "archipelago-extension"]) .arg(generation).status().map_err(|e| e.to_string())?; diff --git a/src/service/client.rs b/src/service/client.rs index 25da1d0..f653689 100644 --- a/src/service/client.rs +++ b/src/service/client.rs @@ -41,6 +41,13 @@ impl Client { } fn operation(&self, packages: bool, method: &str, body: &B) -> Result { let proxy = self.proxy(packages)?; + self.operation_on(&proxy, method, body) + } + fn overlay_proxy(&self) -> Result,String> { + Proxy::new(&self.connection, BUS_NAME, "/org/archipelago/System1/ManagedOverlays", + "org.archipelago.System1.ManagedOverlays").map_err(error) + } + fn operation_on(&self, proxy: &Proxy<'_>, method: &str, body: &B) -> Result { let flags = if self.interactive { MethodFlags::AllowInteractiveAuth.into() } else { Default::default() }; let path: OwnedObjectPath = proxy.call_with_flags(method,flags,body).map_err(error)?.ok_or("Missing operation reply")?; let id = path.as_str().rsplit('/').next().and_then(|p| p.strip_prefix("op_")).ok_or("Invalid operation object path")?; @@ -92,6 +99,31 @@ impl Client { } fn dispatch(&self, args: &[&str]) -> Result { match args { + ["overlay", "status"] => { + let proxy = self.overlay_proxy()?; + self.operation_on(&proxy, "RefreshCatalog", &(self.options(),))?; + map(proxy.call("GetState", &()).map_err(error)?) + } + ["overlay", "list"] | ["overlay", "list", _] | ["overlay", "list", _, _] => { + let proxy = self.overlay_proxy()?; + self.operation_on(&proxy, "RefreshCatalog", &(self.options(),))?; + let query = args.get(2).copied().unwrap_or(""); + let cursor = args.get(3).copied().unwrap_or(""); + let (rows, next, context): (Vec, String, String) = proxy.call("ListAvailable", + &(query, cursor, 100u32)).map_err(error)?; + Ok(json!({"overlays":rows.into_iter().map(map).collect::,_>>()?, + "next_cursor":next,"context_id":context})) + } + ["overlay", operation, rest @ ..] if matches!(*operation, "add" | "remove" | "order" | "clear") => { + let proxy = self.overlay_proxy()?; + self.operation_on(&proxy, "RefreshCatalog", &(self.options(),))?; + let state = map(proxy.call("GetState", &()).map_err(error)?)?; + let context = state["context_id"].as_str().ok_or("Missing overlay context")?; + let selected = edit_overlays(&state["desired"]["selection"], operation, rest)?; + let wire: Vec = selected.iter().map(|item| Dictionary::from([ + ("overlay_id".into(), text(&item.overlay_id)), ("commit".into(), text(&item.commit))])).collect(); + self.stage(self.operation_on(&proxy, "PrepareSet", &(wire, context, self.options()))?) + } ["status"] => self.query(false,"GetStatus"), ["transaction", "list"] | ["transaction", "list", _] => { let cursor = args.get(2).copied().unwrap_or(""); @@ -203,6 +235,49 @@ impl Client { } } +fn edit_overlays(value: &Value, operation: &str, args: &[&str]) -> Result, String> { + let mut selection: Vec = serde_json::from_value(value.clone()).map_err(error)?; + match (operation, args) { + ("add", [id, commit]) => { + if id.is_empty() || id.len() > 1024 || !archipelago_contracts::system_bus::checksum(commit) { + return Err("Expected overlay add ID EXACT_COMMIT".into()); + } + if selection.iter().any(|item| item.overlay_id == *id) { return Err("Overlay already selected".into()); } + selection.push(super::plans::Overlay { overlay_id:(*id).into(), commit:(*commit).into() }); + } + ("remove", [id]) => { + let index = selection.iter().position(|item| item.overlay_id == *id).ok_or("Overlay is not selected")?; + selection.remove(index); + } + ("clear", []) => selection.clear(), + ("order", ids) => { + if ids.len() != selection.len() { return Err("Order must name every selected overlay exactly once".into()); } + let mut by_id: std::collections::BTreeMap<_, _> = selection.into_iter().map(|item| (item.overlay_id.clone(), item)).collect(); + selection = ids.iter().map(|id| by_id.remove(*id).ok_or_else(|| "Unknown or duplicate overlay in order".to_string())) + .collect::>()?; + } + _ => return Err("Expected overlay add ID COMMIT | remove ID | order ID... | clear".into()), + } + Ok(selection) +} + +#[cfg(test)] +mod overlay_tests { + use super::*; + #[test] + fn complete_list_edits_preserve_commits_and_reject_lost_entries() { + let source = json!([{"overlay_id":"one","commit":"a".repeat(64)}, + {"overlay_id":"two","commit":"b".repeat(64)}]); + let reordered = edit_overlays(&source, "order", &["two", "one"]).unwrap(); + assert_eq!(reordered[0].commit, "b".repeat(64)); + assert!(edit_overlays(&source, "order", &["one"]).is_err()); + assert!(edit_overlays(&source, "order", &["one", "one"]).is_err()); + assert!(edit_overlays(&source, "remove", &["absent"]).is_err()); + assert_eq!(edit_overlays(&source, "remove", &["one"]).unwrap()[0].overlay_id, "two"); + assert!(edit_overlays(&source, "clear", &[]).unwrap().is_empty()); + } +} + pub fn dispatch(args: &[String]) -> Result<(),String> { let mut interactive = false; let mut offline = false; diff --git a/src/service/managed_overlays.rs b/src/service/managed_overlays.rs new file mode 100644 index 0000000..8e7a78c --- /dev/null +++ b/src/service/managed_overlays.rs @@ -0,0 +1,100 @@ +//! Typed managed overlay catalog transport. All network/filesystem work runs in +//! the admitted worker; read RPCs consume its context-bound verified projection. +use super::{authorization::{self, Action}, overlays, runtime::Runtime, wire, BusError, Dictionary}; +use archipelago_contracts::system_bus::{self, Method}; +use std::sync::{Arc, RwLock}; +use zbus::{Connection, message::Header, zvariant::OwnedObjectPath}; + +pub struct ManagedOverlays { pub runtime: Arc, pub status: Arc> } + +#[zbus::interface(name = "org.archipelago.System1.ManagedOverlays")] +impl ManagedOverlays { + #[zbus(out_args("transaction"))] + async fn prepare_set(&self, selection: Vec, context_id: &str, options: Dictionary, + #[zbus(connection)] connection: &Connection, #[zbus(header)] header: Header<'_>) -> Result { + if !system_bus::checksum(context_id) || selection.len() > 256 { + return Err(BusError::InvalidArgument("Invalid overlay context or selection size".into())); + } + let mut names = std::collections::BTreeSet::new(); + let mut selected = Vec::new(); + let mut bytes = 0; + for row in selection { + if row.len() != 2 || !row.contains_key("overlay_id") || !row.contains_key("commit") { + return Err(BusError::InvalidArgument("Expected overlay_id and commit only".into())); + } + let id = <&str>::try_from(&row["overlay_id"]).map_err(|_| BusError::InvalidArgument("Invalid overlay_id type".into()))?; + let commit = <&str>::try_from(&row["commit"]).map_err(|_| BusError::InvalidArgument("Invalid commit type".into()))?; + bytes += id.len() + commit.len(); + if id.is_empty() || id.len() > 1024 || !system_bus::checksum(commit) || !names.insert(id.to_owned()) || + bytes > system_bus::MAX_REQUEST_BYTES { + return Err(BusError::InvalidArgument("Invalid, duplicate or oversized overlay selection".into())); + } + selected.push(super::plans::Overlay { overlay_id:id.into(), commit:commit.into() }); + } + let options = wire::options(Method::PrepareSet, options)?; + let caller = authorization::authorize(connection, &header, &options, Action::OverlayChange, None).await?; + let uid = caller.uid; + let offline = options.offline; + let context = context_id.to_owned(); + self.runtime.submit(connection, caller, Method::PrepareSet, options, + serde_json::json!({"selection":selected,"context_id":context}), "", move |worker| + overlays::prepare_set(worker, selected, &context, uid, offline)).await + } + + #[zbus(out_args("state"))] + fn get_state(&self) -> Result { + let catalog = overlays::catalog()?; + let mut state = catalog["state"].clone(); + state["revision"] = serde_json::json!(self.revision().map_err(|_| BusError::Unavailable("Observer unavailable".into()))?); + wire::map(&state) + } + + #[zbus(out_args("overlays", "next_cursor", "context_id"))] + fn list_available(&self, query: &str, cursor: &str, limit: u32) -> Result<(Vec, String, String), BusError> { + if query.len() > 1024 || limit == 0 || limit > system_bus::MAX_PAGE_ENTRIES { + return Err(BusError::InvalidArgument("Invalid overlay query bounds".into())); + } + let catalog = overlays::catalog()?; + let context = catalog["context_id"].as_str().ok_or_else(|| BusError::Unavailable("Missing catalog context".into()))?; + let query = query.to_lowercase(); + let rows: Vec<_> = catalog["overlays"].as_array().ok_or_else(|| BusError::Unavailable("Invalid overlay catalog".into()))?.iter() + .filter(|row| row["overlay_id"].as_str().unwrap_or("").to_lowercase().contains(&query)).collect(); + let binding = super::storage::hash(serde_json::json!([context,catalog["catalog_commit"],query]).to_string().as_bytes()); + let token = |position: usize| super::storage::hash(format!("{binding}:{position}").as_bytes()); + let start = if cursor.is_empty() { 0 } else { (1..=rows.len()).find(|&n| token(n) == cursor) + .ok_or_else(|| BusError::PlanStale("Overlay cursor does not match catalog/query".into()))? }; + let end = (start + limit as usize).min(rows.len()); + Ok((rows[start..end].iter().map(|row| wire::map(&serde_json::json!({ + "overlay_id":row["overlay_id"],"commit":row["commit"],"snapshot_id":row["snapshot_id"], + "architecture":row["architecture"],"compatible_snapshot":row["compatible_snapshot"], + "version":row["manifest"]["metadata"]["version"]}))).collect::,_>>()?, + if end < rows.len() { token(end) } else { String::new() }, context.into())) + } + + #[zbus(out_args("overlay"))] + fn get_overlay(&self, overlay_id: &str, commit: &str) -> Result { + if overlay_id.is_empty() || overlay_id.len() > 1024 || !system_bus::checksum(commit) { + return Err(BusError::InvalidArgument("Invalid overlay identity".into())); + } + let catalog = overlays::catalog()?; + let value = catalog["overlays"].as_array().ok_or_else(|| BusError::Unavailable("Invalid overlay catalog".into()))?.iter() + .find(|row| row["overlay_id"] == overlay_id && row["commit"] == commit) + .ok_or_else(|| BusError::NotFound("Exact overlay commit is not in the verified catalog".into()))?; + wire::map(value) + } + + #[zbus(out_args("transaction"))] + async fn refresh_catalog(&self, options: Dictionary, #[zbus(connection)] connection: &Connection, + #[zbus(header)] header: Header<'_>) -> Result { + let options = wire::options(Method::RefreshCatalog, options)?; + let caller = authorization::authorize(connection, &header, &options, Action::Refresh, None).await?; + let offline = options.offline; let force = options.force; + self.runtime.submit(connection, caller, Method::RefreshCatalog, options, + super::packages::refresh_binding("overlays")?, "", move |worker| overlays::refresh_catalog(worker, offline, force)).await + } + + #[zbus(property)] + fn revision(&self) -> zbus::fdo::Result { + self.status.read().map(|s| s.revision).map_err(|_| zbus::fdo::Error::Failed("Observer unavailable".into())) + } +} diff --git a/src/service/mod.rs b/src/service/mod.rs index b58c31b..4804bf2 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -14,6 +14,9 @@ mod inputs; mod runtime; mod host_extensions; pub(crate) mod packages; +pub(crate) mod overlays; +mod managed_overlays; +pub(crate) mod overlay_build; use archipelago_contracts::system_bus::{self as protocol, BUS_NAME, MANAGER_INTERFACE, MANAGER_PATH}; use std::{collections::HashMap, fs, os::unix::fs::MetadataExt, @@ -101,6 +104,7 @@ impl Manager { self.runtime.submit(connection, caller, method, options, serde_json::json!({"plan_id":id,"target":plan.target}), "", move |worker| { if matches!(plan.intent, plans::Intent::Enable { .. }) { packages::configure(worker, &plan, download) } else if matches!(plan.intent, plans::Intent::Change { .. } | plans::Intent::Restore { .. }) { packages::execute_change(worker, &plan, download, offline) } + else if matches!(plan.intent, plans::Intent::Overlays { .. }) { overlays::execute(worker, &plan, download, offline) } else { crate::updates::managed::execute(worker, &plan, download, offline) } }).await } @@ -251,6 +255,8 @@ impl ObjectRegistry { HashMap::from([(MANAGER_INTERFACE.into(), HashMap::from([("StatusRevision".into(), OwnedValue::from(revision))]))]))]); objects.insert(OwnedObjectPath::try_from("/org/archipelago/System1/HostExtensions").expect("constant path"), HashMap::from([("org.archipelago.System1.HostExtensions".into(),Dictionary::from([("Revision".into(),revision.into())]))])); + objects.insert(OwnedObjectPath::try_from("/org/archipelago/System1/ManagedOverlays").expect("constant path"), + HashMap::from([("org.archipelago.System1.ManagedOverlays".into(),Dictionary::from([("Revision".into(),revision.into())]))])); let journal = self.runtime.journal.lock().map_err(|_| BusError::Unavailable("Journal unavailable".into()))?; for record in journal.records().filter(|r| !r.state.terminal()) { let path = OwnedObjectPath::try_from(protocol::transaction_path(&record.id).expect("retained operation identity")).expect("transaction path"); @@ -282,6 +288,7 @@ pub fn run() -> Result<(), String> { .serve_at(MANAGER_PATH, Manager { status: status.clone(), runtime: runtime.clone() }).map_err(|e| e.to_string())? .serve_at(MANAGER_PATH, ObjectRegistry { status: status.clone(), runtime: runtime.clone() }).map_err(|e| e.to_string())? .serve_at("/org/archipelago/System1/HostExtensions", host_extensions::HostExtensions { runtime: runtime.clone(),status:status.clone() }).map_err(|e| e.to_string())? + .serve_at("/org/archipelago/System1/ManagedOverlays", managed_overlays::ManagedOverlays { runtime: runtime.clone(),status:status.clone() }).map_err(|e| e.to_string())? .name(BUS_NAME).map_err(|e| e.to_string())?.build().map_err(|e| e.to_string())?; let mut revisions = HashMap::new(); let mut last_observation = std::time::Instant::now() - Duration::from_secs(5); @@ -330,6 +337,9 @@ pub fn run() -> Result<(), String> { connection.emit_signal(None::<&str>, "/org/archipelago/System1/HostExtensions", "org.freedesktop.DBus.Properties", "PropertiesChanged", &("org.archipelago.System1.HostExtensions", HashMap::from([("Revision", OwnedValue::from(revision))]),Vec::::new())).map_err(|e| e.to_string())?; + connection.emit_signal(None::<&str>, "/org/archipelago/System1/ManagedOverlays", "org.freedesktop.DBus.Properties", + "PropertiesChanged", &("org.archipelago.System1.ManagedOverlays", + HashMap::from([("Revision", OwnedValue::from(revision))]),Vec::::new())).map_err(|e| e.to_string())?; } std::thread::sleep(Duration::from_millis(100)); } diff --git a/src/service/overlay_build.rs b/src/service/overlay_build.rs new file mode 100644 index 0000000..01b0e56 --- /dev/null +++ b/src/service/overlay_build.rs @@ -0,0 +1,116 @@ +//! Supervised generic overlay build invocation; inputs are engine-owned paths. +use super::{storage, worker::{Failure, Result, Worker}}; +use archipelago_contracts::system_bus::{self, ErrorCode, Phase}; +use serde_json::{json, Value}; +use std::{fs, path::Path, time::Duration}; + +fn fail(message: impl Into) -> Failure { Failure::new(ErrorCode::ExecutionFailed, message) } + +/// Rebuild an authenticated source artifact for the selected snapshot. Original +/// authored hashes bind source bytes; the new lock is produced by the resolver. +pub(crate) fn rebuild(worker: &Worker, ordinal: u32, base: &Path, + source: &archipelago_composer::artifact::Artifact, snapshot: &str, offline: bool) + -> Result { + let parent = Path::new("/var/lib/archipelago/service/overlay-work").join(worker.events.id()); + storage::directory(&parent)?; + let sources = parent.join(format!("rebuild-sources-{ordinal}")); + if sources.symlink_metadata().is_ok() { return Err(fail("Rebuild sources already exist")); } + storage::directory(&sources)?; + let declared = source.lock["authored_sources"].as_object().ok_or_else(|| fail("Missing authored source hashes"))?; + let mut by_hash = std::collections::BTreeMap::new(); + for row in &source.payload { + if row.package.is_none() { + if let archipelago_composer::paths::Kind::File { sha256 } = &row.object.kind { + by_hash.entry(sha256.as_str()).or_insert(&row.source); + } + } + } + for (relative, hash) in declared { + let path = Path::new(relative); + if path.components().any(|c| !matches!(c, std::path::Component::Normal(_))) || relative.is_empty() { + return Err(fail("Invalid authored source path")); + } + let digest = hash.as_str().filter(|s| system_bus::checksum(s)).ok_or_else(|| fail("Invalid source hash"))?; + let payload = by_hash.get(digest).ok_or_else(|| fail("Authored source bytes are not retained in artifact"))?; + let bytes = fs::read(payload.root.join(payload.path.trim_start_matches('/'))).map_err(storage::io_error)?; + if storage::hash(&bytes) != digest { return Err(fail("Retained authored source changed")); } + let destination = sources.join(path); + fs::create_dir_all(destination.parent().ok_or_else(|| fail("Invalid source parent"))?).map_err(storage::io_error)?; + fs::write(destination, bytes).map_err(storage::io_error)?; + } + let policy_path = base.join("usr/lib/archipelago/hook-policy/overlay-build.json"); + if !policy_path.is_file() || policy_path.is_symlink() { + return Err(Failure::new(ErrorCode::Unsupported, "Signed base lacks a versioned overlay build action policy")); + } + let policy: Value = storage::json(&policy_path)?; + let bootstrap = parent.join(format!("rebuild-bootstrap-{ordinal}")); + if bootstrap.symlink_metadata().is_ok() { return Err(fail("Rebuild bootstrap already exists")); } + worker.command("/usr/bin/cp", &["--archive", "--reflink=auto", "--", base.to_str().ok_or_else(|| fail("Invalid base path"))?, + bootstrap.to_str().ok_or_else(|| fail("Invalid bootstrap path"))?], Duration::from_secs(600), true)?; + if bootstrap.join("etc").symlink_metadata().is_ok() { return Err(fail("Unexpected bootstrap /etc")); } + fs::rename(bootstrap.join("usr/etc"), bootstrap.join("etc")).map_err(storage::io_error)?; + let result = build(worker, ordinal, &bootstrap, &sources, &source.manifest.to_string(), &policy, snapshot, offline)?; + let commit = result["commit"].as_str().ok_or_else(|| fail("Missing built commit"))?; + let checkout = parent.join(format!("rebuilt-{ordinal}")); + worker.command("/usr/bin/ostree", &["--repo=/sysroot/ostree/repo", "checkout", "--force-copy", commit, + checkout.to_str().ok_or_else(|| fail("Invalid built checkout path"))?], Duration::from_secs(600), true)?; + let checker = parent.join("rebuilt-artifact.py"); + fs::write(&checker, archipelago_composer::artifact::CHECKER).map_err(storage::io_error)?; + fs::write(parent.join("materialize.py"), archipelago_composer::MATERIALIZER).map_err(storage::io_error)?; + let output = worker.command("/usr/bin/python3", &["-I", "-B", checker.to_str().ok_or_else(|| fail("Invalid checker path"))?, + checkout.to_str().ok_or_else(|| fail("Invalid checkout path"))?], Duration::from_secs(600), true)?; + let checked = serde_json::from_str(&output).map_err(|_| fail("Invalid rebuilt artifact output"))?; + let artifact = archipelago_composer::artifact::read_checked(&checkout, commit, checked).map_err(fail)?; + if artifact.layer.id != source.layer.id || artifact.manifest != source.manifest || + artifact.layer.header.snapshot_id != snapshot || artifact.lock_sha256 != result["lock_sha256"].as_str().unwrap_or("") { + return Err(fail("Rebuilt artifact differs from requested declaration/target")); + } + Ok(artifact) +} + +/// Bootstrap is a disposable authenticated target-snapshot checkout with runtime +/// /etc. Sources and action policy must have been verified against retained source +/// and profile identities by the caller. No caller-controlled URL/key/argv enters. +pub(crate) fn build(worker: &Worker, ordinal: u32, bootstrap: &Path, sources: &Path, + manifest: &str, policy: &Value, snapshot: &str, offline: bool) -> Result { + if !system_bus::operation_id(worker.events.id()) || !system_bus::checksum(snapshot) || ordinal >= 256 { + return Err(fail("Invalid overlay build identity")); + } + let normalized = archipelago_builder::overlay::normalize(manifest).map_err(fail)?; + for path in [bootstrap, sources] { + if !path.is_absolute() || !fs::symlink_metadata(path).map_err(storage::io_error)?.is_dir() || + path.ancestors().any(|parent| parent.is_symlink()) { + return Err(fail("Invalid protected overlay build input")); + } + } + let parent = Path::new("/var/lib/archipelago/service/overlay-build"); + storage::directory(parent)?; + let name = format!("{}-{ordinal}", worker.events.id()); + let work = parent.join(&name); + if work.symlink_metadata().is_ok() { return Err(fail("Overlay build workspace already exists")); } + worker.events.checkpoint(Phase::Composing, true, "Building a managed overlay from its declaration")?; + worker.events.effect(&format!("overlay_build_{ordinal}"), json!(name))?; + storage::directory(&work)?; + storage::directory(&work.join("adapters"))?; + fs::write(work.join("manifest.json"), normalized).map_err(storage::io_error)?; + storage::atomic(&work.join("policy.json"), policy)?; + for (name, source) in archipelago_builder::overlay::adapters() { + fs::write(work.join("adapters").join(name), source).map_err(storage::io_error)?; + } + fs::write(work.join("adapters/artifact.py"), archipelago_composer::artifact::CHECKER).map_err(storage::io_error)?; + fs::write(work.join("adapters/materialize.py"), archipelago_composer::MATERIALIZER).map_err(storage::io_error)?; + let text = |path: &Path| path.to_str().map(str::to_owned).ok_or_else(|| fail("Non-UTF-8 workspace path")); + worker.command("/usr/bin/cp", &["--archive", "--reflink=auto", "--", &text(sources)?, + &text(&work.join("sources"))?], Duration::from_secs(600), true)?; + worker.command("/bin/bash", &["-euo", "pipefail", &text(&work.join("adapters/build-overlay.sh"))?, + &text(&work)?, &text(bootstrap)?, snapshot, "/sysroot/ostree/repo", + &format!("service/overlay-builds/{name}"), if offline {"1"} else {"0"}], Duration::from_secs(7200), true)?; + let result: Value = storage::json(&work.join("result.json"))?; + if result["version"] != 0 || result["snapshot_id"] != snapshot || + !result["commit"].as_str().is_some_and(system_bus::checksum) || + !result["lock_sha256"].as_str().is_some_and(system_bus::checksum) { + return Err(fail("Invalid overlay build result")); + } + worker.events.effect(&format!("overlay_built_{ordinal}"), result.clone())?; + Ok(result) +} diff --git a/src/service/overlays.rs b/src/service/overlays.rs new file mode 100644 index 0000000..7d8ecca --- /dev/null +++ b/src/service/overlays.rs @@ -0,0 +1,378 @@ +//! Protected indexed-layer inputs for the managed composition worker. +//! Catalog admission and PrepareSet execution must use this loader under the +//! shared sysroot lock; arbitrary paths/remote keys are not D-Bus inputs. +use super::{storage, worker::{Failure, Result, Worker}}; +use archipelago_composer::{artifact::{self, Artifact}, compose}; +use archipelago_contracts::system_bus::{self, ErrorCode}; +use serde_json::json; +use std::{fs, path::{Path, PathBuf}, time::Duration}; + +const CATALOG: &str = "/var/lib/archipelago/service/overlay-catalog.json"; + +pub(crate) fn execute(worker: &Worker, plan: &super::plans::Plan, download: bool, offline: bool) -> Result { + let _lock = crate::updates::lock().map_err(|_| Failure::new(ErrorCode::Busy, "Sysroot unavailable or provisioning incomplete"))?; + let (context, state) = super::packages::current(worker)?; + plan.check_context(&context)?; + crate::updates::managed::ensure_pending_owned(worker, &state)?; + let super::plans::Intent::Overlays { selection } = &plan.intent else { + return Err(Failure::new(ErrorCode::InvalidArgument, "Expected overlay plan")); + }; + if plan.inputs["overlay"]["finalizer_sha256"] != storage::hash(include_bytes!("../../adapters/finalize-managed.sh")) { + return Err(Failure::new(ErrorCode::PlanStale, "Managed finalizer changed")); + } + // This is a locally composed commit bound by the service-owned immutable + // plan, not an unsigned remote image admitted as a distribution base. + let raw = worker.command("/usr/bin/ostree", &["--repo=/sysroot/ostree/repo", "cat", &plan.target, + "/usr/lib/archipelago/managed-overlays.json"], Duration::from_secs(60), true)?; + let retained: serde_json::Value = serde_json::from_str(&raw).map_err(|_| failure("Invalid retained overlay intent"))?; + if retained["version"] != 0 || retained["selection"] != json!(selection) || retained["inputs"] != plan.inputs["overlay"] { + return Err(Failure::new(ErrorCode::TrustFailed, "Prepared composition does not match overlay plan")); + } + super::packages::execute_locked(worker, plan, download, offline) +} + +pub(crate) fn prepare_set(worker: &Worker, selection: Vec, expected_context: &str, + uid: u32, offline: bool) -> Result { + let _lock = crate::updates::lock().map_err(|_| Failure::new(ErrorCode::Busy, "Sysroot unavailable or provisioning incomplete"))?; + prepare_set_locked(worker, selection, expected_context, uid, offline, None) +} + +/// Caller holds the update/sysroot lock and has verified the target image track. +pub(crate) fn prepare_update(worker: &Worker, target: &str, context: &super::plans::Context, + intent: &serde_json::Value, uid: u32, offline: bool) -> Result { + let selection: Vec = serde_json::from_value(intent["selection"].clone()) + .map_err(|_| failure("Invalid retained overlay selection"))?; + prepare_set_locked(worker, selection, &super::packages::context_id(context)?, uid, offline, Some(target)) +} + +fn prepare_set_locked(worker: &Worker, selection: Vec, expected_context: &str, + uid: u32, offline: bool, update_target: Option<&str>) -> Result { + let (context, state) = super::packages::current(worker)?; + if super::packages::context_id(&context)? != expected_context { + return Err(Failure::new(ErrorCode::PlanStale, "Host context changed")); + } + crate::updates::managed::ensure_pending_owned(worker, &state)?; + let catalog = if update_target.is_none() { catalog()? } else { + json!({"context_id":expected_context,"catalog_commit":null,"overlays":selection}) + }; + if catalog["context_id"] != expected_context { return Err(Failure::new(ErrorCode::PlanStale, "Refresh overlay catalog")); } + let available: std::collections::BTreeSet<_> = catalog["overlays"].as_array() + .ok_or_else(|| failure("Missing catalog entries"))?.iter().filter_map(|row| + Some((row["overlay_id"].as_str()?, row["commit"].as_str()?))).collect(); + for item in &selection { + if !available.contains(&(item.overlay_id.as_str(), item.commit.as_str())) { + return Err(Failure::new(ErrorCode::NotFound, "Selected exact overlay is absent from verified catalog")); + } + } + worker.events.checkpoint(system_bus::Phase::Planning, true, "Checking the complete ordered overlay selection")?; + let projection = project_state(worker, &state, &context)?; + let clean_base = update_target.or_else(|| projection["desired"]["clean_base"].as_str()).filter(|s| system_bus::checksum(s)) + .ok_or_else(|| failure("Missing clean managed base"))?.to_owned(); + let (root, base) = load_base(worker, &clean_base, offline)?; + if update_target.is_none() && base.snapshot != context.snapshot { return Err(Failure::new(ErrorCode::PlanStale, "Base snapshot changed")); } + let mut layers = Vec::new(); + let mut declarations = Vec::new(); + for (ordinal, item) in selection.iter().enumerate() { + let layer = load_layer(worker, &item.commit, offline)?; + if layer.layer.id != item.overlay_id { return Err(Failure::new(ErrorCode::TrustFailed, "Overlay identity mismatch")); } + declarations.push(json!({"overlay_id":layer.layer.id,"manifest":layer.manifest, + "source_commit":layer.layer.commit,"source_lock_sha256":layer.lock_sha256})); + layers.push(super::overlay_build::rebuild(worker, ordinal as u32, &root, &layer, &base.snapshot, offline)?); + } + let tree = compose_tree(worker, &root, &base, &clean_base, &layers)?; + let composed = &tree.plan; + let summary = json!({"selection":selection,"previous":projection["desired"], + "base":context.managed_base,"target":clean_base,"snapshot":base.snapshot, + "package_count":composed.packages.len(),"path_changes":composed.history.iter().map(|e| + json!({"path":e.path,"removed":e.after.is_none(),"added":e.before.is_none()})).collect::>(), + "required_actions":if update_target.is_some() { vec!["org.archipelago.system.overlay-change", "org.archipelago.system.stage-update"] } + else { vec!["org.archipelago.system.overlay-change"] }}); + let overlay_inputs = json!({"version":0,"clean_base":clean_base,"catalog_commit":catalog["catalog_commit"], + // Retain rebuild intention separately from snapshot-specific outputs. + // The previous lock is evidence, not resolution for the next snapshot. + "declarations":declarations, + "layers":layers.iter().map(|a| json!({"id":a.layer.id,"commit":a.layer.commit, + "lock_sha256":a.lock_sha256})).collect::>(), + "finalizer_sha256":storage::hash(include_bytes!("../../adapters/finalize-managed.sh"))}); + tree.finalize(worker)?; + let intent_path = tree.root.join("usr/lib/archipelago/managed-overlays.json"); + storage::atomic(&intent_path, &json!({"version":0,"clean_base":clean_base,"selection":selection, + "inputs":overlay_inputs}))?; + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&intent_path, fs::Permissions::from_mode(0o644)).map_err(storage::io_error)?; + worker.events.checkpoint(system_bus::Phase::Composing, true, "Retaining the checked managed composition")?; + let output = worker.command("/usr/bin/ostree", &["--repo=/sysroot/ostree/repo", "commit", + &format!("--branch=service/overlays/{}", worker.events.id()), + &format!("--tree=dir={}", tree.root.display()), + &format!("--add-metadata-string=archipelago.snapshot={}", base.snapshot), + &format!("--add-metadata-string=archipelago.base={clean_base}")], Duration::from_secs(600), true)?; + let target = output.trim(); + if !system_bus::checksum(target) { return Err(failure("Invalid managed composition commit")); } + worker.events.effect("overlay_commit", json!(target))?; + let mut inputs = super::packages::prepare_reapply(worker, target, &state)?; + inputs["overlay"] = overlay_inputs; + if let Some(target) = update_target { inputs["upstream_target"] = json!(target); } + let (after, _) = super::packages::current(worker)?; + if after != context { return Err(Failure::new(ErrorCode::PlanStale, "Host context changed during planning")); } + let plan = super::plans::Plan { version:1, owner_uid:uid, + created_at_usec:super::journal::now().map_err(|_| failure("Clock unavailable"))?, + target:target.into(), context, intent:super::plans::Intent::Overlays { selection }, + inputs, summary:summary.clone() }; + let plans = Path::new("/var/lib/archipelago/service/plans"); + storage::directory(plans)?; + worker.events.checkpoint(system_bus::Phase::Planning, false, "Persisting immutable overlay plan")?; + let id = plan.save(plans)?; + Ok(json!({"outcome":"planned","changed":false,"plan_id":id,"plan":summary})) +} + +#[derive(serde::Deserialize)] +#[serde(deny_unknown_fields)] +struct CatalogIndex { version: u32, overlays: Vec } + +pub(crate) fn catalog() -> Result { + let value: serde_json::Value = storage::json(Path::new(CATALOG))?; + let context: super::plans::Context = serde_json::from_value(value["context"].clone()).map_err(|_| failure("Invalid overlay catalog context"))?; + let observed = super::observation::observe().map_err(|_| Failure::new(ErrorCode::Unavailable, "Host observation unavailable"))?; + let binding = crate::updates::binding().map_err(|_| Failure::new(ErrorCode::NoTrack, "Configured trust unavailable"))?; + if observed.booted.as_ref().map(|d| d.deployment_id.as_str()) != Some(context.booted.as_str()) || + observed.pending.as_ref().map(|d| d.deployment_id.as_str()) != context.pending.as_deref() || + storage::hash(&serde_json::to_vec(&binding).map_err(|_| failure("Invalid trust binding"))?) != context.trust || + value["policy"] != super::packages::feature_policy()? { + return Err(Failure::new(ErrorCode::PlanStale, "Refresh overlays for the changed host context")); + } + Ok(value) +} + +pub(crate) fn refresh_catalog(worker: &Worker, offline: bool, force: bool) -> Result { + let _lock = crate::updates::lock().map_err(|_| Failure::new(ErrorCode::Busy, "Sysroot unavailable or provisioning incomplete"))?; + let (context, state) = super::packages::current(worker)?; + let context_id = super::packages::context_id(&context)?; + let now = super::journal::now().map_err(|_| failure("Clock unavailable"))?; + if let Ok(cached) = catalog() { + let age = now.saturating_sub(cached["revision"].as_u64().unwrap_or(0)); + if cached["context_id"] == context_id { + if offline || (!force && age < 60_000_000) { + return Ok(json!({"outcome":"catalog-ready","changed":false,"context_id":context_id,"revision":cached["revision"]})); + } + if force && age < 5_000_000 { return Err(Failure::new(ErrorCode::Busy, "Overlay refresh rate limit")); } + } + } + if offline { return Err(Failure::new(ErrorCode::Unavailable, "No verified overlay catalog for this offline host context")); } + worker.events.checkpoint(system_bus::Phase::Metadata, true, "Refreshing the signed managed overlay catalog")?; + let (commit, raw) = crate::updates::managed::layer_catalog(worker)?; + let catalog: CatalogIndex = serde_json::from_value(raw).map_err(|_| failure("Invalid signed overlay catalog index"))?; + if catalog.version != 0 || catalog.overlays.len() > 256 { return Err(failure("Unsupported or oversized overlay catalog")); } + let mut names = std::collections::BTreeSet::new(); + let mut descriptors = Vec::new(); + for item in catalog.overlays { + if item.overlay_id.is_empty() || !names.insert(item.overlay_id.clone()) || !system_bus::checksum(&item.commit) { + return Err(failure("Invalid or duplicate catalog identity")); + } + let artifact = load_layer(worker, &item.commit, false)?; + if artifact.layer.id != item.overlay_id || artifact.layer.header.kind != archipelago_contracts::LayerKind::Overlay { + return Err(Failure::new(ErrorCode::TrustFailed, "Catalog identity disagrees with verified layer manifest")); + } + descriptors.push(json!({"overlay_id":item.overlay_id,"commit":item.commit,"manifest":artifact.manifest, + "snapshot_id":artifact.layer.header.snapshot_id,"architecture":artifact.layer.header.architecture, + "compatible_snapshot":artifact.layer.header.snapshot_id == context.snapshot,"lock_sha256":artifact.lock_sha256})); + } + let projection = project_state(worker, &state, &context)?; + let (after, _) = super::packages::current(worker)?; + if after != context { return Err(Failure::new(ErrorCode::PlanStale, "Host context changed during catalog refresh")); } + let value = json!({"version":0,"catalog_commit":commit,"context":context,"context_id":context_id, + "revision":now,"policy":super::packages::feature_policy()?,"overlays":descriptors,"state":projection}); + worker.events.checkpoint(system_bus::Phase::Metadata, false, "Publishing verified overlay catalog")?; + storage::atomic(Path::new(CATALOG), &value)?; + Ok(json!({"outcome":"catalog-ready","changed":false,"context_id":context_id,"revision":now})) +} + +fn project_state(worker: &Worker, state: &serde_json::Value, context: &super::plans::Context) -> Result { + let mut projection = json!({"booted":null,"pending":null,"desired":null,"snapshot_id":context.snapshot, + "context_id":super::packages::context_id(context)?}); + for deployment in state["deployments"].as_array().ok_or_else(|| failure("Missing deployment list"))? { + if deployment["stateroot"] != "archipelago" { continue; } + let role = if deployment["booted"] == true { "booted" } + else if deployment["pending"] == true || deployment["staged"] == true { "pending" } else { continue; }; + let checksum = deployment["checksum"].as_str().filter(|s| system_bus::checksum(s)).ok_or_else(|| failure("Invalid deployment checksum"))?; + let directory = worker.command("/usr/bin/ostree", &["--repo=/sysroot/ostree/repo", "ls", checksum, + "/usr/lib/archipelago"], Duration::from_secs(60), true)?; + let intent = if directory.lines().any(|s| s.ends_with("/managed-overlays.json")) { + let raw = worker.command("/usr/bin/ostree", &["--repo=/sysroot/ostree/repo", "cat", checksum, + "/usr/lib/archipelago/managed-overlays.json"], Duration::from_secs(60), true)?; + let value: serde_json::Value = serde_json::from_str(&raw).map_err(|_| failure("Invalid retained overlay intent"))?; + if value["version"].as_u64() != Some(0) || !value["selection"].is_array() { return Err(failure("Unsupported retained overlay intent")); } + value + } else if directory.lines().any(|s| s.ends_with("/overlays")) { + return Err(Failure::new(ErrorCode::Unsupported, "Legacy test-marker overlay requires migration before typed overlay management")); + } else { json!({"version":0,"selection":[],"clean_base":context.managed_base}) }; + projection[role] = intent; + } + projection["desired"] = if projection["pending"].is_null() { projection["booted"].clone() } else { projection["pending"].clone() }; + Ok(projection) +} + +fn failure(message: impl Into) -> Failure { Failure::new(ErrorCode::ExecutionFailed, message) } + +pub(crate) struct ComposedTree { + pub root: PathBuf, + pub database: PathBuf, + pub plan: compose::Plan, +} + +impl ComposedTree { + /// Install the generated local DB only in the private tree, run the shared + /// finalizer without networking, then rebuild records for generated outputs. + /// Nothing here changes a boot entry or the live package database. + pub(crate) fn finalize(&self, worker: &Worker) -> Result<()> { + let work = self.root.parent().ok_or_else(|| failure("Missing composition workspace"))?; + let local = self.root.join("usr/lib/archipelago/package-db/local"); + let old = work.join("base-local-db"); + if old.symlink_metadata().is_ok() { return Err(failure("Composition finalization already attempted")); } + if !fs::symlink_metadata(&local).map_err(storage::io_error)?.is_dir() { + return Err(failure("Base local package database is not a directory")); + } + worker.events.checkpoint(system_bus::Phase::Finalizing, true, "Validating packages and finalizing the managed composition offline")?; + fs::rename(&local, &old).map_err(storage::io_error)?; + fs::rename(self.database.join("local"), &local).map_err(storage::io_error)?; + let etc = self.root.join("etc"); + if etc.symlink_metadata().is_ok() { return Err(failure("Unexpected staging /etc before finalization")); } + fs::rename(self.root.join("usr/etc"), &etc).map_err(storage::io_error)?; + let finalizer = work.join("finalize-managed.sh"); + fs::write(&finalizer, include_bytes!("../../adapters/finalize-managed.sh")).map_err(storage::io_error)?; + let script = "exec 2>&1; pacman -Dk; /bin/bash -euo pipefail /run/finalize-managed.sh; pacman -Q > /usr/lib/archipelago/packages.txt"; + let output = worker.command("/usr/bin/systemd-nspawn", &["--settings=no", "--register=no", + "--private-network", "--resolv-conf=off", &format!("--directory={}",self.root.display()), + &format!("--bind-ro={}:/run/finalize-managed.sh",finalizer.display()), + "/bin/bash", "-euo", "pipefail", "-c", script], Duration::from_secs(1800), true)?; + fs::rename(&etc, self.root.join("usr/etc")).map_err(storage::io_error)?; + if output.lines().any(|line| { + let line = line.to_ascii_lowercase(); + line.contains("error:") || (line.contains("warning:") && (line.contains("failed") || line.contains("failure"))) + }) { return Err(failure("Required managed finalization reported an error")); } + let final_db = work.join("final-database"); + let mut final_request: serde_json::Value = storage::json(&work.join("database.json"))?; + final_request["finalizer_sha256"] = json!(storage::hash(include_bytes!("../../adapters/finalize-managed.sh"))); + storage::atomic(&work.join("final-database-request.json"), &final_request)?; + worker.command("/usr/bin/python3", &["-I", "-B", + work.join("package_db.py").to_str().ok_or_else(|| failure("Invalid database adapter path"))?, + self.root.to_str().ok_or_else(|| failure("Invalid composed path"))?, + final_db.to_str().ok_or_else(|| failure("Invalid final database path"))?, + work.join("final-database-request.json").to_str().ok_or_else(|| failure("Invalid database request path"))?], + Duration::from_secs(600), true)?; + fs::rename(&local, work.join("pre-finalization-local-db")).map_err(storage::io_error)?; + fs::rename(final_db.join("local"), &local).map_err(storage::io_error)?; + let evidence = self.root.join("usr/lib/archipelago/package-transformations"); + if evidence.symlink_metadata().is_ok() { return Err(failure("Reserved transformation namespace already present")); } + fs::rename(&final_db, &evidence).map_err(storage::io_error)?; + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&evidence, fs::Permissions::from_mode(0o755)).map_err(storage::io_error)?; + storage::atomic(&work.join("finalization.json"), &json!({"version":0, + "adapter_sha256":storage::hash(include_bytes!("../../adapters/finalize-managed.sh")), + "package_count":self.plan.packages.len(),"path_count":self.plan.index.len()}))?; + worker.events.effect("overlay_finalized", json!(true))?; + Ok(()) + } +} + +/// Prepare private filesystem and ALPM outputs. This does not commit or stage a +/// deployment. The caller still must validate/finalize and reapply extensions. +pub(crate) fn compose_tree(worker: &Worker, base_root: &Path, base: &archipelago_composer::base::Base, + image: &str, layers: &[Artifact]) -> Result { + if !system_bus::operation_id(worker.events.id()) { return Err(failure("Invalid composition operation")); } + let parent = Path::new("/var/lib/archipelago/service/overlay-work"); + storage::directory(parent)?; + let work = parent.join(worker.events.id()); + storage::directory(&work)?; + worker.events.effect("overlay_workspace", json!(worker.events.id()))?; + let plan = compose::plan_with_base(base, base_root, image, layers).map_err(|m| Failure::new(ErrorCode::Conflict, m))?; + let request = plan.database_request_with_base(base, layers).map_err(|m| Failure::new(ErrorCode::Conflict, m))?; + let root = work.join("composed"); + let database = work.join("database"); + for (name, contents) in [("materialize.py", archipelago_composer::MATERIALIZER), + ("artifact.py", artifact::CHECKER), ("package_db.py", archipelago_composer::PACKAGE_DB)] { + fs::write(work.join(name), contents).map_err(storage::io_error)?; + } + storage::atomic(&work.join("executor.json"), &plan.executor)?; + storage::atomic(&work.join("database.json"), &request)?; + worker.events.checkpoint(system_bus::Phase::Composing, true, "Composing checked managed layers in a private tree")?; + let text = |path: &Path| path.to_str().map(str::to_owned).ok_or_else(|| failure("Invalid composition path")); + worker.command("/usr/bin/python3", &["-I", "-B", &text(&work.join("materialize.py"))?, + &text(base_root)?, &text(&root)?, &text(&work.join("executor.json"))?], Duration::from_secs(1800), true)?; + worker.command("/usr/bin/python3", &["-I", "-B", &text(&work.join("package_db.py"))?, + &text(&root)?, &text(&database)?, &text(&work.join("database.json"))?], Duration::from_secs(600), true)?; + worker.events.effect("overlay_composition", json!({"layers":layers.iter().map(|a| + json!({"id":a.layer.id,"commit":a.layer.commit,"lock":a.lock_sha256})).collect::>(), + "executor_sha256":storage::hash(plan.executor.to_string().as_bytes())}))?; + Ok(ComposedTree { root, database, plan }) +} + +pub(crate) fn load_base(worker: &Worker, commit: &str, offline: bool) -> Result<(PathBuf, archipelago_composer::base::Base)> { + if !system_bus::checksum(commit) || !system_bus::operation_id(worker.events.id()) { + return Err(Failure::new(ErrorCode::InvalidArgument, "Invalid base/workspace identity")); + } + let parent = Path::new("/var/lib/archipelago/service/overlay-work"); + storage::directory(parent)?; + let work = parent.join(worker.events.id()); + storage::directory(&work)?; + worker.events.effect("overlay_workspace", json!(worker.events.id()))?; + let root = work.join("base-image"); + let managed = crate::updates::managed::checkout_layer; + managed(worker, commit, &root, offline)?; + crate::updates::managed::retain_clean_base(worker, commit)?; + let core_commit = crate::updates::managed::base_layer_commit(worker, commit, false)?; + let core = work.join("base-core"); + managed(worker, &core_commit, &core, offline)?; + let purpose = match fs::symlink_metadata(root.join("usr/lib/archipelago/purpose")) { + Ok(_) => Some(crate::updates::managed::base_layer_commit(worker, commit, true)?), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => None, + Err(e) => return Err(storage::io_error(e)), + }; + let purpose_root = work.join("base-purpose"); + if let Some(commit) = &purpose { managed(worker, commit, &purpose_root, offline)?; } + for (name, contents) in [("base.py", archipelago_composer::base::SCANNER), + ("artifact.py", artifact::CHECKER), ("materialize.py", archipelago_composer::MATERIALIZER)] { + fs::write(work.join(name), contents).map_err(storage::io_error)?; + } + let script = work.join("base.py"); + let text = |p: &Path| p.to_str().map(str::to_owned).ok_or_else(|| failure("Invalid base path")); + let output_path = work.join("base-index.json"); + let mut args = vec!["-I".into(), "-B".into(), text(&script)?, "--output".into(), + text(&output_path)?, text(&root)?, text(&core)?]; + if purpose.is_some() { args.push(text(&purpose_root)?); } + worker.command("/usr/bin/python3", &args.iter().map(String::as_str).collect::>(), + Duration::from_secs(1800), true)?; + // Full Desktop indexes can exceed the worker's bounded diagnostic output. + // Read protected evidence directly instead of transporting it through logs. + let checked = serde_json::from_reader(fs::File::open(&output_path).map_err(storage::io_error)?) + .map_err(|_| failure("Invalid base scanner output"))?; + let base = archipelago_composer::base::read_checked(&root, checked).map_err(failure)?; + worker.events.effect("overlay_base", json!({"image":commit,"core":core_commit,"purpose":purpose, + "snapshot":base.snapshot}))?; + Ok((root, base)) +} + +pub(crate) fn load_layer(worker: &Worker, commit: &str, offline: bool) -> Result { + if !system_bus::checksum(commit) || !system_bus::operation_id(worker.events.id()) { + return Err(Failure::new(ErrorCode::InvalidArgument, "Invalid layer/workspace identity")); + } + let parent = Path::new("/var/lib/archipelago/service/overlay-work"); + storage::directory(parent)?; + let work = parent.join(worker.events.id()); + storage::directory(&work)?; + worker.events.effect("overlay_workspace", json!(worker.events.id()))?; + let checkout = work.join(commit); + crate::updates::managed::checkout_layer(worker, commit, &checkout, offline)?; + let checker = work.join("artifact.py"); + fs::write(&checker, artifact::CHECKER).map_err(storage::io_error)?; + fs::write(work.join("materialize.py"), archipelago_composer::MATERIALIZER).map_err(storage::io_error)?; + let output = worker.command("/usr/bin/python3", &["-I", "-B", + checker.to_str().ok_or_else(|| Failure::new(ErrorCode::ExecutionFailed, "Invalid checker path"))?, + checkout.to_str().ok_or_else(|| Failure::new(ErrorCode::ExecutionFailed, "Invalid checkout path"))?], + Duration::from_secs(600), true)?; + let checked = serde_json::from_str(&output).map_err(|_| Failure::new(ErrorCode::ExecutionFailed, "Invalid artifact checker output"))?; + let result = artifact::read_checked(&checkout, commit, checked) + .map_err(|message| Failure::new(ErrorCode::Conflict, message))?; + worker.events.effect(&format!("layer_{commit}"), json!({"commit":commit,"layer":result.layer.id, + "lock_sha256":result.lock_sha256,"snapshot":result.layer.header.snapshot_id}))?; + Ok(result) +} diff --git a/src/service/packages.rs b/src/service/packages.rs index f728311..a87aa1a 100644 --- a/src/service/packages.rs +++ b/src/service/packages.rs @@ -418,7 +418,7 @@ pub fn execute_change(worker: &Worker, plan: &Plan, download_only: bool, offline pub(crate) fn execute_locked(worker: &Worker, plan: &Plan, download_only: bool, offline: bool) -> Result { let (context, initial) = current(worker)?; plan.check_context(&context)?; - if !matches!(plan.intent, Intent::Change { .. } | Intent::Restore { .. } | Intent::Update) { + if !matches!(plan.intent, Intent::Change { .. } | Intent::Restore { .. } | Intent::Update | Intent::Overlays { .. }) { return Err(Failure::new(ErrorCode::InvalidArgument, "Expected an extension plan")); } let canonical = serde_json::to_value(plan).map_err(|_| failure("Invalid plan"))?; @@ -471,6 +471,7 @@ pub(crate) fn execute_locked(worker: &Worker, plan: &Plan, download_only: bool, fs::write(sandbox.path.join("dkms-policy.tsv"),include_bytes!("../../adapters/dkms-policy.tsv")).map_err(storage::io_error)?; fs::write(sandbox.path.join("dkms-finalize.sh"),include_bytes!("../../adapters/dkms-finalize.sh")).map_err(storage::io_error)?; fs::write(sandbox.path.join("finalize.sh"),include_bytes!("../../adapters/extensions.sh")).map_err(storage::io_error)?; + fs::write(sandbox.path.join("finalize-managed.sh"),include_bytes!("../../adapters/finalize-managed.sh")).map_err(storage::io_error)?; worker.command("/bin/bash", &["-euo","pipefail",sandbox.path.join("finalize.sh").to_str().ok_or_else(|| failure("Invalid workspace"))?, sandbox.path.to_str().ok_or_else(|| failure("Invalid workspace"))?,"1"],Duration::from_secs(1800),true)?; let sources: serde_json::Map = requests.iter().map(|r| (r["name"].as_str().unwrap_or("").into(), diff --git a/src/service/plans.rs b/src/service/plans.rs index 9b3ddf0..9ea9e1f 100644 --- a/src/service/plans.rs +++ b/src/service/plans.rs @@ -104,6 +104,9 @@ impl Plan { Intent::Restore { .. } => vec![Action::ExtensionRestore], Intent::Overlays { .. } => vec![Action::OverlayChange], }; + if matches!(self.intent, Intent::Overlays { .. }) && self.inputs.get("upstream_target").is_some() { + actions.push(if download { Action::Download } else { Action::StageUpdate }); + } let changes = match &self.intent { Intent::Change { requests } => requests.as_slice(), Intent::Restore { changes, .. } => changes.as_slice(), diff --git a/src/service/wire.rs b/src/service/wire.rs index cd235f1..786c17e 100644 --- a/src/service/wire.rs +++ b/src/service/wire.rs @@ -48,7 +48,7 @@ fn variant(key: &str, value: &Value) -> Result { Value::Number(n) => n.as_u64().map(OwnedValue::from) .ok_or_else(|| BusError::ExecutionFailed("Invalid unsigned result value".into())), Value::Object(_) => Ok(dictionary(map(value)?)), - Value::Array(items) if matches!(key, "warnings" | "required_actions") || items.iter().any(Value::is_string) => { + Value::Array(items) if matches!(key, "warnings" | "required_actions" | "requires" | "conflicts" | "before" | "after" | "core" | "purpose" | "inputs" | "outputs") || items.iter().any(Value::is_string) => { let values = items.iter().map(|v| v.as_str().map(str::to_string) .ok_or_else(|| BusError::ExecutionFailed("Invalid string array".into()))).collect::, _>>()?; Ok(strings(values)) diff --git a/src/updates/managed.rs b/src/updates/managed.rs index ea47a6d..33a135f 100644 --- a/src/updates/managed.rs +++ b/src/updates/managed.rs @@ -44,6 +44,76 @@ fn configure(worker: &Worker, binding: &Value) -> Result<()> { Ok(()) } +/// Internal catalog consumer: caller holds the shared sysroot writer lock and +/// supplies a commit selected from the configured catalog, never a client URL. +pub(crate) fn checkout_layer(worker: &Worker, commit: &str, destination: &Path, offline: bool) -> Result<()> { + if !digest(commit) || !destination.is_absolute() || destination.symlink_metadata().is_ok() { + return Err(fail("Invalid or already occupied layer checkout")); + } + let binding = binding().map_err(|_| Failure::new(ErrorCode::NoTrack, "Configured layer trust unavailable"))?; + worker.events.checkpoint(Phase::Metadata, true, "Verifying the selected layer against configured trust")?; + configure(worker, &binding)?; + if !offline { repo(worker, &["pull", "--depth=0", REMOTE, commit], true, false)?; } + // Reverify cached commits too: presence in a local repository is not proof + // that the current configured key authorized this layer. + let verification = repo(worker, &["show", &format!("--gpg-verify-remote={REMOTE}"), commit], false, true)?; + if !verification.contains("Good signature from") { + return Err(Failure::new(ErrorCode::TrustFailed, "Layer lacks a verified signature from the configured remote")); + } + worker.command("/usr/bin/ostree", &[&format!("--repo={STATE}/repo"), "checkout", "--force-copy", commit, + destination.to_str().ok_or_else(|| fail("Invalid layer checkout path"))?], Duration::from_secs(600), true)?; + Ok(()) +} + +/// Resolve a catalog ref from the administrator's configured profile. The +pub(crate) fn base_layer_commit(worker: &Worker, image: &str, purpose: bool) -> Result { + if !digest(image) { return Err(fail("Invalid base image identity")); } + // Called only after checkout_layer has verified the image's signature. + let key = if purpose { "archipelago.layer-purpose" } else { "archipelago.layer-core" }; + let raw = repo(worker, &["show", &format!("--print-metadata-key={key}"), image], false, true)?; + let commit = raw.trim().trim_matches('\''); + if !digest(commit) { return Err(fail("Missing or invalid authenticated base layer reference")); } + Ok(commit.into()) +} + +/// Retain the authenticated clean image behind a local composition. Its identity +/// is needed for future update comparison and recomposition, even after GC. +pub(crate) fn retain_clean_base(worker: &Worker, image: &str) -> Result<()> { + if !digest(image) { return Err(fail("Invalid clean base identity")); } + let verification = repo(worker, &["show", &format!("--gpg-verify-remote={REMOTE}"), image], false, true)?; + if !verification.contains("Good signature from") { + return Err(Failure::new(ErrorCode::TrustFailed, "Clean base signature unavailable")); + } + worker.events.effect("retained_clean_base", json!(image))?; + worker.command("/usr/bin/ostree", &["--repo=/sysroot/ostree/repo", "pull-local", + &format!("{STATE}/repo"), image], Duration::from_secs(600), true)?; + cmd(worker, &["--repo=/sysroot/ostree/repo", "refs", "--force", + &format!("--create=service/bases/{image}"), image], false, true)?; + Ok(()) +} + +/// Resolve a catalog ref from the administrator's configured profile. The +/// service never accepts catalog URLs, keys or ref names from an RPC caller. +pub(crate) fn layer_catalog(worker: &Worker) -> Result<(String, Value)> { + let binding = binding().map_err(|_| Failure::new(ErrorCode::NoTrack, "Configured layer catalog unavailable"))?; + let reference = binding["profile"]["overlay_catalog_ref"].as_str() + .ok_or_else(|| Failure::new(ErrorCode::NoTrack, "Update profile has no managed overlay catalog ref"))?; + if reference.is_empty() || reference.len() > 1024 || + reference.split('/').any(|part| part.is_empty() || part == "." || part == "..") || + !reference.bytes().all(|b| b.is_ascii_alphanumeric() || b"/_.-".contains(&b)) { + return Err(Failure::new(ErrorCode::TrustFailed, "Invalid configured overlay catalog ref")); + } + configure(worker, &binding)?; + let summary = repo(worker, &["remote", "summary", REMOTE], true, false)?; + let commit = summary_commit(&summary, reference).map_err(|_| Failure::new(ErrorCode::NoTrack, "Signed overlay catalog ref is absent"))?; + repo(worker, &["pull", "--depth=0", REMOTE, &commit], true, false)?; + let verification = repo(worker, &["show", &format!("--gpg-verify-remote={REMOTE}"), &commit], false, true)?; + if !verification.contains("Good signature from") { return Err(Failure::new(ErrorCode::TrustFailed, "Overlay catalog signature unavailable")); } + let raw = repo(worker, &["cat", &commit, "/catalog.json"], false, true)?; + let catalog = serde_json::from_str(&raw).map_err(|_| fail("Malformed signed overlay catalog"))?; + Ok((commit, catalog)) +} + pub(crate) fn context(worker: &Worker, binding: &Value, state: &Value) -> Result { let entries = state["deployments"].as_array().ok_or_else(|| fail("Missing deployment records"))?; let boot = entries.iter().find(|d| d["booted"] == true && d["stateroot"] == "archipelago").ok_or_else(|| fail("Missing booted deployment"))?; @@ -78,6 +148,30 @@ fn verified_path(context: &Context, target: &str) -> std::path::PathBuf { Path::new(SERVICE).join("verified-targets").join(format!("{}.json", storage::hash(format!("{}:{target}", context.trust).as_bytes()))) } +fn clean_base_from_intent(managed: &str, intent: Option<&Value>) -> Result { + if !digest(managed) { return Err(fail("Invalid managed base identity")); } + let Some(intent) = intent else { return Ok(managed.into()); }; + if intent["version"].as_u64() != Some(0) || !intent["selection"].is_array() { + return Err(fail("Unsupported retained overlay intent")); + } + intent["clean_base"].as_str().filter(|value| digest(value)).map(str::to_owned) + .ok_or_else(|| fail("Invalid retained clean base identity")) +} + +/// Old deployments have no overlay metadata and retain their existing updater +/// path. A locally rebuilt commit's timestamp must not supersede the upstream +/// image timestamp when deciding whether a distribution update is newer. +fn upstream_base(worker: &Worker, managed: &str) -> Result { + let listing = cmd(worker, &["--repo=/sysroot/ostree/repo", "ls", managed, "/usr/lib/archipelago"], false, true)?; + if !listing.lines().any(|line| line.ends_with("/managed-overlays.json")) { + return clean_base_from_intent(managed, None); + } + let raw = cmd(worker, &["--repo=/sysroot/ostree/repo", "cat", managed, + "/usr/lib/archipelago/managed-overlays.json"], false, true)?; + let intent = serde_json::from_str(&raw).map_err(|_| fail("Malformed retained overlay intent"))?; + clean_base_from_intent(managed, Some(&intent)) +} + fn refresh_locked(worker: &Worker, binding: &Value, context: &Context, offline: bool, force: bool) -> Result { worker.events.checkpoint(Phase::Metadata, true, "Checking the signed image track")?; let cache = Path::new(SERVICE).join("refresh.json"); @@ -114,7 +208,7 @@ pub(crate) fn refresh(worker: &Worker, offline: bool, force: bool) -> Result Result { text.lines().find_map(|line| line.strip_prefix("Date:")).map(|s| s.trim().to_owned()) .filter(|date| date.len() == 25 && date.ends_with(" +0000")) .ok_or_else(|| fail("Missing canonical commit date")) }; - if target != context.managed_base && date(&show)? <= date(&old)? { + if target != upstream && date(&show)? <= date(&old)? { return Err(Failure::new(ErrorCode::PlanStale, "Target is not newer than the selected managed base")); } if details { @@ -155,6 +263,9 @@ pub(crate) fn prepare(worker: &Worker, target: &str, offline: bool, details: boo return Ok(json!({"outcome":"details-ready","changed":false,"target":target, "booted":context.booted,"pending":context.pending.as_deref().unwrap_or(""),"package_changes":changes})); } + if let Some(intent) = overlay_intent { + return crate::service::overlays::prepare_update(worker, target, &context, &intent, owner_uid, offline); + } // Keep the complete selected generation; never silently replace it with the // booted requests when another client has already prepared a pending change. let selected = initial["deployments"].as_array().ok_or_else(|| fail("Missing deployments"))?.iter() @@ -245,3 +356,34 @@ pub(crate) fn staged(state: &Value, target: &str) -> Result { let serial = matches[0]["serial"].as_u64().ok_or_else(|| fail("Missing deployment serial"))?; Ok(json!({"deployment_id":format!("archipelago/{target}.{serial}"),"checksum":target,"reboot_required":true})) } + +#[cfg(test)] +mod compatibility_tests { + use super::*; + + #[test] + fn published_hosts_without_overlay_metadata_keep_the_existing_base() { + let published = "a".repeat(64); + assert_eq!(clean_base_from_intent(&published, None).unwrap(), published); + } + + #[test] + fn local_overlay_results_compare_against_the_upstream_base() { + let upstream = "a".repeat(64); + let local = "b".repeat(64); + let intent = json!({"version":0,"clean_base":upstream,"selection":[ + {"overlay_id":"hardware/example","commit":"c".repeat(64)}]}); + assert_eq!(clean_base_from_intent(&local, Some(&intent)).unwrap(), upstream); + let empty = json!({"version":0,"clean_base":upstream,"selection":[]}); + assert_eq!(clean_base_from_intent(&local, Some(&empty)).unwrap(), upstream); + } + + #[test] + fn malformed_metadata_does_not_fall_back_to_a_clean_host() { + for intent in [json!({"version":1,"clean_base":"a".repeat(64),"selection":[]}), + json!({"version":0,"clean_base":"stable/core","selection":[]}), + json!({"version":0,"clean_base":"a".repeat(64)})] { + assert!(clean_base_from_intent(&"b".repeat(64), Some(&intent)).is_err()); + } + } +}