diff --git a/README.md b/README.md index afa829b..32ee314 100644 --- a/README.md +++ b/README.md @@ -278,3 +278,10 @@ monitoring still need successful end-to-end runs before production use. ## License [MIT](LICENSE) + +## Nizho development integration + +The immutable Nizho adapter and service-backed Flatpak workflow are described in +[the Nizho integration notes](docs/NIZHO.md). System image-package deployment and +production VM acceptance remain incomplete. These development changes must not +be presented as a validated release. diff --git a/crates/archon-distro/src/flatpak.rs b/crates/archon-distro/src/flatpak.rs new file mode 100644 index 0000000..6a939e7 --- /dev/null +++ b/crates/archon-distro/src/flatpak.rs @@ -0,0 +1,68 @@ +//! Native libflatpak bridge. Flatpak owns repository and dependency state. +//! Hosts must broker authorization before invoking the commit protocol. +pub const BRIDGE: &str = include_str!("flatpak_bridge.py"); + +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Request { + pub action: String, + pub package: String, + pub repository: String, +} +impl Request { + pub fn validate(&self) -> Result<(), &'static str> { + if !matches!(self.action.as_str(), "install" | "remove" | "update") { + return Err("unsupported action"); + } + let parts: Vec<_> = self.package.split('/').collect(); + if parts.len() != 4 || parts[0] != "app" || !parts[1..].iter().all(|s| identifier(s)) { + return Err("invalid full application reference"); + } + if !identifier(&self.repository) { + return Err("invalid repository identifier"); + } + Ok(()) + } +} +fn identifier(s: &str) -> bool { + !s.is_empty() + && s.len() <= 255 + && s.as_bytes()[0].is_ascii_alphanumeric() + && s.bytes() + .all(|c| c.is_ascii_alphanumeric() || b"._-".contains(&c)) +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn rejects_injection_and_unsafe_scopes() { + for package in [ + "../etc/passwd", + "app/--help/x86_64/stable", + "runtime/a/x86_64/1", + "app/a/x86_64/$(id)", + ] { + assert!( + Request { + action: "install".into(), + package: package.into(), + repository: "flathub".into() + } + .validate() + .is_err() + ); + } + } + #[test] + fn accepts_full_flatpak_identity() { + assert!( + Request { + action: "install".into(), + package: "app/org.gnome.Calculator/x86_64/stable".into(), + repository: "flathub".into() + } + .validate() + .is_ok() + ); + } +} diff --git a/crates/archon-distro/src/flatpak_bridge.py b/crates/archon-distro/src/flatpak_bridge.py new file mode 100644 index 0000000..89a49db --- /dev/null +++ b/crates/archon-distro/src/flatpak_bridge.py @@ -0,0 +1,293 @@ +#!/usr/bin/python3 +"""Archon libflatpak protocol v1. Fixed operations, no shell, native database. + +Production always opens the system installation. --test-installation opens an +explicit disposable user installation, for real signed-repository tests only. +Each request is a single bounded JSON document; stdout contains JSON events. +""" +import hashlib +import json +import re +import sys +import gi + +gi.require_version("Flatpak", "1.0") +from gi.repository import Flatpak, Gio, GLib + + +def emit(event, **fields): + print(json.dumps({"event": event, **fields}, sort_keys=True), flush=True) + + +def identifier(value): + if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,254}", value): + raise ValueError("invalid identifier") + return value + + +def ref_string(value): + if not isinstance(value, str) or len(value) > 512: + raise ValueError("invalid Flatpak reference") + parts = value.split("/") + if len(parts) != 4 or parts[0] not in ("app", "runtime"): + raise ValueError("expected full app/name/architecture/branch reference") + for item in parts[1:]: + identifier(item) + return value + + +def trusted(installation, name): + identifier(name) + remote = installation.get_remote_by_name(name, None) + if remote.get_disabled() or not remote.get_gpg_verify(): + raise ValueError("repository disabled or signature verification disabled") + return remote + + +def policy(installation): + # Include the full native config and trusted key material, not only the URL. + root = installation.get_path().get_path() + from pathlib import Path + h = hashlib.sha256() + for path in [Path(root) / "repo/config", *sorted((Path(root) / "repo").glob("*.trustedkeys.gpg"))]: + h.update(path.name.encode()) + h.update(path.read_bytes()) + return h.hexdigest() + + +def state(installation): + return sorted([r.format_ref(), r.get_commit(), r.get_origin()] + for r in installation.list_installed_refs(None)) + + +def package(ref, installed, remote=None): + return {"id": ref.format_ref(), "name": (ref.get_appdata_name() or ref.get_name()) if installed and hasattr(ref, "get_appdata_name") else ref.get_name(), "summary": (ref.get_appdata_summary() or "") if installed and hasattr(ref, "get_appdata_summary") else "", + "version": ref.get_commit() or "", "repository": remote or ref.get_origin(), + "backend": "flatpak-system", "installed": installed, + "download_bytes": 0 if installed else ref.get_download_size(), + "installed_bytes": ref.get_installed_size(), "trust": "signature-required"} + + +def read_appstream(path, details_for=None): + """Stream untrusted XML with bounded expansion and bounded retained fields.""" + import gzip + import xml.etree.ElementTree as ET + + class BoundedReader: + def __init__(self, source): + self.source, self.total, self.tail = source, 0, b"" + + def read(self, size=-1): + data = self.source.read(min(size, 65536) if size >= 0 else 65536) + self.total += len(data) + if self.total > 64 * 1048576: + raise ValueError("AppStream metadata exceeds bound") + markup = self.tail + data + if b" 50000: + raise ValueError("AppStream component count exceeds bound") + appid = component.findtext("id", "").removesuffix(".desktop") + if appid and len(appid) <= 255 and (details_for is None or appid == details_for): + info = { + "name": component.findtext("name", appid)[:256], + "summary": component.findtext("summary", "")[:2048], + "categories": [(c.text or "")[:64] for c in component.findall("categories/category")[:64]], + } + if details_for is not None: + description = component.find("description") + info.update({ + "description": "\n".join(description.itertext())[:65536] if description is not None else "", + "license": component.findtext("project_license", "")[:1024], + "homepage": next((u.text or "" for u in component.findall("url") if u.attrib.get("type") == "homepage"), "")[:2048], + }) + result[appid] = info + # Drop completed XML subtrees; searches retain only small summaries. + component.clear() + root.clear() + return result + + +def appstream(installation, remote, details_for=None): + """Read libflatpak's native cache; never create a package database.""" + from pathlib import Path + directory = Path(remote.get_appstream_dir(None).get_path()) + path = directory / "appstream.xml.gz" + if not path.exists(): + installation.update_appstream_sync(remote.get_name(), None, None, None) + return read_appstream(path, details_for) if path.exists() else {} + +def transaction(installation, request, expected=None, expires_at=None, cancellable=None): + action = request["action"] + ref = ref_string(request["package"]) + remote = identifier(request["repository"]) + trusted(installation, remote) + tx = Flatpak.Transaction.new_for_installation(installation, None) + tx.set_no_interaction(True) + tx.connect("add-new-remote", lambda *args: False) + tx.connect("choose-remote-for-ref", lambda tx, for_ref, runtime_ref, remotes: list(remotes).index(remote) if remote in remotes else -1) + if action == "install": + tx.add_install(remote, ref, None) + elif action == "remove": + current = installation.get_installed_ref(Flatpak.Ref.parse(ref).get_kind(), + *ref.split("/")[1:], None) + if current.get_origin() != remote: + raise ValueError("installed origin differs from requested repository") + tx.add_uninstall(ref) + elif action == "update": + tx.add_update(ref, None, None) + else: + raise ValueError("unsupported transaction action") + resolved = None + failures = [] + + def ready(tx): + nonlocal resolved + changes = [] + for op in tx.get_operations(): + origin = op.get_remote() + if origin: + trusted(installation, origin) + changes.append({"action": int(op.get_operation_type()), "package": op.get_ref(), + "repository": origin or "", "commit": op.get_commit() or "", + "download_bytes": op.get_download_size(), "installed_bytes": op.get_installed_size()}) + resolved = {"schema_version": 1, "backend": "flatpak-system", "request": request, + "changes": sorted(changes, key=lambda x: (x["package"], x["action"])), + "installed_state": state(installation), "policy_fingerprint": policy(installation)} + if expected is None: + return False # libflatpak aborts before applying any operation + import time + if expires_at is not None and (not isinstance(expires_at, int) or time.time() >= expires_at): + failures.append("plan expired during native revalidation") + return False + if resolved != expected: + failures.append("stale plan: native resolution or trust policy changed") + return False + return True + + tx.connect("ready", ready) + tx.connect("operation-error", lambda tx, op, error, details: (failures.append(str(error)) or False)) + + def new_operation(tx, op, progress): + progress.connect("changed", lambda p: emit("progress", package=op.get_ref(), + percent=p.get_progress(), detail=p.get_status())) + tx.connect("new-operation", new_operation) + try: + tx.run(cancellable) + except GLib.Error as error: + if failures: + raise ValueError("; ".join(failures)) from error + if expected is not None or resolved is None or not error.matches(Flatpak.error_quark(), Flatpak.Error.ABORTED): + raise + if failures: + raise ValueError("; ".join(failures)) + if resolved is None: + raise ValueError("native engine did not produce a plan") + return resolved + + +def handle(installation, request, cancellable=None): + mode = request["mode"] + if mode == "repositories": + from urllib.parse import urlsplit, urlunsplit + def public_url(remote): + url = urlsplit(remote.get_url()) + return urlunsplit((url.scheme, url.netloc.rsplit("@", 1)[-1], url.path, "", "")) + return [{"id": r.get_name(), "url": public_url(r), "enabled": not r.get_disabled(), + "signature_required": r.get_gpg_verify()} for r in installation.list_remotes(None)] + if mode == "installed": + return [package(r, True) for r in installation.list_installed_refs(None) + if r.get_kind() == Flatpak.RefKind.APP] + if mode == "updates": + result = [] + for ref in installation.list_installed_refs_for_update(None): + if ref.get_kind() != Flatpak.RefKind.APP: continue + origin = ref.get_origin() + trusted(installation, origin) + candidate = installation.fetch_remote_ref_sync(origin, ref.get_kind(), ref.get_name(), ref.get_arch(), ref.get_branch(), None) + item = package(candidate, True, origin) + item["summary"] = "Installed commit: " + ref.get_commit() + result.append(item) + return result + if mode == "search": + query = request.get("query", "").lower() + category = request.get("category", "") + if category: identifier(category) + offset, limit = request.get("offset", 0), request.get("limit", 50) + if not isinstance(query, str) or len(query) > 128 or not 0 <= offset <= 100000 or not 1 <= limit <= 100: + raise ValueError("invalid search bounds") + installed = {r.format_ref() for r in installation.list_installed_refs(None)} + result = [] + for remote in installation.list_remotes(None): + if remote.get_disabled() or not remote.get_gpg_verify(): + continue + metadata = appstream(installation, remote) + for ref in installation.list_remote_refs_sync(remote.get_name(), None): + info = metadata.get(ref.get_name(), {}) + if ref.get_kind() == Flatpak.RefKind.APP and ref.get_arch() == Flatpak.get_default_arch() and query in (ref.get_name() + " " + info.get("name", "") + " " + info.get("summary", "")).lower() and (not category or category in info.get("categories", [])): + item = package(ref, ref.format_ref() in installed, remote.get_name()) + item["name"] = info.get("name", item["name"]) + item["summary"] = info.get("summary", "") + result.append(item) + return sorted(result, key=lambda x: (x["name"], x["repository"], x["id"]))[offset:offset+limit] + if mode == "details": + ref = Flatpak.Ref.parse(ref_string(request["package"])) + remote = identifier(request["repository"]) + trusted(installation, remote) + remote_ref = installation.fetch_remote_ref_sync(remote, ref.get_kind(), ref.get_name(), ref.get_arch(), ref.get_branch(), None) + result = package(remote_ref, any(r.format_ref() == ref.format_ref() for r in installation.list_installed_refs(None)), remote) + metadata = installation.fetch_remote_metadata_sync(remote, remote_ref, None).get_data() + if len(metadata) > 1048576: + raise ValueError("package metadata exceeds bound") + result["metadata"] = metadata.decode("utf-8") + import configparser + parsed = configparser.ConfigParser(interpolation=None, strict=True) + parsed.read_string(result["metadata"]) + result["dependencies"] = parsed.get("Application", "runtime", fallback="Not provided") + result.update(appstream(installation, trusted(installation, remote), ref.get_name()).get(ref.get_name(), {})) + return result + if mode in ("plan", "commit"): + if set(request["request"]) != {"action", "package", "repository"}: + raise ValueError("unexpected transaction fields") + return transaction(installation, request["request"], request.get("expected") if mode == "commit" else None, request.get("expires_at"), cancellable) + raise ValueError("unsupported bridge operation") + + +def main(): + if sys.argv[1:]: + if len(sys.argv) != 3 or sys.argv[1] != "--test-installation": + raise ValueError("invalid arguments") + installation = Flatpak.Installation.new_for_path(Gio.File.new_for_path(sys.argv[2]), True, None) + else: + installation = Flatpak.Installation.new_system(None) + raw = sys.stdin.buffer.readline(1048577) + if len(raw) > 1048576: + raise ValueError("request exceeds bound") + import threading + cancellable = Gio.Cancellable.new() + def controls(): + if sys.stdin.buffer.readline(16).strip() == b"cancel": + cancellable.cancel() + threading.Thread(target=controls, daemon=True).start() + emit("result", value=handle(installation, json.loads(raw), cancellable)) + +if __name__ == "__main__": + try: + main() + except Exception as error: + emit("error", code="backend_failure", detail=str(error)) + sys.exit(1) diff --git a/crates/archon-distro/src/lib.rs b/crates/archon-distro/src/lib.rs index 01b64c1..0118056 100644 --- a/crates/archon-distro/src/lib.rs +++ b/crates/archon-distro/src/lib.rs @@ -6,6 +6,7 @@ //! capability, not a prerequisite for other distributions to gain deep support. mod backend; +pub mod flatpak; pub mod image; pub mod transaction; @@ -42,6 +43,9 @@ impl Distro { let path = std::env::var_os("ARCHON_OS_RELEASE") .map(PathBuf::from) .unwrap_or_else(|| PathBuf::from("/etc/os-release")); + if path == Path::new("/etc/os-release") && Path::new("/usr/lib/nizho-release").exists() { + return Distro::Unknown("Nizho (image backend unavailable)".into()); + } if path == Path::new("/etc/os-release") && Path::new("/usr/lib/arkaos-release").exists() { return Distro::Unknown("ArkaOS (image backend unavailable)".into()); } @@ -66,6 +70,13 @@ impl Distro { /// same way as upstream. fn from_os_release(contents: &str) -> Self { let fields = parse_os_release(contents); + if fields + .get("NAME") + .is_some_and(|name| name == "Nizho" || name == "Nizho OS") + || fields.get("ID").is_some_and(|id| id == "nizho") + { + return Distro::Unknown("Nizho (image backend unavailable)".into()); + } // ArkaOS keeps Fedora's ID for compatibility. Until an image backend // is validated, fail closed instead of exposing live DNF mutations. if fields.get("NAME").is_some_and(|name| name == "ArkaOS") @@ -219,6 +230,22 @@ mod tests { ); } + #[test] + fn nizho_never_selects_live_fedora_backend() { + for release in [ + "ID=nizho\nID_LIKE=fedora\n", + "ID=fedora\nNAME=Nizho\n", + "ID=fedora\nNAME=\"Nizho OS\"\n", + ] { + let distro = Distro::from_os_release(release); + assert_eq!( + distro, + Distro::Unknown("Nizho (image backend unavailable)".into()) + ); + assert!(distro.backend().is_none()); + } + } + #[test] fn detects_fedora_family() { assert_eq!(Distro::from_os_release("ID=fedora\n"), Distro::Fedora); diff --git a/crates/archon/src/commands/mod.rs b/crates/archon/src/commands/mod.rs index 6bc0f10..5920b70 100644 --- a/crates/archon/src/commands/mod.rs +++ b/crates/archon/src/commands/mod.rs @@ -6,3 +6,5 @@ pub mod search; pub mod self_update; pub mod subprocess; pub mod transaction; + +pub mod nizho; diff --git a/crates/archon/src/commands/nizho.rs b/crates/archon/src/commands/nizho.rs new file mode 100644 index 0000000..90cea38 --- /dev/null +++ b/crates/archon/src/commands/nizho.rs @@ -0,0 +1,66 @@ +//! Nizho routes package operations to its authorized system service. +//! Existing native distro command implementations are untouched. +use crate::Command; +use anyhow::{Context, Result, bail}; +use serde_json::{Value, json}; +pub fn dispatch(command: &Command) -> Option> { + if !matches!(archon_distro::Distro::detect(), archon_distro::Distro::Unknown(name) if name.starts_with("Nizho")) + { + return None; + } + let request: Value = match command { + Command::Search { term, all } => json!({"command":"search","query":term,"all":all}), + Command::List { dry_run: false, .. } => json!({"command":"installed"}), + Command::Repos(options) if !options.dry_run => json!({"command":"repositories"}), + Command::History(options) if !options.dry_run => json!({"command":"history"}), + Command::Capabilities => json!({"command":"capabilities"}), + Command::Info { packages, options } if !options.dry_run => { + json!({"command":"info","packages":packages}) + } + Command::Install { + packages, + dry_run, + yes, + refresh: false, + report: false, + } => json!({"command":"install","packages":packages,"dry_run":dry_run,"yes":yes}), + Command::Remove { + packages, + dry_run, + yes, + } => json!({"command":"remove","packages":packages,"dry_run":dry_run,"yes":yes}), + Command::Plan { + packages, + native: false, + .. + } => json!({"command":"install","packages":packages,"dry_run":true,"yes":false}), + Command::Upgrade(options) => { + json!({"command":"update","dry_run":options.dry_run,"yes":options.yes}) + } + // Never fall through to a live native mutation on an immutable host. + _ => { + return Some(Err(anyhow::anyhow!( + "This operation is not supported by Nizho's immutable package backend. Use Capsule for system image status." + ))); + } + }; + Some(run(&request)) +} +fn run(request: &Value) -> Result<()> { + let status = std::process::Command::new("/usr/bin/python3") + .args([ + "-I", + "-c", + include_str!("nizho_client.py"), + &request.to_string(), + ]) + .status() + .context("starting Nizho's unprivileged D-Bus client")?; + if !status.success() { + bail!( + "Nizho package service operation failed (exit {:?})", + status.code() + ); + } + Ok(()) +} diff --git a/crates/archon/src/commands/nizho_client.py b/crates/archon/src/commands/nizho_client.py new file mode 100644 index 0000000..f9b97d3 --- /dev/null +++ b/crates/archon/src/commands/nizho_client.py @@ -0,0 +1,64 @@ +"""Unprivileged Nizho CLI client. No privileged executables, no package engine.""" +import json +import sys +from gi.repository import Gio, GLib + +def safe(value): return ''.join(c for c in str(value) if c.isprintable()) + +BUS='org.nizho.Archon1' +PATH='/org/nizho/Archon1' +IFACE=BUS+'.Manager' + +def main(request): + bus=Gio.bus_get_sync(Gio.BusType.SYSTEM,None) + def call(method, signature=None, args=(), interactive=False): + result=bus.call_sync(BUS,PATH,IFACE,method,GLib.Variant(signature,args) if signature else None,None,Gio.DBusCallFlags.ALLOW_INTERACTIVE_AUTHORIZATION if interactive else Gio.DBusCallFlags.NONE,120000,None) + return result.unpack()[0] if result.n_children() else None + command=request['command'] + if command=='capabilities': + print(json.dumps(call('GetCapabilities'),indent=2));return + if command in ('installed','repositories','history'): + result=call({'installed':'GetInstalledPackages','repositories':'GetRepositories','history':'GetTransactionHistory'}[command], '(uu)' if command=='history' else None,(0,100) if command=='history' else ()) + print(json.dumps(json.loads(result) if isinstance(result,str) else result,indent=2));return + if command=='search': + offset=0 + while True: + rows=call('SearchPackages','(ssuu)',(request['query'],'',offset,100 if request.get('all') else 50)) + for row in rows: print(f'{safe(row[0])} [{safe(row[4])}] {safe(row[2])}'+(' (installed)' if row[6] else '')) + if not request.get('all') or len(rows)<100:return + offset+=100 + packages=request.get('packages',[]) + if command=='update': + candidates=call('GetAvailableUpdates');packages=[row[0] for row in candidates] + for package in packages: + rows=call('GetInstalledPackages') if command in ('remove','update') else call('SearchPackages','(ssuu)',(package.split('/')[1] if '/' in package else package,'',0,100)) + matches=[r for r in rows if r[0]==package or r[0].split('/')[1]==package] + if len(matches)!=1:raise ValueError('Package must identify one exact application reference; use archon search to inspect available references') + row=matches[0] + if command=='info':print(json.dumps(json.loads(call('GetPackageDetails','(ss)',(row[0],row[4]))),indent=2));continue + plan=call('PlanTransaction','(sss)',(command,row[0],row[4])) + print(json.dumps(json.loads(plan[3]),indent=2)) + if request.get('dry_run'): + call('CancelTransaction','(s)',(plan[0],));continue + if not request.get('yes'): + if not sys.stdin.isatty() or input('Authorize and apply this transaction? [y/N] ').strip().lower() not in ('y','yes'): + call('CancelTransaction','(s)',(plan[0],));raise ValueError('Transaction cancelled') + loop=GLib.MainLoop();outcome=[] + def event(connection,sender,path,interface,name,parameters): + args=parameters.unpack() + if args[0]!=plan[0]:return + if name=='TransactionProgress':print(f'{args[1]}% {safe(args[2])}',flush=True) + elif name in ('TransactionCompleted','TransactionFailed'): + outcome.append(None if name=='TransactionCompleted' else args[1]);loop.quit() + subscription=bus.signal_subscribe(BUS,IFACE,None,PATH,None,Gio.DBusSignalFlags.NONE,event) + try: + call('CommitTransaction','(s)',(plan[0],),True) + GLib.timeout_add_seconds(3600,lambda:(loop.quit(),False)[1]);loop.run() + if not outcome:raise ValueError('Timed out waiting for transaction; inspect archon history before retrying') + if outcome[0]:raise ValueError(outcome[0]) + print('Transaction completed') + finally:bus.signal_unsubscribe(subscription) + +try:main(json.loads(sys.argv[1])) +except Exception as error: + print(f'archon: {error}',file=sys.stderr);sys.exit(1) diff --git a/crates/archon/src/main.rs b/crates/archon/src/main.rs index 88168c9..1e09453 100644 --- a/crates/archon/src/main.rs +++ b/crates/archon/src/main.rs @@ -277,6 +277,9 @@ fn main() { } fn run(cli: Cli) -> anyhow::Result<()> { + if let Some(result) = commands::nizho::dispatch(&cli.command) { + return result; + } match cli.command { Command::Transaction { command } => match command { TransactionCommand::Plan { diff --git a/docs/NIZHO.md b/docs/NIZHO.md new file mode 100644 index 0000000..0e748b2 --- /dev/null +++ b/docs/NIZHO.md @@ -0,0 +1,56 @@ +# Nizho integration development + +Nizho is an immutable bootc OS. The Nizho release marker and branded os-release +must never select the live DNF backend. Nizho keeps image deployment, signing, +boot verification and rollback; Archon owns package identities and native backend +logic. Existing distro implementations remain unchanged. + +The development `archon-distro::flatpak` adapter embeds a bounded protocol bridge +to libflatpak via Python GObject. libflatpak owns discovery, repositories, +dependency closure, native state and signature enforcement. The bridge's `ready` +callback exports an abort-before-apply plan. Commit independently resolves and +compares operations, installed state and repository/key fingerprints. It refuses +new remotes, disabled signatures, stale plans and expired commits. Cancellation +uses Gio.Cancellable, not a shell command. + +The bridge itself is not an authorization service. Nizho's root system service +must bind plans to the real D-Bus caller, authorize through polkit, persist state +and prevent replay/conflicts before invoking commit. Debug isolated-installation +arguments are for actual disposable repository tests, not a production bypass. + +On a Nizho system shipping the matching service, normal Archon commands use the +system Flatpak backend through `org.nizho.Archon1.Manager`: + +```sh +archon capabilities +archon search Calculator +archon list --json +archon info app/org.gnome.Calculator/x86_64/stable +archon plan app/org.gnome.Calculator/x86_64/stable +archon install app/org.gnome.Calculator/x86_64/stable +archon remove app/org.gnome.Calculator/x86_64/stable +archon upgrade --dry-run +archon history +``` + +Use actual refs from search; these commands do not assume an application is in a +configured remote. Ambiguous short names are rejected. `--yes` does not bypass +polkit. The CLI is unprivileged and executes no privileged package operation. +`archon update` is the generic self-update alias, but Nizho rejects that operation +for its OS-managed executable. Archon updates with the OS image; application +upgrades use `archon upgrade`. System RPM image operations remain unsupported until Nizho has +a validated build/sign/deployment broker. Do not use live DNF as a fallback. + +Native validation: + +```sh +cargo test --locked --workspace -- --test-threads=2 +python3 scripts/test-flatpak-native.py +``` + +The Python test creates a signed local Flatpak app/runtime repository and a +separate temporary installation. It validates no-install planning, expiry, +cancellation, signed install/update, stale-state rejection, removal and unsigned +artifact/policy rejection. It does not modify the host package installation and +does not certify Nizho VM boot or polkit authentication. Nizho's source/native/UI +suite additionally exercises the actual D-Bus service and GTK widgets. diff --git a/scripts/matrix-scenarios.sh b/scripts/matrix-scenarios.sh index 6ee57ed..7eae849 100755 --- a/scripts/matrix-scenarios.sh +++ b/scripts/matrix-scenarios.sh @@ -74,9 +74,15 @@ PY fi fi printf 'y\n' | archon remove jq --yes - if command -v jq >/dev/null 2>&1; then - echo 'FAIL: jq is still installed after removal'; exit 1 - fi + # Check the native package database, not PATH: an image may retain another + # jq binary or wrapper after the package manager has removed its package. + case "$expected" in + pacman) if pacman -Q jq >/dev/null 2>&1; then echo 'FAIL: jq remains in pacman database'; exit 1; fi ;; + apt) if dpkg-query -W -f='${db:Status-Abbrev}' jq 2>/dev/null | grep -q '^ii'; then echo 'FAIL: jq remains installed in dpkg database'; exit 1; fi ;; + dnf|zypper) if rpm -q jq >/dev/null 2>&1; then echo 'FAIL: jq remains in RPM database'; exit 1; fi ;; + apk) if apk info -e jq >/dev/null 2>&1; then echo 'FAIL: jq remains in apk database'; exit 1; fi ;; + *) echo 'FAIL: no package database check for this distro'; exit 1 ;; + esac echo 'PASS: native jq installation and removal' fi diff --git a/scripts/test-flatpak-metadata.py b/scripts/test-flatpak-metadata.py new file mode 100644 index 0000000..894227c --- /dev/null +++ b/scripts/test-flatpak-metadata.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +"""Untrusted AppStream parser tests; no package database or network operations.""" +import gzip +import importlib.util +from pathlib import Path +import tempfile +import unittest + +source = Path(__file__).resolve().parents[1] / "crates/archon-distro/src/flatpak_bridge.py" +spec = importlib.util.spec_from_file_location("flatpak_bridge", source) +bridge = importlib.util.module_from_spec(spec) +spec.loader.exec_module(bridge) + + +class MetadataTests(unittest.TestCase): + def parse(self, content, details=None): + with tempfile.TemporaryDirectory() as temporary: + path = Path(temporary) / "appstream.xml.gz" + with gzip.open(path, "wb") as stream: + stream.write(content) + return bridge.read_appstream(path, details) + + def test_search_keeps_summaries_and_details_select_one_component(self): + xml = b'org.test.App.desktopTestSummary

Description

Utility
org.test.Other
' + result = self.parse(xml) + self.assertEqual(result["org.test.App"]["categories"], ["Utility"]) + self.assertNotIn("description", result["org.test.App"]) + details = self.parse(xml, "org.test.App") + self.assertEqual(list(details), ["org.test.App"]) + self.assertEqual(details["org.test.App"]["description"], "Description") + + def test_rejects_dtd_entities_and_malformed_roots(self): + for xml in (b']>', + b'', b''): + with self.assertRaises((ValueError, __import__('xml.etree.ElementTree', fromlist=['ParseError']).ParseError)): + self.parse(xml) + + def test_decompressed_metadata_bound(self): + with tempfile.TemporaryDirectory() as temporary: + path = Path(temporary) / "large.xml.gz" + with gzip.open(path, "wb") as stream: + stream.write(b'') + with self.assertRaisesRegex(ValueError, "exceeds bound"): + bridge.read_appstream(path) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/test-flatpak-native.py b/scripts/test-flatpak-native.py new file mode 100644 index 0000000..8ef3263 --- /dev/null +++ b/scripts/test-flatpak-native.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +"""Real signed Flatpak repository, isolated installation; no host package state.""" +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +BRIDGE = Path(__file__).resolve().parents[1] / 'crates/archon-distro/src/flatpak_bridge.py' + +def run(*args, **kwargs): + result = subprocess.run(args, text=True, capture_output=True, **kwargs) + if result.returncode: + raise RuntimeError(f"{args}: {result.stderr} {result.stdout}") + return result.stdout + + +def main(): + with tempfile.TemporaryDirectory(prefix='archon-flatpak-native-') as directory: + root = Path(directory) + keyring = root/'keys'; keyring.mkdir(mode=0o700) + env = dict(os.environ, GNUPGHOME=str(keyring)) + run('gpg', '--batch', '--pinentry-mode', 'loopback', '--passphrase', '', '--quick-generate-key', 'Archon Disposable Test ', 'ed25519', 'sign', '1d', env=env) + fingerprint = next(line.split(':')[9] for line in run('gpg','--batch','--with-colons','--list-keys',env=env).splitlines() if line.startswith('fpr:')) + key = root/'key.gpg'; key.write_bytes(subprocess.check_output(['gpg','--batch','--export',fingerprint],env=env)) + repo = root/'repo' + runtime=root/'runtime'; (runtime/'usr/bin').mkdir(parents=True) + (runtime/'files').mkdir() + (runtime/'metadata').write_text('[Runtime]\nname=org.nizho.ArchonTestPlatform\nruntime=org.nizho.ArchonTestPlatform/x86_64/1\nsdk=org.nizho.ArchonTestPlatform/x86_64/1\n') + app=root/'app'; (app/'files/bin').mkdir(parents=True) + (app/'files/bin/archon-test').write_text('#!/bin/sh\nexit 0\n'); (app/'files/bin/archon-test').chmod(0o755) + (app/'metadata').write_text('[Application]\nname=org.nizho.ArchonTest\nruntime=org.nizho.ArchonTestPlatform/x86_64/1\nsdk=org.nizho.ArchonTestPlatform/x86_64/1\ncommand=archon-test\n') + run('flatpak','build-export','--runtime',f'--gpg-sign={fingerprint}',str(repo),str(runtime),'1',env=env) + run('flatpak','build-finish',str(app),env=env) + run('flatpak','build-export',f'--gpg-sign={fingerprint}',str(repo),str(app),'stable',env=env) + run('flatpak','build-update-repo',f'--gpg-sign={fingerprint}',str(repo),env=env) + installation=root/'installation' + # Register the remote in this isolated installation using libflatpak. + import gi + gi.require_version('Flatpak','1.0') + from gi.repository import Flatpak,Gio,GLib + native=Flatpak.Installation.new_for_path(Gio.File.new_for_path(str(installation)),True,None) + remote=Flatpak.Remote.new('archon-test'); remote.set_url(repo.as_uri());remote.set_gpg_verify(True);remote.set_gpg_key(GLib.Bytes.new(key.read_bytes()));native.modify_remote(remote,None) + def bridge(mode, **fields): + output=run(sys.executable,str(BRIDGE),'--test-installation',str(installation),input=json.dumps(dict(mode=mode,**fields))) + events=[json.loads(line) for line in output.splitlines()] + return next(event['value'] for event in events if event['event']=='result') + request=dict(action='install',package='app/org.nizho.ArchonTest/x86_64/stable',repository='archon-test') + assert bridge('installed')==[] + if os.environ.get('NIZHO_NATIVE_DBUS_TEST'): + subprocess.run(['dbus-run-session','--',sys.executable,os.environ['NIZHO_NATIVE_DBUS_TEST'],os.environ['NIZHO_ARCHON_SERVICE'],str(installation),str(root/'service-state')],check=True) + assert any(p['id']==request['package'] for p in bridge('search',query='ArchonTest',offset=0,limit=50)) + assert 'org.nizho.ArchonTestPlatform' in bridge('details',package=request['package'],repository='archon-test')['dependencies'] + plan=bridge('plan',request=request) + assert bridge('installed')==[], 'planning mutated the installation' + assert len(plan['changes'])>=2, 'runtime dependency was not planned' + expired=subprocess.run([sys.executable,str(BRIDGE),'--test-installation',str(installation)],input=json.dumps(dict(mode='commit',request=request,expected=plan,expires_at=0)),text=True,capture_output=True) + assert expired.returncode != 0 and bridge('installed')==[] + cancelled=subprocess.run([sys.executable,str(BRIDGE),'--test-installation',str(installation)],input=json.dumps(dict(mode='commit',request=request,expected=plan))+'\ncancel\n',text=True,capture_output=True) + assert cancelled.returncode != 0 and bridge('installed')==[] + print('PASS expiry and native cancellation without installation') + bridge('commit',request=request,expected=plan) + assert any(p['name']=='org.nizho.ArchonTest' for p in bridge('installed')) + print('PASS real signed installation and dependency resolution') + (app/'files/bin/archon-test').write_text('#!/bin/sh\n# version two\nexit 0\n') + run('flatpak','build-export',f'--gpg-sign={fingerprint}',str(repo),str(app),'stable',env=env) + run('flatpak','build-update-repo',f'--gpg-sign={fingerprint}',str(repo),env=env) + assert any(p['name']=='org.nizho.ArchonTest' for p in bridge('updates')) + update=dict(request,action='update');update_plan=bridge('plan',request=update) + bridge('commit',request=update,expected=update_plan) + print('PASS real signed update discovery, planning and installation') + # Replaying the old resolved state must fail, without accepting a new plan. + replay=subprocess.run([sys.executable,str(BRIDGE),'--test-installation',str(installation)],input=json.dumps(dict(mode='commit',request=request,expected=plan)),text=True,capture_output=True) + assert replay.returncode != 0, 'replay unexpectedly succeeded' + print('PASS stale/replayed native plan rejection') + request['action']='remove'; plan=bridge('plan',request=request); bridge('commit',request=request,expected=plan) + assert bridge('installed')==[] + print('PASS real removal') + (app/'files/bin/archon-test').write_text('#!/bin/sh\n# unsigned version three\nexit 0\n') + run('flatpak','build-export',str(repo),str(app),'stable',env=env) + run('flatpak','build-update-repo',f'--gpg-sign={fingerprint}',str(repo),env=env) + unsigned=dict(request,action='install') + candidate=subprocess.run([sys.executable,str(BRIDGE),'--test-installation',str(installation)],input=json.dumps(dict(mode='plan',request=unsigned)),text=True,capture_output=True) + if candidate.returncode==0: + unsigned_plan=next(json.loads(line)['value'] for line in candidate.stdout.splitlines() if json.loads(line)['event']=='result') + candidate=subprocess.run([sys.executable,str(BRIDGE),'--test-installation',str(installation)],input=json.dumps(dict(mode='commit',request=unsigned,expected=unsigned_plan)),text=True,capture_output=True) + assert candidate.returncode != 0, 'unsigned artifact was accepted' + assert bridge('installed')==[] + print('PASS unsigned artifact rejection with signature policy still enabled') + # A configured remote with verification disabled is never accepted. + remote.set_gpg_verify(False);native.modify_remote(remote,None) + rejected=subprocess.run([sys.executable,str(BRIDGE),'--test-installation',str(installation)],input=json.dumps(dict(mode='plan',request=request)),text=True,capture_output=True) + assert rejected.returncode != 0 + print('PASS disabled-signature-policy rejection') + print('Artifacts removed only from this test-owned temporary directory') + +if __name__=='__main__': + main()