Skip to main content

agentmux_srv/server/reactive/
lan_continuity.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! LAN key continuity (`docs/specs/SPEC_LAN_KEY_CONTINUITY_2026_10_29.md`): a
5//! pinned name whose agent now shows a different key moves to it with no
6//! person in the loop, but only when the install that hosts the agent vouches
7//! for the key with a certificate, and this machine already trusts that
8//! install. Anything else stays refused.
9//!
10//! The same certificate is what makes a name's FIRST pin: a name with no pin is pinned only when a
11//! trusted install vouches for the key it shows ([`on_first_contact`]); an unvouched first key is
12//! never pinned by itself and its messages stay unproven until the person accepts it.
13//!
14//! The sending half is [`issue_cert`]: the lookup answer for an agent carries
15//! `lan_cert`, a [`WanKeyRecord`] (channel `lan`) signed by the install's own
16//! key. The receiving half is [`move_if_vouched`], called when the name pin
17//! and the key just shown disagree, and by the agent route of `pins.adopt`.
18
19use 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
29/// The channel a LAN key's certificate names.
30pub(crate) const CERT_CHANNEL: &str = "lan";
31/// How far from now a certificate's time may be: it is signed when the answer
32/// is given, so an old copy is a replay.
33pub(crate) const CERT_MAX_AGE_SECS: i64 = 600;
34/// An unvouched key is not looked into again for this long, so a peer that
35/// keeps showing one cannot make this machine ask the directory every time.
36const RECHECK_AFTER_SECS: i64 = 60;
37/// At most this many unvouched keys are remembered at once; past it a key is simply looked into again.
38const MAX_UNVOUCHED: usize = 1024;
39
40/// What made the issuing install trusted.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub(crate) enum Path {
43    /// This machine had already pinned the install for some agent.
44    PinnedInstance,
45    /// The signed-in account's install list shows it live and not revoked.
46    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
58/// The certificate for `agent`'s LAN key (`public_key_b64`), signed by this
59/// install now. `None` when this install has no WAN identity or the key is not
60/// a key.
61pub(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
68/// The pin and the key just shown disagree: move the pin if the hosting install vouches for the key,
69/// else record why it stays refused. `true` means carry on verifying under the (moved) pin.
70pub(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
81/// A name has no pin and shows `observed_key`: pin it only if a trusted install vouches for it. `true`
82/// means carry on verifying under the (new) pin. `false` leaves the name unpinned and the message
83/// unproven, and keeps the key for the pin screen, which asks the person once to accept it.
84pub(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
95/// A machine's sender-key lookup answer with this install's certificate for the key, as an agent's key is answered, so a
96/// peer that trusts the install pins it at first contact (a Swarm broadcast, a quiet note) instead of waiting for the person.
97pub(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    // Only this install's own sender name, and only for the key stored for it: nothing else is ever certified here.
100    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
111/// Put this install's certificate for `public_key_b64` into a lookup answer as `lan_cert`.
112pub(super) fn add_cert(state: &AppState, agent: &str, public_key_b64: &str, answer: &mut serde_json::Map<String, serde_json::Value>) {
113    // An agent that moved to another computer is no longer vouched for from here: the old key gets no certificate and no
114    // statement that this install hosts it, so a copy of it gains nothing.
115    if moved_off(state, agent) {
116        return;
117    }
118    if let Some(cert) = issue_cert(state, agent, public_key_b64) {
119        // The agent's own word that this install hosts it: another install can wrap the public key in a
120        // certificate of its own, but cannot sign for the agent.
121        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
130/// Whether the agent named `agent` was moved to another computer from this one (its record carries the `moved` mark).
131fn 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
136/// The certificate's own checks, none of which need the network: it is a
137/// chain-valid certificate by some install, for this agent and channel `lan`
138/// and exactly the key shown, issued close to now and after the pin it would
139/// replace. Whether the install is trusted is [`instance_trust`]'s.
140pub(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
160/// The refusal [`instance_trust`] gives for an install known to be revoked: the only one that says the install itself is no longer
161/// trusted, as against a directory that could not be asked.
162pub(crate) const REVOKED: &str = "the install is revoked";
163
164/// Whether this machine trusts the install `instance_id`: pinned here for some
165/// agent already, else live in the account's directory. An install this machine
166/// knows to be revoked is trusted by neither way, and a pin does not outlive a
167/// revocation the directory holds.
168pub(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
187/// How long a check of a message from another machine waits on the account's directory: the sign-in token
188/// (which can sit behind a refresh that hangs) and the lookups. The sender gives up on its forward after
189/// 10 s, so a longer wait only ends in a lost message (task #2512).
190const DIRECTORY_WAIT: std::time::Duration = std::time::Duration::from_secs(3);
191
192/// `asking`, within `wait`. Past it the answer is exactly what it is when the directory cannot be asked at all (no
193/// sign-in): a pinned install is trusted as pinned (`Path::PinnedInstance`), claiming nothing from a lookup that did
194/// not happen, and an unpinned one is not trusted, with the reason. An install already known locally to be revoked
195/// was refused before this was asked.
196async 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
210/// [`instance_trust`]'s asks of the account's directory: the token, the revocation of a pinned install, the
211/// listing of an unpinned one.
212async 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
241/// Keep a revocation learned from the directory, so it still stands when the directory cannot be
242/// asked. The install may have no known-install row yet (a pin the user adopted never went through
243/// WAN verification), and recording a check updates a row only, so make the row first.
244fn 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
255/// Move `agent`'s name pin to `observed_key` if `cert` vouches for it; for a name with no pin, make its
256/// first pin the same way. The UID
257/// pins beside the name pin go with the old key and are set again by the next
258/// message that verifies under the new one (`lan_peer_pubkey_pin_replace`).
259/// Returns what vouched, or why nothing did. `by` is who asked, for the audit
260/// line: `"automatic"` for a message that arrived, an agent's id for the route.
261///
262/// `force` skips the wait after an unvouched answer (the agent route asks for it
263/// on purpose).
264pub(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    // A key the name moved off is not taken back, whoever asks and whatever certificate comes with it.
275    if let Some(why) = retired_reason(state, agent, observed_key) {
276        return Err(why);
277    }
278    // Per certifying install too: one install's refusal says nothing of another's certificate for the same key.
279    let marker = (agent.to_lowercase(), format!("{observed_b64}|{}", cert.map_or("", |c| c.instance_id.as_str())));
280    // Asked a moment ago and not vouched: say the same reason again, without asking again.
281    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            // Only the last minute matters, so a peer that shows a new key every time cannot make this grow.
293            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    // Kept from the later of now and the certificate's own time: with the host's clock ahead of
305    // ours, an older certificate of the same host (still inside the freshness window) is then
306    // older than this pin too, and cannot move it back.
307    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        // The pin changed while the install was being asked about (a newer move, or the user's own
314        // change): never write over it from an older check. If it already holds this key, done.
315        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
340/// First contact: pinned only now that a trusted install vouched, and bound to that install. `get_or_set`
341/// keeps whichever key got there first, so a concurrent first contact cannot be overwritten from an older check.
342fn 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
361/// Record that the install behind `cert` vouched for the key `agent` is pinned to. Best effort: a pin left
362/// unbound is bound by the next message that verifies under it ([`bind_after_verified`]) and moves by hand until then.
363fn 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
373/// Whether the agent itself, under the key `key_b64`, says the install behind `cert` hosts it: the statement
374/// the host adds to its lookup answer. A certificate alone proves only that some trusted install wrapped the
375/// key in one, which any of the account's installs can do for a public key it merely saw.
376fn 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
382/// Remember that `agent` moved off `old_b64`, so a message signed with it later is refused as retired.
383pub(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
389/// Why `observed_key` is refused when `agent` once moved off it, in a sentence; `None` if it never did.
390pub(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
396/// A message just verified under `agent`'s pinned key (`key`). If the pin is bound to no install yet, bind it
397/// to the install behind the certificate the peer shows for exactly that key, when this machine trusts that
398/// install. Binding on a verified message keeps it as strong as the pin: a certificate alone proves nothing,
399/// since anyone can wrap a public key in a certificate of an install of their own.
400pub(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    // Not asked again for a minute after an install that is not trusted, as for an unvouched key.
414    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    // `None`: the name has no pin yet, and this certificate is what would make its first one.
438    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    // The pin this check was made against: the move is conditional on it still being the pin.
445    Ok((path, cert.clone(), pinned))
446}
447
448/// A pin moves only on the say of the install that vouched for it, or one that install handed over to (it
449/// signed a revocation naming the new one as its successor). A pin bound to no install yet does not move on
450/// its own: it binds on the next verified message, and until then a person accepts the key.
451async 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    // Or the bound install said, in a statement of its own about this name, that the name moved to exactly this install and key.
457    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
469/// Whether the account's directory holds a revocation `from` signed that names `to` as its successor.
470async 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
486/// A short fingerprint of a base64 key: enough to tell two keys apart on a
487/// screen, never the key. (Not a prefix of the key: it is a hash of it.)
488pub(crate) fn fingerprint(key_b64: &str) -> String {
489    use sha2::{Digest, Sha256};
490    hex::encode(&Sha256::digest(key_b64.as_bytes())[..5])
491}
492
493/// One line to `logs/pin-changes.log`, best effort. Fingerprints and labels
494/// only: never a key.
495pub(crate) fn audit(entry: &serde_json::Value) {
496    tracing::warn!(change = %entry, "pin changed");
497    // Tests keep the entries they cause instead of writing the real log.
498    #[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
506/// Append one line for `entry` to `pin-changes.log` in `dir`.
507pub(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;