Skip to main content

agentmux_mcp/
identity.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Agent identity at the MCP boundary, jekt ids and outgoing jekt / UI-automation signatures.
5//! Split out of main.rs unchanged (SPEC_LARGE_FILE_MODULE_ANALYSIS_2026_09_30.md §4.2).
6
7use super::*;
8
9/// The calling agent's slug (its `AGENTMUX_AGENT_ID`), injected by AgentMux into
10/// this MCP server's trusted environment. MuxAPI identity/preset/memory
11/// REST endpoints stamp their `agent_id` from this — the agent's own model
12/// output cannot reach those endpoints (no auth key in the PTY) nor override
13/// this value, so the slug cannot be forged. See
14/// SPEC_AGENT_APP_API_MCP_BINDINGS_2026_06_28.md §5.
15pub(crate) fn agent_slug() -> Result<String> {
16    let slug = std::env::var("AGENTMUX_AGENT_ID").unwrap_or_default();
17    if slug.is_empty() {
18        anyhow::bail!(
19            "AGENTMUX_AGENT_ID is not set — cannot resolve this agent's identity. \
20             Is this agent pane opened via AgentMux?"
21        );
22    }
23    Ok(slug)
24}
25
26/// Identity M3 (spec §5): resolve a typed agent name at the boundary — the
27/// only place a name is turned into a UID — before a tool stores it.
28/// `Ok(Some(uid))` when exactly one identified agent matches; `Ok(None)` when
29/// none does, the match has no UID, or the srv predates the endpoint (the
30/// tool then sends the name and the server records the miss). `Err` in two
31/// cases, both of which fail the tool call: the name is ambiguous — the
32/// error lists the candidates so the model can retry by uid (§5.2) — or the
33/// resolver could not answer (a store fault, any other non-2xx, an
34/// unreadable or unexpected response), where sending the bare name would
35/// skip the ambiguity check. See `interpret_resolve_response`.
36pub(crate) async fn resolve_agent_name_at_boundary(
37    client: &reqwest::Client,
38    local_url: &str,
39    auth_key: &str,
40    name: &str,
41) -> Result<Option<String>> {
42    Ok(resolve_agent_target_at_boundary(client, local_url, auth_key, name).await?.uid())
43}
44
45/// What a typed agent name came to at the boundary.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub(crate) enum BoundaryResolution {
48    /// Exactly one identified agent: store its uid.
49    Uid(String),
50    /// An agent reachable by name only (no uid), or an srv too old to say:
51    /// send the bare name.
52    NameOnly,
53    /// No agent of that name on this computer, in any channel; the ids it most likely meant, best first.
54    NoSuchAgent(Vec<String>),
55}
56
57impl BoundaryResolution {
58    pub(crate) fn uid(self) -> Option<String> {
59        match self {
60            BoundaryResolution::Uid(uid) => Some(uid),
61            _ => None,
62        }
63    }
64}
65
66/// [`resolve_agent_name_at_boundary`], telling "no such agent" apart from
67/// "reachable by name only", for a caller that must refuse the first: a task
68/// filed for a name nobody answers to can never be claimed (#1257).
69pub(crate) async fn resolve_agent_target_at_boundary(
70    client: &reqwest::Client,
71    local_url: &str,
72    auth_key: &str,
73    name: &str,
74) -> Result<BoundaryResolution> {
75    let url = format!("{}/agentmux/agents/resolve", local_url.trim_end_matches('/'));
76    let resp = client
77        .post(&url)
78        .header(AUTH_KEY_HEADER, auth_key)
79        .json(&serde_json::json!({ "name": name }))
80        .send()
81        .await
82        .map_err(|e| anyhow::anyhow!("agent name resolve request failed: {e}"))?;
83    let status = resp.status();
84    let text = resp.text().await.unwrap_or_default();
85    interpret_resolve_detail(status, &text, name)
86}
87
88/// The response half of `resolve_agent_name_at_boundary`, separated so the
89/// status handling is testable without a server.
90pub(crate) fn interpret_resolve_response(
91    status: reqwest::StatusCode,
92    text: &str,
93    name: &str,
94) -> Result<Option<String>> {
95    Ok(interpret_resolve_detail(status, text, name)?.uid())
96}
97
98/// The response half of [`resolve_agent_target_at_boundary`].
99pub(crate) fn interpret_resolve_detail(
100    status: reqwest::StatusCode,
101    text: &str,
102    name: &str,
103) -> Result<BoundaryResolution> {
104    // Only an srv that predates the endpoint (404/405) gets the
105    // compatibility fallback of sending the bare name. Any other failure —
106    // a store fault (503), a panicked handler (500) — fails the tool call:
107    // proceeding by name would skip the ambiguity check and could hand the
108    // item to an exact-same-name other (Codex P2 on #3563).
109    if status == reqwest::StatusCode::NOT_FOUND || status == reqwest::StatusCode::METHOD_NOT_ALLOWED
110    {
111        return Ok(BoundaryResolution::NameOnly);
112    }
113    if !status.is_success() {
114        anyhow::bail!("could not resolve agent \"{name}\": HTTP {status} — {text}");
115    }
116    let v: Value = serde_json::from_str(text).map_err(|e| {
117        anyhow::anyhow!("could not resolve agent \"{name}\": unreadable response ({e})")
118    })?;
119    match v.get("resolution").and_then(|r| r.as_str()).unwrap_or("") {
120        "one" => match v
121            .get("uid")
122            .and_then(|u| u.as_str())
123            .filter(|u| !u.is_empty())
124        {
125            Some(uid) => Ok(BoundaryResolution::Uid(uid.to_string())),
126            None => anyhow::bail!(
127                "could not resolve agent \"{name}\": a single match came back without a uid"
128            ),
129        },
130        "ambiguous" => {
131            let listed: Vec<String> = v
132                .get("candidates")
133                .and_then(|c| c.as_array())
134                .map(|arr| {
135                    arr.iter()
136                        .map(|c| {
137                            format!(
138                                "  • {} (uid {}{}{})",
139                                c.get("name").and_then(|x| x.as_str()).unwrap_or("?"),
140                                c.get("uid").and_then(|x| x.as_str()).unwrap_or("none"),
141                                c.get("block_id").and_then(|x| x.as_str()).map(|b| format!(", block {b}")).unwrap_or_default(),
142                                if c.get("live").and_then(|x| x.as_bool()).unwrap_or(false) { ", live" } else { "" },
143                            )
144                        })
145                        .collect()
146                })
147                .unwrap_or_default();
148            anyhow::bail!(
149                "Several agents match \"{name}\":\n{}\nAddress one directly by uid, or rename one.",
150                listed.join("\n")
151            )
152        }
153        "none" => Ok(BoundaryResolution::NoSuchAgent(
154            v.get("did_you_mean")
155                .and_then(|d| d.as_array())
156                .map(|ids| ids.iter().filter_map(|i| i.as_str().map(String::from)).collect())
157                .unwrap_or_default(),
158        )),
159        "unidentified" => Ok(BoundaryResolution::NameOnly),
160        other => {
161            anyhow::bail!("could not resolve agent \"{name}\": unexpected resolution {other:?}")
162        }
163    }
164}
165
166/// Process-wide counter for `generate_jekt_msgid` — millis-timestamp alone
167/// isn't guaranteed unique if two jekts are sent in the same millisecond.
168pub(crate) static JEKT_MSGID_COUNTER: AtomicU64 = AtomicU64::new(0);
169
170/// A unique-enough message id for a signed jekt: no `uuid` dependency needed
171/// (this crate doesn't otherwise pull one in) — timestamp + this process's
172/// own pid + a monotonic counter is unique enough for its one purpose (a
173/// value both this signer and the receiving srv agree to include in the
174/// signed material, so a signature can't be replayed under a different id).
175pub(crate) fn generate_jekt_msgid() -> String {
176    let n = JEKT_MSGID_COUNTER.fetch_add(1, Ordering::Relaxed);
177    format!("{}-{}-{}", agentmux_common::time::now_ms_u64(), std::process::id(), n)
178}
179
180/// `FleetBroadcast`'s block_id -> agent-name resolution
181/// (REPORT_CROSS_INSTANCE_CONTROL_ROBUSTNESS_AUDIT_2026_08_22.md): a `/agentmux/discovery`
182/// response's `host.addressable` AND `host.cross_channel` sections both
183/// carry a `block_id` — `addressable` under `agent_id`/`block_id`,
184/// `cross_channel` (a different channel on this same host) under
185/// `name`/`block_id`. A block_id is unique across channels on one host, so
186/// both are folded into one map, not kept separate. `lan`/`wan` entries
187/// carry no `block_id` at all (they're not local blocks) — a target for
188/// those tiers is never in this map, and the caller falls back to treating
189/// it as a literal agent name instead (see the `FleetBroadcast` handler).
190///
191/// Pure (no I/O) — extracted so it's unit-testable without a live discovery
192/// endpoint.
193pub(crate) fn build_block_to_agent_map(discovery: &Value) -> std::collections::HashMap<String, String> {
194    let mut map: std::collections::HashMap<String, String> = discovery
195        .get("host")
196        .and_then(|h| h.get("addressable"))
197        .and_then(|v| v.as_array())
198        .map(|arr| {
199            arr.iter()
200                .filter_map(|e| {
201                    let agent_id = e.get("agent_id")?.as_str()?.to_string();
202                    let block_id = e.get("block_id")?.as_str()?.to_string();
203                    Some((block_id, agent_id))
204                })
205                .collect()
206        })
207        .unwrap_or_default();
208    if let Some(arr) = discovery.get("host").and_then(|h| h.get("cross_channel")).and_then(|v| v.as_array()) {
209        for e in arr {
210            if let (Some(name), Some(block_id)) = (
211                e.get("name").and_then(|v| v.as_str()),
212                e.get("block_id").and_then(|v| v.as_str()),
213            ) {
214                map.insert(block_id.to_string(), name.to_string());
215            }
216        }
217    }
218    map
219}
220
221/// Build the id/timestamp/host-signature/LAN-signature quadruple for an
222/// outgoing jekt (SPEC_JEKT_TRUST_LAYER_COMPLETION_2026_08_13.md §2.2,
223/// SPEC_JEKT_LAN_TIER_SIGNING_2026_08_15.md §2.3). Uses this agent's OWN
224/// host and LAN keys — fetched from srv with its own token (`self_keys.rs`,
225/// `GET /agentmux/agents/self/keys`), falling back to the
226/// `AGENTMUX_JEKT_KEY`/`AGENTMUX_LAN_KEY` written into this agent's env only
227/// — and signs over the same (msgid, source_agent, target_agent,
228/// ts_secs, message) material both schemes share.
229///
230/// Both signatures are computed unconditionally, regardless of which
231/// delivery tier the message actually ends up taking — this process has no
232/// reliable way to know that in advance (routing/forwarding is a
233/// server-side decision, see
234/// `docs/specs/SPEC_JEKT_LAN_TIER_SIGNING_2026_08_15.md` §3). Sending a
235/// `lan_sig` alongside a message that's actually delivered host or WAN
236/// costs nothing — srv only ever consults `lan_sig` when it has
237/// independently determined `delivery_tier == "lan"` (never trusting the
238/// message body's own claim), so an irrelevant signature is simply ignored.
239///
240/// Returns `(request_id, ts_secs, jekt_sig, lan_sig)`. Either signature is
241/// `None` — not an error — when its key is unavailable (no key from srv or
242/// env, or `source_agent` itself unresolved): srv never treats an absent
243/// signature as a reason to fail delivery, so a missing key here must never
244/// block the `Message` tool from sending.
245///
246/// The cross-channel signature (`channel_sig`,
247/// `SPEC_JEKT_CROSS_CHANNEL_TRUST_2026_09_02.md` §D5) rides along on the
248/// same terms as `lan_sig`: same `AGENTMUX_LAN_KEY`, but over a
249/// domain-separated payload that also binds this process's channel
250/// (`AGENTMUX_CHANNEL`, injected into this env at spawn by
251/// `inject_jekt_signing_keys_into_mcp_json`; defaults to `stable` exactly as
252/// srv's own registry writer does). srv only consults it once it has itself
253/// labelled the delivery `channel` — a same-machine forward to a different
254/// instance — so on every other tier it's simply ignored.
255///
256/// Returned as a named struct rather than a tuple: the three signatures are
257/// consecutive `Option<String>`s and a transposition at any of the call
258/// sites would compile clean and silently mislabel trust on the receiver.
259/// There is no WAN signature: srv makes it, at the origin, for the agent the
260/// request's `X-Agent-Token` names, with a key this process never holds
261/// (docs/specs/SPEC_WAN_JEKT_SIGNED_BY_SRV_2026_10_14.md).
262pub(crate) struct OutgoingJektSignatures {
263    request_id: String,
264    ts_secs: i64,
265    jekt_sig: Option<String>,
266    lan_sig: Option<String>,
267    source_channel: Option<String>,
268    channel_sig: Option<String>,
269    source_uid: Option<String>,
270    channel_sig_v2: Option<String>,
271    lan_sig_v2: Option<String>,
272}
273
274impl OutgoingJektSignatures {
275    /// The wire request these signatures were minted for — every send path
276    /// builds it through here so none can forget a field.
277    pub(crate) fn into_request(self, target_agent: String, message: String, source_agent: Option<String>) -> InjectRequest {
278        InjectRequest {
279            target_agent,
280            message,
281            source_agent,
282            request_id: Some(self.request_id),
283            ts_secs: Some(self.ts_secs),
284            jekt_sig: self.jekt_sig,
285            lan_sig: self.lan_sig,
286            source_channel: self.source_channel,
287            channel_sig: self.channel_sig,
288            source_uid: self.source_uid,
289            channel_sig_v2: self.channel_sig_v2,
290            lan_sig_v2: self.lan_sig_v2,
291            files: None,
292            priority: None,
293            reply: None,
294            in_reply_to: None,
295        }
296    }
297}
298
299/// The request for a jekt to `target_agent`, signed: every send path builds
300/// it here. The target is its route name first (`agent_route_name`: a fork's
301/// "Loap #3" is "Loap-3"), because the signatures bind the target: every hop
302/// routes by the route name, and normalizing a signed request at a hop would
303/// break its signature. A blank target is left blank.
304pub(crate) fn signed_jekt(source_agent: Option<String>, target_agent: &str, message: &str) -> InjectRequest {
305    signed_jekt_with_files(source_agent, target_agent, message, None)
306}
307
308/// [`signed_jekt`] for a jekt that carries files: its msgid ends in their
309/// manifest digest, so every signature below covers them too
310/// (`agentmux_common::jekt_files`).
311pub(crate) fn signed_jekt_with_files(
312    source_agent: Option<String>,
313    target_agent: &str,
314    message: &str,
315    files: Option<Vec<agentmux_common::jekt_files::JektFile>>,
316) -> InjectRequest {
317    let target = if target_agent.trim().is_empty() {
318        target_agent.to_string()
319    } else {
320        agentmux_common::slug::agent_route_name(target_agent)
321    };
322    let mut req = sign_outgoing_jekt(source_agent.as_deref(), &target, message, files.as_deref())
323        .into_request(target, message.to_string(), source_agent);
324    req.files = files;
325    req
326}
327
328pub(crate) fn sign_outgoing_jekt(
329    source_agent: Option<&str>,
330    target_agent: &str,
331    message: &str,
332    files: Option<&[agentmux_common::jekt_files::JektFile]>,
333) -> OutgoingJektSignatures {
334    let msgid = match files {
335        Some(files) => agentmux_common::jekt_files::bind_msgid(&generate_jekt_msgid(), files),
336        None => generate_jekt_msgid(),
337    };
338    let ts_secs = agentmux_common::time::now_secs();
339    // The keys: fetched from srv when they're this agent's, else the env's
340    // (identity M4d-3, self_keys.rs).
341    let jekt_sig = (|| {
342        let key = crate::self_keys::jekt_key()?;
343        let src = source_agent?;
344        Some(agentmux_common::jekt_sign::sign_jekt(&key, &msgid, src, target_agent, ts_secs, message))
345    })();
346    let lan_key = crate::self_keys::lan_key();
347    let lan_sig = (|| {
348        let key = lan_key.as_deref()?;
349        let src = source_agent?;
350        agentmux_common::jekt_sign::sign_lan_jekt(key, &msgid, src, target_agent, ts_secs, message)
351    })();
352    let source_channel = std::env::var("AGENTMUX_CHANNEL").ok().filter(|s| !s.is_empty());
353    let channel_sig = (|| {
354        let key = lan_key.as_deref()?;
355        let src = source_agent?;
356        // Same default srv's registry writer uses (`local_channel_id`): an
357        // unset var means the stable channel, not "unknown".
358        let channel = source_channel.as_deref().unwrap_or("stable");
359        agentmux_common::jekt_sign::sign_channel_jekt(key, &msgid, src, channel, target_agent, ts_secs, message)
360    })();
361    // Identity M4d-6: the same cross-channel and LAN material plus this
362    // agent's UID, signed with its UID-keyed key (fetched, never from env), so
363    // a receiver learns which agent sent it, not just which name.
364    let (source_uid, channel_sig_v2, lan_sig_v2) = match (crate::self_keys::uid_signer(), source_agent) {
365        (Some((uid, key)), Some(src)) => {
366            let channel = source_channel.as_deref().unwrap_or("stable");
367            let sig = agentmux_common::jekt_sign::sign_channel_jekt_v2(&key, &msgid, src, &uid, channel, target_agent, ts_secs, message);
368            let lan = agentmux_common::jekt_sign::sign_lan_jekt_v2(&key, &msgid, src, &uid, target_agent, ts_secs, message);
369            (sig.is_some().then_some(uid), sig, lan)
370        }
371        _ => (None, None, None),
372    };
373    let source_channel = (channel_sig.is_some() || channel_sig_v2.is_some())
374        .then(|| source_channel.unwrap_or_else(|| "stable".to_string()));
375    OutgoingJektSignatures {
376        request_id: msgid,
377        ts_secs,
378        jekt_sig,
379        lan_sig,
380        source_channel,
381        channel_sig,
382        source_uid,
383        channel_sig_v2,
384        lan_sig_v2,
385    }
386}
387
388/// Build the identity proof every `/api/v1/ui/*` request carries — an
389/// HMAC-SHA256 signature over this agent's own agent_id, using this
390/// agent's own `AGENTMUX_JEKT_KEY` (the same per-agent key `sign_outgoing_jekt`
391/// above uses for jekt messages; reused rather than inventing a parallel
392/// credential system). Unlike jekt signing, a missing key here is a hard
393/// error, not a silent "send unsigned" — srv has no unverified fallback
394/// path for UI automation (see `crates/srv/src/server/ui_handlers.rs`'s
395/// module doc comment), so a tool call with no key would just 401 anyway;
396/// failing fast with a clear "respawn to get a key" message is more useful
397/// than a confusing round trip.
398pub(crate) fn sign_ui_automation_auth() -> Result<agentmux_common::api_types::UiAutomationAuth> {
399    let agent_id = agent_slug()?;
400    // The jekt key it signs v1 with (identity M4d-3): fetched when ours.
401    let ts_secs = agentmux_common::time::now_secs();
402    let Some(key) = crate::self_keys::jekt_key() else {
403        // A container agent holds no key: srv attributes the request by the container's token and ignores
404        // the signature then. Should it not, the empty signature fails there like any other bad one.
405        if crate::self_keys::in_container() {
406            return Ok(agentmux_common::api_types::UiAutomationAuth { agent_id, ts_secs, sig: String::new() });
407        }
408        if crate::self_keys::fetch_in_progress() {
409            anyhow::bail!(
410                "this agent's signing key is still being fetched from AgentMux (the agent has only just started): \
411                 try again in a few seconds; if the same answer comes back, the agent needs to be respawned to \
412                 get a signing key"
413            );
414        }
415        anyhow::bail!(
416            "srv served no signing key (it was not reachable, or did not accept this agent's token) — this agent \
417             needs to be respawned to get a signing key before it can use UI automation \
418             (the UI tool)"
419        );
420    };
421    let sig = agentmux_common::jekt_sign::sign_jekt(
422        &key,
423        "ui-automation-identity",
424        &agent_id,
425        "__srv__",
426        ts_secs,
427        "",
428    );
429    Ok(agentmux_common::api_types::UiAutomationAuth { agent_id, ts_secs, sig })
430}
431
432#[cfg(test)]
433mod signed_jekt_tests {
434    use super::{signed_jekt, signed_jekt_with_files};
435
436    /// A jekt with files is signed under a msgid that binds them, so every
437    /// signature covers them; a text-only jekt is exactly as before.
438    #[test]
439    fn files_are_bound_into_the_signed_msgid() {
440        use agentmux_common::jekt_files::{msgid_binds, JektFile};
441        let files = vec![JektFile { sha256: "ab".repeat(32), name: "shot.png".into(), size: 3 }];
442        let req = signed_jekt_with_files(None, "agent2", "look", Some(files.clone()));
443        assert!(msgid_binds(req.request_id.as_deref().unwrap(), &files));
444        assert_eq!(req.files, Some(files));
445        let text = signed_jekt(None, "agent2", "look");
446        assert_eq!(agentmux_common::jekt_files::bound_digest(text.request_id.as_deref().unwrap()), None);
447        assert_eq!(text.files, None);
448    }
449
450    /// The target is signed and sent as its route name, so every hop routes
451    /// by the name the fork registered under; an `@` address is left alone.
452    #[test]
453    fn a_display_name_target_is_sent_as_its_route_name() {
454        assert_eq!(signed_jekt(None, "Loap #3", "hi").target_agent, "Loap-3");
455        assert_eq!(signed_jekt(None, "agent2", "hi").target_agent, "agent2");
456        assert_eq!(signed_jekt(None, "agent2@narko", "hi").target_agent, "agent2@narko");
457    }
458}