Skip to main content

agentmux_srv_core/backend/update/
signed_source.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A second source for the update check, for when GitHub's API limits this computer or fails (#47813).
5//!
6//! The check learns which release is latest from the `releases/latest` page, which the API's limit doesn't
7//! touch, and asks the API for its files and checksums. While the API refuses, a release was known by its tag
8//! alone and could not be downloaded. This asks the release's own download address instead: the signed
9//! envelope, its signature and the manifest (`AgentMux-<version>-envelope.json`, `.sig`, `-manifest.json`),
10//! which are not part of the API's limit. Only GitHub's release-download address is used as a source.
11//!
12//! What it guarantees (each has a test below):
13//! - **Nothing older or equal is offered.** The envelope's version must be the tag the check found, and the tag
14//!   must be strictly newer than the running build. An equal or older tag is "nothing new": not an error, not
15//!   a download, and nothing is fetched for it.
16//! - **One verifier.** The file list is read from a manifest that passes the downloader's own check
17//!   (`signature::judge` and `decide`, with the same keys and signature rules, a second signature included),
18//!   so the check can't offer a file the download would refuse. Where the two could disagree on one input,
19//!   a test fails.
20//! - **The release's own upgrade floor, from what the pipeline signed.** A manifest may carry an `upgrade.floor`
21//!   (`SPEC_UPGRADE_FLOOR_IN_SIGNED_MANIFEST`). When it carries a usable one, the floor used is the higher of that
22//!   and this build's own (`BUILD_FLOOR`), and neither the notes' floor line nor the raw `UPGRADE_FLOOR` file is
23//!   asked for. A manifest with none (or an unusable one, logged once per tag) falls back to what was done before:
24//!   the repo's `UPGRADE_FLOOR` file at the release's tag, which the API's answer vouches for no better (GitHub
25//!   over TLS, unsigned). The floor used is then the higher of this build's own and that file's, so a read can only
26//!   block a download, never allow one. A tag that isn't plainly `v<digits>.<digits>.<digits>` builds no address,
27//!   and a file that can't be read or isn't a plain version is no answer.
28//! - **Bounded.** It runs only when the API is limited or failed. A result is kept for its tag, a failed try is
29//!   not repeated before the API's limit ends (and never within [`MIN_RETRY_GAP_MS`]), and a manifest or floor
30//!   that fails is logged once per tag.
31//!
32//! An unsigned, unverifiable or unreachable answer is no answer: the release stays known by its tag.
33
34use agentmux_common::update_manifest::{verify_release, version_core, SignedFloor, UpdateKey, MAX_ENVELOPE_BYTES, MAX_MANIFEST_BYTES, UPDATE_KEYS};
35use parking_lot::Mutex;
36
37use crate::backend::update::check::{Release, ReleaseAsset};
38use crate::backend::update::download::RELEASE_DOWNLOAD_PREFIX;
39use crate::backend::update::install::InstallKind;
40use crate::backend::update::signature::{decide, fetch_small, file_names, judge};
41
42/// The shortest gap before a failed try for one release is repeated, whatever the API says about its limit.
43pub(crate) const MIN_RETRY_GAP_MS: i64 = 5 * 60_000;
44
45/// What the second source made of a release.
46#[derive(Debug)]
47pub(crate) enum Answer {
48    /// The tag isn't newer than the running build: nothing new. Nothing was fetched for it.
49    NothingNew,
50    /// A release whose file list was read from a manifest that verified.
51    Release(Box<Release>),
52    /// No answer, and why.
53    NoAnswer(String),
54}
55
56/// Whether `tag` is strictly newer than the running build `current`. Versions that don't parse are never newer.
57pub(crate) fn newer_than(tag: &str, current: &str) -> bool {
58    matches!((version_core(tag), version_core(current)), (Some(t), Some(c)) if t > c)
59}
60
61/// Where `tag`'s upgrade floor is read: the repo's `UPGRADE_FLOOR` at that tag.
62const FLOOR_FILE_PREFIX: &str = "https://raw.githubusercontent.com/agentmuxai/agentmux/";
63
64/// A floor file is a version and a newline; anything longer is not one.
65const MAX_FLOOR_BYTES: usize = 64;
66
67/// `<digits>.<digits>.<digits>` and nothing else.
68fn plain_version(s: &str) -> bool {
69    let mut parts = s.split('.');
70    let number = |p: Option<&str>| p.is_some_and(|p| !p.is_empty() && p.len() <= 9 && p.bytes().all(|b| b.is_ascii_digit()));
71    number(parts.next()) && number(parts.next()) && number(parts.next()) && parts.next().is_none()
72}
73
74/// The address of the floor file at `tag`, only for a tag of exactly `v<digits>.<digits>.<digits>`.
75pub(crate) fn floor_url(tag: &str) -> Option<String> {
76    plain_version(tag.strip_prefix('v')?).then(|| format!("{FLOOR_FILE_PREFIX}{tag}/UPGRADE_FLOOR"))
77}
78
79/// The floor to use for a release: the higher of this build's own (`build`) and what the floor file at the
80/// release's tag says (`file`: `Ok(None)` when there is no such file). A file that can't be read, isn't there or
81/// isn't a plain version is an error: no floor, so no answer. A lower file never lowers the build's floor.
82pub(crate) fn floor_for(build: Option<&str>, file: Result<Option<Vec<u8>>, String>) -> Result<String, String> {
83    let bytes = file.map_err(|e| format!("the release's upgrade floor couldn't be read: {e}"))?;
84    let bytes = bytes.ok_or_else(|| "the release has no upgrade floor file at its tag".to_string())?;
85    let read = std::str::from_utf8(&bytes).map(str::trim).ok().filter(|t| plain_version(t));
86    let Some(read) = read else { return Err("the release's upgrade floor isn't a version".to_string()) };
87    Ok(match build.filter(|b| version_core(b) >= version_core(read)) {
88        Some(build) => build.to_string(),
89        None => read.to_string(),
90    })
91}
92
93/// The floor in force when the verified manifest carries a usable one: the higher of that and this build's own
94/// (`build`), which a signed floor never lowers. `None` when the manifest has none that can be used: the floor is then
95/// read the way it was before the manifest carried one ([`floor_for`]).
96pub(crate) fn signed_floor_in_force(build: Option<&str>, signed: &SignedFloor) -> Option<String> {
97    agentmux_common::update_manifest::signed_floor_in_force(build, signed)
98}
99
100/// The floor for a release: the signed one when the manifest carries a usable one, else what the floor file at the
101/// release's tag says. `read_file` is asked only in the second case, so a signed floor never needs, and never reads,
102/// the unsigned file.
103pub(crate) async fn resolve_floor<F, Fut>(build: Option<&str>, signed: &SignedFloor, read_file: F) -> Result<String, String>
104where
105    F: FnOnce() -> Fut,
106    Fut: std::future::Future<Output = Result<Option<Vec<u8>>, String>>,
107{
108    match signed_floor_in_force(build, signed) {
109        Some(floor) => Ok(floor),
110        None => floor_for(build, read_file().await),
111    }
112}
113
114/// What the manifest at `fetched` signs about the upgrade floor, once it verifies; `Absent` for anything that does not
115/// (no files, a fetch that failed, a manifest that doesn't verify: those are the verdict's to report).
116pub(crate) fn signed_floor_of(keys: &[UpdateKey], tag: &str, fetched: &Fetched) -> SignedFloor {
117    floor_read(keys, tag, fetched).0
118}
119
120/// [`signed_floor_of`], and why when signed files were fetched and did not verify. That is not the ordinary case (a
121/// release with no signed files is, and a fetch that failed is a network matter): it is what a tampered or mis-signed
122/// release looks like, so the caller says so, once per tag. The floor is `Absent` then, as before.
123pub(crate) fn floor_read(keys: &[UpdateKey], tag: &str, fetched: &Fetched) -> (SignedFloor, Option<String>) {
124    match fetched {
125        Ok(Some((e, s, m))) => match verify_release(keys, tag, e, s, m) {
126            Ok(manifest) => (manifest.signed_floor(), None),
127            Err(why) => (SignedFloor::Absent, Some(why.to_string())),
128        },
129        _ => (SignedFloor::Absent, None),
130    }
131}
132
133/// The decision for `tag`, given what was fetched (`None`: the release has no signed manifest) and the
134/// install it is for. `floor` is the oldest version known to upgrade in place, which a manifest doesn't carry.
135pub(crate) fn answer(
136    keys: &[UpdateKey],
137    tag: &str,
138    current: &str,
139    kind: &InstallKind,
140    arch: &str,
141    floor: Option<&str>,
142    fetched: Option<(&[u8], &str, &[u8])>,
143) -> Answer {
144    if !newer_than(tag, current) {
145        return Answer::NothingNew;
146    }
147    let version = tag.trim_start_matches('v');
148    let Some(fetched) = fetched else {
149        return Answer::NoAnswer("the release has no signed manifest".into());
150    };
151    let manifest = match verify_release(keys, tag, fetched.0, fetched.1, fetched.2) {
152        Ok(m) => m,
153        Err(e) => return Answer::NoAnswer(e.to_string()),
154    };
155    let file = kind.asset_name(version, arch).and_then(|name| manifest.file(&name).cloned());
156    let Some(file) = file else {
157        // A genuine release with nothing for this computer: say so rather than "not available yet".
158        return Answer::Release(Box::new(Release::from_signed(tag, None, floor)));
159    };
160    let asset = ReleaseAsset { url: format!("{RELEASE_DOWNLOAD_PREFIX}{tag}/{}", file.name), name: file.name, size: file.size, sha256: file.sha256 };
161    // The downloader's own decision on the same file, so the two can't differ.
162    if let Err(why) = decide(version, &judge(keys, tag, Some(fetched), &asset)) {
163        return Answer::NoAnswer(why);
164    }
165    Answer::Release(Box::new(Release::from_signed(tag, Some(&asset), floor)))
166}
167
168/// What was fetched for a release: its three signed files (`Ok(None)`: it has none), or why not.
169type Fetched = Result<Option<(Vec<u8>, String, Vec<u8>)>, String>;
170
171/// The answer for `tag` from its floor (or why there is none) and what was fetched: no floor is no answer,
172/// whatever the signed files say.
173fn verdict(keys: &[UpdateKey], tag: &str, current: &str, kind: &InstallKind, arch: &str, floor: &Result<String, String>, fetched: &Fetched) -> Answer {
174    match (floor, fetched) {
175        (Err(why), _) => Answer::NoAnswer(why.clone()),
176        (Ok(floor), Ok(Some((e, s, m)))) => answer(keys, tag, current, kind, arch, Some(floor), Some((e, s, m))),
177        (Ok(_), Ok(None)) => Answer::NoAnswer("the release has no signed manifest at its download address".into()),
178        (Ok(_), Err(e)) => Answer::NoAnswer(e.clone()),
179    }
180}
181
182/// What is kept about a release's tag between checks.
183#[derive(Debug, Clone)]
184struct Tried {
185    tag: String,
186    /// A release that verified: kept for this tag (a signed release's files do not change).
187    found: Option<Release>,
188    /// A failed try is not repeated before this time (unix ms).
189    not_before_ms: i64,
190    /// The failure was logged already.
191    logged: bool,
192}
193
194static TRIED: Mutex<Option<Tried>> = Mutex::new(None);
195
196/// What to do about `tag` now.
197#[derive(Debug, PartialEq, Eq)]
198pub(crate) enum Step {
199    /// A verified release is held for this tag.
200    Held,
201    /// A try failed lately: wait.
202    Wait,
203    /// Ask.
204    Ask,
205}
206
207fn step(tried: Option<&Tried>, tag: &str, now_ms: i64) -> Step {
208    match tried.filter(|t| t.tag == tag) {
209        Some(t) if t.found.is_some() => Step::Held,
210        Some(t) if now_ms < t.not_before_ms => Step::Wait,
211        _ => Step::Ask,
212    }
213}
214
215/// When a failed try for a release may be repeated: not before the API's limit ends, and never sooner than
216/// [`MIN_RETRY_GAP_MS`] from now.
217pub(crate) fn retry_not_before(limited_until_ms: i64, now_ms: i64) -> i64 {
218    limited_until_ms.max(now_ms + MIN_RETRY_GAP_MS)
219}
220
221/// One small file of a release, by name; `Ok(None)` when it is not there (404).
222async fn get(client: &reqwest::Client, dir: &str, name: &str, cap: usize) -> Result<Option<Vec<u8>>, String> {
223    fetch_small(client, &format!("{dir}{name}"), cap).await.map_err(|e| e.to_string())
224}
225
226/// The three signed files of `tag`'s release, from its download address. `Ok(None)`: it has none (404).
227async fn fetch(client: &reqwest::Client, tag: &str) -> Fetched {
228    let (envelope, signature, manifest) = file_names(tag.trim_start_matches('v'));
229    let dir = format!("{RELEASE_DOWNLOAD_PREFIX}{tag}/");
230    let Some(envelope) = get(client, &dir, &envelope, MAX_ENVELOPE_BYTES).await? else { return Ok(None) };
231    let Some(signature) = get(client, &dir, &signature, MAX_ENVELOPE_BYTES).await? else { return Ok(None) };
232    let Some(manifest) = get(client, &dir, &manifest, MAX_MANIFEST_BYTES).await? else { return Ok(None) };
233    Ok(Some((envelope, String::from_utf8_lossy(&signature).into_owned(), manifest)))
234}
235
236/// What was learned of a release's signed floor, kept for its tag: a signed release's files do not change, so a manifest
237/// that was read is read once; a failed fetch is not repeated within [`MIN_RETRY_GAP_MS`].
238#[derive(Debug, Clone)]
239struct FloorTried {
240    tag: String,
241    /// The floor the verified manifest carries (`Absent` also for a release with no signed manifest, or one that did not
242    /// verify); `None` while only a fetch that failed is known.
243    floor: Option<SignedFloor>,
244    not_before_ms: i64,
245    logged: bool,
246}
247
248static SIGNED_FLOOR: Mutex<Option<FloorTried>> = Mutex::new(None);
249
250/// The upgrade floor `tag`'s signed manifest carries, for a check that learned the release from GitHub's API: the same
251/// verifier as the download's, asked once per tag. `Absent` when there is none to use (no manifest, one that does not
252/// verify, a fetch that failed): the floor is then what the release notes say, as before.
253pub(crate) async fn signed_floor_for(client: &reqwest::Client, tag: &str, now_ms: i64) -> SignedFloor {
254    let logged_before = {
255        let held = SIGNED_FLOOR.lock();
256        match held.as_ref().filter(|t| t.tag == tag) {
257            Some(t) if t.floor.is_some() => return t.floor.clone().unwrap_or(SignedFloor::Absent),
258            Some(t) if now_ms < t.not_before_ms => return SignedFloor::Absent,
259            Some(t) => t.logged,
260            None => false,
261        }
262    };
263    let fetched = fetch(client, tag).await;
264    let (signed, unverified) = floor_read(UPDATE_KEYS, tag, &fetched);
265    let mut logged = logged_before;
266    if !logged_before {
267        if let Some(why) = &unverified {
268            // A red flag, not the ordinary case: the release's signed files were there and did not verify. The floor falls
269            // back to the notes' (and the download, which verifies the same files, will refuse the release).
270            tracing::warn!(tag, %why, "update check: the release's signed manifest did not verify, so its signed upgrade floor is not used (a tampered or mis-signed release?)");
271            logged = true;
272        } else if let SignedFloor::Unusable(why) = &signed {
273            tracing::warn!(tag, %why, "update check: the release's signed upgrade floor isn't usable; its notes' floor is used");
274            logged = true;
275        }
276    }
277    // A fetch that failed says nothing about the release: try again later. Anything read (or a 404) is kept.
278    let floor = fetched.is_ok().then(|| signed.clone());
279    *SIGNED_FLOOR.lock() = Some(FloorTried { tag: tag.to_string(), floor, not_before_ms: now_ms + MIN_RETRY_GAP_MS, logged });
280    signed
281}
282
283/// What a check gets from the second source.
284pub(crate) enum Got {
285    NothingNew,
286    Release(Release),
287    /// No answer: the release stays known by its tag.
288    None,
289}
290
291/// The release `tag` names, from the signed files at its download address; called only when the API is
292/// limited (until `limited_until_ms`, 0 when it isn't, as when it failed) or failed.
293pub(crate) async fn release_for(
294    client: &reqwest::Client,
295    tag: &str,
296    current: &str,
297    kind: &InstallKind,
298    build_floor: Option<&str>,
299    limited_until_ms: i64,
300    now_ms: i64,
301) -> Got {
302    if !newer_than(tag, current) {
303        return Got::NothingNew;
304    }
305    let logged_before = {
306        let tried = TRIED.lock();
307        match step(tried.as_ref(), tag, now_ms) {
308            Step::Held => return tried.as_ref().and_then(|t| t.found.clone()).map_or(Got::None, Got::Release),
309            Step::Wait => return Got::None,
310            Step::Ask => tried.as_ref().is_some_and(|t| t.tag == tag && t.logged),
311        }
312    };
313    // The signed files first: their floor, when they carry a usable one, is the floor, and the unsigned file is not asked for.
314    let fetched = fetch(client, tag).await;
315    let signed = signed_floor_of(UPDATE_KEYS, tag, &fetched);
316    let floor = resolve_floor(build_floor, &signed, || async {
317        match floor_url(tag) {
318            Some(url) => fetch_small(client, &url, MAX_FLOOR_BYTES).await.map_err(|e| e.to_string()),
319            None => Err(format!("{tag} isn't a plain release tag")),
320        }
321    })
322    .await;
323    let unusable = match &signed {
324        SignedFloor::Unusable(why) if !logged_before => Some(why.clone()),
325        _ => None,
326    };
327    if let Some(why) = &unusable {
328        tracing::warn!(tag, %why, "update check: the release's signed upgrade floor isn't usable; its notes' or floor file's is used");
329    }
330    let logged_before = logged_before || unusable.is_some();
331    let verdict = verdict(UPDATE_KEYS, tag, current, kind, std::env::consts::ARCH, &floor, &fetched);
332    // A manifest that was fetched and did not verify, or a floor that could not be used, is worth a warning,
333    // once for the tag; a release that has no signed files, or one that could not be reached, is the ordinary case.
334    let did_not_verify = matches!(verdict, Answer::NoAnswer(_)) && (floor.is_err() || matches!(fetched, Ok(Some(_))));
335    let mut tried = TRIED.lock();
336    match verdict {
337        Answer::NothingNew => Got::NothingNew,
338        Answer::Release(r) => {
339            *tried = Some(Tried { tag: tag.to_string(), found: Some((*r).clone()), not_before_ms: 0, logged: logged_before });
340            tracing::info!(tag, "update check: the release's files came from its signed manifest (GitHub's API is not answering)");
341            Got::Release(*r)
342        }
343        Answer::NoAnswer(why) => {
344            if did_not_verify && !logged_before {
345                tracing::warn!(tag, %why, "update check: the release's signed manifest or upgrade floor could not be used, so its files are not offered");
346            }
347            *tried = Some(Tried { tag: tag.to_string(), found: None, not_before_ms: retry_not_before(limited_until_ms, now_ms), logged: logged_before || did_not_verify });
348            Got::None
349        }
350    }
351}
352
353#[cfg(test)]
354mod tests {
355    use super::*;
356    use crate::backend::update::signature::fixtures::*;
357
358    const NEWER_THAN_FIXTURE: &str = "0.60.0";
359
360    fn run(keys: &[UpdateKey], tag: &str, current: &str, kind: &InstallKind, fetched: Option<(&[u8], &str, &[u8])>) -> Answer {
361        answer(keys, tag, current, kind, "x86_64", None, fetched)
362    }
363
364    fn released(a: &Answer) -> Option<&Release> {
365        match a {
366            Answer::Release(r) => Some(r),
367            _ => None,
368        }
369    }
370
371    #[test]
372    fn a_tag_equal_to_or_older_than_the_running_build_is_nothing_new_and_a_newer_one_is_a_release() {
373        let kind = InstallKind::WindowsSetup;
374        let f = Some((ENVELOPE.as_bytes(), SIG, MANIFEST.as_bytes()));
375        for current in ["0.60.1", "0.60.2", "0.61.0", "1.0.0"] {
376            assert!(matches!(run(&keys(), "v0.60.1", current, &kind, f), Answer::NothingNew), "{current}");
377        }
378        // Not even a failed fetch matters for one that is not newer: there is nothing to ask for.
379        assert!(matches!(run(&keys(), "v0.60.1", "0.60.1", &kind, None), Answer::NothingNew));
380        assert!(released(&run(&keys(), "v0.60.1", NEWER_THAN_FIXTURE, &kind, f)).is_some());
381        // A version that doesn't parse is never newer.
382        assert!(matches!(run(&keys(), "v0.60.1", "dev", &kind, f), Answer::NothingNew));
383        assert!(matches!(run(&keys(), "latest", "0.60.0", &kind, f), Answer::NothingNew));
384    }
385
386    #[test]
387    fn an_older_signed_release_replayed_under_a_newer_tag_is_no_answer() {
388        let kind = InstallKind::WindowsSetup;
389        let f = Some((ENVELOPE.as_bytes(), SIG, MANIFEST.as_bytes()));
390        // The envelope and manifest are v0.60.1's, signed; the tag found is v0.60.2.
391        match run(&keys(), "v0.60.2", NEWER_THAN_FIXTURE, &kind, f) {
392            Answer::NoAnswer(why) => assert!(why.contains("v0.60.2"), "{why}"),
393            other => panic!("{other:?}"),
394        }
395    }
396
397    #[tokio::test]
398    async fn a_tag_that_is_not_newer_fetches_nothing() {
399        // No network is needed (the client can't reach anything): it must not even try.
400        let client = reqwest::Client::builder().build().unwrap();
401        let got = release_for(&client, "v0.60.1", "0.60.1", &InstallKind::WindowsSetup, None, 0, 1_000).await;
402        assert!(matches!(got, Got::NothingNew));
403        assert!(TRIED.lock().as_ref().map_or(true, |t| t.tag != "v0.60.1"));
404    }
405
406    #[test]
407    fn the_release_it_reads_has_the_signed_file_with_its_checksum_and_the_floor_this_build_knows() {
408        let kind = InstallKind::WindowsSetup;
409        let a = answer(&keys(), "v0.60.1", NEWER_THAN_FIXTURE, &kind, "x86_64", Some("0.55.0"), Some((ENVELOPE.as_bytes(), SIG, MANIFEST.as_bytes())));
410        let status = crate::backend::update::check::status_for_arch(NEWER_THAN_FIXTURE, "stable", released(&a).unwrap(), 1, &kind, "x86_64");
411        assert_eq!(status.state, "available");
412        assert!(status.can_download, "{status:?}");
413        let asset = status.asset.unwrap();
414        assert_eq!(asset.name, "AgentMux-0.60.1-x64-setup.exe");
415        assert_eq!(asset.sha256, SETUP_SHA);
416        assert_eq!(asset.url, format!("{RELEASE_DOWNLOAD_PREFIX}v0.60.1/AgentMux-0.60.1-x64-setup.exe"));
417        // An install older than that floor is sent to it first, as with the API's answer.
418        let old = crate::backend::update::check::status_for_arch("0.50.0", "stable", released(&a).unwrap(), 1, &kind, "x86_64");
419        assert_eq!(old.install_first.as_deref(), Some("0.55.0"));
420        assert!(!old.can_download);
421    }
422
423    #[test]
424    fn a_signed_release_with_no_file_for_this_computer_says_so() {
425        let kind = InstallKind::LinuxAppImage;
426        let a = answer(&keys(), "v0.60.1", NEWER_THAN_FIXTURE, &kind, "x86_64", None, Some((ENVELOPE.as_bytes(), SIG, MANIFEST.as_bytes())));
427        let status = crate::backend::update::check::status_for(NEWER_THAN_FIXTURE, "stable", released(&a).unwrap(), 1, &kind);
428        assert!(!status.can_download && status.asset.is_none());
429        assert_eq!(status.download_blocked.as_deref(), Some("This release has no file for this computer."));
430    }
431
432    /// The same input through the check's reading and through the downloader's own decision (`gate`'s
433    /// `judge` + `decide`) must agree: a release the check offers is one the download accepts, and the
434    /// reverse. Each case is one input the two share.
435    #[test]
436    fn the_check_and_the_downloader_decide_the_same_on_every_input() {
437        let kind = InstallKind::WindowsSetup;
438        let name = "AgentMux-0.60.1-x64-setup.exe";
439        let k2_only = [UpdateKey { id: "k2", public: KEY }];
440        let both = [UpdateKey { id: "k1", public: [9; 32] }, UpdateKey { id: "k2", public: KEY }];
441        let second = format!("k1 AAAA\nk2 {}", SIG.trim_start_matches("k1 "));
442        let second_only = SIG.replacen("k1 ", "k2 ", 1);
443        let tampered_manifest = MANIFEST.replace("\"size\": 100", "\"size\": 101");
444        let other_envelope = ENVELOPE.replace("v0.60.1", "v0.60.2");
445        let cases: Vec<(&str, Vec<UpdateKey>, &str, &str, &str)> = vec![
446            ("good", keys(), "v0.60.1", SIG, MANIFEST),
447            ("a second signature line, the first one not valid", both.to_vec(), "v0.60.1", second.as_str(), MANIFEST),
448            ("only the second key's signature, and that key pinned", k2_only.to_vec(), "v0.60.1", second_only.as_str(), MANIFEST),
449            ("only the second key's signature, key not pinned", keys(), "v0.60.1", second_only.as_str(), MANIFEST),
450            ("another key", vec![UpdateKey { id: "k1", public: [9; 32] }], "v0.60.1", SIG, MANIFEST),
451            ("no signature at all", keys(), "v0.60.1", "", MANIFEST),
452            ("a tampered manifest", keys(), "v0.60.1", SIG, tampered_manifest.as_str()),
453            ("another release's tag", keys(), "v0.60.2", SIG, MANIFEST),
454            ("an envelope for another tag", keys(), "v0.60.1", SIG, MANIFEST),
455        ];
456        for (label, keys, tag, sig, manifest) in cases {
457            let envelope = if label == "an envelope for another tag" { other_envelope.as_str() } else { ENVELOPE };
458            let fetched = Some((envelope.as_bytes(), sig, manifest.as_bytes()));
459            let checked = run(&keys, tag, NEWER_THAN_FIXTURE, &kind, fetched);
460            // What the downloader does with that file from that release.
461            let asset = ReleaseAsset { name: name.into(), size: 100, url: format!("{RELEASE_DOWNLOAD_PREFIX}{tag}/{name}"), sha256: SETUP_SHA.into() };
462            let download_ok = decide(tag.trim_start_matches('v'), &judge(&keys, tag, fetched, &asset)).is_ok();
463            assert_eq!(released(&checked).is_some_and(|r| r.has_signed_file(name)), download_ok, "{label}: {checked:?}");
464        }
465    }
466
467    #[test]
468    fn the_floor_is_read_only_for_a_plain_release_tag_at_that_tag() {
469        assert_eq!(floor_url("v0.60.31").as_deref(), Some("https://raw.githubusercontent.com/agentmuxai/agentmux/v0.60.31/UPGRADE_FLOOR"));
470        for tag in ["", "v", "0.60.31", "v0.60", "v0.60.31.1", "v0.60.x", "v0.60.31-rc1", "v0.60.31/../main", "v0.60.31?x=1", "v0.60.31 ", "vv0.60.31", "v0.60.-1", "latest", "v1234567890.0.0"] {
471            assert_eq!(floor_url(tag), None, "{tag:?}");
472        }
473    }
474
475    #[test]
476    fn a_floor_at_the_tag_above_the_running_build_blocks_the_download_and_names_what_to_install_first() {
477        let kind = InstallKind::WindowsSetup;
478        // This build's floor is 0.55.0; the release's file says 0.60.1, above the running 0.60.0.
479        let floor = floor_for(Some("0.55.0"), Ok(Some(b"0.60.1\n".to_vec())));
480        assert_eq!(floor.as_deref(), Ok("0.60.1"));
481        let a = answer(&keys(), "v0.60.1", NEWER_THAN_FIXTURE, &kind, "x86_64", floor.as_deref().ok(), Some((ENVELOPE.as_bytes(), SIG, MANIFEST.as_bytes())));
482        let status = crate::backend::update::check::status_for(NEWER_THAN_FIXTURE, "stable", released(&a).unwrap(), 1, &kind);
483        assert_eq!(status.install_first.as_deref(), Some("0.60.1"));
484        assert!(!status.can_download, "{status:?}");
485    }
486
487    #[test]
488    fn a_floor_that_cannot_be_read_offers_nothing_even_with_good_signed_files() {
489        let kind = InstallKind::WindowsSetup;
490        let good = Ok(Some((ENVELOPE.as_bytes().to_vec(), SIG.to_string(), MANIFEST.as_bytes().to_vec())));
491        let unreadable: Vec<Result<Option<Vec<u8>>, String>> = vec![
492            Err("HTTP 503".into()),
493            Ok(None),
494            Ok(Some(vec![])),
495            Ok(Some(b"\n".to_vec())),
496            Ok(Some(b"latest".to_vec())),
497            Ok(Some(b"0.55".to_vec())),
498            Ok(Some(b"0.55.0.1".to_vec())),
499            Ok(Some(b"v0.55.0".to_vec())),
500            Ok(Some(b"0.55.0-rc1".to_vec())),
501            Ok(Some(b"0.55.0\n0.56.0".to_vec())),
502            Ok(Some(vec![0xff, 0xfe, b'0'])),
503            Ok(Some(b"<html>404</html>".to_vec())),
504        ];
505        for file in unreadable {
506            let label = format!("{file:?}");
507            let floor = floor_for(Some("0.55.0"), file);
508            assert!(floor.is_err(), "{label}");
509            match verdict(&keys(), "v0.60.1", NEWER_THAN_FIXTURE, &kind, "x86_64", &floor, &good) {
510                Answer::NoAnswer(_) => {}
511                other => panic!("{label}: {other:?}"),
512            }
513        }
514        // With a floor, the same files are an answer.
515        let ok = floor_for(Some("0.55.0"), Ok(Some(b"0.55.0\n".to_vec())));
516        assert!(released(&verdict(&keys(), "v0.60.1", NEWER_THAN_FIXTURE, &kind, "x86_64", &ok, &good)).is_some());
517    }
518
519    #[test]
520    fn a_floor_file_lower_than_this_builds_floor_does_not_lower_it() {
521        assert_eq!(floor_for(Some("0.55.0"), Ok(Some(b"0.40.0".to_vec()))).as_deref(), Ok("0.55.0"));
522        assert_eq!(floor_for(Some("0.55.0"), Ok(Some(b"0.55.0\r\n".to_vec()))).as_deref(), Ok("0.55.0"));
523        assert_eq!(floor_for(Some("0.55.0"), Ok(Some(b"0.56.0".to_vec()))).as_deref(), Ok("0.56.0"));
524        // A build floor that isn't a version never wins.
525        assert_eq!(floor_for(Some("junk"), Ok(Some(b"0.40.0".to_vec()))).as_deref(), Ok("0.40.0"));
526        assert_eq!(floor_for(None, Ok(Some(b"0.40.0".to_vec()))).as_deref(), Ok("0.40.0"));
527    }
528
529    fn tried(tag: &str, found: bool, not_before_ms: i64) -> Tried {
530        Tried { tag: tag.into(), found: found.then(|| Release::from_signed(tag, None, None)), not_before_ms, logged: false }
531    }
532
533    #[test]
534    fn it_asks_once_per_release_keeps_what_verified_and_waits_out_a_failure() {
535        // Nothing tried: ask. Another release's try says nothing about this one.
536        assert_eq!(step(None, "v0.60.31", 100), Step::Ask);
537        assert_eq!(step(Some(&tried("v0.60.30", false, 10_000)), "v0.60.31", 100), Step::Ask);
538        // A verified release is held for its tag, however long ago.
539        assert_eq!(step(Some(&tried("v0.60.31", true, 0)), "v0.60.31", 99_999_999), Step::Held);
540        // A failed try waits, then is allowed again.
541        assert_eq!(step(Some(&tried("v0.60.31", false, 10_000)), "v0.60.31", 9_999), Step::Wait);
542        assert_eq!(step(Some(&tried("v0.60.31", false, 10_000)), "v0.60.31", 10_000), Step::Ask);
543    }
544
545    #[test]
546    fn a_failed_try_is_not_repeated_before_the_limit_ends_and_never_faster_than_the_gap() {
547        let now = 1_000_000;
548        // The API's limit ends in an hour: the second source waits as long.
549        assert_eq!(retry_not_before(now + 3_600_000, now), now + 3_600_000);
550        // The API failed (no limit), or the limit ends in seconds: still the minimum gap.
551        assert_eq!(retry_not_before(0, now), now + MIN_RETRY_GAP_MS);
552        assert_eq!(retry_not_before(now + 5_000, now), now + MIN_RETRY_GAP_MS);
553        assert!(MIN_RETRY_GAP_MS >= 60_000, "never faster than the timed re-check after a limit");
554    }
555
556    // Two releases as `scripts/release-manifest.mjs build` makes them with an `upgrade` object, signed with the same
557    // seed-7 test key as the fixtures above, copied byte for byte: A has floor 0.55.0 (and a rollout flag), B has 0.60.1.
558    const A_MANIFEST: &str = "{\n  \"format\": 1,\n  \"version\": \"0.60.1\",\n  \"tag\": \"v0.60.1\",\n  \"files\": [\n    {\n      \"name\": \"AgentMux-0.60.1-x64-setup.exe\",\n      \"size\": 5,\n      \"sha256\": \"8fb6d5f37e8055ce720bd0b1d56587f88c0071f285966ba17e72b2b12672aa73\"\n    },\n    {\n      \"name\": \"agentmux-0.60.1-x64-portable.7z\",\n      \"size\": 8,\n      \"sha256\": \"01e782826ae5182220bd6158f883d01ceb1bce659dc020e7c511f802a9aa7737\"\n    }\n  ],\n  \"upgrade\": {\n    \"floor\": \"0.55.0\",\n    \"shared_store_changed\": true\n  }\n}\n";
559    const A_ENVELOPE: &str = "{\n  \"format\": 1,\n  \"tag\": \"v0.60.1\",\n  \"manifest_sha256\": \"2038d37391a59d7b22bb0bee89eb31b6f94df10d4730389b79808fb32a52272f\",\n  \"created_at\": \"2026-10-25T12:00:00Z\"\n}\n";
560    const A_SIG: &str = "k1 wf8ru0NTcp3G7GCZff/1dX9O2SEd7nSHuacY058sSrcQHFkpidkkwklrjqb1hJOr61diLh/2rRGg32Gnn5whDw==\n\n";
561    const B_MANIFEST: &str = "{\n  \"format\": 1,\n  \"version\": \"0.60.1\",\n  \"tag\": \"v0.60.1\",\n  \"files\": [\n    {\n      \"name\": \"AgentMux-0.60.1-x64-setup.exe\",\n      \"size\": 5,\n      \"sha256\": \"8fb6d5f37e8055ce720bd0b1d56587f88c0071f285966ba17e72b2b12672aa73\"\n    },\n    {\n      \"name\": \"agentmux-0.60.1-x64-portable.7z\",\n      \"size\": 8,\n      \"sha256\": \"01e782826ae5182220bd6158f883d01ceb1bce659dc020e7c511f802a9aa7737\"\n    }\n  ],\n  \"upgrade\": {\n    \"floor\": \"0.60.1\"\n  }\n}\n";
562    const B_ENVELOPE: &str = "{\n  \"format\": 1,\n  \"tag\": \"v0.60.1\",\n  \"manifest_sha256\": \"2356952b4c0debe50af877ac299efa107dc851c865b6b96330af581007d5d519\",\n  \"created_at\": \"2026-10-25T12:00:00Z\"\n}\n";
563    const B_SIG: &str = "k1 7hvcUAvIjUfGzcTIOtS5zBD/0/k2VzeyWBR3akHyu6Lzp8kiydOj582QrSRoKVahOHMBnWdN6E+DFbKBgFeKAg==\n\n";
564
565    fn fetched(envelope: &str, sig: &str, manifest: &str) -> Fetched {
566        Ok(Some((envelope.as_bytes().to_vec(), sig.to_string(), manifest.as_bytes().to_vec())))
567    }
568
569    #[test]
570    fn the_floor_is_read_from_the_manifest_that_verified_and_from_nothing_else() {
571        assert_eq!(signed_floor_of(&keys(), "v0.60.1", &fetched(A_ENVELOPE, A_SIG, A_MANIFEST)), SignedFloor::Valid("0.55.0".into()));
572        assert_eq!(signed_floor_of(&keys(), "v0.60.1", &fetched(B_ENVELOPE, B_SIG, B_MANIFEST)), SignedFloor::Valid("0.60.1".into()));
573        // A manifest with none says nothing about it.
574        assert_eq!(signed_floor_of(&keys(), "v0.60.1", &fetched(ENVELOPE, SIG, MANIFEST)), SignedFloor::Absent);
575        // One that does not verify, another release's, a release with no signed files and a failed fetch: nothing to use.
576        let tampered = A_MANIFEST.replace("0.55.0", "0.40.0");
577        assert_eq!(signed_floor_of(&keys(), "v0.60.1", &fetched(A_ENVELOPE, A_SIG, &tampered)), SignedFloor::Absent);
578        assert_eq!(signed_floor_of(&keys(), "v0.60.2", &fetched(A_ENVELOPE, A_SIG, A_MANIFEST)), SignedFloor::Absent);
579        assert_eq!(signed_floor_of(&keys(), "v0.60.1", &fetched(A_ENVELOPE, "k9 AAAA\n", A_MANIFEST)), SignedFloor::Absent);
580        assert_eq!(signed_floor_of(&keys(), "v0.60.1", &Ok(None)), SignedFloor::Absent);
581        assert_eq!(signed_floor_of(&keys(), "v0.60.1", &Err("no network".into())), SignedFloor::Absent);
582    }
583
584    #[test]
585    fn the_floor_in_force_is_the_higher_of_the_signed_floor_and_the_builds() {
586        let signed = |f: &str| SignedFloor::Valid(f.into());
587        // Above the build's: it raises it. Below, or equal: it never lowers it.
588        assert_eq!(signed_floor_in_force(Some("0.55.0"), &signed("0.58.0")).as_deref(), Some("0.58.0"));
589        assert_eq!(signed_floor_in_force(Some("0.55.0"), &signed("0.40.0")).as_deref(), Some("0.55.0"));
590        assert_eq!(signed_floor_in_force(Some("0.55.0"), &signed("0.55.0")).as_deref(), Some("0.55.0"));
591        // A build floor that isn't a version never wins; none at all is the signed one.
592        assert_eq!(signed_floor_in_force(Some("junk"), &signed("0.40.0")).as_deref(), Some("0.40.0"));
593        assert_eq!(signed_floor_in_force(None, &signed("0.40.0")).as_deref(), Some("0.40.0"));
594        // No usable signed floor: nothing in force from it.
595        assert_eq!(signed_floor_in_force(Some("0.55.0"), &SignedFloor::Absent), None);
596        assert_eq!(signed_floor_in_force(Some("0.55.0"), &SignedFloor::Unusable("x".into())), None);
597    }
598
599    #[tokio::test]
600    async fn a_signed_floor_is_used_without_asking_for_the_unsigned_file() {
601        let asked = std::sync::atomic::AtomicBool::new(false);
602        let spy = || async {
603            asked.store(true, std::sync::atomic::Ordering::SeqCst);
604            Ok(Some(b"0.59.0\n".to_vec()))
605        };
606        // The file would say 0.59.0, above the signed 0.58.0: it is not consulted, so the signed one is the floor.
607        let floor = resolve_floor(Some("0.55.0"), &SignedFloor::Valid("0.58.0".into()), spy).await;
608        assert_eq!(floor.as_deref(), Ok("0.58.0"));
609        assert!(!asked.load(std::sync::atomic::Ordering::SeqCst), "the floor file was asked for");
610    }
611
612    #[tokio::test]
613    async fn without_a_usable_signed_floor_the_floor_is_read_as_it_was() {
614        for signed in [SignedFloor::Absent, SignedFloor::Unusable("upgrade.floor isn't a plain version".into())] {
615            let asked = std::sync::atomic::AtomicBool::new(false);
616            let spy = || async {
617                asked.store(true, std::sync::atomic::Ordering::SeqCst);
618                Ok(Some(b"0.56.0\n".to_vec()))
619            };
620            assert_eq!(resolve_floor(Some("0.55.0"), &signed, spy).await.as_deref(), Ok("0.56.0"), "{signed:?}");
621            assert!(asked.load(std::sync::atomic::Ordering::SeqCst), "{signed:?}");
622            // And a file that can't be used is still no answer.
623            assert!(resolve_floor(Some("0.55.0"), &signed, || async { Ok(None) }).await.is_err(), "{signed:?}");
624            assert!(resolve_floor(Some("0.55.0"), &signed, || async { Err("offline".to_string()) }).await.is_err(), "{signed:?}");
625        }
626    }
627
628    #[test]
629    fn a_signed_floor_above_the_running_build_blocks_the_download_and_names_what_to_install_first() {
630        let kind = InstallKind::WindowsSetup;
631        let signed = signed_floor_of(&keys(), "v0.60.1", &fetched(B_ENVELOPE, B_SIG, B_MANIFEST));
632        let floor = signed_floor_in_force(Some("0.55.0"), &signed);
633        assert_eq!(floor.as_deref(), Some("0.60.1"));
634        // The running 0.60.0 is below the signed 0.60.1: no direct upgrade, and the reason names the version to install first.
635        let a = answer(&keys(), "v0.60.1", NEWER_THAN_FIXTURE, &kind, "x86_64", floor.as_deref(), Some((B_ENVELOPE.as_bytes(), B_SIG, B_MANIFEST.as_bytes())));
636        let status = crate::backend::update::check::status_for_arch(NEWER_THAN_FIXTURE, "stable", released(&a).unwrap(), 1, &kind, "x86_64");
637        assert_eq!(status.install_first.as_deref(), Some("0.60.1"));
638        assert!(!status.can_download, "{status:?}");
639        assert_eq!(
640            crate::backend::update::check::install_first_message("0.60.0", "0.60.1", "0.60.1"),
641            "This AgentMux (0.60.0) is older than 0.60.1 can upgrade from; install 0.60.1 first, then upgrade."
642        );
643    }
644
645    #[test]
646    fn the_signed_floor_replaces_the_notes_floor_line_and_the_notes_stay_readable() {
647        use crate::backend::update::check::{release_from_tag, status_for_arch};
648        let kind = InstallKind::WindowsSetup;
649        let notes = release_from_tag("v0.60.1", None).with_body("- Faster startup\n<!-- agentmux:min-upgrade-from=0.50.0 -->");
650        // The notes say 0.50.0; the signed floor says 0.58.0: the signed one is the floor, and the notes lose only the line.
651        let with = notes.clone().with_floor("0.58.0");
652        let status = status_for_arch("0.57.0", "stable", &with, 1, &kind, "x86_64");
653        assert_eq!(status.install_first.as_deref(), Some("0.58.0"));
654        assert_eq!(status.notes.as_deref(), Some("- Faster startup"));
655        // A signed floor lower than the notes' wins too (it is the pipeline's own word for this release).
656        let lower = notes.with_floor("0.40.0");
657        assert_eq!(status_for_arch("0.45.0", "stable", &lower, 1, &kind, "x86_64").install_first, None);
658        // No notes at all: just the floor.
659        let bare = release_from_tag("v0.60.1", None).with_floor("0.58.0");
660        assert_eq!(status_for_arch("0.57.0", "stable", &bare, 1, &kind, "x86_64").install_first.as_deref(), Some("0.58.0"));
661    }
662
663    /// The download's gate takes the floor from the manifest it verified, not from what the check saw: with a check that read
664    /// no floor (its manifest fetch failed, or the notes' floor was used), a manifest signing a floor above the running
665    /// build still refuses.
666    #[test]
667    fn the_downloads_gate_refuses_below_the_signed_floor_whatever_the_check_saw() {
668        use crate::backend::update::signature::{download_verdict, judge_with_floor};
669        let setup = ReleaseAsset { name: "AgentMux-0.60.1-x64-setup.exe".into(), size: 5, url: String::new(), sha256: "8fb6d5f37e8055ce720bd0b1d56587f88c0071f285966ba17e72b2b12672aa73".into() };
670        let gate = |running: &str, build: Option<&str>, e: &str, s: &str, m: &str| {
671            let (outcome, floor) = judge_with_floor(&keys(), "v0.60.1", Some((e.as_bytes(), s, m.as_bytes())), &setup);
672            download_verdict(running, "0.60.1", build, &outcome, &floor)
673        };
674        // Manifest B (floor 0.60.1), running 0.60.0: refused, naming 0.60.1, in the message the check gives.
675        let refusal = gate("0.60.0", Some("0.55.0"), B_ENVELOPE, B_SIG, B_MANIFEST).unwrap_err();
676        assert_eq!(refusal, crate::backend::update::check::install_first_message("0.60.0", "0.60.1", "0.60.1"));
677        assert!(refusal.contains("install 0.60.1 first"), "{refusal}");
678        // At the floor, or above it: allowed.
679        assert!(gate("0.60.1", Some("0.55.0"), B_ENVELOPE, B_SIG, B_MANIFEST).is_ok());
680        // Manifest A (floor 0.55.0): running 0.54.0 is refused, 0.55.0 is allowed.
681        assert!(gate("0.54.0", Some("0.40.0"), A_ENVELOPE, A_SIG, A_MANIFEST).unwrap_err().contains("install 0.55.0 first"));
682        assert!(gate("0.55.0", Some("0.40.0"), A_ENVELOPE, A_SIG, A_MANIFEST).is_ok());
683        // This build's own floor, when higher than the signed one, is the one in force (a signed floor never lowers it).
684        assert!(gate("0.57.0", Some("0.58.0"), A_ENVELOPE, A_SIG, A_MANIFEST).unwrap_err().contains("install 0.58.0 first"));
685        // A manifest that does not verify is refused for its signature, never read for a floor.
686        let tampered = B_MANIFEST.replace("\"size\": 5", "\"size\": 6");
687        assert!(gate("0.60.1", Some("0.55.0"), B_ENVELOPE, B_SIG, &tampered).unwrap_err().contains("signature"));
688    }
689
690    #[test]
691    fn a_floor_that_cannot_be_used_adds_nothing_to_the_gate() {
692        use crate::backend::update::signature::enforce_floor;
693        for floor in [SignedFloor::Absent, SignedFloor::Unusable("x".into())] {
694            assert!(enforce_floor("0.10.0", "0.60.1", Some("0.55.0"), &floor).is_ok());
695        }
696        // A running version that can't be read is below any floor, as in the check.
697        assert!(enforce_floor("junk", "0.60.1", Some("0.55.0"), &SignedFloor::Valid("0.60.1".into())).is_err());
698    }
699
700    #[test]
701    fn signed_files_that_were_fetched_and_did_not_verify_are_reported_once_as_unverified() {
702        let tampered = B_MANIFEST.replace("\"size\": 5", "\"size\": 6");
703        let (floor, why) = floor_read(&keys(), "v0.60.1", &fetched(B_ENVELOPE, B_SIG, &tampered));
704        assert_eq!(floor, SignedFloor::Absent);
705        assert!(why.is_some_and(|w| !w.is_empty()));
706        // The ordinary cases say nothing: a good manifest, no signed files, and a fetch that failed.
707        assert_eq!(floor_read(&keys(), "v0.60.1", &fetched(B_ENVELOPE, B_SIG, B_MANIFEST)), (SignedFloor::Valid("0.60.1".into()), None));
708        assert_eq!(floor_read(&keys(), "v0.60.1", &Ok(None)), (SignedFloor::Absent, None));
709        assert_eq!(floor_read(&keys(), "v0.60.1", &Err("HTTP 503".into())), (SignedFloor::Absent, None));
710    }
711}