Skip to main content

writerslogic_warm/core/
security.rs

1// Copyright 2024-2026 WritersLogic Contributors
2// SPDX-License-Identifier: Apache-2.0
3
4#[cfg(feature = "security")]
5use anyhow::{anyhow, bail, ensure, Result};
6#[cfg(feature = "security")]
7use std::path::Path;
8
9#[cfg(feature = "security")]
10use ed25519_dalek::{Signer, SigningKey, Verifier, VerifyingKey};
11#[cfg(feature = "security")]
12use zeroize::Zeroize;
13
14#[cfg(feature = "security")]
15use aes_gcm::{
16    aead::{Aead, KeyInit},
17    Aes256Gcm, Nonce,
18};
19
20#[cfg(feature = "security")]
21pub struct SigningManager {
22    signing_key: SigningKey,
23    #[allow(dead_code)]
24    verifying_key: VerifyingKey,
25}
26
27#[cfg(feature = "security")]
28impl SigningManager {
29    /// Load or generate an Ed25519 keypair.
30    /// If `key_path` exists, loads from it. Otherwise generates a new keypair
31    /// and saves it to `key_path`.
32    pub fn new(key_path: &Path) -> Result<Self> {
33        let bytes = load_or_create::<32>(key_path, true)?;
34        let signing_key = SigningKey::from_bytes(&bytes);
35        let verifying_key = signing_key.verifying_key();
36        Ok(Self {
37            signing_key,
38            verifying_key,
39        })
40    }
41
42    /// Sign arbitrary data, returning a 64-byte Ed25519 signature.
43    pub fn sign(&self, data: &[u8]) -> [u8; 64] {
44        self.signing_key.sign(data).to_bytes()
45    }
46
47    /// Verify a signature against data.
48    #[allow(dead_code)]
49    pub fn verify(&self, data: &[u8], signature: &[u8; 64]) -> Result<()> {
50        let sig = ed25519_dalek::Signature::from_bytes(signature);
51        self.verifying_key
52            .verify(data, &sig)
53            .map_err(|e| anyhow!("Signature verification failed: {}", e))
54    }
55
56    /// Export the public verifying key (32 bytes).
57    #[allow(dead_code)]
58    pub fn verifying_key_bytes(&self) -> [u8; 32] {
59        self.verifying_key.to_bytes()
60    }
61
62    /// Move the signing key out for use by other managers. Only consumed by the
63    /// provenance layer today, so it is dead under `security`-without-`provenance`.
64    #[allow(dead_code)]
65    pub fn into_signing_key(self) -> SigningKey {
66        self.signing_key
67    }
68}
69
70#[cfg(feature = "security")]
71fn read_fixed<const N: usize>(
72    path: &Path,
73    private: bool,
74) -> Result<Option<zeroize::Zeroizing<[u8; N]>>> {
75    use std::io::Read;
76    let mut file = match super::durable_file::open_regular(path, false) {
77        Ok(file) => file,
78        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
79        Err(error) => return Err(error.into()),
80    };
81    anyhow::ensure!(
82        file.metadata()?.len() == N as u64,
83        "invalid identity file length: expected {N} bytes"
84    );
85    #[cfg(unix)]
86    {
87        use std::os::unix::fs::PermissionsExt;
88        anyhow::ensure!(
89            !private || file.metadata()?.permissions().mode() & 0o077 == 0,
90            "signing key permissions must exclude group and other access"
91        );
92    }
93    #[cfg(not(unix))]
94    let _ = private;
95    let mut bytes = zeroize::Zeroizing::new([0; N]);
96    file.read_exact(&mut *bytes)?;
97    let mut extra = zeroize::Zeroizing::new([0; 1]);
98    anyhow::ensure!(
99        file.read(&mut *extra)? == 0,
100        "identity file changed while reading"
101    );
102    Ok(Some(bytes))
103}
104
105#[cfg(feature = "security")]
106fn load_or_create<const N: usize>(
107    path: &Path,
108    private: bool,
109) -> Result<zeroize::Zeroizing<[u8; N]>> {
110    if let Some(bytes) = read_fixed(path, private)? {
111        super::durable_file::sync_directory(
112            path.parent()
113                .filter(|p| !p.as_os_str().is_empty())
114                .unwrap_or_else(|| Path::new(".")),
115        )?;
116        return Ok(bytes);
117    }
118    if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
119        super::durable_file::create_identity_parent(parent)?;
120    }
121    let mut proposed = zeroize::Zeroizing::new([0; N]);
122    secure_random(&mut *proposed)?;
123    super::durable_file::atomic_create(path, &*proposed)?;
124    read_fixed(path, private)?.ok_or_else(|| anyhow!("identity disappeared after publication"))
125}
126
127#[cfg(feature = "security")]
128fn secure_random(bytes: &mut [u8]) -> Result<()> {
129    use rand::TryRng;
130    rand::rngs::SysRng
131        .try_fill_bytes(bytes)
132        .map_err(|_| anyhow!("operating system randomness unavailable"))
133}
134
135/// The AES-256-GCM cipher behind one heap allocation: moving the manager moves a pointer, not
136/// the key schedule (whose first two round keys are the key), and the `aes-gcm/zeroize`
137/// feature zeroizes the schedule when the box drops.
138#[cfg(feature = "security")]
139pub struct EncryptionManager {
140    cipher: Box<Aes256Gcm>,
141}
142
143#[cfg(feature = "security")]
144/// Bytes of stack `scrub_stack` overwrites below its caller's frame.
145const SCRUB_BYTES: usize = 256 * 1024;
146
147/// Overwrites the stack region below the caller's frame so secrets left there by callees
148/// (Argon2 temporaries, a cipher value before it moved to the heap) do not linger. Best
149/// effort: the language guarantees nothing about frame layout, so the key-zeroization test
150/// in this module measures the result rather than assuming it.
151#[cfg(feature = "security")]
152#[inline(never)]
153pub fn scrub_stack() {
154    let mut pad = [0u64; SCRUB_BYTES / 8];
155    for word in pad.iter_mut() {
156        // SAFETY: `word` is a valid, aligned, exclusive reference into `pad`; the volatile
157        // write keeps the store from being elided as dead.
158        unsafe { std::ptr::write_volatile(word, 0) };
159    }
160    std::hint::black_box(&pad);
161}
162
163#[cfg(feature = "security")]
164impl EncryptionManager {
165    /// Derive an AES-256 key from a passphrase using Argon2id and create the cipher.
166    /// The salt is stored at `{storage_path}/encryption.salt`. If it doesn't exist,
167    /// a new random salt is generated and saved.
168    pub fn new(passphrase: &str, storage_path: &Path) -> Result<Self> {
169        use argon2::Argon2;
170
171        let salt_path = storage_path.join("encryption.salt");
172        let salt = load_or_create::<16>(&salt_path, false)?;
173
174        let mut key = zeroize::Zeroizing::new([0u8; 32]);
175        Argon2::default()
176            .hash_password_into(passphrase.as_bytes(), &*salt, &mut *key)
177            .map_err(|e| anyhow!("Argon2 key derivation failed: {}", e))?;
178
179        let cipher = Self::build_cipher(&key);
180        key.zeroize();
181        // Argon2's finalization and the cipher value before it moved into its box left copies
182        // of the key in callee frames.
183        scrub_stack();
184        Ok(Self { cipher: cipher? })
185    }
186
187    /// A manager over a 256-bit master key, such as the one a default-encrypted store holds in
188    /// `<store>/master.key`. No passphrase derivation runs.
189    pub fn from_key(key: &[u8; 32]) -> Result<Self> {
190        let cipher = Self::build_cipher(key);
191        scrub_stack();
192        Ok(Self { cipher: cipher? })
193    }
194
195    /// Opens (or, for a new store, creates) the master key of the store at `dir` and returns
196    /// its cipher. A new store also gets `key.check`, a sealed constant that a later open
197    /// verifies, so a wrong key is refused even before the store holds a frame. An existing
198    /// store whose key is missing is an error; a fresh key would only make it unreadable.
199    pub(crate) fn open_master(dir: &Path, key_file: Option<&str>, create: bool) -> Result<Self> {
200        use super::sealed::KeySource;
201        const CHECK: &[u8] = b"warm master key check v1";
202        let mut source = KeySource::file(
203            key_file
204                .map(std::path::PathBuf::from)
205                .unwrap_or_else(|| dir.join("master.key")),
206        );
207        let key = match source.load()? {
208            Some(key) => key,
209            None if create => {
210                let key = super::sealed::fresh_key()?;
211                source.store_new(&key)?;
212                key
213            }
214            None => bail!("the store is encrypted but its master key is missing"),
215        };
216        let manager = Self::from_key(&key)?;
217        let check = dir.join("key.check");
218        match std::fs::read(&check) {
219            Ok(sealed) => {
220                let opened = manager.decrypt_with_aad(&sealed, b"key.check");
221                ensure!(
222                    opened.is_ok_and(|plain| plain == CHECK),
223                    "the master key does not open this store (wrong key, or key.check is damaged)"
224                );
225            }
226            Err(e) if e.kind() == std::io::ErrorKind::NotFound && create => {
227                super::durable_file::atomic_create(
228                    &check,
229                    &manager.encrypt_with_aad(CHECK, b"key.check")?,
230                )?;
231            }
232            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
233                bail!("the store is encrypted but key.check is missing")
234            }
235            Err(e) => return Err(e.into()),
236        }
237        Ok(manager)
238    }
239
240    /// Builds the cipher in its own frame so the pre-box copy of the key schedule lies in
241    /// the region `scrub_stack` overwrites.
242    #[inline(never)]
243    fn build_cipher(key: &[u8; 32]) -> Result<Box<Aes256Gcm>> {
244        Ok(Box::new(
245            Aes256Gcm::new_from_slice(key)
246                .map_err(|e| anyhow!("AES-256-GCM init failed: {}", e))?,
247        ))
248    }
249
250    /// Encrypt data. Returns `[nonce:12][ciphertext+tag]`.
251    pub fn encrypt(&self, plaintext: &[u8]) -> Result<Vec<u8>> {
252        // GCM with empty associated data is exactly GCM without it.
253        self.encrypt_with_aad(plaintext, b"")
254    }
255
256    /// Like [`encrypt`](Self::encrypt), binding `aad` into the authentication tag.
257    pub fn encrypt_with_aad(&self, plaintext: &[u8], aad: &[u8]) -> Result<Vec<u8>> {
258        use aes_gcm::aead::Payload;
259        let mut nonce_bytes = [0u8; 12];
260        secure_random(&mut nonce_bytes)?;
261        let nonce = Nonce::try_from(nonce_bytes.as_slice())
262            .map_err(|_| anyhow!("AES-256-GCM nonce construction failed"))?;
263        let ciphertext = self
264            .cipher
265            .encrypt(
266                &nonce,
267                Payload {
268                    msg: plaintext,
269                    aad,
270                },
271            )
272            .map_err(|e| anyhow!("Encryption failed: {}", e))?;
273        let mut output = Vec::with_capacity(12 + ciphertext.len());
274        output.extend_from_slice(&nonce_bytes);
275        output.extend_from_slice(&ciphertext);
276        Ok(output)
277    }
278
279    /// Decrypt data produced by `encrypt_with_aad()` with the same `aad`.
280    pub fn decrypt_with_aad(&self, encrypted: &[u8], aad: &[u8]) -> Result<Vec<u8>> {
281        use aes_gcm::aead::Payload;
282        if encrypted.len() < 12 {
283            return Err(anyhow!(
284                "Encrypted data too short: {} bytes",
285                encrypted.len()
286            ));
287        }
288        let nonce = Nonce::try_from(&encrypted[..12])
289            .map_err(|_| anyhow!("AES-256-GCM nonce construction failed"))?;
290        self.cipher
291            .decrypt(
292                &nonce,
293                Payload {
294                    msg: &encrypted[12..],
295                    aad,
296                },
297            )
298            .map_err(|e| anyhow!("Decryption failed: {}", e))
299    }
300
301    /// Decrypt data produced by `encrypt()`. Input: `[nonce:12][ciphertext+tag]`.
302    pub fn decrypt(&self, encrypted: &[u8]) -> Result<Vec<u8>> {
303        if encrypted.len() < 12 {
304            return Err(anyhow!(
305                "Encrypted data too short: {} bytes (minimum 12 for nonce)",
306                encrypted.len()
307            ));
308        }
309        let nonce = Nonce::try_from(&encrypted[..12])
310            .map_err(|_| anyhow!("AES-256-GCM nonce construction failed"))?;
311        let ciphertext = &encrypted[12..];
312
313        self.cipher
314            .decrypt(&nonce, ciphertext)
315            .map_err(|e| anyhow!("Decryption failed: {}", e))
316    }
317}
318
319/// Hash an ID using SHA-256 for audit log entries (avoids storing raw IDs).
320#[cfg(feature = "security")]
321pub fn hash_id(id: &str) -> [u8; 32] {
322    use sha2::{Digest, Sha256};
323    let mut hasher = Sha256::new();
324    hasher.update(id.as_bytes());
325    hasher.finalize().into()
326}
327
328/// Stub for non-security builds -- hash_id using Fx hashing (non-crypto, 8 bytes zero-padded).
329#[cfg(not(feature = "security"))]
330pub fn hash_id(id: &str) -> [u8; 32] {
331    let hash = crate::core::hash::fx64(id.as_bytes()).to_le_bytes();
332    let mut out = [0u8; 32];
333    out[..8].copy_from_slice(&hash);
334    out
335}
336
337#[cfg(all(test, feature = "security"))]
338mod tests {
339    use super::*;
340    use tempfile::tempdir;
341
342    /// The AES key schedule lives in one heap allocation that is zeroized when the manager
343    /// drops: afterwards no readable heap or anonymous mapping holds the derived key. The
344    /// needle is kept XOR-masked so the test's own copy never matches, and each scan buffer
345    /// is zeroized before release so a scan cannot find its own earlier copy.
346    #[cfg(target_os = "linux")]
347    #[test]
348    fn derived_key_leaves_the_heap_when_the_manager_drops() -> Result<()> {
349        use argon2::Argon2;
350        use std::io::{Read, Seek, SeekFrom};
351
352        /// Where the masked needle occurs in the process's writable anonymous mappings, as
353        /// `range perms name +offset` lines.
354        fn heap_copies(masked: &[u8], mask: &[u8]) -> Result<Vec<String>> {
355            let maps = std::fs::read_to_string("/proc/self/maps")?;
356            let mut mem = std::fs::File::open("/proc/self/mem")?;
357            let mut hits = Vec::new();
358            for line in maps.lines() {
359                let mut parts = line.split_whitespace();
360                let (Some(range), Some(perms)) = (parts.next(), parts.next()) else {
361                    continue;
362                };
363                let name = parts.nth(3).unwrap_or("");
364                if !perms.starts_with("rw") || !(name.is_empty() || name == "[heap]") {
365                    continue;
366                }
367                let (lo, hi) = range
368                    .split_once('-')
369                    .ok_or_else(|| anyhow!("maps range {range}"))?;
370                let (lo, hi) = (u64::from_str_radix(lo, 16)?, u64::from_str_radix(hi, 16)?);
371                if hi <= lo || hi - lo > 1 << 32 {
372                    continue;
373                }
374                // Read in chunks so a page another test thread unmaps mid-scan costs one
375                // chunk, not the whole mapping; chunks overlap by the needle length so no
376                // occurrence straddles a boundary unseen.
377                const CHUNK: u64 = 1 << 16;
378                let overlap = masked.len() as u64 - 1;
379                let mut buf = vec![0u8; (CHUNK + overlap) as usize];
380                let mut at = lo;
381                while at < hi {
382                    let len = (CHUNK + overlap).min(hi - at) as usize;
383                    let chunk = &mut buf[..len];
384                    if mem.seek(SeekFrom::Start(at)).is_ok() && mem.read_exact(chunk).is_ok() {
385                        for (offset, w) in chunk.windows(masked.len()).enumerate() {
386                            if offset as u64 >= CHUNK && at + CHUNK < hi {
387                                break;
388                            }
389                            if w.iter()
390                                .zip(masked)
391                                .zip(mask)
392                                .all(|((b, n), m)| b ^ m == *n)
393                            {
394                                hits.push(format!(
395                                    "{range} {perms} {name:?} +{:#x}",
396                                    at - lo + offset as u64
397                                ));
398                            }
399                        }
400                    }
401                    chunk.zeroize();
402                    at += CHUNK;
403                }
404                buf.zeroize();
405            }
406            Ok(hits)
407        }
408
409        let dir = tempdir()?;
410        let passphrase = "zeroization probe passphrase";
411        let manager = EncryptionManager::new(passphrase, dir.path())?;
412        let salt = std::fs::read(dir.path().join("encryption.salt"))?;
413        let mask: [u8; 32] = std::array::from_fn(|i| (i as u8).wrapping_mul(0x9d) ^ 0x5a);
414        let mut key = [0u8; 32];
415        Argon2::default()
416            .hash_password_into(passphrase.as_bytes(), &salt, &mut key)
417            .map_err(|e| anyhow!("argon2: {e}"))?;
418        let masked: Vec<u8> = key.iter().zip(&mask).map(|(k, m)| k ^ m).collect();
419        key.zeroize();
420        // The test's own derivation left the key in callee frames, like the manager's did.
421        scrub_stack();
422        let ciphertext = manager.encrypt(b"payload")?;
423        // encrypt leaves key-schedule temporaries in the frames it used; like the derivation
424        // above, they are stack residue of this thread, not state the manager owns.
425        scrub_stack();
426        #[cfg(target_arch = "x86_64")]
427        if std::is_x86_feature_detected!("aes") {
428            let mut live = false;
429            for _ in 0..20 {
430                if !heap_copies(&masked, &mask)?.is_empty() {
431                    live = true;
432                    break;
433                }
434                std::thread::sleep(std::time::Duration::from_millis(50));
435            }
436            assert!(
437                live,
438                "a live AES-NI cipher keeps round key 0 (the key) in its heap schedule"
439            );
440        }
441        drop(manager);
442        let survivors = heap_copies(&masked, &mask)?;
443        assert!(
444            survivors.is_empty(),
445            "derived key survives the manager's drop at {survivors:?}"
446        );
447        assert!(!ciphertext.is_empty());
448        Ok(())
449    }
450
451    #[test]
452    fn signature_verifies_only_the_signed_data() {
453        let dir = tempdir().unwrap();
454        let key_path = dir.path().join("test.key");
455        let mgr = SigningManager::new(&key_path).unwrap();
456
457        let data = b"hello world";
458        let sig = mgr.sign(data);
459        mgr.verify(data, &sig).unwrap();
460        assert!(mgr.verify(b"tampered", &sig).is_err());
461    }
462
463    #[test]
464    fn test_signing_key_persistence() {
465        let dir = tempdir().unwrap();
466        let key_path = dir.path().join("test.key");
467
468        let vk1 = {
469            let mgr = SigningManager::new(&key_path).unwrap();
470            mgr.verifying_key_bytes()
471        };
472        let vk2 = {
473            let mgr = SigningManager::new(&key_path).unwrap();
474            mgr.verifying_key_bytes()
475        };
476        assert_eq!(vk1, vk2, "Reloaded key should match");
477    }
478
479    #[test]
480    fn concurrent_identity_creation_converges_without_replacement() {
481        let directory = tempdir().unwrap();
482        let path = directory.path().join("nested/key");
483        let barrier = std::sync::Arc::new(std::sync::Barrier::new(8));
484        let keys: Vec<_> = std::thread::scope(|scope| {
485            let handles: Vec<_> = (0..8)
486                .map(|_| {
487                    let path = &path;
488                    let barrier = &barrier;
489                    scope.spawn(move || {
490                        barrier.wait();
491                        SigningManager::new(path).unwrap().verifying_key_bytes()
492                    })
493                })
494                .collect();
495            handles.into_iter().map(|h| h.join().unwrap()).collect()
496        });
497        assert!(keys.iter().all(|key| *key == keys[0]));
498        assert_eq!(
499            SigningManager::new(&path).unwrap().verifying_key_bytes(),
500            keys[0]
501        );
502        let before = std::fs::read(&path).unwrap();
503        assert!(!super::super::durable_file::atomic_create(&path, &[0; 32]).unwrap());
504        assert_eq!(std::fs::read(&path).unwrap(), before);
505    }
506
507    #[test]
508    fn concurrent_salt_creation_produces_interoperable_ciphertexts() {
509        let directory = tempdir().unwrap();
510        let barrier = std::sync::Arc::new(std::sync::Barrier::new(2));
511        let encrypted: Vec<_> = std::thread::scope(|scope| {
512            let handles: Vec<_> = (0..2)
513                .map(|_| {
514                    let directory = &directory;
515                    let barrier = &barrier;
516                    scope.spawn(move || {
517                        barrier.wait();
518                        EncryptionManager::new("shared", directory.path())
519                            .unwrap()
520                            .encrypt_with_aad(b"stored", b"domain")
521                            .unwrap()
522                    })
523                })
524                .collect();
525            handles.into_iter().map(|h| h.join().unwrap()).collect()
526        });
527        let reopened = EncryptionManager::new("shared", directory.path()).unwrap();
528        for ciphertext in &encrypted {
529            assert_eq!(
530                reopened.decrypt_with_aad(ciphertext, b"domain").unwrap(),
531                b"stored"
532            );
533            assert!(reopened
534                .decrypt_with_aad(ciphertext, b"other-domain")
535                .is_err());
536        }
537        assert_ne!(encrypted[0][..12], encrypted[1][..12]);
538    }
539
540    #[test]
541    fn identity_lengths_and_links_fail_without_rewriting_input() {
542        let directory = tempdir().unwrap();
543        let key = directory.path().join("key");
544        for size in [31, 32, 33, 1 << 20] {
545            let file = std::fs::File::create(&key).unwrap();
546            file.set_len(size).unwrap();
547            #[cfg(unix)]
548            {
549                use std::os::unix::fs::PermissionsExt;
550                file.set_permissions(std::fs::Permissions::from_mode(0o600))
551                    .unwrap();
552            }
553            assert_eq!(SigningManager::new(&key).is_ok(), size == 32);
554            assert_eq!(std::fs::metadata(&key).unwrap().len(), size);
555        }
556        let salt = directory.path().join("encryption.salt");
557        for size in [15, 16, 17] {
558            let file = std::fs::File::create(&salt).unwrap();
559            file.set_len(size).unwrap();
560            assert_eq!(read_fixed::<16>(&salt, false).is_ok(), size == 16);
561        }
562        std::fs::remove_file(&key).unwrap();
563        std::fs::create_dir(&key).unwrap();
564        assert!(SigningManager::new(&key).is_err());
565        #[cfg(unix)]
566        {
567            use std::os::unix::fs::{symlink, PermissionsExt};
568            std::fs::remove_dir(&key).unwrap();
569            symlink(&salt, &key).unwrap();
570            assert!(SigningManager::new(&key).is_err());
571            assert!(key.symlink_metadata().unwrap().file_type().is_symlink());
572            std::fs::remove_file(&key).unwrap();
573            std::fs::write(&key, [0; 32]).unwrap();
574            std::fs::set_permissions(&key, std::fs::Permissions::from_mode(0o644)).unwrap();
575            assert!(SigningManager::new(&key).is_err());
576        }
577    }
578
579    #[test]
580    fn identity_publication_crash_child() {
581        let Some(path) = crate::compatibility::var_os("WARM_IDENTITY_TEST_PATH") else {
582            return;
583        };
584        SigningManager::new(Path::new(&path)).unwrap();
585        panic!("expected publication interruption");
586    }
587
588    #[test]
589    fn identity_reopens_after_each_publication_interruption() {
590        for phase in ["synced", "published", "durable"] {
591            let directory = tempdir().unwrap();
592            let path = directory.path().join("key");
593            let output = std::process::Command::new(std::env::current_exe().unwrap())
594                .args([
595                    "--exact",
596                    "core::security::tests::identity_publication_crash_child",
597                ])
598                .env("WARM_IDENTITY_TEST_PATH", &path)
599                .env("WARM_IDENTITY_CRASH_AT", phase)
600                .output()
601                .unwrap();
602            assert_eq!(output.status.code(), Some(84), "{phase}: {output:?}");
603            let published = std::fs::read(&path).ok();
604            assert_eq!(published.is_some(), phase != "synced");
605            let manager = SigningManager::new(&path).unwrap();
606            if let Some(bytes) = published {
607                assert_eq!(std::fs::read(&path).unwrap(), bytes);
608            }
609            let next = SigningManager::new(&path).unwrap();
610            next.verify(b"recovered", &manager.sign(b"recovered"))
611                .unwrap();
612        }
613    }
614
615    #[test]
616    fn test_encryption_roundtrip() {
617        let dir = tempdir().unwrap();
618        let mgr = EncryptionManager::new("test-passphrase", dir.path()).unwrap();
619
620        let plaintext = b"sensitive data here";
621        let encrypted = mgr.encrypt(plaintext).unwrap();
622        assert_ne!(&encrypted[12..], plaintext);
623
624        let decrypted = mgr.decrypt(&encrypted).unwrap();
625        assert_eq!(decrypted, plaintext);
626    }
627
628    #[test]
629    fn test_encryption_salt_persistence() {
630        let dir = tempdir().unwrap();
631
632        let encrypted = {
633            let mgr = EncryptionManager::new("passphrase", dir.path()).unwrap();
634            mgr.encrypt(b"test data").unwrap()
635        };
636
637        let mgr = EncryptionManager::new("passphrase", dir.path()).unwrap();
638        let decrypted = mgr.decrypt(&encrypted).unwrap();
639        assert_eq!(decrypted, b"test data");
640    }
641
642    #[test]
643    fn test_encryption_wrong_passphrase() {
644        let dir = tempdir().unwrap();
645
646        let encrypted = {
647            let mgr = EncryptionManager::new("correct", dir.path()).unwrap();
648            mgr.encrypt(b"secret").unwrap()
649        };
650        let same_salt = EncryptionManager::new("wrong", dir.path()).unwrap();
651        assert!(same_salt.decrypt(&encrypted).is_err());
652
653        // A fresh salt derives yet another key.
654        std::fs::remove_file(dir.path().join("encryption.salt")).unwrap();
655        let mgr = EncryptionManager::new("wrong", dir.path()).unwrap();
656        assert!(mgr.decrypt(&encrypted).is_err());
657    }
658
659    #[test]
660    fn test_hash_id_deterministic() {
661        let h1 = hash_id("test-id");
662        let h2 = hash_id("test-id");
663        assert_eq!(h1, h2);
664        assert_ne!(hash_id("other"), h1);
665    }
666}