/healthz names the build, the admin health tab reads the family, and pack/unpack carries every registered tree.
Browse files at this commit30917a3f4a1a841bf015126a7e22c287d3232ccfParent: 25140f310 changed files +942 -13
- .github/workflows/main.yml +31 -11
- Cargo.lock +34 -0
- crates/im-web/Cargo.toml +5 -0
- crates/im-web/assets/main.css +15 -0
- crates/im-web/build.rs +9 -0
- crates/im-web/src/admin.rs +182 -0
- crates/im-web/src/i18n.rs +12 -0
- crates/im-web/src/main.rs +65 -2
- crates/im-web/src/pack.rs +574 -0
- style/main.scss +15 -0
.github/workflows/main.ymlmodified+31 -11
| @@ -28,6 +28,10 @@ env: | |||
| 28 | # moves the path with it — a baked-in absolute path once kept pointing at | 28 | # moves the path with it — a baked-in absolute path once kept pointing at |
| 29 | # the previous user's home and failed the deploy on permissions. | 29 | # the previous user's home and failed the deploy on permissions. |
| 30 | DEPLOY_SUBDIR: im | 30 | DEPLOY_SUBDIR: im |
| 31 | + # Baked into the binary by build.rs and asserted against after the | ||
| 32 | + # deploy restart: a /healthz answered by a stale process from an old | ||
| 33 | + # deploy now fails and rolls back instead of reporting green. | ||
| 34 | + IM_BUILD_SHA: ${{ github.sha }} | ||
| 31 | 35 | ||
| 32 | jobs: | 36 | jobs: |
| 33 | deploy: | 37 | deploy: |
| @@ -143,10 +147,11 @@ jobs: | |||
| 143 | 147 | ||
| 144 | # bash -s for the same reason as above: the login shell is not | 148 | # bash -s for the same reason as above: the login shell is not |
| 145 | # bash and must never see this script. | 149 | # bash and must never see this script. |
| 146 | - ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR' '$SERVICE'" <<'REMOTE' | 150 | + ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR' '$SERVICE' '$GITHUB_SHA'" <<'REMOTE' |
| 147 | set -euo pipefail | 151 | set -euo pipefail |
| 148 | deploy_path=$HOME/$1 | 152 | deploy_path=$HOME/$1 |
| 149 | service=$2 | 153 | service=$2 |
| 154 | + expected="ok $3" | ||
| 150 | export XDG_RUNTIME_DIR=/run/user/$(id -u) | 155 | export XDG_RUNTIME_DIR=/run/user/$(id -u) |
| 151 | # Read before anything moves: a config the health check cannot | 156 | # Read before anything moves: a config the health check cannot |
| 152 | # read is a failure to stop on, not one to roll back from. | 157 | # read is a failure to stop on, not one to roll back from. |
| @@ -155,6 +160,12 @@ jobs: | |||
| 155 | echo "no listen address in $deploy_path/config/im.toml" >&2 | 160 | echo "no listen address in $deploy_path/config/im.toml" >&2 |
| 156 | exit 1 | 161 | exit 1 |
| 157 | fi | 162 | fi |
| 163 | + # The config directory carries secrets: the toml and any keys | ||
| 164 | + # files are held to 0600, and the editor's stray secret-bearing | ||
| 165 | + # backups go away — every deploy, the same way. | ||
| 166 | + chmod 0600 -- "$deploy_path/config/"*.toml 2>/dev/null || true | ||
| 167 | + chmod 0600 -- "$deploy_path/config/"*.keys 2>/dev/null || true | ||
| 168 | + find "$deploy_path/config" -maxdepth 1 -type f \( -name '*.bak*' -o -name '*.pre-*' \) -delete | ||
| 158 | chmod +x -- "$deploy_path/current.new/im-web" | 169 | chmod +x -- "$deploy_path/current.new/im-web" |
| 159 | rm -rf -- "$deploy_path/current.previous" | 170 | rm -rf -- "$deploy_path/current.previous" |
| 160 | if [ -e "$deploy_path/current" ]; then | 171 | if [ -e "$deploy_path/current" ]; then |
| @@ -169,20 +180,29 @@ jobs: | |||
| 169 | systemctl --user daemon-reload | 180 | systemctl --user daemon-reload |
| 170 | systemctl --user enable -- "$service" | 181 | systemctl --user enable -- "$service" |
| 171 | systemctl --user restart "$service" | 182 | systemctl --user restart "$service" |
| 172 | - # The unit is Type=simple, so a restart returns before the process | 183 | + # The unit is Type=simple, so a restart returns before the new |
| 173 | - # has bound its port. Wait for the health route rather than a clock. | 184 | + # process has bound its port — and before an old one has let go |
| 185 | + # of it. Wait for the health route rather than a clock, and | ||
| 186 | + # check the answer names this commit: a stale process can still | ||
| 187 | + # answer, and did once on a sibling deploy. | ||
| 188 | + rollback() { | ||
| 189 | + rm -rf -- "$deploy_path/current" | ||
| 190 | + mv -- "$deploy_path/current.previous" "$deploy_path/current" | ||
| 191 | + systemctl --user restart "$service" | ||
| 192 | + } | ||
| 174 | for _ in $(seq 1 30); do | 193 | for _ in $(seq 1 30); do |
| 175 | - if curl -fsS "http://$listen/healthz" >/dev/null 2>&1; then | 194 | + served=$(curl -fsS "http://$listen/healthz" 2>/dev/null) || { sleep 1; continue; } |
| 176 | - echo 'im is up' | 195 | + if [ "$served" != "$expected" ]; then |
| 177 | - rm -rf -- "$deploy_path/current.previous" | 196 | + echo "/healthz answered '$served', wanted '$expected'; rolling back" >&2 |
| 178 | - exit 0 | 197 | + rollback |
| 198 | + exit 1 | ||
| 179 | fi | 199 | fi |
| 180 | - sleep 1 | 200 | + echo 'im is up' |
| 201 | + rm -rf -- "$deploy_path/current.previous" | ||
| 202 | + exit 0 | ||
| 181 | done | 203 | done |
| 182 | echo 'im did not answer /healthz; rolling back' >&2 | 204 | echo 'im did not answer /healthz; rolling back' >&2 |
| 183 | - rm -rf -- "$deploy_path/current" | 205 | + rollback |
| 184 | - mv -- "$deploy_path/current.previous" "$deploy_path/current" | ||
| 185 | - systemctl --user restart "$service" | ||
| 186 | exit 1 | 206 | exit 1 |
| 187 | REMOTE | 207 | REMOTE |
| 188 | 208 | ||
Cargo.lockmodified+34 -0
| @@ -1139,6 +1139,16 @@ version = "2.5.0" | |||
| 1139 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1139 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1140 | checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" | 1140 | checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" |
| 1141 | 1141 | ||
| 1142 | +[[package]] | ||
| 1143 | +name = "filetime" | ||
| 1144 | +version = "0.2.29" | ||
| 1145 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1146 | +checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" | ||
| 1147 | +dependencies = [ | ||
| 1148 | + "cfg-if", | ||
| 1149 | + "libc", | ||
| 1150 | +] | ||
| 1151 | + | ||
| 1142 | [[package]] | 1152 | [[package]] |
| 1143 | name = "find-msvc-tools" | 1153 | name = "find-msvc-tools" |
| 1144 | version = "0.1.12" | 1154 | version = "0.1.12" |
| @@ -1882,6 +1892,7 @@ version = "0.1.0" | |||
| 1882 | dependencies = [ | 1892 | dependencies = [ |
| 1883 | "base64 0.23.1", | 1893 | "base64 0.23.1", |
| 1884 | "data-encoding", | 1894 | "data-encoding", |
| 1895 | + "flate2", | ||
| 1885 | "futures-util", | 1896 | "futures-util", |
| 1886 | "grass", | 1897 | "grass", |
| 1887 | "http", | 1898 | "http", |
| @@ -1889,8 +1900,10 @@ dependencies = [ | |||
| 1889 | "lettre", | 1900 | "lettre", |
| 1890 | "parking_lot", | 1901 | "parking_lot", |
| 1891 | "qrcode", | 1902 | "qrcode", |
| 1903 | + "reqwest", | ||
| 1892 | "serde", | 1904 | "serde", |
| 1893 | "serde_json", | 1905 | "serde_json", |
| 1906 | + "tar", | ||
| 1894 | "thiserror", | 1907 | "thiserror", |
| 1895 | "time", | 1908 | "time", |
| 1896 | "tokio", | 1909 | "tokio", |
| @@ -3884,6 +3897,17 @@ version = "1.0.1" | |||
| 3884 | source = "registry+https://github.com/rust-lang/crates.io-index" | 3897 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 3885 | checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" | 3898 | checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" |
| 3886 | 3899 | ||
| 3900 | +[[package]] | ||
| 3901 | +name = "tar" | ||
| 3902 | +version = "0.4.46" | ||
| 3903 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3904 | +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" | ||
| 3905 | +dependencies = [ | ||
| 3906 | + "filetime", | ||
| 3907 | + "libc", | ||
| 3908 | + "xattr", | ||
| 3909 | +] | ||
| 3910 | + | ||
| 3887 | [[package]] | 3911 | [[package]] |
| 3888 | name = "tempfile" | 3912 | name = "tempfile" |
| 3889 | version = "3.27.0" | 3913 | version = "3.27.0" |
| @@ -5287,6 +5311,16 @@ dependencies = [ | |||
| 5287 | "tap", | 5311 | "tap", |
| 5288 | ] | 5312 | ] |
| 5289 | 5313 | ||
| 5314 | +[[package]] | ||
| 5315 | +name = "xattr" | ||
| 5316 | +version = "1.6.1" | ||
| 5317 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 5318 | +checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" | ||
| 5319 | +dependencies = [ | ||
| 5320 | + "libc", | ||
| 5321 | + "rustix 1.1.4", | ||
| 5322 | +] | ||
| 5323 | + | ||
| 5290 | [[package]] | 5324 | [[package]] |
| 5291 | name = "yoke" | 5325 | name = "yoke" |
| 5292 | version = "0.8.3" | 5326 | version = "0.8.3" |
crates/im-web/Cargo.tomlmodified+5 -0
| @@ -32,6 +32,11 @@ ulid.workspace = true | |||
| 32 | base64.workspace = true | 32 | base64.workspace = true |
| 33 | toml.workspace = true | 33 | toml.workspace = true |
| 34 | data-encoding = "2.11.1" | 34 | data-encoding = "2.11.1" |
| 35 | +# The admin health panel probes each service's `/healthz` where it stands. | ||
| 36 | +reqwest = { version = "0.13.5", default-features = false, features = ["rustls"] } | ||
| 37 | +# `pack` / `unpack`: the family's backup archive, one gzipped tar. | ||
| 38 | +tar = "0.4" | ||
| 39 | +flate2 = "1" | ||
| 35 | qrcode = { version = "0.14.1", default-features = false, features = ["svg"] } | 40 | qrcode = { version = "0.14.1", default-features = false, features = ["svg"] } |
| 36 | # TLS through rustls with the ring provider: no OpenSSL on the deployment box, | 41 | # TLS through rustls with the ring provider: no OpenSSL on the deployment box, |
| 37 | # and no system certificate store to be missing inside a container. | 42 | # and no system certificate store to be missing inside a container. |
crates/im-web/assets/main.cssmodified+15 -0
| @@ -1000,6 +1000,21 @@ body:has(.log-list) .admin-card:has(.log-list) { | |||
| 1000 | color: var(--muted); | 1000 | color: var(--muted); |
| 1001 | } | 1001 | } |
| 1002 | 1002 | ||
| 1003 | +.health-dot { | ||
| 1004 | + display: inline-block; | ||
| 1005 | + width: 0.55rem; | ||
| 1006 | + height: 0.55rem; | ||
| 1007 | + border-radius: 50%; | ||
| 1008 | + margin-right: 0.4rem; | ||
| 1009 | + vertical-align: baseline; | ||
| 1010 | +} | ||
| 1011 | +.health-dot.health-on { | ||
| 1012 | + background: #2e9e5b; | ||
| 1013 | +} | ||
| 1014 | +.health-dot.health-off { | ||
| 1015 | + background: var(--muted); | ||
| 1016 | +} | ||
| 1017 | + | ||
| 1003 | .actions { | 1018 | .actions { |
| 1004 | display: flex; | 1019 | display: flex; |
| 1005 | flex-wrap: wrap; | 1020 | flex-wrap: wrap; |
crates/im-web/build.rsmodified+9 -0
| @@ -15,4 +15,13 @@ fn main() { | |||
| 15 | let out_dir = format!("{manifest_dir}/assets"); | 15 | let out_dir = format!("{manifest_dir}/assets"); |
| 16 | std::fs::create_dir_all(&out_dir).expect("failed to create assets/"); | 16 | std::fs::create_dir_all(&out_dir).expect("failed to create assets/"); |
| 17 | std::fs::write(format!("{out_dir}/main.css"), &css).expect("failed to write assets/main.css"); | 17 | std::fs::write(format!("{out_dir}/main.css"), &css).expect("failed to write assets/main.css"); |
| 18 | + | ||
| 19 | + // The commit this binary was built from, served by `/healthz` and | ||
| 20 | + // asserted against after the deploy restart, so a stale process | ||
| 21 | + // holding the port cannot pass for this deploy. "dev" locally, where | ||
| 22 | + // nothing asserts it. The rerun-if-env-changed line is load-bearing: | ||
| 23 | + // without it a rust-cache hit would ship last deploy's sha. | ||
| 24 | + let sha = std::env::var("IM_BUILD_SHA").unwrap_or_else(|_| "dev".into()); | ||
| 25 | + println!("cargo:rustc-env=IM_BUILD_SHA={sha}"); | ||
| 26 | + println!("cargo:rerun-if-env-changed=IM_BUILD_SHA"); | ||
| 18 | } | 27 | } |
crates/im-web/src/admin.rsmodified+182 -0
| @@ -149,6 +149,7 @@ async fn admin_page(cx: &Cx) -> Result<Response> { | |||
| 149 | ("message", t(lang, Key::NavMessage)), | 149 | ("message", t(lang, Key::NavMessage)), |
| 150 | ("settings", t(lang, Key::NavSettings)), | 150 | ("settings", t(lang, Key::NavSettings)), |
| 151 | ("logs", t(lang, Key::NavLogs)), | 151 | ("logs", t(lang, Key::NavLogs)), |
| 152 | + ("health", t(lang, Key::NavHealth)), | ||
| 152 | ] | 153 | ] |
| 153 | .into_iter() | 154 | .into_iter() |
| 154 | .map(|(id, label)| { | 155 | .map(|(id, label)| { |
| @@ -165,6 +166,7 @@ async fn admin_page(cx: &Cx) -> Result<Response> { | |||
| 165 | "message" => message_section(cx, lang).await?, | 166 | "message" => message_section(cx, lang).await?, |
| 166 | "settings" => settings_section(cx, lang).await?, | 167 | "settings" => settings_section(cx, lang).await?, |
| 167 | "logs" => logs_section(cx, lang).await?, | 168 | "logs" => logs_section(cx, lang).await?, |
| 169 | + "health" => health_section(cx, lang).await?, | ||
| 168 | // `section=clients` lands here too — the sections are one table | 170 | // `section=clients` lands here too — the sections are one table |
| 169 | // now, and the old address keeps working. | 171 | // now, and the old address keeps working. |
| 170 | "services" | "clients" => services_section(cx, shown, lang).await?, | 172 | "services" | "clients" => services_section(cx, shown, lang).await?, |
| @@ -1431,6 +1433,95 @@ async fn logs_section(cx: &Cx, lang: i18n::Lang) -> Result<String, topcoat::Erro | |||
| 1431 | )) | 1433 | )) |
| 1432 | .map(|card| card + LOG_FIT_SCRIPT) | 1434 | .map(|card| card + LOG_FIT_SCRIPT) |
| 1433 | } | 1435 | } |
| 1436 | + | ||
| 1437 | +/// The read-only family health panel. One row per services-table entry — | ||
| 1438 | +/// self included, im's own row lives on the same table — probed where it | ||
| 1439 | +/// stands: `GET {url}/healthz`, no credentials, two seconds to answer. | ||
| 1440 | +/// A fourth registered service appears here on its own; nothing on this | ||
| 1441 | +/// section takes input, and the live morph brings the next reading the | ||
| 1442 | +/// way it refreshes every other section. | ||
| 1443 | +async fn health_section(cx: &Cx, lang: i18n::Lang) -> Result<String, topcoat::Error> { | ||
| 1444 | + let services = im_core::services::list(&app(cx).store).await?; | ||
| 1445 | + // Every probe at once: a family member that is down costs its two | ||
| 1446 | + // seconds, not two seconds each. | ||
| 1447 | + let http = reqwest::Client::new(); | ||
| 1448 | + let mut probes = Vec::new(); | ||
| 1449 | + for service in &services { | ||
| 1450 | + let http = http.clone(); | ||
| 1451 | + let url = format!("{}/healthz", service.url.trim_end_matches('/')); | ||
| 1452 | + probes.push(tokio::spawn(async move { probe_healthz(&http, &url).await })); | ||
| 1453 | + } | ||
| 1454 | + | ||
| 1455 | + let mut rows = String::new(); | ||
| 1456 | + for (service, probe) in services.iter().zip(probes) { | ||
| 1457 | + let key = escape(&service.key); | ||
| 1458 | + let name = escape(&service.name); | ||
| 1459 | + let url = escape(&service.url); | ||
| 1460 | + let state = match probe.await.unwrap_or(Probe::Down) { | ||
| 1461 | + Probe::Up { body, ms } => format!( | ||
| 1462 | + r#"<span class="health-dot health-on"></span>{} <span class="muted">· {ms} ms</span>"#, | ||
| 1463 | + escape(&body) | ||
| 1464 | + ), | ||
| 1465 | + Probe::Down => format!( | ||
| 1466 | + r#"<span class="health-dot health-off"></span><span class="muted">{}</span>"#, | ||
| 1467 | + t(lang, Key::HealthUnreachable), | ||
| 1468 | + ), | ||
| 1469 | + }; | ||
| 1470 | + rows.push_str(&format!( | ||
| 1471 | + r#"<tr><td class="mono">{key}</td><td>{name}</td><td class="mono"><a href="{url}" target="_blank" rel="noopener noreferrer">{url}</a></td><td>{state}</td></tr>"#, | ||
| 1472 | + )); | ||
| 1473 | + } | ||
| 1474 | + Ok(format!( | ||
| 1475 | + r#"<div class="admin-card"> | ||
| 1476 | + <div class="auth-title">{title}</div> | ||
| 1477 | + <div class="admin-table-wrap"> | ||
| 1478 | + <table class="admin-table"> | ||
| 1479 | + <thead><tr><th>{key_label}</th><th>{name_label}</th><th>{url_label}</th><th>{state_label}</th></tr></thead> | ||
| 1480 | + <tbody>{rows}</tbody> | ||
| 1481 | + </table> | ||
| 1482 | + </div> | ||
| 1483 | +</div>"#, | ||
| 1484 | + title = t(lang, Key::HealthTitle), | ||
| 1485 | + key_label = t(lang, Key::ServiceKeyLabel), | ||
| 1486 | + name_label = t(lang, Key::NameCol), | ||
| 1487 | + url_label = t(lang, Key::AddressLabel), | ||
| 1488 | + state_label = t(lang, Key::HealthStateCol), | ||
| 1489 | + )) | ||
| 1490 | +} | ||
| 1491 | + | ||
| 1492 | +/// One `/healthz` reading. `Up` carries the body — the deploy contract's | ||
| 1493 | +/// `ok <build sha>` — and the answer's latency; everything else, refused | ||
| 1494 | +/// or wrong status or a body that does not begin ok or the two-second | ||
| 1495 | +/// ceiling, is `Down`. | ||
| 1496 | +enum Probe { | ||
| 1497 | + Up { body: String, ms: u128 }, | ||
| 1498 | + Down, | ||
| 1499 | +} | ||
| 1500 | + | ||
| 1501 | +async fn probe_healthz(http: &reqwest::Client, url: &str) -> Probe { | ||
| 1502 | + let started = std::time::Instant::now(); | ||
| 1503 | + let Ok(answer) = http | ||
| 1504 | + .get(url) | ||
| 1505 | + .timeout(std::time::Duration::from_secs(2)) | ||
| 1506 | + .send() | ||
| 1507 | + .await | ||
| 1508 | + else { | ||
| 1509 | + return Probe::Down; | ||
| 1510 | + }; | ||
| 1511 | + if !answer.status().is_success() { | ||
| 1512 | + return Probe::Down; | ||
| 1513 | + } | ||
| 1514 | + let body = answer.text().await.unwrap_or_default(); | ||
| 1515 | + let body = body.trim(); | ||
| 1516 | + if body.starts_with("ok") { | ||
| 1517 | + Probe::Up { | ||
| 1518 | + body: body.chars().take(64).collect(), | ||
| 1519 | + ms: started.elapsed().as_millis(), | ||
| 1520 | + } | ||
| 1521 | + } else { | ||
| 1522 | + Probe::Down | ||
| 1523 | + } | ||
| 1524 | +} | ||
| 1434 | /// Fits the log's page size to the browser's own viewport: measured against | 1525 | /// Fits the log's page size to the browser's own viewport: measured against |
| 1435 | /// the first rendered row, never against a guess at the row height. A fit | 1526 | /// the first rendered row, never against a guess at the row height. A fit |
| 1436 | /// that would change the page size reloads once through a fresh | 1527 | /// that would change the page size reloads once through a fresh |
| @@ -2507,4 +2598,95 @@ mod tests { | |||
| 2507 | ); | 2598 | ); |
| 2508 | } | 2599 | } |
| 2509 | } | 2600 | } |
| 2601 | + | ||
| 2602 | + /// The deploy asserts this body after the restart — the answer must | ||
| 2603 | + /// carry the baked build sha, `dev` in a plain build. | ||
| 2604 | + #[tokio::test] | ||
| 2605 | + async fn healthz_answers_the_baked_sha() { | ||
| 2606 | + let setup = setup().await; | ||
| 2607 | + let (status, _, body) = get_full(&setup.router, "/healthz", None).await; | ||
| 2608 | + assert_eq!(status, StatusCode::OK); | ||
| 2609 | + assert!( | ||
| 2610 | + body.starts_with("ok "), | ||
| 2611 | + "healthz must answer `ok <build sha>`, got {body:?}" | ||
| 2612 | + ); | ||
| 2613 | + } | ||
| 2614 | + | ||
| 2615 | + /// The probe reads a service answering the deploy body as Up with the | ||
| 2616 | + /// body carried, and a service with nobody home as Down — not a hang, | ||
| 2617 | + /// not an error. | ||
| 2618 | + #[tokio::test] | ||
| 2619 | + async fn health_probe_reads_ok_and_refuses_the_rest() { | ||
| 2620 | + use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; | ||
| 2621 | + | ||
| 2622 | + let http = reqwest::Client::new(); | ||
| 2623 | + | ||
| 2624 | + // A stand-in service answering the deploy body. | ||
| 2625 | + use super::{Probe, probe_healthz}; | ||
| 2626 | + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); | ||
| 2627 | + | ||
| 2628 | + let addr = listener.local_addr().unwrap(); | ||
| 2629 | + let talker = tokio::spawn(async move { | ||
| 2630 | + let (mut sock, _) = listener.accept().await.unwrap(); | ||
| 2631 | + let mut buf = [0u8; 1024]; | ||
| 2632 | + let _ = sock.read(&mut buf).await; | ||
| 2633 | + sock.write_all(b"HTTP/1.1 200 OK\r\ncontent-length: 6\r\n\r\nok dev") | ||
| 2634 | + .await | ||
| 2635 | + .unwrap(); | ||
| 2636 | + }); | ||
| 2637 | + let probe = probe_healthz(&http, &format!("http://{addr}/healthz")).await; | ||
| 2638 | + talker.await.unwrap(); | ||
| 2639 | + let Probe::Up { body, .. } = probe else { | ||
| 2640 | + panic!("a service answering `ok dev` must read Up"); | ||
| 2641 | + }; | ||
| 2642 | + assert_eq!(body, "ok dev"); | ||
| 2643 | + | ||
| 2644 | + // Nobody home: refused connection, Down. | ||
| 2645 | + let dark = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); | ||
| 2646 | + let addr = dark.local_addr().unwrap(); | ||
| 2647 | + drop(dark); | ||
| 2648 | + let probe = probe_healthz(&http, &format!("http://{addr}/healthz")).await; | ||
| 2649 | + assert!(matches!(probe, Probe::Down), "a dark port must read Down"); | ||
| 2650 | + } | ||
| 2651 | + | ||
| 2652 | + /// The section is admin-only and, a bundle permitting, renders the | ||
| 2653 | + /// health table with its nav slot. | ||
| 2654 | + #[tokio::test] | ||
| 2655 | + async fn health_section_is_admin_only_and_renders() { | ||
| 2656 | + let setup = setup().await; | ||
| 2657 | + // A family row to render: a port nobody listens on refuses the | ||
| 2658 | + // probe instantly, so the row reads Down without waiting it out. | ||
| 2659 | + // A fixture key, not a sibling's — the panel renders whatever the | ||
| 2660 | + // table holds. | ||
| 2661 | + let dark = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); | ||
| 2662 | + let dead_url = format!("http://{}", dark.local_addr().unwrap()); | ||
| 2663 | + drop(dark); | ||
| 2664 | + im_core::services::add( | ||
| 2665 | + &setup.store, | ||
| 2666 | + &im_core::services::Service { | ||
| 2667 | + key: "xy".into(), | ||
| 2668 | + name: "Fixture".into(), | ||
| 2669 | + url: dead_url, | ||
| 2670 | + owner: None, | ||
| 2671 | + client_id: None, | ||
| 2672 | + storage_limit_bytes: None, | ||
| 2673 | + }, | ||
| 2674 | + ) | ||
| 2675 | + .await | ||
| 2676 | + .unwrap(); | ||
| 2677 | + let (status, location, _) = | ||
| 2678 | + get_full(&setup.router, "/admin?section=health", Some(&setup.plain_cookie)).await; | ||
| 2679 | + assert_eq!(status, StatusCode::SEE_OTHER); | ||
| 2680 | + assert_eq!(location.as_deref(), Some("/")); | ||
| 2681 | + if setup.assets { | ||
| 2682 | + let (status, _, body) = | ||
| 2683 | + get_full(&setup.router, "/admin?section=health", Some(&setup.admin_cookie)).await; | ||
| 2684 | + assert_eq!(status, StatusCode::OK); | ||
| 2685 | + assert!(body.contains("Family health"), "{body}"); | ||
| 2686 | + assert!(body.contains("/admin?section=health"), "the nav carries the section: {body}"); | ||
| 2687 | + assert!(body.contains("health-dot"), "{body}"); | ||
| 2688 | + assert!(body.contains(">xy</td>"), "the fixture row renders: {body}"); | ||
| 2689 | + assert!(body.contains("Unreachable"), "the dark row reads Down: {body}"); | ||
| 2690 | + } | ||
| 2691 | + } | ||
| 2510 | } | 2692 | } |
crates/im-web/src/i18n.rsmodified+12 -0
| @@ -172,6 +172,10 @@ pub enum Key { | |||
| 172 | NavLogs, | 172 | NavLogs, |
| 173 | NavMessage, | 173 | NavMessage, |
| 174 | NavServices, | 174 | NavServices, |
| 175 | + NavHealth, | ||
| 176 | + HealthTitle, | ||
| 177 | + HealthStateCol, | ||
| 178 | + HealthUnreachable, | ||
| 175 | OkInvited, | 179 | OkInvited, |
| 176 | OkRevoked, | 180 | OkRevoked, |
| 177 | OkDisabled, | 181 | OkDisabled, |
| @@ -573,6 +577,14 @@ pub fn t(lang: Lang, key: Key) -> &'static str { | |||
| 573 | (NavMessage, Tr) => "Mesaj", | 577 | (NavMessage, Tr) => "Mesaj", |
| 574 | (NavServices, En) => "Services", | 578 | (NavServices, En) => "Services", |
| 575 | (NavServices, Tr) => "Hizmetler", | 579 | (NavServices, Tr) => "Hizmetler", |
| 580 | + (NavHealth, En) => "Health", | ||
| 581 | + (NavHealth, Tr) => "Sağlık", | ||
| 582 | + (HealthTitle, En) => "Family health", | ||
| 583 | + (HealthTitle, Tr) => "Aile sağlığı", | ||
| 584 | + (HealthStateCol, En) => "State", | ||
| 585 | + (HealthStateCol, Tr) => "Durum", | ||
| 586 | + (HealthUnreachable, En) => "Unreachable", | ||
| 587 | + (HealthUnreachable, Tr) => "Erişilemiyor", | ||
| 576 | (OkInvited, En) => "Invite created.", | 588 | (OkInvited, En) => "Invite created.", |
| 577 | (OkInvited, Tr) => "Davet oluşturuldu.", | 589 | (OkInvited, Tr) => "Davet oluşturuldu.", |
| 578 | (OkEmailChanged, En) => "Email changed.", | 590 | (OkEmailChanged, En) => "Email changed.", |
crates/im-web/src/main.rsmodified+65 -2
| @@ -20,6 +20,7 @@ mod layout; | |||
| 20 | mod live; | 20 | mod live; |
| 21 | mod mailer; | 21 | mod mailer; |
| 22 | mod oidc; | 22 | mod oidc; |
| 23 | +mod pack; | ||
| 23 | mod pages; | 24 | mod pages; |
| 24 | mod people; | 25 | mod people; |
| 25 | mod photo; | 26 | mod photo; |
| @@ -29,7 +30,10 @@ use config::Config; | |||
| 29 | 30 | ||
| 30 | #[route(GET "/healthz")] | 31 | #[route(GET "/healthz")] |
| 31 | async fn healthz() -> Result<&'static str> { | 32 | async fn healthz() -> Result<&'static str> { |
| 32 | - Ok("ok") | 33 | + // The build's commit, baked by build.rs — the deploy asserts the exact |
| 34 | + // body after the restart, so a stale process holding the port cannot | ||
| 35 | + // pass for this one. | ||
| 36 | + Ok(concat!("ok ", env!("IM_BUILD_SHA"))) | ||
| 33 | } | 37 | } |
| 34 | 38 | ||
| 35 | #[tokio::main] | 39 | #[tokio::main] |
| @@ -111,9 +115,68 @@ async fn main() { | |||
| 111 | }; | 115 | }; |
| 112 | revoke_client(config, id).await; | 116 | revoke_client(config, id).await; |
| 113 | } | 117 | } |
| 118 | + Some("pack") => { | ||
| 119 | + let mut root = None; | ||
| 120 | + let mut out = None; | ||
| 121 | + let mut rest = args[2..].iter(); | ||
| 122 | + while let Some(arg) = rest.next() { | ||
| 123 | + match arg.as_str() { | ||
| 124 | + "--root" => match rest.next() { | ||
| 125 | + Some(value) => root = Some(value.clone()), | ||
| 126 | + None => { | ||
| 127 | + eprintln!("usage: im-web pack [--root DIR] [--out FILE]"); | ||
| 128 | + eprintln!("im: --root needs a directory"); | ||
| 129 | + std::process::exit(2); | ||
| 130 | + } | ||
| 131 | + }, | ||
| 132 | + "--out" => match rest.next() { | ||
| 133 | + Some(value) => out = Some(value.clone()), | ||
| 134 | + None => { | ||
| 135 | + eprintln!("usage: im-web pack [--root DIR] [--out FILE]"); | ||
| 136 | + eprintln!("im: --out needs a file"); | ||
| 137 | + std::process::exit(2); | ||
| 138 | + } | ||
| 139 | + }, | ||
| 140 | + other => { | ||
| 141 | + eprintln!("usage: im-web pack [--root DIR] [--out FILE]"); | ||
| 142 | + eprintln!("im: unexpected argument {other}"); | ||
| 143 | + std::process::exit(2); | ||
| 144 | + } | ||
| 145 | + } | ||
| 146 | + } | ||
| 147 | + pack::pack_command(&config, root.as_deref(), out.as_deref()).await; | ||
| 148 | + } | ||
| 149 | + Some("unpack") => { | ||
| 150 | + let Some(archive) = args.get(2) else { | ||
| 151 | + eprintln!("usage: im-web unpack FILE [--root DIR] [--force]"); | ||
| 152 | + std::process::exit(2); | ||
| 153 | + }; | ||
| 154 | + let mut root: Option<String> = None; | ||
| 155 | + let mut force = false; | ||
| 156 | + let mut rest = args[3..].iter(); | ||
| 157 | + while let Some(arg) = rest.next() { | ||
| 158 | + match arg.as_str() { | ||
| 159 | + "--force" => force = true, | ||
| 160 | + "--root" => match rest.next() { | ||
| 161 | + Some(value) => root = Some(value.clone()), | ||
| 162 | + None => { | ||
| 163 | + eprintln!("usage: im-web unpack FILE [--root DIR] [--force]"); | ||
| 164 | + eprintln!("im: --root needs a directory"); | ||
| 165 | + std::process::exit(2); | ||
| 166 | + } | ||
| 167 | + }, | ||
| 168 | + other => { | ||
| 169 | + eprintln!("usage: im-web unpack FILE [--root DIR] [--force]"); | ||
| 170 | + eprintln!("im: unexpected argument {other}"); | ||
| 171 | + std::process::exit(2); | ||
| 172 | + } | ||
| 173 | + } | ||
| 174 | + } | ||
| 175 | + pack::unpack_command(archive, root.as_deref(), force); | ||
| 176 | + } | ||
| 114 | Some(other) => { | 177 | Some(other) => { |
| 115 | eprintln!( | 178 | eprintln!( |
| 116 | - "im: unknown command {other:?} (expected: invite, revoke, promote, demote, create-client, rotate-client, revoke-client, or none to serve)" | 179 | + "im: unknown command {other:?} (expected: invite, revoke, promote, demote, create-client, rotate-client, revoke-client, pack, unpack, or none to serve)" |
| 117 | ); | 180 | ); |
| 118 | std::process::exit(2); | 181 | std::process::exit(2); |
| 119 | } | 182 | } |
crates/im-web/src/pack.rsadded+574 -0
| @@ -0,0 +1,574 @@ | |||
| 1 | +//! `im-web pack` / `im-web unpack` — the family's backup, and its restore. | ||
| 2 | +//! | ||
| 3 | +//! One 0600 gzipped tar carries every service tree the deployment holds: | ||
| 4 | +//! the database with its WAL sidecars, the config directory, the signing | ||
| 5 | +//! key, and the object store. A `manifest.json` rides as the first member | ||
| 6 | +//! and names what went in, so a restore can check before it overwrites. | ||
| 7 | +//! | ||
| 8 | +//! The keys come from im's services table plus im itself — the archive | ||
| 9 | +//! follows the family as it grows, and no key is ever spelled out here. | ||
| 10 | +//! | ||
| 11 | +//! Like every CLI arm this runs while the server is stopped: Turso is a | ||
| 12 | +//! single-writer engine, and a database packed under a live writer is not | ||
| 13 | +//! a backup. | ||
| 14 | + | ||
| 15 | +use std::fs::{self, File, OpenOptions}; | ||
| 16 | +use std::io::Read as _; | ||
| 17 | +use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; | ||
| 18 | +use std::path::{Component, Path, PathBuf}; | ||
| 19 | + | ||
| 20 | +use serde::{Deserialize, Serialize}; | ||
| 21 | + | ||
| 22 | +use crate::config::Config; | ||
| 23 | + | ||
| 24 | +/// The manifest at the archive's root: which keys ride inside and which | ||
| 25 | +/// files each brought, and when it was packed. `version` gates the | ||
| 26 | +/// restore — a shape this binary does not know refuses itself instead of | ||
| 27 | +/// guessing. | ||
| 28 | +#[derive(Serialize, Deserialize)] | ||
| 29 | +struct Manifest { | ||
| 30 | + version: u32, | ||
| 31 | + packed_at: String, | ||
| 32 | + services: Vec<PackedService>, | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +#[derive(Serialize, Deserialize)] | ||
| 36 | +struct PackedService { | ||
| 37 | + key: String, | ||
| 38 | + /// Paths relative to the pack root — the form the manifest names and | ||
| 39 | + /// the restore writes back: `<key>/<key>.db`, `<key>/config/x.toml`. | ||
| 40 | + files: Vec<String>, | ||
| 41 | +} | ||
| 42 | + | ||
| 43 | +const MANIFEST_NAME: &str = "manifest.json"; | ||
| 44 | + | ||
| 45 | +/// Every family tree worth packing, one key each: the services table's | ||
| 46 | +/// rows plus im's own key. The row for im normally stands on that table — | ||
| 47 | +/// `register_self` writes it on every boot — but a database too young or | ||
| 48 | +/// too emptied to hold it does not keep im's tree out of the archive. | ||
| 49 | +pub async fn family_keys(config: &Config) -> Vec<String> { | ||
| 50 | + let store = im_core::store::Store::open(&config.database) | ||
| 51 | + .await | ||
| 52 | + .expect("failed to open the database"); | ||
| 53 | + let services = im_core::services::list(&store) | ||
| 54 | + .await | ||
| 55 | + .expect("failed to read the services table"); | ||
| 56 | + drop(store); | ||
| 57 | + | ||
| 58 | + let mut keys = vec![im_core::services::SELF_OWNER.to_string()]; | ||
| 59 | + for service in services { | ||
| 60 | + if !keys.contains(&service.key) { | ||
| 61 | + keys.push(service.key); | ||
| 62 | + } | ||
| 63 | + } | ||
| 64 | + keys | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +/// `im-web pack [--root DIR] [--out FILE]`. `--root` is the directory the | ||
| 68 | +/// family trees sit under; without it, the parent of the working | ||
| 69 | +/// directory — on the server, `$HOME` with `$HOME/im`, `$HOME/in`, … | ||
| 70 | +/// inside. Without `--out`, a stamped name in the working directory. | ||
| 71 | +pub async fn pack_command(config: &Config, root: Option<&str>, out: Option<&str>) { | ||
| 72 | + let keys = family_keys(config).await; | ||
| 73 | + let root = root.map(PathBuf::from).unwrap_or_else(default_root); | ||
| 74 | + let out = out.map(PathBuf::from).unwrap_or_else(archive_name); | ||
| 75 | + println!( | ||
| 76 | + "im packing {} service tree(s) from {}", | ||
| 77 | + keys.len(), | ||
| 78 | + root.display() | ||
| 79 | + ); | ||
| 80 | + match pack(&root, &keys, &out) { | ||
| 81 | + Ok(()) => println!("im packed {}", out.display()), | ||
| 82 | + Err(problem) => { | ||
| 83 | + eprintln!("im: {problem}"); | ||
| 84 | + std::process::exit(1); | ||
| 85 | + } | ||
| 86 | + } | ||
| 87 | +} | ||
| 88 | + | ||
| 89 | +/// `im-web unpack FILE [--root DIR] [--force]`. Without `--force` an | ||
| 90 | +/// existing target database stops the restore before anything moves. | ||
| 91 | +pub fn unpack_command(archive: &str, root: Option<&str>, force: bool) { | ||
| 92 | + let root = root.map(PathBuf::from).unwrap_or_else(default_root); | ||
| 93 | + println!("im restoring {archive} into {}", root.display()); | ||
| 94 | + match unpack(Path::new(archive), &root, force) { | ||
| 95 | + Ok(restored) => println!("im restored {restored} file(s)"), | ||
| 96 | + Err(problem) => { | ||
| 97 | + eprintln!("im: {problem}"); | ||
| 98 | + std::process::exit(1); | ||
| 99 | + } | ||
| 100 | + } | ||
| 101 | +} | ||
| 102 | + | ||
| 103 | +/// Packs each key's tree — the database trio, the signing key, `config/`, | ||
| 104 | +/// `storage/` — into one 0600 gzipped tar. A missing piece is a line on | ||
| 105 | +/// stderr, not a failure: a tree without a `storage/` is normal, and the | ||
| 106 | +/// pack's job is to take what is there. | ||
| 107 | +pub fn pack(root: &Path, keys: &[String], out: &Path) -> Result<(), String> { | ||
| 108 | + let mut packed = Vec::new(); | ||
| 109 | + for key in keys { | ||
| 110 | + let home = root.join(key); | ||
| 111 | + if !home.is_dir() { | ||
| 112 | + eprintln!("im {key}: no tree at {}, skipping", home.display()); | ||
| 113 | + continue; | ||
| 114 | + } | ||
| 115 | + let mut files = Vec::new(); | ||
| 116 | + // The database travels with its WAL sidecars or not at all — a | ||
| 117 | + // checkpointed tree legitimately carries neither. | ||
| 118 | + for name in [ | ||
| 119 | + format!("{key}.db"), | ||
| 120 | + format!("{key}.db-wal"), | ||
| 121 | + format!("{key}.db-shm"), | ||
| 122 | + format!("{key}.key"), | ||
| 123 | + ] { | ||
| 124 | + if home.join(&name).is_file() { | ||
| 125 | + files.push(format!("{key}/{name}")); | ||
| 126 | + } else { | ||
| 127 | + eprintln!("im {key}: {name} not present, skipped"); | ||
| 128 | + } | ||
| 129 | + } | ||
| 130 | + for dir in ["config", "storage"] { | ||
| 131 | + let tree = home.join(dir); | ||
| 132 | + if !tree.exists() { | ||
| 133 | + eprintln!("im {key}: {dir}/ not present, skipped"); | ||
| 134 | + continue; | ||
| 135 | + } | ||
| 136 | + if !tree.is_dir() { | ||
| 137 | + return Err(format!("{} is not a directory", tree.display())); | ||
| 138 | + } | ||
| 139 | + files.extend(walk(&tree, root)?); | ||
| 140 | + } | ||
| 141 | + if files.is_empty() { | ||
| 142 | + eprintln!("im {key}: nothing to pack, skipped"); | ||
| 143 | + continue; | ||
| 144 | + } | ||
| 145 | + files.sort(); | ||
| 146 | + packed.push(PackedService { | ||
| 147 | + key: key.clone(), | ||
| 148 | + files, | ||
| 149 | + }); | ||
| 150 | + } | ||
| 151 | + if packed.is_empty() { | ||
| 152 | + return Err("nothing to pack: none of the family trees holds a file".into()); | ||
| 153 | + } | ||
| 154 | + | ||
| 155 | + let manifest = Manifest { | ||
| 156 | + version: 1, | ||
| 157 | + packed_at: time::OffsetDateTime::now_utc() | ||
| 158 | + .format(&time::format_description::well_known::Rfc3339) | ||
| 159 | + .unwrap_or_else(|_| "unknown".into()), | ||
| 160 | + services: packed, | ||
| 161 | + }; | ||
| 162 | + let manifest_body = serde_json::to_vec_pretty(&manifest) | ||
| 163 | + .map_err(|e| format!("failed to write the manifest: {e}"))?; | ||
| 164 | + | ||
| 165 | + if let Some(parent) = out.parent() { | ||
| 166 | + if !parent.as_os_str().is_empty() { | ||
| 167 | + fs::create_dir_all(parent) | ||
| 168 | + .map_err(|e| format!("failed to create {}: {e}", parent.display()))?; | ||
| 169 | + } | ||
| 170 | + } | ||
| 171 | + // 0600 from the first byte: the archive carries signing keys, so | ||
| 172 | + // there is no window where it reads wider. | ||
| 173 | + let file = OpenOptions::new() | ||
| 174 | + .create(true) | ||
| 175 | + .truncate(true) | ||
| 176 | + .write(true) | ||
| 177 | + .mode(0o600) | ||
| 178 | + .open(out) | ||
| 179 | + .map_err(|e| format!("failed to create {}: {e}", out.display()))?; | ||
| 180 | + let mut tar = tar::Builder::new(flate2::write::GzEncoder::new( | ||
| 181 | + file, | ||
| 182 | + flate2::Compression::default(), | ||
| 183 | + )); | ||
| 184 | + let mut header = tar::Header::new_gnu(); | ||
| 185 | + header.set_size(manifest_body.len() as u64); | ||
| 186 | + header.set_mode(0o600); | ||
| 187 | + header.set_cksum(); | ||
| 188 | + tar.append_data(&mut header, MANIFEST_NAME, manifest_body.as_slice()) | ||
| 189 | + .map_err(|e| format!("failed to add {MANIFEST_NAME}: {e}"))?; | ||
| 190 | + for service in &manifest.services { | ||
| 191 | + for relative in &service.files { | ||
| 192 | + let path = root.join(relative); | ||
| 193 | + tar.append_path_with_name(&path, relative) | ||
| 194 | + .map_err(|e| format!("failed to add {relative}: {e}"))?; | ||
| 195 | + } | ||
| 196 | + } | ||
| 197 | + tar.into_inner() | ||
| 198 | + .map_err(|e| format!("failed to seal {PART}: {e}", PART = out.display()))? | ||
| 199 | + .finish() | ||
| 200 | + .map_err(|e| format!("failed to seal {}: {e}", out.display()))?; | ||
| 201 | + Ok(()) | ||
| 202 | +} | ||
| 203 | + | ||
| 204 | +/// Restores an archive under `root`. Refuses when a target database is | ||
| 205 | +/// already there — unless `force` says an overwrite is meant — and lands | ||
| 206 | +/// every config, keys file, and signing key at 0600, whatever the packing | ||
| 207 | +/// machine's modes were. Answers the number of files restored. | ||
| 208 | +pub fn unpack(archive: &Path, root: &Path, force: bool) -> Result<usize, String> { | ||
| 209 | + let manifest = read_manifest(archive)?; | ||
| 210 | + if manifest.version != 1 { | ||
| 211 | + return Err(format!( | ||
| 212 | + "archive manifest version {} is not understood here", | ||
| 213 | + manifest.version | ||
| 214 | + )); | ||
| 215 | + } | ||
| 216 | + if !force { | ||
| 217 | + let in_the_way: Vec<&str> = manifest | ||
| 218 | + .services | ||
| 219 | + .iter() | ||
| 220 | + .filter(|service| { | ||
| 221 | + root.join(&service.key) | ||
| 222 | + .join(format!("{}.db", service.key)) | ||
| 223 | + .is_file() | ||
| 224 | + }) | ||
| 225 | + .map(|service| service.key.as_str()) | ||
| 226 | + .collect(); | ||
| 227 | + if !in_the_way.is_empty() { | ||
| 228 | + return Err(format!( | ||
| 229 | + "refusing to overwrite an existing database for {} — pass --force to unpack over it", | ||
| 230 | + in_the_way.join(", ") | ||
| 231 | + )); | ||
| 232 | + } | ||
| 233 | + } | ||
| 234 | + | ||
| 235 | + let file = File::open(archive).map_err(|e| format!("failed to open {}: {e}", archive.display()))?; | ||
| 236 | + let mut restored = 0; | ||
| 237 | + for entry in tar::Archive::new(flate2::read::GzDecoder::new(file)) | ||
| 238 | + .entries() | ||
| 239 | + .map_err(|e| format!("failed to read {}: {e}", archive.display()))? | ||
| 240 | + { | ||
| 241 | + let mut entry = | ||
| 242 | + entry.map_err(|e| format!("{} is damaged: {e}", archive.display()))?; | ||
| 243 | + let name = entry | ||
| 244 | + .path() | ||
| 245 | + .map_err(|e| format!("{} is damaged: {e}", archive.display()))? | ||
| 246 | + .to_path_buf(); | ||
| 247 | + let Some(relative) = safe_relative(&name) else { | ||
| 248 | + return Err(format!( | ||
| 249 | + "archive member {name:?} is not a safe relative path" | ||
| 250 | + )); | ||
| 251 | + }; | ||
| 252 | + if relative == Path::new(MANIFEST_NAME) { | ||
| 253 | + continue; | ||
| 254 | + } | ||
| 255 | + // Directories are made as their files need them; anything else a | ||
| 256 | + // member could be — a link, a device — is not something this | ||
| 257 | + // archive has business carrying. | ||
| 258 | + if !entry.header().entry_type().is_file() { | ||
| 259 | + return Err(format!("archive member {relative:?} is not a regular file")); | ||
| 260 | + } | ||
| 261 | + let destination = root.join(relative); | ||
| 262 | + if let Some(parent) = destination.parent() { | ||
| 263 | + fs::create_dir_all(parent) | ||
| 264 | + .map_err(|e| format!("failed to create {}: {e}", parent.display()))?; | ||
| 265 | + } | ||
| 266 | + entry | ||
| 267 | + .unpack(&destination) | ||
| 268 | + .map_err(|e| format!("failed to restore {}: {e}", destination.display()))?; | ||
| 269 | + if let Some(secret) = secret_mode(&destination) { | ||
| 270 | + fs::set_permissions(&destination, fs::Permissions::from_mode(secret)) | ||
| 271 | + .map_err(|e| format!("failed to tighten {}: {e}", destination.display()))?; | ||
| 272 | + } | ||
| 273 | + restored += 1; | ||
| 274 | + } | ||
| 275 | + Ok(restored) | ||
| 276 | +} | ||
| 277 | + | ||
| 278 | +/// Walks `dir` for regular files, each named relative to `root` — the | ||
| 279 | +/// form the manifest names and the restore writes back. Symlinks are | ||
| 280 | +/// refused rather than followed: the archive is the bytes of the tree, | ||
| 281 | +/// not where its links point. | ||
| 282 | +fn walk(dir: &Path, root: &Path) -> Result<Vec<String>, String> { | ||
| 283 | + let mut files = Vec::new(); | ||
| 284 | + let mut stack = vec![dir.to_path_buf()]; | ||
| 285 | + while let Some(current) = stack.pop() { | ||
| 286 | + let entries = fs::read_dir(¤t) | ||
| 287 | + .map_err(|e| format!("failed to read {}: {e}", current.display()))?; | ||
| 288 | + for entry in entries { | ||
| 289 | + let entry = entry | ||
| 290 | + .map_err(|e| format!("failed to read {}: {e}", current.display()))?; | ||
| 291 | + let path = entry.path(); | ||
| 292 | + let kind = entry | ||
| 293 | + .file_type() | ||
| 294 | + .map_err(|e| format!("failed to read {}: {e}", path.display()))?; | ||
| 295 | + if kind.is_dir() { | ||
| 296 | + stack.push(path); | ||
| 297 | + } else if kind.is_file() { | ||
| 298 | + let relative = path | ||
| 299 | + .strip_prefix(root) | ||
| 300 | + .map_err(|e| format!("failed to name {}: {e}", path.display()))? | ||
| 301 | + .to_string_lossy() | ||
| 302 | + .into_owned(); | ||
| 303 | + files.push(relative); | ||
| 304 | + } else { | ||
| 305 | + eprintln!("im skipping {}: not a regular file", path.display()); | ||
| 306 | + } | ||
| 307 | + } | ||
| 308 | + } | ||
| 309 | + Ok(files) | ||
| 310 | +} | ||
| 311 | + | ||
| 312 | +/// The archive member as a path that stays under the restore root — | ||
| 313 | +/// `None` for the absolute, upward-traversing, or empty names an archive | ||
| 314 | +/// has no business carrying. | ||
| 315 | +fn safe_relative(name: &Path) -> Option<&Path> { | ||
| 316 | + if name.is_absolute() || name.as_os_str().is_empty() { | ||
| 317 | + return None; | ||
| 318 | + } | ||
| 319 | + for component in name.components() { | ||
| 320 | + match component { | ||
| 321 | + Component::Normal(_) | Component::CurDir => {} | ||
| 322 | + _ => return None, | ||
| 323 | + } | ||
| 324 | + } | ||
| 325 | + Some(name) | ||
| 326 | +} | ||
| 327 | + | ||
| 328 | +/// The mode a restored file is held to: 0600 for the things that carry | ||
| 329 | +/// secrets — config toml, `*.keys`, the signing keys — and `None` for | ||
| 330 | +/// everything else. | ||
| 331 | +fn secret_mode(path: &Path) -> Option<u32> { | ||
| 332 | + let shown = path.to_string_lossy(); | ||
| 333 | + if shown.ends_with(".toml") || shown.ends_with(".keys") || shown.ends_with(".key") { | ||
| 334 | + Some(0o600) | ||
| 335 | + } else { | ||
| 336 | + None | ||
| 337 | + } | ||
| 338 | +} | ||
| 339 | + | ||
| 340 | +/// Reads the archive's manifest, its first member — the pass that decides | ||
| 341 | +/// whether the restore may start at all. | ||
| 342 | +fn read_manifest(archive: &Path) -> Result<Manifest, String> { | ||
| 343 | + let file = | ||
| 344 | + File::open(archive).map_err(|e| format!("failed to open {}: {e}", archive.display()))?; | ||
| 345 | + for entry in tar::Archive::new(flate2::read::GzDecoder::new(file)) | ||
| 346 | + .entries() | ||
| 347 | + .map_err(|e| format!("failed to read {}: {e}", archive.display()))? | ||
| 348 | + { | ||
| 349 | + let mut entry = | ||
| 350 | + entry.map_err(|e| format!("{} is damaged: {e}", archive.display()))?; | ||
| 351 | + let is_manifest = entry | ||
| 352 | + .path() | ||
| 353 | + .map_err(|e| format!("{} is damaged: {e}", archive.display()))? | ||
| 354 | + == Path::new(MANIFEST_NAME); | ||
| 355 | + if is_manifest { | ||
| 356 | + let mut body = String::new(); | ||
| 357 | + entry | ||
| 358 | + .read_to_string(&mut body) | ||
| 359 | + .map_err(|e| format!("failed to read {MANIFEST_NAME}: {e}"))?; | ||
| 360 | + return serde_json::from_str(&body) | ||
| 361 | + .map_err(|e| format!("{}'s manifest does not parse: {e}", archive.display())); | ||
| 362 | + } | ||
| 363 | + } | ||
| 364 | + Err(format!("{} carries no {MANIFEST_NAME}", archive.display())) | ||
| 365 | +} | ||
| 366 | + | ||
| 367 | +/// The parent of the working directory: on the server the trees sit under | ||
| 368 | +/// `$HOME`, the deploy directory the process runs from inside it. | ||
| 369 | +fn default_root() -> PathBuf { | ||
| 370 | + let cwd = match std::env::current_dir() { | ||
| 371 | + Ok(cwd) => cwd, | ||
| 372 | + Err(e) => { | ||
| 373 | + eprintln!("im: cannot read the working directory: {e}"); | ||
| 374 | + std::process::exit(2); | ||
| 375 | + } | ||
| 376 | + }; | ||
| 377 | + match cwd.parent() { | ||
| 378 | + Some(parent) => parent.to_path_buf(), | ||
| 379 | + None => { | ||
| 380 | + eprintln!("im: no family root above {}", cwd.display()); | ||
| 381 | + eprintln!("usage: pass --root DIR"); | ||
| 382 | + std::process::exit(2); | ||
| 383 | + } | ||
| 384 | + } | ||
| 385 | +} | ||
| 386 | + | ||
| 387 | +/// The archive's default name: stamped, in the working directory. | ||
| 388 | +fn archive_name() -> PathBuf { | ||
| 389 | + const STAMP: &[time::format_description::BorrowedFormatItem<'static>] = | ||
| 390 | + time::macros::format_description!( | ||
| 391 | + "im-pack-[year][month][day]-[hour][minute][second].tar.gz" | ||
| 392 | + ); | ||
| 393 | + PathBuf::from( | ||
| 394 | + time::OffsetDateTime::now_utc() | ||
| 395 | + .format(STAMP) | ||
| 396 | + .unwrap_or_else(|_| "im-pack.tar.gz".into()), | ||
| 397 | + ) | ||
| 398 | +} | ||
| 399 | + | ||
| 400 | +#[cfg(test)] | ||
| 401 | +mod tests { | ||
| 402 | + use super::*; | ||
| 403 | + | ||
| 404 | + /// A throwaway tree under the OS temp dir, gone with the test. | ||
| 405 | + struct TempDir(PathBuf); | ||
| 406 | + | ||
| 407 | + impl TempDir { | ||
| 408 | + fn new(label: &str) -> TempDir { | ||
| 409 | + let path = std::env::temp_dir() | ||
| 410 | + .join(format!("im-pack-{label}-{}", ulid::Ulid::generate())); | ||
| 411 | + fs::create_dir_all(&path).unwrap(); | ||
| 412 | + TempDir(path) | ||
| 413 | + } | ||
| 414 | + } | ||
| 415 | + | ||
| 416 | + impl Drop for TempDir { | ||
| 417 | + fn drop(&mut self) { | ||
| 418 | + let _ = fs::remove_dir_all(&self.0); | ||
| 419 | + } | ||
| 420 | + } | ||
| 421 | + | ||
| 422 | + fn write(path: &Path, bytes: &[u8]) { | ||
| 423 | + fs::create_dir_all(path.parent().unwrap()).unwrap(); | ||
| 424 | + fs::write(path, bytes).unwrap(); | ||
| 425 | + } | ||
| 426 | + | ||
| 427 | + fn mode_of(path: &Path) -> u32 { | ||
| 428 | + fs::metadata(path).unwrap().permissions().mode() & 0o777 | ||
| 429 | + } | ||
| 430 | + | ||
| 431 | + /// The data-driven gate: the keys are whatever the caller hands over — | ||
| 432 | + /// here `im` and a fixture sibling `xy` that is not in/iz — and the | ||
| 433 | + /// roundtrip treats them identically. Also the standing refusals: the | ||
| 434 | + /// archive lands 0600, secrets restore 0600, and a second unpack | ||
| 435 | + /// stops at the existing database unless --force names the overwrite. | ||
| 436 | + #[test] | ||
| 437 | + fn roundtrip_im_and_xy() { | ||
| 438 | + let source = TempDir::new("src"); | ||
| 439 | + // im: the full tree — database trio, signing key, config, storage. | ||
| 440 | + write(&source.0.join("im/im.db"), b"im-db"); | ||
| 441 | + write(&source.0.join("im/im.db-wal"), b"im-wal"); | ||
| 442 | + write(&source.0.join("im/im.db-shm"), b"im-shm"); | ||
| 443 | + write(&source.0.join("im/im.key"), b"im-key"); | ||
| 444 | + write(&source.0.join("im/config/im.toml"), b"listen = \"127.0.0.1:7650\"\n"); | ||
| 445 | + write(&source.0.join("im/storage/a/blob"), b"im-blob"); | ||
| 446 | + // xy: a bare sibling — database and config only. `zz` has no tree | ||
| 447 | + // at all; its pack is a stderr line, not a failure. | ||
| 448 | + write(&source.0.join("xy/xy.db"), b"xy-db"); | ||
| 449 | + write(&source.0.join("xy/config/xy.toml"), b"listen = \"127.0.0.1:8000\"\n"); | ||
| 450 | + | ||
| 451 | + let keys = ["im".to_string(), "xy".to_string(), "zz".to_string()]; | ||
| 452 | + let out = source.0.join("pack.tar.gz"); | ||
| 453 | + pack(&source.0, &keys, &out).expect("pack succeeds"); | ||
| 454 | + assert!(out.is_file()); | ||
| 455 | + assert_eq!(mode_of(&out), 0o600, "the archive lands 0600"); | ||
| 456 | + | ||
| 457 | + let destination = TempDir::new("dest"); | ||
| 458 | + unpack(&out, &destination.0, false).expect("unpack into an empty root"); | ||
| 459 | + for (relative, bytes) in [ | ||
| 460 | + ("im/im.db", &b"im-db"[..]), | ||
| 461 | + ("im/im.db-wal", b"im-wal"), | ||
| 462 | + ("im/im.db-shm", b"im-shm"), | ||
| 463 | + ("im/im.key", b"im-key"), | ||
| 464 | + ("im/config/im.toml", b"listen = \"127.0.0.1:7650\"\n"), | ||
| 465 | + ("im/storage/a/blob", b"im-blob"), | ||
| 466 | + ("xy/xy.db", b"xy-db"), | ||
| 467 | + ("xy/config/xy.toml", b"listen = \"127.0.0.1:8000\"\n"), | ||
| 468 | + ] { | ||
| 469 | + assert_eq!( | ||
| 470 | + fs::read(destination.0.join(relative)).unwrap(), | ||
| 471 | + bytes, | ||
| 472 | + "{relative} must roundtrip" | ||
| 473 | + ); | ||
| 474 | + } | ||
| 475 | + for secret in ["im/im.key", "im/config/im.toml", "xy/config/xy.toml"] { | ||
| 476 | + assert_eq!( | ||
| 477 | + mode_of(&destination.0.join(secret)), | ||
| 478 | + 0o600, | ||
| 479 | + "{secret} must land 0600" | ||
| 480 | + ); | ||
| 481 | + } | ||
| 482 | + | ||
| 483 | + // Without --force, a target database stops the restore before | ||
| 484 | + // anything moves. | ||
| 485 | + let problem = unpack(&out, &destination.0, false) | ||
| 486 | + .expect_err("an existing database must refuse the unpack"); | ||
| 487 | + assert!(problem.contains("--force"), "the refusal names the way out: {problem}"); | ||
| 488 | + assert_eq!( | ||
| 489 | + fs::read(destination.0.join("im/im.db")).unwrap(), | ||
| 490 | + b"im-db", | ||
| 491 | + "the refused unpack left the tree alone" | ||
| 492 | + ); | ||
| 493 | + unpack(&out, &destination.0, true).expect("--force unpacks over it"); | ||
| 494 | + assert_eq!(fs::read(destination.0.join("im/im.db")).unwrap(), b"im-db"); | ||
| 495 | + } | ||
| 496 | + | ||
| 497 | + /// A member whose name climbs out of the restore root is refused, not | ||
| 498 | + /// extracted — a tampered archive cannot write past the root. The | ||
| 499 | + /// tar library refuses to *write* such a name, so the hostile archive | ||
| 500 | + /// is ustar bytes laid by hand, the way an attacker would. | ||
| 501 | + #[test] | ||
| 502 | + fn unpack_refuses_escaping_names() { | ||
| 503 | + use std::io::Write as _; | ||
| 504 | + | ||
| 505 | + let source = TempDir::new("evil-src"); | ||
| 506 | + let archive = source.0.join("evil.tar.gz"); | ||
| 507 | + | ||
| 508 | + let mut tar = Vec::new(); | ||
| 509 | + raw_member( | ||
| 510 | + &mut tar, | ||
| 511 | + MANIFEST_NAME, | ||
| 512 | + br#"{"version":1,"packed_at":"now","services":[{"key":"xy","files":[]}]}"#, | ||
| 513 | + ); | ||
| 514 | + raw_member(&mut tar, "../escape", b"gotcha"); | ||
| 515 | + tar.extend_from_slice(&[0u8; 1024]); | ||
| 516 | + let mut gz = flate2::write::GzEncoder::new( | ||
| 517 | + File::create(&archive).unwrap(), | ||
| 518 | + flate2::Compression::default(), | ||
| 519 | + ); | ||
| 520 | + gz.write_all(&tar).unwrap(); | ||
| 521 | + gz.finish().unwrap(); | ||
| 522 | + | ||
| 523 | + let destination = TempDir::new("evil-dest"); | ||
| 524 | + let problem = unpack(&archive, &destination.0, false) | ||
| 525 | + .expect_err("an escaping member must refuse the unpack"); | ||
| 526 | + assert!(problem.contains("safe relative"), "{problem}"); | ||
| 527 | + assert!( | ||
| 528 | + !destination.0.parent().unwrap().join("escape").exists(), | ||
| 529 | + "nothing may land outside the root" | ||
| 530 | + ); | ||
| 531 | + } | ||
| 532 | + | ||
| 533 | + /// One raw ustar member: header block, body, padding — no library | ||
| 534 | + /// path validation, so a hostile name travels through untouched. | ||
| 535 | + fn raw_member(tar: &mut Vec<u8>, name: &str, body: &[u8]) { | ||
| 536 | + let mut header = [0u8; 512]; | ||
| 537 | + header[..name.len()].copy_from_slice(name.as_bytes()); | ||
| 538 | + header[124..136].copy_from_slice(format!("{:011o}\0", body.len()).as_bytes()); | ||
| 539 | + header[136..148].copy_from_slice(b"00000000000\0"); | ||
| 540 | + header[148..156].copy_from_slice(b" "); | ||
| 541 | + header[156] = b'0'; | ||
| 542 | + header[257..263].copy_from_slice(b"ustar\0"); | ||
| 543 | + header[263..265].copy_from_slice(b"00"); | ||
| 544 | + let sum: u32 = header.iter().map(|byte| u32::from(*byte)).sum(); | ||
| 545 | + header[148..156].copy_from_slice(format!("{sum:06o}\0 ").as_bytes()); | ||
| 546 | + tar.extend_from_slice(&header); | ||
| 547 | + tar.extend_from_slice(body); | ||
| 548 | + tar.extend(std::iter::repeat_n(0u8, (512 - body.len() % 512) % 512)); | ||
| 549 | + } | ||
| 550 | + | ||
| 551 | + /// An archive whose manifest names a shape this binary does not know | ||
| 552 | + /// refuses itself instead of guessing. | ||
| 553 | + #[test] | ||
| 554 | + fn unpack_refuses_a_future_manifest() { | ||
| 555 | + let source = TempDir::new("future-src"); | ||
| 556 | + let archive = source.0.join("future.tar.gz"); | ||
| 557 | + let file = File::create(&archive).unwrap(); | ||
| 558 | + let mut tar = tar::Builder::new(flate2::write::GzEncoder::new( | ||
| 559 | + file, | ||
| 560 | + flate2::Compression::default(), | ||
| 561 | + )); | ||
| 562 | + let manifest = br#"{"version":99,"packed_at":"tomorrow","services":[]}"#; | ||
| 563 | + let mut header = tar::Header::new_gnu(); | ||
| 564 | + header.set_size(manifest.len() as u64); | ||
| 565 | + header.set_cksum(); | ||
| 566 | + tar.append_data(&mut header, MANIFEST_NAME, &manifest[..]).unwrap(); | ||
| 567 | + tar.into_inner().unwrap().finish().unwrap(); | ||
| 568 | + | ||
| 569 | + let destination = TempDir::new("future-dest"); | ||
| 570 | + let problem = unpack(&archive, &destination.0, false) | ||
| 571 | + .expect_err("an unknown manifest version must refuse"); | ||
| 572 | + assert!(problem.contains("version"), "{problem}"); | ||
| 573 | + } | ||
| 574 | +} | ||
style/main.scssmodified+15 -0
| @@ -1039,6 +1039,21 @@ body:has(.log-list) { | |||
| 1039 | .mono { font-family: var(--font-mono); } | 1039 | .mono { font-family: var(--font-mono); } |
| 1040 | .muted { color: var(--muted); } | 1040 | .muted { color: var(--muted); } |
| 1041 | 1041 | ||
| 1042 | +// The admin Health section's per-service state dot: green while the | ||
| 1043 | +// service's /healthz answers ok, muted when it does not. The green is | ||
| 1044 | +// iz's connection card's — the same light across the family's panels. | ||
| 1045 | +.health-dot { | ||
| 1046 | + display: inline-block; | ||
| 1047 | + width: 0.55rem; | ||
| 1048 | + height: 0.55rem; | ||
| 1049 | + border-radius: 50%; | ||
| 1050 | + margin-right: 0.4rem; | ||
| 1051 | + vertical-align: baseline; | ||
| 1052 | + | ||
| 1053 | + &.health-on { background: #2e9e5b; } | ||
| 1054 | + &.health-off { background: var(--muted); } | ||
| 1055 | +} | ||
| 1056 | + | ||
| 1042 | .actions { | 1057 | .actions { |
| 1043 | display: flex; | 1058 | display: flex; |
| 1044 | flex-wrap: wrap; | 1059 | flex-wrap: wrap; |