Skip to main content

agentmux_srv_core/backend/update/
signature.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Signed update checksums (`docs/specs/SPEC_SIGNED_UPDATE_CHECKSUMS_2026_10_25.md` §5, §7, §8).
5//! When a download starts, this fetches the release's signed manifest (envelope,
6//! signature, manifest: a few KB), checks it against the key this build pins
7//! (`agentmux_common::update_manifest`) and compares it with the file about to be
8//! downloaded. Step 3, **enforce**: a release from the first signed one on is
9//! downloaded only when its manifest verifies and agrees; one that doesn't verify,
10//! disagrees, lacks the file or isn't signed is refused with the message the person
11//! reads (§7). A release made before signing existed (`FIRST_SIGNED`) still reads as
12//! `unsigned` and is downloaded as before, so nobody on an old release is stranded.
13
14pub(crate) use agentmux_common::update_manifest::{decide, file_names, Outcome};
15use agentmux_common::update_manifest::{judge_file_and_floor, SignedFloor, UpdateKey, MAX_ENVELOPE_BYTES, MAX_MANIFEST_BYTES, UPDATE_KEYS};
16
17use crate::backend::update::check::ReleaseAsset;
18use crate::backend::update::download::RELEASE_DOWNLOAD_PREFIX;
19
20/// The decision, given what was fetched (`None`: the release has no signed
21/// manifest) and the file about to be downloaded.
22pub(crate) fn judge(keys: &[UpdateKey], tag: &str, fetched: Option<(&[u8], &str, &[u8])>, asset: &ReleaseAsset) -> Outcome {
23    judge_with_floor(keys, tag, fetched, asset).0
24}
25
26/// [`judge`], and the upgrade floor the verified manifest signs.
27pub(crate) fn judge_with_floor(keys: &[UpdateKey], tag: &str, fetched: Option<(&[u8], &str, &[u8])>, asset: &ReleaseAsset) -> (Outcome, SignedFloor) {
28    judge_file_and_floor(keys, tag, fetched, &asset.name, asset.size, &asset.sha256)
29}
30
31/// Why a small release file wasn't read.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub(crate) enum FetchError {
34    /// GitHub didn't answer, or answered with an error status.
35    Transport(String),
36    /// It answered with more than the file may hold.
37    TooLarge(usize),
38}
39
40impl std::fmt::Display for FetchError {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        match self {
43            FetchError::Transport(why) => f.write_str(why),
44            FetchError::TooLarge(cap) => write!(f, "larger than {cap} bytes"),
45        }
46    }
47}
48
49/// Fetch one small release file: `None` when the release has no such file (404),
50/// an error for anything else, and never more than `cap` bytes.
51pub(crate) async fn fetch_small(client: &reqwest::Client, url: &str, cap: usize) -> Result<Option<Vec<u8>>, FetchError> {
52    let transport = |why: String| FetchError::Transport(why);
53    let mut resp = tokio::time::timeout(std::time::Duration::from_secs(20), client.get(url).send())
54        .await
55        .map_err(|_| transport("GitHub didn't answer".to_string()))?
56        .map_err(|e| transport(e.to_string()))?;
57    if resp.status() == reqwest::StatusCode::NOT_FOUND {
58        return Ok(None);
59    }
60    if !resp.status().is_success() {
61        return Err(transport(format!("HTTP {}", resp.status())));
62    }
63    let mut body = Vec::new();
64    while let Some(chunk) = tokio::time::timeout(std::time::Duration::from_secs(20), resp.chunk())
65        .await
66        .map_err(|_| transport("GitHub stopped answering".to_string()))?
67        .map_err(|e| transport(e.to_string()))?
68    {
69        if body.len() + chunk.len() > cap {
70            return Err(FetchError::TooLarge(cap));
71        }
72        body.extend_from_slice(&chunk);
73    }
74    Ok(Some(body))
75}
76
77/// Fetch the signed manifest of `asset`'s release and judge it. Release files
78/// sit side by side, so the others' addresses are the asset's with the name
79/// swapped; an address that isn't on AgentMux's releases is not fetched.
80pub(crate) async fn check(version: &str, asset: &ReleaseAsset) -> (Outcome, SignedFloor) {
81    let tag = format!("v{version}");
82    let Some(dir) = asset.url.strip_suffix(asset.name.as_str()).filter(|d| d.starts_with(RELEASE_DOWNLOAD_PREFIX)) else {
83        return (Outcome::Failed("the release file isn't on AgentMux's GitHub releases".into()), SignedFloor::Absent);
84    };
85    let client = match crate::http_client::builder()
86        .user_agent(format!("AgentMux/{}", env!("CARGO_PKG_VERSION")))
87        .connect_timeout(std::time::Duration::from_secs(10))
88        .build()
89    {
90        Ok(c) => c,
91        Err(e) => return (Outcome::Unreachable(e.to_string()), SignedFloor::Absent),
92    };
93    let (envelope_name, signature_name, manifest_name) = file_names(version);
94    let envelope = match fetch_small(&client, &format!("{dir}{envelope_name}"), MAX_ENVELOPE_BYTES).await {
95        Ok(Some(b)) => b,
96        Ok(None) => return (Outcome::Unsigned, SignedFloor::Absent),
97        Err(e) => return (Outcome::Unreachable(format!("couldn't fetch the envelope: {e}")), SignedFloor::Absent),
98    };
99    let signatures = match fetch_small(&client, &format!("{dir}{signature_name}"), MAX_ENVELOPE_BYTES).await {
100        Ok(Some(b)) => String::from_utf8_lossy(&b).into_owned(),
101        Ok(None) => return (Outcome::Failed("the envelope has no signature file".into()), SignedFloor::Absent),
102        Err(e) => return (Outcome::Unreachable(format!("couldn't fetch the signature: {e}")), SignedFloor::Absent),
103    };
104    let manifest = match fetch_small(&client, &format!("{dir}{manifest_name}"), MAX_MANIFEST_BYTES).await {
105        Ok(Some(b)) => b,
106        Ok(None) => return (Outcome::Failed("the envelope has no manifest".into()), SignedFloor::Absent),
107        Err(e) => return (Outcome::Unreachable(format!("couldn't fetch the manifest: {e}")), SignedFloor::Absent),
108    };
109    judge_with_floor(UPDATE_KEYS, &tag, Some((&envelope, &signatures, &manifest)), asset)
110}
111
112/// Refuse a release whose signed upgrade floor is above the running build: the higher of the floor the verified manifest
113/// signs and this build's own (`build`), as the check reads it, and the same message. The download asks this itself, from
114/// the manifest it has just verified, so it does not depend on what the check saw: a check whose manifest fetch failed, or
115/// had not run, reads the unsigned notes' floor, and a download must not install over a signed floor because of that.
116/// A manifest with no usable floor says nothing here (the check's own reading of the notes stands).
117pub(crate) fn enforce_floor(running: &str, version: &str, build: Option<&str>, signed: &SignedFloor) -> Result<(), String> {
118    let Some(floor) = crate::backend::update::signed_source::signed_floor_in_force(build, signed) else { return Ok(()) };
119    // A running version that can't be read is older than any floor, as in the check.
120    if crate::backend::update::check::version_core(running) < crate::backend::update::check::version_core(&floor) {
121        return Err(crate::backend::update::check::install_first_message(running, version, &floor));
122    }
123    Ok(())
124}
125
126/// Whether a download may start, given what the signed manifest said: the signature decision ([`decide`]), then the floor
127/// ([`enforce_floor`]).
128pub(crate) fn download_verdict(running: &str, version: &str, build: Option<&str>, outcome: &Outcome, floor: &SignedFloor) -> Result<(), String> {
129    decide(version, outcome)?;
130    enforce_floor(running, version, build, floor)
131}
132
133/// Check the release's signed manifest, log what was found, and say whether the download may start: the file must be
134/// listed as it is, and the running build (`running`) must not be below the floor the manifest signs ([`enforce_floor`]).
135pub(crate) async fn gate(running: &str, version: &str, asset: &ReleaseAsset) -> Result<(), String> {
136    let (outcome, floor) = check(version, asset).await;
137    let file = &asset.name;
138    match &outcome {
139        Outcome::Unsigned => tracing::info!(%version, %file, "update signature: the release has no signed manifest"),
140        Outcome::Verified => tracing::info!(%version, %file, "update signature: verified; the signed manifest matches the digest in use"),
141        Outcome::NotListed(why) | Outcome::Disagrees(why) => tracing::error!(%version, %file, %why, "update signature: verified, but it disagrees with the file offered"),
142        Outcome::Failed(why) => tracing::error!(%version, %file, %why, "update signature: the signed manifest did not verify"),
143        Outcome::Unreachable(why) => tracing::warn!(%version, %file, %why, "update signature: couldn't fetch the signed manifest"),
144    }
145    let result = download_verdict(running, version, crate::backend::update::check::build_floor(), &outcome, &floor);
146    if let Err(message) = &result {
147        tracing::warn!(%running, %version, %message, "update: not downloading: refused by the signature or the signed upgrade floor");
148    }
149    result
150}
151
152/// A fixed signed release (seed-7 key), for this module's tests and the second source's.
153#[cfg(test)]
154pub(crate) mod fixtures {
155    use agentmux_common::update_manifest::UpdateKey;
156
157    // The same fixed release the common crate and the release script test (seed-7 key).
158    pub(crate) const KEY: [u8; 32] = [
159        0xea, 0x4a, 0x6c, 0x63, 0xe2, 0x9c, 0x52, 0x0a, 0xbe, 0xf5, 0x50, 0x7b, 0x13, 0x2e, 0xc5, 0xf9, 0x95, 0x47, 0x76, 0xae, 0xbe, 0xbe, 0x7b, 0x92, 0x42,
160        0x1e, 0xea, 0x69, 0x14, 0x46, 0xd2, 0x2c,
161    ];
162    pub(crate) const 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\": 100,\n      \"sha256\": \"8fb6d5f37e8055ce720bd0b1d56587f88c0071f285966ba17e72b2b12672aa73\"\n    },\n    {\n      \"name\": \"agentmux-0.60.1-x64-portable.7z\",\n      \"size\": 50,\n      \"sha256\": \"01e782826ae5182220bd6158f883d01ceb1bce659dc020e7c511f802a9aa7737\"\n    }\n  ]\n}\n";
163    pub(crate) const ENVELOPE: &str = "{\n  \"format\": 1,\n  \"tag\": \"v0.60.1\",\n  \"manifest_sha256\": \"8a83f0bb7ce99e7537b872b55d6e688da6713ebd078b0dd88c740b1a3c5809eb\",\n  \"created_at\": \"2026-10-25T12:00:00Z\"\n}\n";
164    pub(crate) const SIG: &str = "k1 oGZeVKdahQJP1mqd964PNT7Fie6IbSoUMkDXrmi1QbUVn947HuHtRZNRJt36L22rcAkLPGRWolco8DB2AZXZCw==\n";
165    pub(crate) const SETUP_SHA: &str = "8fb6d5f37e8055ce720bd0b1d56587f88c0071f285966ba17e72b2b12672aa73";
166
167    pub(crate) fn keys() -> Vec<UpdateKey> {
168        vec![UpdateKey { id: "k1", public: KEY }]
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    use super::fixtures::*;
175    use super::*;
176
177    fn asset(name: &str, size: u64, sha256: &str) -> ReleaseAsset {
178        ReleaseAsset { name: name.into(), size, url: format!("{RELEASE_DOWNLOAD_PREFIX}v0.60.1/{name}"), sha256: sha256.into() }
179    }
180
181    fn judged(asset: &ReleaseAsset) -> Outcome {
182        judge(&keys(), "v0.60.1", Some((ENVELOPE.as_bytes(), SIG, MANIFEST.as_bytes())), asset)
183    }
184
185    #[test]
186    fn a_release_without_a_signed_manifest_reads_as_unsigned() {
187        assert_eq!(judge(&keys(), "v0.60.1", None, &asset("AgentMux-0.60.1-x64-setup.exe", 100, SETUP_SHA)), Outcome::Unsigned);
188    }
189
190    #[test]
191    fn the_signed_manifest_agreeing_with_the_digest_in_use_is_verified() {
192        assert_eq!(judged(&asset("AgentMux-0.60.1-x64-setup.exe", 100, SETUP_SHA)), Outcome::Verified);
193        // The listing's digest is case-insensitive hex.
194        assert_eq!(judged(&asset("AgentMux-0.60.1-x64-setup.exe", 100, &SETUP_SHA.to_uppercase())), Outcome::Verified);
195    }
196
197    #[test]
198    fn a_file_the_manifest_does_not_describe_that_way_is_a_disagreement_not_a_failure() {
199        assert!(matches!(judged(&asset("AgentMux-0.60.1-x64-setup.exe", 101, SETUP_SHA)), Outcome::Disagrees(w) if w.contains("size")));
200        assert!(matches!(judged(&asset("AgentMux-0.60.1-x64-setup.exe", 100, &"0".repeat(64))), Outcome::Disagrees(w) if w.contains("SHA-256")));
201        assert!(matches!(judged(&asset("AgentMux-0.60.1-other.exe", 100, SETUP_SHA)), Outcome::NotListed(w) if w.contains("isn't in the signed manifest")));
202    }
203
204    #[test]
205    fn a_manifest_that_does_not_verify_is_a_failure_with_the_reason() {
206        let a = asset("AgentMux-0.60.1-x64-setup.exe", 100, SETUP_SHA);
207        // Another key, a different release's tag, a tampered manifest, a missing signature line.
208        let other = vec![UpdateKey { id: "k1", public: [9; 32] }];
209        assert!(matches!(judge(&other, "v0.60.1", Some((ENVELOPE.as_bytes(), SIG, MANIFEST.as_bytes())), &a), Outcome::Failed(_)));
210        assert!(matches!(judge(&keys(), "v0.60.2", Some((ENVELOPE.as_bytes(), SIG, MANIFEST.as_bytes())), &a), Outcome::Failed(w) if w.contains("v0.60.2")));
211        let tampered = MANIFEST.replace("\"size\": 100", "\"size\": 101");
212        assert!(matches!(judge(&keys(), "v0.60.1", Some((ENVELOPE.as_bytes(), SIG, tampered.as_bytes())), &a), Outcome::Failed(_)));
213        assert!(matches!(judge(&keys(), "v0.60.1", Some((ENVELOPE.as_bytes(), "", MANIFEST.as_bytes())), &a), Outcome::Failed(_)));
214    }
215
216    #[tokio::test]
217    async fn an_address_off_the_releases_is_not_fetched() {
218        let mut a = asset("AgentMux-0.60.1-x64-setup.exe", 100, SETUP_SHA);
219        a.url = "https://example.com/AgentMux-0.60.1-x64-setup.exe".into();
220        assert!(matches!(check("0.60.1", &a).await.0, Outcome::Failed(w) if w.contains("isn't on AgentMux's GitHub releases")));
221        // ...and that is a refusal for a signed-era release, never a download.
222        assert!(gate("0.60.4", "0.60.4", &a).await.is_err());
223    }
224}