Skip to main content

sovereign_update/
lib.rs

1//! Claude-Code-style update check for sovereign binaries (EPIC #4232, #4242).
2//!
3//! * [`startup`] — call first thing in `main`. Prints at most one stderr line
4//!   from the cache, and refreshes a stale cache (24 h) on a detached thread.
5//!   It never blocks, never fails the command, and is silent on every error.
6//!   It is skipped by `SOVEREIGN_DISABLE_UPDATE_CHECK=1`, `CI`, a non-TTY
7//!   stderr, or `--json`/`--quiet`.
8//! * [`update_command`] — the body of `<bin> update [--check]`. It installs the
9//!   NEWER of the latest release and the green nightly (#4189 manifest), by
10//!   main ancestry, and never downgrades. It verifies the sha256 (fail
11//!   closed), smoke-tests `--version`, and renames the new binary over the
12//!   running one, keeping `<exe>.prev`. Fleet hosts report and do not install.
13//!
14//! ```no_run
15//! const PRODUCT: sovereign_update::Product = sovereign_update::Product {
16//!     bin: "pv",
17//!     repo: "paiml/aprender",
18//!     version: env!("CARGO_PKG_VERSION"),
19//!     build_sha: None,
20//!     release_asset: Some("{bin}-{tag}-{target}.tar.gz"),
21//!     nightly: true,
22//! };
23//! sovereign_update::startup(&PRODUCT, &std::env::args().collect::<Vec<_>>());
24//! ```
25
26pub mod cache;
27pub mod decide;
28pub mod fetch;
29pub mod install;
30pub mod policy;
31
32use decide::{Candidate, Current, Decision};
33use fetch::Net;
34use policy::Installs;
35use std::io::IsTerminal;
36use std::path::Path;
37use std::time::Duration;
38
39/// What a binary says about itself. All fields are compile-time constants.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub struct Product {
42    /// Executable name, e.g. `apr`.
43    pub bin: &'static str,
44    /// `owner/name` on GitHub.
45    pub repo: &'static str,
46    /// `env!("CARGO_PKG_VERSION")`.
47    pub version: &'static str,
48    /// Build commit, when the binary embeds one (#4219).
49    pub build_sha: Option<&'static str>,
50    /// Release asset name template over `{bin}` `{tag}` `{version}` `{target}`;
51    /// `None` when releases carry no asset for this bin.
52    pub release_asset: Option<&'static str>,
53    /// Whether the repo's `nightly` release carries an #4189 manifest.
54    pub nightly: bool,
55}
56
57/// Per request, for the background refresh child.
58const TIMEOUT: Duration = Duration::from_secs(10);
59/// The refresh child exits after this, whatever the network is doing.
60const REFRESH_DEADLINE: Duration = Duration::from_secs(60);
61/// Hidden `update` argument the startup check runs its refresh child with.
62const REFRESH_ARG: &str = "--refresh-cache";
63const UPDATE_TIMEOUT: Duration = Duration::from_secs(120);
64
65/// The target triple this binary was built for, as release assets name it.
66#[must_use]
67pub fn host_target() -> String {
68    let os = match std::env::consts::OS {
69        "linux" if cfg!(target_env = "musl") => "unknown-linux-musl",
70        "linux" => "unknown-linux-gnu",
71        "macos" => "apple-darwin",
72        "windows" => "pc-windows-msvc",
73        other => other,
74    };
75    format!("{}-{os}", std::env::consts::ARCH)
76}
77
78fn env(k: &str) -> Option<String> {
79    std::env::var(k).ok()
80}
81
82/// This host's name: procfs, `/etc/hostname`, `$HOSTNAME`, then `uname -n`
83/// (macOS has neither file). Empty if all fail, which [`policy::installs`]
84/// treats as report-only.
85fn hostname() -> String {
86    let file = |p: &str| std::fs::read_to_string(p).ok();
87    let uname = || {
88        std::process::Command::new("uname")
89            .arg("-n")
90            .output()
91            .ok()
92            .filter(|o| o.status.success())
93            .map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
94    };
95    file("/proc/sys/kernel/hostname")
96        .or_else(|| file("/etc/hostname"))
97        .or_else(|| env("HOSTNAME"))
98        .or_else(uname)
99        .map(|s| s.trim().to_string())
100        .unwrap_or_default()
101}
102
103fn this_host_installs() -> Installs {
104    let manifest = policy::arbiter_manifest(&env);
105    policy::installs(&hostname(), manifest.as_deref().filter(|m| m.exists()))
106}
107
108fn now() -> u64 {
109    std::time::SystemTime::now()
110        .duration_since(std::time::UNIX_EPOCH)
111        .map_or(0, |d| d.as_secs())
112}
113
114fn user_agent(p: &Product) -> String {
115    format!("{}/{} sovereign-update", p.bin, p.version)
116}
117
118/// Fresh check against the network: the release, the nightly, and ancestry.
119pub fn check(net: &dyn Net, p: &Product, target: &str) -> Result<Decision, String> {
120    let release = fetch::latest_release(net, p, target)?;
121    let nightly = fetch::nightly(net, p, target)?;
122    let cur = Current {
123        version: p.version.to_string(),
124        build_sha: p.build_sha.map(str::to_string),
125    };
126    let anc = |a: &str, b: &str| fetch::ancestry(net, p.repo, a, b);
127    Ok(decide::decide(
128        &cur,
129        release.as_ref(),
130        nightly.as_ref(),
131        &anc,
132    ))
133}
134
135/// Run a check and record it. A failure keeps the previous `available`, so a
136/// flaky network neither hides a known update nor retries more than daily.
137pub fn refresh(net: &dyn Net, p: &Product, target: &str, path: &Path, now: u64) {
138    let old = cache::load(path);
139    let (available, error) = match check(net, p, target) {
140        Ok(Decision::Available(c)) => (Some(c), None),
141        Ok(Decision::UpToDate) => (None, None),
142        Err(e) => (old.and_then(|c| c.available), Some(e)),
143    };
144    let c = cache::Cache {
145        schema: cache::SCHEMA.into(),
146        checked_at: now,
147        current_version: p.version.into(),
148        current_sha: p.build_sha.map(Into::into),
149        available,
150        error,
151    };
152    let _ = cache::store(path, &c);
153}
154
155/// Call at the top of `main`. Never blocks, never fails, never errors aloud.
156pub fn startup(p: &Product, args: &[String]) {
157    // `update` is unix-only (install.rs); never announce what it cannot do.
158    if !cfg!(unix) {
159        return;
160    }
161    if policy::check_allowed(&env, std::io::stderr().is_terminal(), args).is_err() {
162        return;
163    }
164    let Some(path) = cache::path(&env, p.bin) else {
165        return;
166    };
167    if let Some(line) = startup_with(p, args, &path, now(), &this_host_installs(), &spawn_refresh) {
168        eprintln!("{line}");
169    }
170}
171
172/// The startup check after the skip rules. It takes no [`Net`]: it cannot
173/// block on the network by construction. It reads the cache, claims the day
174/// and hands the refresh to `spawn`. Returns the notice to print, if any.
175pub fn startup_with(
176    p: &Product,
177    args: &[String],
178    path: &Path,
179    now: u64,
180    installs: &Installs,
181    spawn: &dyn Fn(),
182) -> Option<String> {
183    if args.get(1).is_some_and(|a| a == "update") {
184        return None;
185    }
186    let c = cache::load(path);
187    let line = c.as_ref().and_then(|c| cache::notice(p, c, installs));
188    // Claim the day before spawning, so concurrent runs start one refresh,
189    // not one each. A refresh that dies leaves the claim: next try in 24 h.
190    if cache::needs_refresh(p, c.as_ref(), now)
191        && cache::store(path, &cache::claim(p, c.as_ref(), now)).is_ok()
192    {
193        spawn();
194    }
195    line
196}
197
198/// Run `<exe> update --refresh-cache` as a detached child. A thread would die
199/// with a short command (`pv --version` exits long before GitHub answers); a
200/// child outlives it. Its stdio is null, so it can never print into the user's
201/// terminal, and a waiter thread reaps it if this process lives longer.
202fn spawn_refresh() {
203    use std::process::{Command, Stdio};
204    let Ok(exe) = std::env::current_exe() else {
205        return;
206    };
207    let mut cmd = Command::new(exe);
208    cmd.args(["update", REFRESH_ARG])
209        .stdin(Stdio::null())
210        .stdout(Stdio::null())
211        .stderr(Stdio::null());
212    #[cfg(unix)]
213    std::os::unix::process::CommandExt::process_group(&mut cmd, 0);
214    if let Ok(mut child) = cmd.spawn() {
215        std::thread::spawn(move || child.wait());
216    }
217}
218
219fn describe(c: &Candidate) -> String {
220    let src = match c.source {
221        decide::Source::Release => format!("release {}", c.git_ref),
222        decide::Source::Nightly => {
223            format!("nightly {}", c.git_ref.chars().take(12).collect::<String>())
224        }
225    };
226    format!("{} ({src})", c.version)
227}
228
229/// Body of `<bin> update [--check]`, with every effect injected. Returns the
230/// exit code and the lines to print (stdout).
231pub fn update_with(
232    net: &dyn Net,
233    p: &Product,
234    target: &str,
235    installs: &Installs,
236    exe: &Path,
237    check_only: bool,
238) -> (i32, Vec<String>) {
239    let c = match check(net, p, target) {
240        Ok(Decision::UpToDate) => {
241            return (0, vec![format!("{} {} is up to date", p.bin, p.version)])
242        }
243        Ok(Decision::Available(c)) => c,
244        Err(e) => return (1, vec![format!("{}: update check failed: {e}", p.bin)]),
245    };
246    let mut out = vec![format!(
247        "{} {} -> {} available",
248        p.bin,
249        p.version,
250        describe(&c)
251    )];
252    if check_only {
253        return (0, out);
254    }
255    if let Installs::Arbiter(why) = installs {
256        out.push(format!(
257            "not installing: {why}; the fleet arbiter manages installs on this host"
258        ));
259        return (0, out);
260    }
261    match install::install(net, p.bin, &c, exe) {
262        Ok(prev) => {
263            out.push(format!(
264                "updated {} -> {} (previous kept at {})",
265                exe.display(),
266                c.version,
267                prev.display()
268            ));
269            (0, out)
270        }
271        Err(e) => {
272            out.push(format!("{}: update refused: {e}", p.bin));
273            (1, out)
274        }
275    }
276}
277
278/// `<bin> update [--check]` against the real network and the running exe.
279#[must_use]
280pub fn update_command(p: &Product, check_only: bool) -> i32 {
281    if !cfg!(unix) {
282        eprintln!(
283            "{}: self-update is unix-only; download from https://github.com/{}/releases",
284            p.bin, p.repo
285        );
286        return 1;
287    }
288    // Say what it is waiting on: DNS is not bounded by the request timeout.
289    eprintln!("{}: checking https://github.com/{} ...", p.bin, p.repo);
290    let exe = match std::env::current_exe() {
291        Ok(e) => e,
292        Err(e) => {
293            eprintln!("{}: cannot locate the running executable: {e}", p.bin);
294            return 1;
295        }
296    };
297    let net = fetch::Http::new(UPDATE_TIMEOUT, &user_agent(p));
298    let (code, lines) = update_with(
299        &net,
300        p,
301        &host_target(),
302        &this_host_installs(),
303        &exe,
304        check_only,
305    );
306    for l in lines {
307        if code == 0 {
308            println!("{l}");
309        } else {
310            eprintln!("{l}");
311        }
312    }
313    // A successful check also refreshes the cache, so the startup notice agrees.
314    if let Some(path) = cache::path(&env, p.bin) {
315        refresh(&net, p, &host_target(), &path, now());
316    }
317    code
318}
319
320/// What `<bin> update <args>` asked for.
321#[derive(Debug, Clone, Copy, PartialEq, Eq)]
322pub enum UpdateArgs {
323    Install,
324    Check,
325    Help,
326    /// The startup check's detached child: refresh the cache, print nothing.
327    RefreshCache,
328    Bad,
329}
330
331/// Parse the arguments after `update`.
332#[must_use]
333pub fn parse_update_args(args: &[String]) -> UpdateArgs {
334    match args {
335        [] => UpdateArgs::Install,
336        [a] if a == "--check" => UpdateArgs::Check,
337        [a] if a == "--help" || a == "-h" => UpdateArgs::Help,
338        [a] if a == REFRESH_ARG => UpdateArgs::RefreshCache,
339        _ => UpdateArgs::Bad,
340    }
341}
342
343/// Entry for a binary that dispatches `update` before its own CLI parser:
344/// `if args.get(1) == Some("update") { exit(update_main(&P, &args[2..])) }`.
345/// Intercepting in the binary's own `main` means the executable replaced is
346/// always the one named `p.bin`, never a host binary that embeds its library.
347#[must_use]
348pub fn update_main(p: &Product, args: &[String]) -> i32 {
349    let usage = format!(
350        "usage: {0} update [--check]\n  Install the newer of the latest release and the green nightly (sha256-verified).\n  --check  report only\n  Disable the startup check with {1}=1.",
351        p.bin,
352        policy::DISABLE_ENV
353    );
354    match parse_update_args(args) {
355        UpdateArgs::Install => update_command(p, false),
356        UpdateArgs::Check => update_command(p, true),
357        UpdateArgs::Help => {
358            println!("{usage}");
359            0
360        }
361        UpdateArgs::RefreshCache => {
362            // ureq's timeout does not bound DNS resolution; a hung resolver
363            // must not leave one stuck child per day. Hard deadline.
364            std::thread::spawn(|| {
365                std::thread::sleep(REFRESH_DEADLINE);
366                std::process::exit(0);
367            });
368            if let Some(path) = cache::path(&env, p.bin) {
369                let net = fetch::Http::new(TIMEOUT, &user_agent(p));
370                refresh(&net, p, &host_target(), &path, now());
371            }
372            0
373        }
374        UpdateArgs::Bad => {
375            eprintln!("{usage}");
376            2
377        }
378    }
379}
380
381#[cfg(test)]
382#[allow(clippy::disallowed_methods)] // serde_json::json! expands to Result::unwrap
383mod tests {
384    use super::*;
385    use std::collections::HashMap;
386
387    struct Fake(HashMap<String, Vec<u8>>, bool);
388    impl Net for Fake {
389        fn get(&self, url: &str) -> Result<Option<Vec<u8>>, String> {
390            if self.1 {
391                return Err("offline".into());
392            }
393            Ok(self.0.get(url).cloned())
394        }
395    }
396
397    const P: Product = Product {
398        bin: "pv",
399        repo: "o/r",
400        version: "0.69.0",
401        build_sha: None,
402        release_asset: Some("{bin}-{tag}-{target}.tar.gz"),
403        nightly: true,
404    };
405    const T: &str = "x86_64-unknown-linux-gnu";
406    const LATEST: &str = "https://api.github.com/repos/o/r/releases?per_page=30";
407
408    fn with_release(tag: &str) -> HashMap<String, Vec<u8>> {
409        let n = format!("pv-{tag}-{T}.tar.gz");
410        let body = serde_json::json!([{"tag_name": tag, "prerelease": false, "draft": false, "assets": [{"name": n, "browser_download_url": format!("https://dl/{n}")}]}]);
411        HashMap::from([(LATEST.to_string(), serde_json::to_vec(&body).expect("json"))])
412    }
413
414    #[test]
415    fn update_rows() {
416        let exe = Path::new("/nonexistent/pv");
417        let (c, o) = update_with(
418            &Fake(with_release("v0.69.0"), false),
419            &P,
420            T,
421            &Installs::User,
422            exe,
423            false,
424        );
425        assert_eq!((c, o[0].as_str()), (0, "pv 0.69.0 is up to date"));
426        let (c, o) = update_with(
427            &Fake(with_release("v0.69.1"), false),
428            &P,
429            T,
430            &Installs::User,
431            exe,
432            true,
433        );
434        assert_eq!(
435            (c, o.as_slice()),
436            (
437                0,
438                ["pv 0.69.0 -> 0.69.1 (release v0.69.1) available".to_string()].as_slice()
439            )
440        );
441        let (c, o) = update_with(
442            &Fake(with_release("v0.69.1"), false),
443            &P,
444            T,
445            &Installs::Arbiter("fleet host yoga".into()),
446            exe,
447            false,
448        );
449        assert_eq!(c, 0, "fleet host reports, does not install");
450        assert!(o[1].starts_with("not installing: fleet host yoga"), "{o:?}");
451        let (c, o) = update_with(
452            &Fake(with_release("v0.69.1"), false),
453            &P,
454            T,
455            &Installs::User,
456            exe,
457            false,
458        );
459        assert_eq!(c, 1, "no published digest -> refused: {o:?}");
460        assert!(o[1].contains("no published digest"), "{o:?}");
461        let (c, _) = update_with(
462            &Fake(HashMap::new(), true),
463            &P,
464            T,
465            &Installs::User,
466            exe,
467            true,
468        );
469        assert_eq!(
470            c, 1,
471            "an explicit check that cannot reach the network says so"
472        );
473        let (c, o) = update_with(
474            &Fake(HashMap::new(), false),
475            &P,
476            T,
477            &Installs::User,
478            exe,
479            true,
480        );
481        assert_eq!(
482            (c, o[0].as_str()),
483            (0, "pv 0.69.0 is up to date"),
484            "nothing published (404s)"
485        );
486    }
487
488    #[test]
489    fn refresh_keeps_known_update_when_offline() {
490        let d = tempfile::tempdir().expect("tempdir");
491        let path = d.path().join("pv/update-check.json");
492        refresh(&Fake(with_release("v0.69.1"), false), &P, T, &path, 100);
493        let c = cache::load(&path).expect("stored");
494        assert_eq!(
495            c.available.as_ref().map(|a| a.version.as_str()),
496            Some("0.69.1")
497        );
498        refresh(&Fake(HashMap::new(), true), &P, T, &path, 200);
499        let c2 = cache::load(&path).expect("stored");
500        assert_eq!(
501            (c2.checked_at, c2.available, c2.error.is_some()),
502            (200, c.available, true)
503        );
504    }
505
506    #[test]
507    fn startup_spawns_once_a_day_and_never_refreshes_inline() {
508        let d = tempfile::tempdir().expect("tempdir");
509        let path = d.path().join("pv/update-check.json");
510        let spawned = std::cell::Cell::new(0);
511        let spawn = || spawned.set(spawned.get() + 1);
512        let run = |args: &[&str], now| {
513            let a: Vec<String> = args.iter().map(|s| (*s).to_string()).collect();
514            startup_with(&P, &a, &path, now, &Installs::User, &spawn)
515        };
516        assert_eq!(
517            run(&["pv", "validate"], 1000),
518            None,
519            "cold cache: no notice yet"
520        );
521        assert_eq!(
522            spawned.get(),
523            1,
524            "cold cache: the refresh is spawned, not run"
525        );
526        let claim = cache::load(&path).expect("the day is claimed before spawning");
527        assert_eq!((claim.checked_at, claim.available), (1000, None));
528        assert_eq!(run(&["pv", "validate"], 2000), None);
529        assert_eq!(spawned.get(), 1, "within 24 h: no second refresh");
530        refresh(&Fake(with_release("v0.69.1"), false), &P, T, &path, 3000);
531        let n = run(&["pv"], 4000).expect("the cached update is announced");
532        assert!(n.starts_with("pv 0.69.0 -> 0.69.1 available"), "{n}");
533        assert_eq!(run(&["pv", "update"], 1 + 3000 + cache::TTL_SECS), None);
534        assert_eq!(spawned.get(), 1, "`update` itself never spawns a refresh");
535        assert!(run(&["pv"], 3000 + cache::TTL_SECS).is_some());
536        assert_eq!(spawned.get(), 2, "after 24 h: one more refresh");
537    }
538
539    #[test]
540    fn update_args_rows() {
541        let a =
542            |v: &[&str]| parse_update_args(&v.iter().map(|s| (*s).to_string()).collect::<Vec<_>>());
543        assert_eq!(a(&[]), UpdateArgs::Install);
544        assert_eq!(a(&["--check"]), UpdateArgs::Check);
545        assert_eq!(a(&["-h"]), UpdateArgs::Help);
546        assert_eq!(a(&["--refresh-cache"]), UpdateArgs::RefreshCache);
547        assert_eq!(a(&["--force"]), UpdateArgs::Bad);
548        assert_eq!(a(&["--check", "x"]), UpdateArgs::Bad);
549    }
550
551    #[test]
552    #[cfg(target_os = "linux")]
553    fn host_target_is_a_triple() {
554        let t = host_target();
555        assert_eq!(t.split('-').count(), 4, "{t}");
556    }
557}