Skip to main content

agentmux_srv/server/
caller.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Who is calling, derived from the request's credential — identity M4a
5//! (`docs/specs/SPEC_AGENT_IDENTITY_CARRIED_NOT_DERIVED_2026_09_23.md`
6//! §6.5.3).
7//!
8//! A request that carries `X-Agent-Token` for a token this srv minted is
9//! [`Caller::Agent`] with that token's UID. Anything else is
10//! [`Caller::Unattributed`] — the UI, `bashwrap`, `muxsh`, a tokenless agent,
11//! a peer srv. **This is attribution, never authorization:** at the same-user
12//! boundary a request that omits its token cannot be told apart from the UI
13//! (§6.5.1), so nothing here refuses a request; the routes that act for an
14//! agent refuse one without a token themselves (`agent_only`). An unknown or foreign-channel
15//! token is counted and treated as absent — an agent deleted while running,
16//! or a token that reached another channel's srv through a forwarded
17//! environment, keeps working exactly as before.
18//!
19//! Derived only for requests that authenticated with the full instance key:
20//! a token on a LAN-key request must not lift it to host trust (§6.5.3).
21
22use axum::body::Body;
23use axum::extract::State;
24use axum::http::Request;
25use axum::middleware::Next;
26use axum::response::Response;
27
28use super::{AppState, ReactiveAuthVia};
29
30/// The request header an agent's MCP sets from its inherited
31/// `AGENTMUX_AGENT_TOKEN`.
32pub(crate) const AGENT_TOKEN_HEADER: &str = "X-Agent-Token";
33
34/// Who a request is attributed to. Inserted into every request's extensions
35/// on the authed and LAN-forward route groups.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub(crate) enum Caller {
38    /// Carried a token this srv minted for `uid`.
39    Agent { uid: String },
40    /// Anything else. Not an error, and not a lesser principal: most callers
41    /// (the UI among them) are this.
42    Unattributed,
43}
44
45impl Caller {
46    /// The caller's UID, if attributed.
47    pub(crate) fn uid(&self) -> Option<&str> {
48        match self {
49            Caller::Agent { uid } => Some(uid),
50            Caller::Unattributed => None,
51        }
52    }
53}
54
55/// The UID to persist beside an actor name (identity M4c-1, spec §6.5.9):
56/// the request's attributed UID, or `""` — unknown, never guessed — when the
57/// request is Unattributed or carries no `Caller` at all.
58pub(crate) fn attributed_uid(caller: Option<&Caller>) -> String {
59    caller
60        .and_then(Caller::uid)
61        .map(str::to_string)
62        .unwrap_or_default()
63}
64
65/// Resolve the request's [`Caller`]. Pure, so the rules are testable without
66/// a router: `token` is the header value, `full_key` whether the request
67/// authenticated with the full instance key, `lookup` the token index.
68/// What the token index said about a token.
69pub(crate) enum Lookup {
70    Index(Option<String>),
71    /// No index attached (it failed to build at boot) — counted apart from an
72    /// unknown token, so the two are not confused.
73    NoIndex,
74}
75
76pub(crate) fn derive_caller(
77    token: Option<&str>,
78    full_key: bool,
79    lookup: impl FnOnce(&str) -> Lookup,
80) -> Caller {
81    let Some(token) = token.map(str::trim).filter(|t| !t.is_empty()) else {
82        return Caller::Unattributed;
83    };
84    if !full_key {
85        crate::backend::agent_resolve::record_uid_fallback("m4.token_on_lan_key");
86        return Caller::Unattributed;
87    }
88    match lookup(token) {
89        Lookup::Index(Some(uid)) => Caller::Agent { uid },
90        Lookup::Index(None) => {
91            crate::backend::agent_resolve::record_uid_fallback("m4.token_unknown");
92            Caller::Unattributed
93        }
94        Lookup::NoIndex => {
95            crate::backend::agent_resolve::record_uid_fallback("m4.token_index_unavailable");
96            Caller::Unattributed
97        }
98    }
99}
100
101/// Inserts [`Caller`]. Layered *inside* `auth_middleware` /
102/// `lan_or_full_auth_middleware`; both mark which key authenticated the
103/// request (`ReactiveAuthVia`), and a `Caller` is derived only when that mark
104/// says the full key — a request that reached here unmarked is Unattributed,
105/// never assumed full-key (review on #3571). The WebSocket upgrade is always
106/// Unattributed (§6.5.3): WebSocket RPC is the UI's channel, and a token
107/// must never ride on it.
108pub(crate) async fn caller_middleware(
109    State(state): State<AppState>,
110    mut req: Request<Body>,
111    next: Next,
112) -> Response {
113    let full_key = req.extensions().get::<ReactiveAuthVia>() == Some(&ReactiveAuthVia::FullAuthKey);
114    // A CORS preflight skips auth, so it is never marked; it is not a
115    // token on a LAN key and must not be counted as one.
116    // A container token names its agent itself; a header can't re-point it.
117    let pinned = req
118        .extensions()
119        .get::<crate::backend::container::credential::ContainerGrant>()
120        .map(|g| g.agent_token.clone());
121    let header = if req.uri().path() == "/ws" || req.method() == axum::http::Method::OPTIONS {
122        None
123    } else {
124        req.headers()
125            .get(AGENT_TOKEN_HEADER)
126            .and_then(|v| v.to_str().ok())
127    };
128    let token = match &pinned {
129        Some(agent_token) => agent_token.as_deref(),
130        None => header,
131    };
132    let caller = derive_caller(token, full_key, |t| match state.mstore.token_index() {
133        Some(index) => Lookup::Index(index.uid_for(t)),
134        None => Lookup::NoIndex,
135    });
136    req.extensions_mut().insert(caller);
137    next.run(req).await
138}
139
140/// `GET /agentmux/identity/fallbacks` — every §9.2 counter and the two
141/// live gauges (§6.5.6). The phase gates read this: M4d and M5 wait for
142/// `live.tokenless_or_unknown` to reach zero and for the fallback counters
143/// to stop moving. Read-only; auth-gated like every loopback route.
144///
145/// Also reports who the request itself was attributed to (`caller`), so an
146/// agent can check that its token is being recognised.
147pub(crate) async fn handle_identity_fallbacks(
148    State(state): State<AppState>,
149    caller: Option<axum::Extension<Caller>>,
150) -> axum::Json<serde_json::Value> {
151    let counters: serde_json::Map<String, serde_json::Value> =
152        crate::backend::agent_resolve::uid_fallback_counts()
153            .into_iter()
154            .map(|(site, n)| (site.to_string(), serde_json::json!(n)))
155            .collect();
156    // `has_row` reads the store per UID-less registration, so off the async
157    // worker (incident #1782).
158    let registrations = state.reactive_handler.list_agents();
159    let mstore = state.mstore.clone();
160    // A failed read reports the gauges as null, never as a drained zero.
161    let gauges = tokio::task::spawn_blocking(move || {
162        crate::backend::identity_spawn::live_gauges(
163            &registrations,
164            |block| crate::backend::blockcontroller::get_controller(block).is_some(),
165            |block| crate::backend::identity_spawn::store_block_has_row(&mstore, block),
166        )
167    })
168    .await
169    .ok();
170    let (tokenless_or_unknown, unidentified) = match gauges {
171        Some((t, u)) => (serde_json::json!(t), serde_json::json!(u)),
172        None => (serde_json::Value::Null, serde_json::Value::Null),
173    };
174    let caller_uid = caller.as_ref().and_then(|c| c.0.uid().map(str::to_string));
175    axum::Json(serde_json::json!({
176        // Counters and gauges are in memory, per srv, since this boot: a
177        // counter that has not fired is absent (read it as zero), and a gate
178        // reader must sample every channel's srv (spec §9.2).
179        "boot_id": state.boot_id.to_string(),
180        "caller": caller_uid,
181        "counters": counters,
182        "gauges": {
183            "live.tokenless_or_unknown": tokenless_or_unknown,
184            "live.unidentified": unidentified,
185        },
186    }))
187}
188
189#[cfg(test)]
190mod tests {
191    use super::*;
192
193    fn index(token: &str) -> Lookup {
194        Lookup::Index((token == "tok-y").then(|| "uid-y".to_string()))
195    }
196
197    #[test]
198    fn a_known_token_on_the_full_key_is_the_agent() {
199        assert_eq!(
200            derive_caller(Some("tok-y"), true, index),
201            Caller::Agent {
202                uid: "uid-y".into()
203            }
204        );
205    }
206
207    #[test]
208    fn no_token_is_unattributed() {
209        assert_eq!(derive_caller(None, true, index), Caller::Unattributed);
210        assert_eq!(derive_caller(Some("  "), true, index), Caller::Unattributed);
211    }
212
213    /// Never a 401: an unknown token (deleted agent, another channel's srv)
214    /// is treated as absent.
215    #[test]
216    fn an_unknown_token_is_unattributed_not_refused() {
217        assert_eq!(
218            derive_caller(Some("tok-gone"), true, index),
219            Caller::Unattributed
220        );
221    }
222
223    #[test]
224    fn a_missing_index_is_unattributed() {
225        assert_eq!(
226            derive_caller(Some("tok-y"), true, |_| Lookup::NoIndex),
227            Caller::Unattributed
228        );
229    }
230
231    /// A token must not lift a LAN-key request to host trust.
232    #[test]
233    fn a_token_on_a_lan_key_request_is_ignored() {
234        assert_eq!(
235            derive_caller(Some("tok-y"), false, index),
236            Caller::Unattributed
237        );
238    }
239}