Skip to main content

agentmux_srv/server/reactive/
lan_v2.rs

1//! Identity M4d-6 (`SPEC_AGENT_IDENTITY_CARRIED_NOT_DERIVED_2026_09_23.md`
2//! §6.5.10): the LAN v2 signature, checked once the v1 LAN signature verified.
3//! LAN peers are unauthenticated, so a UID it proves is recorded only as
4//! claimed by that LAN path: never verified, never matched to a local row.
5//! A sender that presents a UID and a v2 signature has made a claim, though: a
6//! claim that does not hold up counts as a failed signature, like a name key
7//! that does not match its pin.
8//!
9//! [`sign_at_origin`] is the sending half for an agent whose own process
10//! signed nothing (`SPEC_LAN_JEKT_SIGNED_BY_SRV_2026_10_25.md`).
11
12use super::{AppState, InjectionRequest};
13
14/// [`sign_at_origin_why`], and one INFO line saying what became of the signature
15/// of a request about to go to the LAN peer at `peer_url`.
16pub(super) fn sign_and_log(
17    mstore: &crate::backend::storage::store::Store,
18    caller_uid: &str,
19    req: InjectionRequest,
20    peer_url: &str,
21) -> InjectionRequest {
22    let (req, signature) = sign_at_origin_why(mstore, caller_uid, req);
23    tracing::info!(target = %req.target_agent, source = req.source_agent.as_deref().unwrap_or(""), peer = %peer_url, v2 = req.lan_sig_v2.is_some(), "LAN forward: {signature}");
24    req
25}
26
27/// One INFO line for a request that arrived over the LAN: what was made of its signature. Called for
28/// every request `deliver` takes, so it also tells `relay_watch` that the sender is reachable.
29pub(super) fn log_receipt(req: &InjectionRequest) {
30    crate::muxbus::relay_watch::heard_from(req.source_agent.as_deref(), &req.target_agent);
31    if let Some(note) = receipt_note(req) {
32        tracing::info!(target = %req.target_agent, source = req.source_agent.as_deref().unwrap_or(""), v2 = req.lan_sig_v2.is_some(), "LAN receipt: {note}");
33    }
34}
35
36/// In a word, what the receiving side made of a LAN request's signature, for
37/// the log line of every LAN receipt: a peer that sees `network-claimed` on a
38/// message can then be told whether nothing was signed or nothing could be
39/// checked. `None` for a request that did not arrive over the LAN.
40pub(super) fn receipt_note(req: &InjectionRequest) -> Option<&'static str> {
41    if req.delivery_tier.as_deref() != Some("lan") {
42        return None;
43    }
44    Some(match req.lan_verified {
45        Some(true) => "signature verified",
46        Some(false) => "signature failed verification",
47        None if req.lan_sig.is_none() => "unverified: no signature came with it",
48        None if req.source_agent.as_deref().is_none_or(str::is_empty) => "unverified: signed, but names no sender",
49        None => "unverified: signed, but no key for the sender was found among the LAN peers",
50    })
51}
52
53/// Record `source_uid` as claimed by this LAN path when the answering peer
54/// gave that UID's key for `claimed`, the `(name, uid)` pin matches, and the
55/// v2 signature verifies under it. Only once the v1 check passed, so the
56/// name pin already matched: the UID pin is set only beside it.
57///
58/// A request that carries both a UID and a v2 signature but fails any of those
59/// checks (the peer gave another UID for the name, the pin holds a different
60/// key, the signature does not verify, the pin store cannot be read) is no
61/// longer verified: `lan_verified` becomes `Some(false)`. A request with no v2
62/// at all is left as v1 decided it, and so is one whose peer gave no UID key
63/// for a name that never gave one: there is nothing to contradict. Once a UID
64/// is pinned under the name, the peer owes its key again: a cache that no
65/// longer holds it is asked afresh (`name_key` must come back unchanged), and
66/// an answer without it fails the jekt rather than fall back to v1.
67pub(super) async fn claim_uid(state: &AppState, req: &mut InjectionRequest, claimed: &str, name_key: &[u8]) {
68    if req.lan_verified != Some(true) {
69        return;
70    }
71    super::lan_continuity::bind_after_verified(state, claimed, name_key).await;
72    let (Some(sig), Some(uid)) = (req.lan_sig_v2.clone(), req.source_uid.clone().filter(|u| !u.is_empty())) else {
73        return;
74    };
75    let record = crate::backend::agent_resolve::record_uid_fallback;
76    let Some((answered_uid, key)) = uid_key_owed(state, claimed, name_key).await else {
77        if state.mstore.lan_peer_uid_pin_exists(claimed).unwrap_or(true) {
78            record("m4d.lan_v2_pinned_peer_gave_no_uid_key");
79            req.lan_verified = Some(false);
80        }
81        return;
82    };
83    if answered_uid != uid {
84        record("m4d.lan_v2_other_uid");
85        req.lan_verified = Some(false);
86        return;
87    }
88    use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
89    let key_b64 = BASE64.encode(&key);
90    // A UID key is pinned only once the message verifies under it, so a key a peer merely shows (after a
91    // move cleared the UID pins, or for a UID not seen before) pins nothing.
92    let verified = agentmux_common::jekt_sign::verify_lan_jekt_v2(
93        &key,
94        req.request_id.as_deref().unwrap_or(""),
95        claimed,
96        &uid,
97        &req.target_agent,
98        req.ts_secs.unwrap_or(0),
99        &req.message,
100        &sig,
101    );
102    if !verified {
103        record("m4d.lan_v2_bad_sig");
104        req.lan_verified = Some(false);
105        return;
106    }
107    match state.mstore.lan_peer_uid_pin_get_or_set(claimed, &uid, &key_b64) {
108        Ok(pinned) if pinned == key_b64 => req.lan_claimed_uid = uid,
109        Ok(_) => {
110            record("m4d.lan_v2_pin_mismatch");
111            req.lan_verified = Some(false);
112        }
113        Err(_) => req.lan_verified = Some(false), // fail closed, as for the name pin
114    }
115}
116
117/// The UID key the peer gave beside `claimed`'s name key: the cached answer,
118/// or, when a UID is already pinned under the name and the cache has none, one
119/// fresh ask.
120async fn uid_key_owed(state: &AppState, claimed: &str, name_key: &[u8]) -> Option<(String, Vec<u8>)> {
121    if let Some(answer) = state.lan_discovery.cached_lan_uid_key(claimed) {
122        return Some(answer);
123    }
124    if !state.mstore.lan_peer_uid_pin_exists(claimed).unwrap_or(true) {
125        return None;
126    }
127    state.lan_discovery.refetch_lan_uid_key(claimed, name_key, &state.http_client).await
128}
129
130/// The LAN forward of a jekt from an agent that signed nothing itself. A Codex
131/// agent's jekts arrived at every LAN peer with no signature (so
132/// `TRUST=network-claimed`, however good the receiver's checks) though srv held
133/// the agent's key and its token named it. As for WAN
134/// (`SPEC_WAN_JEKT_SIGNED_BY_SRV_2026_10_14.md` §3.1), srv signs, here at the
135/// origin, for the agent the request's own token names, and only then:
136///
137/// 1. `caller_uid` is non-empty: this srv saw the agent's token, so this is
138///    the origin, not a hop (a hop carries no `Caller`).
139/// 2. The request is host-tier, as every origin request is.
140/// 3. Nothing is signed yet: an agent's own `lan_sig` is never replaced.
141/// 4. The token's row owns `source_agent` alone (`actor::wan_signer`).
142///
143/// It signs with that name's LAN key (v1), and with the UID-keyed key (v2) when
144/// the sender carried no UID of its own, the same two signatures the MCP makes.
145/// The receiver checks exactly what it checked before; nothing there changes.
146/// Any unmet condition, or a missing key, returns the request as it came.
147#[cfg(test)]
148pub(super) fn sign_at_origin(
149    mstore: &crate::backend::storage::store::Store,
150    caller_uid: &str,
151    req: InjectionRequest,
152) -> InjectionRequest {
153    sign_at_origin_why(mstore, caller_uid, req).0
154}
155
156/// [`sign_at_origin`], and in a word what became of the signature: the agent
157/// signed it itself, srv signed it, or why neither (for the log line of a LAN
158/// forward, so a peer that sees `network-claimed` can be explained).
159pub(super) fn sign_at_origin_why(
160    mstore: &crate::backend::storage::store::Store,
161    caller_uid: &str,
162    mut req: InjectionRequest,
163) -> (InjectionRequest, &'static str) {
164    if req.lan_sig.is_some() {
165        return (req, "signed by the agent's own process");
166    }
167    if req.delivery_tier.as_deref() != Some("host") {
168        return (req, "unsigned: a forwarded request, not the origin (not host-tier)");
169    }
170    let Some(signer) = crate::server::actor::wan_signer(mstore, caller_uid, &req).map(str::to_string) else {
171        return (req, "unsigned: no agent token names the sender (or its row doesn't own the name alone)");
172    };
173    let Some(key) = mstore.agent_lan_key_ensure(&signer).ok().and_then(|k| agentmux_common::jekt_sign::decode_key(&k.private_key)) else {
174        return (req, "unsigned: no LAN key for the sender");
175    };
176    let (msgid, ts) = msgid_and_ts(&req);
177    let Some(sig) = agentmux_common::jekt_sign::sign_lan_jekt(&key, &msgid, &signer, &req.target_agent, ts, &req.message) else {
178        return (req, "unsigned: signing failed");
179    };
180    req.request_id = Some(msgid.clone());
181    req.ts_secs = Some(ts);
182    req.lan_sig = Some(sig);
183    if req.lan_sig_v2.is_none() && req.source_uid.as_deref().is_none_or(str::is_empty) {
184        let uid_key = mstore.agent_uid_keys_ensure(caller_uid).ok().flatten()
185            .and_then(|(keys, _)| agentmux_common::jekt_sign::decode_key(&keys.lan.private_key));
186        if let Some(v2) = uid_key.and_then(|k| agentmux_common::jekt_sign::sign_lan_jekt_v2(&k, &msgid, &signer, caller_uid, &req.target_agent, ts, &req.message)) {
187            req.source_uid = Some(caller_uid.to_string());
188            req.lan_sig_v2 = Some(v2);
189        }
190    }
191    tracing::info!(agent_id = %signer, "LAN jekt signed at the origin: the sender's process signed nothing");
192    (req, "signed by srv at the origin")
193}
194
195/// The message id and time a signature covers. The MCP sets both; a sender that did not (a shell's
196/// `muxsh agent send`) gets them here, so the signature has something to cover.
197fn msgid_and_ts(req: &InjectionRequest) -> (String, i64) {
198    let msgid = req.request_id.clone().filter(|m| !m.is_empty()).unwrap_or_else(|| {
199        static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
200        let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
201        format!("{}-{}-s{n}", agentmux_common::time::now_ms_u64(), std::process::id())
202    });
203    (msgid, req.ts_secs.filter(|t| *t > 0).unwrap_or_else(agentmux_common::time::now_secs))
204}
205
206/// The same-machine, other-instance counterpart of [`sign_at_origin`]: the cross-channel signatures
207/// (`channel_sig`, and `channel_sig_v2` when the sender carried no UID of its own) for an agent whose own
208/// process signed nothing, so the receiving instance still finds a published key's signature on it. The
209/// conditions are `sign_at_origin`'s, and a signature already there is never replaced.
210pub(super) fn channel_sign_at_origin(
211    mstore: &crate::backend::storage::store::Store,
212    caller_uid: &str,
213    mut req: InjectionRequest,
214) -> InjectionRequest {
215    if req.channel_sig.is_some() || req.delivery_tier.as_deref() != Some("host") {
216        return req;
217    }
218    let Some(signer) = crate::server::actor::wan_signer(mstore, caller_uid, &req).map(str::to_string) else {
219        return req;
220    };
221    let Some(key) = mstore.agent_lan_key_ensure(&signer).ok().and_then(|k| agentmux_common::jekt_sign::decode_key(&k.private_key)) else {
222        return req;
223    };
224    let (msgid, ts) = msgid_and_ts(&req);
225    let channel = crate::backend::reactive::registry::local_channel_id();
226    let Some(sig) = agentmux_common::jekt_sign::sign_channel_jekt(&key, &msgid, &signer, &channel, &req.target_agent, ts, &req.message) else {
227        return req;
228    };
229    req.request_id = Some(msgid.clone());
230    req.ts_secs = Some(ts);
231    req.channel_sig = Some(sig);
232    if req.channel_sig_v2.is_none() && req.source_uid.as_deref().is_none_or(str::is_empty) {
233        let uid_key = mstore.agent_uid_keys_ensure(caller_uid).ok().flatten()
234            .and_then(|(keys, _)| agentmux_common::jekt_sign::decode_key(&keys.lan.private_key));
235        if let Some(v2) = uid_key.and_then(|k| agentmux_common::jekt_sign::sign_channel_jekt_v2(&k, &msgid, &signer, caller_uid, &channel, &req.target_agent, ts, &req.message)) {
236            req.source_uid = Some(caller_uid.to_string());
237            req.channel_sig_v2 = Some(v2);
238        }
239    }
240    req.source_channel = Some(channel);
241    tracing::info!(agent_id = %signer, "cross-channel jekt signed at the origin: the sender's process signed nothing");
242    req
243}
244
245#[cfg(test)]
246#[path = "../tests/reactive/lan_v2_tests.rs"]
247mod tests;