Skip to main content

agentmux_srv_core/backend/agent_move/
signed.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The two signed statements of a move (SPEC_MOVE_AN_AGENT_TO_ANOTHER_COMPUTER section 6): what the destination says about
5//! itself before anything is sealed, and what the source offers. A LAN operation's answer carries no signature of its own,
6//! so each statement is signed by the install that makes it, under a domain tag of its own, and checked by the other end
7//! against the install key it already trusts.
8//!
9//! - [`PreflightAnswer`]: signed by the **destination**. It names the destination install, the install it answers (the
10//!   audience), the nonce the asker chose, the destination's box key and a facts string. The asker seals the move's key
11//!   only to a box key that verifies, for this nonce, under the destination's trusted install key.
12//! - [`SignedOffer`]: signed by the **source**. The summary names the move, the attempt, the manifest hash, the size and
13//!   chunk count, the agent, who asked, what is carried and the sealed content key, for one destination. The consent text
14//!   and the verification of the archive are built from this summary, never from anything the offer carries outside it.
15
16use base64::Engine;
17use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
18use serde::{Deserialize, Serialize};
19
20const PREFLIGHT_DOMAIN: &str = "amx-agent-move-preflight-v1";
21const OFFER_DOMAIN: &str = "amx-agent-move-offer-v1";
22pub(super) const FIELD_SEP: char = '\u{1}';
23const STD: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD;
24
25/// Why a statement was not accepted.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub enum SignedError {
28    /// The signature is missing, malformed or not by the expected install key.
29    BadSignature,
30    /// The statement is for another install than this one.
31    WrongAudience,
32    /// The statement answers another request than this one.
33    WrongNonce,
34    /// The statement is older than it may be, or from the future.
35    Stale,
36    /// The body does not read as the statement it should be.
37    Malformed(&'static str),
38}
39
40impl std::fmt::Display for SignedError {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        match self {
43            Self::BadSignature => write!(f, "the signature does not verify under the install's key"),
44            Self::WrongAudience => write!(f, "the statement is for another computer"),
45            Self::WrongNonce => write!(f, "the statement answers another request"),
46            Self::Stale => write!(f, "the statement is too old or from the future"),
47            Self::Malformed(why) => write!(f, "the statement is malformed: {why}"),
48        }
49    }
50}
51
52impl std::error::Error for SignedError {}
53
54pub(super) fn sign(seed: &[u8; 32], domain: &str, material: &str) -> String {
55    let key = SigningKey::from_bytes(seed);
56    STD.encode(key.sign(format!("{domain}{FIELD_SEP}{material}").as_bytes()).to_bytes())
57}
58
59pub(super) fn verify(public: &[u8; 32], domain: &str, material: &str, sig_b64: &str) -> Result<(), SignedError> {
60    let key = VerifyingKey::from_bytes(public).map_err(|_| SignedError::BadSignature)?;
61    let bytes: [u8; 64] = STD.decode(sig_b64).ok().and_then(|b| b.try_into().ok()).ok_or(SignedError::BadSignature)?;
62    key.verify(format!("{domain}{FIELD_SEP}{material}").as_bytes(), &Signature::from_bytes(&bytes)).map_err(|_| SignedError::BadSignature)
63}
64
65pub(super) fn clean(field: &str) -> bool {
66    !field.is_empty() && !field.contains(FIELD_SEP)
67}
68
69/// The destination's answer to a preflight.
70#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
71pub struct PreflightAnswer {
72    pub dest_install: String,
73    /// The install that asked.
74    pub audience: String,
75    /// The asker's own random value, which a copy of an older answer cannot have.
76    pub nonce: String,
77    /// The destination's X25519 box key, standard base64: where the move's content key is sealed.
78    pub box_key: String,
79    /// What the asker is told about this computer (version, capacity bands, harness, sign-in), as JSON text.
80    pub facts: String,
81    pub sig: String,
82}
83
84impl PreflightAnswer {
85    fn material(&self) -> String {
86        let s = FIELD_SEP;
87        format!("{}{s}{}{s}{}{s}{}{s}{}", self.dest_install, self.audience, self.nonce, self.box_key, self.facts)
88    }
89
90    pub fn sign(seed: &[u8; 32], dest_install: &str, audience: &str, nonce: &str, box_key: &[u8; 32], facts: &str) -> Result<Self, SignedError> {
91        if !clean(dest_install) || !clean(audience) || !clean(nonce) || facts.contains(FIELD_SEP) {
92            return Err(SignedError::Malformed("a field is empty or holds a separator"));
93        }
94        let mut answer = Self { dest_install: dest_install.to_string(), audience: audience.to_string(), nonce: nonce.to_string(), box_key: STD.encode(box_key), facts: facts.to_string(), sig: String::new() };
95        answer.sig = sign(seed, PREFLIGHT_DOMAIN, &answer.material());
96        Ok(answer)
97    }
98
99    /// The box key, when this answer is the destination's `dest_public` for this asker and this nonce.
100    pub fn verify(&self, dest_public: &[u8; 32], my_install: &str, nonce: &str) -> Result<[u8; 32], SignedError> {
101        verify(dest_public, PREFLIGHT_DOMAIN, &self.material(), &self.sig)?;
102        if self.audience != my_install {
103            return Err(SignedError::WrongAudience);
104        }
105        if self.nonce != nonce {
106            return Err(SignedError::WrongNonce);
107        }
108        STD.decode(&self.box_key).ok().and_then(|k| k.try_into().ok()).ok_or(SignedError::Malformed("the box key is not 32 bytes"))
109    }
110}
111
112/// The paid model route an agent runs on at the source, as the signed offer names it: the destination shows the person what
113/// it would bill and keeps the route only when the archive names exactly this one.
114#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
115pub struct RouteRef {
116    pub harness: String,
117    pub route: String,
118    pub model: String,
119}
120
121/// What an offer says, signed by the source install.
122#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
123pub struct OfferSummary {
124    pub move_id: String,
125    pub attempt: u32,
126    /// The hash of the manifest inside the archive; the archive's own manifest must hash to it.
127    pub manifest_hash: String,
128    /// The size of the archive file, and the chunks it is sent in.
129    pub total_bytes: u64,
130    pub total_chunks: u64,
131    pub agent_uid: String,
132    pub agent_name: String,
133    /// `native` or `container`: where the agent would run.
134    pub runtime: String,
135    /// Who asked for the move, as the source authenticated it, and whether that was an agent or a person.
136    pub requester: String,
137    pub asker_kind: String,
138    /// The agent whose key signs this move's operations at the destination (`chunk`, `status`, `abort`): the offer is
139    /// taken only from that agent, so another agent of the same install cannot file it as its own.
140    pub operator: String,
141    /// What is carried, one short line each (shown to the person deciding).
142    pub contents: Vec<String>,
143    pub source_install: String,
144    pub dest_install: String,
145    pub issued_at_ms: i64,
146    /// The move's content key, sealed to the destination's box key.
147    pub sealed_key: String,
148    /// The paid model route the agent runs on, when it has one.
149    #[serde(default, skip_serializing_if = "Option::is_none")]
150    pub route: Option<RouteRef>,
151    /// The harness (its provider id) the agent runs on: the destination checks its CLI is, or can be, there before it asks the person.
152    #[serde(default, skip_serializing_if = "String::is_empty")]
153    pub harness: String,
154}
155
156/// An [`OfferSummary`] as it travels: the exact text that was signed, and its signature.
157#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
158pub struct SignedOffer {
159    pub summary: String,
160    pub sig: String,
161}
162
163impl SignedOffer {
164    pub fn sign(seed: &[u8; 32], summary: &OfferSummary) -> Result<Self, SignedError> {
165        let text = serde_json::to_string(summary).map_err(|_| SignedError::Malformed("the summary does not serialize"))?;
166        Ok(Self { sig: sign(seed, OFFER_DOMAIN, &text), summary: text })
167    }
168
169    /// The summary, when it was signed by `source_public`, is for `my_install` and was issued within `max_age_ms`.
170    pub fn verify(&self, source_public: &[u8; 32], my_install: &str, now_ms: i64, max_age_ms: i64) -> Result<OfferSummary, SignedError> {
171        verify(source_public, OFFER_DOMAIN, &self.summary, &self.sig)?;
172        let summary: OfferSummary = serde_json::from_str(&self.summary).map_err(|_| SignedError::Malformed("the summary does not read"))?;
173        if summary.dest_install != my_install {
174            return Err(SignedError::WrongAudience);
175        }
176        let age = now_ms - summary.issued_at_ms;
177        if age > max_age_ms || age < -60_000 {
178            return Err(SignedError::Stale);
179        }
180        if !clean(&summary.move_id) || !clean(&summary.operator) || !clean(&summary.source_install) || !clean(&summary.manifest_hash) || !clean(&summary.sealed_key) {
181            return Err(SignedError::Malformed("a field is empty or holds a separator"));
182        }
183        Ok(summary)
184    }
185}
186
187#[cfg(test)]
188#[path = "signed_tests.rs"]
189mod tests;