Skip to main content

agentmux_srv_core/backend/remote_panes/
key.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! This computer's signing key for one host it paired with to watch its agents
5//! (docs/specs/SPEC_REMOTE_PANES_WATCH_AND_DRIVE_AN_AGENT_ON_ANOTHER_COMPUTER_2026_11_20.md §3, §5.3).
6//!
7//! The host pins the public half at pairing and checks every feed open, history page, attachment and send against
8//! it (`viewer::signing`). It is an ECDSA P-256 key, the shape a phone's is, made here at pairing, one per host: a
9//! pairing forgotten here and made again gets a new one. The private half is kept in the secret store (the OS
10//! keychain) beside the pairing's token, never in a file.
11
12use base64::Engine as _;
13use ring::rand::SystemRandom;
14use ring::signature::{EcdsaKeyPair, KeyPair, ECDSA_P256_SHA256_ASN1_SIGNING};
15
16use crate::backend::viewer::signing;
17
18/// A computer's key for one host.
19pub struct ComputerKey {
20    pair: EcdsaKeyPair,
21    pkcs8: String,
22}
23
24fn b64(bytes: &[u8]) -> String {
25    base64::engine::general_purpose::STANDARD.encode(bytes)
26}
27
28impl ComputerKey {
29    /// A new key.
30    pub fn generate() -> Result<Self, String> {
31        let pkcs8 = EcdsaKeyPair::generate_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING, &SystemRandom::new())
32            .map_err(|_| "this computer could not make a signing key".to_string())?;
33        Self::from_pkcs8(&b64(pkcs8.as_ref()))
34    }
35
36    /// The key kept as `pkcs8` (standard base64 of its PKCS#8 document).
37    pub fn from_pkcs8(pkcs8: &str) -> Result<Self, String> {
38        let bad = || "the signing key kept for this pairing is unreadable: forget the pairing and pair again".to_string();
39        let der = base64::engine::general_purpose::STANDARD.decode(pkcs8.trim()).map_err(|_| bad())?;
40        let pair = EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING, &der, &SystemRandom::new()).map_err(|_| bad())?;
41        Ok(Self { pair, pkcs8: pkcs8.trim().to_string() })
42    }
43
44    /// What is kept in the secret store.
45    pub fn pkcs8(&self) -> &str {
46        &self.pkcs8
47    }
48
49    /// The public half as the host's pairing route takes it (`device_key`): base64 of the 65-byte point.
50    pub fn public(&self) -> String {
51        b64(self.pair.public_key().as_ref())
52    }
53
54    fn sign(&self, text: &str) -> Result<String, String> {
55        let sig = self.pair.sign(&SystemRandom::new(), text.as_bytes()).map_err(|_| "signing failed".to_string())?;
56        Ok(b64(sig.as_ref()))
57    }
58
59    /// The headers of a read (a feed open, a history page, an attachment) of `path_and_query` from the host whose
60    /// certificate is `host_fingerprint`, signed now with a fresh nonce (`signing::open_signed_text`).
61    pub fn read_headers(&self, path_and_query: &str, host_fingerprint: &str) -> Result<Vec<(&'static str, String)>, String> {
62        let (now, nonce) = (agentmux_common::time::now_ms(), uuid::Uuid::new_v4().simple().to_string());
63        let sig = self.sign(&signing::open_signed_text("GET", path_and_query, now, &nonce, host_fingerprint))?;
64        Ok(vec![(signing::TIMESTAMP_HEADER, now.to_string()), (signing::NONCE_HEADER, nonce), (signing::SIGNATURE_HEADER, sig)])
65    }
66
67    /// The headers of a `method` request to `path` carrying `body`, signed now (`signing::signed_text`).
68    pub fn write_headers(&self, method: &str, path: &str, body: &[u8]) -> Result<Vec<(&'static str, String)>, String> {
69        let now = agentmux_common::time::now_ms();
70        let sig = self.sign(&signing::signed_text(method, path, now, body))?;
71        Ok(vec![(signing::TIMESTAMP_HEADER, now.to_string()), (signing::SIGNATURE_HEADER, sig)])
72    }
73}
74
75#[cfg(test)]
76mod tests {
77    use super::*;
78    use crate::backend::viewer::signing::DeviceKey;
79
80    fn header<'a>(headers: &'a [(&'static str, String)], name: &str) -> &'a str {
81        headers.iter().find(|(n, _)| *n == name).map(|(_, v)| v.as_str()).unwrap()
82    }
83
84    #[test]
85    fn a_kept_key_signs_reads_and_writes_the_host_verifies() {
86        let made = ComputerKey::generate().unwrap();
87        let key = ComputerKey::from_pkcs8(made.pkcs8()).unwrap();
88        assert_eq!(key.public(), made.public(), "the kept key is the same key");
89        let pinned = DeviceKey::parse(&made.public()).unwrap();
90        assert!(matches!(pinned, DeviceKey::P256(_)));
91
92        let path = "/agentmux/viewer/agents/demo/history?before=g:3&limit=200";
93        let read = key.read_headers(path, "aa11").unwrap();
94        let (ts, nonce) = (header(&read, signing::TIMESTAMP_HEADER).parse().unwrap(), header(&read, signing::NONCE_HEADER));
95        assert!(signing::nonce_shape_ok(nonce));
96        let text = signing::open_signed_text("GET", path, ts, nonce, "aa11");
97        assert!(pinned.verifies(text.as_bytes(), header(&read, signing::SIGNATURE_HEADER)));
98        let other_host = signing::open_signed_text("GET", path, ts, nonce, "bb22");
99        assert!(!pinned.verifies(other_host.as_bytes(), header(&read, signing::SIGNATURE_HEADER)), "bound to the host");
100        assert_ne!(nonce, header(&key.read_headers(path, "aa11").unwrap(), signing::NONCE_HEADER), "a fresh nonce each time");
101
102        let body = br#"{"message":"hi","message_id":"m1"}"#;
103        let write = key.write_headers("POST", "/agentmux/viewer/agents/demo/input", body).unwrap();
104        let ts = header(&write, signing::TIMESTAMP_HEADER).parse().unwrap();
105        let text = signing::signed_text("POST", "/agentmux/viewer/agents/demo/input", ts, body);
106        assert!(pinned.verifies(text.as_bytes(), header(&write, signing::SIGNATURE_HEADER)));
107    }
108
109    #[test]
110    fn an_unreadable_kept_key_says_to_pair_again() {
111        for kept in ["not base64!".to_string(), b64(b"not a key")] {
112            assert!(ComputerKey::from_pkcs8(&kept).err().is_some_and(|e| e.contains("pair again")), "{kept}");
113        }
114    }
115}