Skip to main content

m4a_agent/
identity.rs

1//! The session identity: one session = one identity = one nick = one credential set.
2//!
3//! The identity is an ed25519 key pair the client generates itself. The private seed is kept in
4//! the [`KeyVault`] and never leaves it except to sign; the agent behind the client is never given
5//! it. A session is bound to ONE tier and ONE server: asking the store for the same session id
6//! against a different server is an error, not a quiet second identity.
7
8use std::sync::Arc;
9
10use ed25519_dalek::{Signer, SigningKey};
11use m4a_seam::keyproof;
12use serde::{Deserialize, Serialize};
13use zeroize::Zeroizing;
14
15use crate::backend::BackendKind;
16use crate::error::{AgentError, Result};
17use crate::vault::{random_bytes, KeyVault};
18
19/// What is public and persistent about an identity. (The private seed is not in here.)
20#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
21pub struct SessionIdentity {
22    pub session_id: String,
23    pub tier: BackendKind,
24    /// The server this identity belongs to (normalized base URL). Part of the binding.
25    pub server_ref: String,
26    pub key_id: String,
27    /// Public key, base64url.
28    pub public_key: String,
29    /// Learned when the operator's invite is redeemed; the nick is the operator's choice.
30    pub nick: Option<String>,
31    pub enrolled: bool,
32    /// The tier-1 (local mail node) session id of the same session, when known. The link is kept
33    /// here and only here; it is one-to-one (see [`IdentityStore::bind_local`]).
34    #[serde(default)]
35    pub local_session: Option<String>,
36}
37
38fn seed_label(sid: &str) -> String {
39    format!("identity-key/{sid}")
40}
41fn record_label(sid: &str) -> String {
42    format!("identity/{sid}")
43}
44/// Where a backend keeps the current access token of a session.
45pub fn token_label(sid: &str) -> String {
46    format!("session-token/{sid}")
47}
48
49fn valid_session_id(s: &str) -> bool {
50    !s.is_empty() && s.len() <= 64 && s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
51}
52
53impl SessionIdentity {
54    /// Signs `msg` with the identity's private key (read from the vault just for this).
55    pub fn sign(&self, vault: &dyn KeyVault, msg: &[u8]) -> Result<String> {
56        let sk = signing_key(vault, &self.session_id)?;
57        Ok(keyproof::encode(&sk.sign(msg).to_bytes()))
58    }
59
60    /// The signature for a login challenge.
61    pub fn sign_login(&self, vault: &dyn KeyVault, c: &keyproof::Challenge) -> Result<String> {
62        self.sign(vault, &keyproof::login_message(c, &self.key_id))
63    }
64
65    /// The proof that this client holds the key it is enrolling.
66    pub fn sign_enroll(&self, vault: &dyn KeyVault, audience: &str, invite: &str) -> Result<String> {
67        self.sign(vault, &keyproof::enroll_message(audience, invite, &self.public_key))
68    }
69}
70
71fn signing_key(vault: &dyn KeyVault, sid: &str) -> Result<SigningKey> {
72    let seed = vault.get(&seed_label(sid))?.ok_or_else(|| AgentError::Identity("the identity key is missing from the vault".into()))?;
73    let seed: Zeroizing<[u8; 32]> = Zeroizing::new(<[u8; 32]>::try_from(&seed[..]).map_err(|_| AgentError::Identity("the identity key has the wrong size".into()))?);
74    Ok(SigningKey::from_bytes(&seed))
75}
76
77/// Finds or creates identities. Everything is kept in the vault.
78#[derive(Clone)]
79pub struct IdentityStore {
80    vault: Arc<dyn KeyVault>,
81}
82
83impl IdentityStore {
84    pub fn new(vault: Arc<dyn KeyVault>) -> Self {
85        Self { vault }
86    }
87
88    pub fn vault(&self) -> &dyn KeyVault {
89        &*self.vault
90    }
91
92    /// The identity of `session_id` for `tier` on `server_ref`: loaded when it exists (and then it
93    /// must match tier and server), generated (new key pair, kept in the vault) when it does not.
94    pub fn resolve(&self, session_id: &str, tier: BackendKind, server_ref: &str) -> Result<SessionIdentity> {
95        if !valid_session_id(session_id) {
96            return Err(AgentError::Identity("session id must be 1-64 characters of [A-Za-z0-9._-]".into()));
97        }
98        let server_ref = server_ref.trim_end_matches('/').to_string();
99        if let Some(raw) = self.vault.get(&record_label(session_id))? {
100            let id: SessionIdentity = serde_json::from_slice(&raw).map_err(|e| AgentError::Identity(format!("stored identity: {e}")))?;
101            if id.tier != tier || id.server_ref != server_ref {
102                return Err(AgentError::Identity("this session is bound to another tier or server; use a new session id".into()));
103            }
104            signing_key(&*self.vault, session_id)?; // the key must still be there
105            return Ok(id);
106        }
107        let seed = random_bytes(32);
108        let sk = SigningKey::from_bytes(<&[u8; 32]>::try_from(&seed[..]).map_err(|_| AgentError::Identity("seed".into()))?);
109        let pk = sk.verifying_key();
110        let id = SessionIdentity { session_id: session_id.to_string(), tier, server_ref, key_id: keyproof::key_id_of(pk.as_bytes()), public_key: keyproof::encode(pk.as_bytes()), nick: None, enrolled: false, local_session: None };
111        // The seed goes first: a record without its key would be a dead identity.
112        self.vault.put(&seed_label(session_id), &seed)?;
113        self.save(&id)?;
114        Ok(id)
115    }
116
117    pub fn save(&self, id: &SessionIdentity) -> Result<()> {
118        self.vault.put(&record_label(&id.session_id), &serde_json::to_vec(id).map_err(|e| AgentError::Identity(e.to_string()))?)
119    }
120
121    /// Links the session to its tier-1 session id. One session has one local id and one local id
122    /// belongs to one session; a second, different link is an error (never a quiet overwrite).
123    pub fn bind_local(&self, id: &mut SessionIdentity, local_id: &str) -> Result<()> {
124        if !valid_session_id(local_id) {
125            return Err(AgentError::Identity("local session id is not a valid id".into()));
126        }
127        if let Some(have) = &id.local_session {
128            return if have == local_id { Ok(()) } else { Err(AgentError::Identity("this session is already linked to another local session".into())) };
129        }
130        let label = format!("local-link/{local_id}");
131        if let Some(owner) = self.vault.get(&label)? {
132            if owner[..] != *id.session_id.as_bytes() {
133                return Err(AgentError::Identity("that local session belongs to another identity".into()));
134            }
135        }
136        self.vault.put(&label, id.session_id.as_bytes())?;
137        id.local_session = Some(local_id.to_string());
138        self.save(id)
139    }
140
141    /// Records the nick the operator assigned. It is frozen after the first call: a different nick
142    /// for the same identity is an error, the only way to another nick is a new identity.
143    pub fn adopt_nick(&self, id: &mut SessionIdentity, nick: &str) -> Result<()> {
144        match &id.nick {
145            Some(n) if n == nick => Ok(()),
146            Some(_) => Err(AgentError::Identity("this identity already has a different nick".into())),
147            None => {
148                id.nick = Some(nick.to_string());
149                self.save(id)
150            }
151        }
152    }
153
154    /// A random 32-byte key for the session's local store (created on first ask).
155    pub fn store_key(&self, session_id: &str) -> Result<Zeroizing<Vec<u8>>> {
156        let label = format!("store-key/{session_id}");
157        if let Some(k) = self.vault.get(&label)? {
158            return Ok(k);
159        }
160        let k = random_bytes(32);
161        self.vault.put(&label, &k)?;
162        Ok(k)
163    }
164
165    /// Forgets the session entirely: key pair, record, token, store key. A later `resolve` makes a
166    /// NEW identity (which the operator must approve again).
167    pub fn forget(&self, session_id: &str) -> Result<()> {
168        if let Some(raw) = self.vault.get(&record_label(session_id))? {
169            if let Ok(id) = serde_json::from_slice::<SessionIdentity>(&raw) {
170                if let Some(l) = id.local_session {
171                    self.vault.delete(&format!("local-link/{l}"))?;
172                }
173            }
174        }
175        for l in [seed_label(session_id), record_label(session_id), token_label(session_id), format!("store-key/{session_id}")] {
176            self.vault.delete(&l)?;
177        }
178        Ok(())
179    }
180}
181
182#[cfg(test)]
183mod tests {
184    use super::*;
185    use crate::vault::MemoryVault;
186
187    fn store() -> IdentityStore {
188        IdentityStore::new(Arc::new(MemoryVault::new()))
189    }
190
191    #[test]
192    fn an_identity_is_generated_once_and_found_again() {
193        let s = store();
194        let a = s.resolve("s1", BackendKind::Server, "https://p.example/").unwrap();
195        assert!(!a.enrolled && a.nick.is_none());
196        assert_eq!(a.server_ref, "https://p.example");
197        assert_eq!(a.key_id, keyproof::key_id_of(&keyproof::decode(&a.public_key).unwrap()));
198        assert_eq!(s.resolve("s1", BackendKind::Server, "https://p.example").unwrap(), a);
199        let b = s.resolve("s2", BackendKind::Server, "https://p.example").unwrap();
200        assert_ne!(a.key_id, b.key_id, "one session, one identity");
201    }
202
203    #[test]
204    fn a_session_cannot_be_moved_to_another_server_or_tier() {
205        let s = store();
206        s.resolve("s1", BackendKind::Server, "https://p.example").unwrap();
207        assert!(s.resolve("s1", BackendKind::Server, "https://other.example").is_err());
208        assert!(s.resolve("s1", BackendKind::Matrix, "https://p.example").is_err());
209        assert!(s.resolve("../x", BackendKind::Server, "https://p.example").is_err());
210        assert!(s.resolve("", BackendKind::Server, "https://p.example").is_err());
211    }
212
213    #[test]
214    fn signatures_verify_under_the_public_key_and_forget_makes_a_new_identity() {
215        let s = store();
216        let id = s.resolve("s1", BackendKind::Matrix, "https://p.example").unwrap();
217        let c = keyproof::Challenge { challenge_id: "c".into(), nonce: "n".into(), expires_ms: 5, audience: "aud".into() };
218        let sig = id.sign_login(s.vault(), &c).unwrap();
219        assert!(keyproof::verify(&id.public_key, &keyproof::login_message(&c, &id.key_id), &sig));
220        let sig = id.sign_enroll(s.vault(), "aud", "inv").unwrap();
221        assert!(keyproof::verify(&id.public_key, &keyproof::enroll_message("aud", "inv", &id.public_key), &sig));
222        s.forget("s1").unwrap();
223        assert!(id.sign(s.vault(), b"x").is_err(), "the key is gone");
224        let again = s.resolve("s1", BackendKind::Matrix, "https://p.example").unwrap();
225        assert_ne!(again.key_id, id.key_id);
226    }
227
228    #[test]
229    fn links_and_nicks_are_one_to_one_and_frozen() {
230        let s = store();
231        let mut a = s.resolve("s1", BackendKind::Server, "https://p.example").unwrap();
232        let mut b = s.resolve("s2", BackendKind::Server, "https://p.example").unwrap();
233        s.bind_local(&mut a, "local-1").unwrap();
234        s.bind_local(&mut a, "local-1").unwrap();
235        assert!(s.bind_local(&mut a, "local-2").is_err(), "one session, one local id");
236        assert!(s.bind_local(&mut b, "local-1").is_err(), "one local id, one session");
237        assert_eq!(s.resolve("s1", BackendKind::Server, "https://p.example").unwrap().local_session.as_deref(), Some("local-1"));
238        s.adopt_nick(&mut a, "kestrel").unwrap();
239        s.adopt_nick(&mut a, "kestrel").unwrap();
240        assert!(s.adopt_nick(&mut a, "other").is_err());
241        s.forget("s1").unwrap();
242        let mut c = s.resolve("s3", BackendKind::Server, "https://p.example").unwrap();
243        s.bind_local(&mut c, "local-1").unwrap(); // the link was released with the identity
244    }
245
246    #[test]
247    fn the_debug_output_and_record_carry_no_private_key() {
248        let s = store();
249        let id = s.resolve("s1", BackendKind::Server, "https://p.example").unwrap();
250        let seed = s.vault().get(&seed_label("s1")).unwrap().unwrap();
251        let seed_b64 = keyproof::encode(&seed);
252        assert!(!format!("{id:?}").contains(&seed_b64));
253        assert!(!String::from_utf8_lossy(&serde_json::to_vec(&id).unwrap()).contains(&seed_b64));
254    }
255}