Skip to main content

agentmux_srv_core/muxbus/
relay.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Outbound cloud relay — jekt delivery **tier 4**.
5//!
6//! Tiers 1–3 (local handler, same-host registry including this machine's
7//! other AgentMux channels, LAN peer) all live in `server/reactive.rs`, and
8//! so does the hold: a known agent of this AgentMux that no tier found
9//! running is held there before this tier is tried, unless the relay says
10//! another install runs it. Tier 4 was, until this module existed, a comment
11//! there — `// 4. Return original error (muxbus-client will fall back to cloud
12//! relay)` — delegating to a "muxbus-client" that the callers agents actually
13//! use are not. The MCP `Message` tool's send POSTs to `/agentmux/reactive/inject`
14//! and bails on `success != true`, so the tier chain silently stopped at three
15//! while the tool's own description promised "local → LAN → cloud". See
16//! `docs/reports/REPORT_NETWORK_ARCHITECTURE_DRYNESS_AND_ROBUST_LAN_2026_09_06.md` §5.
17//!
18//! This module makes tier 4 real and owned by the same handler as the other
19//! three, so every caller inherits it instead of re-implementing it.
20//!
21//! ## What "success" means here
22//!
23//! Tier 4 is **store-and-forward, not delivery**. The cloud persists the
24//! injection and broadcasts a wake signal; the recipient's srv picks it up on
25//! its next sync, which may be seconds away or never (that instance may be
26//! offline). A 2xx here therefore means *queued*, and [`RelayOutcome::Queued`]
27//! is deliberately not named anything that reads as delivered — the tier-3
28//! forward path had exactly that confusion and it produced a real bug (see
29//! `forward_inject_to_peer`'s "one behaviour unified" note).
30
31use std::sync::Arc;
32
33use crate::backend::storage::store::Store;
34
35/// The cloud rejects anything larger (10 KB maximum). Checked locally so an oversized message fails with a
36/// useful error instead of a bare 400 after a round trip.
37const MAX_RELAY_MESSAGE_BYTES: usize = 10240;
38
39/// The longest delivery lifetime the cloud route accepts, in seconds (24 h).
40/// A sender's later deadline is clamped to it: the route cannot hold a message
41/// longer, and asking for longer is a 400 that would fail the send outright.
42const MAX_RELAY_TTL_SECONDS: i64 = 86_400;
43
44/// Bounds how long a failed local delivery can block on the cloud before the
45/// caller gets its answer. Tier 4 runs only after tiers 1–3 have already
46/// failed, so this is additive to a request that is already slow.
47const RELAY_TIMEOUT_SECS: u64 = 10;
48
49/// Base URL of the muxbus REST API.
50///
51/// The env override exists for tests and for running against a local muxbus
52/// server (`http://localhost:3100`, registered in the dev Cognito app client).
53/// Previously private to `pkce.rs`; promoted here because tier 4 needs the same
54/// resolution and two copies of "where is the cloud" is exactly the drift this
55/// report set out to remove.
56pub fn rest_base_url() -> String {
57    std::env::var("AGENTMUX_MUXBUS_REST_URL")
58        .ok()
59        .filter(|v| !v.is_empty())
60        .unwrap_or_else(|| crate::muxbus::cloud_subscriber::MUXBUS_REST_URL.to_string())
61}
62
63/// What the desktop's relay calls send as `User-Agent`, so the relay can tell
64/// app versions apart (reqwest sends none of its own).
65pub(crate) const USER_AGENT: &str = concat!("agentmux/", env!("CARGO_PKG_VERSION"));
66
67/// The most agents one batch request may name (the relay's own limit).
68pub(crate) const MAX_BATCH_AGENTS: usize = 50;
69
70/// How long to stop asking a relay that answered 404 to a batch route
71/// (`/reactive/pending-batch`, `/agents/lease/renew-batch`): it predates them.
72const BATCH_ROUTES_RETRY: std::time::Duration = std::time::Duration::from_secs(600);
73
74static BATCH_ROUTES_MISSING: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<String, std::time::Instant>>> =
75    std::sync::LazyLock::new(Default::default);
76
77/// Whether the relay at `base` recently answered 404 to a batch route. Its
78/// callers then ask per agent, as before the batch routes existed. Keyed by
79/// relay, so a relay without them never switches them off for another.
80pub(crate) fn batch_routes_missing(base: &str) -> bool {
81    BATCH_ROUTES_MISSING
82        .lock()
83        .unwrap_or_else(|e| e.into_inner())
84        .get(base)
85        .is_some_and(|until| *until > std::time::Instant::now())
86}
87
88/// Note a 404 from the relay at `base` to a batch route.
89pub(crate) fn note_batch_routes_missing(base: &str) {
90    tracing::info!("relay has no batch routes yet: asking per agent for now");
91    BATCH_ROUTES_MISSING
92        .lock()
93        .unwrap_or_else(|e| e.into_inner())
94        .insert(base.to_string(), std::time::Instant::now() + BATCH_ROUTES_RETRY);
95}
96
97/// The W3-S carried tuple (`SPEC_WAN_JEKT_VERIFICATION_2026_09_24.md` §2.1):
98/// the sender's WAN signature and the exact values it signed, so a receiver
99/// can re-check it. Field names are the cloud's; an old cloud silently
100/// drops them.
101#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
102pub struct WanCarried {
103    pub wan_sig: String,
104    pub wan_msg_id: String,
105    pub wan_ts_secs: i64,
106    pub wan_source_agent: String,
107    pub wan_target_agent: String,
108    pub wan_source_host: String,
109    pub wan_source_channel: String,
110    pub wan_key_fp: String,
111}
112
113/// The cloud's caps: signature ≤ 128 chars, identifiers ≤ 256.
114const MAX_CARRIED_SIG_CHARS: usize = 128;
115const MAX_CARRIED_ID_CHARS: usize = 256;
116
117/// Sign a WAN jekt at the instance that relays it, for the agent its token
118/// names (`docs/specs/SPEC_WAN_JEKT_SIGNED_BY_SRV_2026_10_14.md` §3). The
119/// tuple rides the relay only if **every** condition holds; otherwise the
120/// message is relayed exactly as before, with nothing carried, so every gap
121/// degrades to "unsigned", never to a false forgery alarm at the receiver.
122/// `Err` names the first condition that failed, for the "queued" log line.
123///
124/// 1. `signer` is the jekt's `source_agent`, established by the caller from
125///    the request's own agent token (`actor::uid_has_slug`), and only at the
126///    origin: a forwarded hop has no token, so `None`. Do not drop this gate:
127///    without it, any local process holding the instance key could have srv
128///    sign as any agent.
129/// 2. `wan.db` holds the agent's key, and the directory this relay sends
130///    into (this relay plus the signed-in account,
131///    `wan_publish::directory_id`) is confirmed to hold it, so a receiver can
132///    find it. A key published under another account or relay doesn't count.
133/// 3. Both ids are well-formed and every field is within the cloud's caps.
134///
135/// Every signed field but the message and target is srv's own: its instance,
136/// its channel, its clock. A `wan_sig`, host or timestamp in the request body
137/// is not read (agents signed these themselves before; see the spec §2).
138pub fn wan_sign_at_origin(
139    req: &crate::backend::reactive::types::InjectionRequest,
140    signer: Option<&str>,
141    wan: Option<&crate::backend::storage::wan_identity::WanIdentityStore>,
142    directory: Option<&str>,
143    local_channel: &str,
144    now_secs: i64,
145) -> Result<WanCarried, &'static str> {
146    use crate::backend::reactive::sanitize::validate_agent_id;
147
148    let wan = wan.ok_or("no wan.db")?;
149    // 1
150    let source = req.source_agent.as_deref().filter(|s| !s.is_empty()).ok_or("no source agent")?;
151    if signer != Some(source) {
152        return Err(if signer.is_none() { "no agent token" } else { "token names another agent" });
153    }
154    // The caller's id when it sent one (the MCP does), else a fresh one: the
155    // receiver's replay check only needs it unique per sender.
156    let minted;
157    let msg_id = match req.request_id.as_deref().filter(|s| !s.is_empty()) {
158        Some(id) => id,
159        None => {
160            minted = uuid::Uuid::new_v4().to_string();
161            &minted
162        }
163    };
164    // 2
165    let key = wan.agent_key_load(source).ok().flatten().ok_or("no key in wan.db")?;
166    let directory = directory.ok_or("no account to publish under")?;
167    if !wan.agent_key_is_published_to(source, &key, directory).unwrap_or(false) {
168        return Err("key not published to this directory");
169    }
170    // 3
171    if !validate_agent_id(source) || !validate_agent_id(&req.target_agent) {
172        return Err("malformed agent id");
173    }
174    let instance = wan
175        .instance_ensure(&crate::backend::reactive::registry::local_host_label())
176        .map_err(|_| "no instance")?;
177    if [msg_id, &instance.instance_id, local_channel].iter().any(|s| s.len() > MAX_CARRIED_ID_CHARS) || now_secs <= 0 {
178        return Err("over the cloud's caps");
179    }
180    let public = key.public_key_bytes().ok_or("malformed key")?;
181    let private = agentmux_common::jekt_sign::decode_key(&key.private_key).ok_or("malformed key")?;
182    let sig = agentmux_common::jekt_sign::sign_wan_jekt(
183        &private,
184        msg_id,
185        source,
186        &instance.instance_id,
187        local_channel,
188        &req.target_agent,
189        now_secs,
190        &req.message,
191    )
192    .ok_or("malformed key")?;
193    if sig.len() > MAX_CARRIED_SIG_CHARS {
194        return Err("over the cloud's caps");
195    }
196    Ok(WanCarried {
197        wan_sig: sig,
198        wan_msg_id: msg_id.to_string(),
199        wan_ts_secs: now_secs,
200        wan_source_agent: source.to_string(),
201        wan_target_agent: req.target_agent.clone(),
202        wan_source_host: instance.instance_id,
203        wan_source_channel: local_channel.to_string(),
204        wan_key_fp: agentmux_common::jekt_sign::wan_key_fingerprint(&public),
205    })
206}
207
208/// Outcome of a tier-4 relay attempt.
209///
210/// There is deliberately no "cloud not configured" variant: that condition is
211/// answered earlier and more cheaply by [`relay_token`] returning `None`, so
212/// reaching this function at all already means tier 4 exists here.
213#[derive(Debug)]
214pub enum RelayOutcome {
215    /// The cloud accepted and persisted the injection. **Queued, not
216    /// delivered** — see the module doc.
217    Queued {
218        injection_id: Option<String>,
219        /// Whether the target is one of the sender's own account's agents,
220        /// when the relay says. `Some(false)` is a likely
221        /// typo: the relay accepts any name.
222        target_in_account: Option<bool>,
223    },
224    /// The cloud was reachable and said no, or the request never landed.
225    Failed(String),
226}
227
228/// The body the cloud route takes, as this srv sends it: the message plus the
229/// carried signature tuple, files, the declared tier, and the sender's own
230/// deadline as the route's `ttl_seconds` (issue #3894).
231fn relay_body(
232    target_agent: &str,
233    message: &str,
234    priority: &str,
235    wan: Option<&WanCarried>,
236    files: Option<&[agentmux_common::jekt_files::CloudFile]>,
237    jekt_tier: Option<&crate::backend::reactive::types::JektTier>,
238    expires_at_ms: Option<i64>,
239) -> serde_json::Value {
240    let mut body = serde_json::json!({
241        "target_agent": target_agent,
242        "message": message,
243        "priority": priority,
244    });
245    // W3-S: the carried tuple rides alongside, only when the carry gate
246    // passed. Without it the body is byte-for-byte the old shape.
247    if let (Some(wan), Some(obj)) = (wan, body.as_object_mut()) {
248        if let Ok(serde_json::Value::Object(fields)) = serde_json::to_value(wan) {
249            obj.extend(fields);
250        }
251    }
252    // Files sent with it, uploaded already (server::jekt_cloud).
253    if let (Some(files), Some(obj)) = (files, body.as_object_mut()) {
254        obj.insert("files".to_string(), serde_json::to_value(files).unwrap_or_default());
255    }
256    // The tier the sender declared, when it declared one, so the receiver
257    // renders the same tier it would for a local jekt. The receiver's own
258    // trust rules still apply on top: a declared tier can raise a message to
259    // `sensitive`, never lower what those rules decide.
260    if let (Some(tier), Some(obj)) = (jekt_tier, body.as_object_mut()) {
261        obj.insert("jekt_tier".to_string(), serde_json::Value::String(tier.to_string()));
262    }
263    // Sent as the remaining lifetime, the unit the route takes, so the message
264    // cannot outlive its sender's window on the way and arrive stale. Clamped
265    // into the route's accepted range; a deadline already past never gets here
266    // — relay_inject drops it first.
267    if let Some(expires_at_ms) = expires_at_ms {
268        let remaining = (expires_at_ms - agentmux_common::time::now_ms()).div_euclid(1000);
269        let ttl = remaining.clamp(1, MAX_RELAY_TTL_SECONDS);
270        if let Some(obj) = body.as_object_mut() {
271            obj.insert("ttl_seconds".to_string(), serde_json::json!(ttl));
272        }
273    }
274    body
275}
276
277/// POST one injection to the cloud relay.
278///
279/// Deliberately takes `base_url` and `token` rather than resolving them
280/// internally: that keeps this function a pure HTTP operation with no globals,
281/// so the tests can point it at a stub relay without mutating process-wide env
282/// (which would race the rest of the test binary).
283///
284/// ## Contract (verified against the cloud relay)
285///
286/// - `source_agent` travels in the **`X-Agent-ID` header, not the body** — the
287///   route 400s without it and derives the sender from it alone.
288/// - `X-Client-Wrapped: true` is required. Without it the cloud wraps the
289///   message in its own `[JEKT:...]` marker before storing; the receiving srv
290///   then wraps it *again* in `Handler::inject_message`, so the recipient sees
291///   a doubled marker. Sending raw + telling the cloud not to wrap yields
292///   exactly one marker, applied by the receiver — identical to how tiers 2
293///   and 3 already behave.
294#[allow(clippy::too_many_arguments)]
295pub async fn relay_inject(
296    base_url: &str,
297    http: &reqwest::Client,
298    token: &str,
299    source_agent: &str,
300    target_agent: &str,
301    message: &str,
302    priority: &str,
303    wan: Option<&WanCarried>,
304    files: Option<&[agentmux_common::jekt_files::CloudFile]>,
305    jekt_tier: Option<&crate::backend::reactive::types::JektTier>,
306    expires_at_ms: Option<i64>,
307) -> RelayOutcome {
308    if message.len() > MAX_RELAY_MESSAGE_BYTES {
309        return RelayOutcome::Failed(format!(
310            "message is {} bytes; the cloud relay accepts at most {}",
311            message.len(),
312            MAX_RELAY_MESSAGE_BYTES
313        ));
314    }
315
316    // A deadline already past: the sender said delivering it is worth less
317    // than dropping it (issue #3894), so nothing goes to the relay — it would
318    // only be stored to expire there, and the recipient would never see it.
319    if expires_at_ms.is_some_and(|expires| expires <= agentmux_common::time::now_ms()) {
320        return RelayOutcome::Failed(
321            "the sender's deadline has passed; the message was dropped, not relayed".to_string(),
322        );
323    }
324    let url = format!("{}/reactive/inject", base_url.trim_end_matches('/'));
325    let body = relay_body(target_agent, message, priority, wan, files, jekt_tier, expires_at_ms);
326    let resp = http
327        .post(&url)
328        .header("Authorization", format!("Bearer {token}"))
329        .header("X-Agent-ID", source_agent)
330        .header("X-Client-Wrapped", "true")
331        .timeout(std::time::Duration::from_secs(RELAY_TIMEOUT_SECS))
332        .json(&body)
333        .send()
334        .await;
335    crate::connectivity::report_http(crate::connectivity::Service::Muxbus, &resp);
336
337    let resp = match resp {
338        Ok(r) => r,
339        Err(e) => return RelayOutcome::Failed(format!("cloud relay unreachable: {e}")),
340    };
341
342    let status = resp.status();
343    if status.is_success() {
344        let body: serde_json::Value = resp.json().await.unwrap_or_default();
345        // The route returns `success: true` alongside the id; treat an
346        // explicit non-true as a failure rather than assuming 2xx means yes —
347        // the same stricter reading tier 2/3 settled on.
348        if body.get("success").and_then(|v| v.as_bool()) != Some(true) {
349            return RelayOutcome::Failed(format!(
350                "cloud relay returned {status} without success:true"
351            ));
352        }
353        return RelayOutcome::Queued {
354            injection_id: body
355                .get("injection_id")
356                .and_then(|v| v.as_str())
357                .map(str::to_string),
358            target_in_account: body.get("target_in_account").and_then(|v| v.as_bool()),
359        };
360    }
361
362    // 402 is the free-tier quota wall, which is a user-actionable condition
363    // rather than a bug — surface the cloud's own message verbatim so the
364    // upgrade URL it includes reaches the operator.
365    let detail = resp.text().await.unwrap_or_default();
366    RelayOutcome::Failed(format!("cloud relay rejected: HTTP {status} — {detail}"))
367}
368
369/// Resolve the credential to relay as, preferring one bound to this specific
370/// sender over the shared account token — the same precedence the inbound
371/// path (`cloud_subscriber::sync_agent_reactive`) already uses, so a
372/// binding-enforced account behaves consistently in both directions.
373///
374/// `None` means the account isn't logged in to muxbus at all, i.e. tier 4
375/// doesn't exist here.
376///
377/// **`store` must be the one muxbus credentials actually live in —
378/// `AppState::id_store`,** the same store `CloudSubscriber::init_global` and
379/// every `muxbus.login`/`status`/`disconnect` handler use. Passing the
380/// per-channel `mstore` finds nothing whenever the shared root resolves (the
381/// normal case), so tier 4 would silently never fire for a logged-in user
382/// (reagent #3023 P0). Note this deliberately does NOT follow `AppState`'s
383/// general steer toward `identity_store` for new muxbus call sites: the
384/// credentials are written to `id_store`, and reading from a store the writer
385/// doesn't use would reintroduce the same bug whenever
386/// `isolated_auth_enabled()` redirects one but not the other.
387///
388/// Ordering matters. The shared account token is a purely local read, so it is
389/// checked FIRST: no credential means the account isn't logged in, and there is
390/// nothing for a per-agent credential to be provisioned against. Doing it the
391/// other way round makes `ensure_agent_credential` attempt a cloud
392/// provisioning round trip (`POST /agents/provision`) on a logged-out instance
393/// — once per failed local inject, i.e. on the hot path of every message to an
394/// unknown agent.
395///
396/// Returns the account too, read from the same shared token: the carry gate
397/// needs the directory this send goes into, and reading the account
398/// separately would let a sign-in in between pair one account's token with
399/// another's directory (Codex P2 on #3994).
400pub async fn relay_token(
401    source_agent: &str,
402    store: &Arc<Store>,
403    http: &reqwest::Client,
404) -> Option<RelayCredential> {
405    let scheduler = crate::broker::get_global()?;
406    let shared = crate::muxbus::cloud_subscriber::load_valid_token(store, &scheduler).await?;
407    let account_sub = crate::muxbus::pkce::token_sub(&shared);
408
409    let token = match crate::muxbus::agent_credentials::ensure_agent_credential(source_agent, store, http).await {
410        Some(per_agent) => per_agent,
411        None => shared,
412    };
413    // `ensure_agent_credential` loads the account token itself when it
414    // provisions, so a sign-in to another account in between could hand back
415    // the new account's per-agent token while `account_sub` is the old one's
416    // (Codex P2 on #3994). Look again; if the account moved, bind no account
417    // and the send goes unsigned rather than into the wrong directory.
418    let after = crate::muxbus::cloud_subscriber::load_valid_token(store, &scheduler)
419        .await
420        .map(|t| crate::muxbus::pkce::token_sub(&t));
421    Some(RelayCredential { token, account_sub: settled_account(account_sub, after) })
422}
423
424/// The account to bind a send to: the one its credential was resolved
425/// under, if it's still the signed-in one afterwards; empty otherwise.
426fn settled_account(before: String, after: Option<String>) -> String {
427    if after.as_deref() == Some(before.as_str()) {
428        before
429    } else {
430        String::new()
431    }
432}
433
434/// What [`relay_token`] resolved: the bearer to send with, and the account
435/// (`sub`) of the shared token it was resolved under — empty if that token
436/// names none, which leaves the carry gate without a directory (unsigned).
437pub struct RelayCredential {
438    pub token: String,
439    pub account_sub: String,
440}
441
442#[cfg(test)]
443mod tests {
444    use super::*;
445
446    /// A stub relay capturing the request it receives, so the tests can assert
447    /// on the wire contract (headers especially) and not just the outcome.
448    struct Captured {
449        agent_id: Option<String>,
450        client_wrapped: Option<String>,
451        authorization: Option<String>,
452        body: serde_json::Value,
453    }
454
455    async fn stub_relay(
456        status: axum::http::StatusCode,
457        response_body: &'static str,
458    ) -> (
459        String,
460        std::sync::Arc<std::sync::Mutex<Option<Captured>>>,
461        tokio_util::sync::DropGuard,
462    ) {
463        let seen = std::sync::Arc::new(std::sync::Mutex::new(None));
464        let sink = seen.clone();
465        let app = axum::Router::new().route(
466            "/reactive/inject",
467            axum::routing::post(
468                move |headers: axum::http::HeaderMap, body: axum::Json<serde_json::Value>| {
469                    let sink = sink.clone();
470                    async move {
471                        let get = |k: &str| {
472                            headers
473                                .get(k)
474                                .and_then(|v| v.to_str().ok())
475                                .map(str::to_string)
476                        };
477                        *sink.lock().unwrap() = Some(Captured {
478                            agent_id: get("x-agent-id"),
479                            client_wrapped: get("x-client-wrapped"),
480                            authorization: get("authorization"),
481                            body: body.0,
482                        });
483                        (
484                            status,
485                            [(axum::http::header::CONTENT_TYPE, "application/json")],
486                            response_body,
487                        )
488                    }
489                },
490            ),
491        );
492        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
493        let addr = listener.local_addr().unwrap();
494        let token = tokio_util::sync::CancellationToken::new();
495        let child = token.clone();
496        tokio::spawn(async move {
497            let _ = axum::serve(listener, app)
498                .with_graceful_shutdown(async move { child.cancelled().await })
499                .await;
500        });
501        (format!("http://{addr}"), seen, token.drop_guard())
502    }
503
504    #[tokio::test]
505    async fn a_queued_injection_returns_its_id() {
506        let (url, _seen, _g) = stub_relay(
507            axum::http::StatusCode::OK,
508            r#"{"success":true,"injection_id":"inj-42"}"#,
509        )
510        .await;
511        let out = relay_inject(
512            &url,
513            &reqwest::Client::new(),
514            "tok",
515            "agent2",
516            "clare",
517            "hello",
518            "normal",
519            None, None, None, None,
520        )
521        .await;
522        match out {
523            RelayOutcome::Queued { injection_id, target_in_account } => {
524                assert_eq!(injection_id.as_deref(), Some("inj-42"));
525                // An older relay says nothing about the account.
526                assert_eq!(target_in_account, None)
527            }
528            other => panic!("expected Queued, got {other:?}"),
529        }
530    }
531
532    /// The wire contract the cloud route actually enforces, pinned so a future
533    /// edit can't quietly drop a header the server 400s (or double-wraps)
534    /// without a test failing.
535    #[tokio::test]
536    async fn the_sender_travels_as_a_header_and_wrapping_is_declined() {
537        let (url, seen, _g) =
538            stub_relay(axum::http::StatusCode::OK, r#"{"success":true}"#).await;
539        let _ = relay_inject(
540            &url,
541            &reqwest::Client::new(),
542            "tok",
543            "agent2",
544            "clare",
545            "hello",
546            "urgent",
547            None, None, None, None,
548        )
549        .await;
550
551        let c = seen.lock().unwrap();
552        let c = c.as_ref().expect("stub relay saw no request");
553        assert_eq!(c.agent_id.as_deref(), Some("agent2"), "X-Agent-ID is required by the route");
554        assert_eq!(
555            c.client_wrapped.as_deref(),
556            Some("true"),
557            "without this the cloud wraps the marker and the receiver wraps it again"
558        );
559        assert_eq!(c.authorization.as_deref(), Some("Bearer tok"));
560        // source_agent is NOT a body field — the route reads it from the header.
561        assert!(c.body.get("source_agent").is_none());
562        assert_eq!(c.body.get("target_agent").and_then(|v| v.as_str()), Some("clare"));
563        assert_eq!(c.body.get("message").and_then(|v| v.as_str()), Some("hello"));
564        assert_eq!(c.body.get("priority").and_then(|v| v.as_str()), Some("urgent"));
565        assert!(c.body.get("ttl_seconds").is_none(), "no sender deadline: the route's own default applies");
566    }
567
568    /// Issue #3894: a jekt with a sender deadline tells the route how long it
569    /// may hold the message, in the route's own unit.
570    #[tokio::test]
571    async fn a_sender_deadline_travels_as_the_remaining_lifetime() {
572        let (url, seen, _g) = stub_relay(axum::http::StatusCode::OK, r#"{"success":true}"#).await;
573        let expires = agentmux_common::time::now_ms() + 600_000;
574        let _ = relay_inject(
575            &url,
576            &reqwest::Client::new(),
577            "tok",
578            "agent2",
579            "clare",
580            "hello",
581            "normal",
582            None, None, None,
583            Some(expires),
584        )
585        .await;
586        let c = seen.lock().unwrap();
587        let ttl = c
588            .as_ref()
589            .expect("stub relay saw no request")
590            .body
591            .get("ttl_seconds")
592            .and_then(|v| v.as_i64())
593            .expect("ttl_seconds reaches the route");
594        assert!((590..=600).contains(&ttl), "about ten minutes, got {ttl}");
595    }
596
597    /// Issue #3894: a request whose deadline has already passed is dropped,
598    /// not submitted — the relay must not store a message the sender said was
599    /// no longer worth delivering.
600    #[tokio::test]
601    async fn a_past_deadline_is_dropped_before_the_route_sees_it() {
602        let (url, seen, _g) = stub_relay(axum::http::StatusCode::OK, r#"{"success":true}"#).await;
603        let out = relay_inject(
604            &url,
605            &reqwest::Client::new(),
606            "tok",
607            "agent2",
608            "clare",
609            "hello",
610            "normal",
611            None, None, None,
612            Some(agentmux_common::time::now_ms() - 1_000),
613        )
614        .await;
615        assert!(matches!(out, RelayOutcome::Failed(_)), "dropped, got {out:?}");
616        assert!(seen.lock().unwrap().is_none(), "nothing reached the route");
617    }
618
619    #[tokio::test]
620    async fn a_quota_rejection_surfaces_the_clouds_own_message() {
621        let (url, _seen, _g) = stub_relay(
622            axum::http::StatusCode::PAYMENT_REQUIRED,
623            r#"{"error":"quota_exceeded","upgrade_url":"https://cloud.agentmux.ai/billing"}"#,
624        )
625        .await;
626        let out = relay_inject(
627            &url,
628            &reqwest::Client::new(),
629            "tok",
630            "agent2",
631            "clare",
632            "hello",
633            "normal",
634            None, None, None, None,
635        )
636        .await;
637        match out {
638            RelayOutcome::Failed(e) => {
639                assert!(e.contains("402"), "status should be visible: {e}");
640                assert!(e.contains("upgrade_url"), "cloud's own body should pass through: {e}");
641            }
642            other => panic!("expected Failed, got {other:?}"),
643        }
644    }
645
646    /// The relay says whether the target is one of the
647    /// sender's own account's agents; `false` reaches the `Message` tool as a
648    /// likely-typo hint.
649    #[tokio::test]
650    async fn a_queued_injection_carries_whether_the_target_is_the_senders() {
651        for (body, want) in [
652            (r#"{"success":true,"injection_id":"inj-7","target_in_account":false}"#, Some(false)),
653            (r#"{"success":true,"injection_id":"inj-8","target_in_account":true}"#, Some(true)),
654        ] {
655            let (url, _seen, _g) = stub_relay(axum::http::StatusCode::OK, body).await;
656            let out = relay_inject(&url, &reqwest::Client::new(), "tok", "agent2", "agnetx", "hello", "normal", None, None, None, None).await;
657            match out {
658                RelayOutcome::Queued { target_in_account, .. } => assert_eq!(target_in_account, want, "{body}"),
659                other => panic!("expected Queued, got {other:?}"),
660            }
661        }
662    }
663
664    /// A 2xx that doesn't say `success: true` must not count — the same
665    /// stricter reading the tier-2/3 forward helper settled on after the LAN
666    /// tier was found treating a body without `success` as a delivery.
667    #[tokio::test]
668    async fn a_2xx_without_success_true_is_a_failure() {
669        let (url, _seen, _g) =
670            stub_relay(axum::http::StatusCode::OK, r#"{"injection_id":"inj-1"}"#).await;
671        let out = relay_inject(
672            &url,
673            &reqwest::Client::new(),
674            "tok",
675            "agent2",
676            "clare",
677            "hello",
678            "normal",
679            None, None, None, None,
680        )
681        .await;
682        assert!(matches!(out, RelayOutcome::Failed(_)), "got {out:?}");
683    }
684
685    /// Checked locally so the caller gets a useful message instead of a bare
686    /// 400 after a wasted round trip.
687    #[tokio::test]
688    async fn an_oversized_message_is_rejected_before_any_request() {
689        let big = "x".repeat(MAX_RELAY_MESSAGE_BYTES + 1);
690        let out = relay_inject(
691            "http://127.0.0.1:1", // never contacted
692            &reqwest::Client::new(),
693            "tok",
694            "agent2",
695            "clare",
696            &big,
697            "normal",
698            None, None, None, None,
699        )
700        .await;
701        match out {
702            RelayOutcome::Failed(e) => assert!(e.contains("10240"), "{e}"),
703            other => panic!("expected Failed, got {other:?}"),
704        }
705    }
706
707    #[tokio::test]
708    async fn an_unreachable_relay_fails_rather_than_hanging() {
709        let url = {
710            let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
711            format!("http://{}", l.local_addr().unwrap())
712        };
713        let out = relay_inject(
714            &url,
715            &reqwest::Client::new(),
716            "tok",
717            "agent2",
718            "clare",
719            "hello",
720            "normal",
721            None, None, None, None,
722        )
723        .await;
724        assert!(matches!(out, RelayOutcome::Failed(_)), "got {out:?}");
725    }
726
727    // ── W3-S carry gate (§2.1) ──
728
729    use crate::backend::reactive::types::InjectionRequest;
730    use crate::backend::storage::wan_identity::WanIdentityStore;
731
732    /// A wan.db with a published key for `camper`, and a request exactly as
733    /// the MCP would send it: signed, host-verified, this instance.
734    const TEST_DIR: &str = "https://relay.test#acct";
735
736    #[test]
737    fn a_send_is_bound_to_an_account_only_if_it_held_through_resolution() {
738        // Codex P2 on #3994: a sign-in to another account while the per-agent
739        // credential resolves can pair one account's token with the other's
740        // directory. Then the send gets no account, so it goes unsigned.
741        assert_eq!(settled_account("acct-a".into(), Some("acct-a".into())), "acct-a");
742        assert_eq!(settled_account("acct-a".into(), Some("acct-b".into())), "");
743        assert_eq!(settled_account("acct-a".into(), None), "", "logged out mid-way");
744    }
745
746    const NOW: i64 = 1_790_000_000;
747
748    /// A jekt from "camper" to "agent2", as srv holds it at the origin, with
749    /// camper's key in wan.db and published.
750    fn origin_request() -> (tempfile::TempDir, WanIdentityStore, InjectionRequest) {
751        let dir = tempfile::tempdir().unwrap();
752        let wan = WanIdentityStore::open(&dir.path().join("wan.db")).unwrap();
753        let key = wan.agent_key_ensure("camper", None).unwrap();
754        wan.agent_key_mark_published("camper", &key.public_key, TEST_DIR).unwrap();
755        let req = InjectionRequest {
756            target_agent: "agent2".into(),
757            message: "hello".into(),
758            source_agent: Some("camper".into()),
759            request_id: Some("msg-1".into()),
760            ..Default::default()
761        };
762        (dir, wan, req)
763    }
764
765    #[test]
766    fn srv_signs_for_the_agent_its_token_names_and_a_receiver_can_check_it() {
767        let (_dir, wan, req) = origin_request();
768        let carried = wan_sign_at_origin(&req, Some("camper"), Some(&wan), Some(TEST_DIR), "stable", NOW)
769            .expect("every condition holds");
770        let instance = wan.instance_ensure(&crate::backend::reactive::registry::local_host_label()).unwrap();
771        let key = wan.agent_key_load("camper").unwrap().unwrap();
772        assert_eq!(carried.wan_msg_id, "msg-1");
773        assert_eq!(carried.wan_ts_secs, NOW, "srv's clock");
774        assert_eq!(carried.wan_source_agent, "camper");
775        assert_eq!(carried.wan_target_agent, "agent2");
776        assert_eq!(carried.wan_source_host, instance.instance_id, "srv's own instance");
777        assert_eq!(carried.wan_source_channel, "stable", "srv's own channel");
778        assert_eq!(
779            carried.wan_key_fp,
780            agentmux_common::jekt_sign::wan_key_fingerprint(&key.public_key_bytes().unwrap())
781        );
782        // What a receiver will reconstruct verifies against the published record.
783        let record = crate::muxbus::wan_publish::certify(&instance, "camper", "stable", &key).unwrap();
784        let view = agentmux_common::jekt_sign::WanCarried {
785            sig: &carried.wan_sig,
786            msg_id: &carried.wan_msg_id,
787            ts_secs: carried.wan_ts_secs,
788            source_agent: &carried.wan_source_agent,
789            target_agent: &carried.wan_target_agent,
790            source_host: &carried.wan_source_host,
791            source_channel: &carried.wan_source_channel,
792            key_fp: &carried.wan_key_fp,
793        };
794        assert_eq!(agentmux_common::jekt_sign::verify_wan_against_record(&view, &record, "hello"), Ok(()));
795        assert!(
796            agentmux_common::jekt_sign::verify_wan_against_record(&view, &record, "hello!").is_err(),
797            "the signature covers the message"
798        );
799    }
800
801    #[test]
802    fn a_request_with_no_id_is_signed_under_a_fresh_one() {
803        // `muxsh agent send` sends none.
804        let (_dir, wan, mut req) = origin_request();
805        req.request_id = None;
806        let a = wan_sign_at_origin(&req, Some("camper"), Some(&wan), Some(TEST_DIR), "stable", NOW).unwrap();
807        let b = wan_sign_at_origin(&req, Some("camper"), Some(&wan), Some(TEST_DIR), "stable", NOW).unwrap();
808        assert!(!a.wan_msg_id.is_empty());
809        assert_ne!(a.wan_msg_id, b.wan_msg_id, "unique per send, so the receiver's replay check passes");
810    }
811
812    #[test]
813    fn what_a_caller_puts_in_the_body_is_not_what_srv_signs() {
814        let (_dir, wan, mut req) = origin_request();
815        // An agent (or an older MCP) supplying its own signature, instance,
816        // channel and time: none of it is read.
817        req.wan_sig = Some("forged".into());
818        req.wan_source_host = Some("another-instance".into());
819        req.source_channel = Some("beta".into());
820        req.ts_secs = Some(1);
821        let carried = wan_sign_at_origin(&req, Some("camper"), Some(&wan), Some(TEST_DIR), "stable", NOW).unwrap();
822        assert_ne!(carried.wan_sig, "forged");
823        assert_ne!(carried.wan_source_host, "another-instance");
824        assert_eq!((carried.wan_source_channel.as_str(), carried.wan_ts_secs), ("stable", NOW));
825    }
826
827    #[test]
828    fn each_condition_failing_in_turn_sends_the_message_unsigned() {
829        let sign = |req: &InjectionRequest, signer: Option<&str>, wan: Option<&WanIdentityStore>, dir: Option<&str>| {
830            wan_sign_at_origin(req, signer, wan, dir, "stable", NOW).err()
831        };
832        let (_dir, wan, req) = origin_request();
833        // 1: no token (a terminal's muxsh, a script, a forwarded hop) ...
834        assert_eq!(sign(&req, None, Some(&wan), Some(TEST_DIR)), Some("no agent token"));
835        // ... or a token naming another agent than the jekt's source.
836        assert_eq!(sign(&req, Some("agent5"), Some(&wan), Some(TEST_DIR)), Some("token names another agent"));
837        let mut sourceless = req.clone();
838        sourceless.source_agent = None;
839        assert_eq!(sign(&sourceless, Some("camper"), Some(&wan), Some(TEST_DIR)), Some("no source agent"));
840        // 2
841        assert_eq!(sign(&req, Some("camper"), None, Some(TEST_DIR)), Some("no wan.db"));
842        assert_eq!(sign(&req, Some("camper"), Some(&wan), None), Some("no account to publish under"));
843        assert_eq!(
844            sign(&req, Some("camper"), Some(&wan), Some("https://relay.test#another-account")),
845            Some("key not published to this directory")
846        );
847        wan.agent_keys_delete(&["camper".to_string()]).unwrap();
848        assert_eq!(sign(&req, Some("camper"), Some(&wan), Some(TEST_DIR)), Some("no key in wan.db"));
849        // A re-minted key isn't published yet.
850        wan.agent_key_ensure("camper", None).unwrap();
851        assert_eq!(
852            sign(&req, Some("camper"), Some(&wan), Some(TEST_DIR)),
853            Some("key not published to this directory")
854        );
855        // 3
856        let (_dir, wan, mut bad) = origin_request();
857        bad.target_agent = "not a name!".into();
858        assert_eq!(sign(&bad, Some("camper"), Some(&wan), Some(TEST_DIR)), Some("malformed agent id"));
859    }
860
861    #[tokio::test]
862    async fn the_carried_tuple_rides_the_body_and_its_absence_keeps_the_old_shape() {
863        let (url, seen, _g) = stub_relay(axum::http::StatusCode::OK, r#"{"success":true}"#).await;
864        let (_dir, wan, req) = origin_request();
865        let carried = wan_sign_at_origin(&req, Some("camper"), Some(&wan), Some(TEST_DIR), "stable", NOW).unwrap();
866        let _ = relay_inject(&url, &reqwest::Client::new(), "tok", "camper", "agent2", "hello", "normal", Some(&carried), None, None, None)
867            .await;
868        {
869            let c = seen.lock().unwrap();
870            let body = &c.as_ref().unwrap().body;
871            for field in [
872                "wan_sig", "wan_msg_id", "wan_ts_secs", "wan_source_agent", "wan_target_agent",
873                "wan_source_host", "wan_source_channel", "wan_key_fp",
874            ] {
875                assert!(body.get(field).is_some(), "{field} missing from the relay body");
876            }
877            assert_eq!(body["wan_ts_secs"], serde_json::json!(NOW));
878        }
879
880        let _ = relay_inject(&url, &reqwest::Client::new(), "tok", "camper", "agent2", "hello", "normal", None, None, None, None).await;
881        let c = seen.lock().unwrap();
882        let keys: std::collections::BTreeSet<_> =
883            c.as_ref().unwrap().body.as_object().unwrap().keys().cloned().collect();
884        assert_eq!(
885            keys,
886            ["message", "priority", "target_agent"].into_iter().map(String::from).collect(),
887            "unsigned relays keep exactly the old body"
888        );
889    }
890
891    /// Files uploaded for a jekt ride its body as the manifest, keys and blob
892    /// ids included (SPEC_JEKT_FILE_TRANSFER_2026_10_05.md §4.4).
893    #[tokio::test]
894    async fn a_cloud_manifest_rides_the_body() {
895        let (url, seen, _g) = stub_relay(axum::http::StatusCode::OK, r#"{"success":true}"#).await;
896        let files = vec![agentmux_common::jekt_files::CloudFile {
897            file: agentmux_common::jekt_files::JektFile { sha256: "ab".repeat(32), name: "shot.png".into(), size: 3 },
898            key: "A".repeat(43) + "=",
899            blob_id: "blob-0123abcd-0000-4000-8000-0123456789ab".into(),
900        }];
901        let _ = relay_inject(&url, &reqwest::Client::new(), "tok", "camper", "agent2", "hello", "normal", None, Some(&files), None, None).await;
902        let c = seen.lock().unwrap();
903        let body = &c.as_ref().unwrap().body;
904        assert_eq!(body["files"][0]["blob_id"], "blob-0123abcd-0000-4000-8000-0123456789ab");
905        assert_eq!(body["files"][0]["sha256"], "ab".repeat(32), "the file's fields sit beside key and blob_id");
906        assert_eq!(body["files"][0]["key"], "A".repeat(43) + "=");
907    }
908
909    /// A declared tier travels with a WAN jekt, as its lowercase name; with
910    /// none declared the body has no `jekt_tier` key (the shape pinned in
911    /// `the_carried_tuple_rides_the_body_and_its_absence_keeps_the_old_shape`).
912    #[tokio::test]
913    async fn a_declared_tier_rides_the_body() {
914        use crate::backend::reactive::types::JektTier;
915        let (url, seen, _g) = stub_relay(axum::http::StatusCode::OK, r#"{"success":true}"#).await;
916        for (tier, want) in [(JektTier::Sensitive, "sensitive"), (JektTier::Info, "info"), (JektTier::Coord, "coord")] {
917            let _ = relay_inject(&url, &reqwest::Client::new(), "tok", "camper", "agent2", "hello", "normal", None, None, Some(&tier), None).await;
918            let c = seen.lock().unwrap();
919            assert_eq!(c.as_ref().unwrap().body["jekt_tier"], want);
920        }
921    }
922}