Skip to main content

crypto_profile/
error.rs

1//! The crate's refusals.
2use crate::algorithm::{Algorithm, SignatureAlgorithm, TlsVersion};
3use crate::capability::Approval;
4use crate::peer_certificate::PeerCertificateViolation;
5use crate::profile::{Options, Profile};
6use std::fmt;
7
8/// A family of algorithms in a TLS policy or a profile.
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10#[non_exhaustive]
11pub enum Family {
12    /// Protocol versions.
13    Version,
14    /// Cipher suites.
15    CipherSuite,
16    /// Key-exchange groups.
17    KxGroup,
18    /// Signature schemes.
19    SignatureScheme,
20    /// Key algorithms.
21    KeyAlgorithm,
22}
23
24/// Why a certificate signing request could not be produced.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26#[non_exhaustive]
27pub enum CsrError {
28    /// A subject alternative name or distinguished-name value is not valid for its type.
29    InvalidName,
30    /// The request parameters were refused.
31    InvalidParams,
32    /// Signing the request failed.
33    Signing,
34}
35
36/// Bounded identity of a peer verifier, independent of certificates and trust anchors.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum PeerVerifierIdentity {
39    /// An owned verifier or completion policy.
40    Owned {
41        /// The certificate rule, absent for default-off policies.
42        rule: Option<crate::PeerCertificateRuleId>,
43        /// Canonical handshake-scheme mask, with bit positions from scheme preference order.
44        handshake_schemes: u16,
45    },
46    /// A verifier whose policy identity cannot be established.
47    Opaque,
48}
49
50/// Why a TLS configuration step was refused.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52#[non_exhaustive]
53pub enum TlsError {
54    /// The provider refused the policy's protocol versions.
55    ProtocolVersions,
56    /// The private key was refused.
57    PrivateKey,
58    /// A process-default provider is already installed.
59    DefaultProviderInstalled,
60    /// The certificate chain is empty, or its end-entity certificate does not carry the key.
61    KeyMismatch,
62    /// A rule-bearing policy requires a completion builder that installs its owned verifier.
63    StrictBuilderRequired {
64        /// The applicable strict completion entry point in `tls`.
65        entry_point: &'static str,
66    },
67    /// The completion policy and verifier have incompatible identities.
68    IncompatiblePeerVerifier {
69        /// The completion policy's identity.
70        expected: PeerVerifierIdentity,
71        /// The supplied verifier's identity.
72        actual: PeerVerifierIdentity,
73    },
74    /// A peer certificate failed its profile's certificate rule.
75    PeerCertificate {
76        /// The governing profile.
77        profile: Profile,
78        /// The bounded refusal descriptor.
79        violation: PeerCertificateViolation,
80    },
81}
82
83impl fmt::Display for TlsError {
84    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85        match self {
86            Self::ProtocolVersions => f.write_str("the provider refused the protocol versions"),
87            Self::PrivateKey => f.write_str("the private key was refused"),
88            Self::DefaultProviderInstalled => {
89                f.write_str("a process-default provider is already installed")
90            }
91            Self::KeyMismatch => {
92                f.write_str("the certificate chain is empty or does not carry the key")
93            }
94            Self::IncompatiblePeerVerifier { expected, actual } => {
95                write!(
96                    f,
97                    "the peer verifier {actual:?} is incompatible with {expected:?}"
98                )
99            }
100            Self::StrictBuilderRequired { entry_point } => {
101                write!(f, "the peer certificate rule requires tls::{entry_point}")
102            }
103            Self::PeerCertificate { profile, violation } => {
104                write!(f, "the {profile} peer certificate was refused: {violation}")
105            }
106        }
107    }
108}
109
110impl std::error::Error for TlsError {
111    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
112        match self {
113            Self::PeerCertificate { violation, .. } => Some(violation),
114            Self::IncompatiblePeerVerifier { .. }
115            | Self::StrictBuilderRequired { .. }
116            | Self::ProtocolVersions
117            | Self::PrivateKey
118            | Self::DefaultProviderInstalled
119            | Self::KeyMismatch => None,
120        }
121    }
122}
123
124/// A refusal from one of the crate's operations. It never carries key or plaintext material.
125#[derive(Debug, Clone, Copy, PartialEq, Eq)]
126#[non_exhaustive]
127pub enum CryptoError {
128    /// The algorithm is not available on this backend's module.
129    Unavailable(Algorithm),
130    /// A TLS policy names nothing in this family.
131    PolicyEmpty(Family),
132    /// A TLS policy names this algorithm more than once.
133    PolicyDuplicate(Algorithm),
134    /// A provider does not carry exactly a policy's algorithms.
135    PolicyDrift,
136    /// A TLS policy lists a version but names nothing in this family usable with it.
137    PolicyVersionUnusable {
138        /// The listed version.
139        version: TlsVersion,
140        /// The family with nothing usable at that version.
141        family: Family,
142    },
143    /// The process is not running the AWS-LC FIPS module, or a provider is not FIPS.
144    NotFips,
145    /// Key generation failed.
146    KeyGeneration(Algorithm),
147    /// A private key was refused.
148    PrivateKey,
149    /// A signature did not verify.
150    Verify,
151    /// Signing failed.
152    Sign,
153    /// A certificate signing request could not be produced.
154    Csr(CsrError),
155    /// A TLS configuration step was refused.
156    Tls(TlsError),
157    /// The random generator failed.
158    Random,
159    /// The AEAD key was refused.
160    AeadKey,
161    /// AEAD sealing failed.
162    AeadSeal,
163    /// The AEAD ciphertext did not authenticate.
164    AeadOpen,
165    /// A sealed-box plaintext is empty.
166    SealPlaintext,
167    /// A sealed blob is shorter than a header, one byte and a tag.
168    SealBlob,
169    /// A sealed blob carries an unknown version.
170    SealVersion,
171    /// A sealed blob's ephemeral key is not an uncompressed P-384 point.
172    SealEphemeralKey,
173    /// A sealing public key is not a canonical P-384 SubjectPublicKeyInfo.
174    SealPublicKey,
175    /// A sealing private key is not a P-384 PKCS#8 key.
176    SealPrivateKey,
177    /// A sealed blob does not open under this key, domain and AAD.
178    SealOpen,
179    /// A cryptographic primitive failed.
180    Primitive,
181    /// A profile, narrowed by its options, names nothing in a family.
182    EmptyProfile {
183        /// The profile.
184        profile: Profile,
185        /// The options it was narrowed by.
186        options: Options,
187        /// The family left empty.
188        category: Family,
189    },
190    /// A key algorithm the profile does not admit.
191    KeyNotInProfile {
192        /// The profile.
193        profile: Profile,
194        /// The refused key algorithm.
195        algorithm: SignatureAlgorithm,
196    },
197    /// An algorithm the running module does not approve.
198    NotApproved {
199        /// The first algorithm found not approved.
200        algorithm: Algorithm,
201        /// Its approval.
202        approval: Approval,
203    },
204}
205
206impl fmt::Display for CryptoError {
207    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
208        match self {
209            CryptoError::Unavailable(a) => {
210                write!(f, "{a:?} is not available on this backend's module")
211            }
212            CryptoError::PolicyEmpty(fam) => write!(f, "the TLS policy names no {fam:?}"),
213            CryptoError::PolicyDuplicate(a) => write!(f, "the TLS policy names {a:?} twice"),
214            CryptoError::PolicyVersionUnusable { version, family } => write!(
215                f,
216                "the TLS policy lists {version:?} but names no {family:?} usable with it"
217            ),
218            CryptoError::PolicyDrift => {
219                f.write_str("the provider does not carry exactly the policy's algorithms")
220            }
221            CryptoError::NotFips => {
222                f.write_str("the AWS-LC FIPS module is not active, or the provider is not FIPS")
223            }
224            CryptoError::KeyGeneration(a) => write!(f, "key generation for {a:?} failed"),
225            CryptoError::PrivateKey => f.write_str("the private key was refused"),
226            CryptoError::Verify => f.write_str("the signature does not verify"),
227            CryptoError::Sign => f.write_str("signing failed"),
228            CryptoError::Csr(e) => write!(f, "the certificate signing request failed: {e:?}"),
229            CryptoError::Tls(e) => write!(f, "the TLS configuration was refused: {e:?}"),
230            CryptoError::Random => f.write_str("the random generator failed"),
231            CryptoError::AeadKey => f.write_str("the AEAD key was refused"),
232            CryptoError::AeadSeal => f.write_str("AEAD sealing failed"),
233            CryptoError::AeadOpen => f.write_str("the AEAD ciphertext does not authenticate"),
234            CryptoError::SealPlaintext => f.write_str("the sealed plaintext is empty"),
235            CryptoError::SealBlob => f.write_str("the sealed blob is too short"),
236            CryptoError::SealVersion => f.write_str("the sealed blob has an unknown version"),
237            CryptoError::SealEphemeralKey => {
238                f.write_str("the sealed blob's ephemeral key is not an uncompressed P-384 point")
239            }
240            CryptoError::SealPublicKey => {
241                f.write_str("the sealing public key is not a canonical P-384 SubjectPublicKeyInfo")
242            }
243            CryptoError::SealPrivateKey => {
244                f.write_str("the sealing private key is not a P-384 PKCS#8 key")
245            }
246            CryptoError::SealOpen => {
247                f.write_str("the sealed blob does not open under this key, domain and AAD")
248            }
249            CryptoError::Primitive => f.write_str("a cryptographic primitive failed"),
250            CryptoError::EmptyProfile {
251                profile,
252                options,
253                category,
254            } => {
255                write!(
256                    f,
257                    "the {profile} profile, with {options}, names no {category:?}"
258                )
259            }
260            CryptoError::KeyNotInProfile { profile, algorithm } => {
261                write!(f, "the {profile} profile does not admit {algorithm} keys")
262            }
263            CryptoError::NotApproved {
264                algorithm,
265                approval,
266            } => {
267                write!(
268                    f,
269                    "{algorithm:?} is not approved by the running module: {approval:?}"
270                )
271            }
272        }
273    }
274}
275
276impl std::error::Error for CryptoError {}
277
278#[cfg(test)]
279mod tests {
280    use super::*;
281    use crate::algorithm::{Algorithm, KxGroup, SignatureAlgorithm, TlsSignatureScheme};
282    use crate::capability::Approval;
283    use crate::profile::{Options, Profile};
284
285    #[test]
286    fn display_texts_are_pinned() {
287        assert_eq!(
288            CryptoError::Random.to_string(),
289            "the random generator failed"
290        );
291        assert_eq!(
292            CryptoError::NotFips.to_string(),
293            "the AWS-LC FIPS module is not active, or the provider is not FIPS"
294        );
295        assert_eq!(
296            CryptoError::Unavailable(Algorithm::Signature(SignatureAlgorithm::MlDsa87)).to_string(),
297            "Signature(MlDsa87) is not available on this backend's module"
298        );
299        assert_eq!(
300            CryptoError::PolicyEmpty(Family::KxGroup).to_string(),
301            "the TLS policy names no KxGroup"
302        );
303        assert_eq!(
304            CryptoError::PolicyVersionUnusable {
305                version: TlsVersion::Tls12,
306                family: Family::KxGroup
307            }
308            .to_string(),
309            "the TLS policy lists Tls12 but names no KxGroup usable with it"
310        );
311        assert_eq!(
312            CryptoError::PolicyDuplicate(Algorithm::Scheme(TlsSignatureScheme::Ed25519))
313                .to_string(),
314            "the TLS policy names Scheme(Ed25519) twice"
315        );
316        assert_eq!(
317            CryptoError::Csr(CsrError::InvalidName).to_string(),
318            "the certificate signing request failed: InvalidName"
319        );
320        assert_eq!(
321            CryptoError::Tls(TlsError::PrivateKey).to_string(),
322            "the TLS configuration was refused: PrivateKey"
323        );
324    }
325
326    #[test]
327    fn profile_display_texts_are_pinned() {
328        let pq = Options {
329            pq_key_exchange_required: true,
330            peer_certificates_match_profile: false,
331        };
332        let table: [(CryptoError, &str); 5] = [
333            (
334                CryptoError::EmptyProfile {
335                    profile: Profile::Cnsa1,
336                    options: pq,
337                    category: Family::KxGroup,
338                },
339                "the cnsa1 profile, with post-quantum key exchange required, names no KxGroup",
340            ),
341            (
342                CryptoError::EmptyProfile {
343                    profile: Profile::Cnsa2,
344                    options: Options::default(),
345                    category: Family::KeyAlgorithm,
346                },
347                "the cnsa2 profile, with no options, names no KeyAlgorithm",
348            ),
349            (
350                CryptoError::KeyNotInProfile {
351                    profile: Profile::Bsi,
352                    algorithm: SignatureAlgorithm::Rsa3072Sha384,
353                },
354                "the bsi profile does not admit rsa3072-sha384 keys",
355            ),
356            (
357                CryptoError::NotApproved {
358                    algorithm: Algorithm::Kx(KxGroup::X25519),
359                    approval: Approval::Unverified,
360                },
361                "Kx(X25519) is not approved by the running module: Unverified",
362            ),
363            (
364                CryptoError::NotApproved {
365                    algorithm: Algorithm::Signature(SignatureAlgorithm::MlDsa87),
366                    approval: Approval::AlgorithmTested { cavp: "A7855 (x)" },
367                },
368                "Signature(MlDsa87) is not approved by the running module: AlgorithmTested { cavp: \"A7855 (x)\" }",
369            ),
370        ];
371        for (e, text) in table {
372            assert_eq!(e.to_string(), text);
373        }
374    }
375
376    #[test]
377    fn every_other_display_text_is_pinned() {
378        let table: [(CryptoError, &str); 16] = [
379            (
380                CryptoError::PolicyDrift,
381                "the provider does not carry exactly the policy's algorithms",
382            ),
383            (
384                CryptoError::KeyGeneration(Algorithm::Signature(SignatureAlgorithm::Ed25519)),
385                "key generation for Signature(Ed25519) failed",
386            ),
387            (CryptoError::PrivateKey, "the private key was refused"),
388            (CryptoError::Verify, "the signature does not verify"),
389            (CryptoError::Sign, "signing failed"),
390            (CryptoError::AeadKey, "the AEAD key was refused"),
391            (CryptoError::AeadSeal, "AEAD sealing failed"),
392            (
393                CryptoError::AeadOpen,
394                "the AEAD ciphertext does not authenticate",
395            ),
396            (CryptoError::SealPlaintext, "the sealed plaintext is empty"),
397            (CryptoError::SealBlob, "the sealed blob is too short"),
398            (
399                CryptoError::SealVersion,
400                "the sealed blob has an unknown version",
401            ),
402            (
403                CryptoError::SealEphemeralKey,
404                "the sealed blob's ephemeral key is not an uncompressed P-384 point",
405            ),
406            (
407                CryptoError::SealPublicKey,
408                "the sealing public key is not a canonical P-384 SubjectPublicKeyInfo",
409            ),
410            (
411                CryptoError::SealPrivateKey,
412                "the sealing private key is not a P-384 PKCS#8 key",
413            ),
414            (
415                CryptoError::SealOpen,
416                "the sealed blob does not open under this key, domain and AAD",
417            ),
418            (CryptoError::Primitive, "a cryptographic primitive failed"),
419        ];
420        for (e, text) in table {
421            assert_eq!(e.to_string(), text);
422        }
423    }
424}