Skip to main content

libtea_client/
signature.rs

1//! Cryptographic signature verification: the verifier trait, a verifier that
2//! checks nothing, and (feature `signature-keys`) one that checks raw detached
3//! signatures against public keys the caller supplies.
4//!
5//! **Experimental:** may change in a 0.x minor release.
6//!
7//! Checksum [`libtea_core::IntegrityOutcome::Verified`] means declared digests
8//! matched decoded artifact bytes. It does **not** mean a publisher signed the
9//! bytes. Only [`SignatureVerifyOutcome::Verified`] says that, and only a
10//! verifier configured by the caller with keys it trusts returns it: nothing
11//! in this crate fetches keys or trusts a key by default.
12//!
13//! See `docs/design/signature-verification.md`.
14//!
15//! [`detect_signature_format`] (re-exported from `libtea-core`) names the
16//! container a downloaded signature appears to use. [`FormatOnlyVerifier`]
17//! never verifies. `KeyVerifier` (feature `signature-keys`) verifies.
18
19use std::path::Path;
20
21pub use libtea_core::signature_format::{
22    detect_signature_format, SignatureFormat, MAX_SIGNATURE_INSPECT_BYTES,
23};
24
25#[cfg(feature = "signature-keys")]
26mod keys;
27#[cfg(feature = "signature-keys")]
28pub use keys::{KeyAlgorithm, KeyError, KeyVerifier, PublicKey};
29
30/// Outcome of a signature check.
31///
32/// **Experimental:** may change in a 0.x minor release.
33///
34/// Callers must not treat anything other than [`Self::Verified`] as authenticity.
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36#[non_exhaustive]
37pub enum SignatureVerifyOutcome {
38    /// The signature is valid for the content under a key the caller supplied.
39    /// [`SignatureVerification::policy`] names the key.
40    Verified,
41    /// The signature was checked and does not match the content under any key.
42    Invalid,
43    /// The signature's format or algorithm is not one this verifier checks.
44    /// The specification asks for such a signature to be treated "as unusable
45    /// rather than as invalid".
46    Unsupported,
47    /// The verifier has no keys or policy configured.
48    NoTrustAnchor,
49    /// No signature bytes were supplied.
50    MissingSignature,
51    /// The signed content could not be read (for example a file that is gone).
52    ContentUnavailable,
53}
54
55impl SignatureVerifyOutcome {
56    /// A stable snake_case name, as in `libtea download --json`.
57    #[must_use]
58    pub fn as_str(self) -> &'static str {
59        match self {
60            Self::Verified => "verified",
61            Self::Invalid => "invalid",
62            Self::Unsupported => "unsupported",
63            Self::NoTrustAnchor => "no_trust_anchor",
64            Self::MissingSignature => "missing_signature",
65            Self::ContentUnavailable => "content_unavailable",
66        }
67    }
68}
69
70/// What a detached signature is checked against: the decoded artifact bytes,
71/// the same bytes the checksums cover.
72///
73/// **Experimental:** may change in a 0.x minor release.
74#[derive(Debug, Clone, Copy)]
75#[non_exhaustive]
76pub enum SignedContent<'a> {
77    /// The bytes, in memory.
78    Bytes(&'a [u8]),
79    /// The bytes, in a file, for example the one
80    /// [`crate::Service::download_format_to_file`] wrote. A verifier reads it
81    /// itself; `KeyVerifier` reads it whole, because the signature algorithms
82    /// it supports take the whole message.
83    File(&'a Path),
84}
85
86/// One verification request.
87///
88/// **Experimental:** may change in a 0.x minor release.
89#[derive(Debug, Clone, Copy)]
90#[non_exhaustive]
91pub struct VerifyRequest<'a> {
92    /// What was signed.
93    pub content: SignedContent<'a>,
94    /// The detached signature bytes, as downloaded.
95    pub signature: &'a [u8],
96    /// The `mediaType` of the artifact format the signature belongs to (it
97    /// selects the artifact format, not the signature's own type).
98    pub media_type: Option<&'a str>,
99}
100
101impl<'a> VerifyRequest<'a> {
102    /// A request for `signature` over `content`, without a media type.
103    #[must_use]
104    pub fn new(content: SignedContent<'a>, signature: &'a [u8]) -> Self {
105        Self {
106            content,
107            signature,
108            media_type: None,
109        }
110    }
111
112    /// Set the artifact format's media type.
113    #[must_use]
114    pub fn with_media_type(mut self, media_type: &'a str) -> Self {
115        self.media_type = Some(media_type);
116        self
117    }
118}
119
120/// The result of [`SignatureVerifier::verify`]: the outcome, and which
121/// verifier and policy produced it, so a result can be audited later.
122///
123/// **Experimental:** may change in a 0.x minor release.
124#[derive(Debug, Clone, PartialEq, Eq)]
125#[non_exhaustive]
126pub struct SignatureVerification {
127    /// The outcome.
128    pub outcome: SignatureVerifyOutcome,
129    /// The verifier and the policy it applied, for example
130    /// `caller key ed25519 sha256:3b6a…` for a [`SignatureVerifyOutcome::Verified`]
131    /// result: the key that verified, by the SHA-256 of its DER
132    /// `SubjectPublicKeyInfo`.
133    pub policy: String,
134    /// Why the outcome is not `Verified`, when there is more to say.
135    pub detail: Option<String>,
136}
137
138impl SignatureVerification {
139    /// A result with no detail.
140    #[must_use]
141    pub fn new(outcome: SignatureVerifyOutcome, policy: impl Into<String>) -> Self {
142        Self {
143            outcome,
144            policy: policy.into(),
145            detail: None,
146        }
147    }
148
149    /// Add a detail.
150    #[must_use]
151    pub fn with_detail(mut self, detail: impl Into<String>) -> Self {
152        self.detail = Some(detail.into());
153        self
154    }
155}
156
157/// A signature verifier configured by the caller.
158///
159/// **Experimental:** may change in a 0.x minor release.
160///
161/// The HTTP client never calls it by itself. An implementation must return
162/// [`SignatureVerifyOutcome::Verified`] only under a policy the caller
163/// configured, and must never derive trust from the server that served the
164/// artifact (for example from a key it also served).
165pub trait SignatureVerifier: Send + Sync {
166    /// Check `request.signature` over `request.content`.
167    fn verify(&self, request: &VerifyRequest<'_>) -> SignatureVerification;
168}
169
170/// A [`SignatureVerifier`] that checks nothing and says so.
171///
172/// **Experimental:** may change in a 0.x minor release.
173///
174/// Returns [`SignatureVerifyOutcome::MissingSignature`] for empty signature
175/// bytes and [`SignatureVerifyOutcome::Unsupported`] for anything else,
176/// whatever format [`detect_signature_format`] finds. It never returns
177/// [`SignatureVerifyOutcome::Verified`].
178///
179/// ```
180/// use libtea_client::signature::{
181///     FormatOnlyVerifier, SignatureVerifier, SignatureVerifyOutcome, SignedContent, VerifyRequest,
182/// };
183///
184/// let verifier = FormatOnlyVerifier::new();
185/// let content = SignedContent::Bytes(b"artifact");
186/// let result = verifier.verify(&VerifyRequest::new(content, b""));
187/// assert_eq!(result.outcome, SignatureVerifyOutcome::MissingSignature);
188/// let result = verifier.verify(&VerifyRequest::new(content, b"sig"));
189/// assert_eq!(result.outcome, SignatureVerifyOutcome::Unsupported);
190/// assert_eq!(result.policy, "format only: no signature is checked");
191/// ```
192#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
193#[non_exhaustive]
194pub struct FormatOnlyVerifier {}
195
196impl FormatOnlyVerifier {
197    /// The verifier.
198    #[must_use]
199    pub fn new() -> Self {
200        Self {}
201    }
202}
203
204impl SignatureVerifier for FormatOnlyVerifier {
205    fn verify(&self, request: &VerifyRequest<'_>) -> SignatureVerification {
206        let outcome = if request.signature.is_empty() {
207            SignatureVerifyOutcome::MissingSignature
208        } else {
209            SignatureVerifyOutcome::Unsupported
210        };
211        SignatureVerification::new(outcome, "format only: no signature is checked")
212    }
213}
214
215#[cfg(test)]
216mod tests {
217    use super::*;
218
219    struct AlwaysUnsupported;
220
221    impl SignatureVerifier for AlwaysUnsupported {
222        fn verify(&self, _request: &VerifyRequest<'_>) -> SignatureVerification {
223            SignatureVerification::new(SignatureVerifyOutcome::Unsupported, "test double")
224        }
225    }
226
227    #[test]
228    fn format_only_verifier_never_claims_verified() {
229        let verifier = FormatOnlyVerifier::new();
230        let armored = b"-----BEGIN PGP SIGNATURE-----\n\nabc\n-----END PGP SIGNATURE-----\n";
231        assert_eq!(
232            detect_signature_format(armored),
233            SignatureFormat::OpenPgpArmored
234        );
235        let content = SignedContent::Bytes(b"artifact");
236        for signature in [armored.as_slice(), b"x", b"{}"] {
237            let request =
238                VerifyRequest::new(content, signature).with_media_type("application/pgp-signature");
239            assert_eq!(
240                verifier.verify(&request).outcome,
241                SignatureVerifyOutcome::Unsupported
242            );
243        }
244        assert_eq!(
245            verifier.verify(&VerifyRequest::new(content, b"")).outcome,
246            SignatureVerifyOutcome::MissingSignature
247        );
248    }
249
250    #[test]
251    fn test_double_never_claims_verified() {
252        let request = VerifyRequest::new(SignedContent::Bytes(b"artifact"), b"sig");
253        let result = AlwaysUnsupported.verify(&request);
254        assert_ne!(result.outcome, SignatureVerifyOutcome::Verified);
255        assert_eq!(result.outcome, SignatureVerifyOutcome::Unsupported);
256    }
257
258    #[test]
259    fn outcome_names_are_stable() {
260        let all = [
261            (SignatureVerifyOutcome::Verified, "verified"),
262            (SignatureVerifyOutcome::Invalid, "invalid"),
263            (SignatureVerifyOutcome::Unsupported, "unsupported"),
264            (SignatureVerifyOutcome::NoTrustAnchor, "no_trust_anchor"),
265            (
266                SignatureVerifyOutcome::MissingSignature,
267                "missing_signature",
268            ),
269            (
270                SignatureVerifyOutcome::ContentUnavailable,
271                "content_unavailable",
272            ),
273        ];
274        for (outcome, name) in all {
275            assert_eq!(outcome.as_str(), name);
276        }
277    }
278}