Skip to main content

lean_ctx_cloud/replica/
crypt.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Replica encryption at rest (SPEC-ENGINE §3.4.2).
3//!
4//! Every text column of a replica is XChaCha20-Poly1305 ciphertext under
5//! the place's replica key `rk` (32 random bytes), with AAD
6//! `place_id|table|row_key|column` and a random 24-byte nonce per value.
7//! `rk` is stored wrapped by the machine's replica master key `mk`; `mk`
8//! lives in the OS keychain (service `lean-ctx-cloud`, account
9//! `replica-master`) or, without one, in `<config>/cloud/replica.key`
10//! (0600, reported as `at_rest: file key`). `LEAN_CTX_REPLICA_KEY_FILE`
11//! forces the file path (tests, staging builds: no keychain dialogs).
12
13use std::path::{Path, PathBuf};
14
15use chacha20poly1305::aead::{Aead, KeyInit as _, Payload};
16use chacha20poly1305::{XChaCha20Poly1305, XNonce};
17use zeroize::Zeroizing;
18
19use crate::CloudError;
20
21/// A 32-byte key that is wiped on drop.
22pub type Key = Zeroizing<[u8; 32]>;
23
24const NONCE_LEN: usize = 24;
25/// AAD domain of a wrapped `rk`.
26const WRAP_AAD: &str = "leanctx.cloud.replica.rk.v1";
27
28/// Where `mk` is kept.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub enum AtRest {
31    Keychain,
32    FileKey,
33}
34
35impl AtRest {
36    pub fn as_str(self) -> &'static str {
37        match self {
38            Self::Keychain => "keychain",
39            Self::FileKey => "file key",
40        }
41    }
42}
43
44fn random_key() -> Result<Key, CloudError> {
45    let mut key = Zeroizing::new([0u8; 32]);
46    getrandom::fill(key.as_mut()).map_err(|e| CloudError::Local(format!("random: {e}")))?;
47    Ok(key)
48}
49
50/// A fresh per-place replica key.
51pub fn new_replica_key() -> Result<Key, CloudError> {
52    random_key()
53}
54
55/// Encrypt `plain` under `key` bound to `aad`: `nonce ‖ ciphertext`.
56pub fn seal(key: &[u8; 32], aad: &str, plain: &[u8]) -> Result<Vec<u8>, CloudError> {
57    let mut nonce = [0u8; NONCE_LEN];
58    getrandom::fill(&mut nonce).map_err(|e| CloudError::Local(format!("random: {e}")))?;
59    let ct = XChaCha20Poly1305::new(key.into())
60        .encrypt(
61            XNonce::from_slice(&nonce),
62            Payload {
63                msg: plain,
64                aad: aad.as_bytes(),
65            },
66        )
67        .map_err(|_| CloudError::Local("replica: encryption failed".into()))?;
68    let mut out = nonce.to_vec();
69    out.extend(ct);
70    Ok(out)
71}
72
73/// Decrypt what [`seal`] made; fails on another key, AAD or a changed byte.
74pub fn open(key: &[u8; 32], aad: &str, sealed: &[u8]) -> Result<Zeroizing<Vec<u8>>, CloudError> {
75    if sealed.len() < NONCE_LEN {
76        return Err(CloudError::Local("replica: ciphertext too short".into()));
77    }
78    let (nonce, ct) = sealed.split_at(NONCE_LEN);
79    XChaCha20Poly1305::new(key.into())
80        .decrypt(
81            XNonce::from_slice(nonce),
82            Payload {
83                msg: ct,
84                aad: aad.as_bytes(),
85            },
86        )
87        .map(Zeroizing::new)
88        .map_err(|_| CloudError::Local("replica: value does not decrypt".into()))
89}
90
91/// The AAD of one column value.
92pub fn aad(place_id: &str, table: &str, row_key: &str, column: &str) -> String {
93    format!("{place_id}|{table}|{row_key}|{column}")
94}
95
96/// Wrap `rk` for storage under `mk`.
97pub fn wrap(mk: &[u8; 32], place_id: &str, rk: &[u8; 32]) -> Result<Vec<u8>, CloudError> {
98    seal(mk, &format!("{WRAP_AAD}|{place_id}"), rk)
99}
100
101/// Unwrap a stored `rk`; `None` when `mk` does not open it
102/// (`replica_key_missing`: the place is re-cloned).
103pub fn unwrap(mk: &[u8; 32], place_id: &str, wrapped: &[u8]) -> Option<Key> {
104    let plain = open(mk, &format!("{WRAP_AAD}|{place_id}"), wrapped).ok()?;
105    let bytes: [u8; 32] = plain.as_slice().try_into().ok()?;
106    Some(Zeroizing::new(bytes))
107}
108
109/// The file `mk` is kept in without a keychain.
110pub fn key_file(config_dir: &Path) -> PathBuf {
111    std::env::var_os("LEAN_CTX_REPLICA_KEY_FILE")
112        .map(PathBuf::from)
113        .unwrap_or_else(|| config_dir.join("replica.key"))
114}
115
116fn load_or_create_file(path: &Path) -> Result<Key, CloudError> {
117    if let Ok(bytes) = std::fs::read(path) {
118        let bytes = Zeroizing::new(bytes);
119        let key: [u8; 32] = bytes
120            .as_slice()
121            .try_into()
122            .map_err(|_| CloudError::Local("replica key file is not a 32-byte key".into()))?;
123        return Ok(Zeroizing::new(key));
124    }
125    let key = random_key()?;
126    let dir = path
127        .parent()
128        .ok_or_else(|| CloudError::Local("replica key file has no directory".into()))?;
129    let name = path
130        .file_name()
131        .and_then(|n| n.to_str())
132        .ok_or_else(|| CloudError::Local("replica key file name".into()))?;
133    crate::state::write_private(dir, name, key.as_ref())?;
134    Ok(key)
135}
136
137/// The machine's replica master key `mk` and where it is kept. The
138/// keychain is used unless `LEAN_CTX_REPLICA_KEY_FILE` is set, the platform
139/// has none, or `keychain_required` is false and the keychain fails;
140/// `keychain_required` (workspace policy `require_keychain_at_rest`)
141/// refuses the file fallback.
142pub fn master_key(config_dir: &Path, keychain_required: bool) -> Result<(Key, AtRest), CloudError> {
143    if std::env::var_os("LEAN_CTX_REPLICA_KEY_FILE").is_none() {
144        match keychain::load_or_create() {
145            Ok(key) => return Ok((key, AtRest::Keychain)),
146            Err(_) if !keychain_required => {}
147            Err(e) => {
148                return Err(CloudError::Config(format!(
149                    "keychain_required_by_policy: {e}"
150                )));
151            }
152        }
153    } else if keychain_required {
154        return Err(CloudError::Config(
155            "keychain_required_by_policy: a key file is set".into(),
156        ));
157    }
158    Ok((load_or_create_file(&key_file(config_dir))?, AtRest::FileKey))
159}
160
161/// OS keychain holding `mk`. Tests never touch the real keychain.
162#[cfg(all(any(target_os = "macos", windows, target_os = "linux"), not(test)))]
163mod keychain {
164    use super::Key;
165
166    const SERVICE: &str = "lean-ctx-cloud";
167    const ACCOUNT: &str = "replica-master";
168
169    pub(super) fn load_or_create() -> Result<Key, String> {
170        let entry = keyring::Entry::new(SERVICE, ACCOUNT).map_err(|e| e.to_string())?;
171        match entry.get_secret() {
172            Ok(bytes) => {
173                let bytes = zeroize::Zeroizing::new(bytes);
174                let key: [u8; 32] = bytes
175                    .as_slice()
176                    .try_into()
177                    .map_err(|_| "keychain entry is not a 32-byte key".to_string())?;
178                Ok(zeroize::Zeroizing::new(key))
179            }
180            Err(keyring::Error::NoEntry) => {
181                let key = super::random_key().map_err(|e| e.to_string())?;
182                entry.set_secret(key.as_ref()).map_err(|e| e.to_string())?;
183                Ok(key)
184            }
185            Err(e) => Err(e.to_string()),
186        }
187    }
188}
189
190#[cfg(not(all(any(target_os = "macos", windows, target_os = "linux"), not(test))))]
191mod keychain {
192    pub(super) fn load_or_create() -> Result<super::Key, String> {
193        Err("no OS keychain here".to_string())
194    }
195}
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200
201    #[test]
202    fn values_are_bound_to_key_and_aad() {
203        let key = [3u8; 32];
204        let a = aad("p1", "nodes", "n_x", "fields");
205        let ct = seal(&key, &a, b"canary statement").unwrap();
206        assert_eq!(open(&key, &a, &ct).unwrap().as_slice(), b"canary statement");
207        assert!(open(&[4u8; 32], &a, &ct).is_err(), "other key");
208        assert!(
209            open(&key, &aad("p1", "nodes", "n_y", "fields"), &ct).is_err(),
210            "other row"
211        );
212        let mut flipped = ct.clone();
213        *flipped.last_mut().unwrap() ^= 1;
214        assert!(open(&key, &a, &flipped).is_err(), "changed byte");
215        assert_ne!(
216            seal(&key, &a, b"canary statement").unwrap(),
217            ct,
218            "random nonce"
219        );
220    }
221
222    #[test]
223    fn replica_keys_wrap_per_place() {
224        let mk = [9u8; 32];
225        let rk = new_replica_key().unwrap();
226        let wrapped = wrap(&mk, "p1", &rk).unwrap();
227        assert_eq!(unwrap(&mk, "p1", &wrapped).unwrap().as_ref(), rk.as_ref());
228        assert!(unwrap(&mk, "p2", &wrapped).is_none());
229        assert!(unwrap(&[1u8; 32], "p1", &wrapped).is_none());
230    }
231
232    #[test]
233    fn the_file_key_is_created_once_and_private() {
234        let dir = tempfile::tempdir().unwrap();
235        let path = dir.path().join("cloud").join("replica.key");
236        let first = load_or_create_file(&path).unwrap();
237        let again = load_or_create_file(&path).unwrap();
238        assert_eq!(first.as_ref(), again.as_ref());
239        #[cfg(unix)]
240        {
241            use std::os::unix::fs::PermissionsExt as _;
242            let mode = std::fs::metadata(&path).unwrap().permissions().mode();
243            assert_eq!(mode & 0o077, 0, "{mode:o}");
244        }
245    }
246}