Skip to main content

agentmux_srv/server/
agent_self_keys.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `GET /agentmux/agents/self/keys` — identity M4d-3
5//! (`SPEC_AGENT_IDENTITY_CARRIED_NOT_DERIVED_2026_09_23.md` §6.5.10).
6//!
7//! An agent's MCP fetches its own signing keys here instead of reading them
8//! from `.mcp.json`, which goes stale: the host jekt key rotates after 24 h
9//! (`JEKT_KEY_TTL_SECS`) while a running agent keeps the copy it was launched
10//! with. Served only to `Caller::Agent(uid)`, the agent its `X-Agent-Token`
11//! names: these are private keys, so the 401 is this endpoint's own.
12//!
13//! The name-keyed jekt, LAN and WAN keys are those of the row's slug only,
14//! ensured as injection ensures them (so the jekt key rotates here), and the
15//! response says which slug they belong to: the MCP uses them only when that
16//! slug is exactly its own `AGENTMUX_AGENT_ID`. The UID-keyed LAN and WAN keys
17//! (M4d-2) ride along for M4d-6's v2 signatures. Nothing here is logged.
18
19use axum::extract::State;
20use axum::http::{header, StatusCode};
21use axum::response::{IntoResponse, Response};
22use axum::Json;
23use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
24use serde::Serialize;
25
26use super::caller::Caller;
27use super::AppState;
28
29#[derive(Serialize, Debug, PartialEq, Eq)]
30pub(crate) struct SelfKeys {
31    /// The row's slug: the only name these name-keyed keys are for.
32    pub slug: String,
33    /// Host-tier HMAC key, base64.
34    pub jekt_key: Option<String>,
35    /// When `jekt_key` expires (unix seconds). srv rotates a key only once it
36    /// has, so the MCP re-fetches at this time, not on a clock of its own.
37    pub jekt_key_expires_at: Option<i64>,
38    /// LAN (and cross-channel) Ed25519 private key, base64.
39    pub lan_key: Option<String>,
40    pub uid: String,
41    /// The UID-keyed LAN private key (M4d-2), base64.
42    pub uid_lan_key: Option<String>,
43    // No WAN key, name- or UID-keyed: srv signs WAN jekts itself
44    // (SPEC_WAN_JEKT_SIGNED_BY_SRV_2026_10_14.md), so no agent holds one.
45}
46
47/// The keys for `uid`, or `None` when it has no row.
48pub(crate) fn self_keys_for(mstore: &crate::backend::storage::store::Store, uid: &str) -> Option<SelfKeys> {
49    let def = mstore.agent_def_get(uid).ok().flatten()?;
50    let slug = def.slug.trim().to_string();
51    // Name-keyed keys are stored under the folded name: when another row's
52    // slug folds to the same one (`Victim` beside `victim`), they aren't this
53    // row's alone, so none are served (`actor::uid_owns_name`).
54    let named = !slug.is_empty() && super::actor::uid_owns_name(mstore, uid, &slug);
55    let jekt_key = named.then(|| mstore.agent_jekt_key_ensure(&slug).ok()).flatten().map(|k| BASE64.encode(k));
56    let jekt_key_expires_at = named.then(|| mstore.agent_jekt_key_expires_at(&slug).ok().flatten()).flatten();
57    let lan_key = named.then(|| mstore.agent_lan_key_ensure(&slug).ok()).flatten().map(|k| k.private_key);
58    let uid_keys = mstore.agent_uid_keys_ensure(uid).ok().flatten().map(|(keys, _)| keys);
59    Some(SelfKeys {
60        slug,
61        jekt_key,
62        jekt_key_expires_at,
63        lan_key,
64        uid: uid.to_string(),
65        uid_lan_key: uid_keys.map(|k| k.lan.private_key),
66    })
67}
68
69pub(crate) async fn handle_agent_self_keys(State(state): State<AppState>, caller: Option<axum::Extension<Caller>>) -> Response {
70    let Some(uid) = caller.as_deref().and_then(Caller::uid).map(str::to_string) else {
71        return (StatusCode::UNAUTHORIZED, Json(serde_json::json!({ "error": "agents/self/keys: this request carries no agent identity (X-Agent-Token)" }))).into_response();
72    };
73    let mstore = state.mstore.clone();
74    let keys = tokio::task::spawn_blocking(move || self_keys_for(&mstore, &uid)).await.ok().flatten();
75    match keys {
76        Some(keys) => ([(header::CACHE_CONTROL, "no-store")], Json(keys)).into_response(),
77        None => (StatusCode::NOT_FOUND, Json(serde_json::json!({ "error": "agents/self/keys: no agent row for this token" }))).into_response(),
78    }
79}
80
81#[cfg(test)]
82mod tests {
83    use super::*;
84    use crate::backend::storage::agents::test_agent_def;
85    use crate::backend::storage::store::Store;
86
87    fn store_with(uid: &str, slug: &str) -> Store {
88        let store = Store::open_in_memory().unwrap();
89        let mut def = test_agent_def(uid, slug, "claude", "agent", agentmux_common::time::now_ms(), "");
90        def.slug = slug.to_string();
91        store.agent_def_insert(&mut def).unwrap();
92        store
93    }
94
95    #[test]
96    fn serves_the_slug_s_keys_the_same_ones_injection_writes() {
97        let store = store_with("uid-aria", "aria");
98        let keys = self_keys_for(&store, "uid-aria").unwrap();
99        assert_eq!(keys.slug, "aria");
100        assert_eq!(keys.jekt_key, Some(BASE64.encode(store.agent_jekt_key_ensure("aria").unwrap())));
101        assert_eq!(keys.lan_key, Some(store.agent_lan_key_ensure("aria").unwrap().private_key));
102        assert!(keys.uid_lan_key.is_some());
103        let expires = keys.jekt_key_expires_at.expect("an expiry with the key");
104        let ttl = crate::backend::storage::agent_jekt_keys::JEKT_KEY_TTL_SECS;
105        assert!((expires - agentmux_common::time::now_secs() - ttl).abs() <= 5, "a fresh key expires a TTL from now");
106        assert_eq!(self_keys_for(&store, "uid-aria").unwrap(), keys, "stable across fetches");
107    }
108
109    #[test]
110    fn no_wan_private_key_is_served_even_with_a_wan_db() {
111        // srv signs WAN jekts itself (SPEC_WAN_JEKT_SIGNED_BY_SRV_2026_10_14.md).
112        let store = store_with("uid-aria", "aria");
113        let dir = tempfile::tempdir().unwrap();
114        let wan = std::sync::Arc::new(
115            crate::backend::storage::wan_identity::WanIdentityStore::open(&dir.path().join("wan.db")).unwrap(),
116        );
117        store.set_wan_identity(wan.clone());
118        let key = wan.agent_key_ensure("aria", None).unwrap();
119        let body = serde_json::to_string(&self_keys_for(&store, "uid-aria").unwrap()).unwrap();
120        assert!(!body.contains("wan_key"), "{body}");
121        assert!(!body.contains(&key.private_key), "the wan.db private key never leaves srv");
122    }
123
124    #[test]
125    fn an_unknown_uid_gets_nothing() {
126        let store = Store::open_in_memory().unwrap();
127        assert_eq!(self_keys_for(&store, "uid-nobody"), None);
128    }
129}