pacman-key 0.4.1

Native Rust interface for managing the pacman keyring on Arch Linux
Documentation
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
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
use std::path::Path;
use std::process::Stdio;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader};
use tokio::process::Command;

use crate::error::{Error, Result};
use crate::parse::{parse_keys, parse_ownertrust, parse_signatures, parse_verify_status};
use crate::process::{self, Operation};
use crate::types::{
    InitializationStatus, Key, OperationOptions, OwnerTrust, RefreshProgress, Signature,
    VerifyResult,
};
use crate::validation::{validate_keyid, validate_keyring_name, validate_path};

const DEFAULT_GPG_HOMEDIR: &str = "/etc/pacman.d/gnupg";

/// Read-only interface for querying a GPG keyring.
///
/// This type is returned by [`Keyring::with_homedir`] and only provides
/// read operations (`list_keys`, `list_signatures`). Write operations
/// require a [`Keyring`] which targets the system pacman keyring.
///
/// # Example
///
/// ```no_run
/// # async fn example() -> pacman_key::Result<()> {
/// use pacman_key::Keyring;
///
/// let reader = Keyring::with_homedir("/custom/gnupg");
/// let keys = reader.list_keys().await?;
/// # Ok(())
/// # }
/// ```
pub struct ReadOnlyKeyring {
    gpg_homedir: String,
}

impl ReadOnlyKeyring {
    fn gpg(&self) -> Command {
        let mut command = Command::new("gpg");
        command.arg(format!("--homedir={}", self.gpg_homedir));
        command
    }

    async fn run_checked(&self, command: &mut Command, operation: &Operation) -> Result<Vec<u8>> {
        let output = process::output(command, operation).await?;

        if !output.status.success() {
            return Err(check_gpg_error(
                &self.gpg_homedir,
                output.status,
                &output.stderr,
            ));
        }

        Ok(output.stdout)
    }

    async fn run_gpg<I, S>(&self, args: I) -> Result<Vec<u8>>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<std::ffi::OsStr>,
    {
        self.run_checked(self.gpg().args(args), &Operation::default())
            .await
    }

    /// Lists all keys in the keyring.
    pub async fn list_keys(&self) -> Result<Vec<Key>> {
        let stdout = self.run_gpg(["--list-keys", "--with-colons"]).await?;
        parse_keys(&String::from_utf8_lossy(&stdout))
    }

    /// Lists signatures on keys in the keyring (non-checking `--list-sigs`).
    ///
    /// If `keyid` is provided, lists signatures only for that key.
    /// Otherwise lists all signatures in the keyring. The `status` field of
    /// each [`Signature`] is `None`; use [`check_signatures`] to verify them.
    ///
    /// [`check_signatures`]: Self::check_signatures
    pub async fn list_signatures(&self, keyid: Option<&str>) -> Result<Vec<Signature>> {
        self.run_list_sigs("--list-sigs", keyid).await
    }

    /// Lists and verifies signatures on keys (`--check-sigs`).
    ///
    /// Like [`list_signatures`] but each [`Signature`]'s `status` is populated
    /// with the verification result.
    ///
    /// [`list_signatures`]: Self::list_signatures
    pub async fn check_signatures(&self, keyid: Option<&str>) -> Result<Vec<Signature>> {
        self.run_list_sigs("--check-sigs", keyid).await
    }

    async fn run_list_sigs(&self, op: &str, keyid: Option<&str>) -> Result<Vec<Signature>> {
        let mut args = vec![op.to_string(), "--with-colons".to_string()];
        if let Some(id) = keyid {
            args.push(validate_keyid(id)?);
        }
        let stdout = self.run_gpg(args).await?;
        parse_signatures(&String::from_utf8_lossy(&stdout))
    }

    /// Exports the given keys as an ASCII-armored block.
    ///
    /// An empty `keyids` slice exports all public keys. Mirrors
    /// `pacman-key --export`.
    pub async fn export_keys(&self, keyids: &[&str]) -> Result<String> {
        let mut args = vec!["--armor".to_string(), "--export".to_string()];
        for id in keyids {
            args.push(validate_keyid(id)?);
        }
        let stdout = self.run_gpg(args).await?;
        Ok(String::from_utf8_lossy(&stdout).into_owned())
    }

    /// Returns the fingerprints of the given keys (or all keys if empty).
    ///
    /// Mirrors `pacman-key --finger`. Note [`list_keys`] already returns the
    /// same fingerprints alongside the full key data; this is a convenience
    /// for when only fingerprints are needed.
    ///
    /// [`list_keys`]: Self::list_keys
    pub async fn fingerprints(&self, keyids: &[&str]) -> Result<Vec<String>> {
        let mut args = vec!["--with-colons".to_string(), "--fingerprint".to_string()];
        for id in keyids {
            args.push(validate_keyid(id)?);
        }
        let stdout = self.run_gpg(args).await?;
        let keys = parse_keys(&String::from_utf8_lossy(&stdout))?;
        Ok(keys.into_iter().map(|k| k.fingerprint).collect())
    }

    /// Verifies a signature against the keyring.
    ///
    /// `sig` is the (binary) signature file; `file` is the signed data for a
    /// detached signature (omit for an embedded one). Mirrors
    /// `pacman-key --verify`, which rejects ASCII-armored signatures.
    ///
    /// Returns a [`VerifyResult`]; a bad signature is reported via
    /// `good == false`, not an error. Only an inability to run gpg or read the
    /// signature file produces an `Err`.
    pub async fn verify_signature(&self, sig: &Path, file: Option<&Path>) -> Result<VerifyResult> {
        let bytes = std::fs::read(sig).map_err(Error::Command)?;
        if bytes
            .windows(b"BEGIN PGP SIGNATURE".len())
            .any(|w| w == b"BEGIN PGP SIGNATURE")
        {
            return Err(Error::InvalidPath {
                path: sig.display().to_string(),
                reason: "armored signatures are not supported (use a binary signature)".to_string(),
            });
        }

        let mut args = vec![
            "--status-fd".to_string(),
            "1".to_string(),
            "--verify".to_string(),
            validate_path(sig)?,
        ];
        if let Some(f) = file {
            args.push(validate_path(f)?);
        }

        // gpg exits non-zero on a bad/untrusted signature; that is a verdict,
        // not a failure, so capture stdout regardless of exit status.
        let output = process::output(self.gpg().args(&args), &Operation::default()).await?;

        Ok(parse_verify_status(&String::from_utf8_lossy(
            &output.stdout,
        )))
    }

    /// Reads owner-trust assignments via `gpg --export-ownertrust`.
    pub async fn get_ownertrust(&self) -> Result<Vec<(String, OwnerTrust)>> {
        let stdout = self.run_gpg(["--export-ownertrust"]).await?;
        Ok(parse_ownertrust(&String::from_utf8_lossy(&stdout)))
    }

    /// Checks whether the keyring is initialized without spawning GPG.
    ///
    /// Verifies the directory exists with mode 755 (as created by
    /// `pacman-key --init`; world-readable so unprivileged pacman can read
    /// the public keyring, pacman commit 4ef664f4) and contains a non-empty
    /// pubring.kbx or pubring.gpg plus trustdb.gpg. Symlinks are followed.
    /// Non-atomic and subject to TOCTOU races; use for informational
    /// purposes, not security decisions.
    pub fn is_initialized(&self) -> Result<InitializationStatus> {
        use std::fs;
        use std::os::unix::fs::PermissionsExt;
        use std::path::Path;

        let dir = Path::new(&self.gpg_homedir);

        let metadata = match fs::metadata(dir) {
            Ok(m) => m,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                return Ok(InitializationStatus::DirectoryMissing);
            }
            Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
                return Err(Error::PermissionDenied);
            }
            Err(e) => return Err(Error::Command(e)),
        };

        if metadata.is_file() {
            return Ok(InitializationStatus::PathIsFile);
        }

        if !metadata.is_dir() {
            return Ok(InitializationStatus::DirectoryMissing);
        }

        // mask keeps setuid/setgid/sticky so nonstandard special bits are flagged
        let mode = metadata.permissions().mode() & 0o7777;
        if mode != 0o755 {
            return Ok(InitializationStatus::IncorrectPermissions { actual: mode });
        }

        // Check for keyring files, propagating permission errors
        let has_pubring = Self::file_exists_and_nonempty(&dir.join("pubring.kbx"))?
            || Self::file_exists_and_nonempty(&dir.join("pubring.gpg"))?;
        if !has_pubring {
            return Ok(InitializationStatus::NoKeyringFiles);
        }

        if !Self::file_exists_and_nonempty(&dir.join("trustdb.gpg"))? {
            return Ok(InitializationStatus::NoTrustDb);
        }

        Ok(InitializationStatus::Ready)
    }

    fn file_exists_and_nonempty(path: &std::path::Path) -> Result<bool> {
        use std::fs;

        match fs::metadata(path) {
            Ok(m) => Ok(m.is_file() && m.len() > 0),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
            Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
                Err(Error::PermissionDenied)
            }
            Err(e) => Err(Error::Command(e)),
        }
    }
}

fn check_gpg_error(homedir: &str, status: std::process::ExitStatus, stderr: &[u8]) -> Error {
    let msg = String::from_utf8_lossy(stderr);

    if msg.contains("Permission denied") || msg.contains("permission denied") {
        return Error::PermissionDenied;
    }

    if msg.contains("No such file or directory") && msg.contains(homedir) {
        return Error::KeyringNotInitialized;
    }

    Error::PacmanKey {
        status: status.code().unwrap_or(-1),
        stderr: msg.to_string(),
    }
}

/// Builds a `pacman-key` arg vector from an operation flag and validated paths.
fn paths_to_args(flag: &str, paths: &[&Path]) -> Result<Vec<String>> {
    let mut args = vec![flag.to_string()];
    for p in paths {
        args.push(validate_path(p)?);
    }
    Ok(args)
}

/// Interface for managing the pacman keyring.
///
/// Provides async methods for key listing, importing, signing, and keyring management.
///
/// # Root Privileges
///
/// Write operations (`init_keyring`, `populate`, `receive_keys`, `locally_sign_key`,
/// `delete_key`) require root privileges and will return [`Error::PermissionDenied`]
/// if called without sufficient permissions.
///
/// [`Error::PermissionDenied`]: crate::Error::PermissionDenied
///
/// # Example
///
/// ```no_run
/// use pacman_key::Keyring;
///
/// # async fn example() -> pacman_key::Result<()> {
/// let keyring = Keyring::new();
/// let keys = keyring.list_keys().await?;
/// println!("Found {} keys", keys.len());
/// # Ok(())
/// # }
/// ```
pub struct Keyring {
    reader: ReadOnlyKeyring,
    keyserver: Option<String>,
}

impl Default for Keyring {
    fn default() -> Self {
        Self::new()
    }
}

impl Keyring {
    /// Creates a new Keyring using the default pacman keyring path.
    #[must_use]
    pub fn new() -> Self {
        Self {
            reader: ReadOnlyKeyring {
                gpg_homedir: DEFAULT_GPG_HOMEDIR.to_string(),
            },
            keyserver: None,
        }
    }

    /// Sets the keyserver used by [`receive_keys`] and [`refresh_keys`].
    ///
    /// Maps to pacman-key's `--keyserver`. When unset, gpg's configured
    /// default keyserver is used.
    ///
    /// [`receive_keys`]: Self::receive_keys
    /// [`refresh_keys`]: Self::refresh_keys
    #[must_use]
    pub fn with_keyserver(mut self, url: impl Into<String>) -> Self {
        self.keyserver = Some(url.into());
        self
    }

    /// Creates a read-only keyring interface for a custom GPG home directory.
    ///
    /// Returns a [`ReadOnlyKeyring`] that can only perform read operations
    /// (`list_keys`, `list_signatures`). This is useful for inspecting
    /// alternative keyrings without risking modifications.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn example() -> pacman_key::Result<()> {
    /// use pacman_key::Keyring;
    ///
    /// let reader = Keyring::with_homedir("/custom/gnupg");
    /// let keys = reader.list_keys().await?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn with_homedir(path: impl Into<String>) -> ReadOnlyKeyring {
        ReadOnlyKeyring {
            gpg_homedir: path.into(),
        }
    }

    pub fn get_homedir(&self) -> &str {
        &self.reader.gpg_homedir
    }

    async fn run_pacman_key<I, S>(&self, args: I) -> Result<()>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<std::ffi::OsStr>,
    {
        self.run_pacman_key_with_options(args, OperationOptions::default())
            .await
    }

    async fn run_pacman_key_with_options<I, S>(
        &self,
        args: I,
        options: OperationOptions,
    ) -> Result<()>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<std::ffi::OsStr>,
    {
        let (status, stderr) = process::stderr_only(
            Command::new("pacman-key").args(args),
            &Operation::new(options),
        )
        .await?;
        if !status.success() {
            return Err(self.check_error(status, &stderr));
        }
        Ok(())
    }

    /// Lists all keys in the keyring.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn example() -> pacman_key::Result<()> {
    /// use pacman_key::Keyring;
    ///
    /// let keyring = Keyring::new();
    /// for key in keyring.list_keys().await? {
    ///     println!("{} - {:?}", key.uid, key.validity);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn list_keys(&self) -> Result<Vec<Key>> {
        self.reader.list_keys().await
    }

    /// Lists signatures on keys in the keyring (non-checking `--list-sigs`).
    ///
    /// If `keyid` is provided, lists signatures only for that key.
    /// Otherwise lists all signatures in the keyring.
    pub async fn list_signatures(&self, keyid: Option<&str>) -> Result<Vec<Signature>> {
        self.reader.list_signatures(keyid).await
    }

    /// Lists and verifies signatures on keys (`--check-sigs`).
    ///
    /// See [`ReadOnlyKeyring::check_signatures`].
    pub async fn check_signatures(&self, keyid: Option<&str>) -> Result<Vec<Signature>> {
        self.reader.check_signatures(keyid).await
    }

    /// Exports the given keys (or all keys) as an ASCII-armored block.
    ///
    /// See [`ReadOnlyKeyring::export_keys`].
    pub async fn export_keys(&self, keyids: &[&str]) -> Result<String> {
        self.reader.export_keys(keyids).await
    }

    /// Returns the fingerprints of the given keys (or all keys).
    ///
    /// See [`ReadOnlyKeyring::fingerprints`].
    pub async fn fingerprints(&self, keyids: &[&str]) -> Result<Vec<String>> {
        self.reader.fingerprints(keyids).await
    }

    /// Verifies a signature against the keyring.
    ///
    /// See [`ReadOnlyKeyring::verify_signature`].
    pub async fn verify_signature(&self, sig: &Path, file: Option<&Path>) -> Result<VerifyResult> {
        self.reader.verify_signature(sig, file).await
    }

    /// Reads owner-trust assignments.
    ///
    /// See [`ReadOnlyKeyring::get_ownertrust`].
    pub async fn get_ownertrust(&self) -> Result<Vec<(String, OwnerTrust)>> {
        self.reader.get_ownertrust().await
    }

    /// Checks whether the keyring is initialized without spawning GPG.
    ///
    /// See [`ReadOnlyKeyring::is_initialized`] for details.
    pub fn is_initialized(&self) -> Result<InitializationStatus> {
        self.reader.is_initialized()
    }

    /// Initializes the pacman keyring.
    ///
    /// Creates the keyring directory and generates a local signing key.
    /// For timeout/cancellation support, use [`init_keyring_with_options`].
    ///
    /// [`init_keyring_with_options`]: Self::init_keyring_with_options
    pub async fn init_keyring(&self) -> Result<()> {
        self.init_keyring_with_options(OperationOptions::default())
            .await
    }

    /// Initializes the pacman keyring with timeout and cancellation support.
    ///
    /// Creates the keyring directory and generates a local signing key.
    pub async fn init_keyring_with_options(&self, options: OperationOptions) -> Result<()> {
        self.run_pacman_key_with_options(&["--init"], options).await
    }

    /// Populates the keyring with keys from distribution keyrings.
    ///
    /// If no keyrings are specified, defaults to "archlinux". Keyring names
    /// must contain only alphanumeric characters, hyphens, or underscores.
    /// For timeout/cancellation support, use [`populate_with_options`].
    ///
    /// [`populate_with_options`]: Self::populate_with_options
    pub async fn populate(&self, keyrings: &[&str]) -> Result<()> {
        self.populate_with_options(keyrings, OperationOptions::default())
            .await
    }

    /// Populates the keyring with timeout and cancellation support.
    ///
    /// If no keyrings are specified, defaults to "archlinux". Keyring names
    /// must contain only alphanumeric characters, hyphens, or underscores.
    pub async fn populate_with_options(
        &self,
        keyrings: &[&str],
        options: OperationOptions,
    ) -> Result<()> {
        for name in keyrings {
            validate_keyring_name(name)?;
        }

        let keyring_args: Vec<&str> = if keyrings.is_empty() {
            vec!["archlinux"]
        } else {
            keyrings.to_vec()
        };

        let args: Vec<&str> = std::iter::once("--populate").chain(keyring_args).collect();

        self.run_pacman_key_with_options(&args, options).await
    }

    /// Receives keys from a keyserver.
    pub async fn receive_keys(&self, keyids: &[&str]) -> Result<()> {
        self.receive_keys_with_options(keyids, OperationOptions::default())
            .await
    }

    /// Receives keys from a keyserver with timeout and cancellation support.
    ///
    /// Uses the keyserver set via [`with_keyserver`], if any.
    ///
    /// [`with_keyserver`]: Self::with_keyserver
    pub async fn receive_keys_with_options(
        &self,
        keyids: &[&str],
        options: OperationOptions,
    ) -> Result<()> {
        if keyids.is_empty() {
            return Ok(());
        }

        let validated: Vec<String> = keyids
            .iter()
            .map(|k| validate_keyid(k))
            .collect::<Result<_>>()?;

        let mut args: Vec<String> = Vec::new();
        if let Some(ks) = &self.keyserver {
            args.push("--keyserver".to_string());
            args.push(ks.clone());
        }
        args.push("--recv-keys".to_string());
        args.extend(validated);

        self.run_pacman_key_with_options(args, options).await
    }

    /// Locally signs a key to mark it as trusted.
    pub async fn locally_sign_key(&self, keyid: &str) -> Result<()> {
        let validated = validate_keyid(keyid)?;
        self.run_pacman_key(&["--lsign-key", &validated]).await
    }

    /// Deletes a key from the keyring.
    pub async fn delete_key(&self, keyid: &str) -> Result<()> {
        let validated = validate_keyid(keyid)?;
        self.run_pacman_key(&["--delete", &validated]).await
    }

    /// Imports keys from file(s) into the keyring (`pacman-key --add`).
    ///
    /// Distinct from [`receive_keys`], which pulls from a keyserver. Each path
    /// must exist. pacman-key updates the trust database afterward; this crate
    /// does not, so call [`update_trustdb`] when trust state must be current.
    ///
    /// [`receive_keys`]: Self::receive_keys
    /// [`update_trustdb`]: Self::update_trustdb
    pub async fn add_keys(&self, files: &[&Path]) -> Result<()> {
        self.add_keys_with_options(files, OperationOptions::default())
            .await
    }

    /// Imports keys from file(s) with timeout and cancellation support.
    pub async fn add_keys_with_options(
        &self,
        files: &[&Path],
        options: OperationOptions,
    ) -> Result<()> {
        if files.is_empty() {
            return Ok(());
        }
        let args = paths_to_args("--add", files)?;
        self.run_pacman_key_with_options(args, options).await
    }

    /// Rebuilds the trust database (`pacman-key --updatedb`,
    /// i.e. `gpg --check-trustdb`).
    ///
    /// pacman-key runs this automatically after every key-mutating operation;
    /// this crate leaves it to the caller. Run it after `add_keys`,
    /// `delete_key`, `locally_sign_key`, `receive_keys`, or `set_ownertrust`
    /// to keep computed validity current.
    pub async fn update_trustdb(&self) -> Result<()> {
        self.update_trustdb_with_options(OperationOptions::default())
            .await
    }

    /// Rebuilds the trust database with timeout and cancellation support.
    pub async fn update_trustdb_with_options(&self, options: OperationOptions) -> Result<()> {
        self.run_pacman_key_with_options(&["--updatedb"], options)
            .await
    }

    /// Imports `pubring.gpg` from one or more keyring directories
    /// (`pacman-key --import`).
    pub async fn import_keyrings(&self, dirs: &[&Path]) -> Result<()> {
        if dirs.is_empty() {
            return Ok(());
        }
        self.run_pacman_key(paths_to_args("--import", dirs)?).await
    }

    /// Imports owner-trust values from `trustdb.gpg` in one or more keyring
    /// directories (`pacman-key --import-trustdb`).
    pub async fn import_trustdb(&self, dirs: &[&Path]) -> Result<()> {
        if dirs.is_empty() {
            return Ok(());
        }
        self.run_pacman_key(paths_to_args("--import-trustdb", dirs)?)
            .await
    }

    /// Sets owner-trust levels for keys, non-interactively.
    ///
    /// A scriptable replacement for the trust submenu of `--edit-key`: feeds
    /// `<fingerprint>:<level>:` lines to `gpg --import-ownertrust`. Each keyid
    /// is validated. Run [`update_trustdb`] afterward to recompute validity.
    ///
    /// [`update_trustdb`]: Self::update_trustdb
    pub async fn set_ownertrust(&self, entries: &[(&str, OwnerTrust)]) -> Result<()> {
        if entries.is_empty() {
            return Ok(());
        }
        let mut input = String::new();
        for (keyid, trust) in entries {
            let fpr = validate_keyid(keyid)?;
            input.push_str(&format!("{}:{}:\n", fpr, trust.to_gpg_level()));
        }
        self.run_gpg_stdin(&["--import-ownertrust"], input.as_bytes())
            .await
    }

    async fn run_gpg_stdin(&self, args: &[&str], input: &[u8]) -> Result<()> {
        use tokio::io::AsyncWriteExt;

        let mut command = self.reader.gpg();
        command
            .args(args)
            .stdin(Stdio::piped())
            .stdout(Stdio::null())
            .stderr(Stdio::piped());
        let (status, stderr) = process::run(&mut command, &Operation::default(), async |child| {
            let mut stdin = child.stdin.take().expect("stdin is piped");
            let stderr = child.stderr.take().expect("stderr is piped");
            let ((), stderr) = tokio::try_join!(
                // Moved in so stdin closes after the write; gpg waits for EOF.
                async move { stdin.write_all(input).await },
                process::collect(stderr, process::STDERR_LIMIT)
            )?;
            Ok(stderr)
        })
        .await?;
        if !status.success() {
            return Err(self.check_error(status, &stderr));
        }
        Ok(())
    }

    /// Refreshes all keys from the keyserver.
    ///
    /// This is a long-running operation. The callback receives progress updates
    /// as keys are refreshed. The timeout covers the initial key listing as well
    /// as the refresh.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn example() -> pacman_key::Result<()> {
    /// use pacman_key::{Keyring, OperationOptions, RefreshProgress, CancellationToken};
    ///
    /// let keyring = Keyring::new();
    /// let token = CancellationToken::new();
    /// let options = OperationOptions {
    ///     timeout_secs: Some(300),
    ///     cancel_token: Some(token.clone()),
    /// };
    ///
    /// // Cancel from another task with: token.cancel()
    /// keyring.refresh_keys(|p| println!("{p:?}"), options).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn refresh_keys<F>(&self, callback: F, options: OperationOptions) -> Result<()>
    where
        F: Fn(RefreshProgress),
    {
        let (list, refresh) = self.refresh_commands();
        self.refresh_with_commands(callback, options, list, refresh)
            .await
    }

    fn refresh_commands(&self) -> (Command, Command) {
        let mut list = self.reader.gpg();
        list.args(["--list-keys", "--with-colons"]);
        let mut refresh = Command::new("pacman-key");
        if let Some(ks) = &self.keyserver {
            refresh.arg("--keyserver").arg(ks);
        }
        refresh.arg("--refresh-keys");
        (list, refresh)
    }

    async fn refresh_with_commands<F>(
        &self,
        callback: F,
        options: OperationOptions,
        mut list: Command,
        mut refresh: Command,
    ) -> Result<()>
    where
        F: Fn(RefreshProgress),
    {
        let operation = Operation::new(options);
        let listed = self.reader.run_checked(&mut list, &operation).await?;
        let total = parse_keys(&String::from_utf8_lossy(&listed))?.len();
        callback(RefreshProgress::Starting { total_keys: total });

        refresh.stdout(Stdio::null()).stderr(Stdio::piped());
        let (status, ()) = process::run(&mut refresh, &operation, async |child| {
            let stderr = child.stderr.take().expect("stderr is piped");
            Self::read_refresh_output(BufReader::new(stderr), &callback, total).await
        })
        .await?;
        if !status.success() {
            return Err(Error::PacmanKey {
                status: status.code().unwrap_or(-1),
                stderr: "refresh failed".to_string(),
            });
        }

        callback(RefreshProgress::Completed);
        Ok(())
    }

    async fn read_refresh_output<F>(
        mut reader: BufReader<tokio::process::ChildStderr>,
        callback: &F,
        total: usize,
    ) -> Result<()>
    where
        F: Fn(RefreshProgress),
    {
        let mut current = 0;
        let mut buf = Vec::new();

        loop {
            buf.clear();

            let mut limited = (&mut reader).take(process::STDERR_LIMIT);
            if limited.read_until(b'\n', &mut buf).await? == 0 {
                break;
            }

            if buf.ends_with(b"\n") {
                buf.pop();
            }

            let line = String::from_utf8_lossy(&buf).into_owned();

            if line.contains("refreshing") || line.contains("requesting") {
                current += 1;
                let keyid = extract_keyid_from_line(&line);
                callback(RefreshProgress::Refreshing {
                    current,
                    total,
                    keyid,
                });
            } else if line.contains("error")
                || line.contains("failed")
                || line.contains("not found")
            {
                let keyid = extract_keyid_from_line(&line);
                callback(RefreshProgress::Error {
                    keyid,
                    message: line.clone(),
                });
            }
        }

        Ok(())
    }

    fn check_error(&self, status: std::process::ExitStatus, stderr: &[u8]) -> Error {
        check_gpg_error(self.get_homedir(), status, stderr)
    }
}

fn extract_keyid_from_line(line: &str) -> String {
    for word in line.split_whitespace().rev() {
        let trimmed = word.trim_end_matches([':', ',', '.']);
        let normalized = trimmed
            .strip_prefix("0x")
            .or_else(|| trimmed.strip_prefix("0X"))
            .unwrap_or(trimmed);
        if !normalized.is_empty()
            && normalized.chars().all(|c| c.is_ascii_hexdigit())
            && matches!(normalized.len(), 8 | 16 | 40)
        {
            return trimmed.to_uppercase();
        }
    }
    String::new()
}

#[cfg(test)]
mod subprocess_tests {
    use super::*;
    use crate::CancellationToken;
    use crate::process::tests::{Fixture, HUNG_GROUP};
    use std::cell::RefCell;
    use std::time::Duration;

    fn options() -> OperationOptions {
        OperationOptions {
            timeout_secs: Some(1),
            cancel_token: None,
        }
    }

    #[tokio::test]
    async fn refresh_deadline_covers_listing_keys() {
        let fixture = Fixture::new();
        let keyring = Keyring::new();
        let list = fixture.command("echo $$ > \"$1/parent\"; exec sleep 60");
        let refresh = fixture.command("touch \"$1/refreshed\"");
        let result = tokio::time::timeout(
            Duration::from_secs(5),
            keyring.refresh_with_commands(|_| {}, options(), list, refresh),
        )
        .await
        .unwrap();
        assert!(matches!(result, Err(Error::Timeout(1))), "{result:?}");
        assert!(!fixture.path("refreshed").exists());
        fixture.stopped().await;
    }

    #[tokio::test]
    async fn refresh_deadline_covers_waiting_after_stderr_closes() {
        let fixture = Fixture::new();
        let keyring = Keyring::new();
        let refresh = fixture.command("echo $$ > \"$1/parent\"; exec 2>&-; exec sleep 60");
        let result = tokio::time::timeout(
            Duration::from_secs(5),
            keyring.refresh_with_commands(|_| {}, options(), Command::new("true"), refresh),
        )
        .await
        .unwrap();
        assert!(matches!(result, Err(Error::Timeout(1))), "{result:?}");
        fixture.stopped().await;
    }

    #[tokio::test]
    async fn refresh_cancellation_covers_waiting_after_stderr_closes() {
        let fixture = Fixture::new();
        let cancel = CancellationToken::new();
        let options = OperationOptions {
            timeout_secs: None,
            cancel_token: Some(cancel.clone()),
        };
        let refresh = fixture
            .command("echo $$ > \"$1/parent\"; exec 2>&-; touch \"$1/ready\"; exec sleep 60");
        let task = tokio::spawn(async move {
            Keyring::new()
                .refresh_with_commands(|_| {}, options, Command::new("true"), refresh)
                .await
        });
        fixture.ready().await;
        cancel.cancel();
        let result = tokio::time::timeout(Duration::from_secs(5), task)
            .await
            .unwrap()
            .unwrap();
        assert!(matches!(result, Err(Error::Cancelled)), "{result:?}");
        fixture.stopped().await;
    }

    #[tokio::test]
    async fn aborting_refresh_kills_its_process_group() {
        let fixture = Fixture::new();
        let refresh = fixture.command(HUNG_GROUP);
        let task = tokio::spawn(async move {
            Keyring::new()
                .refresh_with_commands(
                    |_| {},
                    OperationOptions::default(),
                    Command::new("true"),
                    refresh,
                )
                .await
        });
        fixture.ready().await;
        task.abort();
        assert!(task.await.unwrap_err().is_cancelled());
        fixture.stopped().await;
    }

    #[tokio::test]
    async fn refresh_does_not_start_after_the_deadline() {
        let fixture = Fixture::new();
        let result = Keyring::new()
            .refresh_with_commands(
                |_| std::thread::sleep(Duration::from_secs(1)),
                options(),
                Command::new("true"),
                Command::new(fixture.path("missing")),
            )
            .await;
        assert!(matches!(result, Err(Error::Timeout(1))), "{result:?}");
    }

    #[tokio::test]
    async fn refresh_reports_progress_from_stderr() {
        let fixture = Fixture::new();
        let mut list = Command::new("echo");
        list.arg(crate::parse::tests::SAMPLE_KEY_OUTPUT);
        let refresh = fixture.command(
            "echo 'gpg: requesting key DEADBEEF from hkps://keys.example' >&2; \
             echo 'gpg: key 786C63F330D7CB92: not found on keyserver' >&2",
        );
        let events = RefCell::new(Vec::new());
        let result = Keyring::new()
            .refresh_with_commands(|p| events.borrow_mut().push(p), options(), list, refresh)
            .await;
        assert!(result.is_ok(), "{result:?}");
        let events = events.into_inner();
        assert!(
            matches!(
                &events[..],
                [
                    RefreshProgress::Starting { total_keys: 2 },
                    RefreshProgress::Refreshing { current: 1, total: 2, keyid: refreshed },
                    RefreshProgress::Error { keyid: failed, .. },
                    RefreshProgress::Completed,
                ] if refreshed == "DEADBEEF" && failed == "786C63F330D7CB92"
            ),
            "{events:?}"
        );
    }

    #[tokio::test]
    async fn refresh_stops_when_listing_fails() {
        let fixture = Fixture::new();
        let result = Keyring::new()
            .refresh_with_commands(
                |p| panic!("{p:?}"),
                options(),
                fixture.command("echo 'gpg: Permission denied' >&2; exit 2"),
                Command::new(fixture.path("missing")),
            )
            .await;
        assert!(matches!(result, Err(Error::PermissionDenied)), "{result:?}");
    }

    #[tokio::test]
    async fn refresh_reports_a_failed_exit() {
        let fixture = Fixture::new();
        let result = Keyring::new()
            .refresh_with_commands(
                |p| assert_ne!(p, RefreshProgress::Completed),
                options(),
                Command::new("true"),
                fixture.command("exit 3"),
            )
            .await;
        assert!(
            matches!(result, Err(Error::PacmanKey { status: 3, .. })),
            "{result:?}"
        );
    }

    #[tokio::test]
    async fn set_ownertrust_round_trips_through_gpg() {
        let dir = tempfile::tempdir().unwrap();
        let keyring = Keyring {
            reader: Keyring::with_homedir(dir.path().to_string_lossy()),
            keyserver: None,
        };
        let fingerprint = "ABAF11C65A2970B130ABE3C479BE3E4300411886";
        tokio::time::timeout(
            Duration::from_secs(10),
            keyring.set_ownertrust(&[(fingerprint, OwnerTrust::Full)]),
        )
        .await
        .unwrap()
        .unwrap();
        assert_eq!(
            keyring.get_ownertrust().await.unwrap(),
            vec![(fingerprint.to_string(), OwnerTrust::Full)]
        );
    }

    #[tokio::test]
    async fn zero_timeout_disables_refresh_deadline() {
        let options = OperationOptions {
            timeout_secs: Some(0),
            cancel_token: None,
        };
        let result = Keyring::new()
            .refresh_with_commands(|_| {}, options, Command::new("true"), Command::new("true"))
            .await;
        assert!(result.is_ok(), "{result:?}");
    }

    #[tokio::test]
    async fn refresh_reads_an_overlong_line_in_bounded_chunks() {
        let fixture = Fixture::new();
        let script = format!(
            "yes requesting 2>/dev/null | tr -d '\\n' | head -c {} >&2",
            3 * process::STDERR_LIMIT
        );
        let refreshing = std::cell::Cell::new(0);
        let result = Keyring::new()
            .refresh_with_commands(
                |p| {
                    if matches!(p, RefreshProgress::Refreshing { .. }) {
                        refreshing.set(refreshing.get() + 1);
                    }
                },
                OperationOptions::default(),
                Command::new("true"),
                fixture.command(&script),
            )
            .await;
        assert!(result.is_ok(), "{result:?}");
        assert_eq!(refreshing.get(), 3);
    }

    #[test]
    fn refresh_lists_with_gpg_then_runs_pacman_key() {
        let argv = |command: &Command| {
            let command = command.as_std();
            std::iter::once(command.get_program())
                .chain(command.get_args())
                .map(|arg| arg.to_string_lossy().into_owned())
                .collect::<Vec<_>>()
        };
        let (list, refresh) = Keyring::new()
            .with_keyserver("hkps://keys.example")
            .refresh_commands();
        assert_eq!(
            argv(&list),
            [
                "gpg",
                "--homedir=/etc/pacman.d/gnupg",
                "--list-keys",
                "--with-colons"
            ]
        );
        assert_eq!(
            argv(&refresh),
            [
                "pacman-key",
                "--keyserver",
                "hkps://keys.example",
                "--refresh-keys"
            ]
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_extract_keyid_from_refresh_line() {
        assert_eq!(
            extract_keyid_from_line("gpg: refreshing 1 key from hkps://keyserver.ubuntu.com"),
            ""
        );
        assert_eq!(
            extract_keyid_from_line(
                "gpg: requesting key DEADBEEF from hkps://keyserver.ubuntu.com"
            ),
            "DEADBEEF"
        );
        assert_eq!(
            extract_keyid_from_line("gpg: key 786C63F330D7CB92: public key imported"),
            "786C63F330D7CB92"
        );
    }

    #[test]
    fn test_extract_keyid_lowercase_normalized() {
        assert_eq!(
            extract_keyid_from_line("gpg: key deadbeef: something"),
            "DEADBEEF"
        );
    }

    #[test]
    fn test_extract_keyid_no_match() {
        assert_eq!(extract_keyid_from_line("gpg: some other message"), "");
        assert_eq!(extract_keyid_from_line(""), "");
    }

    #[test]
    fn test_check_error_permission_denied() {
        let keyring = Keyring::new();
        let stderr = b"gpg: Permission denied";
        let status = std::process::Command::new("false").status().unwrap();

        let err = keyring.check_error(status, stderr);
        assert!(matches!(err, Error::PermissionDenied));
    }

    #[test]
    fn test_check_error_permission_denied_lowercase() {
        let keyring = Keyring::new();
        let stderr = b"gpg: permission denied (are you root?)";
        let status = std::process::Command::new("false").status().unwrap();

        let err = keyring.check_error(status, stderr);
        assert!(matches!(err, Error::PermissionDenied));
    }

    #[test]
    fn test_check_error_keyring_not_initialized() {
        let keyring = Keyring::new();
        let stderr = b"gpg: keybox '/etc/pacman.d/gnupg/pubring.kbx': No such file or directory";
        let status = std::process::Command::new("false").status().unwrap();

        let err = keyring.check_error(status, stderr);
        assert!(matches!(err, Error::KeyringNotInitialized));
    }

    #[test]
    fn test_check_error_generic() {
        let keyring = Keyring::new();
        let stderr = b"gpg: some unknown error";
        let status = std::process::Command::new("false").status().unwrap();

        let err = keyring.check_error(status, stderr);
        match err {
            Error::PacmanKey { status: _, stderr } => {
                assert!(stderr.contains("some unknown error"));
            }
            _ => panic!("expected PacmanKey error"),
        }
    }

    #[test]
    fn test_is_initialized_directory_missing() {
        let reader = ReadOnlyKeyring {
            gpg_homedir: "/nonexistent/path/that/does/not/exist".to_string(),
        };
        let status = reader.is_initialized().unwrap();
        assert_eq!(status, InitializationStatus::DirectoryMissing);
    }

    fn keyring_dir(files: &[(&str, &[u8])]) -> (tempfile::TempDir, ReadOnlyKeyring) {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().unwrap();
        let homedir = dir.path().join("gnupg");
        std::fs::create_dir(&homedir).unwrap();
        std::fs::set_permissions(&homedir, std::fs::Permissions::from_mode(0o755)).unwrap();
        for (name, data) in files {
            std::fs::write(homedir.join(name), data).unwrap();
        }
        (dir, Keyring::with_homedir(homedir.to_string_lossy()))
    }

    #[test]
    fn test_is_initialized_no_keyring_files() {
        let (_dir, reader) = keyring_dir(&[]);
        let status = reader.is_initialized().unwrap();
        assert_eq!(status, InitializationStatus::NoKeyringFiles);
    }

    #[test]
    fn test_is_initialized_no_trustdb() {
        let (_dir, reader) = keyring_dir(&[("pubring.kbx", b"data")]);
        let status = reader.is_initialized().unwrap();
        assert_eq!(status, InitializationStatus::NoTrustDb);
    }

    #[test]
    fn test_is_initialized_incorrect_permissions() {
        use std::os::unix::fs::PermissionsExt;

        let (_dir, reader) = keyring_dir(&[("pubring.kbx", b"data"), ("trustdb.gpg", b"data")]);
        for mode in [0o700, 0o777, 0o2755] {
            std::fs::set_permissions(&reader.gpg_homedir, std::fs::Permissions::from_mode(mode))
                .unwrap();
            let status = reader.is_initialized().unwrap();
            assert_eq!(
                status,
                InitializationStatus::IncorrectPermissions { actual: mode }
            );
        }
    }

    #[test]
    fn test_is_initialized_ready() {
        let (_dir, reader) = keyring_dir(&[("pubring.kbx", b"data"), ("trustdb.gpg", b"data")]);
        let status = reader.is_initialized().unwrap();
        assert_eq!(status, InitializationStatus::Ready);
    }

    #[test]
    fn test_is_initialized_with_legacy_pubring() {
        let (_dir, reader) = keyring_dir(&[("pubring.gpg", b"data"), ("trustdb.gpg", b"data")]);
        let status = reader.is_initialized().unwrap();
        assert_eq!(status, InitializationStatus::Ready);
    }

    #[test]
    fn test_is_initialized_path_is_file() {
        use std::fs;
        use std::io::Write;

        let dir = tempfile::tempdir().unwrap();
        let tmp = dir.path().join("gnupg");
        fs::File::create(&tmp).unwrap().write_all(b"data").unwrap();

        let reader = ReadOnlyKeyring {
            gpg_homedir: tmp.to_string_lossy().to_string(),
        };
        let status = reader.is_initialized().unwrap();
        assert_eq!(status, InitializationStatus::PathIsFile);
    }

    #[test]
    fn test_is_initialized_dangling_symlink() {
        use std::os::unix::fs::symlink;

        let dir = tempfile::tempdir().unwrap();
        let link = dir.path().join("gnupg");
        symlink("/nonexistent/pacman_key_target", &link).unwrap();

        let reader = ReadOnlyKeyring {
            gpg_homedir: link.to_string_lossy().to_string(),
        };
        let status = reader.is_initialized().unwrap();
        assert_eq!(status, InitializationStatus::DirectoryMissing);
    }

    #[test]
    fn test_is_initialized_follows_symlink() {
        use std::fs;
        use std::io::Write;
        use std::os::unix::fs::PermissionsExt;
        use std::os::unix::fs::symlink;

        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("target");
        let link = dir.path().join("gnupg");

        fs::create_dir(&target).unwrap();
        fs::set_permissions(&target, fs::Permissions::from_mode(0o755)).unwrap();
        fs::File::create(target.join("pubring.kbx"))
            .unwrap()
            .write_all(b"data")
            .unwrap();
        fs::File::create(target.join("trustdb.gpg"))
            .unwrap()
            .write_all(b"data")
            .unwrap();
        symlink(&target, &link).unwrap();

        let reader = ReadOnlyKeyring {
            gpg_homedir: link.to_string_lossy().to_string(),
        };
        let status = reader.is_initialized().unwrap();
        assert_eq!(status, InitializationStatus::Ready);
    }

    #[test]
    fn test_is_initialized_empty_files_treated_as_missing() {
        let (_dir, reader) = keyring_dir(&[("pubring.kbx", b""), ("trustdb.gpg", b"")]);
        let status = reader.is_initialized().unwrap();
        assert_eq!(status, InitializationStatus::NoKeyringFiles);
    }
}