1use std::collections::HashMap;
20use std::sync::{LazyLock, Mutex};
21
22use agentmux_common::jekt_sign::WanKeyRecord;
23use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
24use serde_json::json;
25
26use super::AppState;
27use crate::backend::storage::lan_peer_pin_installs::PinInstall;
28
29pub(crate) const CERT_CHANNEL: &str = "lan";
31pub(crate) const CERT_MAX_AGE_SECS: i64 = 600;
34const RECHECK_AFTER_SECS: i64 = 60;
37const MAX_UNVOUCHED: usize = 1024;
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub(crate) enum Path {
43 PinnedInstance,
45 AccountDirectory,
47}
48
49impl Path {
50 pub(crate) fn as_str(self) -> &'static str {
51 match self {
52 Path::PinnedInstance => "pinned-instance",
53 Path::AccountDirectory => "account-directory",
54 }
55 }
56}
57
58pub(crate) fn issue_cert(state: &AppState, agent: &str, public_key_b64: &str) -> Option<WanKeyRecord> {
62 let wan = state.mstore.wan_identity().or_else(crate::backend::storage::wan_identity::global)?;
63 let instance = wan.instance_ensure(&crate::backend::reactive::registry::local_host_label()).ok()?;
64 let key: [u8; 32] = BASE64.decode(public_key_b64).ok()?.try_into().ok()?;
65 WanKeyRecord::certify(&instance.private_key, agent, CERT_CHANNEL, &key, &instance.host_hint, agentmux_common::time::now_secs())
66}
67
68pub(super) async fn on_mismatch(state: &AppState, claimed: &str, observed_key: &[u8]) -> bool {
71 let cert = state.lan_discovery.cached_lan_cert(claimed);
72 match move_if_vouched(state, claimed, observed_key, cert.as_ref(), "automatic", false).await {
73 Ok(_) => true,
74 Err(why) => {
75 super::lan_refusals::pin_mismatch_with(claimed, &BASE64.encode(observed_key), cert, Some(why));
76 false
77 }
78 }
79}
80
81pub(super) async fn on_first_contact(state: &AppState, claimed: &str, observed_key: &[u8]) -> bool {
85 let cert = state.lan_discovery.cached_lan_cert(claimed);
86 match move_if_vouched(state, claimed, observed_key, cert.as_ref(), "automatic", false).await {
87 Ok(_) => true,
88 Err(why) => {
89 super::lan_refusals::first_contact_with(claimed, &BASE64.encode(observed_key), cert, Some(why));
90 false
91 }
92 }
93}
94
95pub(super) fn with_sender_cert(state: &AppState, mut sender: serde_json::Value) -> serde_json::Value {
98 let shown = sender.get("agent_id").zip(sender.get("lan_public_key")).and_then(|(a, k)| Some((a.as_str()?.to_string(), k.as_str()?.to_string())));
99 let own = |agent: &str, key: &str| {
101 agent == crate::backend::lan::swarm_broadcast::this_sender_id(&state.hostname) && state.mstore.agent_lan_public_key_load(agent).ok().flatten().as_deref() == Some(key)
102 };
103 if let (Some((agent, key)), Some(obj)) = (shown, sender.as_object_mut()) {
104 if own(&agent, &key) {
105 add_cert(state, &agent, &key, obj);
106 }
107 }
108 sender
109}
110
111pub(super) fn add_cert(state: &AppState, agent: &str, public_key_b64: &str, answer: &mut serde_json::Map<String, serde_json::Value>) {
113 if moved_off(state, agent) {
116 return;
117 }
118 if let Some(cert) = issue_cert(state, agent, public_key_b64) {
119 let pair = state.mstore.agent_lan_key_ensure(agent).ok().filter(|p| p.public_key == public_key_b64);
122 let private = pair.and_then(|p| BASE64.decode(p.private_key).ok());
123 if let Some(sig) = private.and_then(|k| agentmux_common::lan_install_binding::sign_lan_install_binding(&k, agent, &cert.instance_id, cert.issued_at)) {
124 answer.insert("lan_install_sig".to_string(), json!(sig));
125 }
126 answer.insert("lan_cert".to_string(), json!(cert));
127 }
128}
129
130fn moved_off(state: &AppState, agent: &str) -> bool {
132 let Ok(uid) = crate::backend::agent_resolve::resolve_agent_named(&state.mstore, agent) else { return false };
133 matches!(state.mstore.agent_handover_get(&uid), Ok(Some(mark)) if mark.state == crate::registry::Handover::MOVED)
134}
135
136pub(crate) fn check_cert(cert: &WanKeyRecord, agent: &str, observed_key: &[u8], pin_since: i64, now: i64) -> Result<(), &'static str> {
141 let Some(certified) = cert.check_chain() else { return Err("the certificate does not verify") };
142 if cert.agent_id != agent.to_lowercase() {
143 return Err("the certificate names another agent");
144 }
145 if cert.channel != CERT_CHANNEL {
146 return Err("the certificate is not for a LAN key");
147 }
148 if certified.as_slice() != observed_key {
149 return Err("the certificate is for another key");
150 }
151 if (now - cert.issued_at).abs() > CERT_MAX_AGE_SECS {
152 return Err("the certificate is not fresh");
153 }
154 if cert.issued_at <= pin_since {
155 return Err("the certificate is older than the pin it would replace");
156 }
157 Ok(())
158}
159
160pub(crate) const REVOKED: &str = "the install is revoked";
163
164pub(crate) async fn instance_trust(state: &AppState, instance_id: &str) -> Result<Path, String> {
169 let wan = state.mstore.wan_identity().or_else(crate::backend::storage::wan_identity::global);
170 if let Some(wan) = &wan {
171 let known = wan.known_instance_get(instance_id).map_err(|e| format!("the known installs could not be read: {e}"))?;
172 if known.is_some_and(|k| k.revoked_at.is_some()) {
173 return Err(REVOKED.to_string());
174 }
175 }
176 let pinned = match &wan {
177 Some(wan) => wan
178 .agent_instance_pins_list()
179 .map_err(|e| format!("the WAN pins could not be read: {e}"))?
180 .iter()
181 .any(|p| p.instance_id == instance_id),
182 None => false,
183 };
184 within(DIRECTORY_WAIT, pinned, instance_id, ask_directory(state, wan.as_deref(), instance_id, pinned)).await
185}
186
187const DIRECTORY_WAIT: std::time::Duration = std::time::Duration::from_secs(3);
191
192async fn within(wait: std::time::Duration, pinned: bool, instance_id: &str, asking: impl std::future::Future<Output = Result<Path, String>>) -> Result<Path, String> {
197 match tokio::time::timeout(wait, asking).await {
198 Ok(answer) => answer,
199 Err(_) => {
200 tracing::warn!(instance = %instance_id, pinned, wait_secs = wait.as_secs_f32(), "lan check: the account's directory did not answer in time; going on without it");
201 if pinned {
202 Ok(Path::PinnedInstance)
203 } else {
204 Err("the install is not pinned here and the account's directory did not answer in time".to_string())
205 }
206 }
207 }
208}
209
210async fn ask_directory(state: &AppState, wan: Option<&crate::backend::storage::wan_identity::WanIdentityStore>, instance_id: &str, pinned: bool) -> Result<Path, String> {
213 use crate::muxbus::wan_verify::{instance_is_live_install, instance_is_revoked, Directory, GLOBAL_BUDGET};
214 let token = match crate::broker::get_global() {
215 Some(scheduler) => crate::muxbus::cloud_subscriber::load_valid_token(&state.id_store, &scheduler).await,
216 None => None,
217 };
218 let base_url = crate::muxbus::relay::rest_base_url();
219 let dir = token.as_ref().map(|token| Directory { base_url: &base_url, http: &state.http_client, token, budget: &GLOBAL_BUDGET });
220 if pinned {
221 if let Some(dir) = &dir {
222 if instance_is_revoked(dir, instance_id).await == Some(true) {
223 if let Some(wan) = wan {
224 remember_revoked(wan, instance_id, agentmux_common::time::now_secs());
225 }
226 return Err(REVOKED.to_string());
227 }
228 }
229 return Ok(Path::PinnedInstance);
230 }
231 let Some(dir) = dir else {
232 return Err("the install is not pinned here and this machine is not signed in to ask the account's directory".to_string());
233 };
234 match instance_is_live_install(&dir, instance_id).await {
235 Some(true) => Ok(Path::AccountDirectory),
236 Some(false) => Err("the install is not pinned here and the account's directory does not list it as a live install".to_string()),
237 None => Err("the install is not pinned here and the account's directory could not be read".to_string()),
238 }
239}
240
241fn remember_revoked(wan: &crate::backend::storage::wan_identity::WanIdentityStore, instance_id: &str, now: i64) {
245 let _ = wan.known_instance_observe(instance_id, "?", now);
246 let _ = wan.known_instance_record_revocation_check(instance_id, true, now);
247}
248
249static UNVOUCHED: LazyLock<Mutex<HashMap<(String, String), (i64, String)>>> = LazyLock::new(Default::default);
250
251fn unvouched() -> std::sync::MutexGuard<'static, HashMap<(String, String), (i64, String)>> {
252 UNVOUCHED.lock().unwrap_or_else(|e| e.into_inner())
253}
254
255pub(crate) async fn move_if_vouched(
265 state: &AppState,
266 agent: &str,
267 observed_key: &[u8],
268 cert: Option<&WanKeyRecord>,
269 by: &str,
270 force: bool,
271) -> Result<Path, String> {
272 let now = agentmux_common::time::now_secs();
273 let observed_b64 = BASE64.encode(observed_key);
274 if let Some(why) = retired_reason(state, agent, observed_key) {
276 return Err(why);
277 }
278 let marker = (agent.to_lowercase(), format!("{observed_b64}|{}", cert.map_or("", |c| c.instance_id.as_str())));
280 if !force {
282 if let Some((_, why)) = unvouched().get(&marker).filter(|(at, _)| now - at < RECHECK_AFTER_SECS) {
283 return Err(why.clone());
284 }
285 }
286 let result = vouch(state, agent, observed_key, cert, now).await;
287 match &result {
288 Ok(_) => {
289 unvouched().remove(&marker);
290 }
291 Err(why) => {
292 let mut seen = unvouched();
294 seen.retain(|_, (at, _)| now - *at < RECHECK_AFTER_SECS);
295 if seen.len() < MAX_UNVOUCHED {
296 seen.insert(marker, (now, why.clone()));
297 }
298 }
299 }
300 let (path, cert, pinned) = result?;
301 let Some((old, old_since)) = pinned else {
302 return pin_first(state, agent, &observed_b64, &cert, path, by);
303 };
304 let since = agentmux_common::time::now_secs().max(cert.issued_at);
308 let moved = state
309 .mstore
310 .lan_peer_pubkey_pin_move(agent, (&old, old_since), &observed_b64, since)
311 .map_err(|e| format!("the pin could not be moved: {e}"))?;
312 if !moved {
313 return match state.mstore.lan_peer_pubkey_pin_since(agent) {
316 Ok(Some((k, _))) if k == observed_b64 => {
317 super::lan_refusals::clear(agent);
318 Ok(path)
319 }
320 _ => Err("the pin changed while the key was being checked; it was not moved".to_string()),
321 };
322 }
323 super::lan_refusals::clear(agent);
324 bind_to(state, agent, &observed_b64, &cert);
325 retire(state, agent, &old, &cert.instance_id);
326 let entry = json!({
327 "action": "continuity",
328 "kind": "lan",
329 "agent": agent.to_lowercase(),
330 "from": fingerprint(&old),
331 "to": fingerprint(&observed_b64),
332 "by": by,
333 "vouched_by": { "instance": cert.instance_id, "host": cert.host_hint, "path": path.as_str(), "issued_at": cert.issued_at },
334 });
335 audit(&entry);
336 tracing::warn!(agent_id = %agent, path = path.as_str(), instance = %cert.instance_id, by, "LAN key moved: the install that hosts the agent vouched for its new key");
337 Ok(path)
338}
339
340fn pin_first(state: &AppState, agent: &str, observed_b64: &str, cert: &WanKeyRecord, path: Path, by: &str) -> Result<Path, String> {
343 let since = agentmux_common::time::now_secs().max(cert.issued_at);
344 let held = state.mstore.lan_peer_pubkey_pin_get_or_set_at(agent, observed_b64, since).map_err(|e| format!("the pin could not be set: {e}"))?;
345 if held != observed_b64 {
346 return Err("another key was pinned for the name while this one was being checked; it was not pinned".to_string());
347 }
348 super::lan_refusals::clear(agent);
349 bind_to(state, agent, observed_b64, cert);
350 audit(&json!({
351 "action": "first-pin",
352 "kind": "lan",
353 "agent": agent.to_lowercase(),
354 "to": fingerprint(observed_b64),
355 "by": by,
356 "vouched_by": { "instance": cert.instance_id, "host": cert.host_hint, "path": path.as_str(), "issued_at": cert.issued_at },
357 }));
358 Ok(path)
359}
360
361fn bind_to(state: &AppState, agent: &str, key_b64: &str, cert: &WanKeyRecord) {
364 if !agent_says_hosted_by(state, agent, key_b64, cert) {
365 return;
366 }
367 let install = PinInstall { instance_id: cert.instance_id.clone(), host_hint: cert.host_hint.clone() };
368 if let Err(e) = state.mstore.lan_pin_bind(agent, key_b64, &install, agentmux_common::time::now_secs()) {
369 tracing::warn!(agent_id = %agent, error = %e, "LAN pin could not be bound to its install");
370 }
371}
372
373fn agent_says_hosted_by(state: &AppState, agent: &str, key_b64: &str, cert: &WanKeyRecord) -> bool {
377 let (Some(sig), Ok(key)) = (state.lan_discovery.cached_lan_install_sig(agent), BASE64.decode(key_b64)) else { return false };
378 let Ok(key) = <[u8; 32]>::try_from(key.as_slice()) else { return false };
379 agentmux_common::lan_install_binding::verify_lan_install_binding(&key, agent, &cert.instance_id, cert.issued_at, &sig)
380}
381
382pub(crate) fn retire(state: &AppState, agent: &str, old_b64: &str, by: &str) {
384 if let Err(e) = state.mstore.lan_retired_put(agent, &fingerprint(old_b64), agentmux_common::time::now_secs(), by) {
385 tracing::warn!(agent_id = %agent, error = %e, "LAN retired key could not be recorded");
386 }
387}
388
389pub(crate) fn retired_reason(state: &AppState, agent: &str, observed_key: &[u8]) -> Option<String> {
391 let retired = state.mstore.lan_retired_get(agent, &fingerprint(&BASE64.encode(observed_key))).ok()??;
392 let day = chrono::DateTime::from_timestamp(retired.retired_at, 0).unwrap_or_default().format("%Y-%m-%d");
393 Some(format!("this key was retired on {day} by {}: the name moved to another key, and a retired key is not taken back", retired.retired_by))
394}
395
396pub(crate) async fn bind_after_verified(state: &AppState, agent: &str, key: &[u8]) {
401 let key_b64 = BASE64.encode(key);
402 if !matches!(state.mstore.lan_peer_pubkey_pin_since(agent), Ok(Some((k, _))) if k == key_b64) {
403 return;
404 }
405 if !matches!(state.mstore.lan_pin_installed(agent), Ok(None)) {
406 return;
407 }
408 let Some(cert) = state.lan_discovery.cached_lan_cert(agent) else { return };
409 if !agent_says_hosted_by(state, agent, &key_b64, &cert) {
410 return;
411 }
412 let now = agentmux_common::time::now_secs();
413 let marker = (agent.to_lowercase(), format!("bind:{}", cert.instance_id));
415 if unvouched().get(&marker).is_some_and(|(at, _)| now - at < RECHECK_AFTER_SECS) {
416 return;
417 }
418 if check_cert(&cert, agent, key, 0, now).is_ok() && instance_trust(state, &cert.instance_id).await.is_ok() {
419 bind_to(state, agent, &key_b64, &cert);
420 return;
421 }
422 let mut seen = unvouched();
423 seen.retain(|_, (at, _)| now - *at < RECHECK_AFTER_SECS);
424 if seen.len() < MAX_UNVOUCHED {
425 seen.insert(marker, (now, String::new()));
426 }
427}
428
429async fn vouch(
430 state: &AppState,
431 agent: &str,
432 observed_key: &[u8],
433 cert: Option<&WanKeyRecord>,
434 now: i64,
435) -> Result<(Path, WanKeyRecord, Option<(String, i64)>), String> {
436 let cert = cert.ok_or("the peer sent no certificate for the key")?;
437 let pinned = state.mstore.lan_peer_pubkey_pin_since(agent).map_err(|e| format!("the pin could not be read: {e}"))?;
439 check_cert(cert, agent, observed_key, pinned.as_ref().map_or(0, |p| p.1), now).map_err(str::to_string)?;
440 let path = instance_trust(state, &cert.instance_id).await?;
441 if pinned.is_some() {
442 bound_install_allows(state, agent, &cert.instance_id, &BASE64.encode(observed_key)).await?;
443 }
444 Ok((path, cert.clone(), pinned))
446}
447
448async fn bound_install_allows(state: &AppState, agent: &str, certifying: &str, observed_b64: &str) -> Result<(), String> {
452 let bound = state.mstore.lan_pin_installed(agent).map_err(|e| format!("the pin's install could not be read: {e}"))?;
453 let Some(bound) = bound else {
454 return Err("the pin is not bound to an install yet: it binds when the agent next sends a message that verifies under it, and until then the new key is accepted by hand".to_string());
455 };
456 if bound.instance_id == certifying
458 || super::lan_handover::allows(state, agent, &bound.instance_id, certifying, observed_b64, agentmux_common::time::now_secs()).await
459 || handed_over(state, &bound.instance_id, certifying).await
460 {
461 return Ok(());
462 }
463 Err(format!(
464 "the pin was vouched for by the install on {} and only that install, or one it handed over to, can move it: a certificate from another install does not",
465 if bound.host_hint.is_empty() { "another host" } else { bound.host_hint.as_str() }
466 ))
467}
468
469async fn handed_over(state: &AppState, from: &str, to: &str) -> bool {
471 tokio::time::timeout(DIRECTORY_WAIT, handed_over_asking(state, from, to)).await.unwrap_or(false)
472}
473
474async fn handed_over_asking(state: &AppState, from: &str, to: &str) -> bool {
475 use crate::muxbus::wan_verify::{instance_handed_over_to, Directory, GLOBAL_BUDGET};
476 let token = match crate::broker::get_global() {
477 Some(scheduler) => crate::muxbus::cloud_subscriber::load_valid_token(&state.id_store, &scheduler).await,
478 None => None,
479 };
480 let base_url = crate::muxbus::relay::rest_base_url();
481 let Some(token) = token.as_ref() else { return false };
482 let dir = Directory { base_url: &base_url, http: &state.http_client, token, budget: &GLOBAL_BUDGET };
483 instance_handed_over_to(&dir, from).await.is_some_and(|successor| successor == to)
484}
485
486pub(crate) fn fingerprint(key_b64: &str) -> String {
489 use sha2::{Digest, Sha256};
490 hex::encode(&Sha256::digest(key_b64.as_bytes())[..5])
491}
492
493pub(crate) fn audit(entry: &serde_json::Value) {
496 tracing::warn!(change = %entry, "pin changed");
497 #[cfg(test)]
499 AUDITED.lock().unwrap_or_else(|e| e.into_inner()).push(entry.clone());
500 #[cfg(not(test))]
501 if let Ok(root) = agentmux_common::data_paths::agentmux_root() {
502 write_audit(&root.join("logs"), entry);
503 }
504}
505
506pub(crate) fn write_audit(dir: &std::path::Path, entry: &serde_json::Value) {
508 let line = json!({ "at": agentmux_common::time::now_secs(), "change": entry });
509 if std::fs::create_dir_all(dir).is_err() {
510 return;
511 }
512 if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(dir.join("pin-changes.log")) {
513 use std::io::Write;
514 let _ = f.write_all(format!("{line}
515").as_bytes());
516 }
517}
518
519#[cfg(test)]
520pub(crate) static AUDITED: LazyLock<Mutex<Vec<serde_json::Value>>> = LazyLock::new(Default::default);
521
522#[cfg(test)]
523mod tests;