Skip to main content

pacman_key/
keyring.rs

1use std::path::Path;
2use std::process::Stdio;
3use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader};
4use tokio::process::Command;
5
6use crate::error::{Error, Result};
7use crate::parse::{parse_keys, parse_ownertrust, parse_signatures, parse_verify_status};
8use crate::process::{self, Operation};
9use crate::types::{
10    InitializationStatus, Key, OperationOptions, OwnerTrust, RefreshProgress, Signature,
11    VerifyResult,
12};
13use crate::validation::{validate_keyid, validate_keyring_name, validate_path};
14
15const DEFAULT_GPG_HOMEDIR: &str = "/etc/pacman.d/gnupg";
16
17/// Read-only interface for querying a GPG keyring.
18///
19/// This type is returned by [`Keyring::with_homedir`] and only provides
20/// read operations (`list_keys`, `list_signatures`). Write operations
21/// require a [`Keyring`] which targets the system pacman keyring.
22///
23/// # Example
24///
25/// ```no_run
26/// # async fn example() -> pacman_key::Result<()> {
27/// use pacman_key::Keyring;
28///
29/// let reader = Keyring::with_homedir("/custom/gnupg");
30/// let keys = reader.list_keys().await?;
31/// # Ok(())
32/// # }
33/// ```
34pub struct ReadOnlyKeyring {
35    gpg_homedir: String,
36}
37
38impl ReadOnlyKeyring {
39    fn gpg(&self) -> Command {
40        let mut command = Command::new("gpg");
41        command.arg(format!("--homedir={}", self.gpg_homedir));
42        command
43    }
44
45    async fn run_checked(&self, command: &mut Command, operation: &Operation) -> Result<Vec<u8>> {
46        let output = process::output(command, operation).await?;
47
48        if !output.status.success() {
49            return Err(check_gpg_error(
50                &self.gpg_homedir,
51                output.status,
52                &output.stderr,
53            ));
54        }
55
56        Ok(output.stdout)
57    }
58
59    async fn run_gpg<I, S>(&self, args: I) -> Result<Vec<u8>>
60    where
61        I: IntoIterator<Item = S>,
62        S: AsRef<std::ffi::OsStr>,
63    {
64        self.run_checked(self.gpg().args(args), &Operation::default())
65            .await
66    }
67
68    /// Lists all keys in the keyring.
69    pub async fn list_keys(&self) -> Result<Vec<Key>> {
70        let stdout = self.run_gpg(["--list-keys", "--with-colons"]).await?;
71        parse_keys(&String::from_utf8_lossy(&stdout))
72    }
73
74    /// Lists signatures on keys in the keyring (non-checking `--list-sigs`).
75    ///
76    /// If `keyid` is provided, lists signatures only for that key.
77    /// Otherwise lists all signatures in the keyring. The `status` field of
78    /// each [`Signature`] is `None`; use [`check_signatures`] to verify them.
79    ///
80    /// [`check_signatures`]: Self::check_signatures
81    pub async fn list_signatures(&self, keyid: Option<&str>) -> Result<Vec<Signature>> {
82        self.run_list_sigs("--list-sigs", keyid).await
83    }
84
85    /// Lists and verifies signatures on keys (`--check-sigs`).
86    ///
87    /// Like [`list_signatures`] but each [`Signature`]'s `status` is populated
88    /// with the verification result.
89    ///
90    /// [`list_signatures`]: Self::list_signatures
91    pub async fn check_signatures(&self, keyid: Option<&str>) -> Result<Vec<Signature>> {
92        self.run_list_sigs("--check-sigs", keyid).await
93    }
94
95    async fn run_list_sigs(&self, op: &str, keyid: Option<&str>) -> Result<Vec<Signature>> {
96        let mut args = vec![op.to_string(), "--with-colons".to_string()];
97        if let Some(id) = keyid {
98            args.push(validate_keyid(id)?);
99        }
100        let stdout = self.run_gpg(args).await?;
101        parse_signatures(&String::from_utf8_lossy(&stdout))
102    }
103
104    /// Exports the given keys as an ASCII-armored block.
105    ///
106    /// An empty `keyids` slice exports all public keys. Mirrors
107    /// `pacman-key --export`.
108    pub async fn export_keys(&self, keyids: &[&str]) -> Result<String> {
109        let mut args = vec!["--armor".to_string(), "--export".to_string()];
110        for id in keyids {
111            args.push(validate_keyid(id)?);
112        }
113        let stdout = self.run_gpg(args).await?;
114        Ok(String::from_utf8_lossy(&stdout).into_owned())
115    }
116
117    /// Returns the fingerprints of the given keys (or all keys if empty).
118    ///
119    /// Mirrors `pacman-key --finger`. Note [`list_keys`] already returns the
120    /// same fingerprints alongside the full key data; this is a convenience
121    /// for when only fingerprints are needed.
122    ///
123    /// [`list_keys`]: Self::list_keys
124    pub async fn fingerprints(&self, keyids: &[&str]) -> Result<Vec<String>> {
125        let mut args = vec!["--with-colons".to_string(), "--fingerprint".to_string()];
126        for id in keyids {
127            args.push(validate_keyid(id)?);
128        }
129        let stdout = self.run_gpg(args).await?;
130        let keys = parse_keys(&String::from_utf8_lossy(&stdout))?;
131        Ok(keys.into_iter().map(|k| k.fingerprint).collect())
132    }
133
134    /// Verifies a signature against the keyring.
135    ///
136    /// `sig` is the (binary) signature file; `file` is the signed data for a
137    /// detached signature (omit for an embedded one). Mirrors
138    /// `pacman-key --verify`, which rejects ASCII-armored signatures.
139    ///
140    /// Returns a [`VerifyResult`]; a bad signature is reported via
141    /// `good == false`, not an error. Only an inability to run gpg or read the
142    /// signature file produces an `Err`.
143    pub async fn verify_signature(&self, sig: &Path, file: Option<&Path>) -> Result<VerifyResult> {
144        let bytes = std::fs::read(sig).map_err(Error::Command)?;
145        if bytes
146            .windows(b"BEGIN PGP SIGNATURE".len())
147            .any(|w| w == b"BEGIN PGP SIGNATURE")
148        {
149            return Err(Error::InvalidPath {
150                path: sig.display().to_string(),
151                reason: "armored signatures are not supported (use a binary signature)".to_string(),
152            });
153        }
154
155        let mut args = vec![
156            "--status-fd".to_string(),
157            "1".to_string(),
158            "--verify".to_string(),
159            validate_path(sig)?,
160        ];
161        if let Some(f) = file {
162            args.push(validate_path(f)?);
163        }
164
165        // gpg exits non-zero on a bad/untrusted signature; that is a verdict,
166        // not a failure, so capture stdout regardless of exit status.
167        let output = process::output(self.gpg().args(&args), &Operation::default()).await?;
168
169        Ok(parse_verify_status(&String::from_utf8_lossy(
170            &output.stdout,
171        )))
172    }
173
174    /// Reads owner-trust assignments via `gpg --export-ownertrust`.
175    pub async fn get_ownertrust(&self) -> Result<Vec<(String, OwnerTrust)>> {
176        let stdout = self.run_gpg(["--export-ownertrust"]).await?;
177        Ok(parse_ownertrust(&String::from_utf8_lossy(&stdout)))
178    }
179
180    /// Checks whether the keyring is initialized without spawning GPG.
181    ///
182    /// Verifies the directory exists with mode 755 (as created by
183    /// `pacman-key --init`; world-readable so unprivileged pacman can read
184    /// the public keyring, pacman commit 4ef664f4) and contains a non-empty
185    /// pubring.kbx or pubring.gpg plus trustdb.gpg. Symlinks are followed.
186    /// Non-atomic and subject to TOCTOU races; use for informational
187    /// purposes, not security decisions.
188    pub fn is_initialized(&self) -> Result<InitializationStatus> {
189        use std::fs;
190        use std::os::unix::fs::PermissionsExt;
191        use std::path::Path;
192
193        let dir = Path::new(&self.gpg_homedir);
194
195        let metadata = match fs::metadata(dir) {
196            Ok(m) => m,
197            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
198                return Ok(InitializationStatus::DirectoryMissing);
199            }
200            Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
201                return Err(Error::PermissionDenied);
202            }
203            Err(e) => return Err(Error::Command(e)),
204        };
205
206        if metadata.is_file() {
207            return Ok(InitializationStatus::PathIsFile);
208        }
209
210        if !metadata.is_dir() {
211            return Ok(InitializationStatus::DirectoryMissing);
212        }
213
214        // mask keeps setuid/setgid/sticky so nonstandard special bits are flagged
215        let mode = metadata.permissions().mode() & 0o7777;
216        if mode != 0o755 {
217            return Ok(InitializationStatus::IncorrectPermissions { actual: mode });
218        }
219
220        // Check for keyring files, propagating permission errors
221        let has_pubring = Self::file_exists_and_nonempty(&dir.join("pubring.kbx"))?
222            || Self::file_exists_and_nonempty(&dir.join("pubring.gpg"))?;
223        if !has_pubring {
224            return Ok(InitializationStatus::NoKeyringFiles);
225        }
226
227        if !Self::file_exists_and_nonempty(&dir.join("trustdb.gpg"))? {
228            return Ok(InitializationStatus::NoTrustDb);
229        }
230
231        Ok(InitializationStatus::Ready)
232    }
233
234    fn file_exists_and_nonempty(path: &std::path::Path) -> Result<bool> {
235        use std::fs;
236
237        match fs::metadata(path) {
238            Ok(m) => Ok(m.is_file() && m.len() > 0),
239            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
240            Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
241                Err(Error::PermissionDenied)
242            }
243            Err(e) => Err(Error::Command(e)),
244        }
245    }
246}
247
248fn check_gpg_error(homedir: &str, status: std::process::ExitStatus, stderr: &[u8]) -> Error {
249    let msg = String::from_utf8_lossy(stderr);
250
251    if msg.contains("Permission denied") || msg.contains("permission denied") {
252        return Error::PermissionDenied;
253    }
254
255    if msg.contains("No such file or directory") && msg.contains(homedir) {
256        return Error::KeyringNotInitialized;
257    }
258
259    Error::PacmanKey {
260        status: status.code().unwrap_or(-1),
261        stderr: msg.to_string(),
262    }
263}
264
265/// Builds a `pacman-key` arg vector from an operation flag and validated paths.
266fn paths_to_args(flag: &str, paths: &[&Path]) -> Result<Vec<String>> {
267    let mut args = vec![flag.to_string()];
268    for p in paths {
269        args.push(validate_path(p)?);
270    }
271    Ok(args)
272}
273
274/// Interface for managing the pacman keyring.
275///
276/// Provides async methods for key listing, importing, signing, and keyring management.
277///
278/// # Root Privileges
279///
280/// Write operations (`init_keyring`, `populate`, `receive_keys`, `locally_sign_key`,
281/// `delete_key`) require root privileges and will return [`Error::PermissionDenied`]
282/// if called without sufficient permissions.
283///
284/// [`Error::PermissionDenied`]: crate::Error::PermissionDenied
285///
286/// # Example
287///
288/// ```no_run
289/// use pacman_key::Keyring;
290///
291/// # async fn example() -> pacman_key::Result<()> {
292/// let keyring = Keyring::new();
293/// let keys = keyring.list_keys().await?;
294/// println!("Found {} keys", keys.len());
295/// # Ok(())
296/// # }
297/// ```
298pub struct Keyring {
299    reader: ReadOnlyKeyring,
300    keyserver: Option<String>,
301}
302
303impl Default for Keyring {
304    fn default() -> Self {
305        Self::new()
306    }
307}
308
309impl Keyring {
310    /// Creates a new Keyring using the default pacman keyring path.
311    #[must_use]
312    pub fn new() -> Self {
313        Self {
314            reader: ReadOnlyKeyring {
315                gpg_homedir: DEFAULT_GPG_HOMEDIR.to_string(),
316            },
317            keyserver: None,
318        }
319    }
320
321    /// Sets the keyserver used by [`receive_keys`] and [`refresh_keys`].
322    ///
323    /// Maps to pacman-key's `--keyserver`. When unset, gpg's configured
324    /// default keyserver is used.
325    ///
326    /// [`receive_keys`]: Self::receive_keys
327    /// [`refresh_keys`]: Self::refresh_keys
328    #[must_use]
329    pub fn with_keyserver(mut self, url: impl Into<String>) -> Self {
330        self.keyserver = Some(url.into());
331        self
332    }
333
334    /// Creates a read-only keyring interface for a custom GPG home directory.
335    ///
336    /// Returns a [`ReadOnlyKeyring`] that can only perform read operations
337    /// (`list_keys`, `list_signatures`). This is useful for inspecting
338    /// alternative keyrings without risking modifications.
339    ///
340    /// # Example
341    ///
342    /// ```no_run
343    /// # async fn example() -> pacman_key::Result<()> {
344    /// use pacman_key::Keyring;
345    ///
346    /// let reader = Keyring::with_homedir("/custom/gnupg");
347    /// let keys = reader.list_keys().await?;
348    /// # Ok(())
349    /// # }
350    /// ```
351    #[must_use]
352    pub fn with_homedir(path: impl Into<String>) -> ReadOnlyKeyring {
353        ReadOnlyKeyring {
354            gpg_homedir: path.into(),
355        }
356    }
357
358    pub fn get_homedir(&self) -> &str {
359        &self.reader.gpg_homedir
360    }
361
362    async fn run_pacman_key<I, S>(&self, args: I) -> Result<()>
363    where
364        I: IntoIterator<Item = S>,
365        S: AsRef<std::ffi::OsStr>,
366    {
367        self.run_pacman_key_with_options(args, OperationOptions::default())
368            .await
369    }
370
371    async fn run_pacman_key_with_options<I, S>(
372        &self,
373        args: I,
374        options: OperationOptions,
375    ) -> Result<()>
376    where
377        I: IntoIterator<Item = S>,
378        S: AsRef<std::ffi::OsStr>,
379    {
380        let (status, stderr) = process::stderr_only(
381            Command::new("pacman-key").args(args),
382            &Operation::new(options),
383        )
384        .await?;
385        if !status.success() {
386            return Err(self.check_error(status, &stderr));
387        }
388        Ok(())
389    }
390
391    /// Lists all keys in the keyring.
392    ///
393    /// # Example
394    ///
395    /// ```no_run
396    /// # async fn example() -> pacman_key::Result<()> {
397    /// use pacman_key::Keyring;
398    ///
399    /// let keyring = Keyring::new();
400    /// for key in keyring.list_keys().await? {
401    ///     println!("{} - {:?}", key.uid, key.validity);
402    /// }
403    /// # Ok(())
404    /// # }
405    /// ```
406    pub async fn list_keys(&self) -> Result<Vec<Key>> {
407        self.reader.list_keys().await
408    }
409
410    /// Lists signatures on keys in the keyring (non-checking `--list-sigs`).
411    ///
412    /// If `keyid` is provided, lists signatures only for that key.
413    /// Otherwise lists all signatures in the keyring.
414    pub async fn list_signatures(&self, keyid: Option<&str>) -> Result<Vec<Signature>> {
415        self.reader.list_signatures(keyid).await
416    }
417
418    /// Lists and verifies signatures on keys (`--check-sigs`).
419    ///
420    /// See [`ReadOnlyKeyring::check_signatures`].
421    pub async fn check_signatures(&self, keyid: Option<&str>) -> Result<Vec<Signature>> {
422        self.reader.check_signatures(keyid).await
423    }
424
425    /// Exports the given keys (or all keys) as an ASCII-armored block.
426    ///
427    /// See [`ReadOnlyKeyring::export_keys`].
428    pub async fn export_keys(&self, keyids: &[&str]) -> Result<String> {
429        self.reader.export_keys(keyids).await
430    }
431
432    /// Returns the fingerprints of the given keys (or all keys).
433    ///
434    /// See [`ReadOnlyKeyring::fingerprints`].
435    pub async fn fingerprints(&self, keyids: &[&str]) -> Result<Vec<String>> {
436        self.reader.fingerprints(keyids).await
437    }
438
439    /// Verifies a signature against the keyring.
440    ///
441    /// See [`ReadOnlyKeyring::verify_signature`].
442    pub async fn verify_signature(&self, sig: &Path, file: Option<&Path>) -> Result<VerifyResult> {
443        self.reader.verify_signature(sig, file).await
444    }
445
446    /// Reads owner-trust assignments.
447    ///
448    /// See [`ReadOnlyKeyring::get_ownertrust`].
449    pub async fn get_ownertrust(&self) -> Result<Vec<(String, OwnerTrust)>> {
450        self.reader.get_ownertrust().await
451    }
452
453    /// Checks whether the keyring is initialized without spawning GPG.
454    ///
455    /// See [`ReadOnlyKeyring::is_initialized`] for details.
456    pub fn is_initialized(&self) -> Result<InitializationStatus> {
457        self.reader.is_initialized()
458    }
459
460    /// Initializes the pacman keyring.
461    ///
462    /// Creates the keyring directory and generates a local signing key.
463    /// For timeout/cancellation support, use [`init_keyring_with_options`].
464    ///
465    /// [`init_keyring_with_options`]: Self::init_keyring_with_options
466    pub async fn init_keyring(&self) -> Result<()> {
467        self.init_keyring_with_options(OperationOptions::default())
468            .await
469    }
470
471    /// Initializes the pacman keyring with timeout and cancellation support.
472    ///
473    /// Creates the keyring directory and generates a local signing key.
474    pub async fn init_keyring_with_options(&self, options: OperationOptions) -> Result<()> {
475        self.run_pacman_key_with_options(&["--init"], options).await
476    }
477
478    /// Populates the keyring with keys from distribution keyrings.
479    ///
480    /// If no keyrings are specified, defaults to "archlinux". Keyring names
481    /// must contain only alphanumeric characters, hyphens, or underscores.
482    /// For timeout/cancellation support, use [`populate_with_options`].
483    ///
484    /// [`populate_with_options`]: Self::populate_with_options
485    pub async fn populate(&self, keyrings: &[&str]) -> Result<()> {
486        self.populate_with_options(keyrings, OperationOptions::default())
487            .await
488    }
489
490    /// Populates the keyring with timeout and cancellation support.
491    ///
492    /// If no keyrings are specified, defaults to "archlinux". Keyring names
493    /// must contain only alphanumeric characters, hyphens, or underscores.
494    pub async fn populate_with_options(
495        &self,
496        keyrings: &[&str],
497        options: OperationOptions,
498    ) -> Result<()> {
499        for name in keyrings {
500            validate_keyring_name(name)?;
501        }
502
503        let keyring_args: Vec<&str> = if keyrings.is_empty() {
504            vec!["archlinux"]
505        } else {
506            keyrings.to_vec()
507        };
508
509        let args: Vec<&str> = std::iter::once("--populate").chain(keyring_args).collect();
510
511        self.run_pacman_key_with_options(&args, options).await
512    }
513
514    /// Receives keys from a keyserver.
515    pub async fn receive_keys(&self, keyids: &[&str]) -> Result<()> {
516        self.receive_keys_with_options(keyids, OperationOptions::default())
517            .await
518    }
519
520    /// Receives keys from a keyserver with timeout and cancellation support.
521    ///
522    /// Uses the keyserver set via [`with_keyserver`], if any.
523    ///
524    /// [`with_keyserver`]: Self::with_keyserver
525    pub async fn receive_keys_with_options(
526        &self,
527        keyids: &[&str],
528        options: OperationOptions,
529    ) -> Result<()> {
530        if keyids.is_empty() {
531            return Ok(());
532        }
533
534        let validated: Vec<String> = keyids
535            .iter()
536            .map(|k| validate_keyid(k))
537            .collect::<Result<_>>()?;
538
539        let mut args: Vec<String> = Vec::new();
540        if let Some(ks) = &self.keyserver {
541            args.push("--keyserver".to_string());
542            args.push(ks.clone());
543        }
544        args.push("--recv-keys".to_string());
545        args.extend(validated);
546
547        self.run_pacman_key_with_options(args, options).await
548    }
549
550    /// Locally signs a key to mark it as trusted.
551    pub async fn locally_sign_key(&self, keyid: &str) -> Result<()> {
552        let validated = validate_keyid(keyid)?;
553        self.run_pacman_key(&["--lsign-key", &validated]).await
554    }
555
556    /// Deletes a key from the keyring.
557    pub async fn delete_key(&self, keyid: &str) -> Result<()> {
558        let validated = validate_keyid(keyid)?;
559        self.run_pacman_key(&["--delete", &validated]).await
560    }
561
562    /// Imports keys from file(s) into the keyring (`pacman-key --add`).
563    ///
564    /// Distinct from [`receive_keys`], which pulls from a keyserver. Each path
565    /// must exist. pacman-key updates the trust database afterward; this crate
566    /// does not, so call [`update_trustdb`] when trust state must be current.
567    ///
568    /// [`receive_keys`]: Self::receive_keys
569    /// [`update_trustdb`]: Self::update_trustdb
570    pub async fn add_keys(&self, files: &[&Path]) -> Result<()> {
571        self.add_keys_with_options(files, OperationOptions::default())
572            .await
573    }
574
575    /// Imports keys from file(s) with timeout and cancellation support.
576    pub async fn add_keys_with_options(
577        &self,
578        files: &[&Path],
579        options: OperationOptions,
580    ) -> Result<()> {
581        if files.is_empty() {
582            return Ok(());
583        }
584        let args = paths_to_args("--add", files)?;
585        self.run_pacman_key_with_options(args, options).await
586    }
587
588    /// Rebuilds the trust database (`pacman-key --updatedb`,
589    /// i.e. `gpg --check-trustdb`).
590    ///
591    /// pacman-key runs this automatically after every key-mutating operation;
592    /// this crate leaves it to the caller. Run it after `add_keys`,
593    /// `delete_key`, `locally_sign_key`, `receive_keys`, or `set_ownertrust`
594    /// to keep computed validity current.
595    pub async fn update_trustdb(&self) -> Result<()> {
596        self.update_trustdb_with_options(OperationOptions::default())
597            .await
598    }
599
600    /// Rebuilds the trust database with timeout and cancellation support.
601    pub async fn update_trustdb_with_options(&self, options: OperationOptions) -> Result<()> {
602        self.run_pacman_key_with_options(&["--updatedb"], options)
603            .await
604    }
605
606    /// Imports `pubring.gpg` from one or more keyring directories
607    /// (`pacman-key --import`).
608    pub async fn import_keyrings(&self, dirs: &[&Path]) -> Result<()> {
609        if dirs.is_empty() {
610            return Ok(());
611        }
612        self.run_pacman_key(paths_to_args("--import", dirs)?).await
613    }
614
615    /// Imports owner-trust values from `trustdb.gpg` in one or more keyring
616    /// directories (`pacman-key --import-trustdb`).
617    pub async fn import_trustdb(&self, dirs: &[&Path]) -> Result<()> {
618        if dirs.is_empty() {
619            return Ok(());
620        }
621        self.run_pacman_key(paths_to_args("--import-trustdb", dirs)?)
622            .await
623    }
624
625    /// Sets owner-trust levels for keys, non-interactively.
626    ///
627    /// A scriptable replacement for the trust submenu of `--edit-key`: feeds
628    /// `<fingerprint>:<level>:` lines to `gpg --import-ownertrust`. Each keyid
629    /// is validated. Run [`update_trustdb`] afterward to recompute validity.
630    ///
631    /// [`update_trustdb`]: Self::update_trustdb
632    pub async fn set_ownertrust(&self, entries: &[(&str, OwnerTrust)]) -> Result<()> {
633        if entries.is_empty() {
634            return Ok(());
635        }
636        let mut input = String::new();
637        for (keyid, trust) in entries {
638            let fpr = validate_keyid(keyid)?;
639            input.push_str(&format!("{}:{}:\n", fpr, trust.to_gpg_level()));
640        }
641        self.run_gpg_stdin(&["--import-ownertrust"], input.as_bytes())
642            .await
643    }
644
645    async fn run_gpg_stdin(&self, args: &[&str], input: &[u8]) -> Result<()> {
646        use tokio::io::AsyncWriteExt;
647
648        let mut command = self.reader.gpg();
649        command
650            .args(args)
651            .stdin(Stdio::piped())
652            .stdout(Stdio::null())
653            .stderr(Stdio::piped());
654        let (status, stderr) = process::run(&mut command, &Operation::default(), async |child| {
655            let mut stdin = child.stdin.take().expect("stdin is piped");
656            let stderr = child.stderr.take().expect("stderr is piped");
657            let ((), stderr) = tokio::try_join!(
658                // Moved in so stdin closes after the write; gpg waits for EOF.
659                async move { stdin.write_all(input).await },
660                process::collect(stderr, process::STDERR_LIMIT)
661            )?;
662            Ok(stderr)
663        })
664        .await?;
665        if !status.success() {
666            return Err(self.check_error(status, &stderr));
667        }
668        Ok(())
669    }
670
671    /// Refreshes all keys from the keyserver.
672    ///
673    /// This is a long-running operation. The callback receives progress updates
674    /// as keys are refreshed. The timeout covers the initial key listing as well
675    /// as the refresh.
676    ///
677    /// # Example
678    ///
679    /// ```no_run
680    /// # async fn example() -> pacman_key::Result<()> {
681    /// use pacman_key::{Keyring, OperationOptions, RefreshProgress, CancellationToken};
682    ///
683    /// let keyring = Keyring::new();
684    /// let token = CancellationToken::new();
685    /// let options = OperationOptions {
686    ///     timeout_secs: Some(300),
687    ///     cancel_token: Some(token.clone()),
688    /// };
689    ///
690    /// // Cancel from another task with: token.cancel()
691    /// keyring.refresh_keys(|p| println!("{p:?}"), options).await?;
692    /// # Ok(())
693    /// # }
694    /// ```
695    pub async fn refresh_keys<F>(&self, callback: F, options: OperationOptions) -> Result<()>
696    where
697        F: Fn(RefreshProgress),
698    {
699        let (list, refresh) = self.refresh_commands();
700        self.refresh_with_commands(callback, options, list, refresh)
701            .await
702    }
703
704    fn refresh_commands(&self) -> (Command, Command) {
705        let mut list = self.reader.gpg();
706        list.args(["--list-keys", "--with-colons"]);
707        let mut refresh = Command::new("pacman-key");
708        if let Some(ks) = &self.keyserver {
709            refresh.arg("--keyserver").arg(ks);
710        }
711        refresh.arg("--refresh-keys");
712        (list, refresh)
713    }
714
715    async fn refresh_with_commands<F>(
716        &self,
717        callback: F,
718        options: OperationOptions,
719        mut list: Command,
720        mut refresh: Command,
721    ) -> Result<()>
722    where
723        F: Fn(RefreshProgress),
724    {
725        let operation = Operation::new(options);
726        let listed = self.reader.run_checked(&mut list, &operation).await?;
727        let total = parse_keys(&String::from_utf8_lossy(&listed))?.len();
728        callback(RefreshProgress::Starting { total_keys: total });
729
730        refresh.stdout(Stdio::null()).stderr(Stdio::piped());
731        let (status, ()) = process::run(&mut refresh, &operation, async |child| {
732            let stderr = child.stderr.take().expect("stderr is piped");
733            Self::read_refresh_output(BufReader::new(stderr), &callback, total).await
734        })
735        .await?;
736        if !status.success() {
737            return Err(Error::PacmanKey {
738                status: status.code().unwrap_or(-1),
739                stderr: "refresh failed".to_string(),
740            });
741        }
742
743        callback(RefreshProgress::Completed);
744        Ok(())
745    }
746
747    async fn read_refresh_output<F>(
748        mut reader: BufReader<tokio::process::ChildStderr>,
749        callback: &F,
750        total: usize,
751    ) -> Result<()>
752    where
753        F: Fn(RefreshProgress),
754    {
755        let mut current = 0;
756        let mut buf = Vec::new();
757
758        loop {
759            buf.clear();
760
761            let mut limited = (&mut reader).take(process::STDERR_LIMIT);
762            if limited.read_until(b'\n', &mut buf).await? == 0 {
763                break;
764            }
765
766            if buf.ends_with(b"\n") {
767                buf.pop();
768            }
769
770            let line = String::from_utf8_lossy(&buf).into_owned();
771
772            if line.contains("refreshing") || line.contains("requesting") {
773                current += 1;
774                let keyid = extract_keyid_from_line(&line);
775                callback(RefreshProgress::Refreshing {
776                    current,
777                    total,
778                    keyid,
779                });
780            } else if line.contains("error")
781                || line.contains("failed")
782                || line.contains("not found")
783            {
784                let keyid = extract_keyid_from_line(&line);
785                callback(RefreshProgress::Error {
786                    keyid,
787                    message: line.clone(),
788                });
789            }
790        }
791
792        Ok(())
793    }
794
795    fn check_error(&self, status: std::process::ExitStatus, stderr: &[u8]) -> Error {
796        check_gpg_error(self.get_homedir(), status, stderr)
797    }
798}
799
800fn extract_keyid_from_line(line: &str) -> String {
801    for word in line.split_whitespace().rev() {
802        let trimmed = word.trim_end_matches([':', ',', '.']);
803        let normalized = trimmed
804            .strip_prefix("0x")
805            .or_else(|| trimmed.strip_prefix("0X"))
806            .unwrap_or(trimmed);
807        if !normalized.is_empty()
808            && normalized.chars().all(|c| c.is_ascii_hexdigit())
809            && matches!(normalized.len(), 8 | 16 | 40)
810        {
811            return trimmed.to_uppercase();
812        }
813    }
814    String::new()
815}
816
817#[cfg(test)]
818mod subprocess_tests {
819    use super::*;
820    use crate::CancellationToken;
821    use crate::process::tests::{Fixture, HUNG_GROUP};
822    use std::cell::RefCell;
823    use std::time::Duration;
824
825    fn options() -> OperationOptions {
826        OperationOptions {
827            timeout_secs: Some(1),
828            cancel_token: None,
829        }
830    }
831
832    #[tokio::test]
833    async fn refresh_deadline_covers_listing_keys() {
834        let fixture = Fixture::new();
835        let keyring = Keyring::new();
836        let list = fixture.command("echo $$ > \"$1/parent\"; exec sleep 60");
837        let refresh = fixture.command("touch \"$1/refreshed\"");
838        let result = tokio::time::timeout(
839            Duration::from_secs(5),
840            keyring.refresh_with_commands(|_| {}, options(), list, refresh),
841        )
842        .await
843        .unwrap();
844        assert!(matches!(result, Err(Error::Timeout(1))), "{result:?}");
845        assert!(!fixture.path("refreshed").exists());
846        fixture.stopped().await;
847    }
848
849    #[tokio::test]
850    async fn refresh_deadline_covers_waiting_after_stderr_closes() {
851        let fixture = Fixture::new();
852        let keyring = Keyring::new();
853        let refresh = fixture.command("echo $$ > \"$1/parent\"; exec 2>&-; exec sleep 60");
854        let result = tokio::time::timeout(
855            Duration::from_secs(5),
856            keyring.refresh_with_commands(|_| {}, options(), Command::new("true"), refresh),
857        )
858        .await
859        .unwrap();
860        assert!(matches!(result, Err(Error::Timeout(1))), "{result:?}");
861        fixture.stopped().await;
862    }
863
864    #[tokio::test]
865    async fn refresh_cancellation_covers_waiting_after_stderr_closes() {
866        let fixture = Fixture::new();
867        let cancel = CancellationToken::new();
868        let options = OperationOptions {
869            timeout_secs: None,
870            cancel_token: Some(cancel.clone()),
871        };
872        let refresh = fixture
873            .command("echo $$ > \"$1/parent\"; exec 2>&-; touch \"$1/ready\"; exec sleep 60");
874        let task = tokio::spawn(async move {
875            Keyring::new()
876                .refresh_with_commands(|_| {}, options, Command::new("true"), refresh)
877                .await
878        });
879        fixture.ready().await;
880        cancel.cancel();
881        let result = tokio::time::timeout(Duration::from_secs(5), task)
882            .await
883            .unwrap()
884            .unwrap();
885        assert!(matches!(result, Err(Error::Cancelled)), "{result:?}");
886        fixture.stopped().await;
887    }
888
889    #[tokio::test]
890    async fn aborting_refresh_kills_its_process_group() {
891        let fixture = Fixture::new();
892        let refresh = fixture.command(HUNG_GROUP);
893        let task = tokio::spawn(async move {
894            Keyring::new()
895                .refresh_with_commands(
896                    |_| {},
897                    OperationOptions::default(),
898                    Command::new("true"),
899                    refresh,
900                )
901                .await
902        });
903        fixture.ready().await;
904        task.abort();
905        assert!(task.await.unwrap_err().is_cancelled());
906        fixture.stopped().await;
907    }
908
909    #[tokio::test]
910    async fn refresh_does_not_start_after_the_deadline() {
911        let fixture = Fixture::new();
912        let result = Keyring::new()
913            .refresh_with_commands(
914                |_| std::thread::sleep(Duration::from_secs(1)),
915                options(),
916                Command::new("true"),
917                Command::new(fixture.path("missing")),
918            )
919            .await;
920        assert!(matches!(result, Err(Error::Timeout(1))), "{result:?}");
921    }
922
923    #[tokio::test]
924    async fn refresh_reports_progress_from_stderr() {
925        let fixture = Fixture::new();
926        let mut list = Command::new("echo");
927        list.arg(crate::parse::tests::SAMPLE_KEY_OUTPUT);
928        let refresh = fixture.command(
929            "echo 'gpg: requesting key DEADBEEF from hkps://keys.example' >&2; \
930             echo 'gpg: key 786C63F330D7CB92: not found on keyserver' >&2",
931        );
932        let events = RefCell::new(Vec::new());
933        let result = Keyring::new()
934            .refresh_with_commands(|p| events.borrow_mut().push(p), options(), list, refresh)
935            .await;
936        assert!(result.is_ok(), "{result:?}");
937        let events = events.into_inner();
938        assert!(
939            matches!(
940                &events[..],
941                [
942                    RefreshProgress::Starting { total_keys: 2 },
943                    RefreshProgress::Refreshing { current: 1, total: 2, keyid: refreshed },
944                    RefreshProgress::Error { keyid: failed, .. },
945                    RefreshProgress::Completed,
946                ] if refreshed == "DEADBEEF" && failed == "786C63F330D7CB92"
947            ),
948            "{events:?}"
949        );
950    }
951
952    #[tokio::test]
953    async fn refresh_stops_when_listing_fails() {
954        let fixture = Fixture::new();
955        let result = Keyring::new()
956            .refresh_with_commands(
957                |p| panic!("{p:?}"),
958                options(),
959                fixture.command("echo 'gpg: Permission denied' >&2; exit 2"),
960                Command::new(fixture.path("missing")),
961            )
962            .await;
963        assert!(matches!(result, Err(Error::PermissionDenied)), "{result:?}");
964    }
965
966    #[tokio::test]
967    async fn refresh_reports_a_failed_exit() {
968        let fixture = Fixture::new();
969        let result = Keyring::new()
970            .refresh_with_commands(
971                |p| assert_ne!(p, RefreshProgress::Completed),
972                options(),
973                Command::new("true"),
974                fixture.command("exit 3"),
975            )
976            .await;
977        assert!(
978            matches!(result, Err(Error::PacmanKey { status: 3, .. })),
979            "{result:?}"
980        );
981    }
982
983    #[tokio::test]
984    async fn set_ownertrust_round_trips_through_gpg() {
985        let dir = tempfile::tempdir().unwrap();
986        let keyring = Keyring {
987            reader: Keyring::with_homedir(dir.path().to_string_lossy()),
988            keyserver: None,
989        };
990        let fingerprint = "ABAF11C65A2970B130ABE3C479BE3E4300411886";
991        tokio::time::timeout(
992            Duration::from_secs(10),
993            keyring.set_ownertrust(&[(fingerprint, OwnerTrust::Full)]),
994        )
995        .await
996        .unwrap()
997        .unwrap();
998        assert_eq!(
999            keyring.get_ownertrust().await.unwrap(),
1000            vec![(fingerprint.to_string(), OwnerTrust::Full)]
1001        );
1002    }
1003
1004    #[tokio::test]
1005    async fn zero_timeout_disables_refresh_deadline() {
1006        let options = OperationOptions {
1007            timeout_secs: Some(0),
1008            cancel_token: None,
1009        };
1010        let result = Keyring::new()
1011            .refresh_with_commands(|_| {}, options, Command::new("true"), Command::new("true"))
1012            .await;
1013        assert!(result.is_ok(), "{result:?}");
1014    }
1015
1016    #[tokio::test]
1017    async fn refresh_reads_an_overlong_line_in_bounded_chunks() {
1018        let fixture = Fixture::new();
1019        let script = format!(
1020            "yes requesting 2>/dev/null | tr -d '\\n' | head -c {} >&2",
1021            3 * process::STDERR_LIMIT
1022        );
1023        let refreshing = std::cell::Cell::new(0);
1024        let result = Keyring::new()
1025            .refresh_with_commands(
1026                |p| {
1027                    if matches!(p, RefreshProgress::Refreshing { .. }) {
1028                        refreshing.set(refreshing.get() + 1);
1029                    }
1030                },
1031                OperationOptions::default(),
1032                Command::new("true"),
1033                fixture.command(&script),
1034            )
1035            .await;
1036        assert!(result.is_ok(), "{result:?}");
1037        assert_eq!(refreshing.get(), 3);
1038    }
1039
1040    #[test]
1041    fn refresh_lists_with_gpg_then_runs_pacman_key() {
1042        let argv = |command: &Command| {
1043            let command = command.as_std();
1044            std::iter::once(command.get_program())
1045                .chain(command.get_args())
1046                .map(|arg| arg.to_string_lossy().into_owned())
1047                .collect::<Vec<_>>()
1048        };
1049        let (list, refresh) = Keyring::new()
1050            .with_keyserver("hkps://keys.example")
1051            .refresh_commands();
1052        assert_eq!(
1053            argv(&list),
1054            [
1055                "gpg",
1056                "--homedir=/etc/pacman.d/gnupg",
1057                "--list-keys",
1058                "--with-colons"
1059            ]
1060        );
1061        assert_eq!(
1062            argv(&refresh),
1063            [
1064                "pacman-key",
1065                "--keyserver",
1066                "hkps://keys.example",
1067                "--refresh-keys"
1068            ]
1069        );
1070    }
1071}
1072
1073#[cfg(test)]
1074mod tests {
1075    use super::*;
1076
1077    #[test]
1078    fn test_extract_keyid_from_refresh_line() {
1079        assert_eq!(
1080            extract_keyid_from_line("gpg: refreshing 1 key from hkps://keyserver.ubuntu.com"),
1081            ""
1082        );
1083        assert_eq!(
1084            extract_keyid_from_line(
1085                "gpg: requesting key DEADBEEF from hkps://keyserver.ubuntu.com"
1086            ),
1087            "DEADBEEF"
1088        );
1089        assert_eq!(
1090            extract_keyid_from_line("gpg: key 786C63F330D7CB92: public key imported"),
1091            "786C63F330D7CB92"
1092        );
1093    }
1094
1095    #[test]
1096    fn test_extract_keyid_lowercase_normalized() {
1097        assert_eq!(
1098            extract_keyid_from_line("gpg: key deadbeef: something"),
1099            "DEADBEEF"
1100        );
1101    }
1102
1103    #[test]
1104    fn test_extract_keyid_no_match() {
1105        assert_eq!(extract_keyid_from_line("gpg: some other message"), "");
1106        assert_eq!(extract_keyid_from_line(""), "");
1107    }
1108
1109    #[test]
1110    fn test_check_error_permission_denied() {
1111        let keyring = Keyring::new();
1112        let stderr = b"gpg: Permission denied";
1113        let status = std::process::Command::new("false").status().unwrap();
1114
1115        let err = keyring.check_error(status, stderr);
1116        assert!(matches!(err, Error::PermissionDenied));
1117    }
1118
1119    #[test]
1120    fn test_check_error_permission_denied_lowercase() {
1121        let keyring = Keyring::new();
1122        let stderr = b"gpg: permission denied (are you root?)";
1123        let status = std::process::Command::new("false").status().unwrap();
1124
1125        let err = keyring.check_error(status, stderr);
1126        assert!(matches!(err, Error::PermissionDenied));
1127    }
1128
1129    #[test]
1130    fn test_check_error_keyring_not_initialized() {
1131        let keyring = Keyring::new();
1132        let stderr = b"gpg: keybox '/etc/pacman.d/gnupg/pubring.kbx': No such file or directory";
1133        let status = std::process::Command::new("false").status().unwrap();
1134
1135        let err = keyring.check_error(status, stderr);
1136        assert!(matches!(err, Error::KeyringNotInitialized));
1137    }
1138
1139    #[test]
1140    fn test_check_error_generic() {
1141        let keyring = Keyring::new();
1142        let stderr = b"gpg: some unknown error";
1143        let status = std::process::Command::new("false").status().unwrap();
1144
1145        let err = keyring.check_error(status, stderr);
1146        match err {
1147            Error::PacmanKey { status: _, stderr } => {
1148                assert!(stderr.contains("some unknown error"));
1149            }
1150            _ => panic!("expected PacmanKey error"),
1151        }
1152    }
1153
1154    #[test]
1155    fn test_is_initialized_directory_missing() {
1156        let reader = ReadOnlyKeyring {
1157            gpg_homedir: "/nonexistent/path/that/does/not/exist".to_string(),
1158        };
1159        let status = reader.is_initialized().unwrap();
1160        assert_eq!(status, InitializationStatus::DirectoryMissing);
1161    }
1162
1163    fn keyring_dir(files: &[(&str, &[u8])]) -> (tempfile::TempDir, ReadOnlyKeyring) {
1164        use std::os::unix::fs::PermissionsExt;
1165
1166        let dir = tempfile::tempdir().unwrap();
1167        let homedir = dir.path().join("gnupg");
1168        std::fs::create_dir(&homedir).unwrap();
1169        std::fs::set_permissions(&homedir, std::fs::Permissions::from_mode(0o755)).unwrap();
1170        for (name, data) in files {
1171            std::fs::write(homedir.join(name), data).unwrap();
1172        }
1173        (dir, Keyring::with_homedir(homedir.to_string_lossy()))
1174    }
1175
1176    #[test]
1177    fn test_is_initialized_no_keyring_files() {
1178        let (_dir, reader) = keyring_dir(&[]);
1179        let status = reader.is_initialized().unwrap();
1180        assert_eq!(status, InitializationStatus::NoKeyringFiles);
1181    }
1182
1183    #[test]
1184    fn test_is_initialized_no_trustdb() {
1185        let (_dir, reader) = keyring_dir(&[("pubring.kbx", b"data")]);
1186        let status = reader.is_initialized().unwrap();
1187        assert_eq!(status, InitializationStatus::NoTrustDb);
1188    }
1189
1190    #[test]
1191    fn test_is_initialized_incorrect_permissions() {
1192        use std::os::unix::fs::PermissionsExt;
1193
1194        let (_dir, reader) = keyring_dir(&[("pubring.kbx", b"data"), ("trustdb.gpg", b"data")]);
1195        for mode in [0o700, 0o777, 0o2755] {
1196            std::fs::set_permissions(&reader.gpg_homedir, std::fs::Permissions::from_mode(mode))
1197                .unwrap();
1198            let status = reader.is_initialized().unwrap();
1199            assert_eq!(
1200                status,
1201                InitializationStatus::IncorrectPermissions { actual: mode }
1202            );
1203        }
1204    }
1205
1206    #[test]
1207    fn test_is_initialized_ready() {
1208        let (_dir, reader) = keyring_dir(&[("pubring.kbx", b"data"), ("trustdb.gpg", b"data")]);
1209        let status = reader.is_initialized().unwrap();
1210        assert_eq!(status, InitializationStatus::Ready);
1211    }
1212
1213    #[test]
1214    fn test_is_initialized_with_legacy_pubring() {
1215        let (_dir, reader) = keyring_dir(&[("pubring.gpg", b"data"), ("trustdb.gpg", b"data")]);
1216        let status = reader.is_initialized().unwrap();
1217        assert_eq!(status, InitializationStatus::Ready);
1218    }
1219
1220    #[test]
1221    fn test_is_initialized_path_is_file() {
1222        use std::fs;
1223        use std::io::Write;
1224
1225        let dir = tempfile::tempdir().unwrap();
1226        let tmp = dir.path().join("gnupg");
1227        fs::File::create(&tmp).unwrap().write_all(b"data").unwrap();
1228
1229        let reader = ReadOnlyKeyring {
1230            gpg_homedir: tmp.to_string_lossy().to_string(),
1231        };
1232        let status = reader.is_initialized().unwrap();
1233        assert_eq!(status, InitializationStatus::PathIsFile);
1234    }
1235
1236    #[test]
1237    fn test_is_initialized_dangling_symlink() {
1238        use std::os::unix::fs::symlink;
1239
1240        let dir = tempfile::tempdir().unwrap();
1241        let link = dir.path().join("gnupg");
1242        symlink("/nonexistent/pacman_key_target", &link).unwrap();
1243
1244        let reader = ReadOnlyKeyring {
1245            gpg_homedir: link.to_string_lossy().to_string(),
1246        };
1247        let status = reader.is_initialized().unwrap();
1248        assert_eq!(status, InitializationStatus::DirectoryMissing);
1249    }
1250
1251    #[test]
1252    fn test_is_initialized_follows_symlink() {
1253        use std::fs;
1254        use std::io::Write;
1255        use std::os::unix::fs::PermissionsExt;
1256        use std::os::unix::fs::symlink;
1257
1258        let dir = tempfile::tempdir().unwrap();
1259        let target = dir.path().join("target");
1260        let link = dir.path().join("gnupg");
1261
1262        fs::create_dir(&target).unwrap();
1263        fs::set_permissions(&target, fs::Permissions::from_mode(0o755)).unwrap();
1264        fs::File::create(target.join("pubring.kbx"))
1265            .unwrap()
1266            .write_all(b"data")
1267            .unwrap();
1268        fs::File::create(target.join("trustdb.gpg"))
1269            .unwrap()
1270            .write_all(b"data")
1271            .unwrap();
1272        symlink(&target, &link).unwrap();
1273
1274        let reader = ReadOnlyKeyring {
1275            gpg_homedir: link.to_string_lossy().to_string(),
1276        };
1277        let status = reader.is_initialized().unwrap();
1278        assert_eq!(status, InitializationStatus::Ready);
1279    }
1280
1281    #[test]
1282    fn test_is_initialized_empty_files_treated_as_missing() {
1283        let (_dir, reader) = keyring_dir(&[("pubring.kbx", b""), ("trustdb.gpg", b"")]);
1284        let status = reader.is_initialized().unwrap();
1285        assert_eq!(status, InitializationStatus::NoKeyringFiles);
1286    }
1287}