Skip to main content

agentmux_srv/server/reactive/
lan_handover.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A name that moved to another computer, as a computer that pinned it learns of it (SPEC_MOVE_AN_AGENT_TO_ANOTHER_COMPUTER
5//! section 6.5). The source install tells its peers with a signed statement (`agent_move::handover`); a peer that holds the
6//! name keeps what it accepted here, and the pin rule (`lan_continuity`) lets the **destination install** vouch for the new
7//! key when it shows up, as the install the pin was bound to would have.
8//!
9//! What is accepted is narrow: from the install the name's pin is bound to, naming the key the pin holds now, newer than the
10//! pin, unexpired, and from an install this computer still trusts. It moves nothing by itself: the new key is pinned only
11//! when it is shown with the destination's own certificate, through the same checks as any move of a pin. It is kept in
12//! memory: a computer that restarts before the new key appears falls back to accepting the key by hand.
13//!
14//! What was true when it was taken is checked again when it is used ([`allows`]): the pin must still hold the key the statement was
15//! about and still be older than it (the person may have accepted another key since), and the source install must still be
16//! trusted (it may have been revoked since). A statement that fails either is of no use and is dropped.
17
18use std::sync::{Mutex, MutexGuard};
19
20use agentmux_common::jekt_sign::decode_public_key_b64;
21
22use super::lan_continuity::{fingerprint, instance_trust};
23use super::AppState;
24use crate::backend::agent_move::handover::HandoverCertificate;
25
26/// Statements kept at once: a flood from a paired computer cannot make this grow.
27const MAX_KEPT: usize = 256;
28
29struct Accepted {
30    name: String,
31    new_key: String,
32    source_install: String,
33    dest_install: String,
34    expires_at: i64,
35    /// The fingerprint of the key the name's pin held when the statement was taken, and when the statement was issued: the pin
36    /// must still be that key, and still older than the statement, for the statement to move it.
37    old_fp: String,
38    issued_at: i64,
39}
40
41fn kept() -> MutexGuard<'static, Vec<Accepted>> {
42    static KEPT: Mutex<Vec<Accepted>> = Mutex::new(Vec::new());
43    KEPT.lock().unwrap_or_else(|e| e.into_inner())
44}
45
46/// Takes the statement `cert`, sent by an agent of `from_install` and already verified under that install's key. Why not, in
47/// a sentence, when it is not taken.
48pub(crate) async fn accept(state: &AppState, from_install: &str, cert: &HandoverCertificate, now: i64) -> Result<(), String> {
49    if cert.source_install != from_install || cert.dest_install == cert.source_install {
50        return Err("the statement is not from the install that sent it, or names no other install".to_string());
51    }
52    if decode_public_key_b64(&cert.new_key).is_none() {
53        return Err("the new key is not a key".to_string());
54    }
55    let (pinned, since) = state
56        .mstore
57        .lan_peer_pubkey_pin_since(&cert.name)
58        .map_err(|e| format!("the pin could not be read: {e}"))?
59        .ok_or("this computer holds no pin for that name")?;
60    let bound = state.mstore.lan_pin_installed(&cert.name).map_err(|e| format!("the pin's install could not be read: {e}"))?;
61    if !bound.is_some_and(|b| b.instance_id == cert.source_install) {
62        return Err("the name is not pinned under the install that sent this: only that install may say it moved".to_string());
63    }
64    if fingerprint(&pinned) != cert.old_fp {
65        return Err("the statement is not about the key this computer holds for the name".to_string());
66    }
67    if cert.issued_at <= since {
68        return Err("the statement is older than the pin".to_string());
69    }
70    // An install that was revoked cannot hand a name on.
71    instance_trust(state, &cert.source_install).await.map_err(|e| format!("the install is not trusted: {e}"))?;
72    let mut all = kept();
73    all.retain(|a| a.expires_at > now);
74    all.retain(|a| !(a.name == cert.name && a.source_install == cert.source_install));
75    if all.len() >= MAX_KEPT {
76        return Err("too many statements are waiting".to_string());
77    }
78    all.push(Accepted {
79        name: cert.name.clone(),
80        new_key: cert.new_key.clone(),
81        source_install: cert.source_install.clone(),
82        dest_install: cert.dest_install.clone(),
83        expires_at: cert.expires_at,
84        old_fp: cert.old_fp.clone(),
85        issued_at: cert.issued_at,
86    });
87    Ok(())
88}
89
90/// Whether a statement kept here still holds for the pin as it is now: it is about the key the pin holds and was issued after the pin.
91fn about_the_pin(a: &Accepted, pinned: &(String, i64)) -> bool {
92    fingerprint(&pinned.0) == a.old_fp && a.issued_at > pinned.1
93}
94
95/// Whether the install `certifying` may vouch for `observed_key` as `agent`'s key: the install the pin is bound to (`bound`)
96/// said, in a statement taken here, that the name went to exactly that install and exactly that key, and that still holds: the
97/// pin is the key it was about and older than it, and `bound` is still an install this computer trusts.
98pub(crate) async fn allows(state: &AppState, agent: &str, bound: &str, certifying: &str, observed_key: &str, now: i64) -> bool {
99    let Ok(Some(pinned)) = state.mstore.lan_peer_pubkey_pin_since(agent) else { return false };
100    let found = {
101        let all = kept();
102        all.iter()
103            .any(|a| a.name == agent.to_lowercase() && a.source_install == bound && a.dest_install == certifying && a.new_key == observed_key && a.expires_at > now && about_the_pin(a, &pinned))
104    };
105    if !found {
106        return false;
107    }
108    match instance_trust(state, bound).await {
109        Ok(_) => {}
110        Err(why) if why == super::lan_continuity::REVOKED => {
111            // A source that is revoked says nothing any more: what it said is dropped, not kept for the rest of its days.
112            kept().retain(|a| a.source_install != bound);
113            return false;
114        }
115        // The directory could not be asked, or this machine is signed out: nothing is known against the source, so what it said
116        // is kept for when the answer comes, and is not used meanwhile.
117        Err(_) => return false,
118    }
119    true
120}
121
122#[cfg(test)]
123pub(crate) fn forget_all_for_tests() {
124    kept().clear();
125}