1use std::path::{Path, PathBuf};
14
15use chacha20poly1305::aead::{Aead, KeyInit as _, Payload};
16use chacha20poly1305::{XChaCha20Poly1305, XNonce};
17use zeroize::Zeroizing;
18
19use crate::CloudError;
20
21pub type Key = Zeroizing<[u8; 32]>;
23
24const NONCE_LEN: usize = 24;
25const WRAP_AAD: &str = "leanctx.cloud.replica.rk.v1";
27
28#[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
50pub fn new_replica_key() -> Result<Key, CloudError> {
52 random_key()
53}
54
55pub 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
73pub 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
91pub fn aad(place_id: &str, table: &str, row_key: &str, column: &str) -> String {
93 format!("{place_id}|{table}|{row_key}|{column}")
94}
95
96pub 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
101pub 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
109pub 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
137pub 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#[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}