Skip to main content

agentmux_srv/server/remote_ops/
receive.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The receiving half: `POST /agentmux/remote/op` on the peer listener
5//! (spec §4.1-4.2, §6). Every refusal is an answer, `status: refused` with a
6//! `refused_reason`, never a prompt and never a downgrade; the order below is the
7//! order of the checks.
8//!
9//! 1. the call came over the LAN key (a peer), not a local credential;
10//! 2. this machine takes remote operations at all (`network:remote_ops`);
11//! 3. the envelope is well formed, and meant for this machine (`audience`);
12//! 4. it is fresh (a minute either way) and not older than this srv: the nonce store is in
13//!    memory, so a request signed before a restart could be replayed after it;
14//! 5. its signature verifies under the key this machine pins for that agent
15//!    (`reactive::lan_signer`, the same judgement a LAN jekt gets), and the install
16//!    the agent's certificate names, when one is on hand, is the install it claims;
17//! 6. the operation exists, and a state-changing one has a caller whose key is vouched for by a
18//!    fresh certificate from an install this machine trusts;
19//! 7. the nonce is new, or the first answer is repeated;
20//! 8. the operation runs under a [`RemoteCaller`].
21//!
22//! The broadcast `lan_key` only gets a request here; it never authorizes one.
23
24use std::collections::HashMap;
25use std::net::SocketAddr;
26use std::sync::{LazyLock, Mutex};
27use std::time::Duration;
28
29use axum::extract::{ConnectInfo, Extension, State};
30use axum::Json;
31
32use crate::server::remote_ops::op::{OpStatus, RemoteOpResult, SignedRemoteOp, REMOTE_OP_MAX_SKEW_SECS};
33
34use super::{lookup, RemoteCaller, RemoteResult, Verification};
35use crate::server::reactive::lan_signer::{self, SignerKey};
36use crate::server::{AppState, ReactiveAuthVia};
37
38/// How long an operation gets to run before the requester is told it failed.
39const RUN_TIMEOUT: Duration = Duration::from_secs(25);
40
41/// Longer than the clock window on both sides of it, so a request can't outlive its nonce.
42const NONCE_TTL_SECS: i64 = 2 * REMOTE_OP_MAX_SKEW_SECS + 60;
43/// Answers kept at most. Past this, with every entry still live, a new request is refused
44/// rather than evict a nonce a captured copy could then pass as.
45const MAX_NONCES: usize = 5_000;
46
47enum Seen {
48    /// The first copy is still running.
49    Running,
50    Done(RemoteOpResult),
51}
52
53struct Entry {
54    until: i64,
55    seen: Seen,
56}
57
58static NONCES: LazyLock<Mutex<HashMap<(String, String), Entry>>> = LazyLock::new(Default::default);
59
60/// When this srv started, in Unix seconds: forced when the routes are built.
61static STARTED_AT: LazyLock<i64> = LazyLock::new(agentmux_common::time::now_secs);
62
63pub(crate) fn mark_started() {
64    LazyLock::force(&STARTED_AT);
65}
66
67/// What a nonce said when it came in.
68enum Reservation {
69    First,
70    Repeat(RemoteOpResult),
71}
72
73fn reserve(key: &(String, String), now: i64) -> Result<Reservation, &'static str> {
74    let mut nonces = NONCES.lock().unwrap_or_else(|e| e.into_inner());
75    nonces.retain(|_, e| e.until > now);
76    match nonces.get(key) {
77        Some(Entry { seen: Seen::Done(result), .. }) => return Ok(Reservation::Repeat(result.clone())),
78        Some(Entry { seen: Seen::Running, .. }) => return Err("in_progress"),
79        None => {}
80    }
81    if nonces.len() >= MAX_NONCES {
82        return Err("busy");
83    }
84    nonces.insert(key.clone(), Entry { until: now + NONCE_TTL_SECS, seen: Seen::Running });
85    Ok(Reservation::First)
86}
87
88fn settle(key: &(String, String), result: &RemoteOpResult) {
89    let mut nonces = NONCES.lock().unwrap_or_else(|e| e.into_inner());
90    if let Some(entry) = nonces.get_mut(key) {
91        entry.seen = Seen::Done(result.clone());
92    }
93}
94
95/// The name of the machine at `from`, among the LAN `peers`; a short label when none is known.
96pub(crate) fn machine_in(peers: &[crate::backend::lan::discovery::LanInstance], from: Option<SocketAddr>) -> String {
97    let Some(ip) = from.map(|a| a.ip().to_string()) else { return "unknown machine".into() };
98    peers
99        .iter()
100        .find(|p| p.address == ip && !p.hostname.trim().is_empty())
101        .map(|p| p.hostname.trim().to_string())
102        .unwrap_or_else(|| "unknown machine".into())
103}
104
105fn machine_name(state: &AppState, from: Option<SocketAddr>) -> String {
106    // Every entry, not one per instance: the sender may connect from any address it was found at.
107    machine_in(&state.lan_discovery.get_all_instances(), from)
108}
109
110/// Peers whose unproven refusal was written to the audit trail lately, so a flood of bad requests
111/// from one address makes one row a minute, not a row each.
112static UNPROVEN_AUDITED: LazyLock<Mutex<HashMap<(String, String), i64>>> = LazyLock::new(Default::default);
113const UNPROVEN_AUDIT_EVERY_SECS: i64 = 60;
114const UNPROVEN_AUDIT_MAX_PEERS: usize = 256;
115
116/// A request refused before its signature verified: nobody is proven, so the row names the peer's
117/// address, not the agent the request claims to be, and keeps none of the request's own text.
118fn audit_unproven(state: &AppState, from: Option<SocketAddr>, reason: &str, now: i64) {
119    let peer = from.map(|a| a.ip().to_string()).unwrap_or_else(|| "unknown peer".into());
120    {
121        let mut seen = UNPROVEN_AUDITED.lock().unwrap_or_else(|e| e.into_inner());
122        seen.retain(|_, at| now - *at < UNPROVEN_AUDIT_EVERY_SECS);
123        let key = (peer.clone(), reason.to_string());
124        if seen.contains_key(&key) || seen.len() >= UNPROVEN_AUDIT_MAX_PEERS {
125            return;
126        }
127        seen.insert(key, now);
128    }
129    state.reactive_handler.log_fleet_action_audit(
130        Some(&format!("unproven peer {peer}")),
131        "remote-op",
132        "",
133        "remote.refused (unproven)",
134        false,
135        Some(reason),
136        "",
137        None,
138    );
139}
140
141/// The audit row on this machine: `remote.<op>`, by `agent@machine`, with how it was proven and how it ended.
142fn audit(state: &AppState, who: &str, op: &str, proof: &str, result: &RemoteOpResult, nonce: &str, reason: &str) {
143    let ok = matches!(result.status, OpStatus::Done | OpStatus::Queued | OpStatus::PendingVeto);
144    // A read of the Audit is no row in it, whatever the answer: the Audit asks again every few seconds while it is
145    // shown, and a row (a refusal for a computer that does not share, say) would make it ask again at once.
146    if op == crate::backend::audit_query::peers::QUERY_OP {
147        return;
148    }
149    let note = result.refused_reason.clone().or_else(|| result.result.get("error").and_then(|e| e.as_str()).map(str::to_string));
150    state.reactive_handler.log_fleet_action_audit(
151        Some(who),
152        "remote-op",
153        "",
154        &format!("remote.{op} ({proof})"),
155        ok,
156        note.as_deref(),
157        nonce,
158        (!reason.is_empty()).then_some(reason),
159    );
160}
161
162pub(crate) async fn handle_remote_op(
163    State(state): State<AppState>,
164    via: Option<Extension<ReactiveAuthVia>>,
165    peer: Option<ConnectInfo<SocketAddr>>,
166    Json(signed): Json<SignedRemoteOp>,
167) -> Json<RemoteOpResult> {
168    crate::server::lan_watch::claimed(&signed.op.requester.slug);
169    let peer_ip = peer.map(|c| c.0);
170    let via = via.map(|Extension(v)| v);
171    Json(receive(&state, via, peer_ip, signed, agentmux_common::time::now_secs(), *STARTED_AT).await)
172}
173
174/// [`handle_remote_op`] without the HTTP: `now` is the clock and `started_at` when this srv began.
175pub(super) async fn receive(
176    state: &AppState,
177    via: Option<ReactiveAuthVia>,
178    from: Option<SocketAddr>,
179    signed: SignedRemoteOp,
180    now: i64,
181    started_at: i64,
182) -> RemoteOpResult {
183    let op = &signed.op;
184    let who = format!("{}@{}", op.requester.slug, machine_name(state, from));
185    let refuse = |reason: &str, proof: &str| {
186        let result = RemoteOpResult::refused(reason);
187        if proof == "unproven" {
188            audit_unproven(state, from, reason, now);
189        } else {
190            audit(state, &who, &op.op, proof, &result, &op.nonce, &op.reason);
191        }
192        result
193    };
194    if via != Some(ReactiveAuthVia::LanKey) {
195        return refuse("not_a_peer", "unproven");
196    }
197    if !super::enabled(state) {
198        return refuse("remote_ops_off", "unproven");
199    }
200    let max_params = super::max_params_of(&op.op);
201    if let Err(why) = op.check_shape_with(max_params) {
202        return refuse(why, "unproven");
203    }
204    if op.audience != crate::server::remote_ops::op::lan_audience(&state.lan_key) {
205        return refuse("wrong_audience", "unproven");
206    }
207    if (now - op.ts).abs() > REMOTE_OP_MAX_SKEW_SECS {
208        return refuse("stale_request", "unproven");
209    }
210    if op.ts < started_at {
211        return refuse("signed_before_restart", "unproven");
212    }
213    let key = match crate::server::lan_watch::during("sender key lookup", lan_signer::resolve(state, &op.requester.slug)).await {
214        SignerKey::Pinned(key) => key,
215        SignerKey::Unknown => return refuse("unknown_sender", "unproven"),
216        SignerKey::Unproven | SignerKey::Refused => return refuse("unverified_sender", "unproven"),
217    };
218    if !signed.verify_with(&key, max_params) {
219        return refuse("bad_signature", "unproven");
220    }
221    crate::server::lan_watch::during("sender continuity", crate::server::reactive::lan_continuity::bind_after_verified(state, &op.requester.slug, &key)).await;
222    // The install is named by the certificate its agent's host issued, when this machine holds one; the
223    // request's own claim must agree with it. A certificate counts only if it certifies this agent's name
224    // and exactly this key, on the LAN channel, and is fresh (`lan_continuity::check_cert`).
225    let cert = state
226        .lan_discovery
227        .cached_lan_cert(&op.requester.slug)
228        .filter(|cert| crate::server::reactive::lan_continuity::check_cert(cert, &op.requester.slug, &key, 0, now).is_ok());
229    let instance_id = match cert {
230        Some(cert) if !op.requester.instance_id.is_empty() && cert.instance_id != op.requester.instance_id => {
231            return refuse("install_mismatch", "lan-verified");
232        }
233        Some(cert) => cert.instance_id,
234        None => String::new(),
235    };
236    let mut caller = RemoteCaller {
237        agent_uid: op.requester.agent_uid.clone(),
238        slug: op.requester.slug.clone(),
239        machine: machine_name(state, from),
240        instance_id,
241        install_trusted: false,
242        verification: Verification::Lan,
243        reason: op.reason.clone(),
244    };
245    let proof = caller.verification.as_str();
246    let Some(operation) = lookup(&op.op) else {
247        return refuse("unknown_op", proof);
248    };
249    if operation.changes_state || operation.needs_approved_install {
250        if caller.instance_id.is_empty() {
251            return refuse("needs_certificate", proof);
252        }
253        // A certificate any install can issue for itself proves nothing about who hosts the agent:
254        // the install must be one this machine already trusts, as for moving a pinned key.
255        if let Err(why) = crate::server::lan_watch::during("install trust check", crate::server::reactive::lan_continuity::instance_trust(state, &caller.instance_id)).await {
256            tracing::info!(agent = %caller.slug, install = %caller.instance_id, %why, "remote operation refused: the install that vouches for the agent is not trusted here");
257            return refuse("install_not_trusted", proof);
258        }
259        caller.install_trusted = true;
260    }
261    let nonce_key = (op.requester.slug.to_ascii_lowercase(), op.nonce.clone());
262    match reserve(&nonce_key, now) {
263        Ok(Reservation::First) => {}
264        Ok(Reservation::Repeat(first)) => return first,
265        Err(why) => return refuse(why, proof),
266    }
267    let ran: RemoteResult = match tokio::time::timeout(RUN_TIMEOUT, crate::server::lan_watch::during(&format!("operation {}", op.op), (operation.run)(state, &caller, op.params.clone()))).await {
268        Ok(ran) => ran,
269        Err(_) => Err(crate::server::lan_watch::timed_out(super::RemoteRefusal::failed("the operation did not finish in time"))),
270    };
271    let mut result = match ran {
272        Ok(value) => RemoteOpResult::done(value),
273        Err(refusal) if refusal.code == "failed" => RemoteOpResult::failed(&refusal.message),
274        Err(refusal) => {
275            let mut r = RemoteOpResult::refused(refusal.code);
276            r.result = serde_json::json!({ "message": refusal.message });
277            r
278        }
279    };
280    result.audit_id = op.nonce.clone();
281    audit(state, &caller.actor(), &op.op, proof, &result, &op.nonce, &op.reason);
282    settle(&nonce_key, &result);
283    result
284}