diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 11e72a6..3c276fa 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -28,6 +28,10 @@ env: # moves the path with it — a baked-in absolute path once kept pointing at # the previous user's home and failed the deploy on permissions. DEPLOY_SUBDIR: im + # Baked into the binary by build.rs and asserted against after the + # deploy restart: a /healthz answered by a stale process from an old + # deploy now fails and rolls back instead of reporting green. + IM_BUILD_SHA: ${{ github.sha }} jobs: deploy: @@ -143,10 +147,11 @@ jobs: # bash -s for the same reason as above: the login shell is not # bash and must never see this script. - ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR' '$SERVICE'" <<'REMOTE' + ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR' '$SERVICE' '$GITHUB_SHA'" <<'REMOTE' set -euo pipefail deploy_path=$HOME/$1 service=$2 + expected="ok $3" export XDG_RUNTIME_DIR=/run/user/$(id -u) # Read before anything moves: a config the health check cannot # read is a failure to stop on, not one to roll back from. @@ -155,6 +160,12 @@ jobs: echo "no listen address in $deploy_path/config/im.toml" >&2 exit 1 fi + # The config directory carries secrets: the toml and any keys + # files are held to 0600, and the editor's stray secret-bearing + # backups go away — every deploy, the same way. + chmod 0600 -- "$deploy_path/config/"*.toml 2>/dev/null || true + chmod 0600 -- "$deploy_path/config/"*.keys 2>/dev/null || true + find "$deploy_path/config" -maxdepth 1 -type f \( -name '*.bak*' -o -name '*.pre-*' \) -delete chmod +x -- "$deploy_path/current.new/im-web" rm -rf -- "$deploy_path/current.previous" if [ -e "$deploy_path/current" ]; then @@ -169,20 +180,29 @@ jobs: systemctl --user daemon-reload systemctl --user enable -- "$service" systemctl --user restart "$service" - # The unit is Type=simple, so a restart returns before the process - # has bound its port. Wait for the health route rather than a clock. + # The unit is Type=simple, so a restart returns before the new + # process has bound its port — and before an old one has let go + # of it. Wait for the health route rather than a clock, and + # check the answer names this commit: a stale process can still + # answer, and did once on a sibling deploy. + rollback() { + rm -rf -- "$deploy_path/current" + mv -- "$deploy_path/current.previous" "$deploy_path/current" + systemctl --user restart "$service" + } for _ in $(seq 1 30); do - if curl -fsS "http://$listen/healthz" >/dev/null 2>&1; then - echo 'im is up' - rm -rf -- "$deploy_path/current.previous" - exit 0 + served=$(curl -fsS "http://$listen/healthz" 2>/dev/null) || { sleep 1; continue; } + if [ "$served" != "$expected" ]; then + echo "/healthz answered '$served', wanted '$expected'; rolling back" >&2 + rollback + exit 1 fi - sleep 1 + echo 'im is up' + rm -rf -- "$deploy_path/current.previous" + exit 0 done echo 'im did not answer /healthz; rolling back' >&2 - rm -rf -- "$deploy_path/current" - mv -- "$deploy_path/current.previous" "$deploy_path/current" - systemctl --user restart "$service" + rollback exit 1 REMOTE diff --git a/Cargo.lock b/Cargo.lock index a457196..c2cf937 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1139,6 +1139,16 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "filetime" +version = "0.2.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" +dependencies = [ + "cfg-if", + "libc", +] + [[package]] name = "find-msvc-tools" version = "0.1.12" @@ -1882,6 +1892,7 @@ version = "0.1.0" dependencies = [ "base64 0.23.1", "data-encoding", + "flate2", "futures-util", "grass", "http", @@ -1889,8 +1900,10 @@ dependencies = [ "lettre", "parking_lot", "qrcode", + "reqwest", "serde", "serde_json", + "tar", "thiserror", "time", "tokio", @@ -3884,6 +3897,17 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", + "xattr", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -5287,6 +5311,16 @@ dependencies = [ "tap", ] +[[package]] +name = "xattr" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" +dependencies = [ + "libc", + "rustix 1.1.4", +] + [[package]] name = "yoke" version = "0.8.3" diff --git a/crates/im-web/Cargo.toml b/crates/im-web/Cargo.toml index 1f713b1..cbad81c 100644 --- a/crates/im-web/Cargo.toml +++ b/crates/im-web/Cargo.toml @@ -32,6 +32,11 @@ ulid.workspace = true base64.workspace = true toml.workspace = true data-encoding = "2.11.1" +# The admin health panel probes each service's `/healthz` where it stands. +reqwest = { version = "0.13.5", default-features = false, features = ["rustls"] } +# `pack` / `unpack`: the family's backup archive, one gzipped tar. +tar = "0.4" +flate2 = "1" qrcode = { version = "0.14.1", default-features = false, features = ["svg"] } # TLS through rustls with the ring provider: no OpenSSL on the deployment box, # and no system certificate store to be missing inside a container. diff --git a/crates/im-web/assets/main.css b/crates/im-web/assets/main.css index d1b3428..b2a0c81 100644 --- a/crates/im-web/assets/main.css +++ b/crates/im-web/assets/main.css @@ -1000,6 +1000,21 @@ body:has(.log-list) .admin-card:has(.log-list) { color: var(--muted); } +.health-dot { + display: inline-block; + width: 0.55rem; + height: 0.55rem; + border-radius: 50%; + margin-right: 0.4rem; + vertical-align: baseline; +} +.health-dot.health-on { + background: #2e9e5b; +} +.health-dot.health-off { + background: var(--muted); +} + .actions { display: flex; flex-wrap: wrap; diff --git a/crates/im-web/build.rs b/crates/im-web/build.rs index 2e177b6..9dce544 100644 --- a/crates/im-web/build.rs +++ b/crates/im-web/build.rs @@ -15,4 +15,13 @@ fn main() { let out_dir = format!("{manifest_dir}/assets"); std::fs::create_dir_all(&out_dir).expect("failed to create assets/"); std::fs::write(format!("{out_dir}/main.css"), &css).expect("failed to write assets/main.css"); + + // The commit this binary was built from, served by `/healthz` and + // asserted against after the deploy restart, so a stale process + // holding the port cannot pass for this deploy. "dev" locally, where + // nothing asserts it. The rerun-if-env-changed line is load-bearing: + // without it a rust-cache hit would ship last deploy's sha. + let sha = std::env::var("IM_BUILD_SHA").unwrap_or_else(|_| "dev".into()); + println!("cargo:rustc-env=IM_BUILD_SHA={sha}"); + println!("cargo:rerun-if-env-changed=IM_BUILD_SHA"); } diff --git a/crates/im-web/src/admin.rs b/crates/im-web/src/admin.rs index b64d0ff..525ba30 100644 --- a/crates/im-web/src/admin.rs +++ b/crates/im-web/src/admin.rs @@ -149,6 +149,7 @@ async fn admin_page(cx: &Cx) -> Result { ("message", t(lang, Key::NavMessage)), ("settings", t(lang, Key::NavSettings)), ("logs", t(lang, Key::NavLogs)), + ("health", t(lang, Key::NavHealth)), ] .into_iter() .map(|(id, label)| { @@ -165,6 +166,7 @@ async fn admin_page(cx: &Cx) -> Result { "message" => message_section(cx, lang).await?, "settings" => settings_section(cx, lang).await?, "logs" => logs_section(cx, lang).await?, + "health" => health_section(cx, lang).await?, // `section=clients` lands here too — the sections are one table // now, and the old address keeps working. "services" | "clients" => services_section(cx, shown, lang).await?, @@ -1431,6 +1433,95 @@ async fn logs_section(cx: &Cx, lang: i18n::Lang) -> Result Result { + let services = im_core::services::list(&app(cx).store).await?; + // Every probe at once: a family member that is down costs its two + // seconds, not two seconds each. + let http = reqwest::Client::new(); + let mut probes = Vec::new(); + for service in &services { + let http = http.clone(); + let url = format!("{}/healthz", service.url.trim_end_matches('/')); + probes.push(tokio::spawn(async move { probe_healthz(&http, &url).await })); + } + + let mut rows = String::new(); + for (service, probe) in services.iter().zip(probes) { + let key = escape(&service.key); + let name = escape(&service.name); + let url = escape(&service.url); + let state = match probe.await.unwrap_or(Probe::Down) { + Probe::Up { body, ms } => format!( + r#"{} · {ms} ms"#, + escape(&body) + ), + Probe::Down => format!( + r#"{}"#, + t(lang, Key::HealthUnreachable), + ), + }; + rows.push_str(&format!( + r#"{key}{name}{url}{state}"#, + )); + } + Ok(format!( + r#"
+
{title}
+
+ + + {rows} +
{key_label}{name_label}{url_label}{state_label}
+
+
"#, + title = t(lang, Key::HealthTitle), + key_label = t(lang, Key::ServiceKeyLabel), + name_label = t(lang, Key::NameCol), + url_label = t(lang, Key::AddressLabel), + state_label = t(lang, Key::HealthStateCol), + )) +} + +/// One `/healthz` reading. `Up` carries the body — the deploy contract's +/// `ok ` — and the answer's latency; everything else, refused +/// or wrong status or a body that does not begin ok or the two-second +/// ceiling, is `Down`. +enum Probe { + Up { body: String, ms: u128 }, + Down, +} + +async fn probe_healthz(http: &reqwest::Client, url: &str) -> Probe { + let started = std::time::Instant::now(); + let Ok(answer) = http + .get(url) + .timeout(std::time::Duration::from_secs(2)) + .send() + .await + else { + return Probe::Down; + }; + if !answer.status().is_success() { + return Probe::Down; + } + let body = answer.text().await.unwrap_or_default(); + let body = body.trim(); + if body.starts_with("ok") { + Probe::Up { + body: body.chars().take(64).collect(), + ms: started.elapsed().as_millis(), + } + } else { + Probe::Down + } +} /// Fits the log's page size to the browser's own viewport: measured against /// the first rendered row, never against a guess at the row height. A fit /// that would change the page size reloads once through a fresh @@ -2507,4 +2598,95 @@ mod tests { ); } } + + /// The deploy asserts this body after the restart — the answer must + /// carry the baked build sha, `dev` in a plain build. + #[tokio::test] + async fn healthz_answers_the_baked_sha() { + let setup = setup().await; + let (status, _, body) = get_full(&setup.router, "/healthz", None).await; + assert_eq!(status, StatusCode::OK); + assert!( + body.starts_with("ok "), + "healthz must answer `ok `, got {body:?}" + ); + } + + /// The probe reads a service answering the deploy body as Up with the + /// body carried, and a service with nobody home as Down — not a hang, + /// not an error. + #[tokio::test] + async fn health_probe_reads_ok_and_refuses_the_rest() { + use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; + + let http = reqwest::Client::new(); + + // A stand-in service answering the deploy body. + use super::{Probe, probe_healthz}; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + + let addr = listener.local_addr().unwrap(); + let talker = tokio::spawn(async move { + let (mut sock, _) = listener.accept().await.unwrap(); + let mut buf = [0u8; 1024]; + let _ = sock.read(&mut buf).await; + sock.write_all(b"HTTP/1.1 200 OK\r\ncontent-length: 6\r\n\r\nok dev") + .await + .unwrap(); + }); + let probe = probe_healthz(&http, &format!("http://{addr}/healthz")).await; + talker.await.unwrap(); + let Probe::Up { body, .. } = probe else { + panic!("a service answering `ok dev` must read Up"); + }; + assert_eq!(body, "ok dev"); + + // Nobody home: refused connection, Down. + let dark = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = dark.local_addr().unwrap(); + drop(dark); + let probe = probe_healthz(&http, &format!("http://{addr}/healthz")).await; + assert!(matches!(probe, Probe::Down), "a dark port must read Down"); + } + + /// The section is admin-only and, a bundle permitting, renders the + /// health table with its nav slot. + #[tokio::test] + async fn health_section_is_admin_only_and_renders() { + let setup = setup().await; + // A family row to render: a port nobody listens on refuses the + // probe instantly, so the row reads Down without waiting it out. + // A fixture key, not a sibling's — the panel renders whatever the + // table holds. + let dark = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let dead_url = format!("http://{}", dark.local_addr().unwrap()); + drop(dark); + im_core::services::add( + &setup.store, + &im_core::services::Service { + key: "xy".into(), + name: "Fixture".into(), + url: dead_url, + owner: None, + client_id: None, + storage_limit_bytes: None, + }, + ) + .await + .unwrap(); + let (status, location, _) = + get_full(&setup.router, "/admin?section=health", Some(&setup.plain_cookie)).await; + assert_eq!(status, StatusCode::SEE_OTHER); + assert_eq!(location.as_deref(), Some("/")); + if setup.assets { + let (status, _, body) = + get_full(&setup.router, "/admin?section=health", Some(&setup.admin_cookie)).await; + assert_eq!(status, StatusCode::OK); + assert!(body.contains("Family health"), "{body}"); + assert!(body.contains("/admin?section=health"), "the nav carries the section: {body}"); + assert!(body.contains("health-dot"), "{body}"); + assert!(body.contains(">xy"), "the fixture row renders: {body}"); + assert!(body.contains("Unreachable"), "the dark row reads Down: {body}"); + } + } } diff --git a/crates/im-web/src/i18n.rs b/crates/im-web/src/i18n.rs index 3b6caea..de1adbf 100644 --- a/crates/im-web/src/i18n.rs +++ b/crates/im-web/src/i18n.rs @@ -172,6 +172,10 @@ pub enum Key { NavLogs, NavMessage, NavServices, + NavHealth, + HealthTitle, + HealthStateCol, + HealthUnreachable, OkInvited, OkRevoked, OkDisabled, @@ -573,6 +577,14 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (NavMessage, Tr) => "Mesaj", (NavServices, En) => "Services", (NavServices, Tr) => "Hizmetler", + (NavHealth, En) => "Health", + (NavHealth, Tr) => "Sağlık", + (HealthTitle, En) => "Family health", + (HealthTitle, Tr) => "Aile sağlığı", + (HealthStateCol, En) => "State", + (HealthStateCol, Tr) => "Durum", + (HealthUnreachable, En) => "Unreachable", + (HealthUnreachable, Tr) => "Erişilemiyor", (OkInvited, En) => "Invite created.", (OkInvited, Tr) => "Davet oluşturuldu.", (OkEmailChanged, En) => "Email changed.", diff --git a/crates/im-web/src/main.rs b/crates/im-web/src/main.rs index 847b49b..84d4989 100644 --- a/crates/im-web/src/main.rs +++ b/crates/im-web/src/main.rs @@ -20,6 +20,7 @@ mod layout; mod live; mod mailer; mod oidc; +mod pack; mod pages; mod people; mod photo; @@ -29,7 +30,10 @@ use config::Config; #[route(GET "/healthz")] async fn healthz() -> Result<&'static str> { - Ok("ok") + // The build's commit, baked by build.rs — the deploy asserts the exact + // body after the restart, so a stale process holding the port cannot + // pass for this one. + Ok(concat!("ok ", env!("IM_BUILD_SHA"))) } #[tokio::main] @@ -111,9 +115,68 @@ async fn main() { }; revoke_client(config, id).await; } + Some("pack") => { + let mut root = None; + let mut out = None; + let mut rest = args[2..].iter(); + while let Some(arg) = rest.next() { + match arg.as_str() { + "--root" => match rest.next() { + Some(value) => root = Some(value.clone()), + None => { + eprintln!("usage: im-web pack [--root DIR] [--out FILE]"); + eprintln!("im: --root needs a directory"); + std::process::exit(2); + } + }, + "--out" => match rest.next() { + Some(value) => out = Some(value.clone()), + None => { + eprintln!("usage: im-web pack [--root DIR] [--out FILE]"); + eprintln!("im: --out needs a file"); + std::process::exit(2); + } + }, + other => { + eprintln!("usage: im-web pack [--root DIR] [--out FILE]"); + eprintln!("im: unexpected argument {other}"); + std::process::exit(2); + } + } + } + pack::pack_command(&config, root.as_deref(), out.as_deref()).await; + } + Some("unpack") => { + let Some(archive) = args.get(2) else { + eprintln!("usage: im-web unpack FILE [--root DIR] [--force]"); + std::process::exit(2); + }; + let mut root: Option = None; + let mut force = false; + let mut rest = args[3..].iter(); + while let Some(arg) = rest.next() { + match arg.as_str() { + "--force" => force = true, + "--root" => match rest.next() { + Some(value) => root = Some(value.clone()), + None => { + eprintln!("usage: im-web unpack FILE [--root DIR] [--force]"); + eprintln!("im: --root needs a directory"); + std::process::exit(2); + } + }, + other => { + eprintln!("usage: im-web unpack FILE [--root DIR] [--force]"); + eprintln!("im: unexpected argument {other}"); + std::process::exit(2); + } + } + } + pack::unpack_command(archive, root.as_deref(), force); + } Some(other) => { eprintln!( - "im: unknown command {other:?} (expected: invite, revoke, promote, demote, create-client, rotate-client, revoke-client, or none to serve)" + "im: unknown command {other:?} (expected: invite, revoke, promote, demote, create-client, rotate-client, revoke-client, pack, unpack, or none to serve)" ); std::process::exit(2); } diff --git a/crates/im-web/src/pack.rs b/crates/im-web/src/pack.rs new file mode 100644 index 0000000..844cbe9 --- /dev/null +++ b/crates/im-web/src/pack.rs @@ -0,0 +1,574 @@ +//! `im-web pack` / `im-web unpack` — the family's backup, and its restore. +//! +//! One 0600 gzipped tar carries every service tree the deployment holds: +//! the database with its WAL sidecars, the config directory, the signing +//! key, and the object store. A `manifest.json` rides as the first member +//! and names what went in, so a restore can check before it overwrites. +//! +//! The keys come from im's services table plus im itself — the archive +//! follows the family as it grows, and no key is ever spelled out here. +//! +//! Like every CLI arm this runs while the server is stopped: Turso is a +//! single-writer engine, and a database packed under a live writer is not +//! a backup. + +use std::fs::{self, File, OpenOptions}; +use std::io::Read as _; +use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; +use std::path::{Component, Path, PathBuf}; + +use serde::{Deserialize, Serialize}; + +use crate::config::Config; + +/// The manifest at the archive's root: which keys ride inside and which +/// files each brought, and when it was packed. `version` gates the +/// restore — a shape this binary does not know refuses itself instead of +/// guessing. +#[derive(Serialize, Deserialize)] +struct Manifest { + version: u32, + packed_at: String, + services: Vec, +} + +#[derive(Serialize, Deserialize)] +struct PackedService { + key: String, + /// Paths relative to the pack root — the form the manifest names and + /// the restore writes back: `/.db`, `/config/x.toml`. + files: Vec, +} + +const MANIFEST_NAME: &str = "manifest.json"; + +/// Every family tree worth packing, one key each: the services table's +/// rows plus im's own key. The row for im normally stands on that table — +/// `register_self` writes it on every boot — but a database too young or +/// too emptied to hold it does not keep im's tree out of the archive. +pub async fn family_keys(config: &Config) -> Vec { + let store = im_core::store::Store::open(&config.database) + .await + .expect("failed to open the database"); + let services = im_core::services::list(&store) + .await + .expect("failed to read the services table"); + drop(store); + + let mut keys = vec![im_core::services::SELF_OWNER.to_string()]; + for service in services { + if !keys.contains(&service.key) { + keys.push(service.key); + } + } + keys +} + +/// `im-web pack [--root DIR] [--out FILE]`. `--root` is the directory the +/// family trees sit under; without it, the parent of the working +/// directory — on the server, `$HOME` with `$HOME/im`, `$HOME/in`, … +/// inside. Without `--out`, a stamped name in the working directory. +pub async fn pack_command(config: &Config, root: Option<&str>, out: Option<&str>) { + let keys = family_keys(config).await; + let root = root.map(PathBuf::from).unwrap_or_else(default_root); + let out = out.map(PathBuf::from).unwrap_or_else(archive_name); + println!( + "im packing {} service tree(s) from {}", + keys.len(), + root.display() + ); + match pack(&root, &keys, &out) { + Ok(()) => println!("im packed {}", out.display()), + Err(problem) => { + eprintln!("im: {problem}"); + std::process::exit(1); + } + } +} + +/// `im-web unpack FILE [--root DIR] [--force]`. Without `--force` an +/// existing target database stops the restore before anything moves. +pub fn unpack_command(archive: &str, root: Option<&str>, force: bool) { + let root = root.map(PathBuf::from).unwrap_or_else(default_root); + println!("im restoring {archive} into {}", root.display()); + match unpack(Path::new(archive), &root, force) { + Ok(restored) => println!("im restored {restored} file(s)"), + Err(problem) => { + eprintln!("im: {problem}"); + std::process::exit(1); + } + } +} + +/// Packs each key's tree — the database trio, the signing key, `config/`, +/// `storage/` — into one 0600 gzipped tar. A missing piece is a line on +/// stderr, not a failure: a tree without a `storage/` is normal, and the +/// pack's job is to take what is there. +pub fn pack(root: &Path, keys: &[String], out: &Path) -> Result<(), String> { + let mut packed = Vec::new(); + for key in keys { + let home = root.join(key); + if !home.is_dir() { + eprintln!("im {key}: no tree at {}, skipping", home.display()); + continue; + } + let mut files = Vec::new(); + // The database travels with its WAL sidecars or not at all — a + // checkpointed tree legitimately carries neither. + for name in [ + format!("{key}.db"), + format!("{key}.db-wal"), + format!("{key}.db-shm"), + format!("{key}.key"), + ] { + if home.join(&name).is_file() { + files.push(format!("{key}/{name}")); + } else { + eprintln!("im {key}: {name} not present, skipped"); + } + } + for dir in ["config", "storage"] { + let tree = home.join(dir); + if !tree.exists() { + eprintln!("im {key}: {dir}/ not present, skipped"); + continue; + } + if !tree.is_dir() { + return Err(format!("{} is not a directory", tree.display())); + } + files.extend(walk(&tree, root)?); + } + if files.is_empty() { + eprintln!("im {key}: nothing to pack, skipped"); + continue; + } + files.sort(); + packed.push(PackedService { + key: key.clone(), + files, + }); + } + if packed.is_empty() { + return Err("nothing to pack: none of the family trees holds a file".into()); + } + + let manifest = Manifest { + version: 1, + packed_at: time::OffsetDateTime::now_utc() + .format(&time::format_description::well_known::Rfc3339) + .unwrap_or_else(|_| "unknown".into()), + services: packed, + }; + let manifest_body = serde_json::to_vec_pretty(&manifest) + .map_err(|e| format!("failed to write the manifest: {e}"))?; + + if let Some(parent) = out.parent() { + if !parent.as_os_str().is_empty() { + fs::create_dir_all(parent) + .map_err(|e| format!("failed to create {}: {e}", parent.display()))?; + } + } + // 0600 from the first byte: the archive carries signing keys, so + // there is no window where it reads wider. + let file = OpenOptions::new() + .create(true) + .truncate(true) + .write(true) + .mode(0o600) + .open(out) + .map_err(|e| format!("failed to create {}: {e}", out.display()))?; + let mut tar = tar::Builder::new(flate2::write::GzEncoder::new( + file, + flate2::Compression::default(), + )); + let mut header = tar::Header::new_gnu(); + header.set_size(manifest_body.len() as u64); + header.set_mode(0o600); + header.set_cksum(); + tar.append_data(&mut header, MANIFEST_NAME, manifest_body.as_slice()) + .map_err(|e| format!("failed to add {MANIFEST_NAME}: {e}"))?; + for service in &manifest.services { + for relative in &service.files { + let path = root.join(relative); + tar.append_path_with_name(&path, relative) + .map_err(|e| format!("failed to add {relative}: {e}"))?; + } + } + tar.into_inner() + .map_err(|e| format!("failed to seal {PART}: {e}", PART = out.display()))? + .finish() + .map_err(|e| format!("failed to seal {}: {e}", out.display()))?; + Ok(()) +} + +/// Restores an archive under `root`. Refuses when a target database is +/// already there — unless `force` says an overwrite is meant — and lands +/// every config, keys file, and signing key at 0600, whatever the packing +/// machine's modes were. Answers the number of files restored. +pub fn unpack(archive: &Path, root: &Path, force: bool) -> Result { + let manifest = read_manifest(archive)?; + if manifest.version != 1 { + return Err(format!( + "archive manifest version {} is not understood here", + manifest.version + )); + } + if !force { + let in_the_way: Vec<&str> = manifest + .services + .iter() + .filter(|service| { + root.join(&service.key) + .join(format!("{}.db", service.key)) + .is_file() + }) + .map(|service| service.key.as_str()) + .collect(); + if !in_the_way.is_empty() { + return Err(format!( + "refusing to overwrite an existing database for {} — pass --force to unpack over it", + in_the_way.join(", ") + )); + } + } + + let file = File::open(archive).map_err(|e| format!("failed to open {}: {e}", archive.display()))?; + let mut restored = 0; + for entry in tar::Archive::new(flate2::read::GzDecoder::new(file)) + .entries() + .map_err(|e| format!("failed to read {}: {e}", archive.display()))? + { + let mut entry = + entry.map_err(|e| format!("{} is damaged: {e}", archive.display()))?; + let name = entry + .path() + .map_err(|e| format!("{} is damaged: {e}", archive.display()))? + .to_path_buf(); + let Some(relative) = safe_relative(&name) else { + return Err(format!( + "archive member {name:?} is not a safe relative path" + )); + }; + if relative == Path::new(MANIFEST_NAME) { + continue; + } + // Directories are made as their files need them; anything else a + // member could be — a link, a device — is not something this + // archive has business carrying. + if !entry.header().entry_type().is_file() { + return Err(format!("archive member {relative:?} is not a regular file")); + } + let destination = root.join(relative); + if let Some(parent) = destination.parent() { + fs::create_dir_all(parent) + .map_err(|e| format!("failed to create {}: {e}", parent.display()))?; + } + entry + .unpack(&destination) + .map_err(|e| format!("failed to restore {}: {e}", destination.display()))?; + if let Some(secret) = secret_mode(&destination) { + fs::set_permissions(&destination, fs::Permissions::from_mode(secret)) + .map_err(|e| format!("failed to tighten {}: {e}", destination.display()))?; + } + restored += 1; + } + Ok(restored) +} + +/// Walks `dir` for regular files, each named relative to `root` — the +/// form the manifest names and the restore writes back. Symlinks are +/// refused rather than followed: the archive is the bytes of the tree, +/// not where its links point. +fn walk(dir: &Path, root: &Path) -> Result, String> { + let mut files = Vec::new(); + let mut stack = vec![dir.to_path_buf()]; + while let Some(current) = stack.pop() { + let entries = fs::read_dir(¤t) + .map_err(|e| format!("failed to read {}: {e}", current.display()))?; + for entry in entries { + let entry = entry + .map_err(|e| format!("failed to read {}: {e}", current.display()))?; + let path = entry.path(); + let kind = entry + .file_type() + .map_err(|e| format!("failed to read {}: {e}", path.display()))?; + if kind.is_dir() { + stack.push(path); + } else if kind.is_file() { + let relative = path + .strip_prefix(root) + .map_err(|e| format!("failed to name {}: {e}", path.display()))? + .to_string_lossy() + .into_owned(); + files.push(relative); + } else { + eprintln!("im skipping {}: not a regular file", path.display()); + } + } + } + Ok(files) +} + +/// The archive member as a path that stays under the restore root — +/// `None` for the absolute, upward-traversing, or empty names an archive +/// has no business carrying. +fn safe_relative(name: &Path) -> Option<&Path> { + if name.is_absolute() || name.as_os_str().is_empty() { + return None; + } + for component in name.components() { + match component { + Component::Normal(_) | Component::CurDir => {} + _ => return None, + } + } + Some(name) +} + +/// The mode a restored file is held to: 0600 for the things that carry +/// secrets — config toml, `*.keys`, the signing keys — and `None` for +/// everything else. +fn secret_mode(path: &Path) -> Option { + let shown = path.to_string_lossy(); + if shown.ends_with(".toml") || shown.ends_with(".keys") || shown.ends_with(".key") { + Some(0o600) + } else { + None + } +} + +/// Reads the archive's manifest, its first member — the pass that decides +/// whether the restore may start at all. +fn read_manifest(archive: &Path) -> Result { + let file = + File::open(archive).map_err(|e| format!("failed to open {}: {e}", archive.display()))?; + for entry in tar::Archive::new(flate2::read::GzDecoder::new(file)) + .entries() + .map_err(|e| format!("failed to read {}: {e}", archive.display()))? + { + let mut entry = + entry.map_err(|e| format!("{} is damaged: {e}", archive.display()))?; + let is_manifest = entry + .path() + .map_err(|e| format!("{} is damaged: {e}", archive.display()))? + == Path::new(MANIFEST_NAME); + if is_manifest { + let mut body = String::new(); + entry + .read_to_string(&mut body) + .map_err(|e| format!("failed to read {MANIFEST_NAME}: {e}"))?; + return serde_json::from_str(&body) + .map_err(|e| format!("{}'s manifest does not parse: {e}", archive.display())); + } + } + Err(format!("{} carries no {MANIFEST_NAME}", archive.display())) +} + +/// The parent of the working directory: on the server the trees sit under +/// `$HOME`, the deploy directory the process runs from inside it. +fn default_root() -> PathBuf { + let cwd = match std::env::current_dir() { + Ok(cwd) => cwd, + Err(e) => { + eprintln!("im: cannot read the working directory: {e}"); + std::process::exit(2); + } + }; + match cwd.parent() { + Some(parent) => parent.to_path_buf(), + None => { + eprintln!("im: no family root above {}", cwd.display()); + eprintln!("usage: pass --root DIR"); + std::process::exit(2); + } + } +} + +/// The archive's default name: stamped, in the working directory. +fn archive_name() -> PathBuf { + const STAMP: &[time::format_description::BorrowedFormatItem<'static>] = + time::macros::format_description!( + "im-pack-[year][month][day]-[hour][minute][second].tar.gz" + ); + PathBuf::from( + time::OffsetDateTime::now_utc() + .format(STAMP) + .unwrap_or_else(|_| "im-pack.tar.gz".into()), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A throwaway tree under the OS temp dir, gone with the test. + struct TempDir(PathBuf); + + impl TempDir { + fn new(label: &str) -> TempDir { + let path = std::env::temp_dir() + .join(format!("im-pack-{label}-{}", ulid::Ulid::generate())); + fs::create_dir_all(&path).unwrap(); + TempDir(path) + } + } + + impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + fn write(path: &Path, bytes: &[u8]) { + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, bytes).unwrap(); + } + + fn mode_of(path: &Path) -> u32 { + fs::metadata(path).unwrap().permissions().mode() & 0o777 + } + + /// The data-driven gate: the keys are whatever the caller hands over — + /// here `im` and a fixture sibling `xy` that is not in/iz — and the + /// roundtrip treats them identically. Also the standing refusals: the + /// archive lands 0600, secrets restore 0600, and a second unpack + /// stops at the existing database unless --force names the overwrite. + #[test] + fn roundtrip_im_and_xy() { + let source = TempDir::new("src"); + // im: the full tree — database trio, signing key, config, storage. + write(&source.0.join("im/im.db"), b"im-db"); + write(&source.0.join("im/im.db-wal"), b"im-wal"); + write(&source.0.join("im/im.db-shm"), b"im-shm"); + write(&source.0.join("im/im.key"), b"im-key"); + write(&source.0.join("im/config/im.toml"), b"listen = \"127.0.0.1:7650\"\n"); + write(&source.0.join("im/storage/a/blob"), b"im-blob"); + // xy: a bare sibling — database and config only. `zz` has no tree + // at all; its pack is a stderr line, not a failure. + write(&source.0.join("xy/xy.db"), b"xy-db"); + write(&source.0.join("xy/config/xy.toml"), b"listen = \"127.0.0.1:8000\"\n"); + + let keys = ["im".to_string(), "xy".to_string(), "zz".to_string()]; + let out = source.0.join("pack.tar.gz"); + pack(&source.0, &keys, &out).expect("pack succeeds"); + assert!(out.is_file()); + assert_eq!(mode_of(&out), 0o600, "the archive lands 0600"); + + let destination = TempDir::new("dest"); + unpack(&out, &destination.0, false).expect("unpack into an empty root"); + for (relative, bytes) in [ + ("im/im.db", &b"im-db"[..]), + ("im/im.db-wal", b"im-wal"), + ("im/im.db-shm", b"im-shm"), + ("im/im.key", b"im-key"), + ("im/config/im.toml", b"listen = \"127.0.0.1:7650\"\n"), + ("im/storage/a/blob", b"im-blob"), + ("xy/xy.db", b"xy-db"), + ("xy/config/xy.toml", b"listen = \"127.0.0.1:8000\"\n"), + ] { + assert_eq!( + fs::read(destination.0.join(relative)).unwrap(), + bytes, + "{relative} must roundtrip" + ); + } + for secret in ["im/im.key", "im/config/im.toml", "xy/config/xy.toml"] { + assert_eq!( + mode_of(&destination.0.join(secret)), + 0o600, + "{secret} must land 0600" + ); + } + + // Without --force, a target database stops the restore before + // anything moves. + let problem = unpack(&out, &destination.0, false) + .expect_err("an existing database must refuse the unpack"); + assert!(problem.contains("--force"), "the refusal names the way out: {problem}"); + assert_eq!( + fs::read(destination.0.join("im/im.db")).unwrap(), + b"im-db", + "the refused unpack left the tree alone" + ); + unpack(&out, &destination.0, true).expect("--force unpacks over it"); + assert_eq!(fs::read(destination.0.join("im/im.db")).unwrap(), b"im-db"); + } + + /// A member whose name climbs out of the restore root is refused, not + /// extracted — a tampered archive cannot write past the root. The + /// tar library refuses to *write* such a name, so the hostile archive + /// is ustar bytes laid by hand, the way an attacker would. + #[test] + fn unpack_refuses_escaping_names() { + use std::io::Write as _; + + let source = TempDir::new("evil-src"); + let archive = source.0.join("evil.tar.gz"); + + let mut tar = Vec::new(); + raw_member( + &mut tar, + MANIFEST_NAME, + br#"{"version":1,"packed_at":"now","services":[{"key":"xy","files":[]}]}"#, + ); + raw_member(&mut tar, "../escape", b"gotcha"); + tar.extend_from_slice(&[0u8; 1024]); + let mut gz = flate2::write::GzEncoder::new( + File::create(&archive).unwrap(), + flate2::Compression::default(), + ); + gz.write_all(&tar).unwrap(); + gz.finish().unwrap(); + + let destination = TempDir::new("evil-dest"); + let problem = unpack(&archive, &destination.0, false) + .expect_err("an escaping member must refuse the unpack"); + assert!(problem.contains("safe relative"), "{problem}"); + assert!( + !destination.0.parent().unwrap().join("escape").exists(), + "nothing may land outside the root" + ); + } + + /// One raw ustar member: header block, body, padding — no library + /// path validation, so a hostile name travels through untouched. + fn raw_member(tar: &mut Vec, name: &str, body: &[u8]) { + let mut header = [0u8; 512]; + header[..name.len()].copy_from_slice(name.as_bytes()); + header[124..136].copy_from_slice(format!("{:011o}\0", body.len()).as_bytes()); + header[136..148].copy_from_slice(b"00000000000\0"); + header[148..156].copy_from_slice(b" "); + header[156] = b'0'; + header[257..263].copy_from_slice(b"ustar\0"); + header[263..265].copy_from_slice(b"00"); + let sum: u32 = header.iter().map(|byte| u32::from(*byte)).sum(); + header[148..156].copy_from_slice(format!("{sum:06o}\0 ").as_bytes()); + tar.extend_from_slice(&header); + tar.extend_from_slice(body); + tar.extend(std::iter::repeat_n(0u8, (512 - body.len() % 512) % 512)); + } + + /// An archive whose manifest names a shape this binary does not know + /// refuses itself instead of guessing. + #[test] + fn unpack_refuses_a_future_manifest() { + let source = TempDir::new("future-src"); + let archive = source.0.join("future.tar.gz"); + let file = File::create(&archive).unwrap(); + let mut tar = tar::Builder::new(flate2::write::GzEncoder::new( + file, + flate2::Compression::default(), + )); + let manifest = br#"{"version":99,"packed_at":"tomorrow","services":[]}"#; + let mut header = tar::Header::new_gnu(); + header.set_size(manifest.len() as u64); + header.set_cksum(); + tar.append_data(&mut header, MANIFEST_NAME, &manifest[..]).unwrap(); + tar.into_inner().unwrap().finish().unwrap(); + + let destination = TempDir::new("future-dest"); + let problem = unpack(&archive, &destination.0, false) + .expect_err("an unknown manifest version must refuse"); + assert!(problem.contains("version"), "{problem}"); + } +} diff --git a/style/main.scss b/style/main.scss index e9b366e..46483be 100644 --- a/style/main.scss +++ b/style/main.scss @@ -1039,6 +1039,21 @@ body:has(.log-list) { .mono { font-family: var(--font-mono); } .muted { color: var(--muted); } +// The admin Health section's per-service state dot: green while the +// service's /healthz answers ok, muted when it does not. The green is +// iz's connection card's — the same light across the family's panels. +.health-dot { + display: inline-block; + width: 0.55rem; + height: 0.55rem; + border-radius: 50%; + margin-right: 0.4rem; + vertical-align: baseline; + + &.health-on { background: #2e9e5b; } + &.health-off { background: var(--muted); } +} + .actions { display: flex; flex-wrap: wrap;