Skip to main content

vault_core/
update.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! The signed release manifest behind `unv update` (Phase 54, roadmap R26).
4//!
5//! Same shape as the provider catalogue (an Ed25519 signature over the exact
6//! payload bytes, then a shape check) but with its **own** key, so a leaked
7//! catalogue key cannot ship a binary and the reverse. A manifest names one
8//! version and, per platform, one archive with its SHA-256 and size. Nothing
9//! here does I/O beyond reading the running executable's path.
10//!
11//! [`UPDATE_KEY_HEX`] is empty until the maintainer generates the update
12//! key and pins its public half; with no key pinned every verify is refused,
13//! so a build without one can never self-update by accident.
14
15use base64::Engine;
16use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
17use serde::{Deserialize, Serialize};
18use std::path::Path;
19
20pub const SCHEMA: u32 = 1;
21
22/// Public half of the update-signing key (64 hex digits). Empty = not pinned.
23/// Never reuse the catalogue key here.
24pub const UPDATE_KEY_HEX: &str = "";
25
26/// Where the release job publishes the signed CLI manifest.
27pub const DEFAULT_URL: &str =
28    "https://github.com/darthdemono/UnENVerse/releases/latest/download/unv-update.json";
29
30const MAX_ASSETS: usize = 16;
31const MAX_ARCHIVE_BYTES: u64 = 512 * 1024 * 1024;
32
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34pub struct Asset {
35    /// `linux-x86_64`, `windows-x86_64`, ...
36    pub target: String,
37    pub url: String,
38    /// Lowercase hex SHA-256 of the archive.
39    pub sha256: String,
40    pub size: u64,
41}
42
43#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44pub struct Manifest {
45    pub schema: u32,
46    pub version: String,
47    pub published_at: String,
48    #[serde(default)]
49    pub notes: String,
50    pub assets: Vec<Asset>,
51}
52
53#[derive(Serialize, Deserialize)]
54struct Signed {
55    payload: String,
56    signature: String,
57}
58
59/// `x.y.z` as numbers; anything else (pre-release, build metadata) is refused
60/// so a manifest cannot smuggle in an ordering this code does not understand.
61pub fn parse_version(v: &str) -> Option<(u64, u64, u64)> {
62    let mut it = v.split('.');
63    let mut n = || {
64        let s = it.next()?;
65        (!s.is_empty() && s.len() <= 9 && s.bytes().all(|b| b.is_ascii_digit()))
66            .then(|| s.parse::<u64>().ok())
67            .flatten()
68    };
69    let t = (n()?, n()?, n()?);
70    it.next().is_none().then_some(t)
71}
72
73/// The target string for the running binary, matching the release archive names.
74/// A musl build (Alpine) gets its own `-musl` archive: the glibc one will not start there.
75pub fn current_target() -> String {
76    let libc = if cfg!(target_env = "musl") {
77        "-musl"
78    } else {
79        ""
80    };
81    format!(
82        "{}-{}{}",
83        std::env::consts::OS,
84        std::env::consts::ARCH,
85        libc
86    )
87}
88
89pub fn pinned_key() -> Result<[u8; 32], String> {
90    let mut key = [0u8; 32];
91    if UPDATE_KEY_HEX.len() != 64 || hex::decode_to_slice(UPDATE_KEY_HEX, &mut key).is_err() {
92        return Err(
93            "this build has no update key pinned, so it cannot verify an update; \
94             reinstall from the release page"
95                .into(),
96        );
97    }
98    Ok(key)
99}
100
101fn validate(m: &Manifest) -> Result<(), String> {
102    if m.schema != SCHEMA {
103        return Err(format!("unsupported manifest schema {}", m.schema));
104    }
105    if parse_version(&m.version).is_none() {
106        return Err(format!(
107            "`{}` is not a plain x.y.z version",
108            m.version.escape_debug()
109        ));
110    }
111    if m.published_at.len() != 20 || !m.published_at.ends_with('Z') {
112        return Err("published_at must be YYYY-MM-DDTHH:MM:SSZ".into());
113    }
114    if m.notes.len() > 20_000 {
115        return Err("release notes are over 20 kB".into());
116    }
117    if m.assets.is_empty() || m.assets.len() > MAX_ASSETS {
118        return Err("asset count out of range".into());
119    }
120    for (i, a) in m.assets.iter().enumerate() {
121        if m.assets[..i].iter().any(|b| b.target == a.target) {
122            return Err(format!("duplicate target `{}`", a.target.escape_debug()));
123        }
124        let target_ok = !a.target.is_empty()
125            && a.target.len() <= 32
126            && a.target
127                .bytes()
128                .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-');
129        if !target_ok {
130            return Err(format!("bad target `{}`", a.target.escape_debug()));
131        }
132        if !a.url.starts_with("https://") {
133            return Err(format!("non-https URL for `{}`", a.target));
134        }
135        let hex_ok = a.sha256.len() == 64
136            && a.sha256
137                .bytes()
138                .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
139        if !hex_ok {
140            return Err(format!("bad sha256 for `{}`", a.target));
141        }
142        if a.size == 0 || a.size > MAX_ARCHIVE_BYTES {
143            return Err(format!("archive size out of range for `{}`", a.target));
144        }
145    }
146    Ok(())
147}
148
149/// Check signature, then shape. Does not compare versions.
150pub fn verify(raw: &[u8], key: &[u8; 32]) -> Result<Manifest, String> {
151    let signed: Signed =
152        serde_json::from_slice(raw).map_err(|e| format!("not an update manifest: {e}"))?;
153    let sig = base64::engine::general_purpose::STANDARD
154        .decode(signed.signature.trim())
155        .map_err(|_| "signature is not base64".to_string())?;
156    let sig =
157        Signature::from_slice(&sig).map_err(|_| "signature has the wrong length".to_string())?;
158    let vk = VerifyingKey::from_bytes(key).map_err(|e| e.to_string())?;
159    vk.verify(signed.payload.as_bytes(), &sig)
160        .map_err(|_| "signature does not match the pinned update key".to_string())?;
161    let m: Manifest = serde_json::from_str(&signed.payload).map_err(|e| e.to_string())?;
162    validate(&m)?;
163    Ok(m)
164}
165
166/// Publisher side: sign `m` with a 32-byte Ed25519 seed.
167pub fn sign(m: &Manifest, seed: &[u8; 32]) -> Result<String, String> {
168    validate(m)?;
169    let payload = serde_json::to_string(m).map_err(|e| e.to_string())?;
170    let sig = SigningKey::from_bytes(seed).sign(payload.as_bytes());
171    let signature = base64::engine::general_purpose::STANDARD.encode(sig.to_bytes());
172    serde_json::to_string_pretty(&Signed { payload, signature }).map_err(|e| e.to_string())
173}
174
175impl Manifest {
176    /// Is this manifest strictly newer than `current`? A downgrade or the same
177    /// version is never an update.
178    pub fn is_newer_than(&self, current: &str) -> bool {
179        match (parse_version(&self.version), parse_version(current)) {
180            (Some(a), Some(b)) => a > b,
181            _ => false,
182        }
183    }
184
185    pub fn asset_for(&self, target: &str) -> Option<&Asset> {
186        self.assets.iter().find(|a| a.target == target)
187    }
188}
189
190/// Lowercase hex SHA-256 of `bytes`.
191pub fn sha256_hex(bytes: &[u8]) -> String {
192    use sha2::{Digest, Sha256};
193    hex::encode(Sha256::digest(bytes))
194}
195
196/// File the release archives ship beside the executable. Only a binary that
197/// sits next to it was unpacked from a standalone archive and may replace itself.
198pub const STANDALONE_MARKER: &str = ".unv-standalone";
199
200#[derive(Debug, PartialEq, Eq)]
201pub enum Origin {
202    /// Unpacked from a release archive: may self-replace.
203    Standalone,
204    /// Owned by something else; the string is the command that updates it.
205    Managed(&'static str),
206    /// Not recognisably either: declined, with the remedy in the message.
207    Unknown,
208}
209
210/// Classify an executable path. `marker_dir_has_marker` is whether
211/// [`STANDALONE_MARKER`] exists beside it (passed in so this stays pure).
212pub fn classify(exe: &Path, marker_dir_has_marker: bool) -> Origin {
213    let p = exe.to_string_lossy().replace('\\', "/").to_lowercase();
214    let managed: [(&str, &'static str); 10] = [
215        (
216            "/nix/store/",
217            "nix profile upgrade, or update your Nix configuration",
218        ),
219        ("/homebrew/", "brew upgrade unv"),
220        ("/linuxbrew/", "brew upgrade unv"),
221        // Intel Homebrew's Cellar sits under /usr/local.
222        ("/cellar/", "brew upgrade unv"),
223        ("/scoop/", "scoop update unv"),
224        ("/windowsapps/", "winget upgrade unv"),
225        ("/winget/", "winget upgrade unv"),
226        ("/.cargo/bin/", "cargo install unv-cli --locked --force"),
227        ("/snap/", "sudo snap refresh unv"),
228        (
229            "/usr/",
230            "your package manager (for example dnf upgrade unv or apt upgrade unv)",
231        ),
232    ];
233    // A package manager's directory wins over the marker: a marker copied into
234    // /usr/bin must not turn a dnf-owned file into one we overwrite.
235    for (needle, cmd) in managed {
236        // /usr/local is where a hand-copied binary goes, so only the bare /usr/ rule steps aside.
237        if p.contains(needle) && !(needle == "/usr/" && p.contains("/usr/local/")) {
238            return Origin::Managed(cmd);
239        }
240    }
241    if marker_dir_has_marker {
242        Origin::Standalone
243    } else {
244        Origin::Unknown
245    }
246}
247
248#[cfg(test)]
249mod tests {
250    use super::*;
251
252    const SEED: [u8; 32] = [5; 32];
253
254    fn key() -> [u8; 32] {
255        SigningKey::from_bytes(&SEED).verifying_key().to_bytes()
256    }
257
258    fn manifest() -> Manifest {
259        Manifest {
260            schema: SCHEMA,
261            version: "0.55.0".into(),
262            published_at: "2026-10-17T12:00:00Z".into(),
263            notes: "notes".into(),
264            assets: vec![Asset {
265                target: "linux-x86_64".into(),
266                url: "https://example.test/unv.tar.gz".into(),
267                sha256: sha256_hex(b"x"),
268                size: 1,
269            }],
270        }
271    }
272
273    /// Release archives are named `<os>-<arch>[-musl]`; the arm64 and musl names the
274    /// release job publishes must pass manifest validation and be found by `asset_for`.
275    #[test]
276    fn release_target_names_validate_and_musl_is_detected() {
277        let names = [
278            "linux-x86_64",
279            "linux-aarch64",
280            "linux-x86_64-musl",
281            "linux-aarch64-musl",
282            "windows-x86_64",
283            "windows-aarch64",
284            "macos-x86_64",
285            "macos-aarch64",
286        ];
287        let mut m = manifest();
288        m.assets = names
289            .iter()
290            .map(|n| Asset {
291                target: (*n).into(),
292                url: "https://example.test/unv.tar.gz".into(),
293                sha256: sha256_hex(b"x"),
294                size: 1,
295            })
296            .collect();
297        let signed = sign(&m, &SEED).unwrap();
298        let ok = verify(signed.as_bytes(), &key()).unwrap();
299        for n in names {
300            assert!(ok.asset_for(n).is_some(), "{n}");
301        }
302        assert_eq!(
303            current_target().ends_with("-musl"),
304            cfg!(target_env = "musl")
305        );
306    }
307
308    #[test]
309    fn accepts_a_signed_manifest() {
310        let raw = sign(&manifest(), &SEED).unwrap();
311        assert_eq!(verify(raw.as_bytes(), &key()).unwrap(), manifest());
312    }
313
314    #[test]
315    fn refuses_a_wrong_key_and_a_tampered_payload() {
316        let raw = sign(&manifest(), &SEED).unwrap();
317        assert!(verify(raw.as_bytes(), &[9; 32]).is_err());
318        let tampered = raw.replace("0.55.0", "9.9.9");
319        assert!(verify(tampered.as_bytes(), &key()).is_err());
320    }
321
322    #[test]
323    fn refuses_a_signed_but_malformed_manifest() {
324        let mut m = manifest();
325        m.assets[0].url = "http://example.test/a".into();
326        assert!(sign(&m, &SEED).is_err());
327        let mut m = manifest();
328        m.version = "1.0.0-rc1".into();
329        assert!(sign(&m, &SEED).is_err());
330        let mut m = manifest();
331        m.assets[0].sha256 = "ABC".into();
332        assert!(sign(&m, &SEED).is_err());
333        let mut m = manifest();
334        m.assets.push(m.assets[0].clone());
335        assert!(sign(&m, &SEED).is_err());
336    }
337
338    #[test]
339    fn only_a_strictly_newer_version_is_an_update() {
340        let m = manifest();
341        assert!(m.is_newer_than("0.54.9"));
342        assert!(!m.is_newer_than("0.55.0"));
343        assert!(!m.is_newer_than("0.56.0"));
344        assert!(m.is_newer_than("0.9.0"));
345        assert!(!m.is_newer_than("garbage"));
346    }
347
348    #[test]
349    fn no_pinned_key_refuses_everything() {
350        assert!(pinned_key().is_err());
351    }
352
353    #[test]
354    fn classifies_install_origins() {
355        let p = |s: &str| Path::new(s).to_path_buf();
356        assert_eq!(classify(&p("/opt/tools/unv"), true), Origin::Standalone);
357        assert_eq!(classify(&p("/opt/tools/unv"), false), Origin::Unknown);
358        assert!(matches!(
359            classify(&p("/usr/bin/unv"), true),
360            Origin::Managed(_)
361        ));
362        assert!(matches!(
363            classify(&p("/home/a/.cargo/bin/unv"), false),
364            Origin::Managed(_)
365        ));
366        assert!(matches!(
367            classify(&p("C:\\Users\\a\\scoop\\apps\\unv\\current\\unv.exe"), true),
368            Origin::Managed(_)
369        ));
370        assert_eq!(classify(&p("/usr/local/bin/unv"), true), Origin::Standalone);
371        assert_eq!(
372            classify(&p("/usr/local/Cellar/unv/0.60.2/bin/unv"), true),
373            Origin::Managed("brew upgrade unv")
374        );
375    }
376}