Skip to main content

agentmux_srv_core/backend/
agent_image_digest.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The digest of the default agent image, from the signed manifest of the release this srv is.
5//!
6//! The image tag `agent-base:<version>` can be pushed by anything that can write the package, so
7//! a tag alone doesn't say which image the release built. The release's signed manifest does:
8//! it lists the image's digest (`agentmux_common::update_manifest::ManifestImage`), covered by
9//! the same signature as the release's files. A container is created from the image at that
10//! digest, tagged locally as `agent-base:<version>` (`container::pull::pinned`).
11//!
12//! Fetched when a container is created, kept for the life of srv, and never fetched on a turn
13//! of a container that exists. What it does when it can't tell:
14//! - a verified manifest that lists the image: [`Pin::Digest`];
15//! - no manifest (a build that was never released, a release made before signing), none that
16//!   can be reached, or one that lists no image: [`Pin::Unpinned`], and the version tag is
17//!   pulled as before, with a log line saying the image is unverified;
18//! - a manifest that is there but does not verify: [`Pin::Refused`], and the default image is
19//!   not pulled.
20
21use std::sync::OnceLock;
22use std::time::{Duration, Instant};
23
24use agentmux_common::update_manifest::{verify_release, UpdateKey, MAX_ENVELOPE_BYTES, MAX_MANIFEST_BYTES, UPDATE_KEYS};
25
26use crate::backend::container::image::AGENT_BASE_REPO;
27use crate::backend::update::download::RELEASE_DOWNLOAD_PREFIX;
28use crate::backend::update::signature::{fetch_small, file_names, FetchError};
29
30/// The name the release lists the default agent image under.
31pub(crate) const IMAGE_NAME: &str = "agent-base";
32
33/// The name it lists the developer variant under (the same repository, another image).
34pub(crate) const DEVELOPER_IMAGE_NAME: &str = "agent-base-developer";
35
36/// The version of the release this srv is.
37const CURRENT: &str = env!("CARGO_PKG_VERSION");
38
39/// How long all three manifest files may take to fetch: a container is waiting for it.
40const FETCH_TOTAL: Duration = Duration::from_secs(12);
41
42/// How long an answer of "can't tell" is kept before the next container asks again.
43const UNPINNED_KEPT: Duration = Duration::from_secs(120);
44
45/// What to run the default agent image from.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub(crate) enum Pin {
48    /// The release's own image: `ghcr.io/agentmuxai/agent-base@sha256:<digest>`.
49    Digest(String),
50    /// Nothing signed says which image; why, for the log.
51    Unpinned(String),
52    /// A manifest is there and is not trusted; why, for the person.
53    Refused(String),
54}
55
56/// What was fetched of a release's signed manifest.
57pub(crate) enum Fetched {
58    /// The release has no envelope (made before signing, or never released).
59    NoManifest,
60    /// GitHub could not be reached, or answered with something unusable.
61    Unreachable(String),
62    /// The envelope is there but a file it needs isn't.
63    Incomplete(String),
64    Files { envelope: Vec<u8>, signatures: String, manifest: Vec<u8> },
65}
66
67/// The decision for the image the release lists as `image_name`, given what was fetched for the release called `version`.
68pub(crate) fn decide(keys: &[UpdateKey], version: &str, image_name: &str, fetched: Fetched) -> Pin {
69    let (envelope, signatures, manifest) = match fetched {
70        Fetched::NoManifest => return Pin::Unpinned("the release has no signed manifest".into()),
71        Fetched::Unreachable(why) => return Pin::Unpinned(format!("the signed manifest couldn't be fetched: {why}")),
72        Fetched::Incomplete(why) => return Pin::Refused(why),
73        Fetched::Files { envelope, signatures, manifest } => (envelope, signatures, manifest),
74    };
75    let manifest = match verify_release(keys, &format!("v{version}"), &envelope, &signatures, &manifest) {
76        Ok(m) => m,
77        Err(e) => return Pin::Refused(e.to_string()),
78    };
79    match manifest.image(image_name) {
80        None => Pin::Unpinned(format!("the signed manifest lists no {image_name} image")),
81        // The repository is this app's own, never one the manifest names.
82        Some(image) if image.reference != AGENT_BASE_REPO => Pin::Unpinned(format!("the signed manifest lists the agent image under {}", image.reference)),
83        Some(image) => Pin::Digest(format!("{AGENT_BASE_REPO}@{}", image.digest)),
84    }
85}
86
87/// A file that couldn't be read: GitHub not answering is "can't tell", but a file larger than any
88/// such file may be is the release's metadata being wrong, which is refused like any other.
89fn unread(error: FetchError, file: &str) -> Fetched {
90    match error {
91        FetchError::Transport(why) => Fetched::Unreachable(why),
92        FetchError::TooLarge(cap) => Fetched::Incomplete(format!("the release's {file} is larger than {cap} bytes")),
93    }
94}
95
96/// Fetch the three files of the signed release called `version`.
97async fn fetch(version: &str) -> Fetched {
98    let client = match crate::http_client::builder()
99        .user_agent(format!("AgentMux/{CURRENT}"))
100        .connect_timeout(Duration::from_secs(6))
101        .build()
102    {
103        Ok(c) => c,
104        Err(e) => return Fetched::Unreachable(e.to_string()),
105    };
106    let dir = format!("{RELEASE_DOWNLOAD_PREFIX}v{version}/");
107    let (envelope_name, signature_name, manifest_name) = file_names(version);
108    let envelope = match fetch_small(&client, &format!("{dir}{envelope_name}"), MAX_ENVELOPE_BYTES).await {
109        Ok(Some(b)) => b,
110        Ok(None) => return Fetched::NoManifest,
111        Err(e) => return unread(e, "envelope"),
112    };
113    let signatures = match fetch_small(&client, &format!("{dir}{signature_name}"), MAX_ENVELOPE_BYTES).await {
114        Ok(Some(b)) => String::from_utf8_lossy(&b).into_owned(),
115        Ok(None) => return Fetched::Incomplete("the release's envelope has no signature".into()),
116        Err(e) => return unread(e, "signature"),
117    };
118    let manifest = match fetch_small(&client, &format!("{dir}{manifest_name}"), MAX_MANIFEST_BYTES).await {
119        Ok(Some(b)) => b,
120        Ok(None) => return Fetched::Incomplete("the release's envelope has no manifest".into()),
121        Err(e) => return unread(e, "manifest"),
122    };
123    Fetched::Files { envelope, signatures, manifest }
124}
125
126/// What to run the default agent image of this srv's own version from. Fetches once; a verified
127/// answer (a digest, or a refusal) stands for the life of srv, "can't tell" for a couple of
128/// minutes.
129pub(crate) async fn pin_for_running_version(image_name: &str) -> Pin {
130    static KEPT: OnceLock<tokio::sync::Mutex<std::collections::HashMap<String, (Instant, Pin)>>> = OnceLock::new();
131    let mut kept = KEPT.get_or_init(Default::default).lock().await;
132    if let Some((at, pin)) = kept.get(image_name) {
133        if !matches!(pin, Pin::Unpinned(_)) || at.elapsed() < UNPINNED_KEPT {
134            return pin.clone();
135        }
136    }
137    let fetched = tokio::time::timeout(FETCH_TOTAL, fetch(CURRENT)).await.unwrap_or_else(|_| Fetched::Unreachable("GitHub didn't answer in time".into()));
138    let pin = decide(UPDATE_KEYS, CURRENT, image_name, fetched);
139    match &pin {
140        Pin::Digest(reference) => tracing::info!(version = CURRENT, image = image_name, %reference, "the signed manifest names the agent image"),
141        Pin::Unpinned(why) => tracing::info!(version = CURRENT, image = image_name, %why, "the agent image can't be checked against a signed manifest; using its version tag, unverified"),
142        Pin::Refused(why) => tracing::warn!(version = CURRENT, image = image_name, %why, "the release's signed manifest isn't trusted; not pulling the agent image"),
143    }
144    kept.insert(image_name.to_string(), (Instant::now(), pin.clone()));
145    pin
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151    use base64::engine::general_purpose::STANDARD as BASE64;
152    use base64::Engine;
153    use ed25519_dalek::{Signer, SigningKey};
154    use sha2::{Digest, Sha256};
155
156    const VERSION: &str = "0.60.1";
157    const H: &str = "1111111111111111111111111111111111111111111111111111111111111111";
158
159    fn key() -> UpdateKey {
160        UpdateKey { id: "k1", public: SigningKey::from_bytes(&[3; 32]).verifying_key().to_bytes() }
161    }
162
163    fn release(images: &str) -> Fetched {
164        let manifest = format!(r#"{{"format":1,"version":"{VERSION}","tag":"v{VERSION}","files":[{{"name":"a.exe","size":1,"sha256":"{H}"}}],"images":{images}}}"#);
165        let sha: String = Sha256::digest(manifest.as_bytes()).iter().map(|b| format!("{b:02x}")).collect();
166        let envelope = format!(r#"{{"format":1,"tag":"v{VERSION}","manifest_sha256":"{sha}","created_at":"2026-10-28T00:00:00Z"}}"#);
167        let signatures = format!("k1 {}\n", BASE64.encode(SigningKey::from_bytes(&[3; 32]).sign(envelope.as_bytes()).to_bytes()));
168        Fetched::Files { envelope: envelope.into_bytes(), signatures, manifest: manifest.into_bytes() }
169    }
170
171    fn image(reference: &str) -> String {
172        format!(r#"[{{"name":"agent-base","ref":"{reference}","digest":"sha256:{H}"}}]"#)
173    }
174
175    #[test]
176    fn a_verified_manifest_that_lists_the_image_pins_it_by_digest() {
177        assert_eq!(decide(&[key()], VERSION, IMAGE_NAME, release(&image(AGENT_BASE_REPO))), Pin::Digest(format!("{AGENT_BASE_REPO}@sha256:{H}")));
178    }
179
180    #[test]
181    fn the_developer_variant_is_pinned_by_its_own_listing() {
182        let both = format!(
183            r#"[{{"name":"agent-base","ref":"{AGENT_BASE_REPO}","digest":"sha256:{H}"}},{{"name":"agent-base-developer","ref":"{AGENT_BASE_REPO}","digest":"sha256:{}"}}]"#,
184            "3".repeat(64)
185        );
186        assert_eq!(decide(&[key()], VERSION, DEVELOPER_IMAGE_NAME, release(&both)), Pin::Digest(format!("{AGENT_BASE_REPO}@sha256:{}", "3".repeat(64))));
187        assert_eq!(decide(&[key()], VERSION, IMAGE_NAME, release(&both)), Pin::Digest(format!("{AGENT_BASE_REPO}@sha256:{H}")), "the base image keeps its own digest");
188        let only_base = decide(&[key()], VERSION, DEVELOPER_IMAGE_NAME, release(&image(AGENT_BASE_REPO)));
189        assert!(matches!(only_base, Pin::Unpinned(why) if why.contains("agent-base-developer")), "a release without one: its tag is used, unverified");
190    }
191
192    #[test]
193    fn without_a_signed_listing_the_version_tag_is_used_unverified() {
194        let unpinned = |f: Fetched| matches!(decide(&[key()], VERSION, IMAGE_NAME, f), Pin::Unpinned(_));
195        assert!(unpinned(Fetched::NoManifest), "a build that was never released");
196        assert!(unpinned(Fetched::Unreachable("offline".into())));
197        assert!(unpinned(release("[]")), "a release before the field");
198        assert!(unpinned(release(&image("ghcr.io/someone/else"))), "never a repository the app didn't choose");
199    }
200
201    #[test]
202    fn a_file_over_its_cap_is_refused_and_a_silent_github_is_not() {
203        let transport = unread(FetchError::Transport("HTTP 503".into()), "manifest");
204        assert!(matches!(decide(&[key()], VERSION, IMAGE_NAME, transport), Pin::Unpinned(_)));
205        let padded = unread(FetchError::TooLarge(4096), "envelope");
206        assert!(matches!(decide(&[key()], VERSION, IMAGE_NAME, padded), Pin::Refused(why) if why.contains("envelope") && why.contains("4096")));
207    }
208
209    #[test]
210    fn a_manifest_that_is_there_and_not_trusted_refuses_the_default_image() {
211        let refused = |f: Fetched, keys: &[UpdateKey], version: &str| matches!(decide(keys, version, IMAGE_NAME, f), Pin::Refused(_));
212        assert!(refused(release(&image(AGENT_BASE_REPO)), &[UpdateKey { id: "k1", public: [9; 32] }], VERSION), "another key");
213        assert!(refused(release(&image(AGENT_BASE_REPO)), &[], VERSION), "no key pinned");
214        assert!(refused(release(&image(AGENT_BASE_REPO)), &[key()], "0.60.2"), "another release's manifest");
215        assert!(refused(Fetched::Incomplete("no signature".into()), &[key()], VERSION));
216        let Fetched::Files { envelope, signatures, manifest } = release(&image(AGENT_BASE_REPO)) else { unreachable!() };
217        let tampered = String::from_utf8(manifest).unwrap().replace(&format!("sha256:{H}"), &format!("sha256:{}", "2".repeat(64)));
218        assert!(refused(Fetched::Files { envelope, signatures, manifest: tampered.into_bytes() }, &[key()], VERSION), "a digest swapped after signing");
219    }
220}