agentmux_srv_core/backend/viewer/
signing.rs1use base64::Engine as _;
26use sha2::{Digest, Sha256};
27
28pub const SIG_VERSION: &str = "amxv-sig-v1";
30pub const TIMESTAMP_HEADER: &str = "x-amxv-timestamp";
32pub const SIGNATURE_HEADER: &str = "x-amxv-signature";
34pub const MAX_SKEW_MS: i64 = 60_000;
36
37#[derive(Debug, Clone, PartialEq, Eq)]
39pub enum DeviceKey {
40 P256(Vec<u8>),
42 Ed25519([u8; 32]),
43}
44
45impl DeviceKey {
46 pub fn parse(b64: &str) -> Result<Self, &'static str> {
49 const SHAPE: &str = "device_key must be standard base64 of a 65-byte P-256 point or a 32-byte Ed25519 key";
50 let bytes = base64::engine::general_purpose::STANDARD.decode(b64.trim()).map_err(|_| SHAPE)?;
51 match bytes.len() {
52 65 if bytes[0] == 0x04 => Ok(Self::P256(bytes)),
55 32 => {
56 let key: [u8; 32] = bytes.try_into().map_err(|_| SHAPE)?;
57 ed25519_dalek::VerifyingKey::from_bytes(&key).map_err(|_| "device_key is not an Ed25519 key")?;
58 Ok(Self::Ed25519(key))
59 }
60 _ => Err(SHAPE),
61 }
62 }
63
64 pub fn verifies(&self, message: &[u8], signature_b64: &str) -> bool {
66 let Ok(sig) = base64::engine::general_purpose::STANDARD.decode(signature_b64.trim()) else {
67 return false;
68 };
69 match self {
70 Self::P256(point) => ring::signature::UnparsedPublicKey::new(&ring::signature::ECDSA_P256_SHA256_ASN1, point)
71 .verify(message, &sig)
72 .is_ok(),
73 Self::Ed25519(key) => {
74 let Ok(key) = ed25519_dalek::VerifyingKey::from_bytes(key) else {
75 return false;
76 };
77 let Ok(sig) = ed25519_dalek::Signature::from_slice(&sig) else {
78 return false;
79 };
80 key.verify_strict(message, &sig).is_ok()
81 }
82 }
83 }
84}
85
86pub fn signed_text(method: &str, path: &str, timestamp_ms: i64, body: &[u8]) -> String {
88 let body_hash = hex::encode(Sha256::digest(body));
89 format!("{SIG_VERSION}\n{method}\n{path}\n{timestamp_ms}\n{body_hash}")
90}
91
92pub fn fresh(timestamp_ms: i64, now_ms: i64) -> bool {
94 (now_ms - timestamp_ms).abs() <= MAX_SKEW_MS
95}
96
97pub const OPEN_SIG_VERSION: &str = "amxv-sig-v2";
112pub const NONCE_HEADER: &str = "x-amxv-nonce";
114pub const NONCE_MEMORY_MS: i64 = 3 * 60_000;
117pub const MAX_NONCES: usize = 8192;
119
120pub fn open_signed_text(method: &str, path: &str, timestamp_ms: i64, nonce: &str, host_fingerprint: &str) -> String {
122 format!("{OPEN_SIG_VERSION}\n{method}\n{path}\n{timestamp_ms}\n{nonce}\n{host_fingerprint}")
123}
124
125pub fn nonce_shape_ok(nonce: &str) -> bool {
127 (16..=128).contains(&nonce.len()) && nonce.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
128}
129
130#[derive(Debug, Default)]
132pub struct NonceLog {
133 seen: std::collections::HashMap<String, i64>,
135}
136
137impl NonceLog {
138 pub fn first_use(&mut self, device: &str, nonce: &str, now_ms: i64) -> bool {
141 self.seen.retain(|_, forget_at| *forget_at > now_ms);
142 let key = format!("{device}\n{nonce}");
143 if self.seen.contains_key(&key) || self.seen.len() >= MAX_NONCES {
144 return false;
145 }
146 self.seen.insert(key, now_ms + NONCE_MEMORY_MS);
147 true
148 }
149}
150
151#[cfg(test)]
152mod tests {
153 use super::*;
154 use ring::rand::SystemRandom;
155 use ring::signature::{EcdsaKeyPair, KeyPair, ECDSA_P256_SHA256_ASN1_SIGNING};
156
157 fn b64(bytes: &[u8]) -> String {
158 base64::engine::general_purpose::STANDARD.encode(bytes)
159 }
160
161 fn p256() -> EcdsaKeyPair {
162 let rng = SystemRandom::new();
163 let pkcs8 = EcdsaKeyPair::generate_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING, &rng).unwrap();
164 EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING, pkcs8.as_ref(), &rng).unwrap()
165 }
166
167 #[test]
168 fn a_p256_signature_over_the_signed_text_verifies() {
169 let pair = p256();
170 let key = DeviceKey::parse(&b64(pair.public_key().as_ref())).unwrap();
171 assert!(matches!(key, DeviceKey::P256(_)));
172 let text = signed_text("POST", "/agentmux/viewer/agents/Clamk/input", 1_791_963_024_123, br#"{"message":"hi"}"#);
173 let sig = pair.sign(&SystemRandom::new(), text.as_bytes()).unwrap();
174 assert!(key.verifies(text.as_bytes(), &b64(sig.as_ref())));
175 let other = signed_text("POST", "/agentmux/viewer/agents/Clamk/input", 1_791_963_024_123, br#"{"message":"rm"}"#);
177 assert!(!key.verifies(other.as_bytes(), &b64(sig.as_ref())));
178 let stranger = DeviceKey::parse(&b64(p256().public_key().as_ref())).unwrap();
180 assert!(!stranger.verifies(text.as_bytes(), &b64(sig.as_ref())));
181 assert!(!key.verifies(text.as_bytes(), "not base64!"));
182 }
183
184 fn random_nonce() -> String {
186 uuid::Uuid::new_v4().simple().to_string()
187 }
188
189 #[test]
190 fn a_nonce_opens_once_per_device_until_it_is_forgotten() {
191 let mut log = NonceLog::default();
192 let nonce = random_nonce();
193 assert!(log.first_use("d1", &nonce, 1_000));
194 assert!(!log.first_use("d1", &nonce, 2_000), "a replay");
195 assert!(log.first_use("d2", &nonce, 2_000), "another device's nonce is its own");
196 assert!(log.first_use("d1", &nonce, 1_000 + NONCE_MEMORY_MS + 1), "forgotten once stale anyway");
197 let (short, spaced) = (nonce[..8].to_string(), format!("{} {}", &nonce[..10], &nonce[10..]));
198 assert!(nonce_shape_ok(&nonce) && !nonce_shape_ok(&short) && !nonce_shape_ok(&spaced));
199 }
200
201 #[test]
202 fn a_full_nonce_log_refuses_instead_of_forgetting() {
203 let mut log = NonceLog::default();
204 for _ in 0..MAX_NONCES {
205 assert!(log.first_use("d", &random_nonce(), 1));
206 }
207 assert!(!log.first_use("d", &random_nonce(), 2));
208 }
209
210 #[test]
211 fn an_open_signature_is_bound_to_the_host_and_the_nonce() {
212 let pair = p256();
213 let key = DeviceKey::parse(&b64(pair.public_key().as_ref())).unwrap();
214 let nonce = random_nonce();
215 let text = open_signed_text("GET", "/agentmux/viewer/agents/a/feed", 5, &nonce, "aa11");
216 let sig = b64(pair.sign(&SystemRandom::new(), text.as_bytes()).unwrap().as_ref());
217 assert!(key.verifies(text.as_bytes(), &sig));
218 let other_host = open_signed_text("GET", "/agentmux/viewer/agents/a/feed", 5, &nonce, "bb22");
219 assert!(!key.verifies(other_host.as_bytes(), &sig));
220 let other_nonce = open_signed_text("GET", "/agentmux/viewer/agents/a/feed", 5, &random_nonce(), "aa11");
221 assert!(!key.verifies(other_nonce.as_bytes(), &sig));
222 }
223
224 #[test]
225 fn an_ed25519_signature_verifies() {
226 let signing = ed25519_dalek::SigningKey::from_bytes(&[7u8; 32]);
227 let key = DeviceKey::parse(&b64(signing.verifying_key().as_bytes())).unwrap();
228 let text = signed_text("POST", "/p", 1, b"{}");
229 use ed25519_dalek::Signer as _;
230 let sig = signing.sign(text.as_bytes());
231 assert!(key.verifies(text.as_bytes(), &b64(&sig.to_bytes())));
232 assert!(!key.verifies(b"other", &b64(&sig.to_bytes())));
233 }
234
235 #[test]
236 fn keys_of_the_wrong_shape_are_refused() {
237 assert!(DeviceKey::parse("").is_err());
238 assert!(DeviceKey::parse("%%%").is_err());
239 assert!(DeviceKey::parse(&b64(&[4u8; 64])).is_err(), "64 bytes is neither shape");
240 let mut compressed = vec![0x02];
241 compressed.extend([1u8; 32]);
242 assert!(DeviceKey::parse(&b64(&compressed)).is_err(), "compressed points are not accepted");
243 let mut off = vec![0x04];
245 off.extend([1u8; 64]);
246 let off = DeviceKey::parse(&b64(&off)).unwrap();
247 let pair = p256();
248 let sig = pair.sign(&SystemRandom::new(), b"x").unwrap();
249 assert!(!off.verifies(b"x", &b64(sig.as_ref())));
250 }
251
252 #[test]
253 fn the_signed_text_is_five_lines_with_the_body_hash_last() {
254 let text = signed_text("POST", "/agentmux/viewer/agents/A%20B/input", 42, b"");
255 assert_eq!(
256 text,
257 "amxv-sig-v1\nPOST\n/agentmux/viewer/agents/A%20B/input\n42\n\
258 e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
259 );
260 }
261
262 #[test]
263 fn a_timestamp_is_fresh_within_a_minute_either_way() {
264 assert!(fresh(100_000, 160_000));
265 assert!(fresh(160_000, 100_000));
266 assert!(!fresh(100_000, 160_001));
267 assert!(!fresh(160_001, 100_000));
268 }
269}