Skip to main content

second_brain_sync/
crypto.rs

1use 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
91/// Seal one plaintext JSONL record into a single base64 line safe for the
92/// line-oriented SSH transport. base64 is required because the AEAD frame is
93/// binary and the wire is newline-delimited text.
94pub fn seal_line(enc: &dyn SyncEncryptor, plaintext: &[u8]) -> Result<String> {
95    let framed = enc.encrypt(plaintext)?;
96    Ok(B64.encode(framed))
97}
98
99/// Open one wire line back into the plaintext JSONL record.
100pub 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
117/// Load the 32-byte sync key from `path`, generating and persisting a fresh one
118/// if absent. The file is written 0600 because the key grants full read of every
119/// synced memory (safety: file perms must be 0600).
120pub fn load_or_create_key(path: &Path) -> Result<[u8; KEY_LEN]> {
121    match fs::read_to_string(path) {
122        Ok(contents) => {
123            let trimmed = contents.trim();
124            let raw = B64.decode(trimmed).context("decoding base64 sync key")?;
125            let key: [u8; KEY_LEN] = raw.as_slice().try_into().map_err(|_| {
126                anyhow!("sync key must decode to {KEY_LEN} bytes, got {}", raw.len())
127            })?;
128            // correct an over-permissive key file left by an earlier write or manual copy.
129            fs::set_permissions(path, fs::Permissions::from_mode(0o600))
130                .context("tightening sync key permissions to 0600")?;
131            Ok(key)
132        }
133        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
134            let mut key = [0u8; KEY_LEN];
135            OsRng.fill_bytes(&mut key);
136            write_key(path, &key)?;
137            Ok(key)
138        }
139        Err(e) => Err(e).context("reading sync key"),
140    }
141}
142
143fn write_key(path: &Path, key: &[u8; KEY_LEN]) -> Result<()> {
144    if let Some(parent) = path.parent()
145        && !parent.as_os_str().is_empty()
146    {
147        fs::create_dir_all(parent).context("creating sync key parent dir")?;
148    }
149    let mut file = fs::OpenOptions::new()
150        .create(true)
151        .write(true)
152        .truncate(true)
153        .mode(0o600)
154        .open(path)
155        .context("opening sync key for write")?;
156    file.write_all(B64.encode(key).as_bytes())
157        .context("writing sync key")?;
158    file.write_all(b"\n").context("writing sync key newline")?;
159    // because OpenOptions::mode only applies on creation, enforce 0600 even when
160    // truncating an existing file (safety: file perms must be 0600).
161    fs::set_permissions(path, fs::Permissions::from_mode(0o600))
162        .context("setting sync key mode 0600")?;
163    Ok(())
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169
170    fn test_key(seed: u8) -> [u8; KEY_LEN] {
171        [seed; KEY_LEN]
172    }
173
174    #[test]
175    fn round_trip_returns_plaintext() {
176        let enc = XChaChaEncryptor::new(test_key(7));
177        let plaintext = b"sensitive memory line as jsonl";
178        let ct = enc.encrypt(plaintext).unwrap();
179        assert_ne!(
180            ct.as_slice(),
181            plaintext,
182            "ciphertext must differ from plaintext"
183        );
184        let pt = enc.decrypt(&ct).unwrap();
185        assert_eq!(pt, plaintext);
186    }
187
188    #[test]
189    fn nonce_is_random_per_message() {
190        let enc = XChaChaEncryptor::new(test_key(3));
191        let a = enc.encrypt(b"same input").unwrap();
192        let b = enc.encrypt(b"same input").unwrap();
193        assert_ne!(a, b, "fresh random nonce must yield distinct ciphertext");
194    }
195
196    #[test]
197    fn decrypt_with_wrong_key_fails() {
198        let enc = XChaChaEncryptor::new(test_key(1));
199        let other = XChaChaEncryptor::new(test_key(2));
200        let ct = enc.encrypt(b"secret").unwrap();
201        assert!(
202            other.decrypt(&ct).is_err(),
203            "AEAD must reject a payload sealed under a different key"
204        );
205    }
206
207    #[test]
208    fn flipped_ciphertext_byte_fails() {
209        let enc = XChaChaEncryptor::new(test_key(9));
210        let mut ct = enc.encrypt(b"tamper me").unwrap();
211        let last = ct.len() - 1;
212        ct[last] ^= 0x01;
213        assert!(
214            enc.decrypt(&ct).is_err(),
215            "Poly1305 tag must reject a single flipped byte"
216        );
217    }
218
219    #[test]
220    fn legacy_plaintext_frame_is_rejected() {
221        let enc = XChaChaEncryptor::new(test_key(5));
222        let mut legacy = vec![MAGIC_PLAINTEXT];
223        legacy.extend_from_slice(b"{\"local_seq\":1}");
224        assert!(enc.decrypt(&legacy).is_err());
225    }
226
227    #[test]
228    fn empty_frame_is_rejected() {
229        let enc = XChaChaEncryptor::new(test_key(5));
230        assert!(enc.decrypt(&[]).is_err());
231    }
232
233    #[test]
234    fn seal_open_line_round_trips() {
235        let enc = XChaChaEncryptor::new(test_key(4));
236        let record = b"{\"local_seq\":42,\"op\":\"Create\"}";
237        let line = seal_line(&enc, record).unwrap();
238        assert!(!line.contains('\n'), "wire line must be single-line");
239        let out = open_line(&enc, &line).unwrap();
240        assert_eq!(out, record);
241    }
242
243    #[test]
244    fn open_line_rejects_legacy_jsonl() {
245        let enc = XChaChaEncryptor::new(test_key(4));
246        let legacy = "{\"local_seq\":1,\"op\":\"Create\"}";
247        let err = open_line(&enc, legacy).unwrap_err();
248        assert!(
249            err.to_string().contains("not an encrypted sync line"),
250            "unexpected error: {err:#}"
251        );
252    }
253
254    #[test]
255    fn open_line_rejects_base64_of_a_plaintext_frame() {
256        let enc = XChaChaEncryptor::new(test_key(4));
257        let mut legacy = vec![MAGIC_PLAINTEXT];
258        legacy.extend_from_slice(b"{\"local_seq\":1}");
259        assert!(open_line(&enc, &B64.encode(legacy)).is_err());
260    }
261
262    #[test]
263    fn load_or_create_key_creates_0600_and_is_idempotent() {
264        let dir = tempfile::tempdir().unwrap();
265        let path = dir.path().join("nested").join("sync.key");
266        let first = load_or_create_key(&path).unwrap();
267
268        let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
269        assert_eq!(mode, 0o600, "key file must be 0600");
270
271        let second = load_or_create_key(&path).unwrap();
272        assert_eq!(
273            first, second,
274            "second load must return the same persisted key"
275        );
276    }
277}