agentmux_srv_core/backend/agent_move/
handover.rs1use serde::{Deserialize, Serialize};
12
13use super::signed::{clean, sign, verify, SignedError, FIELD_SEP};
14
15const DOMAIN: &str = "amx-agent-handover-v1";
16pub const LIFETIME_SECS: i64 = 7 * 24 * 60 * 60;
18
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
20pub struct HandoverCertificate {
21 pub name: String,
23 pub uid: String,
24 pub old_fp: String,
26 pub new_key: String,
28 pub source_install: String,
29 pub dest_install: String,
30 pub move_id: String,
31 pub issued_at: i64,
32 pub expires_at: i64,
33 pub sig: String,
34}
35
36impl HandoverCertificate {
37 fn material(&self) -> String {
38 let s = FIELD_SEP;
39 format!(
40 "{}{s}{}{s}{}{s}{}{s}{}{s}{}{s}{}{s}{}{s}{}",
41 self.name, self.uid, self.old_fp, self.new_key, self.source_install, self.dest_install, self.move_id, self.issued_at, self.expires_at
42 )
43 }
44
45 #[allow(clippy::too_many_arguments)]
47 pub fn sign(seed: &[u8; 32], name: &str, uid: &str, old_fp: &str, new_key: &str, (source_install, dest_install): (&str, &str), move_id: &str, now: i64) -> Result<Self, SignedError> {
48 let name = name.to_lowercase();
49 if ![name.as_str(), uid, old_fp, new_key, source_install, dest_install, move_id].iter().all(|f| clean(f)) {
50 return Err(SignedError::Malformed("a field is empty or holds a separator"));
51 }
52 let mut cert = Self {
53 name,
54 uid: uid.to_string(),
55 old_fp: old_fp.to_string(),
56 new_key: new_key.to_string(),
57 source_install: source_install.to_string(),
58 dest_install: dest_install.to_string(),
59 move_id: move_id.to_string(),
60 issued_at: now,
61 expires_at: now + LIFETIME_SECS,
62 sig: String::new(),
63 };
64 cert.sig = sign(seed, DOMAIN, &cert.material());
65 Ok(cert)
66 }
67
68 pub fn verify(&self, source_public: &[u8; 32], now: i64) -> Result<(), SignedError> {
70 verify(source_public, DOMAIN, &self.material(), &self.sig)?;
71 if now >= self.expires_at || self.issued_at > now + 60 || self.expires_at - self.issued_at > LIFETIME_SECS {
72 return Err(SignedError::Stale);
73 }
74 Ok(())
75 }
76}
77
78#[cfg(test)]
79#[path = "handover_tests.rs"]
80mod tests;