cryptex 3.0.0

Store and retrieve secrets in OS keyrings, encrypted SQLite or Turso files, in-memory and browser keyrings, or under a YubiHSM 2 or Nitrokey 3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
/*
    Copyright Michael Lodder. All Rights Reserved.
    SPDX-License-Identifier: Apache-2.0
*/
use super::*;
use rusqlite::{Connection, OpenFlags};
use sqlite_plugin::flags::{AccessFlags, LockLevel, OpenKind, OpenOpts};
use sqlite_plugin::vfs::{RegisterOpts, Vfs, VfsHandle, VfsResult, register_static};
use std::ffi::CString;
use std::fs::{self, File};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, Mutex, RwLock};
use zeroize::Zeroizing;

use super::file_common::{
    acquire_single_opener_lock, file_keyring, get_keyring_file, private_open_options, sibling_path,
    sync_parent_dir,
};
use super::page_cipher::{ActiveCipher, LOGICAL_PAGE_SIZE, PageFile, logical_size, truncate};
use super::page_header::{HEADER_SIZE, open_or_create};
use super::sqlite_common::{KEYRING_FILE, init_schema, lock_connection};
use crate::error::KeyRingError;

pub use super::cipher::PageCipher as CipherAlgorithm;

/// Connection parameters for [`EncryptedVfsKeyring`].
///
/// Accepted format:
/// ```text
/// password=mysecret [cipher=xchacha20poly1305|aes256gcm]
/// ```
///
/// The salt is generated and stored in the keyring file's header with the
/// cipher and costs, so reopening needs only the password (or `key=`).
pub type ConnectionParams = file_common::ConnectionParams<CipherAlgorithm>;

static VFS_COUNTER: AtomicU32 = AtomicU32::new(0);

// ─── VFS state ────────────────────────────────────────────────────────────────

/// A SQLite VFS that encrypts every page with the current cipher. The cipher
/// sits behind a lock so `rekey` can rotate it under the open connection.
#[derive(Clone)]
pub(crate) struct EncryptedVfs {
    cipher: Arc<RwLock<ActiveCipher>>,
}

impl EncryptedVfs {
    fn new(cipher: ActiveCipher) -> Self {
        Self {
            cipher: Arc::new(RwLock::new(cipher)),
        }
    }

    fn rotate(&self, cipher: ActiveCipher) -> Result<()> {
        *self.cipher.write().map_err(|_| vfs_poisoned())? = cipher;
        Ok(())
    }
}

fn vfs_poisoned() -> KeyRingError {
    KeyRingError::GeneralError {
        msg: "VFS state lock poisoned".to_string(),
    }
}

// ─── File handle ──────────────────────────────────────────────────────────────

pub(crate) struct EncryptedHandle {
    file: File,
    layout: PageFile,
    delete_on_close: bool,
    path: PathBuf,
}

impl VfsHandle for EncryptedHandle {
    fn readonly(&self) -> bool {
        false
    }
    fn in_memory(&self) -> bool {
        false
    }
}

// ─── Vfs implementation ───────────────────────────────────────────────────────

impl Vfs for EncryptedVfs {
    type Handle = EncryptedHandle;

    fn open(&self, path: Option<&str>, opts: OpenOpts) -> VfsResult<Self::Handle> {
        let is_readonly = opts.mode().is_readonly();
        let mut file_opts = private_open_options();
        file_opts.read(true);

        let path = match path {
            Some(p) => {
                file_opts
                    .write(!is_readonly)
                    .create(!is_readonly)
                    .truncate(false);
                PathBuf::from(p)
            }
            None => {
                // Unpredictable name + O_EXCL (`create_new`) + 0600 defeats symlink
                // and pre-creation attacks on the shared temp directory.
                let mut rand = [0u8; 16];
                getrandom::fill(&mut rand).map_err(|_| sqlite_plugin::vars::SQLITE_CANTOPEN)?;
                file_opts.write(true).create_new(true);
                std::env::temp_dir().join(format!(
                    "cryptex-tmp-{}-{}-{}.db",
                    std::process::id(),
                    VFS_COUNTER.fetch_add(1, Ordering::Relaxed),
                    hex::encode(rand)
                ))
            }
        };
        let file = file_opts
            .open(&path)
            .map_err(|_| sqlite_plugin::vars::SQLITE_CANTOPEN)?;

        Ok(EncryptedHandle {
            file,
            layout: layout(opts.kind()),
            delete_on_close: opts.delete_on_close(),
            path,
        })
    }

    fn close(&self, handle: Self::Handle) -> VfsResult<()> {
        if handle.delete_on_close {
            let _ = fs::remove_file(&handle.path);
        }
        Ok(())
    }

    fn delete(&self, path: &str) -> VfsResult<()> {
        fs::remove_file(path).map_err(|_| sqlite_plugin::vars::SQLITE_IOERR_DELETE)
    }

    fn access(&self, path: &str, _flags: AccessFlags) -> VfsResult<bool> {
        Ok(Path::new(path).exists())
    }

    fn file_size(&self, handle: &mut Self::Handle) -> VfsResult<usize> {
        logical_size(&handle.file, handle.layout)
            .map(|n| n as usize)
            .map_err(|_| sqlite_plugin::vars::SQLITE_IOERR_FSTAT)
    }

    fn truncate(&self, handle: &mut Self::Handle, logical_size: usize) -> VfsResult<()> {
        truncate(&mut handle.file, handle.layout, logical_size)
            .map_err(|_| sqlite_plugin::vars::SQLITE_IOERR_TRUNCATE)
    }

    fn read(&self, handle: &mut Self::Handle, offset: usize, data: &mut [u8]) -> VfsResult<usize> {
        self.cipher
            .read()
            .map_err(|_| sqlite_plugin::vars::SQLITE_IOERR_READ)?
            .read_at(&mut handle.file, handle.layout, offset, data)
            .map_err(|_| sqlite_plugin::vars::SQLITE_IOERR_READ)
    }

    fn write(&self, handle: &mut Self::Handle, offset: usize, data: &[u8]) -> VfsResult<usize> {
        self.cipher
            .read()
            .map_err(|_| sqlite_plugin::vars::SQLITE_IOERR_WRITE)?
            .write_at(&mut handle.file, handle.layout, offset, data)
            .map_err(|_| sqlite_plugin::vars::SQLITE_IOERR_WRITE)
    }

    fn sync(&self, handle: &mut Self::Handle) -> VfsResult<()> {
        handle
            .file
            .sync_all()
            .map_err(|_| sqlite_plugin::vars::SQLITE_IOERR_FSYNC)
    }

    fn lock(&self, _handle: &mut Self::Handle, _level: LockLevel) -> VfsResult<()> {
        Ok(())
    }

    fn unlock(&self, _handle: &mut Self::Handle, _level: LockLevel) -> VfsResult<()> {
        Ok(())
    }

    fn check_reserved_lock(&self, _handle: &mut Self::Handle) -> VfsResult<bool> {
        Ok(false)
    }
}

/// The page layout for a file SQLite opens: only the database itself starts
/// with the keyring header.
fn layout(kind: OpenKind) -> PageFile {
    match kind {
        OpenKind::MainDb => PageFile::main(HEADER_SIZE),
        OpenKind::MainJournal | OpenKind::Wal | OpenKind::SubJournal | OpenKind::SuperJournal => {
            PageFile::JOURNAL
        }
        OpenKind::TempDb | OpenKind::TempJournal | OpenKind::TransientDb | OpenKind::Unknown => {
            PageFile::TEMP
        }
    }
}

// ─── VFS registration ─────────────────────────────────────────────────────────

fn register_encrypted_vfs(vfs: EncryptedVfs) -> Result<String> {
    let name = format!(
        "cryptex-evfs-{}",
        VFS_COUNTER.fetch_add(1, Ordering::Relaxed)
    );
    let cname = CString::new(name.as_str())
        .map_err(|e| KeyRingError::GeneralError { msg: e.to_string() })?;
    register_static(
        cname,
        vfs,
        RegisterOpts {
            make_default: false,
        },
    )
    .map_err(|e| KeyRingError::GeneralError {
        msg: format!("VFS registration failed (code {})", e),
    })?;
    Ok(name)
}

// ─── EncryptedVfsKeyring ──────────────────────────────────────────────────────

/// A keyring stored in a bundled SQLite database whose pages are encrypted
/// by a custom VFS. The default file is `~/.cryptex/keyring.db3`.
pub struct EncryptedVfsKeyring {
    /// `Connection` is `Send` but not `Sync`; the mutex makes the keyring
    /// `Sync` and lets `rekey` swap the connection through `&self`.
    conn: Mutex<Connection>,
    vfs: EncryptedVfs,
    vfs_name: String,
    db_path: PathBuf,
    /// Exclusive advisory lock on a sidecar file, held for the keyring's
    /// lifetime. Guarantees a single opener: the encrypted VFS performs no
    /// SQLite-level locking, so concurrent opens would otherwise corrupt the
    /// database. Released automatically when the keyring is dropped. A sidecar
    /// (not the db file) is locked so the lock survives `rekey`'s atomic rename.
    _lock: File,
}

file_keyring!(EncryptedVfsKeyring, conn);

impl EncryptedVfsKeyring {
    /// Open (or create) the keyring in `path` (default `~/.cryptex`).
    pub fn with_params(connection: &ConnectionParams, path: Option<PathBuf>) -> Result<Self> {
        let db_path = get_keyring_file(path, KEYRING_FILE)?;

        // Fail fast if another opener already holds the keyring, before touching
        // the database. The encrypted VFS does no SQLite-level locking.
        let lock = acquire_single_opener_lock(&db_path)?;
        let vfs = EncryptedVfs::new(open_or_create(&db_path, connection)?);
        let vfs_name = register_encrypted_vfs(vfs.clone())?;
        let conn = open_connection(&db_path, &vfs_name)?;

        Ok(Self {
            conn: Mutex::new(conn),
            vfs,
            vfs_name,
            db_path,
            _lock: lock,
        })
    }

    /// Re-encrypt the database with a new key (and optionally a different cipher).
    ///
    /// Writes to a temp file first, then atomically renames — original is
    /// untouched until the rename succeeds. The connection is closed before
    /// the rename and reopened on the rekeyed file, so the keyring stays
    /// usable afterwards. The connection lock is held throughout, so no other
    /// thread can write while pages are being copied.
    pub fn rekey(&self, new_params: &ConnectionParams) -> Result<()> {
        let mut conn = lock_connection(&self.conn)?;
        let page_count: u32 = conn.pragma_query_value(None, "page_count", |row| row.get(0))?;

        // The temp file gets its own header: a fresh salt and file id, and
        // the new cipher and costs.
        let tmp_path = self.db_path.with_extension("cryptex-rekey-tmp");
        match fs::remove_file(&tmp_path) {
            Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e.into()),
            _ => {}
        }
        let new_cipher = open_or_create(&tmp_path, new_params)?;
        if let Err(e) = self.reencrypt_into(&tmp_path, &new_cipher, page_count as usize) {
            let _ = fs::remove_file(&tmp_path);
            return Err(e);
        }

        // Close the connection before replacing the file: its handle would
        // otherwise keep pointing at the old file (and Windows refuses to
        // rename over an open file).
        *conn = Connection::open_in_memory()?;

        // A clean close deletes the rollback journal. One that is still here
        // is from an interrupted write, and SQLite would replay it onto the
        // rekeyed file under the wrong key.
        if sibling_path(&self.db_path, "-journal").exists() {
            let _ = fs::remove_file(&tmp_path);
            *conn = open_connection(&self.db_path, &self.vfs_name)?;
            return Err(KeyRingError::GeneralError {
                msg: "the keyring has an unfinished write; reopen it and try the rekey again"
                    .to_string(),
            });
        }

        if let Err(e) = fs::rename(&tmp_path, &self.db_path) {
            let _ = fs::remove_file(&tmp_path);
            *conn = open_connection(&self.db_path, &self.vfs_name)?;
            return Err(KeyRingError::GeneralError {
                msg: format!("unable to replace keyring file: {}", e),
            });
        }

        sync_parent_dir(&self.db_path)?;
        self.vfs.rotate(new_cipher)?;
        *conn = open_connection(&self.db_path, &self.vfs_name)?;

        Ok(())
    }

    /// Copy the first `page_count` pages of the database into `dst_path`,
    /// decrypting with the current cipher and encrypting with `new_cipher`.
    fn reencrypt_into(
        &self,
        dst_path: &Path,
        new_cipher: &ActiveCipher,
        page_count: usize,
    ) -> Result<()> {
        let main = PageFile::main(HEADER_SIZE);
        let mut src = File::open(&self.db_path)?;
        // `dst_path` already holds its header, so it is not truncated.
        let mut dst = private_open_options().write(true).open(dst_path)?;
        let cipher = self.vfs.cipher.read().map_err(|_| vfs_poisoned())?;
        let mut page = Zeroizing::new([0u8; LOGICAL_PAGE_SIZE]);
        for offset in (0..page_count).map(|n| n * LOGICAL_PAGE_SIZE) {
            cipher.read_at(&mut src, main, offset, &mut *page)?;
            new_cipher.write_at(&mut dst, main, offset, &*page)?;
        }
        dst.sync_all()?;
        Ok(())
    }
}

impl Drop for EncryptedVfsKeyring {
    /// SQLite keeps every registered VFS for the life of the process, so the
    /// cipher is swapped for a throwaway key once the connection is closed.
    /// The old cipher's key schedule is zeroized when it is dropped.
    fn drop(&mut self) {
        let Ok(conn) = self.conn.get_mut() else {
            return;
        };
        // Closing first matters: the connection may still flush pages, and
        // they must be written under the real key.
        let Ok(closed) = Connection::open_in_memory() else {
            return;
        };
        *conn = closed;
        let _ = self.vfs.rotate(ActiveCipher::from_key(
            CipherAlgorithm::default(),
            &[0u8; 32],
            [0u8; 32],
        ));
    }
}

/// Open the keyring database through the registered encrypted VFS, verify the
/// key can read it, and ensure the `secrets` table exists.
fn open_connection(db_path: &Path, vfs_name: &str) -> Result<Connection> {
    let conn = Connection::open_with_flags_and_vfs(
        db_path,
        OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_CREATE,
        vfs_name,
    )?;
    init_schema(&conn)?;
    Ok(conn)
}

// ─── Tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::{CipherAlgorithm, ConnectionParams, EncryptedVfs, EncryptedVfsKeyring};
    use crate::KeyRing;
    use crate::file_common::test_support::TestDir;
    use std::fs::File;

    fn params(s: &str) -> ConnectionParams {
        s.parse().unwrap()
    }

    #[test]
    fn works() {
        let dir = TestDir::new(".test-evfs-works");

        let p = params("password=works_test salt=1qaz2wsx3edc4rfv5tgb");

        {
            let res = EncryptedVfsKeyring::with_params(&p, dir.keyring_dir());
            assert!(res.is_ok(), "open failed: {:?}", res.err());
            let mut kr = res.unwrap();

            assert!(kr.set_secret("k1", b"value1").is_ok());
            let got = kr.get_secret("k1").unwrap();
            assert_eq!(got.0, b"value1");

            assert!(kr.delete_secret("k1").is_ok());
            assert!(kr.get_secret("k1").is_err());

            assert!(kr.set_secret("persist", b"persisted").is_ok());
        }

        {
            let mut kr = EncryptedVfsKeyring::with_params(&p, dir.keyring_dir()).unwrap();
            let got = kr.get_secret("persist").unwrap();
            assert_eq!(got.0, b"persisted");
        }
    }

    #[test]
    fn drop_wipes_the_vfs_key() {
        let dir = TestDir::new(".test-evfs-drop-wipe");
        let p = params("password=drop_wipe_test salt=1qaz2wsx3edc4rfv5tgb");

        let mut kr = EncryptedVfsKeyring::with_params(&p, dir.keyring_dir()).unwrap();
        kr.set_secret("k", b"v").unwrap();
        // SQLite keeps the registered VFS alive after the keyring is gone;
        // this clone shares its cipher.
        let vfs = kr.vfs.clone();
        let db_path = kr.db_path.clone();
        let reads_file = |vfs: &EncryptedVfs| {
            let mut file = File::open(&db_path).unwrap();
            let cipher = vfs.cipher.read().unwrap();
            cipher
                .read_at(
                    &mut file,
                    super::PageFile::main(super::HEADER_SIZE),
                    0,
                    &mut [0u8; 16],
                )
                .is_ok()
        };
        assert!(reads_file(&vfs));

        drop(kr);
        assert!(
            !reads_file(&vfs),
            "the dropped keyring's VFS still holds its key"
        );

        let mut kr = EncryptedVfsKeyring::with_params(&p, dir.keyring_dir()).unwrap();
        assert_eq!(kr.get_secret("k").unwrap().0, b"v");
    }

    #[test]
    fn header_decides_cipher_and_salt_on_reopen() {
        let dir = TestDir::new(".test-evfs-header");
        let created = params("password=header_test cipher=aes256gcm");
        {
            let mut kr = EncryptedVfsKeyring::with_params(&created, dir.keyring_dir()).unwrap();
            kr.set_secret("k", b"header-secret").unwrap();
        }

        let raw = std::fs::read(dir.join(super::KEYRING_FILE)).unwrap();
        assert_eq!(&raw[..8], b"CRYPTEXP");
        assert!(!raw.windows(13).any(|w| w == b"header-secret"));
        assert!(!raw.windows(13).any(|w| w == b"SQLite format"));

        // Only the password is needed: the stored header supplies the
        // cipher, salt and costs, whatever the connection string says.
        let mut kr =
            EncryptedVfsKeyring::with_params(&params("password=header_test"), dir.keyring_dir())
                .unwrap();
        assert_eq!(kr.get_secret("k").unwrap().0, b"header-secret");
    }

    #[test]
    fn edited_header_breaks_the_keyring() {
        let dir = TestDir::new(".test-evfs-header-edit");
        let p = params("password=edit_test");
        {
            let mut kr = EncryptedVfsKeyring::with_params(&p, dir.keyring_dir()).unwrap();
            kr.set_secret("k", b"v").unwrap();
        }
        let path = dir.join(super::KEYRING_FILE);
        let mut raw = std::fs::read(&path).unwrap();
        // Flip a bit in the stored file id.
        raw[60] ^= 1;
        std::fs::write(&path, raw).unwrap();
        assert!(EncryptedVfsKeyring::with_params(&p, dir.keyring_dir()).is_err());
    }

    #[test]
    fn raw_key_keyring_round_trips() {
        let dir = TestDir::new(".test-evfs-raw-key");
        let p = params(&format!("key={}", "5a".repeat(32)));
        {
            let mut kr = EncryptedVfsKeyring::with_params(&p, dir.keyring_dir()).unwrap();
            kr.set_secret("k", b"v").unwrap();
        }
        let mut kr = EncryptedVfsKeyring::with_params(&p, dir.keyring_dir()).unwrap();
        assert_eq!(kr.get_secret("k").unwrap().0, b"v");
        drop(kr);
        let pw = params("password=not_the_key");
        assert!(EncryptedVfsKeyring::with_params(&pw, dir.keyring_dir()).is_err());
    }

    #[test]
    fn rekey_refuses_to_run_over_a_leftover_journal() {
        let dir = TestDir::new(".test-evfs-rekey-journal");
        let p = params("password=journal_test");
        let mut kr = EncryptedVfsKeyring::with_params(&p, dir.keyring_dir()).unwrap();
        kr.set_secret("k", b"v").unwrap();
        // An empty journal is not replayed, so the keyring stays usable.
        let journal = dir.join(format!("{}-journal", super::KEYRING_FILE));
        File::create(&journal).unwrap();

        let err = kr.rekey(&params("password=new_journal_test")).unwrap_err();
        assert!(err.to_string().contains("unfinished write"), "{err}");
        assert_eq!(kr.get_secret("k").unwrap().0, b"v");

        std::fs::remove_file(&journal).unwrap();
        kr.rekey(&params("password=new_journal_test")).unwrap();
        assert_eq!(kr.get_secret("k").unwrap().0, b"v");
    }

    #[test]
    fn concurrent_open_is_rejected() {
        let dir = TestDir::new(".test-evfs-concurrent");

        let p = params("password=concurrent_test salt=1qaz2wsx3edc4rfv5tgb");

        let first = EncryptedVfsKeyring::with_params(&p, dir.keyring_dir()).unwrap();

        // A second opener must be rejected while the first is alive.
        let second = EncryptedVfsKeyring::with_params(&p, dir.keyring_dir());
        assert!(
            matches!(second, Err(crate::error::KeyRingError::AccessDenied { .. })),
            "expected AccessDenied for concurrent open, got: {:?}",
            second.err()
        );

        // After the first is dropped, the lock releases and reopening succeeds.
        drop(first);
        let reopened = EncryptedVfsKeyring::with_params(&p, dir.keyring_dir());
        assert!(
            reopened.is_ok(),
            "reopen after drop failed: {:?}",
            reopened.err()
        );
    }

    #[test]
    fn wrong_key_fails() {
        let dir = TestDir::new(".test-evfs-wrongkey");

        let correct = params("password=correct_password salt=1qaz2wsx3edc4rfv5tgb");
        let wrong = params("password=wrong_password salt=1qaz2wsx3edc4rfv5tgb");

        {
            let mut kr = EncryptedVfsKeyring::with_params(&correct, dir.keyring_dir()).unwrap();
            kr.set_secret("x", b"secret").unwrap();
        }

        {
            let result = EncryptedVfsKeyring::with_params(&wrong, dir.keyring_dir());
            assert!(result.is_err(), "expected error with wrong key");
        }
    }

    #[test]
    fn invalid_hex_key_is_an_error() {
        let result = "key=not-hex".parse::<ConnectionParams>();
        assert!(result.is_err());
    }

    #[test]
    fn rekey_works() {
        let dir = TestDir::new(".test-evfs-rekey");

        let old_params = params("password=old_pass salt=old_salt_value_here_");
        let new_params = params("password=new_pass salt=new_salt_value_here_");

        {
            let mut kr = EncryptedVfsKeyring::with_params(&old_params, dir.keyring_dir()).unwrap();
            kr.set_secret("data", b"important").unwrap();
            kr.rekey(&new_params).unwrap();
        }

        {
            let mut kr = EncryptedVfsKeyring::with_params(&new_params, dir.keyring_dir()).unwrap();
            assert_eq!(kr.get_secret("data").unwrap().0, b"important");
        }

        {
            let result = EncryptedVfsKeyring::with_params(&old_params, dir.keyring_dir());
            assert!(result.is_err(), "old key should fail after rekey");
        }
    }

    #[test]
    fn rekey_allows_continued_use_on_same_connection() {
        let dir = TestDir::new(".test-evfs-rekey-continue");

        let old_params = params("password=old_pass salt=old_salt_value_here_");
        let new_params = params("password=new_pass salt=new_salt_value_here_ cipher=aes256gcm");

        {
            let mut kr = EncryptedVfsKeyring::with_params(&old_params, dir.keyring_dir()).unwrap();
            for i in 0..50 {
                kr.set_secret(format!("before_{i}"), format!("value_{i}"))
                    .unwrap();
            }
            kr.rekey(&new_params).unwrap();

            // Reads, writes and deletes on the same keyring must hit the
            // rekeyed file, not the replaced one.
            for i in 0..50 {
                kr.set_secret(format!("after_{i}"), format!("value_{i}"))
                    .unwrap();
            }
            assert_eq!(kr.get_secret("before_7").unwrap().0, b"value_7");
            kr.delete_secret("before_0").unwrap();
        }

        {
            let mut kr = EncryptedVfsKeyring::with_params(&new_params, dir.keyring_dir()).unwrap();
            assert!(kr.get_secret("before_0").is_err());
            for i in 1..50 {
                assert_eq!(
                    kr.get_secret(format!("before_{i}")).unwrap().0,
                    format!("value_{i}").as_bytes()
                );
            }
            for i in 0..50 {
                assert_eq!(
                    kr.get_secret(format!("after_{i}")).unwrap().0,
                    format!("value_{i}").as_bytes()
                );
            }
        }

        assert!(EncryptedVfsKeyring::with_params(&old_params, dir.keyring_dir()).is_err());
    }

    #[test]
    fn rekey_through_shared_reference_on_another_thread() {
        let dir = TestDir::new(".test-evfs-rekey-shared");

        let old_params = params("password=old_pass salt=old_salt_value_here_");
        let new_params = params("password=new_pass salt=new_salt_value_here_");

        let mut kr = EncryptedVfsKeyring::with_params(&old_params, dir.keyring_dir()).unwrap();
        kr.set_secret("shared", b"value").unwrap();

        let kr = std::sync::Arc::new(kr);
        let worker = std::sync::Arc::clone(&kr);
        std::thread::spawn(move || worker.rekey(&new_params))
            .join()
            .unwrap()
            .unwrap();

        let mut kr = std::sync::Arc::try_unwrap(kr).ok().unwrap();
        assert_eq!(kr.get_secret("shared").unwrap().0, b"value");
        drop(kr);

        assert!(EncryptedVfsKeyring::with_params(&old_params, dir.keyring_dir()).is_err());
    }

    #[test]
    fn bulk_insert_and_retrieve() {
        let dir = TestDir::new(".test-evfs-bulk");

        let p = params("password=bulk_test salt=bulk_salt_value_here_");

        let entries: Vec<(String, Vec<u8>)> = (0..50)
            .map(|i| {
                (
                    format!("key_{:02}", i),
                    format!("value_{:06}", i).into_bytes(),
                )
            })
            .collect();

        {
            let mut kr = EncryptedVfsKeyring::with_params(&p, dir.keyring_dir()).unwrap();
            for (k, v) in &entries {
                kr.set_secret(k, v).unwrap();
            }
        }

        {
            let mut kr = EncryptedVfsKeyring::with_params(&p, dir.keyring_dir()).unwrap();
            for (k, v) in &entries {
                let got = kr.get_secret(k).unwrap();
                assert_eq!(&got.0, v, "mismatch for {k}");
            }
        }
    }

    #[test]
    fn aes_bulk_insert_and_retrieve() {
        let dir = TestDir::new(".test-evfs-aes-bulk");

        let p = params("password=aes_bulk_test salt=aes_bulk_salt_here_ cipher=aes256gcm");
        assert_eq!(p.cipher, CipherAlgorithm::Aes256Gcm);

        let entries: Vec<(String, Vec<u8>)> = (0..50)
            .map(|i| {
                (
                    format!("key_{:02}", i),
                    format!("value_{:06}", i).into_bytes(),
                )
            })
            .collect();

        {
            let mut kr = EncryptedVfsKeyring::with_params(&p, dir.keyring_dir()).unwrap();
            for (k, v) in &entries {
                kr.set_secret(k, v).unwrap();
            }
        }

        {
            let mut kr = EncryptedVfsKeyring::with_params(&p, dir.keyring_dir()).unwrap();
            for (k, v) in &entries {
                let got = kr.get_secret(k).unwrap();
                assert_eq!(&got.0, v, "mismatch for {k}");
            }
        }
    }
}