Skip to main content

agentmux_srv/server/
jekt_cloud.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Files sent with a jekt over the cloud relay
5//! (`docs/specs/SPEC_JEKT_FILE_TRANSFER_2026_10_05.md` §4.4).
6//!
7//! Sending: each file is encrypted (AES-256-GCM, a fresh key per file and
8//! send), uploaded to a URL the relay issues (`POST /reactive/blob`), and
9//! named in a cloud manifest with its key and blob id. The key is sealed to
10//! the install that runs the target when its lease offers a key
11//! (`jekt_seal`, spec §7), and travels as plain base64 to an older one. The
12//! jekt's msgid is rebound to that manifest, so srv's WAN signature covers
13//! keys and blob ids too. Receiving: after the claim, each blob is downloaded
14//! through a URL the relay issues to the target alone
15//! (`GET /reactive/blob/:id`), decrypted and checked against its hash, then
16//! stored like any received file.
17
18use std::sync::Arc;
19use std::time::Duration;
20
21use agentmux_common::jekt_files::{self, CloudFile, JektFile};
22use base64::Engine;
23use ring::aead::{Aad, LessSafeKey, Nonce, UnboundKey, AES_256_GCM, NONCE_LEN};
24use ring::rand::{SecureRandom, SystemRandom};
25
26use super::jekt_seal::{self, Recipient};
27use crate::backend::attachments;
28use crate::backend::reactive::types::{FilesDelivery, InjectionRequest};
29
30/// An upload or download may take this long; the relay's URLs live 300 s.
31const TRANSFER_TIMEOUT: Duration = Duration::from_secs(240);
32/// Bytes a blob adds to its file: the nonce in front, the GCM tag behind.
33const OVERHEAD: usize = NONCE_LEN + 16;
34const B64: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD;
35
36/// Encrypt `plain` under a fresh key: the blob (nonce, ciphertext, tag) and
37/// the key.
38fn seal(mut plain: Vec<u8>) -> Option<(Vec<u8>, [u8; 32])> {
39    let rng = SystemRandom::new();
40    let mut key = [0u8; 32];
41    let mut nonce = [0u8; NONCE_LEN];
42    rng.fill(&mut key).ok()?;
43    rng.fill(&mut nonce).ok()?;
44    let sealing = LessSafeKey::new(UnboundKey::new(&AES_256_GCM, &key).ok()?);
45    sealing
46        .seal_in_place_append_tag(Nonce::assume_unique_for_key(nonce), Aad::empty(), &mut plain)
47        .ok()?;
48    let mut blob = Vec::with_capacity(NONCE_LEN + plain.len());
49    blob.extend_from_slice(&nonce);
50    blob.extend_from_slice(&plain);
51    Some((blob, key))
52}
53
54/// Decrypt a blob `seal` made; `None` if the key, nonce or tag don't match.
55fn open(blob: &[u8], key: &[u8; 32]) -> Option<Vec<u8>> {
56    if blob.len() < OVERHEAD {
57        return None;
58    }
59    let (nonce, sealed) = blob.split_at(NONCE_LEN);
60    let opening = LessSafeKey::new(UnboundKey::new(&AES_256_GCM, key).ok()?);
61    let mut buf = sealed.to_vec();
62    let plain = opening
63        .open_in_place(Nonce::try_assume_unique_for_key(nonce).ok()?, Aad::empty(), &mut buf)
64        .ok()?;
65    Some(plain.to_vec())
66}
67
68/// Send `req` and its files through the relay: `Ok(Some(answer))` once the
69/// relay queued it, `Ok(None)` when this instance has no relay or the relay
70/// didn't take it (the caller holds or refuses), `Err` with why the files
71/// can't go that way at all.
72pub(crate) async fn relay(state: &super::AppState, req: &InjectionRequest, caller_uid: &str) -> Result<Option<serde_json::Value>, String> {
73    let files = req.files.as_deref().unwrap_or_default();
74    let Some(source) = req.source_agent.as_deref().filter(|s| !s.is_empty()) else {
75        return Ok(None);
76    };
77    if req.delivery_tier.as_deref() == Some("wan") {
78        return Ok(None);
79    }
80    jekt_files::check_tier_limits(files, "wan").map_err(|e| format!("files refused: {e}"))?;
81    let Some(credential) = crate::muxbus::relay::relay_token(source, &state.id_store, &state.http_client).await else {
82        return Ok(None);
83    };
84    let base = crate::muxbus::relay::rest_base_url();
85    // Only to a target running now on an install that says it can fetch
86    // them: the relay doesn't bind a jekt to the install that will claim it,
87    // so a target with no live holder could be claimed later by an older
88    // install, which would deliver the text without its files (spec §3.4).
89    let holder = crate::muxbus::wan_lease::holder(&base, &req.target_agent, source, &credential.token, &state.http_client).await;
90    let refused = |why: &str| format!("files refused: {} {why}; nothing was sent", req.target_agent);
91    let held_by = takes_cloud_files(&holder).map_err(refused)?;
92    let seal_to = match &held_by.seal {
93        Some(offer) => Some(recipient(state, &base, &req.target_agent, &held_by.channel, offer).await.map_err(|why| refused(&why))?),
94        None => None,
95    };
96    let cloud_req = upload(&base, &state.http_client, &credential.token, source, req, seal_to.as_ref()).await?;
97    Ok(super::reactive::try_cloud_relay(state, &cloud_req, caller_uid).await)
98}
99
100/// The key to seal `target`'s files to, from its lease's offer, checked
101/// against the agent's record in the account's key directory. `Err` says
102/// why not, after the target's name: a holder that offers a key gets sealed
103/// keys or nothing, never plain ones.
104async fn recipient(
105    state: &super::AppState,
106    base: &str,
107    target: &str,
108    channel: &str,
109    offer: &jekt_seal::SealOffer,
110) -> Result<Recipient, String> {
111    const NO_IDENTITY: &str = "can't be sent sealed files: this AgentMux has no WAN identity";
112    const SIGNED_OUT: &str = "can't be sent sealed files: this AgentMux isn't signed in to the cloud";
113    let wan = crate::backend::storage::wan_identity::global().ok_or(NO_IDENTITY)?;
114    let own = wan
115        .instance_ensure(&crate::backend::reactive::registry::local_host_label())
116        .map_err(|_| NO_IDENTITY)?;
117    // The directory answers the account's own token, not an agent's.
118    let scheduler = crate::broker::get_global().ok_or(SIGNED_OUT)?;
119    let token = crate::muxbus::cloud_subscriber::load_valid_token(&state.id_store, &scheduler)
120        .await
121        .ok_or(SIGNED_OUT)?;
122    let dir = crate::muxbus::wan_verify::Directory {
123        base_url: base,
124        http: &state.http_client,
125        token: &token,
126        budget: &crate::muxbus::wan_verify::GLOBAL_BUDGET,
127    };
128    let now = agentmux_common::time::now_secs();
129    let record =
130        crate::muxbus::wan_verify::recipient_record(&wan, &own.instance_id, &dir, target, &offer.instance, channel, &offer.key_fp, now)
131            .await?;
132    jekt_seal::check_offer(offer, &record, target).map_err(str::to_string)
133}
134
135/// Whether the target's lease holder can fetch files from the relay: only a
136/// live holder that says so. `Err` says why not, after the target's name.
137fn takes_cloud_files(holder: &crate::muxbus::wan_lease::Holder) -> Result<&crate::muxbus::wan_lease::HeldBy, &'static str> {
138    use crate::muxbus::wan_lease::Holder;
139    match holder {
140        Holder::Other(h) if h.features.iter().any(|f| f == jekt_files::CLOUD_FEATURE) => Ok(h),
141        Holder::Other(_) => Err("runs on an AgentMux too old to receive files through the cloud relay"),
142        Holder::Free | Holder::Yours => Err("isn't running on another computer right now, and files through the cloud relay go only to a running agent"),
143        Holder::Unknown | Holder::Unsupported | Holder::Unreachable => Err("can't be confirmed to receive files: the cloud relay didn't say who runs it"),
144    }
145}
146
147/// Encrypt and upload each file, sealing its key to `seal_to` when there is
148/// one; the request to relay, its files named by the cloud manifest and its
149/// msgid bound to it.
150async fn upload(
151    base: &str,
152    http: &reqwest::Client,
153    token: &str,
154    source: &str,
155    req: &InjectionRequest,
156    seal_to: Option<&Recipient>,
157) -> Result<InjectionRequest, String> {
158    let svc = attachments::get().ok_or("files refused: the attachment store isn't available")?;
159    let mut cloud = Vec::new();
160    for f in req.files.as_deref().unwrap_or_default() {
161        let path = svc.store().find_blob(&f.sha256).map(|(p, _)| p);
162        let plain = match path {
163            Some(p) => tokio::fs::read(p).await.ok(),
164            None => None,
165        }
166        .filter(|b| b.len() as u64 == f.size)
167        .ok_or_else(|| format!("files refused: {} is no longer in this AgentMux's store", f.name))?;
168        let (blob, key) = tokio::task::spawn_blocking(move || seal(plain))
169            .await
170            .ok()
171            .flatten()
172            .ok_or("files refused: couldn't encrypt a file")?;
173        let issued: serde_json::Value = http
174            .post(format!("{}/reactive/blob", base.trim_end_matches('/')))
175            .header("Authorization", format!("Bearer {token}"))
176            .header("X-Agent-ID", source)
177            .json(&serde_json::json!({ "target_agent": req.target_agent, "size": blob.len() }))
178            .send()
179            .await
180            .map_err(|e| format!("files refused: the cloud relay is unreachable: {e}"))?
181            .error_for_status()
182            .map_err(|e| format!("files refused: the cloud relay refused a file: {e}"))?
183            .json()
184            .await
185            .map_err(|e| format!("files refused: the cloud relay's answer is unreadable: {e}"))?;
186        let (Some(blob_id), Some(url)) = (issued["blob_id"].as_str(), issued["upload_url"].as_str()) else {
187            return Err("files refused: the cloud relay can't take files".to_string());
188        };
189        http.put(url)
190            .timeout(TRANSFER_TIMEOUT)
191            .body(blob)
192            .send()
193            .await
194            .and_then(|r| r.error_for_status())
195            .map_err(|e| format!("files refused: uploading {} failed: {e}", f.name))?;
196        let key = match seal_to {
197            Some(to) => jekt_seal::wrap(&key, to, &f.sha256, blob_id).ok_or("files refused: couldn't seal a file's key")?,
198            None => B64.encode(key),
199        };
200        cloud.push(CloudFile { file: f.clone(), key, blob_id: blob_id.to_string() });
201    }
202    let mut out = req.clone();
203    out.request_id = Some(jekt_files::bind_cloud_msgid(req.request_id.as_deref().unwrap_or_default(), &cloud));
204    out.cloud_files = Some(cloud);
205    Ok(out)
206}
207
208/// On the receiving side, after the claim: check a cloud manifest, then
209/// fetch, decrypt and store each file, setting `req.files` for
210/// `jekt_files::prepare` to list. `Err` when the relay couldn't be reached,
211/// so the caller releases the claim for a retry; a file that is gone,
212/// tampered with or undecryptable is left out and listed as missing.
213pub(crate) async fn fetch(
214    base: &str,
215    http: &reqwest::Client,
216    token: &str,
217    agent_id: &str,
218    req: &mut InjectionRequest,
219    files: Vec<CloudFile>,
220    wan_msg_id: Option<&str>,
221) -> Result<(), String> {
222    let note = |req: &mut InjectionRequest, text: &str| {
223        req.files_delivery = Some(FilesDelivery { delivered: 0, text: text.to_string(), inline: Vec::new(), inline_charge: None });
224    };
225    let plain: Vec<JektFile> = files.iter().map(|f| f.file.clone()).collect();
226    // Before anything is fetched: malformed, or over the relay's limits for a file or the message.
227    if jekt_files::validate_cloud(&files).is_err() {
228        note(req, "The files sent with this message were malformed or over the cloud's limits, so none were delivered.");
229        return Ok(());
230    }
231    // A verified sender's signature covers the manifest through its msgid.
232    if req.wan_verified == Some(true) && !wan_msg_id.is_some_and(|m| jekt_files::cloud_msgid_binds(m, &files)) {
233        note(req, "The files sent with this message don't match its signature, so none were delivered.");
234        return Ok(());
235    }
236    req.files = Some(plain);
237    if super::jekt_files::withheld_reason(req).is_some() {
238        return Ok(()); // `prepare` says they were withheld
239    }
240    let Some(svc) = attachments::get() else {
241        return Ok(());
242    };
243    let base = base.trim_end_matches('/');
244    let derive = super::jekt_files::derives_on_receipt(req);
245    for f in &files {
246        if svc.store().has_blob(&f.file.sha256) {
247            continue; // already here: a retry, or the same file sent before
248        }
249        let key = match file_key(f, agent_id) {
250            Ok(key) => key,
251            Err(why) => {
252                tracing::warn!(file = %f.file.name, why, "jekt cloud files: key didn't open");
253                continue;
254            }
255        };
256        let issued = http
257            .get(format!("{base}/reactive/blob/{}", f.blob_id))
258            .header("Authorization", format!("Bearer {token}"))
259            .header("X-Agent-ID", agent_id)
260            .header("X-Agent-Instance", crate::muxbus::wan_lease::instance_id())
261            .send()
262            .await
263            .map_err(|e| format!("blob URL request failed: {e}"))?;
264        let status = issued.status();
265        if status == reqwest::StatusCode::NOT_FOUND || status == reqwest::StatusCode::GONE {
266            tracing::warn!(file = %f.file.name, %status, "jekt cloud files: blob not available");
267            continue;
268        }
269        if !status.is_success() {
270            return Err(format!("blob URL request answered {status}"));
271        }
272        let url = issued.json::<serde_json::Value>().await.ok().and_then(|v| v["url"].as_str().map(str::to_string));
273        let Some(url) = url else { return Err("blob URL answer unreadable".to_string()) };
274        let mut resp = http
275            .get(&url)
276            .timeout(TRANSFER_TIMEOUT)
277            .send()
278            .await
279            .and_then(|r| r.error_for_status())
280            .map_err(|e| format!("blob download failed: {e}"))?;
281        // Read no more than the file and its encryption can be.
282        let max = f.file.size as usize + OVERHEAD;
283        let mut blob = Vec::with_capacity(max.min(1 << 20));
284        let mut oversized = false;
285        while let Some(chunk) = resp.chunk().await.map_err(|e| format!("blob download cut short: {e}"))? {
286            if blob.len() + chunk.len() > max {
287                oversized = true;
288                break;
289            }
290            blob.extend_from_slice(&chunk);
291        }
292        if oversized {
293            tracing::warn!(file = %f.file.name, "jekt cloud files: blob larger than its file");
294            continue;
295        }
296        let plain = tokio::task::spawn_blocking(move || open(&blob, &key)).await.ok().flatten();
297        let intact = plain.filter(|p| p.len() as u64 == f.file.size && {
298            use sha2::Digest;
299            hex::encode(sha2::Sha256::digest(p)) == f.file.sha256
300        });
301        let Some(plain) = intact else {
302            tracing::warn!(file = %f.file.name, "jekt cloud files: blob didn't decrypt to its file");
303            continue;
304        };
305        store_fetched(&svc, &f.file, &plain, derive).await;
306    }
307    Ok(())
308}
309
310/// Put a fetched file's bytes in the store: derived on the way in when the
311/// sender is proven, else placed as they came.
312async fn store_fetched(svc: &Arc<attachments::Service>, f: &JektFile, plain: &[u8], derive: bool) {
313    let tmp = svc.store().new_incoming_path();
314    let stored = if tokio::fs::write(&tmp, plain).await.is_err() {
315        false
316    } else if derive {
317        svc.commit_upload(tmp.clone(), f.sha256.clone(), f.name.clone()).await.is_ok()
318    } else {
319        svc.store_undecoded(tmp.clone(), f.sha256.clone(), f.name.clone()).await.is_ok()
320    };
321    if !stored {
322        let _ = tokio::fs::remove_file(&tmp).await;
323        tracing::warn!(file = %f.name, "jekt cloud files: received file not stored");
324    }
325}
326
327/// The key `f`'s blob opens with, using `agent_id`'s WAN key on this install
328/// for a sealed one. `Err` says why not.
329fn file_key(f: &CloudFile, agent_id: &str) -> Result<[u8; 32], &'static str> {
330    let wan_key = || {
331        let wan = crate::backend::storage::wan_identity::global().ok_or("no WAN identity here")?;
332        let key = wan.agent_key_load(agent_id).ok().flatten().ok_or("no WAN key for this agent here")?;
333        let public = key.public_key_bytes().ok_or("malformed WAN key")?;
334        let seed: [u8; 32] = agentmux_common::jekt_sign::decode_key(&key.private_key)
335            .and_then(|k| k.try_into().ok())
336            .ok_or("malformed WAN key")?;
337        Ok((public, seed))
338    };
339    open_key(f, wan_key)
340}
341
342/// A plain key decoded, or a sealed one opened with the WAN keypair
343/// `wan_key` gives (asked for only then).
344fn open_key(f: &CloudFile, wan_key: impl FnOnce() -> Result<([u8; 32], [u8; 32]), &'static str>) -> Result<[u8; 32], &'static str> {
345    if !jekt_files::is_sealed_key(&f.key) {
346        return B64.decode(&f.key).ok().and_then(|k| k.try_into().ok()).ok_or("malformed");
347    }
348    let (public, seed) = wan_key()?;
349    jekt_seal::unwrap(&f.key, &public, &seed, &f.file.sha256, &f.blob_id).map_err(|e| match e {
350        // The lease moved between the send and the claim.
351        jekt_seal::UnwrapError::OtherKey => "sealed to another install's copy of this agent",
352        jekt_seal::UnwrapError::Failed => "sealed key didn't open",
353    })
354}
355
356#[cfg(test)]
357mod tests {
358    use super::*;
359
360    #[test]
361    fn a_sealed_blob_opens_only_with_its_key_and_untouched() {
362        let (blob, key) = seal(b"the file".to_vec()).unwrap();
363        assert_eq!(blob.len(), 8 + OVERHEAD);
364        assert_eq!(open(&blob, &key).as_deref(), Some(&b"the file"[..]));
365        let (_, other) = seal(b"x".to_vec()).unwrap();
366        assert_eq!(open(&blob, &other), None, "another key");
367        let mut tampered = blob.clone();
368        tampered[NONCE_LEN] ^= 1;
369        assert_eq!(open(&tampered, &key), None, "the tag catches a changed byte");
370        assert_eq!(open(&blob[..4], &key), None);
371    }
372
373    #[test]
374    fn each_send_uses_a_fresh_key_and_nonce() {
375        let (a, ka) = seal(b"same".to_vec()).unwrap();
376        let (b, kb) = seal(b"same".to_vec()).unwrap();
377        assert_ne!(ka, kb);
378        assert_ne!(a, b);
379    }
380
381    fn manifest() -> Vec<CloudFile> {
382        vec![CloudFile {
383            file: JektFile { sha256: "ab".repeat(32), name: "shot.png".into(), size: 3 },
384            key: "A".repeat(43) + "=",
385            blob_id: "blob-0123abcd-0000-4000-8000-0123456789ab".into(),
386        }]
387    }
388
389    #[test]
390    fn only_a_live_holder_that_says_so_takes_cloud_files() {
391        use crate::muxbus::wan_lease::Holder;
392        use crate::muxbus::wan_lease::HeldBy;
393        let capable = HeldBy { desc: "computer x".into(), features: vec![jekt_files::CLOUD_FEATURE.into()], ..Default::default() };
394        assert!(takes_cloud_files(&Holder::Other(capable)).is_ok());
395        let old = HeldBy { desc: "computer x".into(), ..Default::default() };
396        assert!(takes_cloud_files(&Holder::Other(old)).unwrap_err().contains("too old"));
397        // No live capable holder: an older install could claim it later.
398        for unknown in [Holder::Free, Holder::Yours, Holder::Unknown, Holder::Unsupported, Holder::Unreachable] {
399            assert!(takes_cloud_files(&unknown).is_err(), "{unknown:?}");
400        }
401    }
402
403    #[test]
404    fn a_key_sealed_by_the_sender_opens_on_the_receiver_and_its_blob_with_it() {
405        use agentmux_common::jekt_sign::{generate_wan_keypair, WanKeyRecord};
406        let (public, seed) = generate_wan_keypair([4; 32]);
407        let record = WanKeyRecord::certify(&[9; 32], "jf-mac", "stable", &public, "starpower", 1).unwrap();
408        let offer = jekt_seal::offer(&record.instance_id, "jf-mac", &public, &seed).unwrap();
409        let to = jekt_seal::check_offer(&offer, &record, "jf-mac").unwrap();
410
411        let (blob, key) = seal(b"the screenshot".to_vec()).unwrap();
412        let mut f = manifest().remove(0);
413        f.key = jekt_seal::wrap(&key, &to, &f.file.sha256, &f.blob_id).unwrap();
414        assert!(jekt_files::validate_cloud(std::slice::from_ref(&f)).is_ok(), "{}", f.key);
415
416        let opened = open_key(&f, || Ok((public, seed))).unwrap();
417        assert_eq!(open(&blob, &opened).as_deref(), Some(&b"the screenshot"[..]));
418        // Another install's copy of the agent, or none here.
419        let other = generate_wan_keypair([5; 32]);
420        assert!(open_key(&f, || Ok(other)).unwrap_err().contains("another install"));
421        assert_eq!(open_key(&f, || Err("no WAN key for this agent here")), Err("no WAN key for this agent here"));
422        // A plain key never asks for the WAN key.
423        let plain = CloudFile { key: B64.encode(key), ..f.clone() };
424        assert_eq!(open_key(&plain, || panic!("not asked")), Ok(key));
425    }
426
427    #[tokio::test]
428    async fn a_verified_jekt_whose_msgid_does_not_bind_its_manifest_gets_no_files() {
429        let client = reqwest::Client::new();
430        let mut req = InjectionRequest { wan_verified: Some(true), delivery_tier: Some("wan".into()), ..Default::default() };
431        fetch("http://127.0.0.1:1", &client, "t", "agenty", &mut req, manifest(), Some("m-1")).await.unwrap();
432        assert!(req.files.is_none());
433        assert!(req.files_delivery.unwrap().text.contains("don't match its signature"));
434    }
435
436    #[tokio::test]
437    async fn a_manifest_over_the_cloud_limits_is_refused_before_fetching() {
438        let client = reqwest::Client::new();
439        let mut files = manifest();
440        files[0].file.size = 30 * 1024 * 1024;
441        let mut req = InjectionRequest { delivery_tier: Some("wan".into()), ..Default::default() };
442        // Nothing listens at the base: a fetch would fail with Err.
443        fetch("http://127.0.0.1:1", &client, "t", "agenty", &mut req, files, None).await.unwrap();
444        assert!(req.files.is_none());
445        assert!(req.files_delivery.unwrap().text.contains("over the cloud's limits"));
446    }
447
448    #[tokio::test]
449    async fn a_failed_signature_withholds_cloud_files_without_fetching() {
450        let client = reqwest::Client::new();
451        let files = manifest();
452        let msgid = jekt_files::bind_cloud_msgid("m-1", &files);
453        let mut req = InjectionRequest { wan_verified: Some(false), delivery_tier: Some("wan".into()), ..Default::default() };
454        // Nothing listens at the base: a fetch would fail with Err.
455        fetch("http://127.0.0.1:1", &client, "t", "agenty", &mut req, files, Some(&msgid)).await.unwrap();
456        assert_eq!(req.files.as_ref().map(|f| f.len()), Some(1), "listed for `prepare` to say withheld");
457    }
458}