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
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
/*
    Copyright Michael Lodder. All Rights Reserved.
    SPDX-License-Identifier: Apache-2.0
*/
//! Pieces shared by every file-backed keyring: connection-string parsing,
//! password key derivation (Argon2id, or PBKDF2-HMAC-SHA256 in `fips`
//! builds), and keyring file/directory helpers.

use super::*;
#[cfg(not(feature = "fips"))]
use argon2::{Algorithm, Argon2, Params as Argon2Params, Version};

use crate::error::KeyRingError;
#[cfg(any(
    feature = "file",
    feature = "encrypted-vfs",
    feature = "turso",
    feature = "turso-encrypted-io"
))]
use std::fs;
#[cfg(any(
    feature = "file",
    feature = "encrypted-vfs",
    feature = "turso",
    feature = "turso-encrypted-io"
))]
use std::fs::OpenOptions;
#[cfg(any(
    feature = "encrypted-vfs",
    feature = "turso",
    feature = "turso-encrypted-io"
))]
use std::fs::{File, TryLockError};
use std::iter;
#[cfg(any(
    feature = "file",
    feature = "encrypted-vfs",
    feature = "turso",
    feature = "turso-encrypted-io"
))]
use std::path::{Path, PathBuf};
use std::str::FromStr;
use zeroize::{Zeroize, Zeroizing};

#[cfg(any(
    feature = "file",
    feature = "encrypted-vfs",
    feature = "turso",
    feature = "turso-encrypted-io"
))]
// SQL shared by every file-backed keyring. Numbered parameters and
// `excluded.value` work with both SQLite and Turso.
pub(crate) const VERIFY_KEY_SQL: &str = "SELECT COUNT(*) FROM sqlite_master";
#[cfg(any(
    feature = "file",
    feature = "encrypted-vfs",
    feature = "turso",
    feature = "turso-encrypted-io"
))]
pub(crate) const CREATE_SECRETS_SQL: &str =
    "CREATE TABLE IF NOT EXISTS secrets (id TEXT UNIQUE NOT NULL, value TEXT NOT NULL)";
#[cfg(any(
    feature = "file",
    feature = "encrypted-vfs",
    feature = "turso",
    feature = "turso-encrypted-io"
))]
pub(crate) const SELECT_SECRET_SQL: &str = "SELECT value FROM secrets WHERE id = ?1";
#[cfg(any(
    feature = "file",
    feature = "encrypted-vfs",
    feature = "turso",
    feature = "turso-encrypted-io"
))]
pub(crate) const UPSERT_SECRET_SQL: &str = "INSERT INTO secrets(id, value) VALUES(?1, ?2) \
     ON CONFLICT(id) DO UPDATE SET value = excluded.value";
#[cfg(any(
    feature = "file",
    feature = "encrypted-vfs",
    feature = "turso",
    feature = "turso-encrypted-io"
))]
pub(crate) const DELETE_SECRET_SQL: &str = "DELETE FROM secrets WHERE id = ?1";
#[cfg(any(
    feature = "file",
    feature = "encrypted-vfs",
    feature = "turso",
    feature = "turso-encrypted-io"
))]
pub(crate) const SELECT_IDS_SQL: &str = "SELECT id FROM secrets ORDER BY id";

#[cfg(any(
    feature = "file",
    feature = "encrypted-vfs",
    feature = "turso",
    feature = "turso-encrypted-io"
))]
/// Storage behind a file-backed keyring. Secrets are stored hex-encoded.
pub(crate) trait SecretStore {
    /// Fetch the secret stored under `id`.
    fn get(&self, id: &str) -> Result<KeyRingSecret>;
    /// Insert or replace the secret stored under `id`.
    fn set(&self, id: &str, secret: &[u8]) -> Result<()>;
    /// Remove the secret stored under `id`, if any.
    fn delete(&self, id: &str) -> Result<()>;
    /// Every id in the store, in order.
    fn ids(&self) -> Result<Vec<String>>;
}

#[cfg(any(
    feature = "file",
    feature = "encrypted-vfs",
    feature = "turso",
    feature = "turso-encrypted-io",
))]
/// Decode a stored hex value, or report [`KeyRingError::ItemNotFound`].
pub(crate) fn decode_secret(value: Option<Zeroizing<String>>) -> Result<KeyRingSecret> {
    let value = value.ok_or(KeyRingError::ItemNotFound)?;
    hex::decode(value.as_str())
        .map(KeyRingSecret)
        .map_err(|e| KeyRingError::GeneralError {
            msg: format!("corrupt secret encoding: {}", e),
        })
}

#[cfg(any(
    feature = "file",
    feature = "encrypted-vfs",
    feature = "turso",
    feature = "turso-encrypted-io",
))]
/// The error for a database the derived key cannot read.
pub(crate) fn invalid_key() -> KeyRingError {
    KeyRingError::AccessDenied {
        msg: "Invalid key or corrupted database".to_string(),
    }
}

/// Implements [`DynKeyRing`] by delegating to the [`SecretStore`] in field
/// `$store`, and [`NewKeyRing`] by parsing the calling module's
/// `ConnectionParams` and calling `with_params(&params, None)`.
#[allow(unused_macros)]
macro_rules! file_keyring {
    ($keyring:ty, $store:ident) => {
        impl $crate::DynKeyRing for $keyring {
            fn get_secret(&mut self, id: &str) -> $crate::Result<$crate::KeyRingSecret> {
                $crate::file_common::SecretStore::get(&self.$store, id)
            }

            fn set_secret(&mut self, id: &str, secret: &[u8]) -> $crate::Result<()> {
                $crate::file_common::SecretStore::set(&self.$store, id, secret)
            }

            fn delete_secret(&mut self, id: &str) -> $crate::Result<()> {
                $crate::file_common::SecretStore::delete(&self.$store, id)
            }
        }

        impl $keyring {
            /// Every id in the keyring, in order.
            pub fn keys(&self) -> $crate::Result<Vec<String>> {
                $crate::file_common::SecretStore::ids(&self.$store)
            }
        }

        impl $crate::NewKeyRing for $keyring {
            fn new<S: AsRef<str>>(lock_key: S) -> $crate::Result<Self> {
                let params = lock_key.as_ref().parse::<ConnectionParams>()?;
                Self::with_params(&params, None)
            }
        }
    };
}
// Only the backends that own a `SecretStore` use the macro.
#[cfg(any(
    feature = "file",
    feature = "encrypted-vfs",
    feature = "turso-encrypted-io",
    feature = "yubihsm-usb",
    feature = "yubihsm-http"
))]
pub(crate) use file_keyring;

/// A cipher choice that can be set with `cipher=<name>` in a connection string.
pub trait CipherParam: Copy + Default + Zeroize {
    /// Parse the value of a `cipher=` connection parameter.
    fn parse(value: &str) -> Result<Self>;
}

/// Placeholder cipher for keyrings whose cipher is not configurable.
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, Zeroize)]
pub struct NoCipher;

impl CipherParam for NoCipher {
    fn parse(_value: &str) -> Result<Self> {
        Err(KeyRingError::GeneralError {
            msg: "cipher is not configurable for this keyring".to_string(),
        })
    }
}

/// The connection params for file-backed keyrings
///
/// [`ConnectionParams`] supports passing the values as a string
/// similar to postgres.
///
/// ```
/// use cryptex::file_common::ConnectionParams;
///
/// let params = "password=1qaz2wsx3edc4rfv salt=0okm9ijn8uhb7ygv".parse::<ConnectionParams>().unwrap();
/// ```
///
/// or with extra parameters. `memory` is Argon2's memory cost in KiB blocks.
/// A `fips` build takes `iterations` for PBKDF2 instead of the Argon2 costs.
///
/// ```
/// use cryptex::file_common::ConnectionParams;
///
/// # #[cfg(not(feature = "fips"))]
/// let params = "password=1qaz2wsx3edc4rfv salt=0okm9ijn8uhb7ygv memory=32768 threads=3 parallel=2".parse::<ConnectionParams>().unwrap();
/// # #[cfg(feature = "fips")]
/// let params = "password=1qaz2wsx3edc4rfv salt=0okm9ijn8uhb7ygv iterations=700000".parse::<ConnectionParams>().unwrap();
/// ```
#[derive(Zeroize)]
pub struct ConnectionParams<C: CipherParam = NoCipher> {
    /// The key used to open the keyring. This is used mutually exclusive
    /// with password and salt
    pub key: Vec<u8>,
    /// The password to use to open the keyring
    pub password: Vec<u8>,
    /// The salt to use when hashing the password
    pub salt: Vec<u8>,
    /// The Argon2 memory cost in KiB blocks
    pub memory: u32,
    /// The number of iterations or threads requirement
    pub threads: u32,
    /// The parallel requirement
    pub parallel: u32,
    /// The PBKDF2-HMAC-SHA256 iteration count, used instead of Argon2 in
    /// `fips` builds
    #[cfg(feature = "fips")]
    pub iterations: u32,
    /// The cipher used to encrypt the keyring, if the keyring supports a choice
    pub cipher: C,
}

impl<C: CipherParam> Default for ConnectionParams<C> {
    fn default() -> Self {
        Self {
            key: vec![],
            password: vec![],
            salt: vec![],
            memory: default_memory_cost(),
            threads: default_threads(),
            parallel: default_parallel(),
            #[cfg(feature = "fips")]
            iterations: default_iterations(),
            cipher: C::default(),
        }
    }
}

impl<C: CipherParam> Drop for ConnectionParams<C> {
    fn drop(&mut self) {
        self.key.zeroize();
        self.password.zeroize();
        self.salt.zeroize();
    }
}

impl<C: CipherParam> FromStr for ConnectionParams<C> {
    type Err = KeyRingError;

    fn from_str(s: &str) -> Result<Self> {
        Parser::parse(s)
    }
}

impl<C: CipherParam> ConnectionParams<C> {
    fn param(&mut self, key: &str, value: &str) -> Result<()> {
        match key {
            "key" => {
                self.key = hex::decode(value).map_err(|_| KeyRingError::GeneralError {
                    msg: "invalid hex key".to_string(),
                })?
            }
            "password" => self.password = value.as_bytes().to_vec(),
            "salt" => self.salt = value.as_bytes().to_vec(),
            "cipher" => self.cipher = C::parse(value)?,
            #[cfg(not(feature = "fips"))]
            "memory" => {
                self.memory = parse_cost(
                    "memory",
                    value,
                    Argon2Params::DEFAULT_M_COST,
                    Argon2Params::MAX_M_COST,
                )?
            }
            #[cfg(not(feature = "fips"))]
            "threads" => {
                self.threads = parse_cost(
                    "threads",
                    value,
                    Argon2Params::DEFAULT_T_COST,
                    Argon2Params::MAX_T_COST,
                )?
            }
            #[cfg(not(feature = "fips"))]
            "parallel" => {
                self.parallel = parse_cost(
                    "parallel",
                    value,
                    Argon2Params::DEFAULT_P_COST,
                    Argon2Params::MAX_P_COST,
                )?
            }
            #[cfg(feature = "fips")]
            "iterations" => {
                self.iterations =
                    parse_cost("iterations", value, default_iterations(), MAX_ITERATIONS)?
            }
            _ => {
                return Err(KeyRingError::GeneralError {
                    msg: format!("unknown parameter: {}", key),
                });
            }
        };
        Ok(())
    }

    /// Set the key
    pub fn key(&mut self, key: &[u8]) -> &mut Self {
        self.key = key.to_vec();
        self
    }

    /// Set the password
    pub fn password(&mut self, password: &[u8]) -> &mut Self {
        self.password = password.to_vec();
        self
    }

    /// Set the salt
    pub fn salt(&mut self, salt: &[u8]) -> &mut Self {
        self.salt = salt.to_vec();
        self
    }

    /// Set the memory cost
    pub fn memory(&mut self, cost: u32) -> &mut Self {
        self.memory = cost;
        self
    }

    /// Set the time cost
    pub fn time(&mut self, cost: u32) -> &mut Self {
        self.threads = cost;
        self
    }

    /// Set the parallel cost
    pub fn parallel(&mut self, cost: u32) -> &mut Self {
        self.parallel = cost;
        self
    }
}

#[cfg(any(
    feature = "memory",
    feature = "encrypted-vfs",
    feature = "turso-encrypted-io"
))]
impl<C: CipherParam> ConnectionParams<C> {
    /// The password KDF's costs as a stored header records them: Argon2
    /// memory, time and parallelism, or the PBKDF2 iteration count and two
    /// zeros in `fips` builds.
    pub(crate) fn kdf_costs(&self) -> [u32; 3] {
        #[cfg(not(feature = "fips"))]
        return [self.memory, self.threads, self.parallel];
        #[cfg(feature = "fips")]
        return [self.iterations, 0, 0];
    }

    /// Set the costs read back from a stored header.
    pub(crate) fn set_kdf_costs(&mut self, costs: [u32; 3]) {
        #[cfg(not(feature = "fips"))]
        {
            [self.memory, self.threads, self.parallel] = costs;
        }
        #[cfg(feature = "fips")]
        {
            self.iterations = costs[0];
        }
    }
}

/// Refuse stored costs no honest keyring would use.
///
/// A stored header is read before anything is authenticated, so a crafted
/// file must not be able to demand terabytes of memory or billions of
/// rounds before its contents fail to decrypt.
#[cfg(any(
    feature = "memory",
    feature = "encrypted-vfs",
    feature = "turso-encrypted-io"
))]
pub(crate) fn check_stored_kdf_costs(costs: [u32; 3]) -> Result<()> {
    #[cfg(not(feature = "fips"))]
    let reasonable = {
        let [memory, threads, parallel] = costs;
        memory <= 1024 * 1024 && threads <= 64 && parallel <= 64
    };
    #[cfg(feature = "fips")]
    let reasonable = costs[0] <= MAX_ITERATIONS;
    if reasonable {
        Ok(())
    } else {
        Err(KeyRingError::GeneralError {
            msg: "the stored key derivation costs are unreasonable".to_string(),
        })
    }
}

/// Parse an Argon2 cost and check it lies in `[min, max)`.
fn parse_cost(name: &str, value: &str, min: u32, max: u32) -> Result<u32> {
    let cost = value
        .parse::<u32>()
        .map_err(|e| KeyRingError::GeneralError {
            msg: format!("expected an integer for {}: {}", name, e),
        })?;
    if !(min..max).contains(&cost) {
        return Err(KeyRingError::GeneralError {
            msg: format!(
                "invalid value for {} must be between {} and {}",
                name, min, max
            ),
        });
    }
    Ok(cost)
}

/// Derive the raw encryption key from [`ConnectionParams`].
///
/// If `params.key` is set, returns it directly; otherwise derives a 32-byte
/// key from the password + salt via Argon2id.
pub(crate) fn derive_key<C: CipherParam>(
    params: &ConnectionParams<C>,
) -> Result<Zeroizing<Vec<u8>>> {
    if !params.key.is_empty() {
        return Ok(Zeroizing::new(params.key.to_vec()));
    }
    password_key(params)
}

/// Highest PBKDF2 iteration count a connection string or stored header may
/// ask for; well past any sensible setting, low enough to bound the work.
#[cfg(feature = "fips")]
pub(crate) const MAX_ITERATIONS: u32 = 100_000_000;

/// The shortest salt PBKDF2 accepts: NIST SP 800-132 requires 128 bits.
#[cfg(feature = "fips")]
const MIN_SALT_LEN: usize = 16;

/// PBKDF2-HMAC-SHA256 over password + salt.
#[cfg(feature = "fips")]
fn password_key<C: CipherParam>(params: &ConnectionParams<C>) -> Result<Zeroizing<Vec<u8>>> {
    if params.salt.len() < MIN_SALT_LEN {
        return Err(KeyRingError::GeneralError {
            msg: format!("salt must be at least {} bytes", MIN_SALT_LEN),
        });
    }
    if !(default_iterations()..=MAX_ITERATIONS).contains(&params.iterations) {
        return Err(KeyRingError::GeneralError {
            msg: format!(
                "iterations must be between {} and {}",
                default_iterations(),
                MAX_ITERATIONS
            ),
        });
    }
    let mut okm = Zeroizing::new(vec![0u8; 32]);
    pbkdf2::pbkdf2_hmac::<sha2::Sha256>(
        &params.password,
        &params.salt,
        params.iterations,
        &mut okm,
    );
    Ok(okm)
}

/// Argon2id over password + salt.
#[cfg(not(feature = "fips"))]
fn password_key<C: CipherParam>(params: &ConnectionParams<C>) -> Result<Zeroizing<Vec<u8>>> {
    let argon2_params = Argon2Params::new(
        params.memory,
        params.threads,
        params.parallel,
        Some(Argon2Params::DEFAULT_OUTPUT_LEN),
    )
    .map_err(|e| KeyRingError::GeneralError {
        msg: format!("invalid Argon2 parameters: {}", e),
    })?;
    let argon2 = Argon2::new(Algorithm::Argon2id, Version::V0x13, argon2_params);
    let mut okm = Zeroizing::new(vec![0u8; 32]);
    argon2
        .hash_password_into(&params.password, &params.salt, &mut okm)
        .map_err(|e| KeyRingError::GeneralError {
            msg: format!("Argon2 key derivation failed: {}", e),
        })?;
    Ok(okm)
}

/// Derive a key with [`derive_key`] and require it to be exactly 32 bytes.
#[cfg(any(
    feature = "encrypted-vfs",
    feature = "memory",
    feature = "turso",
    feature = "turso-encrypted-io"
))]
pub(crate) fn derive_key_32<C: CipherParam>(
    params: &ConnectionParams<C>,
) -> Result<Zeroizing<[u8; 32]>> {
    let key = derive_key(params)?;
    let mut out = Zeroizing::new([0u8; 32]);
    if key.len() != out.len() {
        return Err(KeyRingError::GeneralError {
            msg: "key must be 32 bytes".to_string(),
        });
    }
    out.copy_from_slice(&key);
    Ok(out)
}

#[cfg(any(
    feature = "file",
    feature = "encrypted-vfs",
    feature = "turso",
    feature = "turso-encrypted-io",
))]
/// Resolve the keyring file `file_name` inside `in_path` (default
/// `~/.cryptex`), creating the directory if needed. Only a directory cryptex
/// owns (the default, or one it just created) is restricted and hidden; a
/// caller's existing folder is left as it is.
pub(crate) fn get_keyring_file(in_path: Option<PathBuf>, file_name: &str) -> Result<PathBuf> {
    let is_default = in_path.is_none();
    let mut path = match in_path {
        None => {
            // WASI has no home directory, so keep the keyring next to the
            // program.
            #[cfg(target_os = "wasi")]
            let mut path = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
            #[cfg(not(target_os = "wasi"))]
            let mut path = dirs::home_dir()
                .or_else(dirs::document_dir)
                .or_else(dirs::data_local_dir)
                .ok_or_else(|| KeyRingError::GeneralError {
                    msg: "no home directory to keep the keyring in; pass a path".to_string(),
                })?;
            path.push(format!(".{}", env!("CARGO_PKG_NAME")));
            path
        }
        Some(path) => path,
    };

    let created = !path.is_dir();
    if created {
        fs::create_dir_all(&path).map_err(|e| KeyRingError::GeneralError {
            msg: format!("unable to create folder {}: {}", path.display(), e),
        })?;
    }
    if is_default || created {
        secure_dir(&path)?;
        make_hidden(&path);
    }
    path.push(file_name);
    Ok(path)
}

/// [`OpenOptions`] that create files readable and writable by the owner only.
#[cfg(any(
    feature = "file",
    feature = "encrypted-vfs",
    feature = "turso",
    feature = "turso-encrypted-io"
))]
pub(crate) fn private_open_options() -> OpenOptions {
    let mut opts = OpenOptions::new();
    restrict_to_owner(&mut opts);
    opts
}

#[cfg(all(
    unix,
    any(
        feature = "file",
        feature = "encrypted-vfs",
        feature = "turso",
        feature = "turso-encrypted-io"
    )
))]
fn restrict_to_owner(opts: &mut OpenOptions) {
    use std::os::unix::fs::OpenOptionsExt;
    opts.mode(0o600);
}

#[cfg(all(
    not(unix),
    any(
        feature = "file",
        feature = "encrypted-vfs",
        feature = "turso",
        feature = "turso-encrypted-io"
    )
))]
fn restrict_to_owner(_opts: &mut OpenOptions) {}

/// Acquire an exclusive advisory lock guaranteeing a single opener of the
/// keyring. A sidecar `<db>.lock` file is locked (not the database itself) so
/// the lock is unaffected by `rekey`'s atomic rename of the database file. The
/// returned handle must be kept alive for the keyring's lifetime; the OS
/// releases the lock when the handle is dropped or the process exits, so a
/// crashed process never leaves a stale lock behind.
#[cfg(any(
    feature = "encrypted-vfs",
    feature = "turso",
    feature = "turso-encrypted-io"
))]
pub(crate) fn acquire_single_opener_lock(db_path: &Path) -> Result<File> {
    let lock_path = sibling_path(db_path, ".lock");

    let file = private_open_options()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(&lock_path)
        .map_err(|e| KeyRingError::GeneralError {
            msg: format!(
                "unable to open keyring lock file {}: {}",
                lock_path.display(),
                e
            ),
        })?;

    match file.try_lock() {
        Ok(()) => Ok(file),
        Err(TryLockError::WouldBlock) => Err(KeyRingError::AccessDenied {
            msg: "keyring is already open by another process".to_string(),
        }),
        // WASI does not implement locking at all, so a keyring there relies on
        // the caller keeping a single writer. Everywhere else a filesystem
        // that refuses to lock is an error: FUSE, NFS and SMB mounts report
        // `Unsupported`, and opening unlocked would let two writers race.
        #[cfg(target_os = "wasi")]
        Err(TryLockError::Error(e)) if e.kind() == std::io::ErrorKind::Unsupported => Ok(file),
        Err(TryLockError::Error(e)) => Err(KeyRingError::GeneralError {
            msg: format!("unable to lock keyring: {}", e),
        }),
    }
}

/// Make a rename inside `path`'s directory durable. Without this a crash
/// soon after a successful rekey can bring back the old file.
#[cfg(all(
    unix,
    any(
        feature = "encrypted-vfs",
        feature = "turso",
        feature = "turso-encrypted-io"
    )
))]
pub(crate) fn sync_parent_dir(path: &Path) -> Result<()> {
    match path.parent() {
        Some(dir) => Ok(File::open(dir)?.sync_all()?),
        None => Ok(()),
    }
}

/// Windows cannot open a directory as a file to flush it; NTFS journals the
/// rename itself.
#[cfg(all(
    not(unix),
    any(
        feature = "encrypted-vfs",
        feature = "turso",
        feature = "turso-encrypted-io"
    )
))]
pub(crate) fn sync_parent_dir(_path: &Path) -> Result<()> {
    Ok(())
}

/// `path` with `suffix` appended to its file name, e.g. `keyring.db3` + `-wal`.
#[cfg(any(
    feature = "encrypted-vfs",
    feature = "turso",
    feature = "turso-encrypted-io"
))]
pub(crate) fn sibling_path(path: &Path, suffix: &str) -> PathBuf {
    let mut s = path.as_os_str().to_os_string();
    s.push(suffix);
    PathBuf::from(s)
}

#[cfg(all(
    unix,
    any(
        feature = "file",
        feature = "encrypted-vfs",
        feature = "turso",
        feature = "turso-encrypted-io"
    )
))]
fn secure_dir(path: &Path) -> Result<()> {
    use std::os::unix::fs::PermissionsExt;

    fs::set_permissions(path, fs::Permissions::from_mode(0o700)).map_err(|e| {
        KeyRingError::GeneralError {
            msg: format!("unable to secure folder {}: {}", path.display(), e),
        }
    })
}

#[cfg(all(
    not(unix),
    any(
        feature = "file",
        feature = "encrypted-vfs",
        feature = "turso",
        feature = "turso-encrypted-io"
    )
))]
fn secure_dir(_path: &Path) -> Result<()> {
    Ok(())
}

/// Create `path` as an empty owner-only file if it does not exist yet, so a
/// database library that opens it next never creates it with umask
/// permissions. An existing file is left untouched.
#[cfg(any(feature = "file", feature = "turso", feature = "turso-encrypted-io"))]
pub(crate) fn create_private_file(path: &Path) -> Result<()> {
    private_open_options()
        .write(true)
        .create(true)
        .truncate(false)
        .open(path)
        .map(drop)
        .map_err(|e| KeyRingError::GeneralError {
            msg: format!("unable to create keyring file {}: {}", path.display(), e),
        })
}

/// Restrict the database file itself to owner-only access (defense in depth
/// beyond the `0o700` parent directory).
#[cfg(all(unix, any(feature = "file", feature = "turso")))]
pub(crate) fn secure_file(path: &Path) -> Result<()> {
    use std::os::unix::fs::PermissionsExt;

    fs::set_permissions(path, fs::Permissions::from_mode(0o600)).map_err(|e| {
        KeyRingError::GeneralError {
            msg: format!("unable to secure keyring file {}: {}", path.display(), e),
        }
    })
}

#[cfg(all(not(unix), any(feature = "file", feature = "turso")))]
pub(crate) fn secure_file(_path: &Path) -> Result<()> {
    Ok(())
}

#[cfg(all(
    target_os = "windows",
    any(
        feature = "file",
        feature = "encrypted-vfs",
        feature = "turso",
        feature = "turso-encrypted-io"
    )
))]
fn make_hidden(path: &Path) {
    use std::ffi::OsStr;
    use std::os::windows::ffi::OsStrExt;

    const FILE_ATTRIBUTE_HIDDEN: u32 = 0x2;

    // SAFETY: matches the Win32 `SetFileAttributesW` signature in kernel32.
    unsafe extern "system" {
        fn SetFileAttributesW(lpfilename: *const u16, dwfileattributes: u32) -> i32;
    }

    let wide: Vec<u16> = OsStr::new(path)
        .encode_wide()
        .chain(iter::once(0))
        .collect();
    // SAFETY: `wide` is a NUL-terminated UTF-16 path that outlives the call,
    // and SetFileAttributesW only reads it. Failure is harmless (the folder is
    // just not hidden), so the return value is ignored.
    unsafe {
        SetFileAttributesW(wide.as_ptr(), FILE_ATTRIBUTE_HIDDEN);
    }
}

#[cfg(all(
    not(target_os = "windows"),
    any(
        feature = "file",
        feature = "encrypted-vfs",
        feature = "turso",
        feature = "turso-encrypted-io"
    )
))]
fn make_hidden(_path: &Path) {}

struct Parser<'a> {
    s: &'a str,
    it: iter::Peekable<std::str::CharIndices<'a>>,
}

impl<'a> Parser<'a> {
    fn parse<C: CipherParam>(s: &'a str) -> Result<ConnectionParams<C>> {
        let mut parser = Parser {
            s,
            it: s.char_indices().peekable(),
        };

        let mut connection_string = ConnectionParams::default();
        // A repeated keyword used to overwrite the first one, so a password
        // that contained ` salt=...` could silently swap the salt or turn the
        // password into a raw key.
        let mut seen: Vec<&'a str> = Vec::new();

        while let Some((key, value)) = parser.parameter()? {
            if seen.contains(&key) {
                return Err(KeyRingError::GeneralError {
                    msg: format!("duplicate parameter: {}", key),
                });
            }
            seen.push(key);
            connection_string.param(key, &value)?;
        }
        Ok(connection_string)
    }

    fn skip_ws(&mut self) {
        self.take_while(char::is_whitespace);
    }

    fn take_while<F>(&mut self, f: F) -> &'a str
    where
        F: Fn(char) -> bool,
    {
        let start = match self.it.peek() {
            Some(&(i, _)) => i,
            None => return "",
        };

        loop {
            match self.it.peek() {
                Some(&(_, c)) if f(c) => {
                    self.it.next();
                }
                Some(&(i, _)) => return &self.s[start..i],
                None => return &self.s[start..],
            }
        }
    }

    fn consume(&mut self, target: char) -> Result<()> {
        match self.it.next() {
            Some((_, c)) if c == target => Ok(()),
            // The offending character is not echoed: it may be part of a secret.
            Some((i, _)) => Err(KeyRingError::GeneralError {
                msg: format!("unexpected character at byte {}: expected `{}`", i, target),
            }),
            None => Err(KeyRingError::GeneralError {
                msg: "unexpected EOF".to_string(),
            }),
        }
    }

    fn consume_if(&mut self, target: char) -> bool {
        match self.it.peek() {
            Some(&(_, c)) if c == target => {
                self.it.next();
                true
            }
            _ => false,
        }
    }

    fn keyword(&mut self) -> Option<&'a str> {
        let s = self.take_while(|c| !c.is_whitespace() && c != '=');
        if s.is_empty() { None } else { Some(s) }
    }

    fn value(&mut self) -> Result<Zeroizing<String>> {
        if self.consume_if('\'') {
            let value = self.quoted_value()?;
            self.consume('\'')?;
            Ok(value)
        } else {
            self.simple_value()
        }
    }

    fn simple_value(&mut self) -> Result<Zeroizing<String>> {
        // Sized up front so pushing never reallocates and strands a copy.
        let mut value = Zeroizing::new(String::with_capacity(self.s.len()));

        while let Some(&(_, c)) = self.it.peek() {
            if c.is_whitespace() {
                break;
            }

            self.it.next();
            if c == '\\' {
                if let Some((_, c2)) = self.it.next() {
                    value.push(c2);
                }
            } else {
                value.push(c);
            }
        }

        if value.is_empty() {
            return Err(KeyRingError::GeneralError {
                msg: "unexpected EOF".to_string(),
            });
        }

        Ok(value)
    }

    fn quoted_value(&mut self) -> Result<Zeroizing<String>> {
        // Sized up front so pushing never reallocates and strands a copy.
        let mut value = Zeroizing::new(String::with_capacity(self.s.len()));

        while let Some(&(_, c)) = self.it.peek() {
            if c == '\'' {
                return Ok(value);
            }

            self.it.next();
            if c == '\\' {
                if let Some((_, c2)) = self.it.next() {
                    value.push(c2);
                }
            } else {
                value.push(c);
            }
        }

        Err(KeyRingError::GeneralError {
            msg: "unterminated quoted connection parameter value".to_string(),
        })
    }

    fn parameter(&mut self) -> Result<Option<(&'a str, Zeroizing<String>)>> {
        self.skip_ws();
        let keyword = match self.keyword() {
            Some(keyword) => keyword,
            None => return Ok(None),
        };
        self.skip_ws();
        self.consume('=')?;
        self.skip_ws();
        let value = self.value()?;

        Ok(Some((keyword, value)))
    }
}

/// Helpers shared by the file-backed keyring tests.
#[cfg(all(
    test,
    any(
        feature = "file",
        feature = "encrypted-vfs",
        feature = "turso",
        feature = "turso-encrypted-io"
    )
))]
pub(crate) mod test_support {
    use std::ops::Deref;
    use std::path::{Path, PathBuf};

    /// A scratch keyring directory under the crate root. It is emptied when
    /// created and removed when dropped, even if the test panics.
    pub(crate) struct TestDir(PathBuf);

    impl TestDir {
        pub(crate) fn new(name: &str) -> Self {
            // Under WASI only the preopened directory is reachable, so use a
            // path relative to it.
            #[cfg(target_os = "wasi")]
            let path = PathBuf::from(name);
            #[cfg(not(target_os = "wasi"))]
            let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(name);
            let _ = std::fs::remove_dir_all(&path);
            Self(path)
        }

        /// The directory as the `path` argument of `with_params`.
        pub(crate) fn keyring_dir(&self) -> Option<PathBuf> {
            Some(self.0.clone())
        }
    }

    impl Deref for TestDir {
        type Target = Path;

        fn deref(&self) -> &Path {
            &self.0
        }
    }

    impl Drop for TestDir {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{ConnectionParams, NoCipher, derive_key};

    #[cfg(not(feature = "fips"))]
    #[test]
    fn parses_all_fields() {
        let p: ConnectionParams = "password=pw salt='a b' memory=32768 threads=3 parallel=2"
            .parse()
            .unwrap();
        assert_eq!(p.password, b"pw");
        assert_eq!(p.salt, b"a b");
        assert_eq!((p.memory, p.threads, p.parallel), (32768, 3, 2));
        assert_eq!(p.cipher, NoCipher);
    }

    #[cfg(feature = "fips")]
    #[test]
    fn fips_parses_iterations_and_refuses_argon2_costs() {
        let p: ConnectionParams = "password=pw salt='a b' iterations=700000".parse().unwrap();
        assert_eq!(p.iterations, 700_000);
        assert_eq!(p.cipher, NoCipher);
        for s in ["memory=32768", "threads=3", "parallel=2", "iterations=1"] {
            assert!(s.parse::<ConnectionParams>().is_err(), "accepted: {s}");
        }
    }

    #[cfg(feature = "fips")]
    #[test]
    fn fips_refuses_short_salts() {
        let p: ConnectionParams = "password=pw salt=fifteen-bytes!!".parse().unwrap();
        assert!(derive_key(&p).is_err());
    }

    #[test]
    fn rejects_bad_input() {
        for s in [
            "key=not-hex",
            "cipher=aes256gcm",
            "unknown=1",
            "memory=abc",
            "threads=0",
            "password='unterminated",
            "password",
        ] {
            assert!(s.parse::<ConnectionParams>().is_err(), "accepted: {s}");
        }
    }

    #[test]
    fn errors_do_not_echo_secret_characters() {
        for (s, leaked) in [("password=pw salt Q", 'Q'), ("key=zz", 'z')] {
            let err = s.parse::<ConnectionParams>().err().unwrap().to_string();
            assert!(!err.contains(leaked), "{err}");
        }
    }

    #[test]
    fn raw_key_bypasses_argon2() {
        let p: ConnectionParams = "key=aabb".parse().unwrap();
        assert_eq!(&*derive_key(&p).unwrap(), &[0xaa, 0xbb]);
    }

    #[test]
    fn password_derivation_is_deterministic() {
        let a: ConnectionParams = "password=pw salt=saltsaltsaltsalt".parse().unwrap();
        let b: ConnectionParams = "password=pw salt=saltsaltsaltsalt".parse().unwrap();
        let c: ConnectionParams = "password=pw2 salt=saltsaltsaltsalt".parse().unwrap();
        let ka = derive_key(&a).unwrap();
        assert_eq!(ka.len(), 32);
        assert_eq!(ka, derive_key(&b).unwrap());
        assert_ne!(ka, derive_key(&c).unwrap());
    }

    #[cfg(all(unix, feature = "file"))]
    #[test]
    fn caller_folder_permissions_are_left_alone() {
        use super::get_keyring_file;
        use super::test_support::TestDir;
        use std::os::unix::fs::PermissionsExt;

        let dir = TestDir::new(".test-caller-folder-mode");
        std::fs::create_dir_all(&*dir).unwrap();
        std::fs::set_permissions(&*dir, std::fs::Permissions::from_mode(0o755)).unwrap();
        get_keyring_file(dir.keyring_dir(), "k.db3").unwrap();
        let mode = std::fs::metadata(&*dir).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o755);

        let created = dir.join("new");
        get_keyring_file(Some(created.clone()), "k.db3").unwrap();
        let mode = std::fs::metadata(&created).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o700);
    }

    #[cfg(all(unix, feature = "file"))]
    #[test]
    fn private_file_is_owner_only_and_keeps_content() {
        use super::create_private_file;
        use super::test_support::TestDir;
        use std::os::unix::fs::PermissionsExt;

        let dir = TestDir::new(".test-private-file");
        std::fs::create_dir_all(&*dir).unwrap();
        let path = dir.join("k.db3");
        create_private_file(&path).unwrap();
        let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o600);

        std::fs::write(&path, b"existing").unwrap();
        create_private_file(&path).unwrap();
        assert_eq!(std::fs::read(&path).unwrap(), b"existing");
    }
}