second_brain_sync/
crypto.rs1use std::fs;
2use std::io::Write;
3use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
4use std::path::{Path, PathBuf};
5
6use anyhow::{Context, Result, anyhow, bail};
7use base64::Engine;
8use base64::engine::general_purpose::STANDARD as B64;
9use chacha20poly1305::aead::{Aead, KeyInit, OsRng};
10use chacha20poly1305::{XChaCha20Poly1305, XNonce};
11use rand_core::RngCore;
12
13const KEY_LEN: usize = 32;
14const NONCE_LEN: usize = 24;
15
16const MAGIC_PLAINTEXT: u8 = 0x00;
17const MAGIC_XCHACHA: u8 = 0x01;
18
19pub trait SyncEncryptor: Send + Sync {
20 fn encrypt(&self, plaintext: &[u8]) -> Result<Vec<u8>>;
21 fn decrypt(&self, ciphertext: &[u8]) -> Result<Vec<u8>>;
22}
23
24pub struct PassthroughEncryptor;
25
26impl SyncEncryptor for PassthroughEncryptor {
27 fn encrypt(&self, plaintext: &[u8]) -> Result<Vec<u8>> {
28 Ok(plaintext.to_vec())
29 }
30
31 fn decrypt(&self, ciphertext: &[u8]) -> Result<Vec<u8>> {
32 Ok(ciphertext.to_vec())
33 }
34}
35
36pub struct XChaChaEncryptor {
37 key: [u8; KEY_LEN],
38}
39
40impl XChaChaEncryptor {
41 pub fn new(key: [u8; KEY_LEN]) -> Self {
42 Self { key }
43 }
44
45 pub fn key_base64(&self) -> String {
46 B64.encode(self.key)
47 }
48
49 fn cipher(&self) -> XChaCha20Poly1305 {
50 XChaCha20Poly1305::new((&self.key).into())
51 }
52}
53
54impl SyncEncryptor for XChaChaEncryptor {
55 fn encrypt(&self, plaintext: &[u8]) -> Result<Vec<u8>> {
56 let mut nonce_bytes = [0u8; NONCE_LEN];
57 OsRng.fill_bytes(&mut nonce_bytes);
58 let nonce = XNonce::from_slice(&nonce_bytes);
59
60 let ct = self
61 .cipher()
62 .encrypt(nonce, plaintext)
63 .map_err(|e| anyhow!("xchacha20poly1305 encrypt failed: {e}"))?;
64
65 let mut framed = Vec::with_capacity(1 + NONCE_LEN + ct.len());
66 framed.push(MAGIC_XCHACHA);
67 framed.extend_from_slice(&nonce_bytes);
68 framed.extend_from_slice(&ct);
69 Ok(framed)
70 }
71
72 fn decrypt(&self, framed: &[u8]) -> Result<Vec<u8>> {
73 match framed.first() {
74 None => bail!("empty sync payload"),
75 Some(&MAGIC_PLAINTEXT) => bail!("refusing an unencrypted sync payload"),
76 Some(&MAGIC_XCHACHA) => {
77 if framed.len() < 1 + NONCE_LEN {
78 bail!("encrypted payload too short to contain a nonce");
79 }
80 let nonce = XNonce::from_slice(&framed[1..1 + NONCE_LEN]);
81 let ct = &framed[1 + NONCE_LEN..];
82 self.cipher().decrypt(nonce, ct).map_err(|e| {
83 anyhow!("xchacha20poly1305 decrypt failed (bad key or tampered payload): {e}")
84 })
85 }
86 Some(other) => bail!("unknown sync payload magic byte: {other:#x}"),
87 }
88 }
89}
90
91pub fn seal_line(enc: &dyn SyncEncryptor, plaintext: &[u8]) -> Result<String> {
95 let framed = enc.encrypt(plaintext)?;
96 Ok(B64.encode(framed))
97}
98
99pub fn open_line(enc: &dyn SyncEncryptor, line: &str) -> Result<Vec<u8>> {
101 let framed = B64
102 .decode(line.trim())
103 .context("not an encrypted sync line (plaintext lines are refused)")?;
104 enc.decrypt(&framed)
105}
106
107#[cfg(test)]
108pub(crate) fn frame_format() -> String {
109 format!("base64({MAGIC_XCHACHA:#04x} | nonce[{NONCE_LEN}] | xchacha20poly1305 ciphertext)")
110}
111
112pub fn default_key_path() -> Result<PathBuf> {
113 let home = dirs::home_dir().context("cannot determine home directory")?;
114 Ok(home.join(".second-brain").join("sync.key"))
115}
116
117pub fn load_or_create_key(path: &Path) -> Result<[u8; KEY_LEN]> {
121 if let Some(key) = read_key(path)? {
122 return Ok(key);
123 }
124 let mut key = [0u8; KEY_LEN];
125 OsRng.fill_bytes(&mut key);
126 if create_key(path, &key)? {
127 return Ok(key);
128 }
129 read_key(path)?.with_context(|| {
130 format!(
131 "{} exists but reads as missing; is it a dangling symlink?",
132 path.display()
133 )
134 })
135}
136
137fn read_key(path: &Path) -> Result<Option<[u8; KEY_LEN]>> {
138 let contents = match fs::read_to_string(path) {
139 Ok(contents) => contents,
140 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
141 Err(e) => return Err(e).context("reading sync key"),
142 };
143 let raw = B64
144 .decode(contents.trim())
145 .context("decoding base64 sync key")?;
146 let key: [u8; KEY_LEN] = raw
147 .as_slice()
148 .try_into()
149 .map_err(|_| anyhow!("sync key must decode to {KEY_LEN} bytes, got {}", raw.len()))?;
150 fs::set_permissions(path, fs::Permissions::from_mode(0o600))
152 .context("tightening sync key permissions to 0600")?;
153 Ok(Some(key))
154}
155
156fn create_key(path: &Path, key: &[u8; KEY_LEN]) -> Result<bool> {
160 if let Some(parent) = path.parent()
161 && !parent.as_os_str().is_empty()
162 {
163 fs::create_dir_all(parent).context("creating sync key parent dir")?;
164 }
165 let mut staged = path.as_os_str().to_owned();
166 staged.push(format!(".{:016x}.tmp", OsRng.next_u64()));
167 let staged = PathBuf::from(staged);
168 let mut file = fs::OpenOptions::new()
169 .write(true)
170 .create_new(true)
171 .mode(0o600)
172 .open(&staged)
173 .context("staging the sync key")?;
174 let written = file
175 .write_all(format!("{}\n", B64.encode(key)).as_bytes())
176 .and_then(|()| file.sync_all());
177 drop(file);
178 if let Err(e) = written {
179 let left = match fs::remove_file(&staged) {
180 Ok(()) => String::new(),
181 Err(cleanup) => format!("; {} was left behind: {cleanup}", staged.display()),
182 };
183 return Err(e).context(format!("writing sync key{left}"));
184 }
185 let linked = fs::hard_link(&staged, path);
186 if let Err(e) = fs::remove_file(&staged) {
187 tracing::warn!("could not remove {}: {e}", staged.display());
188 }
189 match linked {
190 Ok(()) => Ok(true),
191 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(false),
192 Err(e) => Err(e).context("linking the sync key into place"),
193 }
194}
195
196#[cfg(test)]
197mod tests {
198 use super::*;
199
200 fn test_key(seed: u8) -> [u8; KEY_LEN] {
201 [seed; KEY_LEN]
202 }
203
204 #[test]
205 fn round_trip_returns_plaintext() {
206 let enc = XChaChaEncryptor::new(test_key(7));
207 let plaintext = b"sensitive memory line as jsonl";
208 let ct = enc.encrypt(plaintext).unwrap();
209 assert_ne!(
210 ct.as_slice(),
211 plaintext,
212 "ciphertext must differ from plaintext"
213 );
214 let pt = enc.decrypt(&ct).unwrap();
215 assert_eq!(pt, plaintext);
216 }
217
218 #[test]
219 fn nonce_is_random_per_message() {
220 let enc = XChaChaEncryptor::new(test_key(3));
221 let a = enc.encrypt(b"same input").unwrap();
222 let b = enc.encrypt(b"same input").unwrap();
223 assert_ne!(a, b, "fresh random nonce must yield distinct ciphertext");
224 }
225
226 #[test]
227 fn decrypt_with_wrong_key_fails() {
228 let enc = XChaChaEncryptor::new(test_key(1));
229 let other = XChaChaEncryptor::new(test_key(2));
230 let ct = enc.encrypt(b"secret").unwrap();
231 assert!(
232 other.decrypt(&ct).is_err(),
233 "AEAD must reject a payload sealed under a different key"
234 );
235 }
236
237 #[test]
238 fn flipped_ciphertext_byte_fails() {
239 let enc = XChaChaEncryptor::new(test_key(9));
240 let mut ct = enc.encrypt(b"tamper me").unwrap();
241 let last = ct.len() - 1;
242 ct[last] ^= 0x01;
243 assert!(
244 enc.decrypt(&ct).is_err(),
245 "Poly1305 tag must reject a single flipped byte"
246 );
247 }
248
249 #[test]
250 fn legacy_plaintext_frame_is_rejected() {
251 let enc = XChaChaEncryptor::new(test_key(5));
252 let mut legacy = vec![MAGIC_PLAINTEXT];
253 legacy.extend_from_slice(b"{\"local_seq\":1}");
254 assert!(enc.decrypt(&legacy).is_err());
255 }
256
257 #[test]
258 fn empty_frame_is_rejected() {
259 let enc = XChaChaEncryptor::new(test_key(5));
260 assert!(enc.decrypt(&[]).is_err());
261 }
262
263 #[test]
264 fn seal_open_line_round_trips() {
265 let enc = XChaChaEncryptor::new(test_key(4));
266 let record = b"{\"local_seq\":42,\"op\":\"Create\"}";
267 let line = seal_line(&enc, record).unwrap();
268 assert!(!line.contains('\n'), "wire line must be single-line");
269 let out = open_line(&enc, &line).unwrap();
270 assert_eq!(out, record);
271 }
272
273 #[test]
274 fn open_line_rejects_legacy_jsonl() {
275 let enc = XChaChaEncryptor::new(test_key(4));
276 let legacy = "{\"local_seq\":1,\"op\":\"Create\"}";
277 let err = open_line(&enc, legacy).unwrap_err();
278 assert!(
279 err.to_string().contains("not an encrypted sync line"),
280 "unexpected error: {err:#}"
281 );
282 }
283
284 #[test]
285 fn open_line_rejects_base64_of_a_plaintext_frame() {
286 let enc = XChaChaEncryptor::new(test_key(4));
287 let mut legacy = vec![MAGIC_PLAINTEXT];
288 legacy.extend_from_slice(b"{\"local_seq\":1}");
289 assert!(open_line(&enc, &B64.encode(legacy)).is_err());
290 }
291
292 #[test]
293 fn load_or_create_key_creates_0600_and_is_idempotent() {
294 let dir = tempfile::tempdir().unwrap();
295 let path = dir.path().join("nested").join("sync.key");
296 let first = load_or_create_key(&path).unwrap();
297
298 let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
299 assert_eq!(mode, 0o600, "key file must be 0600");
300
301 let second = load_or_create_key(&path).unwrap();
302 assert_eq!(
303 first, second,
304 "second load must return the same persisted key"
305 );
306 }
307
308 #[test]
309 fn a_dangling_key_symlink_is_an_error_naming_the_path() {
310 let dir = tempfile::tempdir().unwrap();
311 let path = dir.path().join("sync.key");
312 std::os::unix::fs::symlink(dir.path().join("gone"), &path).unwrap();
313 let error = load_or_create_key(&path).unwrap_err();
314 assert!(format!("{error:#}").contains("sync.key"), "{error:#}");
315 }
316
317 #[test]
318 fn callers_creating_the_key_at_once_all_get_the_one_on_disk() {
319 for _ in 0..50 {
320 let dir = tempfile::tempdir().unwrap();
321 let path = dir.path().join("sync.key");
322 let start = std::sync::Arc::new(std::sync::Barrier::new(16));
323 let keys: Vec<[u8; KEY_LEN]> = (0..16)
324 .map(|_| {
325 let path = path.clone();
326 let start = start.clone();
327 std::thread::spawn(move || {
328 start.wait();
329 load_or_create_key(&path).unwrap()
330 })
331 })
332 .collect::<Vec<_>>()
333 .into_iter()
334 .map(|handle| handle.join().unwrap())
335 .collect();
336 let on_disk = load_or_create_key(&path).unwrap();
337 assert!(keys.iter().all(|key| *key == on_disk));
338 assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
339 }
340 }
341}