Skip to main content

agentmux_srv/server/reactive/
lan_refusals.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The key a LAN peer showed for a name whose pinned key is different, kept
5//! in memory so the operator's pin screen can offer to accept it. It is not
6//! stored: after a restart the next refused message records it again.
7
8use std::collections::HashMap;
9use std::sync::{LazyLock, Mutex};
10
11/// The last key refused for one name.
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub(crate) struct Refusal {
14    pub key_b64: String,
15    pub last_seen_at: i64,
16    pub count: u32,
17    /// The certificate the peer sent with the key, if any (`lan_continuity`).
18    pub cert: Option<agentmux_common::jekt_sign::WanKeyRecord>,
19    /// Why it was not vouched for, in a sentence.
20    pub why: Option<String>,
21    /// The name has no pin: this is a first key nobody vouched for, not a different key for a pinned name.
22    pub first_contact: bool,
23}
24
25/// First keys held at once; past it the one seen longest ago is dropped, so a peer that claims many names
26/// cannot grow this map or the pin screen's list without limit.
27const MAX_FIRST_CONTACT: usize = 64;
28
29static REFUSALS: LazyLock<Mutex<HashMap<String, Refusal>>> = LazyLock::new(Default::default);
30
31fn refusals() -> std::sync::MutexGuard<'static, HashMap<String, Refusal>> {
32    REFUSALS.lock().unwrap_or_else(|e| e.into_inner())
33}
34
35/// A message signed by `observed_key_b64` for `agent` was refused because
36/// the name is pinned to another key: log it and remember the key.
37#[cfg(test)]
38pub(crate) fn pin_mismatch(agent: &str, observed_key_b64: &str) {
39    pin_mismatch_with(agent, observed_key_b64, None, None);
40}
41
42/// [`pin_mismatch`], with the certificate that came with the key and the reason
43/// it did not move the pin.
44pub(crate) fn pin_mismatch_with(
45    agent: &str,
46    observed_key_b64: &str,
47    cert: Option<agentmux_common::jekt_sign::WanKeyRecord>,
48    why: Option<String>,
49) {
50    tracing::warn!(agent_id = %agent, why = why.as_deref().unwrap_or(""), "LAN pubkey mismatch against pinned key — possible identity spoofing attempt");
51    note(agent, observed_key_b64, agentmux_common::time::now_secs(), cert, why);
52}
53
54/// A name with no pin showed `observed_key_b64` and no trusted install vouched for it: nothing is pinned,
55/// and the key is kept for the pin screen to offer to accept.
56pub(crate) fn first_contact_with(
57    agent: &str,
58    observed_key_b64: &str,
59    cert: Option<agentmux_common::jekt_sign::WanKeyRecord>,
60    why: Option<String>,
61) {
62    tracing::info!(agent_id = %agent, why = why.as_deref().unwrap_or(""), "LAN first contact: no trusted install vouched for the key, so it is not pinned and its messages stay unproven");
63    note(agent, observed_key_b64, agentmux_common::time::now_secs(), cert, why);
64    let mut map = refusals();
65    if let Some(entry) = map.get_mut(&agent.to_lowercase()) {
66        entry.first_contact = true;
67    }
68    while map.values().filter(|r| r.first_contact).count() > MAX_FIRST_CONTACT {
69        let Some(oldest) = map.iter().filter(|(_, r)| r.first_contact).min_by_key(|(_, r)| r.last_seen_at).map(|(name, _)| name.clone()) else { break };
70        map.remove(&oldest);
71    }
72}
73
74/// Every name with a key held for it, for the names that have no pin to list them under.
75pub(crate) fn all() -> Vec<(String, Refusal)> {
76    refusals().iter().map(|(name, r)| (name.clone(), r.clone())).collect()
77}
78
79fn note(
80    agent: &str,
81    observed_key_b64: &str,
82    now: i64,
83    cert: Option<agentmux_common::jekt_sign::WanKeyRecord>,
84    why: Option<String>,
85) {
86    let mut map = refusals();
87    let entry = map
88        .entry(agent.to_lowercase())
89        .or_insert_with(|| Refusal { key_b64: String::new(), last_seen_at: now, count: 0, cert: None, why: None, first_contact: false });
90    if entry.key_b64 != observed_key_b64 {
91        *entry = Refusal { key_b64: observed_key_b64.to_string(), last_seen_at: now, count: 0, cert: None, why: None, first_contact: false };
92    }
93    entry.count += 1;
94    entry.last_seen_at = now;
95    entry.cert = cert;
96    entry.why = why;
97}
98
99/// The last key refused for `agent`, if any since this srv started.
100pub(crate) fn get(agent: &str) -> Option<Refusal> {
101    refusals().get(&agent.to_lowercase()).cloned()
102}
103
104/// Forget it: the pin was moved or cleared.
105pub(crate) fn clear(agent: &str) {
106    refusals().remove(&agent.to_lowercase());
107}
108
109#[cfg(test)]
110mod tests {
111    use super::*;
112
113    #[test]
114    fn first_keys_held_are_capped_and_the_oldest_goes_first() {
115        for n in 0..(MAX_FIRST_CONTACT + 10) {
116            first_contact_with(&format!("cap-name-{n}"), "key", None, None);
117            // Seen at distinct times: the oldest is the one dropped.
118            let mut map = refusals();
119            map.get_mut(&format!("cap-name-{n}")).unwrap().last_seen_at = n as i64;
120        }
121        let held: Vec<String> = all().into_iter().filter(|(name, r)| name.starts_with("cap-name-") && r.first_contact).map(|(n, _)| n).collect();
122        assert!(held.len() <= MAX_FIRST_CONTACT, "{}", held.len());
123        assert!(!held.contains(&"cap-name-0".to_string()), "the oldest was dropped");
124        assert!(held.contains(&format!("cap-name-{}", MAX_FIRST_CONTACT + 9)), "the newest is kept");
125        // A different key for a pinned name is not counted against the cap.
126        pin_mismatch("cap-pinned", "key");
127        assert!(get("cap-pinned").is_some_and(|r| !r.first_contact));
128    }
129
130    #[test]
131    fn the_last_refused_key_is_kept_with_a_count() {
132        note("Maop-t", "key-a", 10, None, None);
133        note("maop-t", "key-a", 20, None, None);
134        let r = get("MAOP-T").unwrap();
135        assert_eq!((r.key_b64.as_str(), r.last_seen_at, r.count), ("key-a", 20, 2));
136        note("maop-t", "key-b", 30, None, None);
137        let r = get("maop-t").unwrap();
138        assert_eq!((r.key_b64.as_str(), r.count), ("key-b", 1), "a different key starts over");
139        clear("maop-t");
140        assert!(get("maop-t").is_none());
141    }
142}