Skip to main content

pacman_key/
types.rs

1use chrono::NaiveDate;
2pub use tokio_util::sync::CancellationToken;
3
4/// Status of keyring initialization.
5///
6/// Returned by [`ReadOnlyKeyring::is_initialized`] to indicate the current
7/// state of the keyring directory without spawning GPG processes.
8///
9/// # Security Considerations
10///
11/// This method performs non-atomic filesystem checks and is subject to
12/// TOCTOU race conditions. The keyring state may change between the
13/// check and subsequent operations. Use this for informational purposes
14/// or pre-flight checks, not for security-critical decisions.
15///
16/// [`ReadOnlyKeyring::is_initialized`]: crate::ReadOnlyKeyring::is_initialized
17#[derive(Debug, Clone, PartialEq, Eq)]
18#[non_exhaustive]
19pub enum InitializationStatus {
20    /// Keyring is fully initialized and ready for use.
21    Ready,
22    /// The keyring directory does not exist.
23    DirectoryMissing,
24    /// Path exists but is a regular file, not a directory.
25    PathIsFile,
26    /// Directory exists but contains no keyring files (pubring.kbx or pubring.gpg).
27    NoKeyringFiles,
28    /// Directory exists but trustdb.gpg is missing.
29    NoTrustDb,
30    /// Directory exists but has incorrect permissions
31    /// (`pacman-key --init` creates it 755).
32    IncorrectPermissions { actual: u32 },
33}
34
35/// A GPG key from the pacman keyring.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct Key {
38    pub fingerprint: String,
39    pub uid: String,
40    pub created: Option<NaiveDate>,
41    pub expires: Option<NaiveDate>,
42    pub validity: KeyValidity,
43    pub key_type: KeyType,
44    /// Capabilities of the primary key itself (sign/certify/encrypt/auth).
45    pub usage: KeyUsage,
46    /// Subkeys attached to this primary key.
47    pub subkeys: Vec<Subkey>,
48}
49
50/// A subkey attached to a primary key.
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct Subkey {
53    pub fingerprint: String,
54    pub key_type: KeyType,
55    pub created: Option<NaiveDate>,
56    pub expires: Option<NaiveDate>,
57    pub usage: KeyUsage,
58}
59
60/// Key capabilities parsed from GPG's capability field.
61///
62/// Derived from the lowercase letters in the `--with-colons` capability field
63/// (field 12), which describe what the key itself can do.
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
65pub struct KeyUsage {
66    pub sign: bool,
67    pub certify: bool,
68    pub encrypt: bool,
69    pub authenticate: bool,
70}
71
72/// The cryptographic algorithm and key size.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct KeyType {
75    pub algorithm: String,
76    pub bits: u32,
77}
78
79impl std::fmt::Display for KeyType {
80    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81        write!(f, "{}{}", self.algorithm.to_lowercase(), self.bits)
82    }
83}
84
85/// GPG key validity level.
86///
87/// Represents how confident GPG is that the key belongs to the claimed identity.
88/// This is derived from signature verification and the web of trust, not to be
89/// confused with owner trust (how much we trust the key owner to sign other keys).
90///
91/// Values correspond to GPG's validity field in `--with-colons` output.
92#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
93#[non_exhaustive]
94pub enum KeyValidity {
95    /// Validity unknown (new key or insufficient data)
96    #[default]
97    Unknown,
98    /// Validity undefined (not yet computed)
99    Undefined,
100    /// Key is explicitly distrusted
101    Never,
102    /// Marginally valid (some trust path exists)
103    Marginal,
104    /// Fully valid (strong trust path)
105    Full,
106    /// Ultimately valid (user's own key or explicitly trusted)
107    Ultimate,
108    /// Key has expired
109    Expired,
110    /// Key has been revoked
111    Revoked,
112    /// Key has been disabled
113    Disabled,
114    /// Key is invalid (e.g. missing self-signature)
115    Invalid,
116}
117
118impl KeyValidity {
119    pub fn from_gpg_char(c: char) -> Self {
120        match c {
121            'o' => Self::Unknown,
122            'q' => Self::Undefined,
123            'n' => Self::Never,
124            'm' => Self::Marginal,
125            'f' => Self::Full,
126            'u' => Self::Ultimate,
127            'e' => Self::Expired,
128            'r' => Self::Revoked,
129            'd' => Self::Disabled,
130            'i' => Self::Invalid,
131            _ => Self::Unknown,
132        }
133    }
134}
135
136/// A signature on a key.
137#[derive(Debug, Clone, PartialEq, Eq)]
138pub struct Signature {
139    pub keyid: String,
140    pub uid: String,
141    pub created: Option<NaiveDate>,
142    pub expires: Option<NaiveDate>,
143    pub sig_class: String,
144    /// Verification status, populated only by `check_signatures` (`--check-sigs`).
145    /// `None` for the non-checking `list_signatures` (`--list-sigs`).
146    pub status: Option<SigStatus>,
147}
148
149/// Verification status of a signature, from GPG's `--check-sigs` output.
150#[derive(Debug, Clone, Copy, PartialEq, Eq)]
151pub enum SigStatus {
152    /// Signature verified good (`!`).
153    Good,
154    /// Signature is bad (`-`).
155    Bad,
156    /// Signing key is not in the local keyring (`?`).
157    MissingKey,
158    /// Other verification error (`%`).
159    Error,
160}
161
162impl SigStatus {
163    /// Maps a GPG `--check-sigs` field-2 marker to a status. Empty (non-checking
164    /// `--list-sigs`) yields `None`.
165    pub fn from_gpg_marker(marker: &str) -> Option<Self> {
166        match marker {
167            "!" => Some(Self::Good),
168            "-" => Some(Self::Bad),
169            "?" => Some(Self::MissingKey),
170            "%" => Some(Self::Error),
171            _ => None,
172        }
173    }
174}
175
176/// Result of verifying a signature with [`ReadOnlyKeyring::verify_signature`].
177///
178/// [`ReadOnlyKeyring::verify_signature`]: crate::ReadOnlyKeyring::verify_signature
179#[derive(Debug, Clone, PartialEq, Eq)]
180pub struct VerifyResult {
181    /// The signature is cryptographically valid (`GOODSIG`/`VALIDSIG`).
182    pub good: bool,
183    /// The signing key is trusted fully or ultimately (`TRUST_FULLY`/`TRUST_ULTIMATE`).
184    /// pacman considers a package signature acceptable only when this is true.
185    pub trusted: bool,
186    /// Fingerprint of the signing key, if reported (`VALIDSIG`).
187    pub key_fpr: Option<String>,
188    /// User ID of the signer, if reported (`GOODSIG`).
189    pub uid: Option<String>,
190}
191
192/// GPG owner trust level (how much the key owner is trusted to sign other keys).
193///
194/// Distinct from [`KeyValidity`], which is the computed validity of a key.
195#[derive(Debug, Clone, Copy, PartialEq, Eq)]
196pub enum OwnerTrust {
197    /// No owner trust assigned.
198    Unknown,
199    /// Trust undefined.
200    Undefined,
201    /// Explicitly never trust.
202    Never,
203    /// Marginal trust.
204    Marginal,
205    /// Full trust.
206    Full,
207    /// Ultimate trust (own keys).
208    Ultimate,
209}
210
211impl OwnerTrust {
212    /// Parses a numeric level from `gpg --export-ownertrust` output.
213    pub fn from_gpg_level(level: &str) -> Self {
214        match level {
215            "2" => Self::Undefined,
216            "3" => Self::Never,
217            "4" => Self::Marginal,
218            "5" => Self::Full,
219            "6" => Self::Ultimate,
220            _ => Self::Unknown,
221        }
222    }
223
224    /// The numeric level for `gpg --import-ownertrust` input.
225    pub fn to_gpg_level(self) -> u8 {
226        match self {
227            Self::Unknown => 1,
228            Self::Undefined => 2,
229            Self::Never => 3,
230            Self::Marginal => 4,
231            Self::Full => 5,
232            Self::Ultimate => 6,
233        }
234    }
235}
236
237/// Progress updates during key refresh operations.
238#[derive(Debug, Clone, PartialEq, Eq)]
239#[non_exhaustive]
240pub enum RefreshProgress {
241    Starting {
242        total_keys: usize,
243    },
244    Refreshing {
245        current: usize,
246        total: usize,
247        keyid: String,
248    },
249    Completed,
250    Error {
251        keyid: String,
252        message: String,
253    },
254}
255
256/// Options for long-running operations like init, populate, and refresh.
257///
258/// Provides timeout and cancellation support for operations that spawn
259/// subprocesses which may take significant time to complete. See the
260/// [crate docs](crate#subprocesses) for how those subprocesses are stopped.
261///
262/// Note: A `timeout_secs` of 0 is treated as "no timeout".
263#[derive(Debug, Clone, Default)]
264pub struct OperationOptions {
265    /// Timeout for the whole operation, in seconds.
266    /// If None or 0, no timeout is applied.
267    pub timeout_secs: Option<u64>,
268    /// Cancellation token for aborting the operation.
269    /// When cancelled, the subprocess group is killed and `Error::Cancelled` is returned.
270    pub cancel_token: Option<CancellationToken>,
271}
272
273#[cfg(test)]
274mod tests {
275    use super::*;
276
277    #[test]
278    fn test_key_validity_from_gpg_char() {
279        assert_eq!(KeyValidity::from_gpg_char('o'), KeyValidity::Unknown);
280        assert_eq!(KeyValidity::from_gpg_char('q'), KeyValidity::Undefined);
281        assert_eq!(KeyValidity::from_gpg_char('n'), KeyValidity::Never);
282        assert_eq!(KeyValidity::from_gpg_char('m'), KeyValidity::Marginal);
283        assert_eq!(KeyValidity::from_gpg_char('f'), KeyValidity::Full);
284        assert_eq!(KeyValidity::from_gpg_char('u'), KeyValidity::Ultimate);
285        assert_eq!(KeyValidity::from_gpg_char('e'), KeyValidity::Expired);
286        assert_eq!(KeyValidity::from_gpg_char('r'), KeyValidity::Revoked);
287        assert_eq!(KeyValidity::from_gpg_char('d'), KeyValidity::Disabled);
288        assert_eq!(KeyValidity::from_gpg_char('i'), KeyValidity::Invalid);
289        assert_eq!(KeyValidity::from_gpg_char('x'), KeyValidity::Unknown);
290        assert_eq!(KeyValidity::from_gpg_char('-'), KeyValidity::Unknown);
291    }
292
293    #[test]
294    fn test_ownertrust_roundtrip() {
295        for t in [
296            OwnerTrust::Undefined,
297            OwnerTrust::Never,
298            OwnerTrust::Marginal,
299            OwnerTrust::Full,
300            OwnerTrust::Ultimate,
301        ] {
302            let level = t.to_gpg_level().to_string();
303            assert_eq!(OwnerTrust::from_gpg_level(&level), t);
304        }
305        assert_eq!(OwnerTrust::from_gpg_level(""), OwnerTrust::Unknown);
306    }
307
308    #[test]
309    fn test_sig_status_marker() {
310        assert_eq!(SigStatus::from_gpg_marker("!"), Some(SigStatus::Good));
311        assert_eq!(SigStatus::from_gpg_marker("-"), Some(SigStatus::Bad));
312        assert_eq!(SigStatus::from_gpg_marker("?"), Some(SigStatus::MissingKey));
313        assert_eq!(SigStatus::from_gpg_marker("%"), Some(SigStatus::Error));
314        assert_eq!(SigStatus::from_gpg_marker(""), None);
315    }
316}