1pub(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
20pub(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
26pub(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#[derive(Debug, Clone, PartialEq, Eq)]
33pub(crate) enum FetchError {
34 Transport(String),
36 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
49pub(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
77pub(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
112pub(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 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
126pub(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
133pub(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#[cfg(test)]
154pub(crate) mod fixtures {
155 use agentmux_common::update_manifest::UpdateKey;
156
157 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 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 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 assert!(gate("0.60.4", "0.60.4", &a).await.is_err());
223 }
224}