Skip to main content

agentmux_mcp/
self_keys.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Identity M4d-3: this agent's signing keys, fetched from srv
5//! (`GET /agentmux/agents/self/keys`) rather than only read from `.mcp.json`
6//! (`SPEC_AGENT_IDENTITY_CARRIED_NOT_DERIVED_2026_09_23.md` ยง6.5.10).
7//!
8//! The env copy goes stale: srv rotates the host jekt key after 24 h, and an
9//! agent running longer keeps signing with the key it was launched with, so
10//! every jekt it sends fails srv's check. Fetched at startup and again once
11//! the fetched key reaches the expiry srv served with it: srv rotates a key
12//! only after that, so until then nothing newer exists, and the fetch that
13//! follows it is what rotates it. Checked before every tool call, so a UI
14//! automation proof is signed with a live key too.
15//!
16//! The start file holds no signing value, so these fetched keys are the keys. The name-keyed ones
17//! are used only when the slug srv served them for is exactly this process's `AGENTMUX_AGENT_ID`
18//! (a spawn writes the definition's slug there, so the two agree; an agent that still signs under
19//! a name its row doesn't have signs with the env keys of a file an older version wrote, if any).
20//! The UID-keyed keys are held for M4d-6's v2 signatures. Nothing here is
21//! logged.
22
23use std::sync::Mutex;
24use std::time::{Duration, Instant};
25
26use agentmux_common::AUTH_KEY_HEADER;
27use serde::Deserialize;
28
29/// Re-fetch a copy this old even with no expiry to go by (an older srv).
30const REFRESH_AFTER: Duration = Duration::from_secs(5 * 60);
31
32#[derive(Deserialize, Default, Clone)]
33struct Wire {
34    slug: String,
35    jekt_key: Option<String>,
36    /// Unix seconds; absent from an srv that predates it.
37    #[serde(default)]
38    jekt_key_expires_at: Option<i64>,
39    lan_key: Option<String>,
40    #[serde(default)]
41    uid: String,
42    uid_lan_key: Option<String>,
43}
44
45struct Cached {
46    keys: Wire,
47    fetched_at: Instant,
48}
49
50static CACHE: Mutex<Option<Cached>> = Mutex::new(None);
51
52/// `AGENTMUX_AGENT_ID` and the key env vars are process-wide: every test that sets them holds this.
53#[cfg(test)]
54pub(crate) static ENV_LOCK: Mutex<()> = Mutex::new(());
55
56static FETCH: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
57
58/// The answer srv gives a request whose identity signature does not verify: the key this process holds is not the
59/// one srv has (it was replaced while this process ran).
60const REJECTED_SIGNATURE: &str = "identity signature verification failed";
61
62/// Whether a tool's error is srv rejecting this agent's signature.
63pub(crate) fn is_rejected_signature(error: &str) -> bool {
64    error.contains(REJECTED_SIGNATURE)
65}
66
67/// `run`, and once more after srv rejects its signature: the key held is not the one srv has (it was replaced while
68/// this process ran), so the keys are asked for again first. A rejected call did nothing, so repeating it is safe.
69pub(crate) async fn run_healing_a_rejected_signature<T, Fut>(
70    client: &reqwest::Client,
71    local_url: &str,
72    auth_key: &str,
73    run: impl Fn() -> Fut,
74) -> anyhow::Result<T>
75where
76    Fut: std::future::Future<Output = anyhow::Result<T>>,
77{
78    match run().await {
79        Err(e) if is_rejected_signature(&format!("{e:#}")) => {
80            forget_fetched();
81            refresh_if_stale(client, local_url, auth_key).await;
82            run().await
83        }
84        other => other,
85    }
86}
87
88/// Drop the held copy and the retry gate, so the next `refresh_if_stale` asks srv again at once.
89pub(crate) fn forget_fetched() {
90    *CACHE.lock().unwrap_or_else(|e| e.into_inner()) = None;
91    *LAST_ATTEMPT.lock().unwrap_or_else(|e| e.into_inner()) = None;
92}
93
94/// When a fetch was last tried. With no usable copy (an srv without the
95/// endpoint, an unreachable one), every tool call would otherwise retry and
96/// wait out the request; this spaces the retries.
97static LAST_ATTEMPT: Mutex<Option<Instant>> = Mutex::new(None);
98const RETRY_AFTER: Duration = Duration::from_secs(60);
99/// Short, so a slow srv delays a tool call by this at most.
100const FETCH_TIMEOUT: Duration = Duration::from_secs(3);
101
102/// Whether this process runs in a container agent's container, by the hint srv puts in its environment.
103/// Only a hint for this client (srv never reads it): it makes the MCP skip signing material it holds none
104/// of, and srv attributes the request by the container's token.
105pub(crate) fn in_container() -> bool {
106    is_container_hint(std::env::var("AGENTMUX_IN_CONTAINER").ok().as_deref())
107}
108
109fn is_container_hint(value: Option<&str>) -> bool {
110    value == Some("1")
111}
112
113/// Fetch the keys if there is no copy yet, or it is older than five minutes (a key replaced while this process ran is picked up then; srv serves the same one until it is replaced). Errors
114/// leave the old copy (or none) in place: signing then falls back to the env
115/// keys, exactly as before M4d-3.
116pub(crate) async fn refresh_if_stale(client: &reqwest::Client, local_url: &str, auth_key: &str) {
117    // One fetch at a time: a call made while the startup fetch is in flight waits for it (the start file holds
118    // no key to sign with meanwhile), then finds the copy it left.
119    let _one_fetch = FETCH.lock().await;
120    let fresh = CACHE.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|c| still_good(c, agentmux_common::time::now_secs()));
121    // In a container srv signs for the agent and refuses this route: the hint skips the call.
122    if fresh || in_container() || local_url.is_empty() || std::env::var("AGENTMUX_AGENT_TOKEN").map_or(true, |t| t.trim().is_empty()) {
123        return;
124    }
125    {
126        let mut last = LAST_ATTEMPT.lock().unwrap_or_else(|e| e.into_inner());
127        if last.is_some_and(|t| t.elapsed() < RETRY_AFTER) {
128            return;
129        }
130        *last = Some(Instant::now());
131    }
132    let url = format!("{}/agentmux/agents/self/keys", local_url.trim_end_matches('/'));
133    let Ok(resp) = client.get(&url).header(AUTH_KEY_HEADER, auth_key).timeout(FETCH_TIMEOUT).send().await else { return };
134    if !resp.status().is_success() {
135        return;
136    }
137    if let Ok(keys) = resp.json::<Wire>().await {
138        *CACHE.lock().unwrap_or_else(|e| e.into_inner()) = Some(Cached { keys, fetched_at: Instant::now() });
139    }
140}
141
142/// Whether the keys are still on their way: a fetch was tried a moment ago and nothing is held yet. The first
143/// signed call of a process made by hand lands in this window (the fetch runs beside startup), and its answer
144/// should say to try again, not that the agent needs a respawn (#47532).
145pub(crate) fn fetch_in_progress() -> bool {
146    let held = CACHE.lock().unwrap_or_else(|e| e.into_inner()).is_some();
147    let since = LAST_ATTEMPT.lock().unwrap_or_else(|e| e.into_inner()).map(|t| t.elapsed());
148    fetch_pending(held, since)
149}
150
151/// `fetch_in_progress` on its inputs: whether a copy is held, and how long ago the last fetch was started.
152fn fetch_pending(held: bool, since_last_attempt: Option<Duration>) -> bool {
153    !held && since_last_attempt.is_some_and(|d| d < FETCH_TIMEOUT + Duration::from_secs(2))
154}
155
156/// Whether a cached copy needs no re-fetch at `now` (unix seconds).
157fn still_good(c: &Cached, now: i64) -> bool {
158    c.fetched_at.elapsed() < REFRESH_AFTER && c.keys.jekt_key_expires_at.is_none_or(|expires| now < expires)
159}
160
161/// A fetched name-keyed key, decoded, when srv served it for exactly the name
162/// this process signs as.
163fn name_key(pick: impl Fn(&Wire) -> Option<&String>) -> Option<Vec<u8>> {
164    let own = std::env::var("AGENTMUX_AGENT_ID").ok()?;
165    let cache = CACHE.lock().unwrap_or_else(|e| e.into_inner());
166    let cached = cache.as_ref()?;
167    if cached.keys.slug != own {
168        return None;
169    }
170    agentmux_common::jekt_sign::decode_key(pick(&cached.keys)?)
171}
172
173/// The host jekt HMAC key: the fetched one when it is ours, else the env's (set only by a file an older version wrote).
174pub(crate) fn jekt_key() -> Option<Vec<u8>> {
175    name_key(|k| k.jekt_key.as_ref()).or_else(|| env_key("AGENTMUX_JEKT_KEY"))
176}
177
178/// The LAN (and cross-channel) private key: fetched when ours, else the env's (set only by a file an older version wrote).
179pub(crate) fn lan_key() -> Option<Vec<u8>> {
180    name_key(|k| k.lan_key.as_ref()).or_else(|| env_key("AGENTMUX_LAN_KEY"))
181}
182
183/// This agent's UID and its UID-keyed LAN private key, for the v2 signature
184/// (identity M4d-6). Only ever the fetched key, never an env one: the v2
185/// signature claims the UID, so it must come from srv's own record of it.
186pub(crate) fn uid_signer() -> Option<(String, Vec<u8>)> {
187    let cache = CACHE.lock().unwrap_or_else(|e| e.into_inner());
188    let keys = &cache.as_ref()?.keys;
189    let uid = keys.uid.trim();
190    if uid.is_empty() {
191        return None;
192    }
193    Some((uid.to_string(), agentmux_common::jekt_sign::decode_key(keys.uid_lan_key.as_ref()?)?))
194}
195
196fn env_key(var: &str) -> Option<Vec<u8>> {
197    std::env::var(var).ok().filter(|s| !s.is_empty()).and_then(|b64| agentmux_common::jekt_sign::decode_key(&b64))
198}
199
200#[cfg(test)]
201pub(crate) fn set_for_test(slug: &str, jekt_key: Option<&str>) {
202    *CACHE.lock().unwrap_or_else(|e| e.into_inner()) = Some(Cached {
203        keys: Wire { slug: slug.to_string(), jekt_key: jekt_key.map(str::to_string), ..Default::default() },
204        fetched_at: Instant::now(),
205    });
206}
207
208#[cfg(test)]
209pub(crate) fn clear_for_test() {
210    *CACHE.lock().unwrap_or_else(|e| e.into_inner()) = None;
211}
212
213#[cfg(test)]
214mod tests {
215    #[test]
216    fn only_srvs_own_rejection_is_a_rejected_signature() {
217        assert!(super::is_rejected_signature("srv returned 403: identity signature verification failed"));
218        assert!(!super::is_rejected_signature("agent_id=\"x\" is not currently registered with a pane"));
219    }
220
221    #[test]
222    fn forgetting_the_fetched_copy_lets_the_next_call_fetch_at_once() {
223        let _guard = super::ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
224        super::set_for_test("aria", Some("AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE="));
225        *super::LAST_ATTEMPT.lock().unwrap() = Some(std::time::Instant::now());
226        super::forget_fetched();
227        assert!(super::CACHE.lock().unwrap().is_none());
228        assert!(super::LAST_ATTEMPT.lock().unwrap().is_none(), "the 60 s retry gate is open again");
229    }
230
231    /// A call made while the first fetch is in flight waits for it and uses its answer, with one request made.
232    #[tokio::test]
233    async fn a_call_during_the_first_fetch_waits_for_it() {
234        use tokio::io::{AsyncReadExt, AsyncWriteExt};
235        let _guard = super::ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
236        super::forget_fetched();
237        std::env::set_var("AGENTMUX_AGENT_TOKEN", "t");
238        std::env::remove_var("AGENTMUX_IN_CONTAINER");
239        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
240        let url = format!("http://{}", listener.local_addr().unwrap());
241        let served = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
242        let counter = served.clone();
243        tokio::spawn(async move {
244            loop {
245                let Ok((mut sock, _)) = listener.accept().await else { return };
246                counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
247                let mut buf = [0u8; 2048];
248                let _ = sock.read(&mut buf).await;
249                tokio::time::sleep(std::time::Duration::from_millis(300)).await;
250                let body = r#"{"slug":"aria","jekt_key":"BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc=","lan_key":null,"uid":""}"#;
251                let _ = sock
252                    .write_all(format!("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).as_bytes())
253                    .await;
254            }
255        });
256        let client = reqwest::Client::new();
257        let (first, second) = tokio::join!(super::refresh_if_stale(&client, &url, "k"), async {
258            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
259            super::refresh_if_stale(&client, &url, "k").await;
260            super::CACHE.lock().unwrap().is_some()
261        });
262        let _ = first;
263        assert!(second, "the second call returned with the first call's keys held");
264        assert_eq!(served.load(std::sync::atomic::Ordering::SeqCst), 1, "one request, not two");
265        super::forget_fetched();
266        std::env::remove_var("AGENTMUX_AGENT_TOKEN");
267    }
268
269    /// Answers the key request with each of `bodies` in turn (the last one again after that); returns srv's url.
270    async fn serve_keys(bodies: Vec<&'static str>) -> String {
271        use tokio::io::{AsyncReadExt, AsyncWriteExt};
272        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
273        let url = format!("http://{}", listener.local_addr().unwrap());
274        tokio::spawn(async move {
275            for n in 0.. {
276                let Ok((mut sock, _)) = listener.accept().await else { return };
277                let body = bodies[n.min(bodies.len() - 1)];
278                let mut buf = [0u8; 2048];
279                let _ = sock.read(&mut buf).await;
280                let reply = format!("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len());
281                let _ = sock.write_all(reply.as_bytes()).await;
282            }
283        });
284        url
285    }
286
287    /// An MCP that outlives the re-issue: it holds the old key, srv rejects its signature once, it asks srv again, and
288    /// the same call goes through with the current key. A different error is not repeated.
289    #[tokio::test]
290    async fn an_old_key_held_is_replaced_after_one_rejected_signature_and_the_call_goes_through() {
291        use std::sync::atomic::{AtomicUsize, Ordering};
292        let _guard = super::ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
293        super::forget_fetched();
294        std::env::set_var("AGENTMUX_AGENT_TOKEN", "t");
295        std::env::set_var("AGENTMUX_AGENT_ID", "aria");
296        std::env::remove_var("AGENTMUX_IN_CONTAINER");
297        std::env::remove_var("AGENTMUX_JEKT_KEY");
298        // srv served [7; 32] to this process at its start, and has served [1; 32] since the re-issue.
299        let url = serve_keys(vec![
300            r#"{"slug":"aria","jekt_key":"BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc=","lan_key":null,"uid":""}"#,
301            r#"{"slug":"aria","jekt_key":"AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=","lan_key":null,"uid":""}"#,
302        ])
303        .await;
304        let client = reqwest::Client::new();
305        super::refresh_if_stale(&client, &url, "k").await;
306        assert_eq!(jekt_key().as_deref(), Some(&[7u8; 32][..]), "the old key is held");
307
308        let calls = AtomicUsize::new(0);
309        let signs_as_srv_expects = || async {
310            calls.fetch_add(1, Ordering::SeqCst);
311            match jekt_key().as_deref() {
312                Some(k) if k == [1u8; 32] => Ok("verified"),
313                _ => Err(anyhow::anyhow!("srv returned 403: identity signature verification failed")),
314            }
315        };
316        let out = super::run_healing_a_rejected_signature(&client, &url, "k", signs_as_srv_expects).await;
317        assert_eq!(out.unwrap(), "verified", "the next message verifies");
318        assert_eq!(calls.load(Ordering::SeqCst), 2, "one rejection, one repeat");
319
320        let other = AtomicUsize::new(0);
321        let fails_otherwise = || async {
322            other.fetch_add(1, Ordering::SeqCst);
323            Err::<&str, _>(anyhow::anyhow!("the pane is gone"))
324        };
325        assert!(super::run_healing_a_rejected_signature(&client, &url, "k", fails_otherwise).await.is_err());
326        assert_eq!(other.load(Ordering::SeqCst), 1, "any other error is returned as it is");
327        super::forget_fetched();
328        std::env::remove_var("AGENTMUX_AGENT_TOKEN");
329        std::env::remove_var("AGENTMUX_AGENT_ID");
330    }
331
332    #[test]
333    fn only_a_one_is_the_container_hint() {
334        assert!(super::is_container_hint(Some("1")));
335        assert!(!super::is_container_hint(None));
336        assert!(!super::is_container_hint(Some("0")));
337        assert!(!super::is_container_hint(Some("")));
338    }
339
340    #[test]
341    fn keys_are_on_their_way_only_for_a_moment_after_a_fetch_started_with_nothing_held() {
342        use std::time::Duration;
343        assert!(super::fetch_pending(false, Some(Duration::from_millis(500))));
344        assert!(!super::fetch_pending(true, Some(Duration::from_millis(500))), "a held copy is not on its way");
345        assert!(!super::fetch_pending(false, None), "no fetch was tried: this srv serves none");
346        assert!(!super::fetch_pending(false, Some(Duration::from_secs(30))), "an old attempt that left nothing failed");
347    }
348
349    use super::*;
350
351    /// [7; 32] and [1; 32], base64.
352    const FETCHED_B64: &str = "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc=";
353    const ENV_B64: &str = "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=";
354
355    use super::ENV_LOCK as LOCK;
356
357    fn with_env<T>(agent_id: &str, env_key: Option<&str>, f: impl FnOnce() -> T) -> T {
358        let _guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());
359        std::env::set_var("AGENTMUX_AGENT_ID", agent_id);
360        match env_key {
361            Some(k) => std::env::set_var("AGENTMUX_JEKT_KEY", k),
362            None => std::env::remove_var("AGENTMUX_JEKT_KEY"),
363        }
364        let out = f();
365        clear_for_test();
366        std::env::remove_var("AGENTMUX_JEKT_KEY");
367        out
368    }
369
370    #[test]
371    fn a_fetched_key_for_exactly_this_name_wins_over_the_env_copy() {
372        let fetched = [7u8; 32];
373        let key = with_env("aria", Some(ENV_B64), || {
374            set_for_test("aria", Some(FETCHED_B64));
375            jekt_key()
376        });
377        assert_eq!(key.as_deref(), Some(&fetched[..]));
378    }
379
380    #[test]
381    fn a_key_served_for_another_name_is_not_used() {
382        // This agent signs as "aria" but its row's slug is "aria-2": the
383        // served key is aria-2's, and srv checks "aria" against aria's.
384        let env = [1u8; 32];
385        let key = with_env("aria", Some(ENV_B64), || {
386            set_for_test("aria-2", Some(FETCHED_B64));
387            jekt_key()
388        });
389        assert_eq!(key.as_deref(), Some(&env[..]));
390    }
391
392    #[test]
393    fn nothing_fetched_means_the_env_key_as_before() {
394        let env = [1u8; 32];
395        assert_eq!(with_env("aria", Some(ENV_B64), jekt_key).as_deref(), Some(&env[..]));
396        assert_eq!(with_env("aria", None, jekt_key), None);
397    }
398
399    #[test]
400    fn a_copy_is_good_until_its_key_expires_then_refetched() {
401        let cached = |expires: Option<i64>| Cached {
402            keys: Wire { slug: "aria".into(), jekt_key_expires_at: expires, ..Default::default() },
403            fetched_at: Instant::now(),
404        };
405        assert!(still_good(&cached(Some(1_000)), 999));
406        assert!(!still_good(&cached(Some(1_000)), 1_000), "expired: srv may rotate it now");
407        assert!(still_good(&cached(None), 1_000_000), "no expiry served: the five minute clock");
408    }
409
410    #[test]
411    fn the_v2_signer_is_only_ever_the_fetched_uid_key() {
412        let _guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());
413        clear_for_test();
414        assert!(
415            uid_signer().is_none(),
416            "no fetch: no v2, whatever the env holds"
417        );
418        let set = |uid: &str, key: Option<&str>| {
419            *CACHE.lock().unwrap_or_else(|e| e.into_inner()) = Some(Cached {
420                keys: Wire {
421                    slug: "aria".into(),
422                    uid: uid.into(),
423                    uid_lan_key: key.map(str::to_string),
424                    ..Default::default()
425                },
426                fetched_at: Instant::now(),
427            });
428        };
429        set("uid-1", Some(FETCHED_B64));
430        assert_eq!(uid_signer(), Some(("uid-1".to_string(), vec![7u8; 32])));
431        set("", Some(FETCHED_B64));
432        assert!(uid_signer().is_none(), "a key with no UID to claim");
433        set("uid-1", None);
434        assert!(uid_signer().is_none());
435        clear_for_test();
436    }
437}