Skip to main content

agentmux_common/
update_manifest.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! The signed manifest of a release's files
5//! (`docs/specs/SPEC_SIGNED_UPDATE_CHECKSUMS_2026_10_25.md`).
6//!
7//! A release publishes three small files beside its downloads: a **manifest**
8//! (every file with its size and SHA-256), an **envelope** that names the
9//! manifest by its hash and the release by its tag, and a **signature** of the
10//! envelope's exact bytes. AgentMux pins the public key and takes a release
11//! file's name, size and hash only from a manifest that [`verify_release`]
12//! passed, so a file that didn't come out of the release pipeline (a swapped
13//! asset, a rewritten API answer) is never offered, downloaded or run.
14//!
15//! This module only checks bytes it is given: fetching them, and what the
16//! person is told, are the update check's (`srv::backend::update::check`).
17//! The release workflow makes and verifies the same files with
18//! `scripts/release-manifest.mjs`; `tests::a_release_made_by_the_script_verifies`
19//! pins the two to one format.
20
21use base64::engine::general_purpose::STANDARD as BASE64;
22use base64::Engine;
23use ed25519_dalek::{Signature, Verifier, VerifyingKey};
24use serde::Deserialize;
25use sha2::{Digest, Sha256};
26
27/// The envelope's `format`, the only one understood.
28pub const ENVELOPE_FORMAT: u32 = 1;
29/// The manifest's `format`, the only one understood.
30pub const MANIFEST_FORMAT: u32 = 1;
31/// The most bytes read for an envelope: it is a fixed handful of fields.
32pub const MAX_ENVELOPE_BYTES: usize = 4096;
33/// The most bytes read for a manifest. It grows with the files of a release; a
34/// megabyte is thousands of files.
35pub const MAX_MANIFEST_BYTES: usize = 1024 * 1024;
36/// The most files a manifest may list.
37const MAX_FILES: usize = 1000;
38/// The most images a manifest may list.
39const MAX_IMAGES: usize = 16;
40
41/// A public key the app trusts to sign releases, with the id signature lines
42/// name it by.
43#[derive(Debug, Clone, Copy)]
44pub struct UpdateKey {
45    pub id: &'static str,
46    pub public: [u8; 32],
47}
48
49/// The keys this build trusts: at most two (the current one and, once a
50/// rotation is prepared, the next; spec §6). `k1` is the release signing key
51/// (plain Ed25519, raw 32-byte public key); the private half never leaves the
52/// signing service.
53///
54/// `update-keys.json` (beside `src/`) lists the same keys in base64 for the
55/// release workflow, and a test keeps the two equal.
56pub const UPDATE_KEYS: &[UpdateKey] = &[UpdateKey {
57    id: "k1",
58    public: [
59        0x9b, 0xd1, 0xd1, 0x67, 0x85, 0x0e, 0x88, 0x15, 0x36, 0xbf, 0x2a, 0xe3, 0x94, 0x75, 0xe3, 0xd4, 0x3d, 0x02, 0x8d, 0xf8, 0x40, 0x6b, 0x32, 0x36, 0x0c, 0x67, 0x48, 0x23, 0xd2, 0x52, 0x24, 0xb1,
60    ],
61}];
62
63/// What is signed: a release's tag and the hash of its manifest.
64#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
65pub struct Envelope {
66    pub format: u32,
67    pub tag: String,
68    pub manifest_sha256: String,
69    pub created_at: String,
70}
71
72/// One release file, as the pipeline made it.
73#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
74pub struct ManifestFile {
75    pub name: String,
76    pub size: u64,
77    /// Lowercase hex.
78    pub sha256: String,
79}
80
81/// A container image the release built, named by the digest of its content: whatever a
82/// registry serves under a tag, the image at this digest is the one the pipeline made.
83#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
84pub struct ManifestImage {
85    /// What the release calls it, e.g. `agent-base`.
86    pub name: String,
87    /// The repository, without a tag or digest, e.g. `ghcr.io/agentmuxai/agent-base`.
88    #[serde(rename = "ref")]
89    pub reference: String,
90    /// `sha256:` and lowercase hex: the digest of the image (a multi-platform image's index).
91    pub digest: String,
92}
93
94/// A release's files, and the images it built. Older manifests have no `images`, and an app
95/// older than the field ignores it.
96#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
97pub struct Manifest {
98    pub format: u32,
99    pub version: String,
100    pub tag: String,
101    pub files: Vec<ManifestFile>,
102    #[serde(default)]
103    pub images: Vec<ManifestImage>,
104    /// What the release says about upgrading to it: `floor` (the oldest version that may upgrade straight to it) and
105    /// `shared_store_changed` (whether it changes a shared store's schema). Optional, under format 1, and kept as the
106    /// JSON the pipeline signed: a field that isn't usable is read as absent by [`Manifest::signed_floor`] and
107    /// [`Manifest::shared_store_changed`], never a reason to refuse the files (`SPEC_UPGRADE_FLOOR_IN_SIGNED_MANIFEST`).
108    /// An app older than the field ignores it.
109    #[serde(default)]
110    pub upgrade: Option<serde_json::Value>,
111}
112
113/// The upgrade floor a verified manifest carries.
114#[derive(Debug, Clone, PartialEq, Eq)]
115pub enum SignedFloor {
116    /// The manifest says nothing about a floor: today's behaviour (the build's floor, and the notes' or the floor file's).
117    Absent,
118    /// A plain `X.Y.Z` that is not above the release's own version.
119    Valid(String),
120    /// The manifest has a floor that can't be used, and why: treated as absent, and logged by the caller.
121    Unusable(String),
122}
123
124/// Whether the release changes a shared store's schema (`upgrade.shared_store_changed`).
125#[derive(Debug, Clone, Copy, PartialEq, Eq)]
126pub enum SharedStoreChanged {
127    /// Not said: not known, treated as no warning.
128    Absent,
129    /// `true` or `false`.
130    Known(bool),
131    /// Present but not a boolean: treated as absent, and logged by the caller.
132    Unusable,
133}
134
135/// `<digits>.<digits>.<digits>` and nothing else (each part at most nine digits).
136pub fn is_plain_version(s: &str) -> bool {
137    let mut parts = s.split('.');
138    let number = |p: Option<&str>| p.is_some_and(|p| !p.is_empty() && p.len() <= 9 && p.bytes().all(|b| b.is_ascii_digit()));
139    number(parts.next()) && number(parts.next()) && number(parts.next()) && parts.next().is_none()
140}
141
142impl Manifest {
143    /// The floor this manifest signs for its release. It does not refuse anything by itself: the pipeline refuses to sign a
144    /// bad floor, so an unusable one is a bug there, and the app falls back to the floor it would use without one.
145    pub fn signed_floor(&self) -> SignedFloor {
146        let Some(upgrade) = &self.upgrade else { return SignedFloor::Absent };
147        let Some(object) = upgrade.as_object() else { return SignedFloor::Unusable("upgrade isn't an object".into()) };
148        let Some(floor) = object.get("floor") else { return SignedFloor::Absent };
149        let Some(floor) = floor.as_str().filter(|f| is_plain_version(f)) else {
150            return SignedFloor::Unusable("upgrade.floor isn't a plain version".into());
151        };
152        match (version_core(floor), version_core(&self.version)) {
153            (Some(f), Some(v)) if f > v => SignedFloor::Unusable(format!("upgrade.floor {floor} is above the release's own version {}", self.version)),
154            (Some(_), _) => SignedFloor::Valid(floor.to_string()),
155            (None, _) => SignedFloor::Unusable("upgrade.floor isn't a plain version".into()),
156        }
157    }
158
159    /// `upgrade.shared_store_changed`, as the pipeline signed it.
160    pub fn shared_store_changed(&self) -> SharedStoreChanged {
161        match self.upgrade.as_ref().and_then(|u| u.as_object()).and_then(|o| o.get("shared_store_changed")) {
162            None => SharedStoreChanged::Absent,
163            Some(serde_json::Value::Bool(b)) => SharedStoreChanged::Known(*b),
164            Some(_) => SharedStoreChanged::Unusable,
165        }
166    }
167
168    /// The release file called `name`, if the manifest lists it.
169    pub fn file(&self, name: &str) -> Option<&ManifestFile> {
170        self.files.iter().find(|f| f.name == name)
171    }
172
173    /// The image the release lists as `name`, if it does.
174    pub fn image(&self, name: &str) -> Option<&ManifestImage> {
175        self.images.iter().find(|i| i.name == name)
176    }
177}
178
179/// Why a release's manifest isn't trusted.
180#[derive(Debug, Clone, PartialEq, Eq)]
181pub enum VerifyError {
182    /// No signature from a key this build trusts (a release made before
183    /// signing, or one signed only with a key since retired).
184    Unsigned,
185    /// A signature names a trusted key, but it isn't a valid signature of the
186    /// envelope.
187    BadSignature,
188    /// The envelope isn't what the format says.
189    Envelope(String),
190    /// The envelope is for another release than the one asked about.
191    WrongTag { expected: String, got: String },
192    /// The manifest isn't the one the envelope names.
193    ManifestMismatch,
194    /// The manifest isn't what the format says.
195    Manifest(String),
196}
197
198impl std::fmt::Display for VerifyError {
199    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
200        match self {
201            VerifyError::Unsigned => write!(f, "the release isn't signed with a key this AgentMux trusts"),
202            VerifyError::BadSignature => write!(f, "the release's signature doesn't match"),
203            VerifyError::Envelope(why) => write!(f, "the release's envelope is invalid: {why}"),
204            VerifyError::WrongTag { expected, got } => write!(f, "the envelope is for {got}, not {expected}"),
205            VerifyError::ManifestMismatch => write!(f, "the manifest isn't the one the signature covers"),
206            VerifyError::Manifest(why) => write!(f, "the release's manifest is invalid: {why}"),
207        }
208    }
209}
210
211impl std::error::Error for VerifyError {}
212
213/// Lowercase hex of `bytes`.
214pub fn hex(bytes: &[u8]) -> String {
215    use std::fmt::Write;
216    bytes.iter().fold(String::with_capacity(bytes.len() * 2), |mut s, b| {
217        let _ = write!(s, "{b:02x}");
218        s
219    })
220}
221
222fn is_sha256_hex(s: &str) -> bool {
223    s.len() == 64 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
224}
225
226fn is_sha256_digest(s: &str) -> bool {
227    s.strip_prefix("sha256:").is_some_and(is_sha256_hex)
228}
229
230/// A name for an image: lowercase letters, digits, `.`, `-` and `_`, starting with a letter or digit.
231fn is_image_name(name: &str) -> bool {
232    !name.is_empty()
233        && name.len() <= 64
234        && name.starts_with(|c: char| c.is_ascii_lowercase() || c.is_ascii_digit())
235        && name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '.' | '-' | '_'))
236}
237
238/// A registry repository path, `host[:port]/path/...`, with no tag, digest or scheme.
239fn is_image_repository(reference: &str) -> bool {
240    let mut parts = reference.split('/');
241    let host = parts.next().unwrap_or_default();
242    let path: Vec<&str> = parts.collect();
243    let component = |c: &str| {
244        !c.is_empty() && c.starts_with(|ch: char| ch.is_ascii_lowercase() || ch.is_ascii_digit()) && c.chars().all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || matches!(ch, '.' | '-' | '_'))
245    };
246    let host_ok = match host.split_once(':') {
247        Some((h, port)) => component(h) && !port.is_empty() && port.len() <= 5 && port.bytes().all(|b| b.is_ascii_digit()),
248        None => component(host),
249    };
250    reference.len() <= 255 && host_ok && !path.is_empty() && path.iter().all(|c| component(c))
251}
252
253/// A plain release file name: no path, nothing hidden, nothing a shell or
254/// Windows would treat specially.
255fn is_plain_file_name(name: &str) -> bool {
256    !name.is_empty()
257        && name.len() <= 200
258        && !name.starts_with('.')
259        && !name.contains("..")
260        && name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | '+'))
261}
262
263/// Whether one of `signatures`' lines is a valid signature of `envelope` by a
264/// key in `keys`. `Err(Unsigned)` when no line names a trusted key at all.
265///
266/// A signature file is one line per signature: `<key id> <base64 Ed25519
267/// signature>`, over the envelope file's exact bytes (spec §3). Lines for keys
268/// this build doesn't pin are ignored, so a release signed by both the current
269/// and the next key verifies on a build that knows only one.
270fn check_signature(keys: &[UpdateKey], envelope: &[u8], signatures: &str) -> Result<(), VerifyError> {
271    let mut named_a_trusted_key = false;
272    for line in signatures.lines() {
273        let mut parts = line.split_whitespace();
274        let (Some(id), Some(sig_b64), None) = (parts.next(), parts.next(), parts.next()) else { continue };
275        for key in keys.iter().filter(|k| k.id == id) {
276            named_a_trusted_key = true;
277            let Ok(verifying) = VerifyingKey::from_bytes(&key.public) else { continue };
278            let Ok(sig) = BASE64.decode(sig_b64) else { continue };
279            let Ok(sig) = <[u8; 64]>::try_from(sig.as_slice()) else { continue };
280            if verifying.verify(envelope, &Signature::from_bytes(&sig)).is_ok() {
281                return Ok(());
282            }
283        }
284    }
285    Err(if named_a_trusted_key { VerifyError::BadSignature } else { VerifyError::Unsigned })
286}
287
288/// Check a release's `envelope`, its `signatures` file and its `manifest`
289/// against the trusted `keys` for the release called `tag`, and return the
290/// manifest only if every step passes (spec §5.2):
291///
292/// 1. a signature of the envelope by a trusted key;
293/// 2. the envelope's format, and its tag is `tag` (so an old signed envelope
294///    can't be replayed under a newer tag);
295/// 3. the manifest's SHA-256 is the envelope's `manifest_sha256`;
296/// 4. the manifest's format, tag and version agree with the envelope, and each
297///    file in it has a plain name, a SHA-256 and a size; each image, if it lists
298///    any, has a plain name, a repository and a `sha256:` digest, and no name twice.
299pub fn verify_release(
300    keys: &[UpdateKey],
301    tag: &str,
302    envelope: &[u8],
303    signatures: &str,
304    manifest: &[u8],
305) -> Result<Manifest, VerifyError> {
306    if envelope.len() > MAX_ENVELOPE_BYTES {
307        return Err(VerifyError::Envelope("too large".into()));
308    }
309    check_signature(keys, envelope, signatures)?;
310    let env: Envelope = serde_json::from_slice(envelope).map_err(|e| VerifyError::Envelope(e.to_string()))?;
311    if env.format != ENVELOPE_FORMAT {
312        return Err(VerifyError::Envelope(format!("format {} isn't understood", env.format)));
313    }
314    if env.tag != tag {
315        return Err(VerifyError::WrongTag { expected: tag.to_string(), got: env.tag });
316    }
317    if !is_sha256_hex(&env.manifest_sha256) {
318        return Err(VerifyError::Envelope("manifest_sha256 isn't a SHA-256".into()));
319    }
320    if manifest.len() > MAX_MANIFEST_BYTES {
321        return Err(VerifyError::Manifest("too large".into()));
322    }
323    if !hex(&Sha256::digest(manifest)).eq_ignore_ascii_case(&env.manifest_sha256) {
324        return Err(VerifyError::ManifestMismatch);
325    }
326    let parsed: Manifest = serde_json::from_slice(manifest).map_err(|e| VerifyError::Manifest(e.to_string()))?;
327    if parsed.format != MANIFEST_FORMAT {
328        return Err(VerifyError::Manifest(format!("format {} isn't understood", parsed.format)));
329    }
330    if parsed.tag != env.tag || parsed.version != env.tag.trim_start_matches('v') {
331        return Err(VerifyError::Manifest("it names another release than the envelope".into()));
332    }
333    if parsed.files.is_empty() || parsed.files.len() > MAX_FILES {
334        return Err(VerifyError::Manifest("the number of files is out of range".into()));
335    }
336    let mut seen = std::collections::HashSet::new();
337    for f in &parsed.files {
338        if !is_plain_file_name(&f.name) {
339            return Err(VerifyError::Manifest(format!("{:?} isn't a plain file name", f.name)));
340        }
341        if !is_sha256_hex(&f.sha256) {
342            return Err(VerifyError::Manifest(format!("{}: sha256 isn't a SHA-256", f.name)));
343        }
344        if f.size == 0 {
345            return Err(VerifyError::Manifest(format!("{}: size is zero", f.name)));
346        }
347        if !seen.insert(f.name.as_str()) {
348            return Err(VerifyError::Manifest(format!("{} is listed twice", f.name)));
349        }
350    }
351    if parsed.images.len() > MAX_IMAGES {
352        return Err(VerifyError::Manifest("the number of images is out of range".into()));
353    }
354    let mut seen_images = std::collections::HashSet::new();
355    for i in &parsed.images {
356        if !is_image_name(&i.name) {
357            return Err(VerifyError::Manifest(format!("{:?} isn't a plain image name", i.name)));
358        }
359        if !is_image_repository(&i.reference) {
360            return Err(VerifyError::Manifest(format!("{}: ref isn't an image repository", i.name)));
361        }
362        if !is_sha256_digest(&i.digest) {
363            return Err(VerifyError::Manifest(format!("{}: digest isn't sha256: and 64 hex digits", i.name)));
364        }
365        if !seen_images.insert(i.name.as_str()) {
366            return Err(VerifyError::Manifest(format!("image {} is listed twice", i.name)));
367        }
368    }
369    Ok(parsed)
370}
371
372/// The three files of a signed release, as published next to its other files:
373/// the envelope, its signature and the manifest.
374pub fn file_names(version: &str) -> (String, String, String) {
375    (
376        format!("AgentMux-{version}-envelope.json"),
377        format!("AgentMux-{version}-envelope.json.sig"),
378        format!("AgentMux-{version}-manifest.json"),
379    )
380}
381
382/// The first release the pipeline signs (v0.60.4). From it on, a release without a
383/// verified signed manifest is not installed; an older one never had one.
384pub const FIRST_SIGNED: (u64, u64, u64) = (0, 60, 4);
385
386/// `major.minor.patch` out of a version or tag (`v0.59.27`, `0.59.27+g1a2b`),
387/// or `None` when it doesn't start with three integers.
388pub fn version_core(v: &str) -> Option<(u64, u64, u64)> {
389    let v = v.trim().trim_start_matches('v');
390    let core = v.split(['+', '-']).next().unwrap_or(v);
391    let mut parts = core.split('.');
392    let major = parts.next()?.parse().ok()?;
393    let minor = parts.next()?.parse().ok()?;
394    let patch = parts.next()?.parse().ok()?;
395    if parts.next().is_some() {
396        return None;
397    }
398    Some((major, minor, patch))
399}
400
401/// What the signed manifest said about a release file.
402#[derive(Debug, Clone, PartialEq, Eq)]
403pub enum Outcome {
404    /// The release publishes no signed manifest (made before signing).
405    Unsigned,
406    /// Signed and valid; the file is listed with the size and hash it has.
407    Verified,
408    /// Signed and valid, but the file isn't listed in it.
409    NotListed(String),
410    /// Signed and valid, but the file's size or hash differ from the manifest's.
411    Disagrees(String),
412    /// A manifest is there but doesn't verify (or isn't what the envelope signed).
413    Failed(String),
414    /// The signed files couldn't be fetched (GitHub didn't answer, an error status): nothing is known.
415    Unreachable(String),
416}
417
418/// The decision, given what was fetched (`None`: the release has no signed
419/// manifest) and the file called `name` that has `size` bytes and hashes to `sha256`.
420pub fn judge_file(keys: &[UpdateKey], tag: &str, fetched: Option<(&[u8], &str, &[u8])>, name: &str, size: u64, sha256: &str) -> Outcome {
421    judge_file_and_floor(keys, tag, fetched, name, size, sha256).0
422}
423
424/// [`judge_file`], and the upgrade floor the manifest signs. The floor is read from the same verified manifest the file is
425/// judged against, so a download can refuse on it without trusting what an earlier check saw; it is `Absent` whenever the
426/// manifest did not verify (the outcome says why).
427pub fn judge_file_and_floor(keys: &[UpdateKey], tag: &str, fetched: Option<(&[u8], &str, &[u8])>, name: &str, size: u64, sha256: &str) -> (Outcome, SignedFloor) {
428    let Some((envelope, signatures, manifest)) = fetched else {
429        return (Outcome::Unsigned, SignedFloor::Absent);
430    };
431    let manifest: Manifest = match verify_release(keys, tag, envelope, signatures, manifest) {
432        Ok(m) => m,
433        Err(e) => return (Outcome::Failed(e.to_string()), SignedFloor::Absent),
434    };
435    let outcome = match manifest.file(name) {
436        None => Outcome::NotListed(format!("{name} isn't in the signed manifest")),
437        Some(f) if f.size != size => Outcome::Disagrees(format!("size {} in the manifest, {size} in the file", f.size)),
438        Some(f) if !f.sha256.eq_ignore_ascii_case(sha256) => Outcome::Disagrees("the manifest's SHA-256 differs from the file's".into()),
439        Some(_) => Outcome::Verified,
440    };
441    (outcome, manifest.signed_floor())
442}
443
444/// The floor in force when a verified manifest carries a usable one: the higher of that and `build` (a build's own floor),
445/// which a signed floor never lowers. `None` when the manifest has none that can be used.
446pub fn signed_floor_in_force(build: Option<&str>, signed: &SignedFloor) -> Option<String> {
447    let SignedFloor::Valid(signed) = signed else { return None };
448    Some(match build.filter(|b| version_core(b) >= version_core(signed)) {
449        Some(build) => build.to_string(),
450        None => signed.clone(),
451    })
452}
453
454/// What a person reads when the installed version is older than a release can upgrade from. The app's check and download
455/// and the Linux package helper say the same thing.
456pub fn install_first_message(current: &str, latest: &str, floor: &str) -> String {
457    format!("This AgentMux ({current}) is older than {latest} can upgrade from; install {floor} first, then upgrade.")
458}
459
460/// What to do about `outcome` for `version`: `Ok` to go on, or the message to show (spec §7).
461/// The app's download and the Linux package helper say the same thing.
462pub fn decide(version: &str, outcome: &Outcome) -> Result<(), String> {
463    let v = format!("v{}", version.trim_start_matches('v'));
464    let signature_wrong = format!("The signature on {v} doesn't match, so AgentMux won't download it. Don't install it; tell the AgentMux team.");
465    match outcome {
466        Outcome::Verified => Ok(()),
467        Outcome::Unsigned => match version_core(version) {
468            // Made before signing existed: used as before.
469            Some(core) if core < FIRST_SIGNED => Ok(()),
470            // A version that can't be read is not trusted to be an old one.
471            _ => Err(format!("{v} wasn't signed, so AgentMux won't download it itself. Get it from the release page.")),
472        },
473        Outcome::NotListed(_) => Err(format!("{v} has no file for this kind of install.")),
474        Outcome::Disagrees(_) | Outcome::Failed(_) => Err(signature_wrong),
475        Outcome::Unreachable(why) => Err(format!("Couldn't check the signature of {v} ({why}). Try again.")),
476    }
477}
478
479#[cfg(test)]
480mod tests {
481    use super::*;
482    use ed25519_dalek::{Signer, SigningKey};
483
484    const TAG: &str = "v0.60.1";
485
486    fn signing_key(seed: u8) -> SigningKey {
487        SigningKey::from_bytes(&[seed; 32])
488    }
489
490    fn key(id: &'static str, seed: u8) -> UpdateKey {
491        UpdateKey { id, public: signing_key(seed).verifying_key().to_bytes() }
492    }
493
494    fn manifest_json(files: &[(&str, u64, &str)]) -> String {
495        let files: Vec<String> =
496            files.iter().map(|(n, s, h)| format!(r#"{{"name":"{n}","size":{s},"sha256":"{h}"}}"#)).collect();
497        format!(r#"{{"format":1,"version":"0.60.1","tag":"{TAG}","files":[{}]}}"#, files.join(","))
498    }
499
500    fn envelope_json(tag: &str, manifest: &str) -> String {
501        format!(
502            r#"{{"format":1,"tag":"{tag}","manifest_sha256":"{}","created_at":"2026-10-25T12:00:00Z"}}"#,
503            hex(&Sha256::digest(manifest.as_bytes()))
504        )
505    }
506
507    fn sig_line(id: &str, seed: u8, envelope: &str) -> String {
508        format!("{id} {}\n", BASE64.encode(signing_key(seed).sign(envelope.as_bytes()).to_bytes()))
509    }
510
511    const H1: &str = "1111111111111111111111111111111111111111111111111111111111111111";
512    const H2: &str = "2222222222222222222222222222222222222222222222222222222222222222";
513
514    fn release() -> (String, String) {
515        let manifest = manifest_json(&[("AgentMux-0.60.1-x64-setup.exe", 100, H1), ("agentmux-0.60.1-x64-portable.7z", 50, H2)]);
516        (envelope_json(TAG, &manifest), manifest)
517    }
518
519    #[test]
520    fn a_signed_release_gives_its_files() {
521        let (env, man) = release();
522        let m = verify_release(&[key("k1", 1)], TAG, env.as_bytes(), &sig_line("k1", 1, &env), man.as_bytes()).unwrap();
523        assert_eq!(m.file("AgentMux-0.60.1-x64-setup.exe").map(|f| (f.size, f.sha256.as_str())), Some((100, H1)));
524        assert_eq!(m.file("nope.exe"), None);
525    }
526
527    #[test]
528    fn a_release_with_no_signature_from_a_trusted_key_is_unsigned() {
529        let (env, man) = release();
530        let keys = [key("k1", 1)];
531        assert_eq!(verify_release(&keys, TAG, env.as_bytes(), "", man.as_bytes()), Err(VerifyError::Unsigned));
532        // Signed by a key this build doesn't pin.
533        assert_eq!(verify_release(&keys, TAG, env.as_bytes(), &sig_line("k9", 9, &env), man.as_bytes()), Err(VerifyError::Unsigned));
534        // Nothing pinned yet (the shipped list): every release is unsigned.
535        assert_eq!(verify_release(&[], TAG, env.as_bytes(), &sig_line("k1", 1, &env), man.as_bytes()), Err(VerifyError::Unsigned));
536        assert!(UPDATE_KEYS.len() <= 2, "at most two keys: current and next");
537    }
538
539    #[test]
540    fn a_signature_that_doesnt_match_is_refused() {
541        let (env, man) = release();
542        let keys = [key("k1", 1)];
543        // The right key id with another key's signature.
544        assert_eq!(verify_release(&keys, TAG, env.as_bytes(), &sig_line("k1", 2, &env), man.as_bytes()), Err(VerifyError::BadSignature));
545        // A tampered envelope.
546        let tampered = env.replace("2026-10-25", "2026-10-26");
547        assert_eq!(
548            verify_release(&keys, TAG, tampered.as_bytes(), &sig_line("k1", 1, &env), man.as_bytes()),
549            Err(VerifyError::BadSignature)
550        );
551        // Garbage in the signature field.
552        assert_eq!(verify_release(&keys, TAG, env.as_bytes(), "k1 !!!\n", man.as_bytes()), Err(VerifyError::BadSignature));
553    }
554
555    #[test]
556    fn either_of_two_keys_may_have_signed_and_unknown_lines_are_ignored() {
557        let (env, man) = release();
558        let both = [key("k1", 1), key("k2", 2)];
559        for sigs in [sig_line("k1", 1, &env), sig_line("k2", 2, &env), format!("k9 AAAA\n{}{}", sig_line("k1", 9, &env), sig_line("k2", 2, &env))] {
560            assert!(verify_release(&both, TAG, env.as_bytes(), &sigs, man.as_bytes()).is_ok(), "{sigs}");
561        }
562        // A build that knows only the older key still takes a release signed by both.
563        let both_sigs = format!("{}{}", sig_line("k1", 1, &env), sig_line("k2", 2, &env));
564        assert!(verify_release(&[key("k1", 1)], TAG, env.as_bytes(), &both_sigs, man.as_bytes()).is_ok());
565        // And one signed only by the next key is unsigned to it.
566        assert_eq!(
567            verify_release(&[key("k1", 1)], TAG, env.as_bytes(), &sig_line("k2", 2, &env), man.as_bytes()),
568            Err(VerifyError::Unsigned)
569        );
570    }
571
572    #[test]
573    fn an_old_signed_envelope_cant_be_replayed_under_another_tag() {
574        let (env, man) = release();
575        let keys = [key("k1", 1)];
576        let sigs = sig_line("k1", 1, &env);
577        assert_eq!(
578            verify_release(&keys, "v0.60.2", env.as_bytes(), &sigs, man.as_bytes()),
579            Err(VerifyError::WrongTag { expected: "v0.60.2".into(), got: TAG.into() })
580        );
581    }
582
583    #[test]
584    fn a_manifest_other_than_the_one_signed_is_refused_however_large_it_grew() {
585        let (env, man) = release();
586        let keys = [key("k1", 1)];
587        let sigs = sig_line("k1", 1, &env);
588        let swapped = man.replace(H1, H2);
589        assert_eq!(verify_release(&keys, TAG, env.as_bytes(), &sigs, swapped.as_bytes()), Err(VerifyError::ManifestMismatch));
590        // A manifest well past the old 4 KB is fine when it is the signed one.
591        let many: Vec<(String, u64, &str)> = (0..200).map(|i| (format!("file-{i}.bin"), 1 + i as u64, H1)).collect();
592        let refs: Vec<(&str, u64, &str)> = many.iter().map(|(n, s, h)| (n.as_str(), *s, *h)).collect();
593        let big = manifest_json(&refs);
594        assert!(big.len() > 8192);
595        let env2 = envelope_json(TAG, &big);
596        assert_eq!(verify_release(&keys, TAG, env2.as_bytes(), &sig_line("k1", 1, &env2), big.as_bytes()).unwrap().files.len(), 200);
597    }
598
599    #[test]
600    fn a_manifest_that_breaks_the_format_is_refused_even_when_signed() {
601        let keys = [key("k1", 1)];
602        let check = |manifest: String| {
603            let env = envelope_json(TAG, &manifest);
604            verify_release(&keys, TAG, env.as_bytes(), &sig_line("k1", 1, &env), manifest.as_bytes())
605        };
606        let ok = |name: &str| check(manifest_json(&[(name, 1, H1)]));
607        assert!(ok("AgentMux-0.60.1-x64-setup.exe").is_ok());
608        for bad in ["../evil.exe", "a/b.exe", "a\\b.exe", ".hidden", "", "has space.exe", "semi;colon.exe", "dots..exe"] {
609            assert!(matches!(ok(bad), Err(VerifyError::Manifest(_))), "{bad:?}");
610        }
611        assert!(matches!(check(manifest_json(&[("a.exe", 0, H1)])), Err(VerifyError::Manifest(_))), "size zero");
612        assert!(matches!(check(manifest_json(&[("a.exe", 1, "ABC")])), Err(VerifyError::Manifest(_))), "bad hash");
613        assert!(matches!(check(manifest_json(&[("a.exe", 1, &"A".repeat(64))])), Err(VerifyError::Manifest(_))), "uppercase hash");
614        assert!(matches!(check(manifest_json(&[("a.exe", 1, H1), ("a.exe", 2, H2)])), Err(VerifyError::Manifest(_))), "twice");
615        assert!(matches!(check(manifest_json(&[])), Err(VerifyError::Manifest(_))), "no files");
616        assert!(matches!(check(manifest_json(&[("a.exe", 1, H1)]).replace(r#""format":1"#, r#""format":2"#)), Err(VerifyError::Manifest(_))));
617        assert!(matches!(check(manifest_json(&[("a.exe", 1, H1)]).replace("0.60.1", "0.60.9")), Err(VerifyError::Manifest(_))), "another version");
618        assert!(matches!(check("not json".into()), Err(VerifyError::Manifest(_))));
619    }
620
621    const D1: &str = "sha256:1111111111111111111111111111111111111111111111111111111111111111";
622    const BASE: &str = "ghcr.io/agentmuxai/agent-base";
623
624    fn with_images(images: &str) -> String {
625        manifest_json(&[("a.exe", 1, H1)]).replace(r#""files":"#, &format!(r#""images":{images},"files":"#))
626    }
627
628    fn verify_with_images(images: &str) -> Result<Manifest, VerifyError> {
629        let manifest = with_images(images);
630        let env = envelope_json(TAG, &manifest);
631        verify_release(&[key("k1", 1)], TAG, env.as_bytes(), &sig_line("k1", 1, &env), manifest.as_bytes())
632    }
633
634    #[test]
635    fn a_release_may_list_the_images_it_built() {
636        let m = verify_with_images(&format!(r#"[{{"name":"agent-base","ref":"{BASE}","digest":"{D1}"}}]"#)).unwrap();
637        assert_eq!(m.image("agent-base").map(|i| (i.reference.as_str(), i.digest.as_str())), Some((BASE, D1)));
638        assert_eq!(m.image("other"), None);
639        // Releases without the field, and with it empty, have none.
640        assert!(release_manifest().images.is_empty());
641        assert!(verify_with_images("[]").unwrap().images.is_empty());
642        // A registry on a port is a repository too.
643        assert!(verify_with_images(&format!(r#"[{{"name":"b","ref":"localhost:5000/team/base","digest":"{D1}"}}]"#)).is_ok());
644    }
645
646    fn release_manifest() -> Manifest {
647        let (env, man) = release();
648        verify_release(&[key("k1", 1)], TAG, env.as_bytes(), &sig_line("k1", 1, &env), man.as_bytes()).unwrap()
649    }
650
651    #[test]
652    fn an_image_that_breaks_the_format_is_refused_even_when_signed() {
653        let bad = |name: &str, reference: &str, digest: &str| {
654            let r = verify_with_images(&format!(r#"[{{"name":"{name}","ref":"{reference}","digest":"{digest}"}}]"#));
655            assert!(matches!(r, Err(VerifyError::Manifest(_))), "{name} {reference} {digest}: {r:?}");
656        };
657        for digest in ["", "sha256:abc", "md5:1111111111111111111111111111111111111111111111111111111111111111", &D1.replace("sha256:", ""), &format!("{D1}0"), &D1.replace('1', "A")] {
658            bad("agent-base", BASE, digest);
659        }
660        for name in ["", "Agent-Base", "agent base", "../x", "-x", &"a".repeat(65)] {
661            bad(name, BASE, D1);
662        }
663        for reference in ["", "agent-base", "https://ghcr.io/x/y", "ghcr.io/x/y:1.0", "ghcr.io/x/y@sha256:abc", "ghcr.io//y", "ghcr.io/X/y", "ghcr.io/x/y/", "ghcr.io:/x/y", "ghcr.io:99999999/x/y", "ghcr.io/../y"] {
664            bad("agent-base", reference, D1);
665        }
666        let twice = format!(r#"[{{"name":"agent-base","ref":"{BASE}","digest":"{D1}"}},{{"name":"agent-base","ref":"{BASE}","digest":"{D1}"}}]"#);
667        assert!(matches!(verify_with_images(&twice), Err(VerifyError::Manifest(_))), "twice");
668        let many: Vec<String> = (0..17).map(|i| format!(r#"{{"name":"i{i}","ref":"{BASE}","digest":"{D1}"}}"#)).collect();
669        assert!(matches!(verify_with_images(&format!("[{}]", many.join(","))), Err(VerifyError::Manifest(_))), "too many");
670    }
671
672    #[test]
673    fn an_envelope_that_breaks_the_format_is_refused_even_when_signed() {
674        let keys = [key("k1", 1)];
675        let (_, man) = release();
676        let sha = hex(&Sha256::digest(man.as_bytes()));
677        let check = |env: String| verify_release(&keys, TAG, env.as_bytes(), &sig_line("k1", 1, &env), man.as_bytes());
678        let good = format!(r#"{{"format":1,"tag":"{TAG}","manifest_sha256":"{sha}","created_at":"x"}}"#);
679        assert!(check(good.clone()).is_ok());
680        assert!(matches!(check(good.replace(r#""format":1"#, r#""format":2"#)), Err(VerifyError::Envelope(_))));
681        assert!(matches!(check(good.replace(&sha, "abc")), Err(VerifyError::Envelope(_))));
682        assert!(matches!(check("{}".into()), Err(VerifyError::Envelope(_))));
683        let huge = format!(r#"{{"format":1,"tag":"{TAG}","manifest_sha256":"{sha}","created_at":"{}"}}"#, "x".repeat(5000));
684        assert!(matches!(check(huge), Err(VerifyError::Envelope(_))), "an envelope is small by definition");
685    }
686
687    // A release as `scripts/release-manifest.mjs` makes it (build, then sign-key with a
688    // local key whose seed is thirty-two 7s), copied here byte for byte: the script
689    // that signs in the release workflow and this code that checks in the app agree
690    // on every byte, or this fails. The same release is built and checked on the
691    // script's side in `scripts/release-manifest.test.mjs`.
692    #[test]
693    fn a_release_made_by_the_script_verifies() {
694        const PUBLIC_KEY_B64: &str = "6kpsY+KcUgq+9VB7Ey7F+ZVHdq6+vnuSQh7qaRRG0iw=";
695        const SIGNATURES: &str = "k1 oGZeVKdahQJP1mqd964PNT7Fie6IbSoUMkDXrmi1QbUVn947HuHtRZNRJt36L22rcAkLPGRWolco8DB2AZXZCw==
696";
697        const ENVELOPE: &str = "{
698  \"format\": 1,
699  \"tag\": \"v0.60.1\",
700  \"manifest_sha256\": \"8a83f0bb7ce99e7537b872b55d6e688da6713ebd078b0dd88c740b1a3c5809eb\",
701  \"created_at\": \"2026-10-25T12:00:00Z\"
702}
703";
704        const MANIFEST: &str = "{
705  \"format\": 1,
706  \"version\": \"0.60.1\",
707  \"tag\": \"v0.60.1\",
708  \"files\": [
709    {
710      \"name\": \"AgentMux-0.60.1-x64-setup.exe\",
711      \"size\": 100,
712      \"sha256\": \"8fb6d5f37e8055ce720bd0b1d56587f88c0071f285966ba17e72b2b12672aa73\"
713    },
714    {
715      \"name\": \"agentmux-0.60.1-x64-portable.7z\",
716      \"size\": 50,
717      \"sha256\": \"01e782826ae5182220bd6158f883d01ceb1bce659dc020e7c511f802a9aa7737\"
718    }
719  ]
720}
721";
722        let public: [u8; 32] = BASE64.decode(PUBLIC_KEY_B64).unwrap().try_into().unwrap();
723        let keys = [UpdateKey { id: "k1", public }];
724        let m = verify_release(&keys, "v0.60.1", ENVELOPE.as_bytes(), SIGNATURES, MANIFEST.as_bytes()).unwrap();
725        assert_eq!(m.files.len(), 2);
726        assert_eq!(m.file("agentmux-0.60.1-x64-portable.7z").map(|f| f.size), Some(50));
727        // One flipped byte anywhere is refused.
728        let flipped = MANIFEST.replace("\"size\": 50", "\"size\": 51");
729        assert_eq!(verify_release(&keys, "v0.60.1", ENVELOPE.as_bytes(), SIGNATURES, flipped.as_bytes()), Err(VerifyError::ManifestMismatch));
730    }
731
732    // A release that lists an image, as `scripts/release-manifest.mjs build --image` makes it and
733    // signs it with the same seed-7 test key, copied byte for byte.
734    #[test]
735    fn a_release_with_an_image_made_by_the_script_verifies() {
736        const PUBLIC_KEY_B64: &str = "6kpsY+KcUgq+9VB7Ey7F+ZVHdq6+vnuSQh7qaRRG0iw=";
737        const SIGNATURES: &str = "k1 VQMuETqO/U3nRMhmcdyeH7AWC+QHUDbC8fRLumEwsmfzvQepLBcKX9J75BFw4V9p1/EowJDUvkHpZjQTTSpXCw==
738";
739        const ENVELOPE: &str = "{
740  \"format\": 1,
741  \"tag\": \"v0.60.1\",
742  \"manifest_sha256\": \"56cea05f9aa7276f353e91c7748af2ad7a6631873d07a2a7d637e6f646883449\",
743  \"created_at\": \"2026-10-25T12:00:00Z\"
744}
745";
746        const MANIFEST: &str = "{
747  \"format\": 1,
748  \"version\": \"0.60.1\",
749  \"tag\": \"v0.60.1\",
750  \"files\": [
751    {
752      \"name\": \"AgentMux-0.60.1-x64-setup.exe\",
753      \"size\": 5,
754      \"sha256\": \"8fb6d5f37e8055ce720bd0b1d56587f88c0071f285966ba17e72b2b12672aa73\"
755    },
756    {
757      \"name\": \"agentmux-0.60.1-x64-portable.7z\",
758      \"size\": 8,
759      \"sha256\": \"01e782826ae5182220bd6158f883d01ceb1bce659dc020e7c511f802a9aa7737\"
760    }
761  ],
762  \"images\": [
763    {
764      \"name\": \"agent-base\",
765      \"ref\": \"ghcr.io/agentmuxai/agent-base\",
766      \"digest\": \"sha256:abababababababababababababababababababababababababababababababab\"
767    }
768  ]
769}
770";
771        let public: [u8; 32] = BASE64.decode(PUBLIC_KEY_B64).unwrap().try_into().unwrap();
772        let keys = [UpdateKey { id: "k1", public }];
773        let m = verify_release(&keys, "v0.60.1", ENVELOPE.as_bytes(), SIGNATURES, MANIFEST.as_bytes()).unwrap();
774        assert_eq!(m.files.len(), 2);
775        assert_eq!(m.image("agent-base").map(|i| (i.reference.as_str(), i.digest.as_str())), Some((BASE, &*format!("sha256:{}", "ab".repeat(32)))));
776        // The digest is covered: one byte changed after signing is refused.
777        let swapped = MANIFEST.replace("abab", "abac");
778        assert_eq!(verify_release(&keys, "v0.60.1", ENVELOPE.as_bytes(), SIGNATURES, swapped.as_bytes()), Err(VerifyError::ManifestMismatch));
779    }
780
781    // The release workflow reads `update-keys.json` to check what it signed; the app
782    // pins `UPDATE_KEYS`. They are the same keys or the workflow checks the wrong thing.
783    #[test]
784    fn the_keys_file_the_workflow_reads_is_the_keys_the_app_pins() {
785        #[derive(Deserialize)]
786        struct File {
787            keys: Vec<FileKey>,
788        }
789        #[derive(Deserialize)]
790        struct FileKey {
791            id: String,
792            public_key: String,
793        }
794        let file: File = serde_json::from_str(include_str!("../update-keys.json")).unwrap();
795        assert_eq!(file.keys.len(), UPDATE_KEYS.len());
796        for (f, k) in file.keys.iter().zip(UPDATE_KEYS) {
797            assert_eq!(f.id, k.id);
798            assert_eq!(BASE64.decode(&f.public_key).unwrap(), k.public);
799        }
800    }
801
802    #[test]
803    fn hex_is_lowercase_and_padded() {
804        assert_eq!(hex(&[0, 15, 255]), "000fff");
805    }
806
807    #[test]
808    fn the_files_are_named_as_the_release_script_publishes_them() {
809        let (e, s, m) = file_names("0.60.1");
810        assert_eq!((e.as_str(), s.as_str(), m.as_str()), ("AgentMux-0.60.1-envelope.json", "AgentMux-0.60.1-envelope.json.sig", "AgentMux-0.60.1-manifest.json"));
811    }
812
813    #[test]
814    fn a_verified_release_is_downloaded() {
815        assert_eq!(decide("0.60.4", &Outcome::Verified), Ok(()));
816    }
817
818    #[test]
819    fn an_unsigned_release_before_the_first_signed_one_is_downloaded_as_before() {
820        assert_eq!(decide("0.59.40", &Outcome::Unsigned), Ok(()));
821        assert_eq!(decide("v0.60.3", &Outcome::Unsigned), Ok(()));
822    }
823
824    #[test]
825    fn an_unsigned_release_from_the_first_signed_one_on_is_refused() {
826        for v in ["0.60.4", "0.60.5", "0.61.0", "1.0.0"] {
827            let e = decide(v, &Outcome::Unsigned).unwrap_err();
828            assert!(e.contains("wasn't signed") && e.contains("release page"), "{v}: {e}");
829        }
830        // A version that can't be read is not trusted to be an old one.
831        assert!(decide("nightly", &Outcome::Unsigned).is_err());
832    }
833
834    #[test]
835    fn a_bad_signature_or_a_disagreement_is_refused_with_the_signature_message() {
836        for o in [Outcome::Failed("x".into()), Outcome::Disagrees("y".into())] {
837            let e = decide("0.60.4", &o).unwrap_err();
838            assert!(e.contains("The signature on v0.60.4 doesn't match") && e.contains("tell the AgentMux team"), "{e}");
839        }
840    }
841
842    #[test]
843    fn a_release_without_a_file_for_this_install_and_an_unreachable_check_are_refused_plainly() {
844        assert_eq!(decide("0.60.4", &Outcome::NotListed("z".into())).unwrap_err(), "v0.60.4 has no file for this kind of install.");
845        let e = decide("0.60.4", &Outcome::Unreachable("GitHub didn't answer".into())).unwrap_err();
846        assert!(e.contains("Couldn't check the signature of v0.60.4") && e.contains("GitHub didn't answer") && e.contains("Try again"), "{e}");
847    }
848
849    #[test]
850    fn the_first_signed_release_is_the_one_the_pipeline_first_signed() {
851        assert_eq!(FIRST_SIGNED, (0, 60, 4));
852    }
853
854    #[test]
855    fn a_version_is_read_down_to_its_three_numbers() {
856        assert_eq!(version_core("0.59.100"), Some((0, 59, 100)));
857        assert_eq!(version_core("v1.2.3+g1a2b"), Some((1, 2, 3)));
858        assert_eq!(version_core("1.2"), None);
859        assert_eq!(version_core("1.2.3.4"), None);
860    }
861
862    #[test]
863    fn a_release_is_judged_by_the_name_size_and_hash_of_the_file_it_signs() {
864        let k = key("k1", 7);
865        let hash = "8fb6d5f37e8055ce720bd0b1d56587f88c0071f285966ba17e72b2b12672aa73";
866        let manifest = manifest_json(&[("AgentMux_0.60.1_amd64.deb", 100, hash)]);
867        let envelope = envelope_json(TAG, &manifest);
868        let sig = sig_line("k1", 7, &envelope);
869        let judged = |name: &str, size: u64, sha: &str| judge_file(&[k], TAG, Some((envelope.as_bytes(), sig.as_str(), manifest.as_bytes())), name, size, sha);
870        assert_eq!(judged("AgentMux_0.60.1_amd64.deb", 100, hash), Outcome::Verified);
871        assert!(matches!(judged("AgentMux_0.60.1_amd64.deb", 101, hash), Outcome::Disagrees(_)));
872        assert!(matches!(judged("AgentMux_0.60.1_amd64.deb", 100, &"0".repeat(64)), Outcome::Disagrees(_)));
873        assert!(matches!(judged("AgentMux-0.60.1-1.x86_64.rpm", 100, hash), Outcome::NotListed(_)));
874        assert_eq!(judge_file(&[k], TAG, None, "x", 1, hash), Outcome::Unsigned);
875    }
876
877    // A release that carries an `upgrade` object, as `scripts/release-manifest.mjs build` makes it (the floor from
878    // UPGRADE_FLOOR, and `--shared-store-changed true`), signed with the same seed-7 test key, copied byte for byte.
879    const UPGRADE_PUBLIC_KEY_B64: &str = "6kpsY+KcUgq+9VB7Ey7F+ZVHdq6+vnuSQh7qaRRG0iw=";
880    const UPGRADE_SIGNATURES: &str = "k1 wf8ru0NTcp3G7GCZff/1dX9O2SEd7nSHuacY058sSrcQHFkpidkkwklrjqb1hJOr61diLh/2rRGg32Gnn5whDw==
881";
882    const UPGRADE_ENVELOPE: &str = "{
883  \"format\": 1,
884  \"tag\": \"v0.60.1\",
885  \"manifest_sha256\": \"2038d37391a59d7b22bb0bee89eb31b6f94df10d4730389b79808fb32a52272f\",
886  \"created_at\": \"2026-10-25T12:00:00Z\"
887}
888";
889    const UPGRADE_MANIFEST: &str = "{
890  \"format\": 1,
891  \"version\": \"0.60.1\",
892  \"tag\": \"v0.60.1\",
893  \"files\": [
894    {
895      \"name\": \"AgentMux-0.60.1-x64-setup.exe\",
896      \"size\": 5,
897      \"sha256\": \"8fb6d5f37e8055ce720bd0b1d56587f88c0071f285966ba17e72b2b12672aa73\"
898    },
899    {
900      \"name\": \"agentmux-0.60.1-x64-portable.7z\",
901      \"size\": 8,
902      \"sha256\": \"01e782826ae5182220bd6158f883d01ceb1bce659dc020e7c511f802a9aa7737\"
903    }
904  ],
905  \"upgrade\": {
906    \"floor\": \"0.55.0\",
907    \"shared_store_changed\": true
908  }
909}
910";
911
912    fn upgrade_keys() -> [UpdateKey; 1] {
913        let public: [u8; 32] = BASE64.decode(UPGRADE_PUBLIC_KEY_B64).unwrap().try_into().unwrap();
914        [UpdateKey { id: "k1", public }]
915    }
916
917    #[test]
918    fn a_release_with_an_upgrade_object_made_by_the_script_verifies_and_gives_its_floor() {
919        let m = verify_release(&upgrade_keys(), "v0.60.1", UPGRADE_ENVELOPE.as_bytes(), UPGRADE_SIGNATURES, UPGRADE_MANIFEST.as_bytes()).unwrap();
920        assert_eq!(m.files.len(), 2);
921        assert_eq!(m.signed_floor(), SignedFloor::Valid("0.55.0".into()));
922        assert_eq!(m.shared_store_changed(), SharedStoreChanged::Known(true));
923    }
924
925    #[test]
926    fn a_floor_changed_after_signing_is_refused() {
927        // The floor is covered: the manifest's hash is in the signed envelope, so one changed byte fails verification.
928        let lowered = UPGRADE_MANIFEST.replace("\"floor\": \"0.55.0\"", "\"floor\": \"0.40.0\"");
929        assert_ne!(lowered, UPGRADE_MANIFEST);
930        assert_eq!(verify_release(&upgrade_keys(), "v0.60.1", UPGRADE_ENVELOPE.as_bytes(), UPGRADE_SIGNATURES, lowered.as_bytes()), Err(VerifyError::ManifestMismatch));
931        let stripped = UPGRADE_MANIFEST.replace("\"shared_store_changed\": true", "\"shared_store_changed\": false");
932        assert_eq!(verify_release(&upgrade_keys(), "v0.60.1", UPGRADE_ENVELOPE.as_bytes(), UPGRADE_SIGNATURES, stripped.as_bytes()), Err(VerifyError::ManifestMismatch));
933    }
934
935    #[test]
936    fn an_app_that_does_not_know_the_field_reads_the_same_release() {
937        // The manifest and envelope shapes as they were before `upgrade` existed, frozen here: they ignore what they do not
938        // know, so an installed app keeps verifying a release that carries it.
939        #[derive(Deserialize)]
940        #[allow(dead_code)]
941        struct OldManifest {
942            format: u32,
943            version: String,
944            tag: String,
945            files: Vec<ManifestFile>,
946            #[serde(default)]
947            images: Vec<ManifestImage>,
948        }
949        let old: OldManifest = serde_json::from_str(UPGRADE_MANIFEST).unwrap();
950        assert_eq!((old.format, old.version.as_str(), old.tag.as_str(), old.files.len(), old.images.len()), (1, "0.60.1", "v0.60.1", 2, 0));
951        let _: Envelope = serde_json::from_str(UPGRADE_ENVELOPE).unwrap();
952    }
953
954    fn manifest_with_upgrade(upgrade: &str) -> Manifest {
955        let text = format!(r#"{{"format":1,"version":"0.60.1","tag":"v0.60.1","files":[{{"name":"a.exe","size":1,"sha256":"{}"}}]{upgrade}}}"#, "0".repeat(64));
956        serde_json::from_str(&text).unwrap()
957    }
958
959    #[test]
960    fn the_signed_floor_is_valid_only_as_a_plain_version_not_above_the_release() {
961        let floor = |u: &str| manifest_with_upgrade(&format!(r#","upgrade":{u}"#)).signed_floor();
962        assert_eq!(manifest_with_upgrade("").signed_floor(), SignedFloor::Absent);
963        assert_eq!(floor(r#"{"floor":"0.55.0"}"#), SignedFloor::Valid("0.55.0".into()));
964        // At the release's own version is allowed; one above it is not.
965        assert_eq!(floor(r#"{"floor":"0.60.1"}"#), SignedFloor::Valid("0.60.1".into()));
966        assert!(matches!(floor(r#"{"floor":"0.60.2"}"#), SignedFloor::Unusable(why) if why.contains("above the release")));
967        for bad in [r#"{"floor":"soon"}"#, r#"{"floor":"0.55"}"#, r#"{"floor":"v0.55.0"}"#, r#"{"floor":"0.55.0-rc1"}"#, r#"{"floor":""}"#, r#"{"floor":55}"#, r#"{"floor":null}"#, r#"{"floor":["0.55.0"]}"#, r#""0.55.0""#, "5", "[]", "true"] {
968            assert!(matches!(floor(bad), SignedFloor::Unusable(_)), "{bad}");
969        }
970        // An object with no floor says nothing about it; a field this build does not know is ignored.
971        assert_eq!(floor(r#"{"shared_store_changed":true}"#), SignedFloor::Absent);
972        assert_eq!(floor(r#"{"floor":"0.55.0","future":{"a":1}}"#), SignedFloor::Valid("0.55.0".into()));
973    }
974
975    #[test]
976    fn shared_store_changed_is_true_false_or_absent_and_never_touches_the_floor() {
977        let read = |u: &str| manifest_with_upgrade(&format!(r#","upgrade":{u}"#));
978        assert_eq!(manifest_with_upgrade("").shared_store_changed(), SharedStoreChanged::Absent);
979        assert_eq!(read(r#"{"floor":"0.55.0"}"#).shared_store_changed(), SharedStoreChanged::Absent);
980        assert_eq!(read(r#"{"floor":"0.55.0","shared_store_changed":true}"#).shared_store_changed(), SharedStoreChanged::Known(true));
981        assert_eq!(read(r#"{"floor":"0.55.0","shared_store_changed":false}"#).shared_store_changed(), SharedStoreChanged::Known(false));
982        for bad in [r#""yes""#, "1", "null", "[]"] {
983            let m = read(&format!(r#"{{"floor":"0.55.0","shared_store_changed":{bad}}}"#));
984            assert_eq!(m.shared_store_changed(), SharedStoreChanged::Unusable, "{bad}");
985            // A bad flag never changes the floor.
986            assert_eq!(m.signed_floor(), SignedFloor::Valid("0.55.0".into()), "{bad}");
987        }
988        // And a bad floor never changes the flag.
989        let m = read(r#"{"floor":"soon","shared_store_changed":true}"#);
990        assert_eq!(m.shared_store_changed(), SharedStoreChanged::Known(true));
991        assert!(matches!(m.signed_floor(), SignedFloor::Unusable(_)));
992    }
993
994    #[test]
995    fn a_bad_floor_does_not_fail_the_verification_of_the_files() {
996        let manifest = UPGRADE_MANIFEST.replace("\"floor\": \"0.55.0\"", "\"floor\": \"soon\"");
997        let envelope = UPGRADE_ENVELOPE.replace("2038d37391a59d7b22bb0bee89eb31b6f94df10d4730389b79808fb32a52272f", &hex(&Sha256::digest(manifest.as_bytes())));
998        // Signed by the test key (seed 7) the way a pipeline bug could have signed it.
999        let sig_line = format!("k1 {}", BASE64.encode(ed25519_dalek::SigningKey::from_bytes(&[7u8; 32]).sign(envelope.as_bytes()).to_bytes()));
1000        let m = verify_release(&upgrade_keys(), "v0.60.1", envelope.as_bytes(), &sig_line, manifest.as_bytes()).unwrap();
1001        assert!(matches!(m.signed_floor(), SignedFloor::Unusable(_)));
1002        assert_eq!(m.file("AgentMux-0.60.1-x64-setup.exe").map(|f| f.size), Some(5));
1003    }
1004
1005    #[test]
1006    fn a_plain_version_is_three_numbers_and_nothing_else() {
1007        for ok in ["0.55.0", "1.2.3", "10.20.300"] {
1008            assert!(is_plain_version(ok), "{ok}");
1009        }
1010        for bad in ["", "1", "1.2", "1.2.3.4", "v1.2.3", "1.2.3-rc1", "1.2.x", " 1.2.3", "1.2.3\n", "1..3", "1234567890.1.1"] {
1011            assert!(!is_plain_version(bad), "{bad:?}");
1012        }
1013    }
1014}