Skip to main content

coqui_peer_tls/
error.rs

1use core::fmt;
2use std::io;
3
4use coqui_peer::pair::{PairRefusal, PairingError};
5
6/// Sanitized failures while loading, storing or using a peer identity. No message holds key
7/// material; only [`CaFile`](PeerError::CaFile) names a path, the file it could not use.
8#[derive(Debug)]
9#[non_exhaustive]
10pub enum PeerError {
11    /// A peer id is malformed.
12    InvalidId,
13    /// A certificate or its private key is missing or invalid.
14    Certificate,
15    /// A TLS configuration or handshake was refused.
16    Tls,
17    /// A fingerprint is an MD5 digest, which no policy allows.
18    WeakDigest,
19    /// A policy setting is invalid or unsupported; the message names it and lists what is
20    /// supported. It never holds key material.
21    Policy(String),
22    /// A trust glob is malformed.
23    TrustPattern,
24    /// The peer is not waiting for acceptance.
25    NotWaiting,
26    /// The peer was already accepted.
27    AlreadyAccepted,
28    /// The path does not name a file inside a directory.
29    Path,
30    /// The trust policy cannot be used in this role.
31    Unsupported,
32    /// A pairing exchange, or a key rotation, failed: refused by either side, a malformed
33    /// message, an unverified responder, or the store (a rotation announced by a peer that is
34    /// not accepted is [`PairingError::Local`] with `coqui_peer::Error::NotAccepted`).
35    Pairing(PairingError),
36    /// A filesystem or stream operation failed.
37    Io(io::Error),
38    /// A file of certificate authorities ([`CaPolicy::ca_file`](crate::CaPolicy::ca_file),
39    /// [`Roots::bundle_file`](crate::Roots::bundle_file)) or a bundle given as text cannot be
40    /// used: unreadable, holding no certificate, or holding one that is malformed or cannot be
41    /// a trust anchor.
42    CaFile {
43        /// The file; `None` for a bundle given as text.
44        path: Option<std::path::PathBuf>,
45        /// The certificate that failed, by its position in the file from 0; `None` when the
46        /// file cannot be read or holds no certificate.
47        certificate: Option<usize>,
48        /// Why the file could not be read, when that is the failure.
49        read: Option<io::Error>,
50    },
51}
52
53impl fmt::Display for PeerError {
54    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
55        if let Self::Pairing(error) = self {
56            return write!(formatter, "{error}");
57        }
58        if let Self::CaFile {
59            path,
60            certificate,
61            read,
62        } = self
63        {
64            match path {
65                Some(path) => write!(formatter, "CA file {}: ", path.display())?,
66                None => formatter.write_str("CA bundle: ")?,
67            }
68            return match (certificate, read) {
69                (_, Some(_)) => formatter.write_str("cannot be read"),
70                (Some(index), None) => write!(
71                    formatter,
72                    "certificate {index} is malformed or cannot be a trust anchor"
73                ),
74                (None, None) => formatter.write_str("holds no certificate"),
75            };
76        }
77        formatter.write_str(match self {
78            Self::Pairing(_) => "pairing failed",
79            Self::CaFile { .. } => "CA file cannot be used",
80            Self::InvalidId => "peer id is invalid",
81            Self::Certificate => "certificate or private key is invalid",
82            Self::Tls => "TLS configuration or handshake failed",
83            Self::WeakDigest => "fingerprint is an MD5 digest, which is not supported",
84            Self::Policy(message) => message,
85            Self::TrustPattern => "certificate trust pattern is invalid",
86            Self::NotWaiting => "certificate is not waiting for acceptance",
87            Self::AlreadyAccepted => "certificate is already accepted",
88            Self::Path => "path must have a parent directory",
89            Self::Unsupported => "trust policy is not supported in this role",
90            Self::Io(_) => "storage or stream operation failed",
91        })
92    }
93}
94
95impl From<PairingError> for PeerError {
96    fn from(error: PairingError) -> Self {
97        Self::Pairing(error)
98    }
99}
100
101impl From<coqui_peer::Error> for PeerError {
102    fn from(error: coqui_peer::Error) -> Self {
103        match error {
104            coqui_peer::Error::InvalidId => Self::InvalidId,
105            coqui_peer::Error::WeakDigest => Self::WeakDigest,
106            coqui_peer::Error::UnknownDigest(_) => Self::Policy(error.to_string()),
107            coqui_peer::Error::NotWaiting => Self::NotWaiting,
108            coqui_peer::Error::AlreadyAccepted => Self::AlreadyAccepted,
109            coqui_peer::Error::Io(error) => Self::Io(error),
110            coqui_peer::Error::Material => Self::Certificate,
111            other => Self::Pairing(PairingError::Local(other)),
112        }
113    }
114}
115
116impl core::error::Error for PeerError {
117    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
118        match self {
119            Self::Io(error) => Some(error),
120            Self::Pairing(error) => Some(error),
121            Self::CaFile {
122                read: Some(error), ..
123            } => Some(error),
124            _ => None,
125        }
126    }
127}
128
129impl PeerError {
130    /// Why a pairing was refused, by this side or the other, when that is the failure.
131    pub fn pair_refusal(&self) -> Option<PairRefusal> {
132        match self {
133            Self::Pairing(PairingError::Refused(refusal)) => Some(*refusal),
134            _ => None,
135        }
136    }
137
138    /// The trust refusal behind this error, when a handshake failed because this side's
139    /// verifier refused the peer's certificate. The refused side sees only the TLS alert, so
140    /// its own error carries none.
141    pub fn refusal(&self) -> Option<Refusal> {
142        match self {
143            Self::Io(error) => error
144                .get_ref()
145                .and_then(|inner| inner.downcast_ref::<rustls::Error>())
146                .and_then(Refusal::from_rustls),
147            _ => None,
148        }
149    }
150}
151
152/// Why this side refused a peer: its certificate, or its addresses under a policy's access
153/// control list.
154///
155/// A verifier returns it inside
156/// `rustls::Error::InvalidCertificate(CertificateError::Other(OtherError(..)))`, so rustls
157/// sends the `certificate_unknown` alert; [`Refusal::from_rustls`] and
158/// [`PeerError::refusal`] take it back out. [`AddressDenied`](Refusal::AddressDenied) and an
159/// [`AddressUnknown`](Refusal::AddressUnknown) found at the `ClientHello` stop the handshake
160/// before any certificate: rustls sends `access_denied`, and the accept helpers report the
161/// refusal the same way. Expired and not-yet-valid certificates are rustls's own
162/// `CertificateError::Expired` and `NotValidYet`.
163#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
164#[non_exhaustive]
165pub enum Refusal {
166    /// The certificate matches no fixed pin.
167    NotPinned,
168    /// The certificate is not one the trust store accepted. A server with a store-backed pin
169    /// set records it as waiting, within the store's limits, once the peer proved its key.
170    NotAccepted,
171    /// The certificate matches no pin, and the CA policy does not trust its chain or names,
172    /// or the [`Roots`](crate::Roots) do not trust its chain (an unknown issuer, a bad
173    /// signature, a certificate not for server authentication).
174    NotTrusted,
175    /// A pinned peer presented a certificate chain, which the policy does not allow
176    /// ([`Policy::allow_chain_when_pinned`](crate::Policy::allow_chain_when_pinned)).
177    ChainWhenPinned,
178    /// The server's chain is trusted by the [`Roots`](crate::Roots), but the certificate is
179    /// not for the server name the client dialled.
180    NameMismatch,
181    /// The policy's access control list denies the connection's addresses: the rule at index
182    /// `rule`, or its default when `None`. Decided from the `ClientHello`, before any
183    /// certificate.
184    AddressDenied {
185        /// The index of the deciding rule in the list; `None` for the default.
186        rule: Option<usize>,
187    },
188    /// The policy's access control list denies this client's certificate from these
189    /// addresses: the rule at index `rule`, or its default when `None`. Decided before the
190    /// trust store is consulted, so nothing is recorded as waiting.
191    PeerDenied {
192        /// The index of the deciding rule in the list; `None` for the default.
193        rule: Option<usize>,
194    },
195    /// The policy has an access control list, and the connection's source address, or the
196    /// local address a rule with a destination or port needs, is unknown: the list is not
197    /// decided, and the connection is refused.
198    AddressUnknown,
199    /// The two sides authenticate with different certificate types: one with X.509
200    /// certificates, the other with raw public keys (RFC 7250). The side that finds out ends the
201    /// handshake with this refusal and the other sees the `handshake_failure` alert. A server
202    /// that serves both picks its configuration from the `ClientHello`
203    /// ([`offers_raw_public_key`](crate::offers_raw_public_key)).
204    CertificateType,
205}
206
207impl Refusal {
208    /// The refusal inside `error`, when one of this crate's verifiers produced it, or the
209    /// certificate type extensions of the two sides disagree.
210    pub fn from_rustls(error: &rustls::Error) -> Option<Self> {
211        match error {
212            rustls::Error::InvalidCertificate(rustls::CertificateError::Other(other)) => {
213                other.0.downcast_ref::<Self>().copied()
214            }
215            rustls::Error::PeerIncompatible(
216                rustls::PeerIncompatible::IncorrectCertificateTypeExtension,
217            ) => Some(Self::CertificateType),
218            _ => None,
219        }
220    }
221
222    /// The rustls error a verifier returns for this refusal.
223    pub(crate) fn into_rustls(self) -> rustls::Error {
224        rustls::Error::InvalidCertificate(rustls::CertificateError::Other(rustls::OtherError(
225            alloc::sync::Arc::new(self),
226        )))
227    }
228}
229
230impl fmt::Display for Refusal {
231    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
232        formatter.write_str(match self {
233            Self::NotPinned => "peer certificate matches no pinned fingerprint",
234            Self::NotAccepted => "peer certificate is not an accepted peer of the trust store",
235            Self::NotTrusted => {
236                "peer certificate matches no pin and is not trusted by the CA policy or roots"
237            }
238            Self::ChainWhenPinned => {
239                "pinned peer presented a certificate chain, which the policy does not allow"
240            }
241            Self::NameMismatch => "server certificate is not valid for the name dialled",
242            Self::AddressDenied { .. } => "access control list denies the client's address",
243            Self::PeerDenied { .. } => "access control list denies the client's certificate",
244            Self::AddressUnknown => {
245                "access control list needs the connection's addresses, which are unknown"
246            }
247            Self::CertificateType => {
248                "peer authenticates with another certificate type (X.509 or raw public key)"
249            }
250        })
251    }
252}
253
254impl core::error::Error for Refusal {}