Skip to main content

identity_kit/resolver/
x509.rs

1//! `X509Resolver`: the key of an `x5c` certificate chain, validated against trust anchors, and
2//! `X509Certificate`, what a certificate says about its subject.
3
4use core::fmt;
5use core::time::Duration;
6use std::error::Error;
7use std::time::{SystemTime, UNIX_EPOCH};
8
9use rustls_pki_types::pem::PemObject as _;
10use rustls_pki_types::{CertificateDer, TrustAnchor, UnixTime};
11use sha2::{Digest as _, Sha256};
12use webpki::{EndEntityCert, ExtendedKeyUsageValidator, KeyPurposeIdIter};
13use x509_cert::Certificate;
14use x509_cert::der::{Decode as _, Encode as _};
15use x509_cert::ext::pkix::name::GeneralName;
16use x509_cert::ext::pkix::{
17    AuthorityKeyIdentifier, BasicConstraints, KeyUsage, SubjectAltName, SubjectKeyIdentifier,
18};
19use x509_cert::spki::SubjectPublicKeyInfoRef;
20
21use super::{KeyReference, KeyResolutionError, KeyResolver, KeyRole};
22use crate::jose::{Jwk, base64url};
23
24/// `id-ecPublicKey` (RFC 5480 §2.1.1).
25const EC_PUBLIC_KEY: &str = "1.2.840.10045.2.1";
26/// `secp256r1`, the curve P-256 (RFC 5480 §2.1.1.1).
27const SECP256R1: &str = "1.2.840.10045.3.1.7";
28/// `secp384r1`, the curve P-384.
29const SECP384R1: &str = "1.3.132.0.34";
30/// `secp256k1`.
31#[cfg(feature = "secp256k1")]
32const SECP256K1: &str = "1.3.132.0.10";
33/// `id-Ed25519` (RFC 8410 §3).
34const ED25519: &str = "1.3.101.112";
35/// `rsaEncryption` (RFC 8017 Appendix A.1).
36const RSA_ENCRYPTION: &str = "1.2.840.113549.1.1.1";
37/// The shortest RSA modulus accepted, as for signatures (RFC 7518 §3.3).
38const MIN_RSA_BITS: usize = 2048;
39
40/// Resolves a [`KeyReference::X509Chain`], the `x5c` header of a token (RFC 7515 §4.1.6), to
41/// the public key of its first certificate once the chain validates against a trust anchor;
42/// every other reference is [`Unsupported`](KeyResolutionError::Unsupported).
43///
44/// This is the *Inline X.509 Certificates* mechanism of SD-JWT VC §3.5, which the OpenID4VC
45/// High Assurance Interoperability Profile (HAIP) 1.0 mandates for SD-JWT VCs (§6.1.1), for
46/// Status List Tokens (§6.1) and for the signed requests, metadata and attestations of
47/// OID4VCI and OID4VP.
48///
49/// # What is checked
50///
51/// The application supplies the trust anchors; the crate ships none, and a certificate is
52/// never trusted because the token carries it. For a chain `[leaf, intermediate…]`:
53///
54/// 1. The chain has at least one and at most [`MAX_CHAIN_LENGTH`](Self::MAX_CHAIN_LENGTH)
55///    certificates.
56/// 2. Every certificate of the chain reads as one, and the leaf is not self-issued (its
57///    subject is not its issuer), which HAIP requires of every `x5c` it defines: "The X.509
58///    certificate signing the request MUST NOT be self-signed."
59/// 3. A path from the leaf to a trust anchor validates, at the validation time: each
60///    signature, each validity period, `basicConstraints` and the path length, name
61///    constraints on DNS names, and no critical extension that is not understood. The
62///    certificates after the leaf are a pool to build the path from, so their order does not
63///    matter, and one that is itself a trust anchor adds nothing. Path building and these
64///    checks are [`rustls-webpki`](https://docs.rs/rustls-webpki)'s.
65/// 4. Every CA certificate of the path that has a `keyUsage` extension asserts
66///    `keyCertSign` (RFC 5280 §6.1.4), the trust anchor included.
67/// 5. The trust anchor the path ends at is within its own validity period.
68/// 6. A leaf that has a `keyUsage` extension asserts `digitalSignature` or `nonRepudiation`
69///    (`contentCommitment`, which qualified seal certificates carry alone), and not
70///    `keyCertSign` (RFC 5280 §4.2.1.3).
71/// 7. The leaf's key is one a JWS can be verified with: P-256, P-384, secp256k1 (feature
72///    `secp256k1`), Ed25519 or RSA of at least 2048 bits.
73///
74/// Certificates are signed with ECDSA on P-256 or P-384, Ed25519, or RSA from 2048 bits, with
75/// SHA-256, SHA-384 or SHA-512. SHA-1, P-521 and Brainpool curves are refused.
76///
77/// # What is not checked
78///
79/// - **Revocation.** Neither CRLs nor OCSP are consulted. An application that needs it checks
80///   the chain itself, or keeps its trust anchors current.
81/// - **Extended key usage and certificate policies.** SD-JWT VC and HAIP define none for
82///   credential issuers, so any is accepted. The [`KeyRole`] makes no difference either: a
83///   chain is validated the same for an issuer and for a holder.
84/// - **Name constraints on anything but DNS names**, which is why only a DNS name binds an
85///   `iss` ([`X509Certificate::binds`]).
86/// - **Whether the chain leaves out the trust anchor.** HAIP forbids an issuer to include
87///   it. A verifier that pins an intermediate CA cannot tell an issuer's chain that includes
88///   it from a violation, and a copy of an anchor adds no trust, so such a chain validates.
89/// - **Who the subject is.** A valid chain says the key belongs to the subject of the leaf
90///   under one of the trust anchors, not that this subject may issue a given credential:
91///   that is the application's policy, with [`X509Certificate`] to read the subject from.
92///
93/// # The issuer of a token
94///
95/// With `x5c`, the issuer is the subject of the leaf certificate, and an `iss` claim is not
96/// authenticated by the chain (SD-JWT VC §3.5). [`KeyReference::binds_to`] therefore accepts
97/// an `iss` only when the leaf binds it, as an `https` URL whose host is one of its DNS names
98/// ([`X509Certificate::binds`]), and the SD-JWT VC validator accepts a credential without
99/// `iss`.
100///
101/// Every CA under the trust anchors is trusted to certify the names it puts in a leaf, the
102/// subject included: name constraints restrict DNS names in the Subject Alternative Name
103/// extension, not a common name. Which mechanism verifies a token also follows from what the
104/// token carries, a chain or a `kid`, whenever the application configures resolvers for both;
105/// an application that must pin one mechanism per issuer (SD-JWT VC §3.5 asks that an
106/// attacker cannot choose it) checks the `KeyReference` the validator returns, or gives each
107/// issuer's tokens a validator with the one resolver.
108///
109/// # Time
110///
111/// A validator passes its validation time through [`KeyResolver::resolve_key_at`];
112/// [`resolve_key`](KeyResolver::resolve_key) validates at the current time. A resolver that
113/// wraps this one must forward `resolve_key_at`, or its chains are validated at the current
114/// time whatever the validator asks.
115#[derive(Clone)]
116pub struct X509Resolver {
117    anchors: Vec<Anchor>,
118}
119
120/// A trust anchor: its certificate and when that is valid.
121#[derive(Clone)]
122struct Anchor {
123    der: CertificateDer<'static>,
124    not_before: i64,
125    not_after: i64,
126}
127
128impl X509Resolver {
129    /// The most certificates an `x5c` chain may hold.
130    pub const MAX_CHAIN_LENGTH: usize = 10;
131
132    /// A resolver trusting `anchors`, DER-encoded certificates: root CAs, or any CA
133    /// certificate the application pins.
134    ///
135    /// Each anchor must be a CA certificate, one whose `basicConstraints` say `cA` and whose
136    /// `keyUsage`, if it has one, asserts `keyCertSign`: whoever holds the key of an anchor
137    /// can issue certificates this resolver accepts, so a certificate that signs credentials
138    /// is refused as an anchor. A resolver without anchors
139    /// refuses every chain.
140    ///
141    /// # Errors
142    ///
143    /// [`X509Error::InvalidCertificate`] when an anchor is not a certificate, and
144    /// [`X509Error::TrustAnchorNotCa`] when it is not a CA certificate.
145    pub fn new<I, C>(anchors: I) -> Result<Self, X509Error>
146    where
147        I: IntoIterator<Item = C>,
148        C: Into<Vec<u8>>,
149    {
150        let anchors = anchors
151            .into_iter()
152            .enumerate()
153            .map(|(index, anchor)| {
154                let der = CertificateDer::from(anchor.into());
155                let certificate = X509Certificate::parse(&der)
156                    .map_err(|e| X509Error::invalid_certificate(index, e))?;
157                webpki::anchor_from_trusted_cert(&der)
158                    .map_err(|e| X509Error::invalid_certificate(index, e))?;
159                if !certificate.may_issue() {
160                    return Err(X509Error::TrustAnchorNotCa { index });
161                }
162                Ok(Anchor {
163                    der,
164                    not_before: certificate.not_before,
165                    not_after: certificate.not_after,
166                })
167            })
168            .collect::<Result<_, _>>()?;
169        Ok(Self { anchors })
170    }
171
172    /// A resolver trusting every certificate of `pem`, a concatenation of
173    /// `-----BEGIN CERTIFICATE-----` blocks.
174    ///
175    /// # Errors
176    ///
177    /// [`X509Error::InvalidPem`] when `pem` does not read as PEM or holds no certificate, and
178    /// [`X509Error::InvalidCertificate`] when one of them is not a certificate.
179    pub fn from_pem(pem: &str) -> Result<Self, X509Error> {
180        let anchors = CertificateDer::pem_slice_iter(pem.as_bytes())
181            .map(|certificate| certificate.map(|certificate| certificate.to_vec()))
182            .collect::<Result<Vec<_>, _>>()
183            .map_err(|e| X509Error::InvalidPem(e.to_string()))?;
184        if anchors.is_empty() {
185            return Err(X509Error::InvalidPem("no certificate".to_owned()));
186        }
187        Self::new(anchors)
188    }
189
190    /// The trust anchors, DER-encoded.
191    pub fn anchors(&self) -> impl Iterator<Item = &[u8]> {
192        self.anchors.iter().map(|anchor| anchor.der.as_ref())
193    }
194
195    /// Validates `chain`, the certificates of an `x5c` header, leaf first and DER-encoded, at
196    /// `now` (seconds since the Unix epoch), and returns the public key of the leaf.
197    ///
198    /// # Errors
199    ///
200    /// An [`X509Error`] naming the first check of the [type documentation](Self) that fails.
201    pub fn validate(&self, chain: &[Vec<u8>], now: i64) -> Result<Jwk, X509Error> {
202        let (leaf_der, intermediates) = chain.split_first().ok_or(X509Error::EmptyChain)?;
203        if chain.len() > Self::MAX_CHAIN_LENGTH {
204            return Err(X509Error::ChainTooLong {
205                length: chain.len(),
206                max: Self::MAX_CHAIN_LENGTH,
207            });
208        }
209        let certificates = chain
210            .iter()
211            .enumerate()
212            .map(|(index, certificate)| {
213                X509Certificate::parse(certificate)
214                    .map_err(|e| X509Error::invalid_certificate(index, e))
215            })
216            .collect::<Result<Vec<_>, _>>()?;
217        let leaf = &certificates[0];
218        if leaf.is_self_issued() {
219            return Err(X509Error::SelfSigned);
220        }
221
222        let time = u64::try_from(now)
223            .map(|now| UnixTime::since_unix_epoch(Duration::from_secs(now)))
224            .map_err(|_| X509Error::InvalidTime(now))?;
225        let anchors = self
226            .anchors
227            .iter()
228            .map(|anchor| webpki::anchor_from_trusted_cert(&anchor.der))
229            .collect::<Result<Vec<_>, _>>()
230            .map_err(|e| X509Error::PathValidation(Box::new(e)))?;
231        // What `rustls-webpki` leaves to its caller, for each path it has verified; an error
232        // makes path building try another one.
233        let check_path = |path: &webpki::VerifiedPath<'_>| {
234            // A CA certificate with a `keyUsage` that lacks `keyCertSign` issues nothing.
235            for intermediate in path.intermediate_certificates() {
236                let der = intermediate.der();
237                let may_issue = certificates
238                    .iter()
239                    .find(|certificate| certificate.der == der.as_ref())
240                    .is_some_and(X509Certificate::may_issue);
241                if !may_issue {
242                    return Err(webpki::Error::EndEntityUsedAsCa);
243                }
244            }
245            anchor_validity(path.anchor(), anchors.iter().zip(&self.anchors), now)
246        };
247        let intermediates: Vec<CertificateDer<'_>> = intermediates
248            .iter()
249            .map(|certificate| CertificateDer::from(certificate.as_slice()))
250            .collect();
251        let leaf_der = CertificateDer::from(leaf_der.as_slice());
252        let end_entity =
253            EndEntityCert::try_from(&leaf_der).map_err(|e| X509Error::invalid_certificate(0, e))?;
254        end_entity
255            .verify_for_usage(
256                webpki::ALL_VERIFICATION_ALGS,
257                &anchors,
258                &intermediates,
259                time,
260                AnyExtendedKeyUsage,
261                None,
262                Some(&check_path),
263            )
264            .map_err(|e| X509Error::PathValidation(Box::new(e)))?;
265
266        if !leaf.may_sign_tokens() {
267            return Err(X509Error::KeyUsage);
268        }
269        leaf.public_key()
270    }
271}
272
273impl fmt::Debug for X509Resolver {
274    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
275        f.debug_struct("X509Resolver")
276            .field("anchors", &self.anchors.len())
277            .finish()
278    }
279}
280
281#[async_trait::async_trait]
282impl KeyResolver for X509Resolver {
283    async fn resolve_key(
284        &self,
285        key: &KeyReference,
286        role: KeyRole,
287    ) -> Result<Jwk, KeyResolutionError> {
288        let now = SystemTime::now()
289            .duration_since(UNIX_EPOCH)
290            .map_or(0, |elapsed| {
291                i64::try_from(elapsed.as_secs()).unwrap_or(i64::MAX)
292            });
293        self.resolve_key_at(key, role, now).await
294    }
295
296    async fn resolve_key_at(
297        &self,
298        key: &KeyReference,
299        _: KeyRole,
300        now: i64,
301    ) -> Result<Jwk, KeyResolutionError> {
302        match key {
303            KeyReference::X509Chain(chain) => {
304                self.validate(chain, now).map_err(KeyResolutionError::new)
305            }
306            other => Err(KeyResolutionError::unsupported(other)),
307        }
308    }
309}
310
311/// Whether a certificate configured as the trust anchor `used` is valid at `now`; the error
312/// of the last one that is not, otherwise.
313///
314/// `rustls-webpki` reads a trust anchor as a name, a key and name constraints, without a
315/// validity period, so `used` stands for every configured certificate with those three alike.
316/// A certificate with the same name and key and other constraints is another anchor, which
317/// the path was not verified under: it lends this one no validity.
318fn anchor_validity<'a>(
319    used: &TrustAnchor<'_>,
320    configured: impl IntoIterator<Item = (&'a TrustAnchor<'a>, &'a Anchor)>,
321    now: i64,
322) -> Result<(), webpki::Error> {
323    let mut error = webpki::Error::UnknownIssuer;
324    for (anchor, certificate) in configured {
325        if anchor.subject != used.subject
326            || anchor.subject_public_key_info != used.subject_public_key_info
327            || anchor.name_constraints != used.name_constraints
328        {
329            continue;
330        }
331        match outside_validity(now, certificate.not_before, certificate.not_after) {
332            None => return Ok(()),
333            Some(outside) => error = outside,
334        }
335    }
336    Err(error)
337}
338
339/// Why a certificate valid from `not_before` to `not_after`, both inclusive and in seconds
340/// since the Unix epoch, is not valid at `now`; `None` when it is.
341fn outside_validity(now: i64, not_before: i64, not_after: i64) -> Option<webpki::Error> {
342    let time = |seconds: i64| {
343        UnixTime::since_unix_epoch(Duration::from_secs(u64::try_from(seconds).unwrap_or(0)))
344    };
345    if now < not_before {
346        Some(webpki::Error::CertNotValidYet {
347            time: time(now),
348            not_before: time(not_before),
349        })
350    } else if now > not_after {
351        Some(webpki::Error::CertExpired {
352            time: time(now),
353            not_after: time(not_after),
354        })
355    } else {
356        None
357    }
358}
359
360/// Accepts any extended key usage, and a certificate without one: the specifications that
361/// use `x5c` here define none.
362struct AnyExtendedKeyUsage;
363
364impl ExtendedKeyUsageValidator for AnyExtendedKeyUsage {
365    fn validate(&self, iter: KeyPurposeIdIter<'_, '_>) -> Result<(), webpki::Error> {
366        // Reading every entry still refuses an extension that is not a list of OIDs.
367        for purpose in iter {
368            purpose?;
369        }
370        Ok(())
371    }
372}
373
374/// The `keyUsage` bits this module reads.
375#[derive(Debug, Clone, Copy, PartialEq, Eq)]
376struct Usage {
377    digital_signature: bool,
378    non_repudiation: bool,
379    key_cert_sign: bool,
380}
381
382/// What an X.509 certificate says: its subject and issuer, the names of its Subject
383/// Alternative Name extension, its validity period, its key identifiers and its public key.
384///
385/// Reading a certificate verifies nothing: [`X509Resolver`] decides whether it is trusted.
386/// With an `x5c` header the issuer of a token is the subject of the first certificate, so this
387/// is what an application reads to decide whether that issuer may say what the token says.
388///
389/// # Examples
390///
391/// ```
392/// use identity_kit::resolver::{KeyReference, X509Certificate};
393///
394/// /// The subject of the certificate that signed a token, when it was signed with `x5c`.
395/// fn signer(key: &KeyReference) -> Option<String> {
396///     let KeyReference::X509Chain(chain) = key else { return None };
397///     let leaf = X509Certificate::from_der(chain.first()?).ok()?;
398///     Some(leaf.subject().to_owned())
399/// }
400/// # let _ = signer;
401/// ```
402#[derive(Clone, PartialEq, Eq)]
403pub struct X509Certificate {
404    der: Vec<u8>,
405    subject: String,
406    issuer: String,
407    self_issued: bool,
408    ca: bool,
409    dns_names: Vec<String>,
410    uris: Vec<String>,
411    not_before: i64,
412    not_after: i64,
413    subject_key_identifier: Option<Vec<u8>>,
414    authority_key_identifier: Option<Vec<u8>>,
415    key_usage: Option<Usage>,
416    public_key: Vec<u8>,
417}
418
419impl X509Certificate {
420    /// Reads a DER-encoded certificate.
421    ///
422    /// # Errors
423    ///
424    /// [`X509Error::InvalidCertificate`], with index 0, when `der` is not a certificate or one
425    /// of the extensions read here is malformed.
426    pub fn from_der(der: &[u8]) -> Result<Self, X509Error> {
427        Self::parse(der).map_err(|e| X509Error::invalid_certificate(0, e))
428    }
429
430    fn parse(der: &[u8]) -> Result<Self, x509_cert::der::Error> {
431        let certificate = Certificate::from_der(der)?;
432        let tbs = certificate.tbs_certificate();
433        let (mut dns_names, mut uris) = (Vec::new(), Vec::new());
434        if let Some((_, SubjectAltName(names))) = tbs.get_extension::<SubjectAltName>()? {
435            for name in names {
436                match name {
437                    GeneralName::DnsName(name) => dns_names.push(name.to_string()),
438                    GeneralName::UniformResourceIdentifier(uri) => uris.push(uri.to_string()),
439                    _ => {}
440                }
441            }
442        }
443        let subject_key_identifier = tbs
444            .get_extension::<SubjectKeyIdentifier>()?
445            .map(|(_, identifier)| identifier.0.as_bytes().to_vec());
446        let authority_key_identifier = tbs
447            .get_extension::<AuthorityKeyIdentifier>()?
448            .and_then(|(_, identifier)| identifier.key_identifier)
449            .map(|identifier| identifier.as_bytes().to_vec());
450        let key_usage = tbs.get_extension::<KeyUsage>()?.map(|(_, usage)| Usage {
451            digital_signature: usage.digital_signature(),
452            non_repudiation: usage.non_repudiation(),
453            key_cert_sign: usage.key_cert_sign(),
454        });
455        let ca = tbs
456            .get_extension::<BasicConstraints>()?
457            .is_some_and(|(_, constraints)| constraints.ca);
458        let seconds = |time: x509_cert::time::Time| {
459            i64::try_from(time.to_unix_duration().as_secs()).unwrap_or(i64::MAX)
460        };
461        Ok(Self {
462            der: der.to_vec(),
463            subject: tbs.subject().to_string(),
464            issuer: tbs.issuer().to_string(),
465            self_issued: tbs.subject().to_der()? == tbs.issuer().to_der()?,
466            ca,
467            dns_names,
468            uris,
469            not_before: seconds(tbs.validity().not_before),
470            not_after: seconds(tbs.validity().not_after),
471            subject_key_identifier,
472            authority_key_identifier,
473            key_usage,
474            public_key: tbs.subject_public_key_info().to_der()?,
475        })
476    }
477
478    /// The certificate, DER-encoded.
479    pub fn der(&self) -> &[u8] {
480        &self.der
481    }
482
483    /// The subject's distinguished name, as a string (RFC 4514): `CN=Example Issuer,O=Example,C=DE`.
484    pub fn subject(&self) -> &str {
485        &self.subject
486    }
487
488    /// The issuer's distinguished name, as a string (RFC 4514).
489    pub fn issuer(&self) -> &str {
490        &self.issuer
491    }
492
493    /// Whether the subject and the issuer are the same name: a self-signed certificate, or
494    /// one a CA issued to itself.
495    pub fn is_self_issued(&self) -> bool {
496        self.self_issued
497    }
498
499    /// Whether the `basicConstraints` extension says the subject is a CA.
500    pub fn is_ca(&self) -> bool {
501        self.ca
502    }
503
504    /// The `dNSName` entries of the Subject Alternative Name extension.
505    pub fn dns_names(&self) -> &[String] {
506        &self.dns_names
507    }
508
509    /// The `uniformResourceIdentifier` entries of the Subject Alternative Name extension.
510    pub fn uris(&self) -> &[String] {
511        &self.uris
512    }
513
514    /// The start of the validity period, in seconds since the Unix epoch.
515    pub fn not_before(&self) -> i64 {
516        self.not_before
517    }
518
519    /// The end of the validity period, in seconds since the Unix epoch.
520    pub fn not_after(&self) -> i64 {
521        self.not_after
522    }
523
524    /// The Subject Key Identifier extension, if present.
525    pub fn subject_key_identifier(&self) -> Option<&[u8]> {
526        self.subject_key_identifier.as_deref()
527    }
528
529    /// The `keyIdentifier` of the Authority Key Identifier extension, if present: what an
530    /// `aki` trusted authorities query of OID4VP §6.1.1.1 compares, base64url-encoded.
531    pub fn authority_key_identifier(&self) -> Option<&[u8]> {
532        self.authority_key_identifier.as_deref()
533    }
534
535    /// The SHA-256 hash of the DER encoding, base64url-encoded: the `x5t#S256` of RFC 7515
536    /// §4.1.8 and the value of an `x509_hash` client identifier of OID4VP §5.9.3.
537    pub fn sha256_thumbprint(&self) -> String {
538        base64url::encode(&Sha256::digest(&self.der))
539    }
540
541    /// The subject's public key.
542    ///
543    /// # Errors
544    ///
545    /// [`X509Error::UnsupportedKey`] for a key no JWS algorithm of this crate uses, and
546    /// [`X509Error::InvalidKey`] for one that does not decode.
547    pub fn public_key(&self) -> Result<Jwk, X509Error> {
548        jwk_from_spki(&self.public_key)
549    }
550
551    /// Whether this certificate binds `identifier`, the `iss` of a token it signed: an `https`
552    /// URL whose host is one of the `dNSName` entries of the Subject Alternative Name
553    /// extension.
554    ///
555    /// The URL must be written the one way every parser reads alike, since the `iss` goes on
556    /// to other components as a string: no credentials, query or fragment, a domain name
557    /// rather than an IP address as host, in lower case and, when internationalized, in its
558    /// ASCII form, with nothing a URL parser would normalize away. A port and a path are the
559    /// issuer's own. Wildcard names bind nothing.
560    ///
561    /// A `uniformResourceIdentifier` entry binds nothing, an `https` URL or a DID alike: name
562    /// constraints on DNS names, which is how a CA is usually confined to its domains, do not
563    /// reach URIs, so a confined CA could certify any. [`uris`](Self::uris) has them for an
564    /// application that trusts its CAs with that.
565    pub fn binds(&self, identifier: &str) -> bool {
566        let Ok(url) = url::Url::parse(identifier) else {
567            return false;
568        };
569        if url.scheme() != "https"
570            || !url.username().is_empty()
571            || url.password().is_some()
572            || url.query().is_some()
573            || url.fragment().is_some()
574        {
575            return false;
576        }
577        let Some(url::Host::Domain(host)) = url.host() else {
578            return false;
579        };
580        // The parser accepts and repairs much that is not the URL it returns (white space,
581        // backslashes, an upper-case or percent-encoded host); only what it returns unchanged
582        // is bound, give or take the `/` of an empty path.
583        let canonical = url.as_str();
584        let written_canonically = identifier == canonical
585            || (url.path() == "/" && canonical.strip_suffix('/') == Some(identifier));
586        written_canonically
587            && self
588                .dns_names
589                .iter()
590                .any(|name| !name.contains('*') && name.eq_ignore_ascii_case(host))
591    }
592
593    /// Whether this certificate may issue others: a CA whose `keyUsage`, if it has one,
594    /// asserts `keyCertSign` (RFC 5280 §4.2.1.3, §6.1.4).
595    fn may_issue(&self) -> bool {
596        self.ca && self.key_usage.is_none_or(|usage| usage.key_cert_sign)
597    }
598
599    /// Whether this certificate's `keyUsage`, if it has one, lets its key sign a token:
600    /// `digitalSignature` or `nonRepudiation`, and not `keyCertSign`.
601    fn may_sign_tokens(&self) -> bool {
602        self.key_usage.is_none_or(|usage| {
603            (usage.digital_signature || usage.non_repudiation) && !usage.key_cert_sign
604        })
605    }
606}
607
608impl fmt::Debug for X509Certificate {
609    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
610        f.debug_struct("X509Certificate")
611            .field("subject", &self.subject)
612            .field("issuer", &self.issuer)
613            .field("dns_names", &self.dns_names)
614            .field("uris", &self.uris)
615            .field("not_before", &self.not_before)
616            .field("not_after", &self.not_after)
617            .finish_non_exhaustive()
618    }
619}
620
621/// The JWK of a DER-encoded `SubjectPublicKeyInfo`, whatever its algorithm.
622fn jwk_from_spki(der: &[u8]) -> Result<Jwk, X509Error> {
623    let invalid = |e: &dyn fmt::Display| X509Error::InvalidKey(e.to_string());
624    let spki = SubjectPublicKeyInfoRef::from_der(der).map_err(|e| invalid(&e))?;
625    let key = spki.subject_public_key.raw_bytes();
626    let algorithm = spki.algorithm.oid.to_string();
627    match algorithm.as_str() {
628        EC_PUBLIC_KEY => {
629            let curve = spki
630                .algorithm
631                .parameters_oid()
632                .map_err(|e| invalid(&e))?
633                .to_string();
634            match curve.as_str() {
635                SECP256R1 => Jwk::from_p256_public(key).map_err(|e| invalid(&e)),
636                SECP384R1 => p384_jwk(key),
637                #[cfg(feature = "secp256k1")]
638                SECP256K1 => Jwk::from_secp256k1_public(key).map_err(|e| invalid(&e)),
639                _ => Err(X509Error::UnsupportedKey(format!("elliptic curve {curve}"))),
640            }
641        }
642        ED25519 => Jwk::from_ed25519_public(key).map_err(|e| invalid(&e)),
643        RSA_ENCRYPTION => {
644            let jwk = Jwk::from_pkcs1_der(key).map_err(|e| invalid(&e))?;
645            let (modulus, _) = jwk.rsa_public_components().map_err(|e| invalid(&e))?;
646            let bits = modulus
647                .iter()
648                .position(|&byte| byte != 0)
649                .map_or(0, |first| {
650                    (modulus.len() - first) * 8 - modulus[first].leading_zeros() as usize
651                });
652            if bits < MIN_RSA_BITS {
653                return Err(X509Error::UnsupportedKey(format!(
654                    "RSA key of {bits} bits, shorter than {MIN_RSA_BITS}"
655                )));
656            }
657            Ok(jwk)
658        }
659        _ => Err(X509Error::UnsupportedKey(format!("algorithm {algorithm}"))),
660    }
661}
662
663/// The JWK of an uncompressed P-384 point, `0x04 || x || y`.
664fn p384_jwk(point: &[u8]) -> Result<Jwk, X509Error> {
665    const COORDINATE: usize = 48;
666    let invalid = || X509Error::InvalidKey("not an uncompressed P-384 point".to_owned());
667    let (tag, coordinates) = point.split_first().ok_or_else(invalid)?;
668    if *tag != 0x04 || coordinates.len() != 2 * COORDINATE {
669        return Err(invalid());
670    }
671    let (x, y) = coordinates.split_at(COORDINATE);
672    serde_json::from_value(serde_json::json!({
673        "kty": "EC",
674        "crv": "P-384",
675        "x": base64url::encode(x),
676        "y": base64url::encode(y),
677    }))
678    .map_err(|e| X509Error::InvalidKey(e.to_string()))
679}
680
681/// Why an `x5c` chain yields no key.
682#[derive(Debug, thiserror::Error)]
683#[non_exhaustive]
684pub enum X509Error {
685    /// The chain holds no certificate.
686    #[error("the certificate chain is empty")]
687    EmptyChain,
688    /// The chain holds more certificates than [`X509Resolver::MAX_CHAIN_LENGTH`].
689    #[error("the certificate chain has {length} certificates, more than {max}")]
690    ChainTooLong {
691        /// The number of certificates.
692        length: usize,
693        /// The limit.
694        max: usize,
695    },
696    /// A certificate does not decode.
697    #[error("certificate {index} is invalid: {source}")]
698    InvalidCertificate {
699        /// The index of the certificate in the chain, or among the trust anchors.
700        index: usize,
701        /// Why it does not decode.
702        #[source]
703        source: Box<dyn Error + Send + Sync>,
704    },
705    /// The PEM text does not hold certificates.
706    #[error("invalid PEM: {0}")]
707    InvalidPem(String),
708    /// The first certificate is self-issued: its subject is its issuer, as in a self-signed
709    /// certificate. HAIP forbids it, and a certificate is not a trust anchor because a token
710    /// carries it.
711    #[error("the signing certificate is self-signed")]
712    SelfSigned,
713    /// The validation time is before the Unix epoch.
714    #[error("the validation time {0} is before 1970")]
715    InvalidTime(i64),
716    /// No path from the first certificate to a trust anchor validates: an unknown issuer, a
717    /// wrong signature, an expired certificate, a CA constraint. The source says which.
718    #[error("the certificate chain does not validate: {0}")]
719    PathValidation(#[source] Box<dyn Error + Send + Sync>),
720    /// A trust anchor is not a CA certificate, or its `keyUsage` lacks `keyCertSign`.
721    #[error("trust anchor {index} is not a CA certificate")]
722    TrustAnchorNotCa {
723        /// The index of the anchor among those given.
724        index: usize,
725    },
726    /// The first certificate has a `keyUsage` extension that does not allow signing a token:
727    /// it has neither `digitalSignature` nor `nonRepudiation`, or asserts `keyCertSign`.
728    #[error("the signing certificate's key usage does not allow signing a token")]
729    KeyUsage,
730    /// The first certificate's key is of a kind no JWS algorithm of this crate uses.
731    #[error("unsupported certificate key: {0}")]
732    UnsupportedKey(String),
733    /// The first certificate's key does not decode.
734    #[error("invalid certificate key: {0}")]
735    InvalidKey(String),
736}
737
738impl X509Error {
739    /// [`InvalidCertificate`](Self::InvalidCertificate) for the certificate at `index`.
740    fn invalid_certificate<E: Error + Send + Sync + 'static>(index: usize, source: E) -> Self {
741        Self::InvalidCertificate {
742            index,
743            source: Box::new(source),
744        }
745    }
746}
747
748#[cfg(test)]
749mod tests {
750    use super::*;
751
752    #[test]
753    fn validity_is_inclusive_at_both_ends() {
754        for now in [100, 150, 200] {
755            assert!(outside_validity(now, 100, 200).is_none(), "{now}");
756        }
757        assert!(matches!(
758            outside_validity(99, 100, 200),
759            Some(webpki::Error::CertNotValidYet { .. })
760        ));
761        assert!(matches!(
762            outside_validity(201, 100, 200),
763            Some(webpki::Error::CertExpired { .. })
764        ));
765    }
766
767    /// A CA reissued with the same name and key is one trust anchor when its name
768    /// constraints are the same, and the validity of either certificate is the anchor's. With
769    /// other constraints it is another anchor: an expired certificate without constraints is
770    /// not valid again because a constrained one with its name and key is.
771    #[test]
772    fn anchor_validity_is_that_of_the_anchor_the_path_was_verified_under() {
773        use rustls_pki_types::Der;
774
775        let anchor = |constraints: Option<&'static [u8]>| TrustAnchor {
776            subject: Der::from_slice(b"subject"),
777            subject_public_key_info: Der::from_slice(b"key"),
778            name_constraints: constraints.map(Der::from_slice),
779        };
780        let valid = |not_before, not_after| Anchor {
781            der: CertificateDer::from(Vec::new()),
782            not_before,
783            not_after,
784        };
785        let (unconstrained, constrained) = (anchor(None), anchor(Some(b"allowed.example")));
786        let (expired, current) = (valid(100, 200), valid(150, 300));
787        let now = 250;
788
789        let configured = [(&unconstrained, &expired), (&constrained, &current)];
790        assert!(matches!(
791            anchor_validity(&unconstrained, configured, now),
792            Err(webpki::Error::CertExpired { .. })
793        ));
794        assert!(anchor_validity(&constrained, configured, now).is_ok());
795
796        // The same anchor twice: the certificate that is valid decides, in either order.
797        for configured in [
798            [(&unconstrained, &expired), (&unconstrained, &current)],
799            [(&unconstrained, &current), (&unconstrained, &expired)],
800        ] {
801            assert!(anchor_validity(&unconstrained, configured, now).is_ok());
802        }
803        // An anchor that is not configured, by its name or by its key.
804        let other = TrustAnchor {
805            subject: Der::from_slice(b"other"),
806            ..anchor(None)
807        };
808        assert!(matches!(
809            anchor_validity(&other, configured, now),
810            Err(webpki::Error::UnknownIssuer)
811        ));
812    }
813
814    /// A certificate with the names `dns_names` and `uris`, and the key usage `usage`.
815    fn certificate(dns_names: &[&str], uris: &[&str], usage: Option<Usage>) -> X509Certificate {
816        X509Certificate {
817            der: Vec::new(),
818            subject: "CN=example".to_owned(),
819            issuer: "CN=ca".to_owned(),
820            self_issued: false,
821            ca: false,
822            dns_names: dns_names.iter().map(|&name| name.to_owned()).collect(),
823            uris: uris.iter().map(|&uri| uri.to_owned()).collect(),
824            not_before: 0,
825            not_after: 0,
826            subject_key_identifier: None,
827            authority_key_identifier: None,
828            key_usage: usage,
829            public_key: Vec::new(),
830        }
831    }
832
833    /// An `iss` binds only as a URL every parser reads the same way.
834    #[test]
835    fn binds_only_canonical_https_urls() {
836        let named = certificate(&["issuer.example", "xn--mnchen-3ya.example"], &[], None);
837        for bound in [
838            "https://issuer.example",
839            "https://issuer.example/",
840            "https://issuer.example/tenant/1",
841            "https://issuer.example:8443/tenant/",
842            "https://xn--mnchen-3ya.example",
843        ] {
844            assert!(named.binds(bound), "{bound}");
845        }
846        for unbound in [
847            // Another host, however the URL is dressed up.
848            "https://victim.example",
849            "https://issuer.example.victim.example",
850            "https://victim.example@issuer.example",
851            "https://victim.example:pw@issuer.example/",
852            "https://issuer.example\\@victim.example",
853            "https://issuer.example?x=https://victim.example",
854            "https://issuer.example#https://victim.example",
855            // The right host, written as a parser would not write it.
856            " https://issuer.example",
857            "https://issuer.example ",
858            "https:issuer.example",
859            "https:\\\\issuer.example",
860            "https://issuer.exam\tple",
861            "https://ISSUER.example",
862            "HTTPS://issuer.example",
863            "https://issuer.example.",
864            "https://issuer.example:443",
865            "https://%69ssuer.example",
866            "https://\u{ff49}ssuer.example",
867            "https://m\u{fc}nchen.example",
868            // Not an `https` URL at all.
869            "http://issuer.example",
870            "issuer.example",
871            "did:web:issuer.example",
872            "",
873        ] {
874            assert!(!named.binds(unbound), "{unbound:?}");
875        }
876        // An IP address written as a DNS name binds no way of writing that address.
877        let address = certificate(&["192.168.1.1"], &[], None);
878        for unbound in [
879            "https://192.168.1.1",
880            "https://0xc0.0xa8.1.1",
881            "https://3232235777",
882        ] {
883            assert!(!address.binds(unbound), "{unbound}");
884        }
885        // Wildcards bind nothing, and neither does an empty name.
886        let wild = certificate(&["*.issuer.example", "*", ""], &[], None);
887        for unbound in [
888            "https://a.issuer.example",
889            "https://*.issuer.example",
890            "https://",
891        ] {
892            assert!(!wild.binds(unbound), "{unbound}");
893        }
894    }
895
896    /// A URI name binds nothing: name constraints on DNS names do not reach it. An `https`
897    /// URL the certificate also has as a URI name is bound by the DNS name of its host alone.
898    #[test]
899    fn uri_names_bind_nothing() {
900        let uris = [
901            "https://victim.example",
902            "did:web:victim.example",
903            "https://issuer.example/tenant",
904            "",
905        ];
906        let without_dns_names = certificate(&[], &uris, None);
907        for uri in uris {
908            assert!(!without_dns_names.binds(uri), "{uri:?}");
909        }
910        let with_dns_name = certificate(&["issuer.example"], &uris, None);
911        assert!(with_dns_name.binds("https://issuer.example/tenant"));
912        for unbound in ["https://victim.example", "did:web:victim.example", ""] {
913            assert!(!with_dns_name.binds(unbound), "{unbound:?}");
914        }
915    }
916
917    /// RFC 5280 §4.2.1.3: `digitalSignature` and `nonRepudiation` are for signatures "other
918    /// than signatures on certificates", `keyCertSign` for those on certificates.
919    #[test]
920    fn key_usage_decides_what_a_key_signs() {
921        let usage = |digital_signature, non_repudiation, key_cert_sign| {
922            Some(Usage {
923                digital_signature,
924                non_repudiation,
925                key_cert_sign,
926            })
927        };
928        let leaf = |usage| certificate(&[], &[], usage);
929        for signs in [
930            None,
931            usage(true, false, false),
932            usage(false, true, false),
933            usage(true, true, false),
934        ] {
935            assert!(leaf(signs).may_sign_tokens(), "{signs:?}");
936        }
937        for refused in [
938            usage(false, false, false),
939            usage(true, false, true),
940            usage(false, true, true),
941            usage(false, false, true),
942        ] {
943            assert!(!leaf(refused).may_sign_tokens(), "{refused:?}");
944        }
945
946        let ca = |usage| X509Certificate {
947            ca: true,
948            ..certificate(&[], &[], usage)
949        };
950        assert!(ca(None).may_issue());
951        assert!(ca(usage(false, false, true)).may_issue());
952        assert!(ca(usage(true, false, true)).may_issue());
953        assert!(!ca(usage(true, false, false)).may_issue());
954        // Without `cA`, `keyCertSign` is not enough.
955        assert!(!leaf(usage(false, false, true)).may_issue());
956        assert!(!leaf(None).may_issue());
957    }
958
959    #[test]
960    fn p384_points_are_uncompressed() {
961        let mut point = vec![0x04];
962        point.extend([0x11; 48]);
963        point.extend([0x22; 48]);
964        let jwk = serde_json::to_value(p384_jwk(&point).unwrap()).unwrap();
965        assert_eq!(jwk["crv"], "P-384");
966        assert_eq!(
967            base64url::decode(jwk["x"].as_str().unwrap()).unwrap(),
968            [0x11; 48]
969        );
970        assert_eq!(
971            base64url::decode(jwk["y"].as_str().unwrap()).unwrap(),
972            [0x22; 48]
973        );
974        // Compressed, truncated, or empty.
975        let mut compressed = vec![0x02];
976        compressed.extend([0x11; 48]);
977        for invalid in [&compressed[..], &point[..96], &[]] {
978            assert!(matches!(p384_jwk(invalid), Err(X509Error::InvalidKey(_))));
979        }
980    }
981}