Skip to main content

lean_ctx_cloud/
instance_key.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The instance's long-lived keys: Ed25519 for token assertions and an
3//! X25519 key whose public half enrollment carries.
4//!
5//! The X25519 key is the Montgomery form of a second, independent Ed25519
6//! seed (`kx.key`), so no key ever signs and agrees at once. Seeds are kept
7//! as 64 hex characters in 0600 files and zeroized in memory.
8
9use base64::Engine as _;
10use base64::engine::general_purpose::STANDARD as B64;
11use ed25519_dalek::{Signer as _, SigningKey};
12use zeroize::Zeroizing;
13
14use super::CloudError;
15use super::state::{CloudStore, INSTANCE_KEY_FILE, KX_KEY_FILE};
16
17pub struct InstanceKeys {
18    signing: SigningKey,
19    kx: SigningKey,
20}
21
22impl InstanceKeys {
23    /// Load the instance keys, creating them on first use.
24    pub fn load_or_create(store: &CloudStore) -> Result<Self, CloudError> {
25        Ok(Self {
26            signing: load_or_create_seed(store, INSTANCE_KEY_FILE)?,
27            kx: load_or_create_seed(store, KX_KEY_FILE)?,
28        })
29    }
30
31    /// Existing keys only.
32    pub fn load(store: &CloudStore) -> Result<Self, CloudError> {
33        Ok(Self {
34            signing: load_seed(store, INSTANCE_KEY_FILE)?.ok_or(CloudError::NotConnected)?,
35            kx: load_seed(store, KX_KEY_FILE)?.ok_or(CloudError::NotConnected)?,
36        })
37    }
38
39    /// Ed25519 public key, base64.
40    pub fn public_key_b64(&self) -> String {
41        B64.encode(self.signing.verifying_key().as_bytes())
42    }
43
44    /// X25519 public key, base64.
45    pub fn kx_public_key_b64(&self) -> String {
46        B64.encode(self.kx_public_key())
47    }
48
49    /// X25519 public key.
50    pub fn kx_public_key(&self) -> [u8; 32] {
51        self.kx.verifying_key().to_montgomery().to_bytes()
52    }
53
54    /// Ed25519 signature over `message`, base64.
55    pub fn sign_b64(&self, message: &[u8]) -> String {
56        B64.encode(self.signing.sign(message).to_bytes())
57    }
58
59    /// The Ed25519 signing key, for C0 2.0 documents signed as
60    /// `domain ‖ canonical_json(..)`.
61    pub fn signing_key(&self) -> &SigningKey {
62        &self.signing
63    }
64
65    /// HKDF-SHA256 over the signing seed (C0 2.0 `worker_alias_key` and
66    /// per-place alias seeds). Derived in memory, never stored or sent.
67    pub(crate) fn derive_from_signing_seed(&self, salt: &str, info: &[u8]) -> Zeroizing<[u8; 32]> {
68        derive_from_seed(&self.signing.to_bytes(), salt, info)
69    }
70
71    #[cfg(test)]
72    pub(crate) fn from_seeds(signing: [u8; 32], kx: [u8; 32]) -> Self {
73        Self {
74            signing: SigningKey::from_bytes(&signing),
75            kx: SigningKey::from_bytes(&kx),
76        }
77    }
78}
79
80/// `HKDF-SHA256(ikm = seed, salt, info)`, 32 bytes.
81pub(crate) fn derive_from_seed(seed: &[u8; 32], salt: &str, info: &[u8]) -> Zeroizing<[u8; 32]> {
82    let seed = Zeroizing::new(*seed);
83    let mut out = Zeroizing::new([0u8; 32]);
84    hkdf::Hkdf::<sha2::Sha256>::new(Some(salt.as_bytes()), seed.as_ref())
85        .expand(info, out.as_mut())
86        .expect("32 bytes is a valid HKDF-SHA256 length");
87    out
88}
89
90fn load_seed(store: &CloudStore, name: &str) -> Result<Option<SigningKey>, CloudError> {
91    let Some(bytes) = store.read_config_bytes(name)? else {
92        return Ok(None);
93    };
94    let bytes = Zeroizing::new(bytes);
95    let text = std::str::from_utf8(&bytes).map_err(|_| damaged(name))?;
96    let mut seed = Zeroizing::new([0u8; 32]);
97    hex::decode_to_slice(text.trim(), seed.as_mut()).map_err(|_| damaged(name))?;
98    Ok(Some(SigningKey::from_bytes(&seed)))
99}
100
101fn load_or_create_seed(store: &CloudStore, name: &str) -> Result<SigningKey, CloudError> {
102    if let Some(key) = load_seed(store, name)? {
103        return Ok(key);
104    }
105    let mut seed = Zeroizing::new([0u8; 32]);
106    getrandom::fill(seed.as_mut()).map_err(|e| CloudError::Local(format!("random: {e}")))?;
107    let mut text = Zeroizing::new(hex::encode(seed.as_ref()));
108    text.push('\n');
109    store.write_config_bytes(name, text.as_bytes())?;
110    Ok(SigningKey::from_bytes(&seed))
111}
112
113fn damaged(name: &str) -> CloudError {
114    CloudError::Local(format!(
115        "{name} is damaged; run `lean-ctx cloud disconnect` and connect again"
116    ))
117}
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122    use ed25519_dalek::{Signature, Verifier as _, VerifyingKey};
123
124    #[test]
125    fn keys_persist_and_sign() {
126        let dir = tempfile::tempdir().unwrap();
127        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
128        let first = InstanceKeys::load_or_create(&store).unwrap();
129        let again = InstanceKeys::load(&store).unwrap();
130        assert_eq!(first.public_key_b64(), again.public_key_b64());
131        assert_eq!(first.kx_public_key_b64(), again.kx_public_key_b64());
132        assert_ne!(first.public_key_b64(), first.kx_public_key_b64());
133
134        let public: [u8; 32] = B64
135            .decode(first.public_key_b64())
136            .unwrap()
137            .try_into()
138            .unwrap();
139        let signature: [u8; 64] = B64
140            .decode(first.sign_b64(b"m"))
141            .unwrap()
142            .try_into()
143            .unwrap();
144        assert!(
145            VerifyingKey::from_bytes(&public)
146                .unwrap()
147                .verify(b"m", &Signature::from_bytes(&signature))
148                .is_ok()
149        );
150    }
151}