Skip to main content

agentmux_srv/server/remote_ops/
op.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A remote operation: a typed request one AgentMux sends another on behalf of
5//! one of its agents, which the receiving AgentMux carries out itself
6//! (`docs/specs/SPEC_AGENTS_OPERATE_OTHER_MACHINES_2026_10_30.md` §4.1).
7//!
8//! The envelope and its signature live here, beside the jekt signers, so the
9//! sending and the receiving srv can't drift on the signed material. The
10//! signature is Ed25519 with the requesting agent's LAN key, in a domain of its
11//! own: a jekt's signature never verifies as a remote op, and the reverse.
12//! It covers every field the receiver acts on, the `params` included, so a
13//! request can't be re-aimed (another `audience`), re-attributed (another
14//! `requester`), re-timed or given other parameters.
15
16use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
17use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
18use serde::{Deserialize, Serialize};
19use serde_json::Value;
20
21use agentmux_common::jekt_sign::FIELD_SEP;
22
23/// The signature's domain separator.
24const REMOTE_OP_DOMAIN: &str = "amx-remote-op-v1";
25
26/// The envelope version this build sends and accepts.
27pub const REMOTE_OP_VERSION: u32 = 1;
28
29/// How far from the receiver's clock a request's `ts` may be, in seconds.
30pub const REMOTE_OP_MAX_SKEW_SECS: i64 = 60;
31
32/// The longest `op` name, `nonce` and `reason`, and the largest serialized
33/// `params`, a receiver reads.
34pub const MAX_OP_LEN: usize = 64;
35pub const MAX_NONCE_LEN: usize = 64;
36pub const MAX_REASON_LEN: usize = 500;
37pub const MAX_PARAMS_BYTES: usize = 16 * 1024;
38
39/// The `audience` of a request for the LAN peer whose `lan_key` is `lan_key`: a label of the
40/// key that peer advertises, so a request signed for one machine fails on another. The key is
41/// readable by anything on the LAN, so this binds a request to a machine and proves nothing:
42/// the signature is what proves the sender.
43pub fn lan_audience(lan_key: &str) -> String {
44    use sha2::{Digest, Sha256};
45    let digest = Sha256::digest(format!("amx-remote-op-audience{FIELD_SEP}{lan_key}").as_bytes());
46    let hex: String = digest.iter().take(8).map(|b| format!("{b:02x}")).collect();
47    format!("lan-{hex}")
48}
49
50/// Who asks: the agent, and the install it runs in.
51#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
52pub struct Requester {
53    pub agent_uid: String,
54    pub slug: String,
55    /// The requesting install's id, as its certificate names it. Empty when the
56    /// sender has none to give; a receiver that holds the agent's certificate
57    /// checks the two agree.
58    #[serde(default)]
59    pub instance_id: String,
60}
61
62/// One request.
63#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
64pub struct RemoteOp {
65    pub v: u32,
66    /// From the table in the spec's §4.3: `app.version`, `identity.switch`, ...
67    pub op: String,
68    #[serde(default)]
69    pub params: Value,
70    pub requester: Requester,
71    /// The one machine this request is valid on.
72    pub audience: String,
73    pub ts: i64,
74    /// Unique per request: a retry carries the same one and gets the first answer.
75    pub nonce: String,
76    /// The requester's own words, shown as theirs and never acted on.
77    #[serde(default)]
78    pub reason: String,
79}
80
81/// A request and its signature.
82#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
83pub struct SignedRemoteOp {
84    #[serde(flatten)]
85    pub op: RemoteOp,
86    pub sig: String,
87}
88
89/// How a request ended.
90#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
91#[serde(rename_all = "snake_case")]
92pub enum OpStatus {
93    Done,
94    Queued,
95    /// A countdown with the person's veto is running on the target; the final
96    /// outcome follows as a second result.
97    PendingVeto,
98    Refused,
99    Failed,
100}
101
102/// The answer to one request.
103#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
104pub struct RemoteOpResult {
105    pub status: OpStatus,
106    #[serde(default)]
107    pub result: Value,
108    /// The receiving machine's audit row for this request.
109    #[serde(default)]
110    pub audit_id: String,
111    #[serde(default, skip_serializing_if = "Option::is_none")]
112    pub refused_reason: Option<String>,
113}
114
115impl RemoteOpResult {
116    pub fn done(result: Value) -> Self {
117        Self { status: OpStatus::Done, result, audit_id: String::new(), refused_reason: None }
118    }
119
120    pub fn refused(reason: &str) -> Self {
121        Self { status: OpStatus::Refused, result: Value::Null, audit_id: String::new(), refused_reason: Some(reason.to_string()) }
122    }
123
124    pub fn failed(error: &str) -> Self {
125        Self { status: OpStatus::Failed, result: serde_json::json!({ "error": error }), audit_id: String::new(), refused_reason: None }
126    }
127}
128
129/// `params` as one string that doesn't depend on key order or spacing, so the
130/// sender and the receiver sign and check the same bytes whatever each side's
131/// JSON library does with an object.
132fn canonical(value: &Value, out: &mut String) {
133    match value {
134        Value::Object(map) => {
135            let mut keys: Vec<&String> = map.keys().collect();
136            keys.sort();
137            out.push('{');
138            for (i, key) in keys.into_iter().enumerate() {
139                if i > 0 {
140                    out.push(',');
141                }
142                out.push_str(&Value::String(key.clone()).to_string());
143                out.push(':');
144                canonical(&map[key], out);
145            }
146            out.push('}');
147        }
148        Value::Array(items) => {
149            out.push('[');
150            for (i, item) in items.iter().enumerate() {
151                if i > 0 {
152                    out.push(',');
153                }
154                canonical(item, out);
155            }
156            out.push(']');
157        }
158        other => out.push_str(&other.to_string()),
159    }
160}
161
162/// A field that sits between separators must not hold one; the two free-text
163/// fields are length-prefixed instead.
164fn plain(field: &str) -> bool {
165    !field.contains(FIELD_SEP)
166}
167
168/// `reason` cut to what [`RemoteOp::check_shape`] takes: at most [`MAX_REASON_LEN`] bytes, on a character boundary.
169pub fn clip_reason(reason: &str) -> String {
170    let reason = reason.trim();
171    if reason.len() <= MAX_REASON_LEN {
172        return reason.to_string();
173    }
174    let mut end = MAX_REASON_LEN;
175    while !reason.is_char_boundary(end) {
176        end -= 1;
177    }
178    reason[..end].to_string()
179}
180
181impl RemoteOp {
182    /// Why this envelope can't be signed or acted on, if it can't: a field that
183    /// would blur the signed material, one that is empty or over its limit, or a
184    /// version this build doesn't speak.
185    pub fn check_shape(&self) -> Result<(), &'static str> {
186        self.check_shape_with(MAX_PARAMS_BYTES)
187    }
188
189    /// [`check_shape`](Self::check_shape) with the limit of the operation's own params: most
190    /// operations take [`MAX_PARAMS_BYTES`]; one that carries text (Global Memory) declares more.
191    pub fn check_shape_with(&self, max_params: usize) -> Result<(), &'static str> {
192        if self.v != REMOTE_OP_VERSION {
193            return Err("unsupported_version");
194        }
195        let required = [&self.op, &self.requester.agent_uid, &self.requester.slug, &self.audience, &self.nonce];
196        if required.iter().any(|f| f.is_empty()) {
197            return Err("malformed");
198        }
199        let separated = [&self.op, &self.requester.agent_uid, &self.requester.slug, &self.requester.instance_id, &self.audience, &self.nonce];
200        if !separated.iter().all(|f| plain(f)) {
201            return Err("malformed");
202        }
203        if self.op.len() > MAX_OP_LEN || self.nonce.len() > MAX_NONCE_LEN || self.reason.len() > MAX_REASON_LEN {
204            return Err("too_long");
205        }
206        let mut params = String::new();
207        canonical(&self.params, &mut params);
208        if params.len() > max_params {
209            return Err("too_long");
210        }
211        Ok(())
212    }
213
214    fn signed_material(&self) -> String {
215        let mut params = String::new();
216        canonical(&self.params, &mut params);
217        let sep = FIELD_SEP;
218        format!(
219            "{REMOTE_OP_DOMAIN}{sep}{}{sep}{}{sep}{}{sep}{}{sep}{}{sep}{}{sep}{}{sep}{}{sep}{}:{}{sep}{}:{}",
220            self.v,
221            self.op,
222            self.requester.slug,
223            self.requester.agent_uid,
224            self.requester.instance_id,
225            self.audience,
226            self.ts,
227            self.nonce,
228            self.reason.len(),
229            self.reason,
230            params.len(),
231            params,
232        )
233    }
234
235    /// Sign with the requesting agent's LAN private key (the 32-byte seed).
236    /// `None` for a key of another length or an envelope that fails
237    /// [`check_shape`](Self::check_shape).
238    pub fn sign(self, private_key: &[u8]) -> Option<SignedRemoteOp> {
239        self.sign_with(private_key, MAX_PARAMS_BYTES)
240    }
241
242    /// [`sign`](Self::sign) for an operation whose params may be up to `max_params` bytes.
243    pub fn sign_with(self, private_key: &[u8], max_params: usize) -> Option<SignedRemoteOp> {
244        self.check_shape_with(max_params).ok()?;
245        let seed: [u8; 32] = private_key.try_into().ok()?;
246        let signature = SigningKey::from_bytes(&seed).sign(self.signed_material().as_bytes());
247        Some(SignedRemoteOp { sig: BASE64.encode(signature.to_bytes()), op: self })
248    }
249}
250
251impl SignedRemoteOp {
252    /// Whether `sig` is the claimed requester's signature over this envelope,
253    /// under `public_key`. `false` for anything malformed, never a panic.
254    pub fn verify(&self, public_key: &[u8]) -> bool {
255        self.verify_with(public_key, MAX_PARAMS_BYTES)
256    }
257
258    /// [`verify`](Self::verify) for an operation whose params may be up to `max_params` bytes.
259    pub fn verify_with(&self, public_key: &[u8], max_params: usize) -> bool {
260        if self.op.check_shape_with(max_params).is_err() {
261            return false;
262        }
263        let Ok(key) = <[u8; 32]>::try_from(public_key) else { return false };
264        let Ok(key) = VerifyingKey::from_bytes(&key) else { return false };
265        let Ok(bytes) = BASE64.decode(&self.sig) else { return false };
266        let Ok(bytes) = <[u8; 64]>::try_from(bytes.as_slice()) else { return false };
267        key.verify_strict(self.op.signed_material().as_bytes(), &Signature::from_bytes(&bytes)).is_ok()
268    }
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274    use agentmux_common::jekt_sign::generate_lan_keypair;
275    use serde_json::json;
276
277    fn op() -> RemoteOp {
278        RemoteOp {
279            v: REMOTE_OP_VERSION,
280            op: "app.version".into(),
281            params: json!({ "b": 1, "a": [true, "x"] }),
282            requester: Requester { agent_uid: "uid-lazo".into(), slug: "lazo".into(), instance_id: "inst-1".into() },
283            audience: "lan-aaaa".into(),
284            ts: 1_790_000_000,
285            nonce: "n-1".into(),
286            reason: "checking the version".into(),
287        }
288    }
289
290    fn keys() -> ([u8; 32], [u8; 32]) {
291        generate_lan_keypair([7u8; 32])
292    }
293
294    #[test]
295    fn a_signed_request_verifies_under_the_signers_key_only() {
296        let (public, private) = keys();
297        let signed = op().sign(&private).unwrap();
298        assert!(signed.verify(&public));
299        let (other_public, _) = generate_lan_keypair([8u8; 32]);
300        assert!(!signed.verify(&other_public), "another agent's key");
301    }
302
303    #[test]
304    fn every_field_the_receiver_acts_on_is_covered() {
305        let (public, private) = keys();
306        let signed = op().sign(&private).unwrap();
307        let tamper: Vec<(&str, Box<dyn Fn(&mut RemoteOp)>)> = vec![
308            ("op", Box::new(|o| o.op = "app.health".into())),
309            ("params", Box::new(|o| o.params = json!({ "a": [true, "y"], "b": 1 }))),
310            ("slug", Box::new(|o| o.requester.slug = "manoz".into())),
311            ("uid", Box::new(|o| o.requester.agent_uid = "uid-x".into())),
312            ("install", Box::new(|o| o.requester.instance_id = "inst-2".into())),
313            ("audience", Box::new(|o| o.audience = "lan-bbbb".into())),
314            ("ts", Box::new(|o| o.ts += 1)),
315            ("nonce", Box::new(|o| o.nonce = "n-2".into())),
316            ("reason", Box::new(|o| o.reason = "other".into())),
317        ];
318        for (name, change) in tamper {
319            let mut forged = signed.clone();
320            change(&mut forged.op);
321            assert!(!forged.verify(&public), "a changed {name} still verified");
322        }
323    }
324
325    #[test]
326    fn key_order_and_spacing_of_params_do_not_matter() {
327        let (public, private) = keys();
328        let signed = op().sign(&private).unwrap();
329        let mut reordered = signed.clone();
330        reordered.op.params = serde_json::from_str(r#"{ "a" : [ true , "x" ] , "b" : 1 }"#).unwrap();
331        assert!(reordered.verify(&public));
332    }
333
334    #[test]
335    fn a_jekt_signature_never_verifies_as_a_remote_op() {
336        let (public, private) = keys();
337        let o = op();
338        // The jekt signer over the same fields, as a jekt's material would lay them out.
339        let jekt = agentmux_common::jekt_sign::sign_lan_jekt(&private, &o.nonce, &o.requester.slug, &o.audience, o.ts, &o.op).unwrap();
340        let forged = SignedRemoteOp { op: o, sig: jekt };
341        assert!(!forged.verify(&public));
342    }
343
344    #[test]
345    fn a_separator_in_a_field_is_refused_not_blurred() {
346        let (_, private) = keys();
347        let mut o = op();
348        o.requester.slug = format!("la{FIELD_SEP}zo");
349        assert!(o.sign(&private).is_none());
350        let mut o = op();
351        o.v = 2;
352        assert_eq!(o.check_shape(), Err("unsupported_version"));
353        let mut o = op();
354        o.nonce = String::new();
355        assert_eq!(o.check_shape(), Err("malformed"));
356    }
357
358    #[test]
359    fn free_text_cannot_move_a_boundary() {
360        // reason "ab" + params "c" must not sign the same as reason "a" + params "bc".
361        let (public, private) = keys();
362        let mut a = op();
363        a.reason = "x".repeat(3);
364        let signed = a.sign(&private).unwrap();
365        let mut moved = signed.clone();
366        moved.op.reason = "xx".into();
367        moved.op.params = json!("x");
368        assert!(!moved.verify(&public));
369    }
370
371    #[test]
372    fn oversize_and_malformed_inputs_are_not_verified() {
373        let (public, private) = keys();
374        let signed = op().sign(&private).unwrap();
375        assert!(!signed.verify(&[1, 2, 3]));
376        let mut bad = signed.clone();
377        bad.sig = "not base64!!".into();
378        assert!(!bad.verify(&public));
379        let mut big = op();
380        big.params = json!({ "k": "z".repeat(MAX_PARAMS_BYTES) });
381        assert_eq!(big.check_shape(), Err("too_long"));
382        assert!(op().sign(&private[..31]).is_none());
383    }
384
385    #[test]
386    fn an_operation_with_its_own_limit_signs_and_verifies_under_it_and_only_it() {
387        let (public, private) = generate_lan_keypair([3; 32]);
388        let mut big = op();
389        big.params = json!({ "text": "y".repeat(MAX_PARAMS_BYTES * 4) });
390        assert_eq!(big.check_shape(), Err("too_long"));
391        assert_eq!(big.check_shape_with(MAX_PARAMS_BYTES * 8), Ok(()));
392        assert!(big.clone().sign(&private).is_none(), "the default limit still applies to sign");
393
394        let signed = big.clone().sign_with(&private, MAX_PARAMS_BYTES * 8).unwrap();
395        assert!(signed.verify_with(&public, MAX_PARAMS_BYTES * 8));
396        assert!(!signed.verify(&public), "a receiver that does not know the larger limit refuses it");
397        assert!(!signed.verify_with(&public, MAX_PARAMS_BYTES * 2));
398        assert!(big.sign_with(&private, MAX_PARAMS_BYTES * 2).is_none());
399    }
400
401    #[test]
402    fn a_long_reason_in_any_script_is_clipped_to_a_signable_length() {
403        let (_, private) = keys();
404        for text in ["x".repeat(2000), "é".repeat(2000), "日本語".repeat(500), format!("  {}  ", "ü".repeat(MAX_REASON_LEN))] {
405            let clipped = clip_reason(&text);
406            assert!(clipped.len() <= MAX_REASON_LEN && !clipped.is_empty());
407            let mut o = op();
408            o.reason = clipped;
409            assert!(o.sign(&private).is_some());
410        }
411        assert_eq!(clip_reason("  short  "), "short");
412    }
413
414    #[test]
415    fn a_lan_audience_names_one_key() {
416        assert_eq!(lan_audience("key-a"), lan_audience("key-a"));
417        assert_ne!(lan_audience("key-a"), lan_audience("key-b"));
418        assert!(lan_audience("key-a").starts_with("lan-") && lan_audience("key-a").len() == 20);
419    }
420
421    #[test]
422    fn the_wire_shape_round_trips() {
423        let (public, private) = keys();
424        let signed = op().sign(&private).unwrap();
425        let wire = serde_json::to_string(&signed).unwrap();
426        let back: SignedRemoteOp = serde_json::from_str(&wire).unwrap();
427        assert!(back.verify(&public));
428        assert_eq!(back, signed);
429    }
430}