agentmux_srv_core/backend/agent_move/
signed.rs1use 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#[derive(Debug, Clone, PartialEq, Eq)]
27pub enum SignedError {
28 BadSignature,
30 WrongAudience,
32 WrongNonce,
34 Stale,
36 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
71pub struct PreflightAnswer {
72 pub dest_install: String,
73 pub audience: String,
75 pub nonce: String,
77 pub box_key: String,
79 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 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#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
123pub struct OfferSummary {
124 pub move_id: String,
125 pub attempt: u32,
126 pub manifest_hash: String,
128 pub total_bytes: u64,
130 pub total_chunks: u64,
131 pub agent_uid: String,
132 pub agent_name: String,
133 pub runtime: String,
135 pub requester: String,
137 pub asker_kind: String,
138 pub operator: String,
141 pub contents: Vec<String>,
143 pub source_install: String,
144 pub dest_install: String,
145 pub issued_at_ms: i64,
146 pub sealed_key: String,
148 #[serde(default, skip_serializing_if = "Option::is_none")]
150 pub route: Option<RouteRef>,
151 #[serde(default, skip_serializing_if = "String::is_empty")]
153 pub harness: String,
154}
155
156#[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 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;