Skip to main content

agentmux_srv_core/backend/lan/discovery/
uid_refetch.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A fresh ask of the LAN peers for the UID key beside a name key whose cached
5//! answer is gone or held none (identity M4d-6, `lan_v2::claim_uid`), and for a
6//! name key whose cached answer was a miss.
7
8use super::*;
9
10/// A cached miss younger than this was made by the lookup that just ran: asking
11/// again would repeat it.
12const MISS_RECHECK_AFTER: std::time::Duration = std::time::Duration::from_secs(5);
13
14impl LanDiscoveryController {
15    /// One token from the fan-out limiter ([`Self::find_agent_lan_pubkey`]).
16    pub(super) fn pubkey_lookup_allowed(&self) -> bool {
17        self.pubkey_lookup_limiter.lock().map(|mut limiter| limiter.check()).unwrap_or(true)
18    }
19
20    /// The UID key `agent_id`'s peer gives beside `name_key`, asked for afresh
21    /// because the cached answer is gone or held none. `None` when the peers
22    /// give none, give another name key, or the limiter refuses the fan-out:
23    /// the caller reads that as "not shown", never as "nothing to check".
24    pub async fn refetch_lan_uid_key(&self, agent_id: &str, name_key: &[u8], http: &reqwest::Client) -> Option<(String, Vec<u8>)> {
25        self.refetch_lan_uid_key_from(&self.get_all_instances(), agent_id, name_key, http).await
26    }
27
28    /// [`Self::find_agent_lan_pubkey`], and when it says `NotFound`, one more ask
29    /// if that answer came from the cache.
30    pub async fn find_agent_lan_pubkey_asking_again(&self, agent_id: &str, http: &reqwest::Client) -> LanPubkeyLookup {
31        match self.find_agent_lan_pubkey(agent_id, http).await {
32            LanPubkeyLookup::NotFound => self.find_agent_lan_pubkey_again(agent_id, http).await,
33            other => other,
34        }
35    }
36
37    /// `agent_id`'s name key after [`Self::find_agent_lan_pubkey`] said
38    /// `NotFound`, asked for once more when that answer came from the cache: a
39    /// miss cached a moment ago (a peer that had not minted the key yet, or had
40    /// not announced itself) must not leave a signed jekt unverified for the rest
41    /// of its life. A miss the lookup itself just made is not repeated. Anything
42    /// but a key reads as `NotFound` again (the limiter's refusal included): the
43    /// caller leaves the jekt unverified, as it would have. A key found here goes
44    /// through the pin check like any other.
45    pub(crate) async fn find_agent_lan_pubkey_again(&self, agent_id: &str, http: &reqwest::Client) -> LanPubkeyLookup {
46        self.find_agent_lan_pubkey_again_from(&self.peers_to_ask(), agent_id, http).await
47    }
48
49    fn peers_to_ask(&self) -> Vec<LanInstance> {
50        #[cfg(any(test, feature = "test-support"))]
51        if let Some(seeded) = Some(self.peers_for_test.lock().unwrap().clone()).filter(|p| !p.is_empty()) {
52            return seeded;
53        }
54        self.get_all_instances()
55    }
56
57    pub(super) async fn find_agent_lan_pubkey_again_from(&self, peers: &[LanInstance], agent_id: &str, http: &reqwest::Client) -> LanPubkeyLookup {
58        let old_miss = self.pubkey_cache.read().ok().is_some_and(|cache| {
59            cache.get(agent_id).is_some_and(|e| {
60                // A miss past its TTL was not served from the cache: the lookup that
61                // just ran asked the peers itself.
62                let left = e.expires.saturating_duration_since(std::time::Instant::now());
63                let age = std::time::Duration::from_secs(LAN_AGENT_CACHE_TTL_SECS).saturating_sub(left);
64                e.public_key.is_none() && !left.is_zero() && age >= MISS_RECHECK_AFTER
65            })
66        });
67        if !old_miss || !self.pubkey_lookup_allowed() {
68            return LanPubkeyLookup::NotFound;
69        }
70        match self.pubkey_from_peers(peers, agent_id, http).await {
71            found @ LanPubkeyLookup::Found(_) => found,
72            _ => LanPubkeyLookup::NotFound,
73        }
74    }
75
76    pub(super) async fn refetch_lan_uid_key_from(
77        &self,
78        peers: &[LanInstance],
79        agent_id: &str,
80        name_key: &[u8],
81        http: &reqwest::Client,
82    ) -> Option<(String, Vec<u8>)> {
83        if !self.pubkey_lookup_allowed() {
84            return None;
85        }
86        // The fan-out caches whatever it finds, a miss included. An ask that
87        // does not confirm this name key with a UID key must leave the cache as
88        // it was, or a miss would stand in for the key that just verified.
89        let before = self.pubkey_cache.read().ok().and_then(|cache| {
90            cache.get(agent_id).map(|e| LanPubkeyCacheEntry { public_key: e.public_key.clone(), uid_key: e.uid_key.clone(), cert: e.cert.clone(), install_sig: e.install_sig.clone(), expires: e.expires })
91        });
92        let shown = match self.pubkey_from_peers(peers, agent_id, http).await {
93            LanPubkeyLookup::Found(key) if key == name_key => self.cached_lan_uid_key(agent_id),
94            _ => None,
95        };
96        if shown.is_none() {
97            if let Ok(mut cache) = self.pubkey_cache.write() {
98                match before {
99                    Some(entry) => cache.insert(agent_id.to_string(), entry),
100                    None => cache.remove(agent_id),
101                };
102            }
103        }
104        shown
105    }
106
107    /// Give the cached answer for `agent_id` a certificate, as a host's lookup answer carries.
108    #[cfg(any(test, feature = "test-support"))]
109    pub fn seed_lan_cert_for_test(&self, agent_id: &str, cert: agentmux_common::jekt_sign::WanKeyRecord) {
110        if let Some(entry) = self.pubkey_cache.write().unwrap().get_mut(agent_id) {
111            entry.cert = Some(cert);
112        }
113    }
114
115    /// The certificate the peer that answered [`Self::find_agent_lan_pubkey`]
116    /// for `agent_id` gave beside its name key, while that answer is cached.
117    pub fn cached_lan_cert(&self, agent_id: &str) -> Option<agentmux_common::jekt_sign::WanKeyRecord> {
118        let cache = self.pubkey_cache.read().ok()?;
119        cache.get(agent_id).filter(|e| e.expires > std::time::Instant::now())?.cert.clone()
120    }
121
122    /// The UID and UID key the peer that answered [`Self::find_agent_lan_pubkey`]
123    /// for `agent_id` gave beside its name key, while that answer is cached
124    /// (identity M4d-6).
125    pub fn cached_lan_uid_key(&self, agent_id: &str) -> Option<(String, Vec<u8>)> {
126        let cache = self.pubkey_cache.read().ok()?;
127        let e = cache.get(agent_id).filter(|e| e.expires > std::time::Instant::now())?;
128        e.uid_key.clone()
129    }
130
131    /// The agent's own signature, from the same answer, that the install behind the certificate hosts it.
132    pub fn cached_lan_install_sig(&self, agent_id: &str) -> Option<String> {
133        let cache = self.pubkey_cache.read().ok()?;
134        cache.get(agent_id).filter(|e| e.expires > std::time::Instant::now())?.install_sig.clone()
135    }
136
137    /// Give the cached answer for `agent_id` the agent's statement of which install hosts it.
138    #[cfg(any(test, feature = "test-support"))]
139    pub fn seed_lan_install_sig_for_test(&self, agent_id: &str, sig: String) {
140        if let Some(entry) = self.pubkey_cache.write().unwrap().get_mut(agent_id) {
141            entry.install_sig = Some(sig);
142        }
143    }
144}
145
146#[cfg(any(test, feature = "test-support"))]
147impl LanDiscoveryController {
148    /// A peer at `addr` ("host:port"), listed as discovery would list it now.
149    pub fn seed_peer_at_for_test(&self, addr: &str) {
150        let (host, port) = addr.rsplit_once(':').unwrap();
151        let instance = LanInstance {
152            instance_id: format!("peer-{port}"),
153            hostname: "test".into(),
154            version: "0".into(),
155            channel: String::new(),
156            os: String::new(),
157            install: String::new(),
158            build: String::new(),
159            address: host.to_string(),
160            port: port.parse().unwrap(),
161            auth_key: "k".into(),
162            agents: vec![],
163            agent_status: Default::default(),
164            agent_lines: Default::default(),
165            agent_providers: Default::default(),
166            agent_kinds: Default::default(),
167            agent_accounts: Default::default(),
168            agent_resets: Default::default(),
169            agent_seats: Default::default(),
170            first_seen: 0,
171            last_seen: agentmux_common::time::now_secs_u64(),
172            last_polled_ok: 0,
173            install_id: String::new(),
174            other_ttl_secs: 4500,
175        };
176        self.peers_for_test.lock().unwrap().push(instance);
177    }
178
179    /// A miss for `agent_id` that was cached `age_secs` ago.
180    pub fn seed_lan_pubkey_miss_for_test(&self, agent_id: &str, age_secs: u64) {
181        let life = std::time::Duration::from_secs(LAN_AGENT_CACHE_TTL_SECS);
182        let left = life.saturating_sub(std::time::Duration::from_secs(age_secs));
183        self.pubkey_cache.write().unwrap().insert(
184            agent_id.to_string(),
185            LanPubkeyCacheEntry { public_key: None, uid_key: None, cert: None, install_sig: None, expires: std::time::Instant::now() + left },
186        );
187    }
188
189    /// [`Self::seed_lan_pubkey_for_test`], with the certificate the answer carried.
190    #[cfg(any(test, feature = "test-support"))]
191    pub fn seed_lan_pubkey_with_cert_for_test(&self, agent_id: &str, public_key: Vec<u8>, cert: Option<agentmux_common::jekt_sign::WanKeyRecord>) {
192        self.pubkey_cache.write().unwrap().insert(
193            agent_id.to_string(),
194            LanPubkeyCacheEntry {
195                public_key: Some(public_key),
196                uid_key: None,
197                cert,
198                install_sig: None,
199                expires: std::time::Instant::now() + std::time::Duration::from_secs(LAN_AGENT_CACHE_TTL_SECS),
200            },
201        );
202    }
203}