384 lines
21 KiB
Rust
384 lines
21 KiB
Rust
//! Temporary hardware-test update adapter: signed OSTree, pinned plans, no reboot.
|
|
use serde_json::{json, Value};
|
|
use std::{fs::{self, File}, os::unix::fs::DirBuilderExt,
|
|
path::{Path, PathBuf}, process::Command, time::{SystemTime, UNIX_EPOCH}};
|
|
|
|
const STATE: &str = "/var/lib/archipelago/updates";
|
|
const REMOTE: &str = "archipelago-hardware-test";
|
|
pub(crate) mod managed;
|
|
|
|
// Support identity is independent of a locally overridden update binding. Only
|
|
// a base signed by the distribution key qualifies; no ref movement is needed.
|
|
pub(crate) fn verify_supported_base(base: &str) -> Result<(), String> {
|
|
if !digest(base) { return Err("invalid base checksum".into()); }
|
|
let dir = "/var/lib/archipelago/support";
|
|
fs::DirBuilder::new().recursive(true).mode(0o700).create(dir).map_err(|e| e.to_string())?;
|
|
let lock = File::options().create(true).truncate(false).write(true)
|
|
.open(format!("{dir}/lock")).map_err(|e| e.to_string())?;
|
|
lock.try_lock().map_err(|e| e.to_string())?;
|
|
let repository = format!("--repo={dir}/repo");
|
|
if !Path::new(dir).join("repo/config").exists() {
|
|
output("ostree", &[&repository, "init", "--mode=archive"])?;
|
|
}
|
|
let key = format!("{dir}/distribution.asc");
|
|
fs::write(&key, include_bytes!("../archipelago-stable.asc")).map_err(|e| e.to_string())?;
|
|
output("ostree", &[&repository, "remote", "delete", "--if-exists", "distribution"])?;
|
|
output("ostree", &[&repository, "remote", "add", &format!("--gpg-import={key}"),
|
|
"--set=gpg-verify=true", "distribution", "https://mirror.nw-sys.ru/archipelago/ostree/images"])?;
|
|
if let Ok(verified) = output("ostree", &[&repository, "show", "--gpg-verify-remote=distribution", base]) {
|
|
if verified.contains("Good signature from") { return Ok(()); }
|
|
}
|
|
output("timeout", &["30", "ostree", &repository, "pull", "--commit-metadata-only",
|
|
"--depth=0", "distribution", base])?;
|
|
Ok(())
|
|
}
|
|
|
|
fn output(program: &str, args: &[&str]) -> Result<String, String> {
|
|
let result = Command::new(program).args(args).env("LC_ALL", "C").env("TZ", "UTC").output().map_err(|e| e.to_string())?;
|
|
if !result.status.success() { return Err(format!("{program}: {}", String::from_utf8_lossy(&result.stderr))); }
|
|
String::from_utf8(result.stdout).map_err(|e| e.to_string())
|
|
}
|
|
fn digest(s: &str) -> bool { s.len() == 64 && s.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) }
|
|
fn write(path: &Path, value: &Value) -> Result<(), String> {
|
|
let temp = path.with_extension("tmp");
|
|
fs::write(&temp, serde_json::to_vec_pretty(value).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?;
|
|
fs::rename(temp, path).map_err(|e| e.to_string())
|
|
}
|
|
fn repo(args: &[&str]) -> Result<String, String> {
|
|
let r = format!("--repo={STATE}/repo");
|
|
output("ostree", &[&[r.as_str()], args].concat())
|
|
}
|
|
fn wait_for_lock(file: &File, timeout: std::time::Duration) -> Result<(), String> {
|
|
let started = std::time::Instant::now();
|
|
loop {
|
|
match file.try_lock() {
|
|
Ok(()) => return Ok(()),
|
|
Err(std::fs::TryLockError::WouldBlock) if started.elapsed() < timeout => {
|
|
std::thread::sleep(std::time::Duration::from_millis(20));
|
|
}
|
|
Err(error) => return Err(format!("another host operation is running or lock unavailable: {error}")),
|
|
}
|
|
}
|
|
}
|
|
|
|
pub(crate) fn lock() -> Result<File, String> {
|
|
if output("id", &["-u"])?.trim() != "0" { return Err("Run as root".into()); }
|
|
if !Path::new("/run/ostree-booted").exists() || !Path::new("/etc/archipelago/provisioned").exists() {
|
|
return Err("complete firstboot in an installed deployment first".into());
|
|
}
|
|
let f = File::options().create(true).truncate(false).write(true).open("/run/archipelago-compose.lock").map_err(|e| e.to_string())?;
|
|
// The local observer briefly holds this same lock (bounded to 10s + 2s
|
|
// termination). Do not fail an admitted mutation on that transient race.
|
|
wait_for_lock(&f, std::time::Duration::from_secs(15))?;
|
|
fs::DirBuilder::new().recursive(true).mode(0o700).create(STATE).map_err(|e| e.to_string())?;
|
|
Ok(f)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod lock_tests {
|
|
use super::*;
|
|
fn files() -> (File, File) {
|
|
let path = std::env::temp_dir().join(format!("archipelago-lock-{}-{}", std::process::id(),
|
|
SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos()));
|
|
let first = File::options().create_new(true).write(true).open(&path).unwrap();
|
|
let second = File::options().write(true).open(&path).unwrap();
|
|
fs::remove_file(path).unwrap();
|
|
(first, second)
|
|
}
|
|
#[test]
|
|
fn mutation_waits_for_short_observation() {
|
|
let (observer, mutation) = files();
|
|
observer.try_lock().unwrap();
|
|
let release = std::thread::spawn(move || {
|
|
std::thread::sleep(std::time::Duration::from_millis(80));
|
|
drop(observer);
|
|
});
|
|
assert!(wait_for_lock(&mutation, std::time::Duration::from_secs(2)).is_ok());
|
|
release.join().unwrap();
|
|
}
|
|
#[test]
|
|
fn competing_writer_still_blocks_mutation() {
|
|
let (writer, mutation) = files();
|
|
writer.try_lock().unwrap();
|
|
assert!(wait_for_lock(&mutation, std::time::Duration::from_millis(40)).is_err());
|
|
drop(writer);
|
|
assert!(wait_for_lock(&mutation, std::time::Duration::ZERO).is_ok());
|
|
}
|
|
}
|
|
pub(crate) fn binding() -> Result<Value, String> {
|
|
let local = Path::new("/etc/archipelago/update.json");
|
|
let path = if local.exists() { local } else { Path::new("/usr/lib/archipelago/update.json") };
|
|
let profile: Value = serde_json::from_slice(&fs::read(path).map_err(|e| format!("update profile {}: {e}", path.display()))?).map_err(|e| e.to_string())?;
|
|
let url = profile["url"].as_str().ok_or("missing update URL")?;
|
|
let reference = profile["refs"][variant()?].as_str().ok_or("missing variant ref")?;
|
|
if profile["version"] != 1 || !(url.starts_with("https://") || url.starts_with("http://") || url.starts_with("file:///")) || url.chars().any(char::is_whitespace) {
|
|
return Err("unsupported update profile URL/version".into());
|
|
}
|
|
if reference.is_empty() || reference.starts_with('/') || reference.split('/').any(|p| p.is_empty() || p == "." || p == "..") ||
|
|
!reference.bytes().all(|c| c.is_ascii_alphanumeric() || b"/_.-".contains(&c)) {
|
|
return Err("invalid update ref".into());
|
|
}
|
|
let key = profile["public_key_file"].as_str().filter(|s| s.starts_with('/')).ok_or("absolute public key path required")?;
|
|
let key_hash = output("sha256sum", &[key])?.split_whitespace().next().ok_or("missing public key checksum")?.to_string();
|
|
Ok(json!({"profile":profile,"key_sha256":key_hash,"reference":reference}))
|
|
}
|
|
fn configure(binding: &Value) -> Result<(), String> {
|
|
if !Path::new(STATE).join("repo/config").exists() { repo(&["init", "--mode=archive"])?; }
|
|
let key = format!("{STATE}/hardware-test.asc");
|
|
fs::copy(binding["profile"]["public_key_file"].as_str().ok_or("missing key")?, &key).map_err(|e| e.to_string())?;
|
|
repo(&["remote", "delete", "--if-exists", REMOTE])?;
|
|
repo(&["remote", "add", &format!("--gpg-import={key}"), "--set=gpg-verify=true",
|
|
"--set=gpg-verify-summary=true", REMOTE, binding["profile"]["url"].as_str().ok_or("missing URL")?])?;
|
|
Ok(())
|
|
}
|
|
fn booted(state: &Value) -> Result<String, String> {
|
|
let deployments = state["deployments"].as_array().ok_or("missing deployments")?;
|
|
if deployments.iter().any(|d| d["pending"] == true || d["staged"] == true) {
|
|
return Err("activate or explicitly reconcile the pending deployment first".into());
|
|
}
|
|
let d = deployments.iter().find(|d| d["booted"] == true && d["stateroot"] == "archipelago").ok_or("missing booted deployment")?;
|
|
let c = d["checksum"].as_str().ok_or("missing checksum")?;
|
|
if !digest(c) { return Err("invalid checksum".into()); }
|
|
Ok(c.into())
|
|
}
|
|
fn summary_commit(summary: &str, reference: &str) -> Result<String, String> {
|
|
let mut selected = false;
|
|
for line in summary.lines() {
|
|
if let Some(name) = line.strip_prefix("* ") { selected = name == reference; }
|
|
else if selected && digest(line.trim()) { return Ok(line.trim().into()); }
|
|
}
|
|
Err("signed summary does not contain the selected image track".into())
|
|
}
|
|
fn purpose_variant(identity: &str) -> Result<&'static str, String> {
|
|
match identity.trim() {
|
|
"purpose/desktop/gnome" => Ok("gnome"),
|
|
"purpose/desktop/kde" => Ok("kde"),
|
|
"purpose/server/container-runner" => Ok("container"),
|
|
other => Err(format!("unsupported Purpose identity: {other:?}")),
|
|
}
|
|
}
|
|
fn variant() -> Result<&'static str, String> {
|
|
match fs::read_to_string("/usr/lib/archipelago/purpose") {
|
|
Ok(identity) => purpose_variant(&identity),
|
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
|
// Legacy images predate the explicit Purpose identity.
|
|
Ok(if Path::new("/usr/lib/archipelago/gnome-firstboot").exists() { "gnome" } else { "core" })
|
|
}
|
|
Err(e) => Err(format!("read Purpose identity: {e}")),
|
|
}
|
|
}
|
|
fn commit_date(repository: &str, commit: &str) -> Result<String, String> {
|
|
let text = output("ostree", &[&format!("--repo={repository}"), "show", commit])?;
|
|
let date = text.lines().find_map(|line| line.strip_prefix("Date:")).ok_or("commit date missing")?.trim();
|
|
// libostree's C-locale UTC date is fixed-width and sorts chronologically.
|
|
if date.len() != 25 || !date.ends_with(" +0000") ||
|
|
!date.bytes().enumerate().all(|(i, c)| match i {
|
|
4 | 7 => c == b'-', 10 | 19 => c == b' ', 13 | 16 => c == b':',
|
|
20 => c == b'+', _ => c.is_ascii_digit(),
|
|
}) {
|
|
return Err("unsupported commit date format; update refused".into());
|
|
}
|
|
Ok(date.into())
|
|
}
|
|
fn require_newer(base: &str, target: &str) -> Result<(), String> {
|
|
if base == target { return Ok(()); }
|
|
// Metadata-only pull still verifies the target's signature before inspecting it.
|
|
repo(&["pull", "--commit-metadata-only", "--depth=0", REMOTE, target])?;
|
|
let before = commit_date("/sysroot/ostree/repo", base)?;
|
|
let after = commit_date(&format!("{STATE}/repo"), target)?;
|
|
if after <= before {
|
|
return Err(format!("Обновление отклонено: целевой образ {target} ({after}) не новее текущей базы {base} ({before}). Используйте явный rollback для отката."));
|
|
}
|
|
Ok(())
|
|
}
|
|
pub(crate) fn stage_deployment(commit: &str) -> Result<(), String> {
|
|
crate::progress::phase("Staging deployment and boot entry", "Подготовка deployment и загрузочной записи");
|
|
let mut args = vec!["admin", "deploy", "--stage", "--retain", "--os=archipelago"];
|
|
if matches!(variant()?, "gnome" | "kde") {
|
|
args.extend(["--karg=quiet", "--karg=splash", "--karg=plymouth.ignore-serial-consoles"]);
|
|
}
|
|
args.push(commit);
|
|
output("ostree", &args).map(|_| ())
|
|
}
|
|
fn reconcile_operations() -> Result<(), String> {
|
|
// Caller owns the shared host-operation lock: no prior CLI operation can run.
|
|
for entry in fs::read_dir(STATE).map_err(|e| e.to_string())? {
|
|
let path = entry.map_err(|e| e.to_string())?.path();
|
|
let name = path.file_name().and_then(|s| s.to_str()).unwrap_or("");
|
|
if !name.starts_with("operation-") || !name.ends_with(".json") { continue; }
|
|
let mut record: Value = serde_json::from_slice(&fs::read(&path).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?;
|
|
if record["state"] == "executing" {
|
|
record["state"] = json!("interrupted");
|
|
record["error"] = json!("Previous process ended without terminal status; inspect actual deployments");
|
|
write(&path, &record)?;
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
fn plan_path(id: &str) -> Result<PathBuf, String> {
|
|
if !digest(id) { return Err("expected a 64-character plan digest".into()); }
|
|
Ok(Path::new(STATE).join(format!("plan-{id}.json")))
|
|
}
|
|
pub fn plan(save: bool) -> Result<(), String> {
|
|
plan_output(save, false, false)
|
|
}
|
|
pub fn plan_json(save: bool) -> Result<(), String> {
|
|
plan_output(save, true, true)
|
|
}
|
|
pub fn diff() -> Result<(), String> { plan_output(false, false, true) }
|
|
|
|
/// Shared planning result. Formatting is a client concern; the future service
|
|
/// admission layer must bind this to its journal before advertising PrepareUpdate.
|
|
pub(crate) struct PreparedUpdate {
|
|
pub plan: Value,
|
|
pub plan_id: Option<String>,
|
|
}
|
|
|
|
pub(crate) fn prepare(save: bool, include_diff: bool, exact_target: Option<&str>) -> Result<PreparedUpdate, String> {
|
|
if exact_target.is_some_and(|s| !digest(s)) { return Err("invalid exact target checksum".into()); }
|
|
let _lock = lock()?;
|
|
reconcile_operations()?;
|
|
let binding = binding()?;
|
|
configure(&binding)?;
|
|
let state = crate::extensions::status()?;
|
|
let current = booted(&state)?;
|
|
let (base, requested) = crate::extensions::intent(¤t)?;
|
|
let files = output("ostree", &["--repo=/sysroot/ostree/repo", "ls", &base, "/usr/lib/archipelago"])?;
|
|
if files.lines().any(|l| l.ends_with("/overlays")) {
|
|
return Err("updating custom managed overlays is not implemented; existing deployment preserved".into());
|
|
}
|
|
let reference = binding["reference"].as_str().ok_or("missing reference")?;
|
|
let target = summary_commit(&repo(&["remote", "summary", REMOTE])?, &reference)?;
|
|
if exact_target.is_some_and(|expected| expected != target) {
|
|
return Err("verified track target differs from the requested target; no implicit retarget".into());
|
|
}
|
|
require_newer(&base, &target)?;
|
|
let mut plan = json!({"version":3,"binding":binding,"variant":variant()?,"reference":reference,
|
|
"target":target,"base":base,"requested":requested,"initial":state});
|
|
if include_diff {
|
|
let inventory = "/usr/lib/archipelago/packages.txt";
|
|
repo(&["pull", "--depth=0", &format!("--subpath={inventory}"), REMOTE, &target])?;
|
|
let before = output("ostree", &["--repo=/sysroot/ostree/repo", "cat", &base, inventory])?;
|
|
let after = repo(&["cat", &target, inventory])?;
|
|
plan["package_changes"] = json!(crate::package_diff::between(&before, &after)?);
|
|
plan["package_changes_scope"] = json!("managed-base");
|
|
}
|
|
let plan_id = if save {
|
|
let temp = Path::new(STATE).join("plan.tmp");
|
|
write(&temp, &plan)?;
|
|
let hash = output("sha256sum", &[temp.to_str().unwrap()])?.split_whitespace().next().ok_or("missing digest")?.to_string();
|
|
fs::rename(&temp, plan_path(&hash)?).map_err(|e| e.to_string())?;
|
|
Some(hash)
|
|
} else { None };
|
|
Ok(PreparedUpdate { plan, plan_id })
|
|
}
|
|
|
|
fn plan_output(save: bool, json_output: bool, include_diff: bool) -> Result<(), String> {
|
|
let PreparedUpdate { plan, plan_id } = prepare(save, include_diff, None)?;
|
|
let reference = plan["reference"].as_str().ok_or("missing plan reference")?;
|
|
let base = plan["base"].as_str().ok_or("missing plan base")?;
|
|
let target = plan["target"].as_str().ok_or("missing plan target")?;
|
|
if plan_id.is_none() {
|
|
if json_output { println!("{}", serde_json::to_string_pretty(&plan).unwrap()); }
|
|
else {
|
|
println!("Track: {reference}\nCurrent: {base}\nTarget: {target}");
|
|
println!("State: {}", if base == target { "up to date" } else { "update available" });
|
|
if let Some(changes) = plan["package_changes"].as_array() {
|
|
println!("\n{:<32} {:<24} {}", "Package", "Installed", "Target");
|
|
for change in changes {
|
|
println!("{:<32} {:<24} {}", change["name"].as_str().unwrap_or("?"),
|
|
change["old_version"].as_str().unwrap_or("—"), change["new_version"].as_str().unwrap_or("removed"));
|
|
}
|
|
}
|
|
}
|
|
return Ok(());
|
|
}
|
|
let hash = plan_id.ok_or("missing saved plan identity")?;
|
|
if json_output {
|
|
println!("{}", serde_json::to_string_pretty(&json!({"plan_id":hash,"plan":plan})).unwrap());
|
|
} else {
|
|
println!("Plan: {hash}\nTarget: {target}\nApply: sudo archipelago update apply --plan {hash}");
|
|
}
|
|
Ok(())
|
|
}
|
|
pub fn apply(id: &str) -> Result<(), String> {
|
|
execute_plan(id, false)
|
|
}
|
|
pub fn download(id: &str) -> Result<(), String> {
|
|
execute_plan(id, true)
|
|
}
|
|
fn execute_plan(id: &str, download_only: bool) -> Result<(), String> {
|
|
crate::progress::phase("Checking saved plan and current deployment", "Проверка плана и текущего deployment");
|
|
let _lock = lock()?;
|
|
reconcile_operations()?;
|
|
let path = plan_path(id)?;
|
|
if output("sha256sum", &[path.to_str().unwrap()])?.split_whitespace().next() != Some(id) {
|
|
return Err("plan integrity failure".into());
|
|
}
|
|
let plan: Value = serde_json::from_slice(&fs::read(&path).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?;
|
|
let operation = Path::new(STATE).join(format!("operation-{}.json", SystemTime::now().duration_since(UNIX_EPOCH).map_err(|e| e.to_string())?.as_nanos()));
|
|
write(&operation, &json!({"plan":id,"state":"executing"}))?;
|
|
let result = apply_plan(&plan, download_only);
|
|
let terminal = match &result { Ok(()) => json!({"plan":id,"state":"completed"}), Err(e) => json!({"plan":id,"state":"failed","error":e}) };
|
|
if let Err(error) = write(&operation, &terminal) {
|
|
eprintln!("Could not record terminal operation state: {error}; inspect deployment status");
|
|
}
|
|
result
|
|
}
|
|
fn apply_plan(plan: &Value, download_only: bool) -> Result<(), String> {
|
|
let binding = binding()?;
|
|
if plan["version"] != 3 || plan["binding"] != binding || plan["variant"] != variant()? { return Err("unsupported plan or infrastructure binding changed; create a new plan".into()); }
|
|
let initial = crate::extensions::status()?;
|
|
booted(&initial)?;
|
|
if initial != plan["initial"] { return Err("deployment state changed; create a new plan".into()); }
|
|
let target = plan["target"].as_str().filter(|s| digest(s)).ok_or("invalid target")?;
|
|
if plan["base"] == target { println!("Already on the selected base; no deployment created."); return Ok(()); }
|
|
configure(&binding)?;
|
|
require_newer(plan["base"].as_str().filter(|s| digest(s)).ok_or("invalid base")?, target)?;
|
|
crate::progress::phase("Downloading and verifying the image", "Загрузка и проверка подписанного образа");
|
|
// The signed summary selects the checksum during planning; exact-checksum pull
|
|
// verifies its commit signature without reinterpreting old build-local ref bindings.
|
|
repo(&["pull", "--depth=0", REMOTE, target])?;
|
|
let files = repo(&["ls", target, "/usr/lib/archipelago"])?;
|
|
crate::progress::phase("Checking Purpose and architecture", "Проверка Purpose и архитектуры");
|
|
let candidate = if files.lines().any(|l| l.ends_with("/purpose")) {
|
|
purpose_variant(&repo(&["cat", target, "/usr/lib/archipelago/purpose"])?)?
|
|
} else if files.lines().any(|l| l.ends_with("/gnome-firstboot")) {
|
|
"gnome"
|
|
} else { "core" };
|
|
if candidate != variant()? { return Err("candidate Purpose differs from booted Purpose".into()); }
|
|
if output("uname", &["-m"])?.trim() != "x86_64" { return Err("only x86_64 is implemented".into()); }
|
|
repo(&["cat", target, "/usr/lib/archipelago/snapshot"])?;
|
|
if download_only {
|
|
if crate::extensions::status()? != initial { return Err("deployment state changed during download".into()); }
|
|
println!("Verified image downloaded; no deployment staged.");
|
|
return Ok(());
|
|
}
|
|
output("ostree", &["--repo=/sysroot/ostree/repo", "pull-local", &format!("{STATE}/repo"), target])?;
|
|
crate::progress::phase("Preparing the new system", "Подготовка новой системы");
|
|
let requested: crate::extensions::Requests = serde_json::from_value(plan["requested"].clone()).map_err(|e| e.to_string())?;
|
|
if crate::extensions::status()? != initial { return Err("deployment state changed during download".into()); }
|
|
if requested.is_empty() {
|
|
stage_deployment(target)?;
|
|
} else { crate::extensions::reapply(target, &requested, &initial)?; }
|
|
println!("Update prepared. Activate with an explicit reboot. Current /usr unchanged.");
|
|
Ok(())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
#[test]
|
|
fn container_runner_purpose_identity_is_supported() {
|
|
assert_eq!(purpose_variant("purpose/server/container-runner").unwrap(), "container");
|
|
assert!(purpose_variant("purpose/server/unknown").is_err());
|
|
}
|
|
use super::*;
|
|
#[test]
|
|
fn summary_track_is_exact_and_missing_track_fails() {
|
|
let a = "a".repeat(64); let b = "b".repeat(64);
|
|
let s = format!("* hardware-test/core-other\n {a}\n* hardware-test/core\n Latest Commit:\n {b}\n");
|
|
assert_eq!(summary_commit(&s, "hardware-test/core").unwrap(), b);
|
|
assert!(summary_commit(&s, "hardware-test/gnome").is_err());
|
|
assert!(plan_path("../../etc/passwd").is_err());
|
|
}
|
|
}
|