Skip to main content

sovereign_update/
policy.rs

1//! When the check may run, and whether this host may install.
2//!
3//! Pure functions over an environment lookup, so every rule is a table row.
4
5/// Why the background check does not run.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum Skip {
8    /// `SOVEREIGN_DISABLE_UPDATE_CHECK` is set to a non-empty value other than `0`.
9    Disabled,
10    /// `CI` is set.
11    Ci,
12    /// stderr is not a terminal, so nobody would read the notice.
13    NotTty,
14    /// `--json` or `--quiet`/`-q` on the command line: output is for a machine.
15    MachineOutput,
16}
17
18pub const DISABLE_ENV: &str = "SOVEREIGN_DISABLE_UPDATE_CHECK";
19/// Overrides where the fleet arbiter's manifest lives.
20pub const ARBITER_ENV: &str = "SOVEREIGN_ARBITER_MANIFEST";
21/// The arbiter manifest, relative to `$HOME` (infra-8d, EPIC #4232). forjar
22/// owns it; every writer runs as the user, so it is not under `/etc`.
23pub const ARBITER_MANIFEST: &str = ".config/sovereign/arbiter-manifest.json";
24/// Fleet hosts: report-only whether or not a manifest exists yet (infra-8d:
25/// "no manifest means report-only, never auto-update"). Matched
26/// case-insensitively as a substring of the hostname.
27pub const FLEET_HOSTS: [&str; 3] = ["lambda-vector", "gx10", "yoga"];
28
29fn set(env: &dyn Fn(&str) -> Option<String>, k: &str) -> bool {
30    env(k).is_some_and(|v| !v.is_empty() && v != "0")
31}
32
33/// `Ok(())` when the check may run.
34pub fn check_allowed(
35    env: &dyn Fn(&str) -> Option<String>,
36    stderr_is_tty: bool,
37    args: &[String],
38) -> Result<(), Skip> {
39    if set(env, DISABLE_ENV) {
40        return Err(Skip::Disabled);
41    }
42    if env("CI").is_some() {
43        return Err(Skip::Ci);
44    }
45    if args
46        .iter()
47        .any(|a| a == "--json" || a == "--quiet" || a == "-q" || a.starts_with("--format=json"))
48    {
49        return Err(Skip::MachineOutput);
50    }
51    if !stderr_is_tty {
52        return Err(Skip::NotTty);
53    }
54    Ok(())
55}
56
57/// Who owns installs on this host.
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub enum Installs {
60    /// The user: `update` may swap the binary.
61    User,
62    /// The fleet arbiter: report only, never self-install. Carries why.
63    Arbiter(String),
64}
65
66/// Where the arbiter manifest is: `$SOVEREIGN_ARBITER_MANIFEST` if set and
67/// non-empty, else `$HOME/.config/sovereign/arbiter-manifest.json`.
68#[must_use]
69pub fn arbiter_manifest(env: &dyn Fn(&str) -> Option<String>) -> Option<std::path::PathBuf> {
70    env(ARBITER_ENV)
71        .filter(|v| !v.is_empty())
72        .map(std::path::PathBuf::from)
73        .or_else(|| {
74            env("HOME")
75                .filter(|h| !h.is_empty())
76                .map(|h| std::path::Path::new(&h).join(ARBITER_MANIFEST))
77        })
78}
79
80/// Decide who owns installs. An existing arbiter manifest (the file IS the
81/// marker) or a fleet hostname makes it the arbiter's.
82#[must_use]
83pub fn installs(hostname: &str, manifest: Option<&std::path::Path>) -> Installs {
84    if let Some(m) = manifest {
85        return Installs::Arbiter(format!("arbiter manifest {}", m.display()));
86    }
87    if hostname.trim().is_empty() {
88        // Fail closed: an undetectable name could be a fleet host.
89        return Installs::Arbiter("hostname unknown".into());
90    }
91    let h = hostname.to_ascii_lowercase();
92    if let Some(f) = FLEET_HOSTS.iter().find(|f| h.contains(*f)) {
93        return Installs::Arbiter(format!("fleet host {hostname} ({f})"));
94    }
95    Installs::User
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101
102    fn env_of(pairs: &'static [(&'static str, &'static str)]) -> impl Fn(&str) -> Option<String> {
103        move |k| {
104            pairs
105                .iter()
106                .find(|(n, _)| *n == k)
107                .map(|(_, v)| (*v).to_string())
108        }
109    }
110    fn args(a: &[&str]) -> Vec<String> {
111        a.iter().map(|s| (*s).to_string()).collect()
112    }
113
114    #[test]
115    fn check_allowed_case_table() {
116        type Row = (
117            &'static str,
118            &'static [(&'static str, &'static str)],
119            bool,
120            &'static [&'static str],
121            Result<(), Skip>,
122        );
123        let rows: [Row; 10] = [
124            ("interactive, no env", &[], true, &["run"], Ok(())),
125            (
126                "disabled by env",
127                &[(DISABLE_ENV, "1")],
128                true,
129                &[],
130                Err(Skip::Disabled),
131            ),
132            (
133                "disable=0 means enabled",
134                &[(DISABLE_ENV, "0")],
135                true,
136                &[],
137                Ok(()),
138            ),
139            (
140                "disable empty means enabled",
141                &[(DISABLE_ENV, "")],
142                true,
143                &[],
144                Ok(()),
145            ),
146            (
147                "CI set, even empty",
148                &[("CI", "")],
149                true,
150                &[],
151                Err(Skip::Ci),
152            ),
153            ("stderr not a tty", &[], false, &[], Err(Skip::NotTty)),
154            (
155                "--json",
156                &[],
157                true,
158                &["list", "--json"],
159                Err(Skip::MachineOutput),
160            ),
161            ("--quiet", &[], true, &["--quiet"], Err(Skip::MachineOutput)),
162            ("-q", &[], true, &["-q"], Err(Skip::MachineOutput)),
163            (
164                "--format=json",
165                &[],
166                true,
167                &["--format=json"],
168                Err(Skip::MachineOutput),
169            ),
170        ];
171        let mut bad = Vec::new();
172        for (name, env, tty, a, want) in rows {
173            let got = check_allowed(&env_of(env), tty, &args(a));
174            if got != want {
175                bad.push(format!("{name}: got {got:?}, want {want:?}"));
176            }
177        }
178        assert!(
179            bad.is_empty(),
180            "check_allowed rows failed:\n{}",
181            bad.join("\n")
182        );
183    }
184
185    #[test]
186    fn installs_case_table() {
187        use std::path::{Path, PathBuf};
188        assert_eq!(installs("laptop", None), Installs::User);
189        for h in ["", "  "] {
190            assert!(
191                matches!(installs(h, None), Installs::Arbiter(_)),
192                "unknown hostname {h:?} is report-only"
193            );
194        }
195        assert!(matches!(
196            installs("laptop", Some(Path::new("/h/m.json"))),
197            Installs::Arbiter(_)
198        ));
199        for h in ["noah-Lambda-Vector", "gx10-5e1a", "YOGA"] {
200            assert!(
201                matches!(installs(h, None), Installs::Arbiter(_)),
202                "{h} is a fleet host even with no manifest"
203            );
204        }
205        assert_eq!(
206            arbiter_manifest(&env_of(&[(ARBITER_ENV, "/m.json"), ("HOME", "/h")])),
207            Some(PathBuf::from("/m.json")),
208            "the env override wins"
209        );
210        assert_eq!(
211            arbiter_manifest(&env_of(&[(ARBITER_ENV, ""), ("HOME", "/h")])),
212            Some(PathBuf::from("/h/.config/sovereign/arbiter-manifest.json")),
213            "an empty override falls back to HOME"
214        );
215        assert_eq!(arbiter_manifest(&env_of(&[])), None);
216    }
217}