Skip to main content

pkix_path/
lib.rs

1#![cfg_attr(not(feature = "std"), no_std)]
2#![cfg_attr(docsrs, feature(doc_cfg))]
3#![forbid(unsafe_code)]
4#![warn(missing_docs, rust_2018_idioms)]
5// Documentation links to `DefaultVerifier`, which needs at least one
6// signature backend enabled. With none of them the item does not exist,
7// so the link cannot resolve and `cargo doc` on a consumer's own
8// feature selection reports an error.
9//
10// Allowing the lint only where it cannot tell a gated item from a
11// mistake loses no signal: a mistyped link is broken with every feature
12// enabled too, and the all-features doc build is what the quality gate
13// runs under RUSTDOCFLAGS=-D warnings. Demoting the links to code spans
14// instead would cost every docs.rs reader a working link, to spare a
15// configuration nobody publishes documentation from.
16// `RsaPssVerifier` and `RsaPkcs1v15Sha1Verifier` are gated on `rsa`,
17// and `rsa` is itself one of the features that brings `DefaultVerifier`
18// into existence — so every link in this crate's docs resolves exactly
19// when `rsa` is on, and the five-feature condition this replaced was
20// both wider than needed and, for a single-signature-feature build like
21// `--features p256`, not wide enough.
22#![cfg_attr(not(feature = "rsa"), allow(rustdoc::broken_intra_doc_links))]
23//! RFC 5280 X.509 certificate path validation — pure Rust, `no_std`.
24//!
25//! Implements certificate path building and validation per
26//! [RFC 5280 §6](https://www.rfc-editor.org/rfc/rfc5280#section-6).
27//!
28//! # Architecture
29//!
30//! Cryptographic signature verification is pluggable via [`SignatureVerifier`].
31//! The default feature set wires in `RustCrypto` backends for RSA
32//! (PKCS#1 v1.5 and RSASSA-PSS with SHA-256/384/512; `rsa` feature) and
33//! ECDSA on P-256 (`p256` feature). The optional `p384`, `p521` and
34//! `ed25519` features add ECDSA on P-384 and P-521 and Ed25519;
35//! `rustcrypto` enables all of them. [`DefaultVerifier`] dispatches over
36//! whatever is enabled, taking the ECDSA curve from the issuer's key.
37//! For FIPS-validated crypto, implement [`SignatureVerifier`] against
38//! `wolfcrypt-rustcrypto` and disable the `rustcrypto` feature.
39//!
40//! Revocation checking is handled by `pkix-revocation`. This crate never
41//! touches the network — use `pkix_chain::verify_chain` for the combined API.
42//!
43//! # Limitations
44//!
45//! The following are **not** currently implemented:
46//! - **`UTCTime` before 1970.** The supported range is **1970-2049**,
47//!   where RFC 5280 §4.1.2.5.1 allows 1950-2049. A certificate whose
48//!   `notBefore` or `notAfter` falls in the missing twenty years is
49//!   refused, and refused at the DER layer — the error reads "malformed
50//!   ASN.1 DER value for UTCTime" and comes back before validation runs.
51//!
52//!   This is a deliberate scope decision, not an accident. The floor is
53//!   the Unix epoch because `der` 0.8 puts it there ("due to common
54//!   operations working on `UNIX_EPOCH`, `UtcTime`s are only supported
55//!   for the years 1970-2049"), and lifting it would mean forking the DER
56//!   layer every consumer of this crate depends on. No conforming CA
57//!   issues certificates dated before 1970, so the trade is a fork of a
58//!   foundational dependency against twenty years of dates nobody uses.
59//!
60//!   It is fail-closed: such a certificate is refused, never misread.
61//!   OpenSSL does read them, so expect a genuine disagreement rather than
62//!   a difference of strictness — NIST PKITS §4.2.3 "Valid pre2000 UTC
63//!   notBefore Date Test3" is exactly this shape, and is the one PKITS
64//!   vector this crate does not evaluate.
65//! - **Legacy signature algorithms** — SHA-1 verifiers (RFC 8017, legacy)
66//!   are intentionally not shipped; deployments requiring legacy SHA-1
67//!   trust must implement [`SignatureVerifier`] themselves. RSA moduli
68//!   outside 1024–8192 bits are refused by the bundled RSA backend.
69//! - **RFC 4518 full Unicode NFKC DN normalization** — ASCII case-folding
70//!   plus insignificant-whitespace collapsing is applied. `BMPString` AVA
71//!   values are transcoded UCS-2-BE → UTF-8 and then compared via the same
72//!   ASCII-only normalization pipeline, so two AVAs that share Unicode
73//!   code points but differ only in DER string-type (e.g. `BMPString`
74//!   "Foo Co" vs `UTF8String` "Foo Co") compare equal. Full RFC 4518 prep
75//!   (NFKC, non-ASCII Unicode case fold, prohibit/bidi steps) is future
76//!   work tracked under `PKIX-l63j`; until it lands, two `BMPString` values
77//!   that contain the same Unicode code points but differ in canonical
78//!   decomposition (e.g. precomposed U+00E9 'é' vs decomposed U+0065 U+0301
79//!   'e'+ combining acute) compare unequal. `UniversalString` AVA values
80//!   are rejected by the `der` crate at parse time (tag 0x1C is not in
81//!   `der::Tag` in 0.7) and never reach the path validator. `TeletexString`
82//!   AVAs use raw DER byte comparison by policy — `pkix-path` deliberately
83//!   does not transcode T.61 to Unicode; see `any_to_str_bytes` rustdoc
84//!   for the rationale.
85//! - **Path building** — converting an unordered bag of certificates into a
86//!   validated chain is handled by `pkix-path-builder`. This crate validates
87//!   a caller-ordered `&[Certificate]` only.
88//! - **AIA fetching** — chains with missing intermediates are not
89//!   reassembled from `AuthorityInfoAccess` URIs here. Callers supply a
90//!   complete chain, or go through `pkix-chain`, which follows
91//!   `caIssuers` URIs via `pkix-aia` / `pkix-aia-http` (`PKIX-zkjb`).
92
93// For no_std builds, pull in the alloc crate explicitly so `alloc::` paths
94// and the `vec!` macro resolve. `#[macro_use]` re-exports alloc macros
95// (vec!, format!, etc.) into the crate root, making them available everywhere
96// without qualifying them as `alloc::vec!(...)`.
97#[cfg(not(feature = "std"))]
98#[macro_use]
99extern crate alloc;
100
101// Unified Vec import: alloc::vec::Vec in no_std, std::vec::Vec under std.
102// Both map to the same concrete type; this alias lets the rest of the file
103// write `Vec<_>` without cfg-gating every use site.
104#[cfg(not(feature = "std"))]
105use alloc::vec::Vec;
106#[cfg(feature = "std")]
107use std::vec::Vec;
108
109// Unified Cow import: same cfg-gate pattern as Vec. `Cow` is owned by
110// `alloc` but `std` re-exports it; we can't write `alloc::borrow::Cow`
111// unconditionally because `extern crate alloc` is gated to no_std mode.
112// Only the serde wire helper uses it (DN comparison is allocation-free).
113#[cfg(all(feature = "serde", not(feature = "std")))]
114use alloc::borrow::Cow;
115#[cfg(all(feature = "serde", feature = "std"))]
116use std::borrow::Cow;
117
118use der::Tagged;
119// Re-exported, not merely imported: both types appear in
120// `SignatureVerifier::verify_signature`'s signature, so an out-of-crate
121// implementor has to name them. Reachable only as `spki::...` they meant
122// reading this crate's source to discover the origin and taking a direct
123// dependency on a matching `spki` version to say it.
124pub use spki::{AlgorithmIdentifierRef, SubjectPublicKeyInfoRef};
125use x509_cert::Certificate;
126
127/// Helper module for format-adaptive serde serialization of DER-encodable
128/// types. Public so downstream crates (`pkix-chain`, `pkix-revocation`,
129/// `pkix-truststore`) can reuse the same wire form on their own result
130/// types without redefining the helpers.
131#[cfg(feature = "serde")]
132#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
133pub mod serde_der;
134
135mod policy_graph;
136mod verification_error;
137pub use verification_error::{VerificationError, VerificationErrorKind};
138
139mod verifiers;
140#[cfg(any(
141    feature = "p256",
142    feature = "p384",
143    feature = "p521",
144    feature = "rsa",
145    feature = "ed25519"
146))]
147pub use verifiers::DefaultVerifier;
148#[cfg(feature = "ecdsa-sha1")]
149#[cfg_attr(docsrs, doc(cfg(feature = "ecdsa-sha1")))]
150pub use verifiers::EcdsaP256Sha1Verifier;
151#[cfg(feature = "p256")]
152pub use verifiers::EcdsaP256Verifier;
153#[cfg(feature = "p384")]
154pub use verifiers::EcdsaP384Verifier;
155#[cfg(feature = "p521")]
156pub use verifiers::EcdsaP521Verifier;
157#[cfg(feature = "ed25519")]
158pub use verifiers::Ed25519Verifier;
159#[cfg(feature = "rsa-sha1")]
160#[cfg_attr(docsrs, doc(cfg(feature = "rsa-sha1")))]
161pub use verifiers::RsaPkcs1v15Sha1Verifier;
162#[cfg(feature = "rsa")]
163pub use verifiers::{
164    RsaPkcs1v15Sha256Verifier, RsaPkcs1v15Sha384Verifier, RsaPkcs1v15Sha512Verifier, RsaPssVerifier,
165};
166
167/// Re-exported for use with [`TrustAnchor::name_constraints`].
168pub use x509_cert::ext::pkix::constraints::name::NameConstraints;
169
170/// Private shorthand for the `GeneralSubtrees` type used throughout NC processing.
171type GeneralSubtrees = x509_cert::ext::pkix::constraints::name::GeneralSubtrees;
172
173/// Opaque wrapper around an underlying ASN.1 / DER error.
174///
175/// Carries a [`Display`] message identical to the wrapped `der::Error` so
176/// diagnostic output is preserved, but does not expose the underlying type
177/// in the public API. This insulates callers from semver-breaking changes
178/// in the `der` crate's error variants.
179///
180/// Construct via [`DerError::new`] (or implicitly via
181/// [`From<der::Error> for Error`]). Sibling workspace crates that wrap
182/// DER decoding failures in their own `Error` enums (`pkix-revocation`,
183/// `pkix-truststore`) call [`DerError::new`] directly.
184///
185/// # Serde wire form
186///
187/// When the `serde` feature is enabled, `DerError` (de)serializes via its
188/// `Display` message as a single `String` field. Because `der::Error` does
189/// not itself carry a textual message — its `Display` is derived from
190/// `der::ErrorKind` — round-trip is **lossy**: a deserialized `DerError`
191/// preserves the original `Display` output verbatim but its
192/// [`core::error::Error::source`] is `None` because the original
193/// `der::Error` value cannot be reconstructed from a free-form string.
194/// This trade is acceptable for diagnostic error types; the success type
195/// (`ValidatedPath`) round-trips losslessly because all its fields are
196/// canonically DER-encodable.
197///
198/// [`Display`]: core::fmt::Display
199#[derive(Clone, Debug)]
200pub struct DerError {
201    /// Original `der::Error` value, when available.
202    ///
203    /// Populated by [`DerError::new`] from a real `der::Error`. `None`
204    /// only when the `DerError` was reconstructed from serialized form;
205    /// in that case [`core::error::Error::source`] returns `None` and the
206    /// Display message is taken from the preserved [`Self::message`].
207    ///
208    /// Under `no_std` builds the `core::error::Error::source` impl is
209    /// not available, so this field is only read for its `Debug`
210    /// representation; `#[allow(dead_code)]` silences the lint in
211    /// that configuration.
212    #[cfg_attr(not(feature = "std"), allow(dead_code))]
213    inner: Option<der::Error>,
214    /// Cached Display rendering of `inner`, preserved across serde
215    /// round-trips so that the diagnostic message survives even when
216    /// `inner` cannot be reconstructed.
217    message: BoxStr,
218}
219
220// Hand-written `PartialEq` / `Eq` compare only the cached Display
221// message. Pre-refactor (tuple struct over `der::Error`) PartialEq was
222// structural over `der::Error`'s `{kind, position}` fields; two
223// `der::Error`s with identical `{kind, position}` always produce
224// identical Display output, so comparing on `message` preserves the
225// pre-refactor equality verdicts in practice. This also makes serde
226// round-trip preserve `Eq` even though deserialize drops the `inner`
227// field (it cannot be reconstructed from the rendered message).
228impl PartialEq for DerError {
229    fn eq(&self, other: &Self) -> bool {
230        self.message == other.message
231    }
232}
233impl Eq for DerError {}
234
235/// Hashes `message`, the one field [`PartialEq`] compares.
236///
237/// That correspondence is the whole argument for correctness: `Hash`
238/// requires that equal values hash equally, and since equality here is
239/// defined solely by `message`, hashing solely `message` cannot violate
240/// it. Hashing `inner` as well would break the contract, because
241/// `inner` is dropped on a serde round-trip while equality is preserved
242/// — two equal values would then hash differently.
243///
244/// Written out rather than derived for that reason: a derive would
245/// include `inner`.
246///
247/// This exists so [`Error`] can derive `Hash`. `Der(DerError)` was the
248/// only variant standing in the way, which in turn is why
249/// `pkix_path_builder::Error::NoValidPath` stores its inner error as a
250/// rendered `String` — the builder's own enum derives `Hash` and could
251/// not hold a non-`Hash` field. That storage choice is now a semver
252/// question rather than a technical obstacle.
253impl core::hash::Hash for DerError {
254    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
255        self.message.hash(state);
256    }
257}
258
259// Internal: use a Box<str> so the struct is `Clone` cheaply and we keep
260// the heap allocation small. A type alias keeps the `#[cfg(not(feature
261// = "std"))]` use-statements in the rest of the file unchanged. Defined
262// here to localise the no_std-vs-std import.
263#[cfg(not(feature = "std"))]
264type BoxStr = alloc::boxed::Box<str>;
265#[cfg(feature = "std")]
266type BoxStr = std::boxed::Box<str>;
267
268impl DerError {
269    /// Construct a `DerError` from a real `der::Error`.
270    ///
271    /// The original `der::Error` is preserved internally so
272    /// [`core::error::Error::source`] returns it; the rendered
273    /// `Display` message is cached so the diagnostic survives serde
274    /// round-trips. See the type-level rustdoc for the round-trip
275    /// fidelity contract.
276    ///
277    /// Exposed to permit sibling workspace crates (`pkix-revocation`,
278    /// `pkix-truststore`) to construct their own `Error::Der`-equivalent
279    /// variants from `der::Error` results without going through the
280    /// `pkix_path::Error::from(der::Error)` conversion (which would
281    /// produce a `pkix_path::Error`, not the sibling crate's `Error`).
282    #[must_use]
283    pub fn new(e: der::Error) -> Self {
284        // Pre-render the Display message so it survives serde round-trips
285        // even when `inner` cannot be reconstructed on the deserialize side.
286        #[cfg(feature = "std")]
287        let message = e.to_string().into_boxed_str();
288        #[cfg(not(feature = "std"))]
289        let message = {
290            use core::fmt::Write as _;
291            let mut s = alloc::string::String::new();
292            // Display on der::Error is infallible (uses core::fmt::Result
293            // = (), no I/O); write! against a String returns Ok unless
294            // allocation fails.
295            let _ = write!(&mut s, "{}", e);
296            s.into_boxed_str()
297        };
298        Self {
299            inner: Some(e),
300            message,
301        }
302    }
303}
304
305impl core::fmt::Display for DerError {
306    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
307        f.write_str(&self.message)
308    }
309}
310
311impl core::error::Error for DerError {
312    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
313        self.inner.as_ref().map(|e| e as &dyn core::error::Error)
314    }
315}
316
317#[cfg(feature = "serde")]
318#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
319const _: () = {
320    use serde::{Deserializer, Serializer};
321
322    // Local helper struct that carries only the message; both branches
323    // of the serde impl re-use the same field-name shape so wire form
324    // is stable between encoder and decoder.
325    #[derive(serde::Serialize, serde::Deserialize)]
326    struct Wire<'a> {
327        // Use Cow to avoid allocating on the serialize side. The
328        // deserialize side always owns the recovered String.
329        #[serde(borrow)]
330        message: Cow<'a, str>,
331    }
332
333    impl serde::Serialize for DerError {
334        fn serialize<S: Serializer>(&self, s: S) -> core::result::Result<S::Ok, S::Error> {
335            Wire {
336                message: Cow::Borrowed(&self.message),
337            }
338            .serialize(s)
339        }
340    }
341
342    impl<'de> serde::Deserialize<'de> for DerError {
343        fn deserialize<D: Deserializer<'de>>(d: D) -> core::result::Result<Self, D::Error> {
344            let Wire { message } = Wire::deserialize(d)?;
345            Ok(Self {
346                inner: None,
347                message: message.into_owned().into_boxed_str(),
348            })
349        }
350    }
351};
352
353/// Errors returned by path validation.
354#[derive(Clone, Debug, PartialEq, Eq, Hash)]
355#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
356#[non_exhaustive]
357pub enum Error {
358    /// Certificate signature verification failed at the given chain index:
359    /// the signature does not verify, or is not a well-formed signature
360    /// value ([`VerificationErrorKind::InvalidSignature`]).
361    SignatureInvalid {
362        /// Zero-based index into the `chain` slice of the failing certificate.
363        index: usize,
364    },
365    /// The certificate's signature could not be checked at the given chain
366    /// index: the [`SignatureVerifier`] does not support its algorithm or
367    /// the issuer's key, or the issuer's key is malformed. `reason` says
368    /// which; it is never [`VerificationErrorKind::InvalidSignature`].
369    SignatureNotVerified {
370        /// Zero-based index into the `chain` slice of the certificate.
371        index: usize,
372        /// Why the verifier could not check the signature.
373        reason: VerificationErrorKind,
374    },
375    /// A structural encoding error was found in a certificate.
376    ///
377    /// Returned when the outer `signatureAlgorithm` OID differs from the
378    /// inner `TBSCertificate.signature` OID (RFC 5280 §4.1.1.2; parameters
379    /// are not compared, see `check_oid_consistency` for rationale), when a
380    /// certificate carries more than one instance of an extension (RFC 5280
381    /// §4.2), and when a security-relevant extension fails to decode.
382    MalformedCertificate {
383        /// Zero-based index into the `chain` slice of the malformed certificate.
384        ///
385        /// The underlying `der::Error` is intentionally not stored here to keep
386        /// this variant `no_std`-compatible and to preserve the stable API shape.
387        /// Callers that need the root-cause parse error should validate the
388        /// DER certificate independently before calling [`validate_path`].
389        index: usize,
390    },
391    /// Certificate validity period check failed (expired or not yet valid).
392    ValidityPeriod {
393        /// Zero-based index into the `chain` slice of the failing certificate.
394        index: usize,
395    },
396    /// Issuer/subject name linkage is broken at the given chain index.
397    ChainBroken {
398        /// Zero-based index into the `chain` slice where the break was found.
399        index: usize,
400    },
401    /// No path from the subject certificate to any trust anchor was found.
402    NoTrustedPath,
403    /// Path length exceeds [`ValidationPolicy::max_path_len`].
404    PathTooLong,
405    /// An intermediate certificate is missing `BasicConstraints` `cA=TRUE`.
406    NotCA {
407        /// Zero-based index into the `chain` slice of the failing certificate.
408        index: usize,
409    },
410    /// An intermediate certificate has a `KeyUsage` extension with `keyCertSign` not set.
411    ///
412    /// This error is only returned when a `KeyUsage` extension is **present** and the
413    /// `keyCertSign` bit is explicitly absent or zero (RFC 5280 §6.1.4(n): "If a `KeyUsage`
414    /// extension is present, verify that the keyCertSign bit is set.").
415    ///
416    /// Certificates with **no** `KeyUsage` extension are not rejected by this check;
417    /// RFC 5280 does not require the extension to be present on CA certificates.
418    KeyUsageMissing {
419        /// Zero-based index into the `chain` slice of the failing certificate.
420        index: usize,
421    },
422    /// An intermediate certificate has a `KeyUsage` extension with `cRLSign` not set.
423    ///
424    /// This error is only returned when
425    /// [`ValidationPolicy::require_crl_sign_on_cas`] is `true` **and** the
426    /// intermediate's `KeyUsage` extension is **present** with the `cRLSign` bit
427    /// explicitly absent or zero. Certificates with **no** `KeyUsage` extension
428    /// are not rejected by this check (RFC 5280 does not require the extension
429    /// to be present on CA certificates).
430    ///
431    /// RFC 5280 §6.1 does not mandate this check; it is an opt-in policy that
432    /// restores PKITS §4.7.4 / §4.7.5 conformance for callers who treat a CA
433    /// cert without `cRLSign` as non-issuable. Default is off.
434    ///
435    /// **Disambiguation:** [`pkix_revocation::Error::CrlSignMissing`] (same
436    /// variant name, different crate) fires during CRL verification when the
437    /// CRL *signer* cert lacks `cRLSign` (RFC 5280 §6.3.3(f)). This variant
438    /// fires during *path validation* when an intermediate CA cert in the
439    /// chain lacks `cRLSign` and the caller opted into the policy check.
440    ///
441    /// [`pkix_revocation::Error::CrlSignMissing`]: https://docs.rs/pkix-revocation/latest/pkix_revocation/enum.Error.html#variant.CrlSignMissing
442    CrlSignMissing {
443        /// Zero-based index into the `chain` slice of the failing certificate.
444        index: usize,
445    },
446    /// A critical extension is present that this implementation does not handle.
447    UnhandledCriticalExtension {
448        /// Zero-based index into the `chain` slice of the failing certificate.
449        index: usize,
450    },
451    /// Certificate name constraints violated (RFC 5280 §4.2.1.10); `index` is the 0-based chain position.
452    ///
453    /// Also returned when a constraint is in effect for a name the validator
454    /// cannot evaluate: a URI without an authority or with an IP-address
455    /// host, a name of an unsupported form (`otherName`, `ediPartyName`,
456    /// `registeredID`) under a constraint of that form, a non-IA5String
457    /// subject `emailAddress`, or a `SmtpUTF8Mailbox` whose domain is not
458    /// ASCII.
459    NameConstraintViolation {
460        /// Zero-based index into the `chain` slice of the failing certificate.
461        index: usize,
462    },
463    /// Certificate policy validation failed (RFC 5280 §6.1.5(g)).
464    ///
465    /// Returned when `explicit_policy` reaches zero and the valid policy tree
466    /// is empty, meaning no acceptable certificate policy exists for the chain.
467    PolicyViolation {
468        /// Zero-based index of the certificate where the violation was detected.
469        index: usize,
470    },
471    /// ASN.1 / DER encoding or decoding error.
472    ///
473    /// Returned when a structural encoding error is found in a certificate or
474    /// when re-encoding `TBSCertificate` for signature verification fails.
475    /// Signature verification now uses heap-allocated encoding (no fixed size
476    /// limit), so this error reflects a genuine DER encoding defect in the
477    /// certificate, not an implementation size constraint.
478    ///
479    /// The inner [`DerError`] is an opaque newtype; the underlying `der::Error`
480    /// is intentionally not exposed so a future major-version bump in the
481    /// `der` crate cannot cascade into a semver break here.
482    Der(DerError),
483    /// A certificate's validity period (notAfter − notBefore) exceeds
484    /// [`ValidationPolicy::max_validity_secs`].
485    ///
486    /// This check fires for every certificate in the chain, not just the leaf.
487    ValidityPeriodExceedsMax {
488        /// Zero-based index into the `chain` slice of the failing certificate.
489        index: usize,
490    },
491    /// A certificate's signature algorithm OID is not in
492    /// [`ValidationPolicy::allowed_signature_algs`].
493    ///
494    /// The check fires before signature verification so the error is diagnostic
495    /// rather than a confusing `SignatureInvalid`.
496    AlgorithmNotAllowed {
497        /// Zero-based index into the `chain` slice of the failing certificate.
498        index: usize,
499    },
500    /// An RSA public key's modulus is smaller than
501    /// [`ValidationPolicy::min_rsa_key_bits`] bits.
502    ///
503    /// Non-RSA keys (EC, Ed25519, …) are not affected by this check.
504    KeyTooSmall {
505        /// Zero-based index into the `chain` slice of the failing certificate.
506        index: usize,
507    },
508    /// The leaf certificate (chain index 0) has no `SubjectAltName` extension,
509    /// or the extension is present but empty.
510    ///
511    /// Only checked when [`ValidationPolicy::require_subject_alt_name`] is `true`.
512    /// Intermediate CA certificates are not subject to this check.
513    MissingSan,
514    /// The leaf certificate (chain index 0) has a `SubjectAltName` extension but
515    /// none of its entries is an `rfc822Name` (email address).
516    ///
517    /// Only checked when [`ValidationPolicy::require_rfc822_san`] is `true`.
518    /// Intermediate CA certificates are not subject to this check.
519    MissingRfc822San,
520    /// The leaf certificate (chain index 0) does not assert all OIDs required
521    /// by [`ValidationPolicy::required_leaf_eku`].
522    ///
523    /// `anyExtendedKeyUsage` (2.5.29.37.0) does not satisfy a specific OID
524    /// requirement — each required OID must be listed explicitly.
525    MissingEku,
526    /// The leaf certificate's `CertificatePolicies` extension does not assert
527    /// a required policy OID from
528    /// [`ValidationPolicy::required_leaf_policy_oids`].
529    ///
530    /// `anyPolicy` (2.5.29.32.0) does not satisfy a specific OID requirement;
531    /// each required OID must be listed explicitly in the leaf's
532    /// `CertificatePolicies` extension.
533    ///
534    /// Distinct from [`Error::PolicyViolation`], which signals failure of the
535    /// RFC 5280 §6.1 policy tree (`initial_policy_set` /
536    /// `initial_explicit_policy`). `MissingLeafPolicyOid` signals a leaf-only
537    /// assertion check that is independent of the policy tree.
538    MissingLeafPolicyOid {
539        /// The required policy OID that the leaf does not assert.
540        #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
541        required: der::asn1::ObjectIdentifier,
542    },
543    /// The leaf certificate's Subject DN does not satisfy
544    /// [`ValidationPolicy::required_leaf_subject_dn_attrs`].
545    ///
546    /// This variant carries no payload; richer "which branch of the rule
547    /// failed" diagnostics are a non-breaking follow-up.
548    SubjectDnAttrRuleUnmet,
549    /// Two certificates in the chain share the same `(issuer DN, serial number)`.
550    ///
551    /// Per RFC 5280 §4.1.2.2, the combination of issuer DN and serial number
552    /// uniquely identifies a certificate. A cert appearing twice at different
553    /// chain positions is a construction error. Returned as a diagnostic rather
554    /// than a confusing [`Error::SignatureInvalid`] or [`Error::ChainBroken`].
555    ///
556    /// Note: two certificates with the same public key but different
557    /// issuer+serial are *distinct* certificates (e.g. cross-signed CAs) and
558    /// are **not** rejected by this check.
559    ///
560    /// `first` and `second` are the zero-based chain indices of the two duplicates.
561    DuplicateCertificate {
562        /// First occurrence index.
563        first: usize,
564        /// Second occurrence index.
565        second: usize,
566    },
567}
568
569impl core::fmt::Display for Error {
570    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
571        match self {
572            Self::SignatureInvalid { index } => {
573                write!(f, "signature invalid at chain index {index}")
574            }
575            Self::SignatureNotVerified { index, reason } => {
576                write!(f, "signature not verified at chain index {index}: {reason}")
577            }
578            Self::ValidityPeriod { index } => {
579                write!(f, "validity period check failed at chain index {index}")
580            }
581            Self::MalformedCertificate { index } => {
582                write!(f, "malformed certificate at chain index {index}")
583            }
584            Self::ChainBroken { index } => {
585                write!(f, "issuer/subject linkage broken at chain index {index}")
586            }
587            Self::NoTrustedPath => write!(f, "no path to a trusted anchor"),
588            Self::PathTooLong => write!(f, "path length exceeds maximum"),
589            Self::NotCA { index } => write!(f, "certificate at index {index} is not a CA"),
590            Self::KeyUsageMissing { index } => {
591                write!(f, "keyCertSign missing at chain index {index}")
592            }
593            Self::CrlSignMissing { index } => {
594                write!(f, "cRLSign missing at chain index {index}")
595            }
596            Self::UnhandledCriticalExtension { index } => {
597                write!(f, "unhandled critical extension at chain index {index}")
598            }
599            Self::NameConstraintViolation { index } => {
600                write!(f, "name constraints violated at certificate index {index}")
601            }
602            Self::PolicyViolation { index } => {
603                write!(f, "certificate policy violation at chain index {index}")
604            }
605            Self::Der(e) => write!(f, "DER error: {e}"),
606            Self::ValidityPeriodExceedsMax { index } => {
607                write!(f, "validity period exceeds maximum at chain index {index}")
608            }
609            Self::AlgorithmNotAllowed { index } => {
610                write!(f, "signature algorithm not allowed at chain index {index}")
611            }
612            Self::KeyTooSmall { index } => {
613                write!(f, "RSA key too small at chain index {index}")
614            }
615            Self::MissingSan => write!(f, "leaf certificate is missing SubjectAltName"),
616            Self::MissingRfc822San => write!(
617                f,
618                "leaf certificate SubjectAltName contains no rfc822Name entry"
619            ),
620            Self::MissingEku => {
621                write!(
622                    f,
623                    "leaf certificate is missing required ExtendedKeyUsage OID(s)"
624                )
625            }
626            Self::MissingLeafPolicyOid { required } => {
627                write!(
628                    f,
629                    "leaf certificate is missing required CertificatePolicies OID {required}"
630                )
631            }
632            Self::SubjectDnAttrRuleUnmet => {
633                write!(
634                    f,
635                    "leaf certificate Subject DN does not satisfy the required attribute rule"
636                )
637            }
638            Self::DuplicateCertificate { first, second } => {
639                write!(
640                    f,
641                    "duplicate certificate (issuer+serial) at chain indices {first} and {second}"
642                )
643            }
644        }
645    }
646}
647
648impl core::error::Error for Error {
649    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
650        match self {
651            Self::Der(e) => Some(e),
652            Self::SignatureInvalid { .. }
653            | Self::SignatureNotVerified { .. }
654            | Self::MalformedCertificate { .. }
655            | Self::ValidityPeriod { .. }
656            | Self::ChainBroken { .. }
657            | Self::NoTrustedPath
658            | Self::PathTooLong
659            | Self::NotCA { .. }
660            | Self::KeyUsageMissing { .. }
661            | Self::CrlSignMissing { .. }
662            | Self::UnhandledCriticalExtension { .. }
663            | Self::NameConstraintViolation { .. }
664            | Self::PolicyViolation { .. }
665            | Self::ValidityPeriodExceedsMax { .. }
666            | Self::AlgorithmNotAllowed { .. }
667            | Self::KeyTooSmall { .. }
668            | Self::MissingSan
669            | Self::MissingRfc822San
670            | Self::MissingEku
671            | Self::MissingLeafPolicyOid { .. }
672            | Self::SubjectDnAttrRuleUnmet
673            | Self::DuplicateCertificate { .. } => None,
674        }
675    }
676}
677
678impl From<der::Error> for Error {
679    fn from(e: der::Error) -> Self {
680        Self::Der(DerError::new(e))
681    }
682}
683
684/// Result alias for this crate.
685pub type Result<T> = core::result::Result<T, Error>;
686
687/// Pluggable signature verification backend.
688///
689/// Implement this trait to provide algorithm-specific signature verification.
690/// The trait is OID-dispatched: the `algorithm` argument carries the OID and
691/// any parameters from the certificate's `signatureAlgorithm` field.
692///
693/// This trait is object-safe and can be used as `dyn SignatureVerifier`.
694/// All method arguments are either `&self` or borrows, so no `Sized` bound
695/// is implied.
696///
697/// # Implementing a custom backend
698///
699/// ```rust,no_run
700/// use der::asn1::ObjectIdentifier;
701/// const MY_RSA_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.11");
702/// const MY_ECDSA_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.2");
703///
704/// struct MyVerifier;
705///
706/// impl pkix_path::SignatureVerifier for MyVerifier {
707///     fn verify_signature(
708///         &self,
709///         algorithm: spki::AlgorithmIdentifierRef<'_>,
710///         _issuer_spki: spki::SubjectPublicKeyInfoRef<'_>,
711///         _message: &[u8],
712///         _signature: &[u8],
713///     ) -> Result<(), pkix_path::VerificationError> {
714///         match algorithm.oid {
715///             MY_RSA_OID => { Ok(()) /* RSA verification */ }
716///             MY_ECDSA_OID => { Ok(()) /* ECDSA verification */ }
717///             _ => Err(pkix_path::VerificationError::unsupported_algorithm()),
718///         }
719///     }
720/// }
721/// ```
722pub trait SignatureVerifier {
723    /// Verify `signature` over `message`.
724    ///
725    /// - `algorithm`    — from the subject cert's `signatureAlgorithm` field
726    /// - `issuer_spki`  — SPKI extracted from the issuer or trust anchor cert
727    /// - `message`      — DER-encoded `TBSCertificate` (the bytes that were signed)
728    /// - `signature`    — raw signature bytes (`BitString` content, not the wrapper)
729    ///
730    /// Returns `Ok(())` when the signature verifies. The caller
731    /// ([`validate_path`]) adds the chain index: an error of kind
732    /// [`VerificationErrorKind::InvalidSignature`] becomes
733    /// [`Error::SignatureInvalid`], any other kind
734    /// [`Error::SignatureNotVerified`] — the verifier does not need to know
735    /// the index.
736    ///
737    /// # Errors
738    ///
739    /// Returns a [`VerificationError`] whose kind says why the signature
740    /// was not accepted: the algorithm is not supported
741    /// ([`UnsupportedAlgorithm`](VerificationErrorKind::UnsupportedAlgorithm)),
742    /// the issuer key is unsupported or does not fit the algorithm
743    /// ([`UnsupportedKey`](VerificationErrorKind::UnsupportedKey)) or does
744    /// not decode ([`MalformedKey`](VerificationErrorKind::MalformedKey)),
745    /// or the signature is malformed or does not verify
746    /// ([`InvalidSignature`](VerificationErrorKind::InvalidSignature)).
747    fn verify_signature(
748        &self,
749        algorithm: AlgorithmIdentifierRef<'_>,
750        issuer_spki: SubjectPublicKeyInfoRef<'_>,
751        message: &[u8],
752        signature: &[u8],
753    ) -> core::result::Result<(), VerificationError>;
754}
755
756/// Forwarding impl so a shared reference to a verifier is itself a
757/// verifier.
758///
759/// This is what makes a verifier that cannot be `Clone` usable.
760/// [`crate::validate_path`] and the `CrlChecker` / `OcspChecker` types in
761/// `pkix-revocation` take a verifier by value and require `Clone`, since
762/// they hold it and may be cloned themselves. A verifier that owns a
763/// hardware token handle, an open session, or anything else not
764/// duplicable therefore could not be used at all.
765///
766/// With this impl it can: pass `&verifier` and the type parameter
767/// becomes `&V`, which is `Copy`, so the `Clone` bound is satisfied for
768/// free and nothing is duplicated. The borrow is the only cost, and it
769/// is what a scoped validation wants anyway.
770///
771/// For a verifier shared by something outliving a borrow — a fetcher
772/// held for the life of a process — use the `Arc` impl below instead.
773impl<T: SignatureVerifier + ?Sized> SignatureVerifier for &T {
774    fn verify_signature(
775        &self,
776        algorithm: AlgorithmIdentifierRef<'_>,
777        issuer_spki: SubjectPublicKeyInfoRef<'_>,
778        message: &[u8],
779        signature: &[u8],
780    ) -> core::result::Result<(), VerificationError> {
781        (**self).verify_signature(algorithm, issuer_spki, message, signature)
782    }
783}
784
785/// Forwarding impl so an `Arc`-shared verifier is itself a verifier.
786///
787/// The owned counterpart to the `&T` impl above, for a verifier that has
788/// to outlive any particular borrow. `Arc<V>` is `Clone` whatever `V` is,
789/// and cloning it is a refcount bump rather than a duplication of
790/// whatever the verifier holds.
791///
792/// # Why this is gated on `std`
793///
794/// `Arc` lives in `alloc::sync`, which exists only on targets with
795/// atomic compare-and-swap. Implementing it unconditionally would make
796/// this crate stop compiling for a `no_std` target without atomics
797/// (`thumbv6m-none-eabi`, for instance) in exchange for a convenience.
798/// Under `std` those atomics are guaranteed, so the impl is free there.
799/// A `no_std` consumer that does have atomics and wants this shape can
800/// write the same four-line forwarding impl over its own newtype.
801#[cfg(feature = "std")]
802#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
803impl<T: SignatureVerifier + ?Sized> SignatureVerifier for std::sync::Arc<T> {
804    fn verify_signature(
805        &self,
806        algorithm: AlgorithmIdentifierRef<'_>,
807        issuer_spki: SubjectPublicKeyInfoRef<'_>,
808        message: &[u8],
809        signature: &[u8],
810    ) -> core::result::Result<(), VerificationError> {
811        (**self).verify_signature(algorithm, issuer_spki, message, signature)
812    }
813}
814
815/// A trust anchor used to terminate path validation.
816///
817/// A trust anchor is typically either a self-signed root CA certificate
818/// or a raw (name, SPKI) pair extracted from a platform trust store.
819/// The trust anchor itself is **not** signature-verified — it is trusted
820/// by definition (RFC 5280 §6.1.1(c)).
821///
822/// **Validity period**: RFC 5280 §6.1.1(c) explicitly excludes the trust
823/// anchor's notBefore/notAfter from path validation. An expired root CA
824/// certificate used as a trust anchor will still anchor valid paths — this
825/// is intentional behavior, not a bug. Callers are responsible for ensuring
826/// their trust store contains the anchors they intend to trust.
827///
828/// **`PartialEq` is byte-level, not semantic**: The derived `PartialEq`
829/// compares fields verbatim. Two anchors representing the same CA may compare
830/// unequal if their DER encodings differ — for example, one `AlgorithmIdentifier`
831/// with explicit `NULL` parameters and another with absent parameters are both
832/// valid for RSA (RFC 3279 §2.3.1) but will not be equal under `==`. Do not use
833/// `==` to deduplicate a trust store; use [`names_match`] and compare
834/// `algorithm.oid` plus `subject_public_key` bytes directly. Path validation
835/// already handles this internally, so it is not affected by this encoding difference.
836///
837/// # Stability
838///
839/// `TrustAnchor` is `#[non_exhaustive]`: new fields may be added in minor
840/// versions. Construct via [`TrustAnchor::new`], [`TrustAnchor::from_cert`],
841/// or `TrustAnchor::from`/`try_from`. Do not use struct literal syntax.
842#[derive(Clone, Debug, PartialEq, Eq)]
843#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
844#[non_exhaustive]
845pub struct TrustAnchor {
846    /// The subject distinguished name of the trust anchor.
847    #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
848    pub subject: x509_cert::name::Name,
849    /// The subject public key info of the trust anchor.
850    ///
851    /// Must be a valid SPKI for the chosen signature algorithm. An empty or
852    /// malformed SPKI will cause signature verification to fail with
853    /// `Error::NoTrustedPath` (no anchor matched), not a panic.
854    #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
855    pub subject_public_key_info: spki::SubjectPublicKeyInfoOwned,
856    /// `NameConstraints` from the trust anchor certificate, if present.
857    ///
858    /// When set, `chain_walk` seeds the initial `permitted_subtrees` and
859    /// `excluded_subtrees` state from this value before walking the chain.
860    /// Populated automatically by `from_cert`; `None` for programmatically
861    /// constructed anchors unless explicitly set.
862    #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::option"))]
863    pub name_constraints: Option<x509_cert::ext::pkix::constraints::name::NameConstraints>,
864}
865
866impl TrustAnchor {
867    /// Create a trust anchor from raw subject name and SPKI.
868    #[must_use]
869    pub const fn new(
870        subject: x509_cert::name::Name,
871        subject_public_key_info: spki::SubjectPublicKeyInfoOwned,
872    ) -> Self {
873        Self {
874            subject,
875            subject_public_key_info,
876            name_constraints: None,
877        }
878    }
879
880    /// Extract subject name and SPKI from a certificate to create a trust anchor.
881    ///
882    /// This is the typical constructor when your trust store contains full
883    /// self-signed root CA certificates.
884    ///
885    /// Prefer [`TrustAnchor::from`] (i.e. `TrustAnchor::from(&cert)`) when you
886    /// need to keep `cert` alive after building the anchor.
887    ///
888    /// # Warning: malformed `NameConstraints` are silently dropped
889    ///
890    /// If the anchor certificate contains a malformed or unparseable
891    /// `NameConstraints` extension, `from_cert` silently sets
892    /// `name_constraints = None` and continues. **The resulting anchor
893    /// will not enforce any name-constraint restrictions from that
894    /// extension**, which may widen the trust scope beyond what the
895    /// certificate intended.
896    ///
897    /// For strict RFC 5280 §4.2 compliance — where a critical extension
898    /// that cannot be parsed MUST cause rejection — use
899    /// [`TrustAnchor::try_from`] instead. That path returns
900    /// `Err(`[`DerError`]`)` so the caller can reject the malformed anchor
901    /// rather than silently operating without name constraints.
902    ///
903    /// # A non-conformant `minimum`/`maximum` is kept, not dropped
904    ///
905    /// RFC 5280 §4.2.1.10 requires `minimum` to be zero and `maximum` to be
906    /// absent, and [`TrustAnchor::try_from`] rejects a certificate encoding
907    /// either. This constructor cannot: it is infallible, so its only
908    /// choices are to keep the subtree or to discard it.
909    ///
910    /// It keeps it, and the constraint is then enforced as though `minimum`
911    /// were zero — which applies it to *more* names than the issuer wrote,
912    /// never fewer. Discarding it would stop enforcing the constraint
913    /// altogether and widen the anchor's trust scope, so between two wrong
914    /// answers this is the conservative one. That makes it deliberately
915    /// unlike the malformed-DER case above, where there is no subtree to
916    /// apply and `None` is the only option.
917    ///
918    /// A caller who wants the certificate refused outright should use
919    /// [`TrustAnchor::try_from`].
920    #[must_use]
921    pub fn from_cert(cert: Certificate) -> Self {
922        let name_constraints = find_cert_ext(&cert, OID_NAME_CONSTRAINTS);
923        Self {
924            subject: cert.tbs_certificate().subject().clone(),
925            subject_public_key_info: cert.tbs_certificate().subject_public_key_info().clone(),
926            name_constraints,
927        }
928    }
929}
930
931impl From<&Certificate> for TrustAnchor {
932    fn from(cert: &Certificate) -> Self {
933        Self {
934            subject: cert.tbs_certificate().subject().clone(),
935            subject_public_key_info: cert.tbs_certificate().subject_public_key_info().clone(),
936            name_constraints: find_cert_ext(cert, OID_NAME_CONSTRAINTS),
937        }
938    }
939}
940
941/// Fail-closed construction from an owned certificate.
942///
943/// Returns `Err(`[`DerError`]`)` if the certificate contains a `NameConstraints`
944/// extension with malformed DER. Use this when building a trust store that
945/// must reject certificates with unparseable critical extensions per
946/// RFC 5280 §4.2.
947///
948/// The error type is the opaque [`DerError`] newtype rather than `der::Error`
949/// so that a future major-version bump in the `der` crate does not cascade
950/// into a semver break here.
951///
952/// # Why only `TryFrom<Certificate>` and not `TryFrom<&Certificate>`
953///
954/// `TryFrom<&Certificate>` would conflict with the blanket impl
955/// `impl<T, U: Into<T>> TryFrom<U>` provided by Rust core, because
956/// `From<&Certificate>` is already implemented (and `From` implies `Into`).
957/// Use `TrustAnchor::try_from(cert.clone())` if you need to keep `cert`.
958impl TryFrom<Certificate> for TrustAnchor {
959    type Error = DerError;
960
961    fn try_from(cert: Certificate) -> core::result::Result<Self, Self::Error> {
962        let name_constraints: Option<NameConstraints> =
963            try_find_cert_ext(&cert, OID_NAME_CONSTRAINTS).map_err(DerError::new)?;
964        // §4.2.1.10's minimum/maximum rule, which this constructor exists to
965        // enforce and did not. `cert_name_constraints` rejects an intermediate
966        // encoding either field; a strict trust store should not then accept
967        // the same extension on its anchor.
968        if name_constraints
969            .as_ref()
970            .is_some_and(|nc| !subtrees_are_conformant(nc))
971        {
972            return Err(DerError::new(der::Error::from(der::ErrorKind::Value {
973                tag: der::Tag::Integer,
974            })));
975        }
976        Ok(Self {
977            subject: cert.tbs_certificate().subject().clone(),
978            subject_public_key_info: cert.tbs_certificate().subject_public_key_info().clone(),
979            name_constraints,
980        })
981    }
982}
983
984/// Compositional rule for asserting required Subject DN attributes on a leaf cert.
985///
986/// Designed to express CA/B Forum S/MIME BR tier rules such as "must have
987/// `organizationName`" or "must have `pseudonym` OR (`givenName` AND
988/// `surname`)" without committing the workspace to a fixed list of attribute
989/// requirements.
990///
991/// The [`Field`][Self::Field] variant matches when the named OID appears at
992/// least once in the leaf's Subject DN RDN sequence (any RDN, any
993/// `AttributeTypeAndValue` within an RDN). [`AllOf`][Self::AllOf] and
994/// [`AnyOf`][Self::AnyOf] compose subordinate rules.
995///
996/// # Vacuity
997///
998/// - `AllOf(vec![])` accepts every Subject DN (vacuously true).
999/// - `AnyOf(vec![])` rejects every Subject DN (vacuously false).
1000///
1001/// Callers writing `AnyOf` should not pass an empty list unless that is the
1002/// intended semantics.
1003///
1004/// # Example
1005///
1006/// Express "Subject must have `pseudonym`, or both `givenName` and
1007/// `surname`":
1008///
1009/// ```rust
1010/// use pkix_path::DnAttrRule;
1011/// use der::asn1::ObjectIdentifier;
1012///
1013/// const PSEUDONYM:  ObjectIdentifier = ObjectIdentifier::new_unwrap("2.5.4.65");
1014/// const GIVEN_NAME: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.5.4.42");
1015/// const SURNAME:    ObjectIdentifier = ObjectIdentifier::new_unwrap("2.5.4.4");
1016///
1017/// let rule = DnAttrRule::AnyOf(vec![
1018///     DnAttrRule::Field(PSEUDONYM),
1019///     DnAttrRule::AllOf(vec![
1020///         DnAttrRule::Field(GIVEN_NAME),
1021///         DnAttrRule::Field(SURNAME),
1022///     ]),
1023/// ]);
1024/// # let _ = rule;
1025/// ```
1026#[non_exhaustive]
1027#[derive(Clone, Debug, PartialEq, Eq)]
1028#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1029pub enum DnAttrRule {
1030    /// Match when the named attribute OID appears at least once in the
1031    /// leaf's Subject DN.
1032    Field(
1033        #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
1034        der::asn1::ObjectIdentifier,
1035    ),
1036    /// Match when every subordinate rule matches. `AllOf(vec![])` is
1037    /// vacuously true.
1038    AllOf(Vec<DnAttrRule>),
1039    /// Match when at least one subordinate rule matches. `AnyOf(vec![])`
1040    /// is vacuously false.
1041    AnyOf(Vec<DnAttrRule>),
1042}
1043
1044/// Walk the Subject DN once and report whether the named OID appears in any
1045/// `AttributeTypeAndValue` within any `RelativeDistinguishedName`.
1046///
1047/// OID equality is exact byte-for-byte comparison; no aliasing or
1048/// canonicalization is performed.
1049fn dn_contains_oid(subject: &x509_cert::name::Name, oid: &der::asn1::ObjectIdentifier) -> bool {
1050    subject.iter().any(|ava| ava.oid == *oid)
1051}
1052
1053/// Evaluate a [`DnAttrRule`] against a Subject DN, returning `true` when the
1054/// rule is satisfied.
1055fn evaluate_dn_attr_rule(subject: &x509_cert::name::Name, rule: &DnAttrRule) -> bool {
1056    match rule {
1057        DnAttrRule::Field(oid) => dn_contains_oid(subject, oid),
1058        DnAttrRule::AllOf(rules) => rules.iter().all(|r| evaluate_dn_attr_rule(subject, r)),
1059        DnAttrRule::AnyOf(rules) => rules.iter().any(|r| evaluate_dn_attr_rule(subject, r)),
1060    }
1061}
1062
1063/// Policy parameters controlling path validation.
1064///
1065/// # Stability
1066///
1067/// `ValidationPolicy` is `#[non_exhaustive]`.
1068/// Construct via [`ValidationPolicy::new`] or [`Default`] + field assignment.
1069/// Do not use struct literal syntax.
1070///
1071/// # Performance note
1072///
1073/// Policy objects are intended to be constructed once (e.g., at server startup)
1074/// and reused for the lifetime of the application. Repeated construction is
1075/// unnecessary.
1076///
1077/// Policy enforcement (`CertificatePolicies`, `PolicyMappings`, `PolicyConstraints`,
1078/// `InhibitAnyPolicy`) is implemented per RFC 5280 §6.1. Use the
1079/// `initial_explicit_policy`, `initial_any_policy_inhibit`,
1080/// `initial_policy_mapping_inhibit`, and `initial_policy_set` fields to
1081/// configure the initial policy state.
1082///
1083/// # Limitations
1084///
1085/// Path-building (RFC 4158 — cross-signed certificates, multiple candidate
1086/// issuers) is **out of scope** for this crate. The caller must supply the
1087/// complete, ordered chain (see `pkix-path-builder` for path discovery).
1088///
1089/// Revocation checking (CRL / OCSP) is out of scope for `pkix-path`; see
1090/// `pkix-revocation` for that functionality.
1091// `clippy::struct_excessive_bools` would prefer enum-typed groupings here,
1092// but the bools map directly to RFC 5280 §6.1.1 named inputs
1093// (`initial-explicit-policy`, `initial-any-policy-inhibit`,
1094// `initial-policy-mapping-inhibit`) and to the SAN-presence and
1095// EKU-presence policy gates. Substituting an enum cluster would obscure the
1096// 1:1 mapping to the spec text and force callers through a pattern-match
1097// adapter for each field. The current shape is the most direct expression
1098// of the spec inputs.
1099#[allow(clippy::struct_excessive_bools)]
1100#[non_exhaustive]
1101#[derive(Clone, Debug, PartialEq, Eq)]
1102#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1103pub struct ValidationPolicy {
1104    /// Maximum chain depth, not counting the trust anchor. Default: 10.
1105    ///
1106    /// A chain of `[leaf]` is depth 0. `[leaf, intermediate, root]` is depth 1
1107    /// (one intermediate). Validation fails if depth exceeds this value.
1108    ///
1109    /// Self-issued certificates do not count towards the depth (RFC 5280
1110    /// §4.2.1.9), but they are not unlimited either: a chain longer than
1111    /// `2 * max_path_len + 3` certificates (the leaf, `max_path_len`
1112    /// intermediates, and up to one self-issued certificate per CA in the
1113    /// path plus one more at the top for an included root) is rejected with
1114    /// [`Error::PathTooLong`] before any other processing. This bounds the
1115    /// work done on an attacker-supplied chain.
1116    pub max_path_len: u8,
1117
1118    /// Current time as seconds since the Unix epoch (1970-01-01T00:00:00Z).
1119    ///
1120    /// Used to check `notBefore` ≤ `now` ≤ `notAfter` on every certificate.
1121    /// **Must be set by the caller** — there is no platform clock in `no_std`.
1122    ///
1123    /// **Warning — the default is 0 (1970-01-01):** Any certificate issued
1124    /// after 1970 has `notBefore > 0` and will fail the validity check with
1125    /// [`Error::ValidityPeriod`]. If you see unexpected `ValidityPeriod`
1126    /// errors, check that `current_time_unix` is set to the current time.
1127    ///
1128    /// **Warning**: passing `u64::MAX` causes all `notAfter` checks to pass.
1129    /// This effectively disables expiry checking — only use it in contexts
1130    /// where you explicitly want permissive (clock-free) validation.
1131    pub current_time_unix: u64,
1132
1133    /// Enforce the `KeyUsage` extension when present. Default: `true`.
1134    ///
1135    /// When `true`, an intermediate certificate whose `KeyUsage` extension is
1136    /// **present** but does not include `keyCertSign` will be rejected with
1137    /// [`Error::KeyUsageMissing`], per RFC 5280 §6.1.4(n).
1138    ///
1139    /// Certificates with **no** `KeyUsage` extension are not affected; RFC 5280
1140    /// only mandates the check when the extension is present.
1141    pub enforce_key_usage: bool,
1142
1143    /// Require `cRLSign` in `KeyUsage` on every intermediate CA. Default: `false`.
1144    ///
1145    /// When `true`, an intermediate certificate whose `KeyUsage` extension is
1146    /// **present** but does not include `cRLSign` will be rejected with
1147    /// [`Error::CrlSignMissing`]. Certificates with **no** `KeyUsage` extension
1148    /// are not affected.
1149    ///
1150    /// RFC 5280 §6.1 does not mandate this check — it conflates path validation
1151    /// with revocation infrastructure. PKITS §4.7.4 and §4.7.5 nonetheless
1152    /// expect such chains to fail because a CA cert without `cRLSign` cannot
1153    /// revoke certs it issued. Enable this flag to restore PKITS conformance
1154    /// or to enforce a stricter "every CA must be able to sign CRLs" rule.
1155    ///
1156    /// This check is independent of [`enforce_key_usage`][Self::enforce_key_usage]:
1157    /// `enforce_key_usage` governs the RFC-mandated `keyCertSign` check, while
1158    /// `require_crl_sign_on_cas` adds a separate cRLSign requirement.
1159    pub require_crl_sign_on_cas: bool,
1160
1161    /// Initial explicit-policy indicator (RFC 5280 §6.1.1).
1162    ///
1163    /// When `true`, path validation requires that at least one valid policy exists
1164    /// from the initial policy set. When `false` (the default), any valid path is
1165    /// accepted even if no certificate policy is asserted.
1166    pub initial_explicit_policy: bool,
1167
1168    /// Initial any-policy inhibit indicator (RFC 5280 §6.1.1).
1169    ///
1170    /// When `true`, the `anyPolicy` OID is not considered a match for any other
1171    /// policy at the start of the path. When `false` (the default), `anyPolicy`
1172    /// is accepted as a wildcard unless later inhibited by a CA certificate.
1173    pub initial_any_policy_inhibit: bool,
1174
1175    /// Initial policy-mapping inhibit indicator (RFC 5280 §6.1.1).
1176    ///
1177    /// When `true`, policy mappings are not permitted in any certificate in the
1178    /// chain. When `false` (the default), policy mappings are allowed.
1179    pub initial_policy_mapping_inhibit: bool,
1180
1181    /// Initial user-requested policy set (RFC 5280 §6.1.1).
1182    ///
1183    /// The set of certificate policies acceptable to the relying party. An empty
1184    /// vec, or any set that contains `anyPolicy` (2.5.29.32.0), is the RFC's
1185    /// any-policy value: all policies are acceptable and the policy graph is
1186    /// not intersected (§6.1.5(g)(ii)). Otherwise the final graph keeps only
1187    /// policies in this set (§6.1.5(g)(iii)).
1188    ///
1189    /// Note: this is `pub` but clones the OID set, so prefer constructing once
1190    /// and reusing the `ValidationPolicy`.
1191    #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::vec"))]
1192    pub initial_policy_set: Vec<der::asn1::ObjectIdentifier>,
1193
1194    /// If `Some(n)`, reject any certificate whose (notAfter − notBefore) exceeds
1195    /// `n` seconds. `None` means unconstrained (the default).
1196    ///
1197    /// Applied to every certificate in the chain, not just the leaf.
1198    /// Violations produce [`Error::ValidityPeriodExceedsMax`].
1199    pub max_validity_secs: Option<u64>,
1200
1201    /// If `Some(list)`, reject any certificate whose signature algorithm OID is
1202    /// not in `list`. `None` means any algorithm is accepted (the default).
1203    ///
1204    /// Applied to every certificate in the chain. The check fires **before**
1205    /// signature verification so the error is diagnostic rather than a confusing
1206    /// [`Error::SignatureInvalid`].
1207    /// Violations produce [`Error::AlgorithmNotAllowed`].
1208    #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::option_vec"))]
1209    pub allowed_signature_algs: Option<Vec<der::asn1::ObjectIdentifier>>,
1210
1211    /// If `Some(bits)`, reject any certificate carrying an RSA public key whose
1212    /// modulus is fewer than `bits` bits. Both `rsaEncryption` and
1213    /// `id-RSASSA-PSS` subject keys count as RSA; other keys are not affected.
1214    /// `None` means unconstrained (the default).
1215    ///
1216    /// Applied to the subject key of every certificate in the chain, leaf
1217    /// included. The trust anchor's key is **not** checked: it is caller
1218    /// configuration, not path input, so filter weak anchors when building
1219    /// the trust store.
1220    /// Violations produce [`Error::KeyTooSmall`].
1221    pub min_rsa_key_bits: Option<u32>,
1222
1223    /// If `true`, the leaf certificate (chain index 0) must have a non-empty
1224    /// `SubjectAltName` extension. `false` means no SAN requirement (the default).
1225    ///
1226    /// Intermediate CA certificates are not checked by this field.
1227    /// Violations produce [`Error::MissingSan`].
1228    pub require_subject_alt_name: bool,
1229
1230    /// If `true`, at least one `rfc822Name` entry must be present in the leaf's
1231    /// `SubjectAltName` extension.
1232    ///
1233    /// Only meaningful when [`require_subject_alt_name`][Self::require_subject_alt_name]
1234    /// is also `true`. When `require_subject_alt_name` is `false`, this field has
1235    /// no effect.
1236    ///
1237    /// Default: `false` (backward compatible).
1238    /// Violations produce [`Error::MissingRfc822San`].
1239    pub require_rfc822_san: bool,
1240
1241    /// If `Some(oids)`, the leaf certificate must explicitly assert every OID in
1242    /// `oids` via its `ExtendedKeyUsage` extension. `None` means no EKU requirement
1243    /// (the default).
1244    ///
1245    /// `anyExtendedKeyUsage` (2.5.29.37.0) does **not** satisfy a specific OID
1246    /// check — each required OID must be listed in the cert's EKU extension.
1247    /// Violations produce [`Error::MissingEku`].
1248    #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::option_vec"))]
1249    pub required_leaf_eku: Option<Vec<der::asn1::ObjectIdentifier>>,
1250
1251    /// If `Some(oids)`, the leaf certificate must explicitly assert every OID
1252    /// in `oids` via its `CertificatePolicies` extension. `None` means no
1253    /// policy-OID assertion requirement (the default).
1254    ///
1255    /// Distinct from [`initial_policy_set`][Self::initial_policy_set]:
1256    /// `initial_policy_set` is the relying party's *acceptable* policy set
1257    /// (RFC 5280 §6.1.1, `user-initial-policy-set`).
1258    /// `required_leaf_policy_oids` requires *assertion* — the OID must appear
1259    /// on the leaf cert's `CertificatePolicies` extension, independent of the
1260    /// policy tree.
1261    ///
1262    /// `anyPolicy` (2.5.29.32.0) does **not** satisfy a specific OID check.
1263    /// Violations produce [`Error::MissingLeafPolicyOid`].
1264    ///
1265    /// This field follows the [`required_leaf_eku`][Self::required_leaf_eku]
1266    /// precedent: leaf-only, opt-in, additive. Intended for CA/B Forum
1267    /// subscriber-profile tier disambiguation where a tier mandates assertion
1268    /// of a specific reserved policy OID.
1269    #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::option_vec"))]
1270    pub required_leaf_policy_oids: Option<Vec<der::asn1::ObjectIdentifier>>,
1271
1272    /// If `Some(rule)`, the leaf certificate's Subject DN must satisfy
1273    /// `rule`. `None` means no Subject DN requirement (the default).
1274    ///
1275    /// Violations produce [`Error::SubjectDnAttrRuleUnmet`]. See
1276    /// [`DnAttrRule`] for the expression grammar and vacuity rules.
1277    ///
1278    /// This field follows the [`required_leaf_eku`][Self::required_leaf_eku]
1279    /// precedent: leaf-only, opt-in, additive. Intended for CA/B Forum
1280    /// subscriber-profile tier disambiguation (e.g., S/MIME
1281    /// Organization-validated tier requires `organizationName`).
1282    pub required_leaf_subject_dn_attrs: Option<DnAttrRule>,
1283}
1284
1285impl ValidationPolicy {
1286    /// Construct a policy with the given time and sensible defaults.
1287    ///
1288    /// This is the only constructor: it forces the caller to supply a timestamp,
1289    /// preventing the silent validity failures that a `Default` with
1290    /// `current_time_unix = 0` would cause.
1291    #[must_use]
1292    pub fn new(now_unix: u64) -> Self {
1293        Self {
1294            max_path_len: 10,
1295            current_time_unix: now_unix,
1296            enforce_key_usage: true,
1297            require_crl_sign_on_cas: false,
1298            initial_explicit_policy: false,
1299            initial_any_policy_inhibit: false,
1300            initial_policy_mapping_inhibit: false,
1301            initial_policy_set: Vec::new(),
1302            max_validity_secs: None,
1303            allowed_signature_algs: None,
1304            min_rsa_key_bits: None,
1305            require_subject_alt_name: false,
1306            require_rfc822_san: false,
1307            required_leaf_eku: None,
1308            required_leaf_policy_oids: None,
1309            required_leaf_subject_dn_attrs: None,
1310        }
1311    }
1312}
1313
1314/// A PKI regime profile that bundles identity, citation, and a validation policy.
1315///
1316/// # Design rationale
1317///
1318/// `ValidationPolicy` is the *mechanism*. A `Profile` is the *policy authority*: it
1319/// records *who* mandates the policy (e.g., CA/B Forum TLS BR §7.1), supplies a
1320/// stable machine-readable identifier, and produces the appropriate
1321/// [`ValidationPolicy`] for a given point in time.
1322///
1323/// Placing the trait in `pkix-path` rather than `pkix-profiles` means that third-party
1324/// profile crates (e.g., `pkix-fpki`, `pkix-etsi`) can implement `Profile` by depending
1325/// only on `pkix-path` — they do not need to pull in `pkix-profiles`, which would create
1326/// a circular coupling between reference implementations and the trait definition.
1327///
1328/// # `no_std` compatibility
1329///
1330/// The trait is `no_std`-safe: it uses only `&str`, `&[ObjectIdentifier]`, and
1331/// `ValidationPolicy` (all of which are available without `std`).
1332/// Implementors on embedded targets may return static `&'static str` slices and
1333/// construct `ValidationPolicy` without allocation.
1334///
1335/// # Implementing `Profile`
1336///
1337/// ```rust,no_run
1338/// use pkix_path::{Profile, ValidationPolicy};
1339///
1340/// struct MyCorpProfile;
1341///
1342/// impl Profile for MyCorpProfile {
1343///     fn id(&self) -> &'static str { "example.corp.internal" }
1344///     fn version(&self) -> &'static str { "2024-01" }
1345///     fn policy(&self, now_unix: u64) -> ValidationPolicy {
1346///         let mut p = ValidationPolicy::new(now_unix);
1347///         p.max_validity_secs = Some(365 * 86_400);
1348///         p
1349///     }
1350///     fn policy_oids(&self) -> &[der::asn1::ObjectIdentifier] { &[] }
1351/// }
1352/// ```
1353pub trait Profile {
1354    /// Stable, dot-separated identifier for this profile.
1355    ///
1356    /// The identifier MUST be unique across all deployed profiles and MUST NOT
1357    /// change between versions of the same profile. Use reverse-DNS or
1358    /// CABF/IETF-style naming conventions, e.g.:
1359    /// - `"cabf.br.tls"` — CA/B Forum TLS Baseline Requirements
1360    /// - `"cabf.smime"` — CA/B Forum S/MIME Baseline Requirements
1361    /// - `"fpki.common-policy"` — US Federal PKI Common Policy
1362    ///
1363    /// Lint engines use this ID as a namespace prefix for finding IDs.
1364    fn id(&self) -> &'static str;
1365
1366    /// Human-readable version string for this profile.
1367    ///
1368    /// Typically the ballot or specification version that last changed the
1369    /// policy rules, e.g., `"SC-081"`, `"2024-01"`, or `"v2.0.1"`.
1370    /// Used for diagnostic messages and audit logs; not parsed by the engine.
1371    fn version(&self) -> &'static str;
1372
1373    /// Produce the [`ValidationPolicy`] for the given point in time.
1374    ///
1375    /// `now_unix` is seconds since the Unix epoch. The profile may use this to
1376    /// implement phased validity caps or algorithm retirement schedules.
1377    /// The returned `ValidationPolicy` MUST have `current_time_unix` set to
1378    /// `now_unix`.
1379    #[must_use]
1380    fn policy(&self, now_unix: u64) -> ValidationPolicy;
1381
1382    /// The certificate policy OIDs that this profile recognises as its own.
1383    ///
1384    /// Used by registry and composition tools to detect when two profiles
1385    /// claim overlapping policy space. Returns an empty slice if the profile
1386    /// does not restrict certificate policy OIDs.
1387    fn policy_oids(&self) -> &[der::asn1::ObjectIdentifier];
1388}
1389
1390/// The result of a successful certificate path validation.
1391///
1392/// A `ValidatedPath` is only produced when [`validate_path`] succeeds, which
1393/// requires the input `chain` to contain at least one certificate. Callers
1394/// may therefore rely on `chain[0]` being valid after a successful validation.
1395///
1396/// Fields are `pub` for direct read access. `#[non_exhaustive]` prevents external
1397/// code from constructing `ValidatedPath` directly and from pattern-matching
1398/// exhaustively, preserving the ability to add fields in future minor versions
1399/// without a breaking change.
1400///
1401/// # `Copy` removal in 0.3.0
1402///
1403/// `ValidatedPath` is no longer `Copy`. The struct now carries owned
1404/// heap-backed fields exposing RFC 5280 §6.1.5 wrap-up outputs (the leaf's
1405/// subject DN, issuer DN, serial number, and SubjectPublicKeyInfo) so
1406/// consumers can read the validated leaf identity without re-parsing
1407/// `chain[0]`. These fields cannot satisfy the `Copy` bound; pre-0.3
1408/// callers that relied on bit-copy semantics need to add `.clone()` or
1409/// pass `&ValidatedPath` instead.
1410///
1411/// # §6.1.5 wrap-up outputs
1412///
1413/// RFC 5280 §6.1.5 specifies that successful path validation produces
1414/// several outputs identifying the validated leaf certificate. The four
1415/// leaf-intrinsic outputs (subject, issuer, serial, SPKI) are surfaced
1416/// here as convenience accessors; consumers no longer need to re-parse
1417/// `chain[0]` to obtain them.
1418///
1419/// The final `valid_policy_tree` is surfaced as
1420/// [`valid_policy_tree`][Self::valid_policy_tree]. The final
1421/// `working_public_key_parameters` is not yet surfaced; future minor
1422/// versions may add it, so callers should pattern match with `..` rest
1423/// patterns on this `#[non_exhaustive]` struct.
1424///
1425/// `Hash` is no longer derived because none of the new field types
1426/// (`x509_cert::name::Name`, `x509_cert::serial_number::SerialNumber`,
1427/// `spki::SubjectPublicKeyInfoOwned`) implement `Hash` upstream. No
1428/// in-tree consumer used `ValidatedPath` as a `HashMap`/`HashSet` key,
1429/// so dropping the derive is observable but should not require code
1430/// changes for any existing user.
1431#[derive(Clone, Debug, PartialEq, Eq)]
1432#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1433#[non_exhaustive]
1434pub struct ValidatedPath {
1435    /// Index into the `anchors` slice of the trust anchor that terminated the path.
1436    pub anchor_index: usize,
1437    /// Number of intermediate certificates in the validated chain, excluding
1438    /// both the leaf and the trust anchor.
1439    ///
1440    /// Computed as `chain.len().saturating_sub(1)` where `chain` is the
1441    /// `[leaf, intermediate_0, ..., intermediate_n]` slice passed to
1442    /// [`validate_path`]. A single leaf certificate yields `depth == 0`;
1443    /// a leaf plus one intermediate yields `depth == 1`.
1444    ///
1445    /// Note: this counts all certificates except the trust anchor — including
1446    /// self-issued intermediates that RFC 5280 §4.2.1.9 excludes from the
1447    /// `pathLenConstraint` count. For chains with self-issued intermediates the
1448    /// `depth` field may be larger than the RFC 5280 path length.
1449    ///
1450    /// **Do not** compare `depth` directly against a certificate's
1451    /// [`BasicConstraints`] `pathLenConstraint` value. RFC 5280 §4.2.1.9
1452    /// defines `pathLenConstraint` as the number of non-self-issued
1453    /// intermediates below the issuing CA, which differs from this field's
1454    /// total certificate count. Use the RFC 5280 §6.1.4(b) accounting
1455    /// performed by `chain_walk` instead.
1456    ///
1457    /// [`BasicConstraints`]: x509_cert::ext::pkix::BasicConstraints
1458    pub depth: usize,
1459
1460    /// Subject DN of the validated leaf certificate (`chain[0].subject`).
1461    ///
1462    /// RFC 5280 §6.1.5 names this output indirectly: a successful path
1463    /// validation produces the leaf's identity (subject + serial uniquely
1464    /// identify a certificate). This field is a convenience accessor —
1465    /// callers could equivalently read `chain[0].tbs_certificate().subject()`,
1466    /// but threading the chain to every consumer that needs the leaf's DN
1467    /// is awkward. The clone is owned to free the validated value from any
1468    /// lifetime tie to the input chain.
1469    #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
1470    pub leaf_subject: x509_cert::name::Name,
1471
1472    /// Issuer DN of the validated leaf certificate (`chain[0].issuer`).
1473    ///
1474    /// This is the §6.1.5(f) `working_issuer_name` output as observed at
1475    /// the leaf cert (which is the first cert processed by the §6.1
1476    /// algorithm, so the leaf's `issuer` is the initial value of
1477    /// `working_issuer_name` before iteration begins; for a successfully
1478    /// validated chain it identifies the directly-signing CA).
1479    #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
1480    pub leaf_issuer: x509_cert::name::Name,
1481
1482    /// Serial number of the validated leaf certificate
1483    /// (`chain[0].serial_number`).
1484    ///
1485    /// Together with [`Self::leaf_issuer`] this forms the RFC 5280
1486    /// §4.1.2.2 unique certificate identifier (`{ issuer, serial }`),
1487    /// which downstream code commonly needs for revocation lookups,
1488    /// audit logging, or de-duplication.
1489    #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
1490    pub leaf_serial: x509_cert::serial_number::SerialNumber,
1491
1492    /// `SubjectPublicKeyInfo` of the validated leaf certificate.
1493    ///
1494    /// This is the §6.1.5(c)(d)(e) `working_public_key` /
1495    /// `working_public_key_algorithm` / `working_public_key_parameters`
1496    /// outputs, bundled into the canonical SPKI form. Downstream code
1497    /// (e.g. application-layer signature verification using the validated
1498    /// leaf as a trust delegate) needs the full SPKI rather than only the
1499    /// algorithm identifier or only the public-key bits.
1500    ///
1501    /// Note: this field reflects the leaf's *encoded* SPKI as it appeared
1502    /// in the certificate, not a normalized/canonicalized form. PSS
1503    /// parameters, RSA `parameters: NULL` vs `parameters: absent`
1504    /// ambiguities, etc. are preserved verbatim.
1505    #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
1506    pub leaf_spki: spki::SubjectPublicKeyInfoOwned,
1507
1508    /// The final RFC 5280 §6.1.5 `valid_policy_tree` (held as the RFC 9618
1509    /// policy graph, see [`PolicyTreeNode`]), or `None` if it was reduced to
1510    /// NULL during validation.
1511    ///
1512    /// `Some(tree)` is the post-§6.1.5(g)(iii) state (i.e. after
1513    /// intersection with `initial_policy_set` and post-pruning), listed
1514    /// depth by depth starting with the depth-0 root.
1515    /// `None` means the path validated only because `explicit_policy`
1516    /// stayed above 0 (no explicit policy was required) — semantically "no
1517    /// acceptable policy is valid for this path". Callers that want to enforce a specific policy OID
1518    /// (or extract qualifiers attached to a specific policy) should
1519    /// inspect this field and treat `None` as "no policy information
1520    /// available", not as a validation failure.
1521    ///
1522    /// Each node carries its policy qualifiers (RFC 5280 §6.1.2(a)) in
1523    /// the upstream `PolicyQualifierInfo` form (a `(qualifier_id_oid,
1524    /// raw_any_value)` pair, no decoding of `qualifier`). See
1525    /// [`PolicyTreeNode`] for the per-node shape.
1526    ///
1527    /// For convenience, [`Self::policy_qualifiers`] iterates
1528    /// `(policy_oid, qualifier)` pairs across all tree nodes.
1529    pub valid_policy_tree: Option<Vec<PolicyTreeNode>>,
1530}
1531
1532/// A node of the final policy graph, exposed for post-validation qualifier
1533/// extraction on [`ValidatedPath::valid_policy_tree`].
1534///
1535/// Policy processing uses the RFC 9618 `valid_policy_graph` in place of the
1536/// RFC 5280 §6.1.2(a) `valid_policy_tree`: there is at most one node per
1537/// `(depth, valid_policy)`, and a node that the RFC 5280 tree would copy
1538/// once per parent appears once, listing every parent in
1539/// [`parent_policies`][Self::parent_policies]. The set of valid policies is
1540/// the same (RFC 9618 §3); the graph's size stays linear in the size of the
1541/// path's policy extensions, where the tree can grow exponentially.
1542///
1543/// This is the public mirror of an internal node type, kept separate so the
1544/// internal representation is not part of the public API surface.
1545#[derive(Clone, Debug, PartialEq, Eq)]
1546#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1547#[non_exhaustive]
1548pub struct PolicyTreeNode {
1549    /// Depth at which this node appears in the tree.
1550    ///
1551    /// `0` is the synthetic anyPolicy root sentinel (always present
1552    /// while the tree is alive; carries no qualifiers). `1` is the
1553    /// trust-anchor-adjacent CA. `n` is the leaf.
1554    pub depth: usize,
1555
1556    /// The policy OID this node represents.
1557    ///
1558    /// May be `id-ce-certificatePolicies-anyPolicy` (2.5.29.32.0) for
1559    /// nodes that survived an anyPolicy expansion or were not yet
1560    /// materialized into specific policies.
1561    #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
1562    pub valid_policy: der::asn1::ObjectIdentifier,
1563
1564    /// Set of policies in the next certificate that are consistent with
1565    /// this node, per RFC 5280 §6.1.2(a) `expected_policy_set`.
1566    ///
1567    /// Initialized to `{valid_policy}` and updated by `PolicyMappings`
1568    /// extensions during the walk.
1569    #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::vec"))]
1570    pub expected_policy_set: Vec<der::asn1::ObjectIdentifier>,
1571
1572    /// Policy qualifiers attached to this node, in the upstream
1573    /// `PolicyQualifierInfo` form: a `(policy_qualifier_id, qualifier)`
1574    /// pair where `qualifier` is a raw `der::Any`. Decoding is left to
1575    /// the caller because [the `x509-cert` 0.2.5 `UserNotice` type has
1576    /// an upstream typo on `notice_ref`][1] — pass-through avoids the
1577    /// buggy decoder. The two standard qualifier IDs are
1578    /// `id-qt-cps` (1.3.6.1.5.5.7.2.1, qualifier is a `CPSuri` /
1579    /// `IA5String`) and `id-qt-unotice` (1.3.6.1.5.5.7.2.2, qualifier
1580    /// is a `UserNotice`).
1581    ///
1582    /// [1]: https://github.com/RustCrypto/formats/issues/x509-cert
1583    #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::vec"))]
1584    pub qualifiers: Vec<x509_cert::ext::pkix::certpolicy::PolicyQualifierInfo>,
1585
1586    /// `valid_policy` of each parent node at `depth - 1` (nodes are unique
1587    /// per depth, so the OID identifies the parent). Empty for the depth-0
1588    /// root. A node's parents are either exactly `[anyPolicy]` or a set of
1589    /// specific policies.
1590    #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::vec"))]
1591    pub parent_policies: Vec<der::asn1::ObjectIdentifier>,
1592}
1593
1594impl ValidatedPath {
1595    /// Iterate `(policy_oid, qualifier)` pairs across every node in the
1596    /// final policy tree.
1597    ///
1598    /// Returns an empty iterator if the tree is `None` (it was reduced to
1599    /// NULL during validation, which is only accepted while no explicit
1600    /// policy is required).
1601    ///
1602    /// Each yielded pair is `(node.valid_policy, &qualifier)` — the
1603    /// qualifier is a reference into the tree, valid for the borrow
1604    /// duration. Multiple qualifiers attached to the same policy yield
1605    /// multiple pairs with equal first elements; multiple nodes with the
1606    /// same policy OID at different depths also yield multiple pairs.
1607    ///
1608    /// Callers commonly need to:
1609    ///
1610    /// 1. Filter by `policy_qualifier_id` to find a specific qualifier
1611    ///    type (CPS pointer or user notice).
1612    /// 2. Read `qualifier.qualifier` (an `Option<der::Any>`) and decode
1613    ///    according to the `policy_qualifier_id`. See [`PolicyTreeNode::qualifiers`]
1614    ///    for why we do not decode upstream-side.
1615    pub fn policy_qualifiers(
1616        &self,
1617    ) -> impl Iterator<
1618        Item = (
1619            &der::asn1::ObjectIdentifier,
1620            &x509_cert::ext::pkix::certpolicy::PolicyQualifierInfo,
1621        ),
1622    > + '_ {
1623        self.valid_policy_tree
1624            .as_ref()
1625            .into_iter()
1626            .flat_map(|tree| tree.iter())
1627            .flat_map(|node| node.qualifiers.iter().map(move |q| (&node.valid_policy, q)))
1628    }
1629}
1630
1631/// Validate a certificate chain from subject to a trust anchor.
1632///
1633/// `chain` must be ordered leaf-first:
1634/// - `chain[0]` is the subject (end-entity) certificate
1635/// - `chain[1..]` are intermediates in issuer order
1636/// - The last element of `chain` must be issued by one of `anchors`
1637///
1638/// Validation follows RFC 5280 §6.1. Each certificate's signature is verified
1639/// using `verifier`, with the signing key taken from the next certificate in
1640/// the chain (or the matching trust anchor for the last cert).
1641///
1642/// # Including the root certificate
1643///
1644/// The self-signed certificate of the trust anchor may be passed as the last
1645/// element of `chain`. It is then processed as path certificate 1 of
1646/// RFC 5280 §6.1 rather than skipped: its own signature, validity period,
1647/// `BasicConstraints`, `KeyUsage`, name constraints and policy extensions all
1648/// apply. In particular a root without a `CertificatePolicies` extension
1649/// (the common case) reduces the policy tree to NULL (§6.1.3(e)), so a
1650/// path that requires an explicit policy fails when the root is included
1651/// and succeeds when it is supplied only as the anchor. Pass the root only
1652/// in `anchors` unless its constraints are meant to apply as a path
1653/// certificate.
1654///
1655/// # Errors
1656///
1657/// Returns `Err(Error::NoTrustedPath)` if `chain` is empty or `anchors` is
1658/// empty. On success, `chain` is therefore guaranteed to contain at least one
1659/// certificate.
1660///
1661/// Returns `Err` on the first RFC 5280 §6.1 check failure. The error variant
1662/// includes the chain index of the failing certificate where applicable.
1663///
1664/// # Limitations
1665///
1666/// See crate-level documentation for current scope limits.
1667pub fn validate_path<V>(
1668    chain: &[Certificate],
1669    anchors: &[TrustAnchor],
1670    policy: &ValidationPolicy,
1671    verifier: &V,
1672) -> Result<ValidatedPath>
1673where
1674    V: SignatureVerifier,
1675{
1676    // (0) Cheap length bound before anything that is super-linear in the
1677    //     chain length (the pairwise duplicate scan in `check_inputs`, and
1678    //     the DN comparisons it and the self-issued count perform). See the
1679    //     `max_path_len` rustdoc for how the bound is derived.
1680    if chain.len() > max_chain_certs(policy.max_path_len) {
1681        return Err(Error::PathTooLong);
1682    }
1683
1684    // (1) Input guards: reject empty chain or anchors, check OID consistency.
1685    check_inputs(chain, anchors)?;
1686    check_oid_consistency(chain)?;
1687
1688    // (2) Path-length check (anchor-independent).
1689    // RFC 5280 §4.2.1.9: pathLen counts non-self-issued intermediates only.
1690    let num_non_si_intermediates = chain[1..]
1691        .iter()
1692        .filter(|c| !is_self_issued_cert(c))
1693        .count();
1694    if num_non_si_intermediates > policy.max_path_len as usize {
1695        return Err(Error::PathTooLong);
1696    }
1697
1698    // (3) Try each name-matching anchor. Iterating all candidates handles key
1699    //     rollover: multiple anchors may share a DN but have different keys
1700    //     (e.g., during a root CA rotation). The first anchor that passes the
1701    //     full chain walk is used; the last error is returned if none succeed.
1702    //
1703    //     Complexity: O(A × N) where A = number of anchors, N = chain length.
1704    //     For the common case of O(1) matching anchors this is effectively O(N).
1705    let last_cert = chain.last().ok_or(Error::NoTrustedPath)?;
1706    let is_self_issued = names_match(
1707        last_cert.tbs_certificate().issuer(),
1708        last_cert.tbs_certificate().subject(),
1709    );
1710    let mut last_err = Error::NoTrustedPath;
1711    for (anchor_index, anchor) in anchors.iter().enumerate() {
1712        if !names_match(&anchor.subject, last_cert.tbs_certificate().issuer()) {
1713            continue;
1714        }
1715        // A self-issued top certificate whose key differs from this
1716        // same-name anchor's is either a key-rollover certificate issued by
1717        // the anchor (valid: its signature verifies under the anchor key) or
1718        // a certificate of an unrelated same-name CA (RFC 5280 §3.2 name
1719        // collision). `chain_walk` tells them apart by verifying the top
1720        // signature with the anchor key; in the collision case that
1721        // signature check is the first failure and is reported as
1722        // `NoTrustedPath` below, since this anchor simply is not the issuer.
1723        let top_key_differs = is_self_issued
1724            && !spki_key_matches(
1725                &anchor.subject_public_key_info,
1726                last_cert.tbs_certificate().subject_public_key_info(),
1727            );
1728        match chain_walk(chain, anchor, policy, verifier) {
1729            Ok(final_policy_tree) => {
1730                // §6.1.5 leaf-intrinsic outputs. `chain[0]` is guaranteed
1731                // non-empty by `check_inputs` at the top of this function.
1732                // The four `leaf_*` fields are direct clones of the leaf's
1733                // `tbs_certificate` fields; populating them from `chain[0]`
1734                // (rather than threading them out of `chain_walk`) avoids
1735                // adding more entries to the walker's return tuple.
1736                let leaf_tbs = chain[0].tbs_certificate();
1737                // Flatten the internal RFC 9618 policy graph into the
1738                // public `PolicyTreeNode` list. The internal shape stays
1739                // private so it can evolve without a public-API break.
1740                let valid_policy_tree =
1741                    final_policy_tree.map(policy_graph::PolicyGraph::into_public);
1742                return Ok(ValidatedPath {
1743                    anchor_index,
1744                    depth: chain.len().saturating_sub(1),
1745                    leaf_subject: leaf_tbs.subject().clone(),
1746                    leaf_issuer: leaf_tbs.issuer().clone(),
1747                    leaf_serial: leaf_tbs.serial_number().clone(),
1748                    leaf_spki: leaf_tbs.subject_public_key_info().clone(),
1749                    valid_policy_tree,
1750                });
1751            }
1752            Err(Error::SignatureInvalid { index } | Error::SignatureNotVerified { index, .. })
1753                if top_key_differs && index == chain.len() - 1 =>
1754            {
1755                // Name collision, not a rollover: keep the previous error
1756                // (initially `NoTrustedPath`) and try the next anchor.
1757            }
1758            Err(e) => last_err = e,
1759        }
1760    }
1761    Err(last_err)
1762}
1763
1764/// Validate a certificate chain using a [`Profile`] to produce the policy.
1765///
1766/// This is a convenience wrapper around [`validate_path`] for callers that
1767/// work with a `Profile` implementation rather than constructing a
1768/// [`ValidationPolicy`] directly.
1769///
1770/// The profile's [`Profile::policy`] method is called with `now_unix` to
1771/// produce the `ValidationPolicy`.  The returned policy's `current_time_unix`
1772/// is then unconditionally overwritten with `now_unix`, so that a buggy
1773/// `Profile` implementation that returns the wrong clock value cannot silently
1774/// cause validity checks to run against the wrong time.
1775///
1776/// See [`validate_path`] for full documentation of the remaining parameters
1777/// and error semantics.
1778///
1779/// # Errors
1780///
1781/// Returns `Err(Error::...)` for each validation failure. See [`Error`] for the full list of failure conditions.
1782pub fn validate_path_with_profile<V, P>(
1783    chain: &[Certificate],
1784    anchors: &[TrustAnchor],
1785    profile: &P,
1786    now_unix: u64,
1787    verifier: &V,
1788) -> Result<ValidatedPath>
1789where
1790    V: SignatureVerifier,
1791    P: Profile,
1792{
1793    let mut policy = profile.policy(now_unix);
1794    // Defense-in-depth: overwrite current_time_unix with the caller's value.
1795    // A correct Profile implementation already sets this in policy(), but
1796    // an incorrect implementation might use a stale or wrong clock. This
1797    // overwrite is a belt-and-suspenders guard — it does not compensate for a
1798    // known bug; no existing Profile impl is incorrect.
1799    policy.current_time_unix = now_unix;
1800    validate_path(chain, anchors, &policy, verifier)
1801}
1802
1803// ---------------------------------------------------------------------------
1804// validate_path helpers — input guards and OID consistency (PKIX-6vu)
1805// ---------------------------------------------------------------------------
1806
1807/// Compare two SPKIs for the purpose of the self-issued anchor guard.
1808///
1809/// Compares algorithm OID and key bytes only — not the parameters field.
1810/// This is intentional: for RSA, explicit NULL parameters and absent
1811/// parameters are both valid encodings of the same algorithm (RFC 3279
1812/// §2.3.1); comparing the full `AlgorithmIdentifier` would wrongly reject
1813/// a valid anchor whose SPKI parameter encoding differs from the cert's.
1814/// For ECDSA, the parameters carry the curve OID, but two keys on different
1815/// curves also differ in their raw key bytes, so OID + key comparison is
1816/// still sufficient to distinguish them.
1817/// Upper bound on `chain.len()` for a given `max_path_len`: the leaf,
1818/// `max_path_len` non-self-issued intermediates, one self-issued certificate
1819/// (key rollover) per CA in the path including the anchor's, and an included
1820/// self-signed root.
1821const fn max_chain_certs(max_path_len: u8) -> usize {
1822    2 * (max_path_len as usize) + 3
1823}
1824
1825fn spki_key_matches(
1826    a: &spki::SubjectPublicKeyInfoOwned,
1827    b: &spki::SubjectPublicKeyInfoOwned,
1828) -> bool {
1829    a.algorithm.oid == b.algorithm.oid && a.subject_public_key == b.subject_public_key
1830}
1831
1832fn check_inputs(chain: &[Certificate], anchors: &[TrustAnchor]) -> Result<()> {
1833    if chain.is_empty() || anchors.is_empty() {
1834        return Err(Error::NoTrustedPath);
1835    }
1836    // Duplicate detection: check all pairs for (issuer DN, serial number) identity.
1837    // Per RFC 5280 §4.1.2.2, issuer+serial uniquely identifies a certificate.
1838    // A cert appearing twice in the chain is a construction error; reporting
1839    // DuplicateCertificate is cleaner than the confusing SignatureInvalid or
1840    // ChainBroken that would otherwise result.
1841    //
1842    // SPKI equality is intentionally NOT used here: cross-signed CAs legitimately
1843    // have two distinct certificates sharing the same public key (same SPKI, different
1844    // issuer+serial). Using issuer+serial avoids false positives in those chains.
1845    //
1846    // O(n²) over chain.len() — acceptable for chains of typical length (2–5 certs).
1847    for i in 0..chain.len() {
1848        for j in (i + 1)..chain.len() {
1849            let a = chain[i].tbs_certificate();
1850            let b = chain[j].tbs_certificate();
1851            if names_match(a.issuer(), b.issuer()) && a.serial_number() == b.serial_number() {
1852                return Err(Error::DuplicateCertificate {
1853                    first: i,
1854                    second: j,
1855                });
1856            }
1857        }
1858    }
1859    Ok(())
1860}
1861
1862/// RFC 5280 §4.1.1.2: outer signatureAlgorithm OID must equal inner TBSCertificate.signature OID.
1863///
1864/// Only OIDs are compared, not parameters.  RFC 5280 says the two
1865/// `AlgorithmIdentifiers` MUST be identical, but many production CAs
1866/// generate certs where one field has explicit NULL parameters and the other
1867/// omits them — a mismatch that OpenSSL and other validators accept in
1868/// practice.  OID-only comparison preserves the security intent (the same
1869/// algorithm must be named in both places) without rejecting otherwise-valid
1870/// certs from common PKI deployments.
1871fn check_oid_consistency(chain: &[Certificate]) -> Result<()> {
1872    for (index, cert) in chain.iter().enumerate() {
1873        if cert.signature_algorithm().oid != cert.tbs_certificate().signature().oid {
1874            return Err(Error::MalformedCertificate { index });
1875        }
1876    }
1877    Ok(())
1878}
1879
1880// ---------------------------------------------------------------------------
1881// Critical extension guard (PKIX-ad6)
1882// ---------------------------------------------------------------------------
1883
1884const OID_KEY_USAGE: der::asn1::ObjectIdentifier =
1885    der::asn1::ObjectIdentifier::new_unwrap("2.5.29.15");
1886
1887const OID_BASIC_CONSTRAINTS: der::asn1::ObjectIdentifier =
1888    der::asn1::ObjectIdentifier::new_unwrap("2.5.29.19");
1889
1890const OID_SUBJECT_ALT_NAME: der::asn1::ObjectIdentifier =
1891    der::asn1::ObjectIdentifier::new_unwrap("2.5.29.17");
1892
1893const OID_EXTENDED_KEY_USAGE: der::asn1::ObjectIdentifier =
1894    der::asn1::ObjectIdentifier::new_unwrap("2.5.29.37");
1895
1896const OID_NAME_CONSTRAINTS: der::asn1::ObjectIdentifier =
1897    der::asn1::ObjectIdentifier::new_unwrap("2.5.29.30");
1898
1899const OID_CERTIFICATE_POLICIES: der::asn1::ObjectIdentifier =
1900    der::asn1::ObjectIdentifier::new_unwrap("2.5.29.32");
1901
1902const OID_POLICY_MAPPINGS: der::asn1::ObjectIdentifier =
1903    der::asn1::ObjectIdentifier::new_unwrap("2.5.29.33");
1904
1905const OID_POLICY_CONSTRAINTS: der::asn1::ObjectIdentifier =
1906    der::asn1::ObjectIdentifier::new_unwrap("2.5.29.36");
1907
1908const OID_INHIBIT_ANY_POLICY: der::asn1::ObjectIdentifier =
1909    der::asn1::ObjectIdentifier::new_unwrap("2.5.29.54");
1910
1911/// OID for the `anyPolicy` wildcard (2.5.29.32.0 — a child of id-ce-certificatePolicies).
1912pub(crate) const OID_ANY_POLICY: der::asn1::ObjectIdentifier =
1913    der::asn1::ObjectIdentifier::new_unwrap("2.5.29.32.0");
1914
1915/// OID for the emailAddress attribute in Distinguished Names (PKCS #9 §5.2.1).
1916/// Used when enforcing RFC 5280 §4.2.1.10 rfc822Name constraints against DN attributes.
1917const OID_EMAIL_ADDRESS: der::asn1::ObjectIdentifier =
1918    der::asn1::ObjectIdentifier::new_unwrap("1.2.840.113549.1.9.1");
1919
1920/// OIDs of extensions that this implementation handles; all others, if critical, cause rejection.
1921///
1922/// `OID_SUBJECT_ALT_NAME` is listed here so that certs with critical SAN extensions
1923/// (e.g. TLS server certs) do not fail with `UnhandledCriticalExtension`. A cert
1924/// with an empty Subject and a critical SAN is handled correctly: the SAN is
1925/// used as the cert's identity via `cert_has_san_identity` / `working_issuer_is_san_identity`
1926/// (RFC 5280 §4.2.1.6), so name linkage does not fall back to the empty Subject DN.
1927///
1928/// `OID_EXTENDED_KEY_USAGE` is listed here so that certs with critical EKU
1929/// (common in CA/B Forum TLS and code-signing certificates) do not fail with
1930/// `UnhandledCriticalExtension`. RFC 5280 §6.1 path validation does not require
1931/// inspecting EKU values; the extension is accepted and its content is not verified.
1932const HANDLED_CRITICAL_OIDS: &[der::asn1::ObjectIdentifier] = &[
1933    OID_KEY_USAGE,
1934    OID_BASIC_CONSTRAINTS,
1935    OID_SUBJECT_ALT_NAME,
1936    OID_EXTENDED_KEY_USAGE,
1937    OID_NAME_CONSTRAINTS,
1938    OID_CERTIFICATE_POLICIES,
1939    OID_POLICY_MAPPINGS,
1940    OID_POLICY_CONSTRAINTS,
1941    OID_INHIBIT_ANY_POLICY,
1942];
1943
1944/// RFC 5280 §4.2: "A certificate MUST NOT include more than one instance of
1945/// a particular extension." Reject such certificates with
1946/// [`Error::MalformedCertificate`].
1947///
1948/// The extension lookups in this crate read only the first instance of an
1949/// OID, while other validators may read the last or reject the certificate;
1950/// accepting duplicates would let one certificate mean different things to
1951/// different validators (e.g. two `basicConstraints` with cA TRUE then FALSE).
1952///
1953/// Sorts a copy of the OIDs, so the cost is O(e log e) in the extension
1954/// count `e` rather than quadratic.
1955fn check_duplicate_extensions(cert: &Certificate, index: usize) -> Result<()> {
1956    let exts = cert
1957        .tbs_certificate()
1958        .extensions()
1959        .map_or(&[][..], |v| v.as_slice());
1960    if exts.len() < 2 {
1961        return Ok(());
1962    }
1963    let mut oids: Vec<der::asn1::ObjectIdentifier> = exts.iter().map(|e| e.extn_id).collect();
1964    oids.sort_unstable();
1965    if oids.windows(2).any(|w| w[0] == w[1]) {
1966        return Err(Error::MalformedCertificate { index });
1967    }
1968    Ok(())
1969}
1970
1971/// RFC 5280 §6.1.3(a)(3): reject any critical extension not in the handled set.
1972fn check_critical_extensions(cert: &Certificate, index: usize) -> Result<()> {
1973    for ext in cert
1974        .tbs_certificate()
1975        .extensions()
1976        .map_or(&[][..], |v| v.as_slice())
1977    {
1978        if ext.critical && !HANDLED_CRITICAL_OIDS.contains(&ext.extn_id) {
1979            return Err(Error::UnhandledCriticalExtension { index });
1980        }
1981    }
1982    Ok(())
1983}
1984
1985// ---------------------------------------------------------------------------
1986// Policy processing (RFC 5280 §6.1) — see `policy_graph` (RFC 9618 graph)
1987// ---------------------------------------------------------------------------
1988
1989// ---------------------------------------------------------------------------
1990// KeyUsage extraction (PKIX-8ae)
1991// ---------------------------------------------------------------------------
1992
1993/// Returns whether the `keyCertSign` bit is set in the `KeyUsage` extension.
1994///
1995/// - `None`         — `KeyUsage` extension absent (no constraint)
1996/// - `Ok(Some(true))`  — keyCertSign is set
1997/// - `Ok(Some(false))` — `KeyUsage` present, keyCertSign NOT set
1998/// - `Ok(None)`        — `KeyUsage` extension absent
1999/// - `Err(_)`          — `KeyUsage` present but DER-malformed (fail-closed)
2000fn has_key_cert_sign(cert: &Certificate) -> der::Result<Option<bool>> {
2001    use x509_cert::ext::pkix::KeyUsage;
2002
2003    try_find_cert_ext::<KeyUsage>(cert, OID_KEY_USAGE).map(|opt| opt.map(|ku| ku.key_cert_sign()))
2004}
2005
2006/// Returns whether the `cRLSign` bit is set in the `KeyUsage` extension.
2007///
2008/// Same shape as [`has_key_cert_sign`]; used by the
2009/// [`ValidationPolicy::require_crl_sign_on_cas`] opt-in check (PKITS §4.7.4 / §4.7.5).
2010///
2011/// - `Ok(Some(true))`  — cRLSign is set
2012/// - `Ok(Some(false))` — `KeyUsage` present, cRLSign NOT set
2013/// - `Ok(None)`        — `KeyUsage` extension absent
2014/// - `Err(_)`          — `KeyUsage` present but DER-malformed (fail-closed)
2015fn has_crl_sign(cert: &Certificate) -> der::Result<Option<bool>> {
2016    use x509_cert::ext::pkix::KeyUsage;
2017
2018    try_find_cert_ext::<KeyUsage>(cert, OID_KEY_USAGE).map(|opt| opt.map(|ku| ku.crl_sign()))
2019}
2020
2021// ---------------------------------------------------------------------------
2022// Extension extraction helpers
2023// ---------------------------------------------------------------------------
2024
2025/// Find and decode an X.509 extension from `cert` by OID.
2026///
2027/// **Fail-open**: returns `None` if the extension is absent *or* if its DER
2028/// value cannot be decoded. Decoding errors are silently discarded.
2029///
2030/// Use this for extensions where a parse failure is tolerable (e.g., optional
2031/// informational extensions). For security-critical extensions where a parse
2032/// failure must be propagated, use [`try_find_cert_ext`] instead.
2033fn find_cert_ext<T: der::DecodeOwned>(
2034    cert: &Certificate,
2035    oid: der::asn1::ObjectIdentifier,
2036) -> Option<T> {
2037    cert.tbs_certificate()
2038        .extensions()
2039        .map_or(&[][..], |v| v.as_slice())
2040        .iter()
2041        .find(|e| e.extn_id == oid)
2042        .and_then(|e| T::from_der(e.extn_value.as_bytes()).ok())
2043}
2044
2045/// Look up and decode an X.509 extension from `cert` by OID.
2046///
2047/// **Fail-closed**: propagates DER decoding errors to the caller rather than
2048/// discarding them. This is appropriate for security-critical extensions where
2049/// a malformed value must not be silently ignored.
2050///
2051/// Returns:
2052/// - `Ok(None)` — extension absent.
2053/// - `Ok(Some(T))` — extension present and decoded successfully.
2054/// - `Err(der::Error)` — extension present but DER decoding failed.
2055///
2056/// For non-critical extensions where a parse failure should be treated as
2057/// absent, use [`find_cert_ext`] (fail-open) instead.
2058fn try_find_cert_ext<T: for<'a> der::Decode<'a, Error = der::Error>>(
2059    cert: &Certificate,
2060    oid: der::asn1::ObjectIdentifier,
2061) -> der::Result<Option<T>> {
2062    cert.tbs_certificate()
2063        .extensions()
2064        .map_or(&[][..], |v| v.as_slice())
2065        .iter()
2066        .find(|e| e.extn_id == oid)
2067        .map_or(Ok(None), |e| T::from_der(e.extn_value.as_bytes()).map(Some))
2068}
2069
2070/// Decode the `SubjectAltName` extension from `cert`.
2071///
2072/// **Fail-closed**: a present-but-malformed SAN returns `Err` rather than being
2073/// silently treated as absent.  Treating a malformed SAN as absent during name
2074/// constraint checking would allow a cert to bypass NC exclusion/permission
2075/// constraints when the SAN extension is present but cannot be decoded (vjc.20).
2076fn cert_subject_alt_names(
2077    cert: &Certificate,
2078    index: usize,
2079) -> crate::Result<Option<x509_cert::ext::pkix::SubjectAltName>> {
2080    try_find_cert_ext(cert, OID_SUBJECT_ALT_NAME).map_err(|_| Error::MalformedCertificate { index })
2081}
2082
2083/// Decode the `NameConstraints` extension from `cert`.
2084///
2085/// Returns `Err(MalformedCertificate)` if the extension is present but:
2086/// - its DER cannot be decoded (vjc.7: fail-closed on security-critical extension), or
2087/// - any `GeneralSubtree` has a non-zero `minimum` or a present `maximum` field
2088///   (vjc.8: RFC 5280 §4.2.1.10 MUST require minimum=0, maximum=absent).
2089///
2090/// Returns `Ok(None)` if the extension is absent.
2091/// Does every `GeneralSubtree` leave `minimum` and `maximum` alone?
2092///
2093/// RFC 5280 §4.2.1.10: "Within this profile, the minimum and maximum fields
2094/// are not used with any name forms, thus minimum MUST be zero, and maximum
2095/// MUST be absent." A certificate that encodes either is non-conformant, and
2096/// the semantics it is asking for are not implemented here.
2097///
2098/// One predicate because three paths need the same answer —
2099/// [`cert_name_constraints`] for intermediates, and both fallible trust-anchor
2100/// constructors. They used to disagree: the rule was applied to intermediates
2101/// and to neither anchor path, so the same extension was grounds for rejection
2102/// in the middle of a chain and accepted at its root.
2103fn subtrees_are_conformant(nc: &NameConstraints) -> bool {
2104    nc.permitted_subtrees
2105        .iter()
2106        .flatten()
2107        .chain(nc.excluded_subtrees.iter().flatten())
2108        .all(|st| st.minimum == 0 && st.maximum.is_none())
2109}
2110
2111fn cert_name_constraints(
2112    cert: &Certificate,
2113    index: usize,
2114) -> crate::Result<Option<NameConstraints>> {
2115    let nc = try_find_cert_ext::<NameConstraints>(cert, OID_NAME_CONSTRAINTS)
2116        .map_err(|_| Error::MalformedCertificate { index })?;
2117
2118    if let Some(nc) = &nc {
2119        if !subtrees_are_conformant(nc) {
2120            return Err(Error::MalformedCertificate { index });
2121        }
2122    }
2123
2124    Ok(nc)
2125}
2126
2127// ---------------------------------------------------------------------------
2128// Validity period checker (PKIX-047)
2129// ---------------------------------------------------------------------------
2130
2131/// Convert an `x509_cert::time::Time` to seconds since the Unix epoch.
2132fn time_to_unix_secs(t: &x509_cert::time::Time) -> u64 {
2133    t.to_unix_duration().as_secs()
2134}
2135
2136/// RFC 5280 §6.1.3(a)(2): check notBefore ≤ now ≤ notAfter.
2137fn check_validity(cert: &Certificate, now_unix: u64, index: usize) -> Result<()> {
2138    let not_before = time_to_unix_secs(&cert.tbs_certificate().validity().not_before);
2139    let not_after = time_to_unix_secs(&cert.tbs_certificate().validity().not_after);
2140    if now_unix >= not_before && now_unix <= not_after {
2141        Ok(())
2142    } else {
2143        Err(Error::ValidityPeriod { index })
2144    }
2145}
2146
2147// ---------------------------------------------------------------------------
2148// Name comparison — RFC 4518 string prep (PKIX-drv)
2149// ---------------------------------------------------------------------------
2150
2151/// Maximum number of attribute-value assertions in one RDN that
2152/// [`names_match`] will compare.
2153///
2154/// RFC 5280 does not limit multi-valued RDNs, but real certificates use
2155/// one AVA per RDN (occasionally two or three). The cap bounds the
2156/// quadratic AVA matching in [`names_match`], which runs on unauthenticated
2157/// input; an RDN above the cap matches nothing.
2158pub const MAX_AVAS_PER_RDN: usize = 64;
2159
2160/// Compare two distinguished names per RFC 4518 string prep rules.
2161///
2162/// Currently implements ASCII case-fold and insignificant-whitespace
2163/// collapsing. `BMPString`-tagged AVAs are transcoded UCS-2-BE → UTF-8
2164/// before normalization, so a `BMPString` AVA and a `UTF8String` (or
2165/// `PrintableString`/`IA5String`/`VisibleString`) AVA that share Unicode
2166/// code points compare equal. Full Unicode NFKC normalization is future
2167/// work.
2168///
2169/// Returns `true` if the names are equivalent.
2170///
2171/// # Ordering
2172///
2173/// RFC 5280 §4.1.2.4 defines `Name` as `SEQUENCE OF RDN`, so RDNs are
2174/// compared positionally (index 0 with index 0, etc.). Within each RDN —
2175/// which is a `SET OF AttributeTypeAndValue` — comparison is order-independent:
2176/// each AVA in one RDN is matched against any AVA in the other.
2177///
2178/// # Limitations
2179///
2180/// - **No NFKC / non-ASCII case fold.** Two AVA values that contain the
2181///   same Unicode characters but differ in canonical decomposition
2182///   (precomposed vs combining, e.g. U+00E9 vs U+0065 U+0301) compare
2183///   unequal even though RFC 4518 says they should match. Non-Latin
2184///   case differences (e.g. Greek lowercase σ vs final σ) are also not
2185///   folded.
2186/// - **`UniversalString` is parser-rejected upstream.** `der` 0.7 omits
2187///   tag 0x1C from `Tag::try_from`, so any cert with a `UniversalString`
2188///   AVA fails to parse before reaching this comparator. This is an
2189///   upstream limitation; the same `BMPString` transcoding applied here
2190///   would generalize to `UniversalString` (UCS-4-BE → UTF-8) once the
2191///   parser accepts it.
2192/// - **`TeletexString` (T61String) uses raw DER byte comparison.**
2193///   `pkix-path` deliberately does not transcode T.61 to Unicode; no
2194///   canonical mapping exists (RFC 4518 §2.1 leaves it "a local matter"
2195///   and OpenSSL, NSS, and `GnuTLS` use mutually incompatible vendor
2196///   tables). Byte-equal `TeletexString` AVAs match; `TeletexString`
2197///   never matches any other string type. Well-formed chains that copy
2198///   the issuer DN bytes per RFC 5280 §4.1.2.4 are unaffected.
2199///
2200/// # Work bound
2201///
2202/// AVA matching within an RDN is quadratic in the RDN's size. To bound the
2203/// work an attacker-supplied name can cause, an RDN with more than
2204/// [`MAX_AVAS_PER_RDN`] attribute-value assertions never matches anything
2205/// (`names_match` returns `false`), so such a name cannot chain.
2206#[must_use]
2207pub fn names_match(a: &x509_cert::name::Name, b: &x509_cert::name::Name) -> bool {
2208    if a.len() != b.len() {
2209        return false;
2210    }
2211    let a_rdns = a.iter_rdn();
2212    let b_rdns = b.iter_rdn();
2213
2214    for (a_rdn, b_rdn) in a_rdns.zip(b_rdns) {
2215        if a_rdn.len() != b_rdn.len() {
2216            return false;
2217        }
2218        // Work bound: the AVA matching below is quadratic in the RDN size,
2219        // and names_match runs on attacker-supplied names before any
2220        // signature has been checked. Real-world RDNs carry one AVA (rarely
2221        // two or three), so an RDN above the cap is treated as matching
2222        // nothing (fail-closed).
2223        if a_rdn.len() > MAX_AVAS_PER_RDN {
2224            return false;
2225        }
2226        // Bijective AVA matching: every AVA in a_rdn must match some AVA in b_rdn,
2227        // AND every AVA in b_rdn must match some AVA in a_rdn (both directions).
2228        //
2229        // The bidirectional check is equivalent to set equality for well-formed RDNs
2230        // (RFC 5280 §5.1.2.4 SHOULD NOT contain duplicate OIDs), and also correctly
2231        // handles the malformed-cert case where an RDN has duplicate OIDs:
2232        //   a={CN=Alice, CN=Alice}, b={CN=Bob, CN=Alice} → both len=2, forward pass
2233        //   finds CN=Alice for each a_ava, but the reverse pass finds no match for
2234        //   CN=Bob → returns false (correct).
2235        // The reverse pass is O(n²) on AVA count; n is 1–5 in practice.
2236        for a_ava in a_rdn.iter() {
2237            let found = b_rdn.iter().any(|b_ava| {
2238                b_ava.oid == a_ava.oid && ava_values_match(&a_ava.value, &b_ava.value)
2239            });
2240            if !found {
2241                return false;
2242            }
2243        }
2244        for b_ava in b_rdn.iter() {
2245            let found = a_rdn.iter().any(|a_ava| {
2246                a_ava.oid == b_ava.oid && ava_values_match(&a_ava.value, &b_ava.value)
2247            });
2248            if !found {
2249                return false;
2250            }
2251        }
2252    }
2253    true
2254}
2255
2256/// Returns `Ok(true)` if `cert` is a CA certificate per its `BasicConstraints`
2257/// extension (RFC 5280 §4.2.1.9), `Ok(false)` if the extension is absent or
2258/// `cA = FALSE`, and `Err(DerError)` if the extension is present but cannot be
2259/// DER-decoded.
2260///
2261/// Propagating decode failure rather than treating a malformed extension as
2262/// "not a CA" is a fail-closed defense-in-depth choice: silently skipping a
2263/// malformed `BasicConstraints` could mask a topologically valid CA whose CRL
2264/// scope or path-building should be honored.
2265///
2266/// This helper is shared by `pkix-path-builder` (path construction) and
2267/// `pkix-revocation::crl` (IDP scope checking) to avoid maintaining two
2268/// parallel implementations of the same RFC 5280 §4.2.1.9 decode.
2269///
2270/// # Errors
2271///
2272/// Returns [`DerError`] if the `BasicConstraints` extension is present but
2273/// fails to DER-decode.
2274pub fn cert_is_ca(cert: &Certificate) -> core::result::Result<bool, DerError> {
2275    use der::Decode as _;
2276    use x509_cert::ext::pkix::BasicConstraints;
2277
2278    let Some(ext) = cert
2279        .tbs_certificate()
2280        .extensions()
2281        .map_or(&[][..], |v| v.as_slice())
2282        .iter()
2283        .find(|e| e.extn_id == OID_BASIC_CONSTRAINTS)
2284    else {
2285        return Ok(false);
2286    };
2287
2288    let bc = BasicConstraints::from_der(ext.extn_value.as_bytes()).map_err(DerError::new)?;
2289    Ok(bc.ca)
2290}
2291
2292/// RFC 5280 §3.3: a certificate is self-issued if subject == issuer and neither is empty.
2293fn is_self_issued_cert(cert: &Certificate) -> bool {
2294    !cert.tbs_certificate().subject().is_empty()
2295        && names_match(
2296            cert.tbs_certificate().subject(),
2297            cert.tbs_certificate().issuer(),
2298        )
2299}
2300
2301/// Returns `true` if `cert` is identified by its `SubjectAltName` rather than its
2302/// Subject DN.
2303///
2304/// RFC 5280 §4.2.1.6 specifies that a certificate with an empty Subject field and
2305/// a **critical** `SubjectAltName` extension is identified by the SAN, not the DN.
2306/// In this case, name linkage checks against the Subject DN are meaningless.
2307///
2308/// Returns `false` for any cert that has a non-empty Subject or a non-critical SAN.
2309fn cert_has_san_identity(cert: &Certificate) -> bool {
2310    // Subject must be empty.
2311    if !cert.tbs_certificate().subject().is_empty() {
2312        return false;
2313    }
2314    // Must have a critical SubjectAltName extension.
2315    cert.tbs_certificate()
2316        .extensions()
2317        .map_or(&[][..], |v| v.as_slice())
2318        .iter()
2319        .any(|ext| ext.extn_id == OID_SUBJECT_ALT_NAME && ext.critical)
2320}
2321
2322/// RFC 5280 §7.1 DN comparison, and §4.2.1.10 subtree containment.
2323///
2324/// Both functions here are private and were reached only through whole-chain
2325/// fixtures, which left several of their decisions untested — a mutation
2326/// sweep flipped the `&&` in both `names_match` AVA loops and both
2327/// comparisons in `dn_within_subtree`'s length guard, and every one
2328/// survived. Unit tests, because the inputs that distinguish these cases
2329/// are DNs no certificate generator produces on the way to anything else.
2330#[cfg(test)]
2331mod tests_dn_comparison {
2332    use super::{dn_within_subtree, names_match};
2333    use der::Decode as _;
2334    use x509_cert::name::Name;
2335
2336    // Hand-built DER. Each is a Name whose RDNs hold one PrintableString AVA.
2337    const CN_ALICE: &[u8] = &[
2338        0x30, 0x10, 0x31, 0x0e, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x05, 0x41, 0x6c,
2339        0x69, 0x63, 0x65,
2340    ];
2341    /// The same value as `CN_ALICE` under a different attribute OID
2342    /// (organizationName, 2.5.4.10).
2343    const O_ALICE: &[u8] = &[
2344        0x30, 0x10, 0x31, 0x0e, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x05, 0x41, 0x6c,
2345        0x69, 0x63, 0x65,
2346    ];
2347    const C_US: &[u8] = &[
2348        0x30, 0x0d, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53,
2349    ];
2350    const C_US_O_TEST: &[u8] = &[
2351        0x30, 0x1c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53,
2352        0x31, 0x0d, 0x30, 0x0b, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x04, 0x54, 0x65, 0x73, 0x74,
2353    ];
2354    const C_US_O_TEST_CN_ALICE: &[u8] = &[
2355        0x30, 0x2c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53,
2356        0x31, 0x0d, 0x30, 0x0b, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x04, 0x54, 0x65, 0x73, 0x74,
2357        0x31, 0x0e, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x05, 0x41, 0x6c, 0x69, 0x63,
2358        0x65,
2359    ];
2360
2361    fn n(der: &[u8]) -> Name {
2362        Name::from_der(der).expect("hand-built Name parses")
2363    }
2364
2365    /// The same value under a different attribute type is a different name.
2366    ///
2367    /// Both AVA loops in `names_match` require the OID *and* the value to
2368    /// agree. With `||` in place of either `&&`, `CN=Alice` and `O=Alice`
2369    /// compare equal — the comparison would stop distinguishing attribute
2370    /// types, and DN equality is what binds a certificate to its issuer.
2371    #[test]
2372    fn the_same_value_under_a_different_attribute_type_is_a_different_name() {
2373        assert!(names_match(&n(CN_ALICE), &n(CN_ALICE)));
2374        assert!(
2375            !names_match(&n(CN_ALICE), &n(O_ALICE)),
2376            "CN=Alice is not O=Alice"
2377        );
2378        assert!(
2379            !names_match(&n(O_ALICE), &n(CN_ALICE)),
2380            "and not in the other argument order either"
2381        );
2382    }
2383
2384    /// A DN is within the subtree rooted at itself.
2385    ///
2386    /// §4.2.1.10 containment is prefix containment, and every sequence is a
2387    /// prefix of itself. The length guard is `constraint.len() >
2388    /// subject.len()`; with `>=` an exactly-equal DN falls out as "not
2389    /// within", which breaks both directions of name constraints — a
2390    /// permitted subtree would reject the DN it names, and an excluded
2391    /// subtree would fail to exclude it.
2392    #[test]
2393    fn a_dn_is_within_the_subtree_rooted_at_itself() {
2394        assert!(dn_within_subtree(&n(C_US_O_TEST), &n(C_US_O_TEST)));
2395        assert!(dn_within_subtree(&n(C_US), &n(C_US)));
2396    }
2397
2398    /// A constraint longer than the subject contains nothing.
2399    ///
2400    /// The guard exists because the `zip` below it stops at the shorter of
2401    /// the two, so without it a deep constraint would be compared only
2402    /// against its own prefix and report a match. With `==` in place of
2403    /// `>`, `{C=US}` lands inside the subtree `{C=US, O=Test, CN=Alice}` —
2404    /// over-permissive for a permitted subtree, since a certificate would
2405    /// satisfy a constraint far more specific than its own name.
2406    #[test]
2407    fn a_constraint_longer_than_the_subject_contains_nothing() {
2408        assert!(
2409            !dn_within_subtree(&n(C_US), &n(C_US_O_TEST_CN_ALICE)),
2410            "{{C=US}} is not inside the subtree {{C=US, O=Test, CN=Alice}}"
2411        );
2412        assert!(
2413            !dn_within_subtree(&n(C_US_O_TEST), &n(C_US_O_TEST_CN_ALICE)),
2414            "one RDN short is still outside"
2415        );
2416    }
2417
2418    /// One RDN with two AVAs sharing a value under different OIDs, and one
2419    /// with a duplicated OID. RFC 5280 §5.1.2.4 says an RDN SHOULD NOT
2420    /// carry duplicate OIDs, so the second is malformed — which is exactly
2421    /// the case `names_match`'s bidirectional pass documents itself as
2422    /// handling.
2423    const CN_AND_O_ALICE: &[u8] = &[
2424        0x30, 0x1e, 0x31, 0x1c, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x05, 0x41, 0x6c,
2425        0x69, 0x63, 0x65, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x05, 0x41, 0x6c, 0x69,
2426        0x63, 0x65,
2427    ];
2428    const CN_ALICE_TWICE: &[u8] = &[
2429        0x30, 0x1e, 0x31, 0x1c, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x05, 0x41, 0x6c,
2430        0x69, 0x63, 0x65, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x05, 0x41, 0x6c, 0x69,
2431        0x63, 0x65,
2432    ];
2433
2434    /// The bidirectional AVA pass is what makes a duplicated OID safe.
2435    ///
2436    /// `{CN=Alice, O=Alice}` and `{CN=Alice, CN=Alice}` have the same RDN
2437    /// count and the same AVA count, and every AVA of the second has a
2438    /// strict match in the first — so the forward pass alone cannot tell
2439    /// them apart. Only the reverse pass can: `O=Alice` has no counterpart
2440    /// in `{CN=Alice, CN=Alice}`.
2441    ///
2442    /// Why this test rather than a simpler one: mutating the `&&` in
2443    /// *either* AVA loop to `||` leaves every other test in this crate
2444    /// green, because for well-formed RDNs the two passes are redundant and
2445    /// each catches what the other would miss. That redundancy is the
2446    /// design, and this is the input where it is load-bearing instead of
2447    /// redundant — a duplicated OID, which the loop's own comment claims to
2448    /// handle and nothing verified.
2449    #[test]
2450    fn a_duplicated_oid_does_not_match_two_distinct_attributes() {
2451        assert!(
2452            !names_match(&n(CN_AND_O_ALICE), &n(CN_ALICE_TWICE)),
2453            "{{CN=Alice, O=Alice}} is not {{CN=Alice, CN=Alice}}"
2454        );
2455        assert!(
2456            !names_match(&n(CN_ALICE_TWICE), &n(CN_AND_O_ALICE)),
2457            "and not in the other argument order, which is the pass that \
2458             catches it when the first is weakened"
2459        );
2460        // Each still matches itself, so the above cannot pass on a
2461        // comparison that never returns true for two-AVA RDNs.
2462        assert!(names_match(&n(CN_AND_O_ALICE), &n(CN_AND_O_ALICE)));
2463        assert!(names_match(&n(CN_ALICE_TWICE), &n(CN_ALICE_TWICE)));
2464    }
2465
2466    /// And the ordinary case still works: a shorter constraint is a prefix.
2467    ///
2468    /// Without this the two negative tests above would pass on a function
2469    /// that never returns `true`.
2470    #[test]
2471    fn a_shorter_constraint_contains_a_longer_subject() {
2472        assert!(dn_within_subtree(&n(C_US_O_TEST), &n(C_US)));
2473        assert!(dn_within_subtree(&n(C_US_O_TEST_CN_ALICE), &n(C_US_O_TEST)));
2474    }
2475}
2476
2477/// Compare two `AttributeTypeAndValue` values after RFC 4518 normalization.
2478///
2479/// Allocation-free: `BMPString` values are transcoded to UTF-8 lazily by
2480/// [`DirStringBytes`] while the two normalized byte streams are compared,
2481/// so the cost of one comparison is linear in the value lengths with no
2482/// heap traffic (review A1 item 10: `names_match` used to allocate two
2483/// transcoding buffers per AVA comparison).
2484fn ava_values_match(a: &der::Any, b: &der::Any) -> bool {
2485    let a_str = any_to_str_bytes(a);
2486    let b_str = any_to_str_bytes(b);
2487
2488    match (a_str, b_str) {
2489        (Some(a_bytes), Some(b_bytes)) => {
2490            NormalizedIter::new(a_bytes).eq(NormalizedIter::new(b_bytes))
2491        }
2492        // Both values are non-string types (e.g. OID, INTEGER) or unhandled string
2493        // types (TeletexString, UniversalString — UniversalString is parser-rejected
2494        // upstream by `der` 0.7's `Tag::try_from`, so this branch in practice covers
2495        // TeletexString and non-string types only):
2496        // compare tag AND content bytes (raw DER). Tag comparison ensures two
2497        // different string encodings of the same text are not considered equal.
2498        (None, None) => a.tag() == b.tag() && a.value() == b.value(),
2499        // One value is a string type and the other is not. Return false (fail-closed).
2500        // A legitimate certificate chain will never encode the same attribute OID as a
2501        // string type in one cert and a non-string type in another, so this mismatch
2502        // indicates a malformed or suspicious certificate.
2503        _ => false,
2504    }
2505}
2506
2507/// Classify a `DirectoryString` Any value as a stream of UTF-8 bytes,
2508/// returning `None` for types that require special pre-processing before
2509/// normalization (see `ava_values_match` for the dispatch logic).
2510///
2511/// The returned [`DirStringBytes`] iterator borrows the `der::Any` content
2512/// bytes; no string type allocates.
2513///
2514/// # Normalization strategy by string type
2515///
2516/// **Passed through — bytes already comparable as UTF-8/ASCII:**
2517/// `UTF8String`, `PrintableString`, `IA5String`, `VisibleString`. These
2518/// types are encoded as ASCII (or UTF-8 in the case of `UTF8String`) at
2519/// the DER level. The bytes are fed directly to `NormalizedIter`
2520/// which applies ASCII case-folding and insignificant-space handling
2521/// (RFC 4518 §2.4 step 6 subset).
2522///
2523/// **Transcoded on the fly — UCS-2-BE → UTF-8:**
2524/// `BMPString`. RFC 4518 §2.1 treats `BMPString` as "a subset of Unicode"
2525/// — every two-byte big-endian unit is a Unicode code point in the BMP.
2526/// Each unit is encoded to UTF-8 as it is consumed so the same
2527/// normalization pipeline used for `UTF8String` applies to the result.
2528/// ASCII-range code points in the BMP (U+0000..=U+007F) become
2529/// single-byte UTF-8, so a BMPString-encoded "Foo Co" compares equal to a
2530/// UTF8String-encoded "Foo Co". Malformed `BMPString` content (odd-length
2531/// bytes, or values in the surrogate range U+D800..=U+DFFF which are not
2532/// valid Unicode scalar values) is detected up front by
2533/// [`bmp_is_well_formed`] and returns `None` (fail-closed): a malformed
2534/// value will not match anything via `ava_values_match`.
2535///
2536/// **Rejected at parse time — UniversalString:**
2537/// `der` 0.7 omits tag 0x1C (`UniversalString`) from `Tag::try_from`,
2538/// causing any cert with a `UniversalString` AVA to fail
2539/// `Certificate::from_der` upstream. This dispatch therefore never sees
2540/// `UniversalString`-tagged values. Documented for completeness; a future
2541/// upstream fix in `der` (or our own pre-decode shim) is required before
2542/// `UniversalString` becomes reachable here.
2543///
2544/// **Committed policy — `TeletexString` (T61String):**
2545/// Raw DER byte comparison only. `pkix-path` deliberately does not
2546/// transcode T.61 to Unicode. RFC 4518 §2.1 states: "As there is no
2547/// standard for mapping `TeletexString` values to Unicode, the mapping is
2548/// left a local matter." RFC 5280 §7.1 classifies `TeletexString` support
2549/// as OPTIONAL. No canonical T.61→Unicode table exists — OpenSSL, NSS,
2550/// and `GnuTLS` each use incompatible vendor extensions. Adopting any one
2551/// of those tables would silently accept mismatches the others reject and
2552/// reject chains the others accept — a name-confusion smell with no
2553/// interoperability win. Byte-equality is fail-closed: two `TeletexString`
2554/// AVAs match iff their DER content bytes are identical, which is what
2555/// RFC 5280 §4.1.2.4 already requires of well-formed issuer/subject DN
2556/// reuse across a chain.
2557///
2558/// # Future work
2559///
2560/// Full RFC 4518 six-step preparation (Map → NFKC → Prohibit → `CheckBidi`
2561/// → insignificant-space) for non-ASCII Unicode code points is tracked
2562/// separately. Until that lands, two `BMPString` values that contain the
2563/// same Unicode code points but differ in canonical decomposition (e.g.
2564/// precomposed U+00E9 'é' vs decomposed U+0065 U+0301 'e'+ combining
2565/// acute) compare unequal even though RFC 4518 says they should match.
2566fn any_to_str_bytes(a: &der::Any) -> Option<DirStringBytes<'_>> {
2567    use der::Tag;
2568    match a.tag() {
2569        Tag::Utf8String | Tag::PrintableString | Tag::Ia5String | Tag::VisibleString => {
2570            Some(DirStringBytes::Plain(a.value().iter()))
2571        }
2572        // `clippy::chunks_exact_to_as_chunks` would have this be
2573        // `as_chunks::<2>().0.iter()`. Declined: this iterator is stored in
2574        // `DirStringBytes::Bmp`, so the change rewrites that variant's field
2575        // type from `ChunksExact<'_, u8>` to `slice::Iter<'_, [u8; 2]>` and
2576        // the `Iterator` impl that transcodes UCS-2 through it. That is a
2577        // real edit to DN-comparison code for a style preference, and
2578        // `bmp_is_well_formed` has already established the length is even,
2579        // which is the correctness property `as_chunks` would make visible
2580        // in the type.
2581        #[expect(
2582            clippy::chunks_exact_to_as_chunks,
2583            reason = "see the comment above; the iterator type is part of DirStringBytes"
2584        )]
2585        Tag::BmpString if bmp_is_well_formed(a.value()) => Some(DirStringBytes::Bmp {
2586            units: a.value().chunks_exact(2),
2587            buf: [0; 4],
2588            len: 0,
2589            pos: 0,
2590        }),
2591        _ => None,
2592    }
2593}
2594
2595/// Returns `true` if `bytes` is well-formed `BMPString` content: an even
2596/// number of octets (UCS-2 units are 16 bits) and no unit in the UTF-16
2597/// surrogate range U+D800..=U+DFFF. Surrogates are *reserved* by Unicode
2598/// and do not represent characters; they appear in UTF-16 only as paired
2599/// surrogates encoding supplementary-plane code points (which are
2600/// forbidden in `BMPString` by definition — `BMP` = Basic Multilingual
2601/// Plane, U+0000..=U+FFFF).
2602fn bmp_is_well_formed(bytes: &[u8]) -> bool {
2603    let (units, rest) = bytes.as_chunks::<2>();
2604    rest.is_empty() && units.iter().all(|u| !(0xD8..=0xDF).contains(&u[0]))
2605}
2606
2607/// UTF-8 byte stream over a `DirectoryString` value (see [`any_to_str_bytes`]).
2608///
2609/// The `Bmp` variant transcodes one UCS-2-BE unit at a time into `buf`
2610/// and yields its UTF-8 bytes; it must only be constructed over content
2611/// that passed [`bmp_is_well_formed`].
2612enum DirStringBytes<'a> {
2613    /// Content bytes that are already UTF-8 / ASCII.
2614    Plain(core::slice::Iter<'a, u8>),
2615    /// UCS-2-BE content, transcoded lazily.
2616    Bmp {
2617        /// Remaining two-byte units.
2618        units: core::slice::ChunksExact<'a, u8>,
2619        /// UTF-8 encoding of the current unit.
2620        buf: [u8; 4],
2621        /// Number of valid bytes in `buf`.
2622        len: u8,
2623        /// Next byte of `buf` to yield.
2624        pos: u8,
2625    },
2626}
2627
2628impl Iterator for DirStringBytes<'_> {
2629    type Item = u8;
2630    fn next(&mut self) -> Option<u8> {
2631        match self {
2632            Self::Plain(it) => it.next().copied(),
2633            Self::Bmp {
2634                units,
2635                buf,
2636                len,
2637                pos,
2638            } => {
2639                if *pos == *len {
2640                    let unit = units.next()?;
2641                    let cp = u16::from_be_bytes([unit[0], unit[1]]);
2642                    // Surrogates were rejected by `bmp_is_well_formed`; the
2643                    // fallback keeps this total without a panic path.
2644                    let ch = char::from_u32(u32::from(cp)).unwrap_or(char::REPLACEMENT_CHARACTER);
2645                    // A BMP scalar value encodes to 1..=3 UTF-8 bytes.
2646                    *len = ch.encode_utf8(buf).len() as u8;
2647                    *pos = 0;
2648                }
2649                let b = buf[usize::from(*pos)];
2650                *pos += 1;
2651                Some(b)
2652            }
2653        }
2654    }
2655}
2656
2657/// Transcode `BMPString` content to UTF-8 (test helper over [`DirStringBytes`]).
2658///
2659/// Returns `None` for malformed content (see [`bmp_is_well_formed`]).
2660#[cfg(test)]
2661fn bmp_string_to_utf8(bytes: &[u8]) -> Option<Vec<u8>> {
2662    let any = der::Any::new(der::Tag::BmpString, bytes).ok()?;
2663    any_to_str_bytes(&any).map(Iterator::collect)
2664}
2665
2666/// Compare two byte slices after RFC 4518 whitespace normalization and case-folding.
2667///
2668/// Rules applied (per RFC 4518 §2):
2669/// 1. ASCII letters (0x41–0x5A): case-fold to lowercase. Non-ASCII bytes are
2670///    passed through unchanged; full Unicode case-folding (NFKC + case-fold)
2671///    is future work.
2672/// 2. Leading/trailing spaces: ignored
2673/// 3. Internal multiple spaces: collapsed to single space
2674#[cfg(test)]
2675fn normalized_eq(a: &[u8], b: &[u8]) -> bool {
2676    NormalizedIter::new(a.iter().copied()).eq(NormalizedIter::new(b.iter().copied()))
2677}
2678
2679/// Streaming adapter that yields bytes after ASCII case-fold and whitespace
2680/// normalization (RFC 4518 §2 subset, see `normalized_eq`).
2681///
2682/// Works over any byte iterator, so `BMPString` values can be normalized
2683/// while they are being transcoded, without an intermediate buffer.
2684///
2685/// # Known limitation
2686///
2687/// Only U+0020 SPACE (byte `0x20`) is treated as insignificant whitespace.
2688/// Tabs (`\t`, `0x09`), non-breaking spaces (`0xA0` in Latin-1), and other
2689/// Unicode whitespace variants pass through unchanged. Full RFC 4518
2690/// insignificant-space handling requires Unicode-aware processing deferred
2691/// to a future release.
2692struct NormalizedIter<I: Iterator<Item = u8>> {
2693    inner: core::iter::Peekable<I>,
2694    /// Set once the first non-space byte has been yielded; spaces seen
2695    /// before that are leading spaces and are dropped.
2696    started: bool,
2697}
2698
2699impl<I: Iterator<Item = u8>> NormalizedIter<I> {
2700    fn new(bytes: I) -> Self {
2701        Self {
2702            inner: bytes.peekable(),
2703            started: false,
2704        }
2705    }
2706}
2707
2708impl<I: Iterator<Item = u8>> Iterator for NormalizedIter<I> {
2709    type Item = u8;
2710    fn next(&mut self) -> Option<u8> {
2711        loop {
2712            let b = self.inner.next()?;
2713            if b != b' ' {
2714                self.started = true;
2715                return Some(b.to_ascii_lowercase());
2716            }
2717            // Consume the rest of this space run. `next_if_eq` rather than
2718            // a peek-and-next pair: the pair's condition can be mutated
2719            // into one that consumes nothing and never ends, because
2720            // `next()` on an exhausted `Peekable` leaves `peek()` at
2721            // `None` forever. There is no such reading of this.
2722            while self.inner.next_if_eq(&b' ').is_some() {}
2723            // Leading run: drop it and continue with the first non-space byte.
2724            // Trailing run (nothing follows): drop it and end.
2725            // Internal run: collapse to exactly one space.
2726            if self.started && self.inner.peek().is_some() {
2727                return Some(b' ');
2728            }
2729        }
2730    }
2731}
2732
2733// ---------------------------------------------------------------------------
2734// NameConstraints matching (PKIX-mew)
2735// ---------------------------------------------------------------------------
2736
2737/// Newtype wrapping a bitmask of `GeneralName` name types for `NameConstraints`.
2738///
2739/// Used by `nc_constrained_types` to track which types have been constrained
2740/// by at least one CA certificate in the path, even if the intersection later
2741/// empties the permitted set for that type.
2742///
2743/// Bare `u32` constants would allow silent misuse (e.g., confusing a count
2744/// with a mask). The newtype makes the intent explicit at every operation site.
2745#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2746struct NcTypeMask(u32);
2747
2748impl NcTypeMask {
2749    const EMPTY: Self = Self(0);
2750    const RFC822: Self = Self(1 << 0);
2751    const DNS: Self = Self(1 << 1);
2752    const DIRECTORY_NAME: Self = Self(1 << 2);
2753    const URI: Self = Self(1 << 3);
2754    /// `IP_ADDRESS` is used by `name_type_bit` and participates in `nc_constrained_types`
2755    /// tracking. `IpAddress` names cannot appear in Subject DNs, so there is no
2756    /// inline DN-path code for this type; SAN `IpAddress` entries are handled by the
2757    /// generic SAN loop in `check_name_constraints` via `type_constrained(name)`.
2758    const IP_ADDRESS: Self = Self(1 << 4);
2759    /// `otherName` (any type-id). `pkix-path` cannot match otherName
2760    /// constraints; an `otherName` SAN is rejected whenever any otherName
2761    /// constraint is in effect. `SmtpUTF8Mailbox` SANs are additionally
2762    /// checked against rfc822Name constraints (RFC 8398 §6).
2763    const OTHER_NAME: Self = Self(1 << 5);
2764    /// `ediPartyName`: unsupported, fail-closed like `OTHER_NAME`.
2765    const EDI_PARTY_NAME: Self = Self(1 << 6);
2766    /// `registeredID`: unsupported, fail-closed like `OTHER_NAME`.
2767    const REGISTERED_ID: Self = Self(1 << 7);
2768
2769    /// Returns `true` if `self` and `other` share at least one bit (non-empty intersection).
2770    ///
2771    /// Named `intersects` rather than `contains` because this is a bitmask test,
2772    /// not a set-membership check — `a.intersects(b)` is symmetric, while `contains`
2773    /// implies `a ⊇ b`.
2774    const fn intersects(self, other: Self) -> bool {
2775        self.0 & other.0 != 0
2776    }
2777}
2778
2779impl core::ops::BitOr for NcTypeMask {
2780    type Output = Self;
2781    fn bitor(self, rhs: Self) -> Self {
2782        Self(self.0 | rhs.0)
2783    }
2784}
2785
2786impl core::ops::BitOrAssign for NcTypeMask {
2787    fn bitor_assign(&mut self, rhs: Self) {
2788        self.0 |= rhs.0;
2789    }
2790}
2791
2792/// Return the `NcTypeMask` bit for the name form of `name`.
2793///
2794/// Every `GeneralName` form has a bit, including the forms `pkix-path`
2795/// cannot match (`otherName`, `ediPartyName`, `registeredID`). Tracking
2796/// those lets
2797/// `check_name_constraints` reject a certificate that carries an
2798/// unsupported form a constraint applies to, as RFC 5280 §4.2.1.10
2799/// requires. `x400Address` is not representable in `x509-cert` 0.3 (a SAN
2800/// containing one fails to decode and is rejected as malformed).
2801const fn name_type_bit(name: &x509_cert::ext::pkix::name::GeneralName) -> NcTypeMask {
2802    use x509_cert::ext::pkix::name::GeneralName;
2803    match name {
2804        GeneralName::Rfc822Name(_) => NcTypeMask::RFC822,
2805        GeneralName::DnsName(_) => NcTypeMask::DNS,
2806        GeneralName::DirectoryName(_) => NcTypeMask::DIRECTORY_NAME,
2807        GeneralName::UniformResourceIdentifier(_) => NcTypeMask::URI,
2808        GeneralName::IpAddress(_) => NcTypeMask::IP_ADDRESS,
2809        GeneralName::OtherName(_) => NcTypeMask::OTHER_NAME,
2810        GeneralName::EdiPartyName(_) => NcTypeMask::EDI_PARTY_NAME,
2811        GeneralName::RegisteredId(_) => NcTypeMask::REGISTERED_ID,
2812    }
2813}
2814
2815/// Returns true if `subject` DN is within the subtree rooted at `constraint`.
2816///
2817/// RFC 5280 §4.2.1.10: a `DirectoryName` constraint is satisfied when the subject's
2818/// DN has the constraint DN as a prefix (most-general to most-specific order).
2819/// E.g., constraint `{C=US, O=Test}` matches subject `{C=US, O=Test, CN=Alice}`.
2820fn dn_within_subtree(subject: &x509_cert::name::Name, constraint: &x509_cert::name::Name) -> bool {
2821    let c_rdns = constraint.iter_rdn();
2822    let s_rdns = subject.iter_rdn();
2823    if constraint.len() > subject.len() {
2824        return false;
2825    }
2826    c_rdns.zip(s_rdns).all(|(c_rdn, s_rdn)| {
2827        // Each pair of RDNs must have matching attribute-value pairs.
2828        if c_rdn.len() != s_rdn.len() {
2829            return false;
2830        }
2831        c_rdn.iter().all(|c_ava| {
2832            s_rdn
2833                .iter()
2834                .any(|s_ava| c_ava.oid == s_ava.oid && ava_values_match(&c_ava.value, &s_ava.value))
2835        })
2836    })
2837}
2838
2839/// Returns true if `a` and `b` are the same `GeneralName` form.
2840///
2841/// Uses `name_type_bit` as the single source of truth so that adding a new
2842/// form to `name_type_bit` automatically extends this check with no
2843/// separate update required.
2844fn same_nc_variant(
2845    a: &x509_cert::ext::pkix::name::GeneralName,
2846    b: &x509_cert::ext::pkix::name::GeneralName,
2847) -> bool {
2848    name_type_bit(a) != NcTypeMask::EMPTY && name_type_bit(a) == name_type_bit(b)
2849}
2850
2851/// Returns true if `name` (a certificate's subject or SAN name) satisfies
2852/// the `subtree` constraint.
2853///
2854/// Unsupported forms never match; `check_name_constraints` rejects them
2855/// separately whenever a constraint of their form is in effect.
2856fn name_matches_subtree(
2857    name: &x509_cert::ext::pkix::name::GeneralName,
2858    subtree: &x509_cert::ext::pkix::constraints::name::GeneralSubtree,
2859) -> bool {
2860    use x509_cert::ext::pkix::name::GeneralName;
2861    match (name, &subtree.base) {
2862        (GeneralName::DnsName(subj), GeneralName::DnsName(constr)) => {
2863            matches_dns_name(subj.as_str(), constr.as_str())
2864        }
2865        (GeneralName::DirectoryName(subj), GeneralName::DirectoryName(constr)) => {
2866            dn_within_subtree(subj, constr)
2867        }
2868        (GeneralName::Rfc822Name(subj), GeneralName::Rfc822Name(constr)) => {
2869            matches_rfc822_name(subj.as_str(), constr.as_str())
2870        }
2871        (
2872            GeneralName::UniformResourceIdentifier(subj),
2873            GeneralName::UniformResourceIdentifier(constr),
2874        ) => matches_uri(subj.as_str(), constr.as_str()),
2875        (GeneralName::IpAddress(subj), GeneralName::IpAddress(constr)) => {
2876            matches_ip_address(subj.as_bytes(), constr.as_bytes())
2877        }
2878        // Mismatched variants or unhandled types: no match.
2879        _ => false,
2880    }
2881}
2882
2883/// Returns true if every name inside constraint `a` is also inside
2884/// constraint `b` (`a ⊆ b`), for two `GeneralSubtree` bases of the same form.
2885///
2886/// Used to intersect permitted subtrees (RFC 5280 §6.1.4(g)(1)) and to
2887/// de-duplicate excluded subtrees. A constraint is *not* a certificate name
2888/// (an iPAddress constraint is address + mask, a URI or rfc822Name
2889/// constraint is a bare host or `.domain`), so this cannot reuse
2890/// [`name_matches_subtree`]. Unsupported forms return `false`.
2891fn subtree_within(
2892    a: &x509_cert::ext::pkix::name::GeneralName,
2893    b: &x509_cert::ext::pkix::name::GeneralName,
2894) -> bool {
2895    use x509_cert::ext::pkix::name::GeneralName;
2896    match (a, b) {
2897        (GeneralName::DnsName(a), GeneralName::DnsName(b)) => {
2898            dns_constraint_within(a.as_str(), b.as_str())
2899        }
2900        (GeneralName::DirectoryName(a), GeneralName::DirectoryName(b)) => dn_within_subtree(a, b),
2901        (GeneralName::Rfc822Name(a), GeneralName::Rfc822Name(b)) => {
2902            rfc822_constraint_within(a.as_str(), b.as_str())
2903        }
2904        (GeneralName::UniformResourceIdentifier(a), GeneralName::UniformResourceIdentifier(b)) => {
2905            uri_constraint_within(a.as_str(), b.as_str())
2906        }
2907        (GeneralName::IpAddress(a), GeneralName::IpAddress(b)) => {
2908            ip_constraint_within(a.as_bytes(), b.as_bytes())
2909        }
2910        _ => false,
2911    }
2912}
2913
2914/// Strip one trailing `.` (the RFC 1034 absolute form) from a DNS name or
2915/// URI host.
2916///
2917/// `pkix-identity` strips the same dot when it binds a dNSName SAN to a
2918/// reference identity, so name-constraint matching must normalize
2919/// identically: otherwise `www.evil.com.` escapes an excluded `evil.com`
2920/// here yet binds to `www.evil.com` there.
2921fn strip_root_dot(s: &str) -> &str {
2922    s.strip_suffix('.').unwrap_or(s)
2923}
2924
2925/// Returns true if `name` is a proper subdomain of `parent` (one or more
2926/// labels added to the left), compared ASCII case-insensitively.
2927///
2928/// Works on bytes, so it cannot panic on a non-ASCII input.
2929fn is_strict_subdomain(name: &str, parent: &str) -> bool {
2930    let (name, parent) = (name.as_bytes(), parent.as_bytes());
2931    name.len() > parent.len() + 1
2932        && name[name.len() - parent.len() - 1] == b'.'
2933        && name[name.len() - parent.len()..].eq_ignore_ascii_case(parent)
2934}
2935
2936/// DNS name constraint matching (RFC 5280 §4.2.1.10).
2937///
2938/// - A constraint without a leading period matches the name itself and any
2939///   subdomain ("adding zero or more labels to the left-hand side").
2940/// - A constraint with a leading period (`.example.com`, a widespread
2941///   extension) matches proper subdomains only.
2942/// - The empty constraint has zero labels, so it matches every DNS name;
2943///   an empty excluded dNSName therefore forbids all DNS names, matching
2944///   OpenSSL, Go and BoringSSL.
2945/// - One trailing dot is ignored on both sides (see [`strip_root_dot`]).
2946///
2947/// Comparison is ASCII case-insensitive.
2948fn matches_dns_name(subject: &str, constraint: &str) -> bool {
2949    let subject = strip_root_dot(subject);
2950    let constraint = strip_root_dot(constraint);
2951    if constraint.is_empty() {
2952        return true;
2953    }
2954    if let Some(parent) = constraint.strip_prefix('.') {
2955        // The apex itself is excluded from a leading-period constraint.
2956        is_strict_subdomain(subject, parent)
2957    } else {
2958        subject.eq_ignore_ascii_case(constraint) || is_strict_subdomain(subject, constraint)
2959    }
2960}
2961
2962/// `a ⊆ b` for two dNSName constraints (see [`subtree_within`]).
2963///
2964/// `x` denotes `{x} ∪ subdomains(x)` and `.x` denotes `subdomains(x)`, so
2965/// `.x ⊆ b` exactly when `x` itself or every subdomain of `x` is covered,
2966/// which reduces to matching `x` against `b` with any leading period of `b`
2967/// dropped.
2968fn dns_constraint_within(a: &str, b: &str) -> bool {
2969    let a = strip_root_dot(a);
2970    match a.strip_prefix('.') {
2971        Some(a_parent) => {
2972            let b = strip_root_dot(b);
2973            matches_dns_name(a_parent, b.strip_prefix('.').unwrap_or(b))
2974        }
2975        None => matches_dns_name(a, b),
2976    }
2977}
2978
2979/// Match a mailbox's domain part against a host (`example.com`) or domain
2980/// (`.example.com`) rfc822Name constraint.
2981fn rfc822_domain_matches(domain: &str, constraint: &str) -> bool {
2982    match constraint.strip_prefix('.') {
2983        // Any host under the domain; the apex is excluded.
2984        Some(parent) => is_strict_subdomain(domain, parent),
2985        None => domain.eq_ignore_ascii_case(constraint),
2986    }
2987}
2988
2989/// RFC 822 (email) name constraint matching (RFC 5280 §4.2.1.10).
2990///
2991/// The domain part of `subject` is the text after the **last** `@`: an
2992/// RFC 5322 quoted local-part may itself contain `@`
2993/// (`"x@good.com"@evil.com` is a mailbox at `evil.com`).
2994fn matches_rfc822_name(subject: &str, constraint: &str) -> bool {
2995    if constraint.contains('@') {
2996        // Constraint is a specific mailbox address: exact match required.
2997        return subject.eq_ignore_ascii_case(constraint);
2998    }
2999    let Some((_, domain)) = subject.rsplit_once('@') else {
3000        return false; // malformed subject
3001    };
3002    rfc822_domain_matches(domain, constraint)
3003}
3004
3005/// `a ⊆ b` for two rfc822Name constraints (see [`subtree_within`]).
3006///
3007/// The three constraint shapes are a mailbox (`u@host`, one address), a
3008/// host (`host`, all mailboxes at that host) and a domain (`.domain`, all
3009/// mailboxes at any host under it).
3010fn rfc822_constraint_within(a: &str, b: &str) -> bool {
3011    if a.contains('@') {
3012        return matches_rfc822_name(a, b);
3013    }
3014    if b.contains('@') {
3015        // A host or domain is never inside a single mailbox.
3016        return false;
3017    }
3018    match (a.strip_prefix('.'), b.strip_prefix('.')) {
3019        (None, _) => rfc822_domain_matches(a, b),
3020        // Every host under a domain is never inside one host.
3021        (Some(_), None) => false,
3022        (Some(a_dom), Some(b_dom)) => {
3023            a_dom.eq_ignore_ascii_case(b_dom) || is_strict_subdomain(a_dom, b_dom)
3024        }
3025    }
3026}
3027
3028/// URI host name constraint matching (RFC 5280 §4.2.1.10).
3029///
3030/// URI constraints use different semantics from DNS constraints:
3031/// - Leading period: subdomains only (same as DNS).
3032/// - No leading period: **exact host only** (unlike DNS, which also matches subdomains).
3033///
3034/// One trailing dot is ignored on both sides (see [`strip_root_dot`]).
3035fn matches_uri_host(host: &str, constraint: &str) -> bool {
3036    let host = strip_root_dot(host);
3037    let constraint = strip_root_dot(constraint);
3038    if constraint.is_empty() {
3039        return false;
3040    }
3041    if let Some(parent) = constraint.strip_prefix('.') {
3042        // Leading dot: subdomains only, apex excluded (same rule as DNS).
3043        is_strict_subdomain(host, parent)
3044    } else {
3045        // RFC 5280 §4.2.1.10: URI constraint without leading period matches
3046        // the exact host only — subdomains are NOT included.
3047        host.eq_ignore_ascii_case(constraint)
3048    }
3049}
3050
3051/// `a ⊆ b` for two URI host constraints (see [`subtree_within`]).
3052fn uri_constraint_within(a: &str, b: &str) -> bool {
3053    let (a, b) = (strip_root_dot(a), strip_root_dot(b));
3054    match (a.strip_prefix('.'), b.strip_prefix('.')) {
3055        (None, _) => matches_uri_host(a, b),
3056        // All subdomains of a domain are never inside one exact host.
3057        (Some(_), None) => false,
3058        (Some(a_dom), Some(b_dom)) => {
3059            a_dom.eq_ignore_ascii_case(b_dom) || is_strict_subdomain(a_dom, b_dom)
3060        }
3061    }
3062}
3063
3064/// Extract the host of a URI for name-constraint matching (RFC 3986 §3.2).
3065///
3066/// Returns `None` when RFC 5280 §4.2.1.10 requires the certificate to be
3067/// rejected under a URI constraint: the URI "doesn't include an authority
3068/// component with a host name specified as a fully qualified domain name
3069/// ... or includes an authority component in which the host name is
3070/// specified as an IP address". Concretely `None` is returned for:
3071///
3072/// - no `scheme ":" "//"` prefix (e.g. `urn:`, `mailto:`), or a malformed
3073///   scheme;
3074/// - an empty host (`file:///x`);
3075/// - an IP-literal (`[2001:db8::1]`) or dotted-quad IPv4 host;
3076/// - a non-numeric port.
3077///
3078/// The authority ends at the first `/`, `?` or `#`; userinfo is everything
3079/// before the **last** `@` inside the authority, so an `@` in the path,
3080/// query or fragment cannot change the host. One trailing dot is stripped.
3081fn uri_host(uri: &str) -> Option<&str> {
3082    let (scheme, rest) = uri.split_once(':')?;
3083    let mut scheme_bytes = scheme.bytes();
3084    if !scheme_bytes.next().is_some_and(|b| b.is_ascii_alphabetic())
3085        || !scheme_bytes.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.'))
3086    {
3087        return None;
3088    }
3089    let rest = rest.strip_prefix("//")?;
3090    let authority = &rest[..rest.find(['/', '?', '#']).unwrap_or(rest.len())];
3091    let host_port = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
3092    if host_port.starts_with('[') {
3093        return None; // IP-literal
3094    }
3095    let host = match host_port.split_once(':') {
3096        Some((host, port)) if port.bytes().all(|b| b.is_ascii_digit()) => host,
3097        Some(_) => return None,
3098        None => host_port,
3099    };
3100    let host = strip_root_dot(host);
3101    if host.is_empty() || is_ipv4_literal(host) {
3102        return None;
3103    }
3104    Some(host)
3105}
3106
3107/// Returns true if `host` has the shape of an RFC 3986 `IPv4address`
3108/// (four dot-separated runs of one to three decimal digits).
3109fn is_ipv4_literal(host: &str) -> bool {
3110    let mut parts = 0usize;
3111    for part in host.split('.') {
3112        parts += 1;
3113        if part.is_empty() || part.len() > 3 || !part.bytes().all(|b| b.is_ascii_digit()) {
3114            return false;
3115        }
3116    }
3117    parts == 4
3118}
3119
3120/// URI name constraint matching (RFC 5280 §4.2.1.10).
3121///
3122/// Extracts the host with [`uri_host`] and applies URI host matching
3123/// rules. A URI without a usable host matches nothing here;
3124/// `check_name_constraints` rejects such URIs outright whenever a URI
3125/// constraint is in effect.
3126fn matches_uri(subject_uri: &str, constraint: &str) -> bool {
3127    uri_host(subject_uri).is_some_and(|host| matches_uri_host(host, constraint))
3128}
3129
3130/// IP address name constraint matching (RFC 5280 §4.2.1.10).
3131///
3132/// `constraint_bytes` must be 8 bytes (IPv4: addr + mask) or 32 bytes (IPv6).
3133/// `subject_bytes` must be 4 bytes (IPv4) or 16 bytes (IPv6).
3134fn matches_ip_address(subject_bytes: &[u8], constraint_bytes: &[u8]) -> bool {
3135    let (expected_subj_len, half) = match constraint_bytes.len() {
3136        8 => (4usize, 4usize),
3137        32 => (16usize, 16usize),
3138        _ => return false,
3139    };
3140    if subject_bytes.len() != expected_subj_len {
3141        return false;
3142    }
3143    let (addr, mask) = constraint_bytes.split_at(half);
3144    subject_bytes
3145        .iter()
3146        .zip(addr.iter().zip(mask.iter()))
3147        .all(|(s, (a, m))| s & m == a & m)
3148}
3149
3150/// `a ⊆ b` for two iPAddress constraints (address + mask, see
3151/// [`subtree_within`]): same address family, `b`'s mask bits are a subset
3152/// of `a`'s, and the two addresses agree under `b`'s mask.
3153fn ip_constraint_within(a: &[u8], b: &[u8]) -> bool {
3154    if a.len() != b.len() || !(a.len() == 8 || a.len() == 32) {
3155        return false;
3156    }
3157    let half = a.len() / 2;
3158    let (a_addr, a_mask) = a.split_at(half);
3159    let (b_addr, b_mask) = b.split_at(half);
3160    (0..half).all(|i| {
3161        a_mask[i] & b_mask[i] == b_mask[i] && a_addr[i] & b_mask[i] == b_addr[i] & b_mask[i]
3162    })
3163}
3164
3165/// RFC 5280 §4.2.1.10 subtree containment for the non-`directoryName` name
3166/// forms.
3167///
3168/// These are pure functions over strings and byte slices, and a mutation
3169/// sweep found every one of them unguarded: the suite reached them only
3170/// through whole-chain fixtures, which never supply the degenerate inputs
3171/// that separate a correct comparison from a nearly-correct one.
3172#[cfg(test)]
3173mod tests_constraint_forms {
3174    use super::{
3175        ip_constraint_within, is_ipv4_literal, is_strict_subdomain, matches_ip_address,
3176        subtree_within, uri_constraint_within,
3177    };
3178    use der::Decode as _;
3179    use x509_cert::ext::pkix::name::GeneralName;
3180
3181    /// `.example.com` is not a *strict* subdomain of `example.com`.
3182    ///
3183    /// A strict subdomain adds at least one label, so the shortest one is
3184    /// `a.example.com`. The guard is `name.len() > parent.len() + 1`, and
3185    /// both of its obvious weakenings admit this degenerate input: `>=`
3186    /// directly, and `*` in place of `+` because `parent.len() * 1` is
3187    /// `parent.len()`. The leading dot then satisfies the separator check
3188    /// and the suffix compares equal, so a bare `.example.com` would be
3189    /// reported as a subdomain of itself-with-a-dot.
3190    #[test]
3191    fn a_leading_dot_alone_is_not_a_strict_subdomain() {
3192        assert!(!is_strict_subdomain(".example.com", "example.com"));
3193        // The real thing still is.
3194        assert!(is_strict_subdomain("a.example.com", "example.com"));
3195        assert!(is_strict_subdomain("deep.a.example.com", "example.com"));
3196        // And a sibling that merely ends in the same bytes is not.
3197        assert!(!is_strict_subdomain("notexample.com", "example.com"));
3198    }
3199
3200    /// A URI subtree contains itself.
3201    ///
3202    /// Both arms are `Some`, so the comparison is
3203    /// `equal || is_strict_subdomain`. With `&&` a domain would have to be a
3204    /// strict subdomain of itself, which nothing is, and a constraint would
3205    /// stop containing its own subtree.
3206    #[test]
3207    fn a_uri_subtree_contains_itself_and_its_subdomains() {
3208        assert!(uri_constraint_within(".example.com", ".example.com"));
3209        assert!(uri_constraint_within(".a.example.com", ".example.com"));
3210        assert!(!uri_constraint_within(".example.com", ".a.example.com"));
3211    }
3212
3213    /// `is_ipv4_literal` rejects an empty label and an over-long one.
3214    ///
3215    /// The three conditions are joined by `||`, so turning either into `&&`
3216    /// makes one of them reachable only together with the next: an empty
3217    /// label stops being rejected, or a four-digit label does.
3218    #[test]
3219    fn an_ipv4_literal_needs_one_to_three_digits_per_label() {
3220        assert!(is_ipv4_literal("192.0.2.1"));
3221        assert!(
3222            !is_ipv4_literal("1..2.3"),
3223            "an empty label is not a digit run"
3224        );
3225        assert!(
3226            !is_ipv4_literal("1234.1.1.1"),
3227            "four digits is outside one-to-three, all-digits notwithstanding"
3228        );
3229        assert!(!is_ipv4_literal("a.b.c.d"));
3230    }
3231
3232    /// `matches_ip_address` handles IPv6 constraints, not only IPv4.
3233    ///
3234    /// The length match has an arm for 8 bytes (IPv4 address + mask) and one
3235    /// for 32 (IPv6). Deleting the 32-byte arm sends every IPv6 constraint
3236    /// to `_ => return false`, so an excluded IPv6 subtree would stop
3237    /// excluding and a permitted one would stop permitting.
3238    #[test]
3239    fn an_ipv6_constraint_is_matched() {
3240        // 2001:db8::/32 as constraint (16 address + 16 mask), subject
3241        // 2001:db8::1.
3242        let mut constraint = [0u8; 32];
3243        constraint[0..4].copy_from_slice(&[0x20, 0x01, 0x0d, 0xb8]);
3244        constraint[16..20].copy_from_slice(&[0xff, 0xff, 0xff, 0xff]);
3245        let mut subject = [0u8; 16];
3246        subject[0..4].copy_from_slice(&[0x20, 0x01, 0x0d, 0xb8]);
3247        subject[15] = 1;
3248        assert!(matches_ip_address(&subject, &constraint));
3249
3250        // Outside the prefix.
3251        let mut other = [0u8; 16];
3252        other[0..4].copy_from_slice(&[0x20, 0x01, 0x0d, 0xb9]);
3253        assert!(!matches_ip_address(&other, &constraint));
3254
3255        // IPv4 still works, so this is about the arm and not the function.
3256        let v4_constraint = [192, 0, 2, 0, 255, 255, 255, 0];
3257        assert!(matches_ip_address(&[192, 0, 2, 7], &v4_constraint));
3258        assert!(!matches_ip_address(&[192, 0, 3, 7], &v4_constraint));
3259    }
3260
3261    /// `ip_constraint_within` accepts both lengths it documents.
3262    ///
3263    /// The guard is `a.len() != b.len() || !(a.len() == 8 || a.len() == 32)`.
3264    /// Either comparison flipped to `!=` turns the negation into a refusal
3265    /// of exactly the family that comparison names, so both families are
3266    /// here: 8 bytes is the IPv4 case the function is most used for, and 32
3267    /// the IPv6 one, where the refusal would be silent because an
3268    /// `ip_constraint_within` that answers `false` reports "not contained"
3269    /// rather than "could not tell".
3270    #[test]
3271    fn an_ip_constraint_is_within_a_shorter_prefix_of_either_family() {
3272        // 192.0.2.0/24 inside 192.0.0.0/16: b's mask bits are a subset of
3273        // a's, and the addresses agree under b's mask.
3274        let a = [192, 0, 2, 0, 255, 255, 255, 0];
3275        let b = [192, 0, 0, 0, 255, 255, 0, 0];
3276        assert!(ip_constraint_within(&a, &b));
3277        assert!(!ip_constraint_within(&b, &a), "the wider one is not inside");
3278
3279        // 2001:db8:1::/48 inside 2001:db8::/32, the same relation in the
3280        // 32-byte form.
3281        let mut a6 = [0u8; 32];
3282        a6[..6].copy_from_slice(&[0x20, 0x01, 0x0d, 0xb8, 0x00, 0x01]);
3283        a6[16..22].copy_from_slice(&[0xff; 6]);
3284        let mut b6 = [0u8; 32];
3285        b6[..4].copy_from_slice(&[0x20, 0x01, 0x0d, 0xb8]);
3286        b6[16..20].copy_from_slice(&[0xff; 4]);
3287        assert!(ip_constraint_within(&a6, &b6));
3288        assert!(
3289            !ip_constraint_within(&b6, &a6),
3290            "the wider one is not inside"
3291        );
3292
3293        // Mismatched family lengths are not comparable.
3294        let v6 = [0u8; 32];
3295        assert!(!ip_constraint_within(&a, &v6));
3296    }
3297
3298    /// Only 8 and 32 bytes are iPAddress *constraints*.
3299    ///
3300    /// A 16-byte value is a bare IPv6 address with no mask, and a 4-byte
3301    /// one a bare IPv4 address. Accepted, the function would read the
3302    /// second half of the value as the mask: two all-zero 16-byte blobs
3303    /// would then contain each other, which is the widest possible
3304    /// subtree. The guard refuses them, and the length it rejects them for
3305    /// is why both `== 8` and `== 32` have to be comparisons against the
3306    /// lengths they name.
3307    #[test]
3308    fn an_address_without_a_mask_is_not_a_constraint() {
3309        fn refused<const N: usize>() {
3310            let bare = [0u8; N];
3311            assert!(
3312                !ip_constraint_within(&bare, &bare),
3313                "{N} bytes is not an address-plus-mask constraint"
3314            );
3315        }
3316        refused::<0>();
3317        refused::<4>();
3318        refused::<16>();
3319        refused::<17>();
3320        refused::<64>();
3321    }
3322
3323    /// `subtree_within` routes two `directoryName`s to the DN comparison.
3324    ///
3325    /// Deleting that match arm sends them to the catch-all, so a
3326    /// `directoryName` constraint would stop containing anything — including
3327    /// itself.
3328    #[test]
3329    fn two_directory_names_are_compared_as_dns() {
3330        // C=US  and  C=US,O=Test
3331        const C_US: &[u8] = &[
3332            0x30, 0x0d, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55,
3333            0x53,
3334        ];
3335        const C_US_O_TEST: &[u8] = &[
3336            0x30, 0x1c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55,
3337            0x53, 0x31, 0x0d, 0x30, 0x0b, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x04, 0x54, 0x65,
3338            0x73, 0x74,
3339        ];
3340        let dn = |der: &[u8]| {
3341            GeneralName::DirectoryName(
3342                x509_cert::name::Name::from_der(der).expect("hand-built Name parses"),
3343            )
3344        };
3345
3346        assert!(subtree_within(&dn(C_US_O_TEST), &dn(C_US)));
3347        assert!(subtree_within(&dn(C_US), &dn(C_US)));
3348        assert!(!subtree_within(&dn(C_US), &dn(C_US_O_TEST)));
3349    }
3350}
3351
3352// ---------------------------------------------------------------------------
3353// RSA key size helper (PKIX-ken.1.5)
3354// ---------------------------------------------------------------------------
3355
3356use verifiers::{OID_RSASSA_PSS, OID_RSA_ENCRYPTION};
3357
3358/// Decode the RSA modulus from an SPKI and return its bit length.
3359///
3360/// Both `rsaEncryption` and `id-RSASSA-PSS` subject keys count as RSA: RFC
3361/// 4055 §1.2 encodes the public key identically (`RSAPublicKey`) under
3362/// either OID, and only the algorithm-identifier parameters differ.
3363///
3364/// Returns `None` when:
3365/// - the key algorithm OID is neither `rsaEncryption` nor `id-RSASSA-PSS`
3366///   (non-RSA key; check does not apply), or
3367/// - the SPKI bytes cannot be decoded (malformed; signature verification will also fail).
3368///
3369/// Uses `der::SliceReader` and `der::asn1::UintRef` from the existing `der`
3370/// dependency — no additional crate required.
3371///
3372/// `RSAPublicKey ::= SEQUENCE { modulus INTEGER, publicExponent INTEGER }` (RFC 3279 §2.3.1).
3373/// `UintRef::as_bytes()` strips the leading 0x00 sign byte from a DER unsigned INTEGER,
3374/// returning only the magnitude. Bit length is derived as `magnitude_bytes * 8`, which
3375/// over-counts by at most 7 bits for keys whose high magnitude byte has leading zero bits —
3376/// this lenient rounding is acceptable for a minimum-floor check: a real 2040-bit key
3377/// would measure as 2048 bits and pass a 2048-bit floor. Key-generation tools always
3378/// produce keys whose top bit is set, so the practical impact is zero.
3379fn rsa_public_key_bits(spki: &spki::SubjectPublicKeyInfoOwned) -> Option<u32> {
3380    use der::{asn1::UintRef, Reader};
3381
3382    if spki.algorithm.oid != OID_RSA_ENCRYPTION && spki.algorithm.oid != OID_RSASSA_PSS {
3383        return None; // Non-RSA key: check does not apply.
3384    }
3385    // BitString::as_bytes() returns None when unused_bits != 0.
3386    // RSA SPKI subject_public_key is always octet-aligned (unused_bits = 0).
3387    let raw = spki.subject_public_key.as_bytes()?;
3388
3389    // raw is a DER-encoded RSAPublicKey SEQUENCE.
3390    // RSAPublicKey ::= SEQUENCE { modulus INTEGER, publicExponent INTEGER }
3391    //
3392    // We decode the modulus INTEGER and then skip the publicExponent so the
3393    // sequence reader does not complain about trailing data (der 0.7 requires
3394    // the closure to consume the entire SEQUENCE content).
3395    //
3396    // Skip strategy: read the modulus, then call tlv_bytes() to consume the
3397    // exponent TLV as a raw byte slice (no allocation, no decode required).
3398    let modulus_byte_len: usize = der::SliceReader::new(raw)
3399        .ok()?
3400        .sequence(|r| {
3401            // UintRef strips the leading 0x00 sign byte; as_bytes() returns magnitude only.
3402            let modulus: UintRef<'_> = r.decode()?;
3403            let modulus_len = modulus.as_bytes().len();
3404            // Consume the publicExponent TLV so the nested reader has no trailing data.
3405            let _ = r.tlv_bytes()?;
3406            Ok::<_, der::Error>(modulus_len)
3407        })
3408        .ok()?;
3409
3410    // saturating_mul guards against overflow on a hypothetical absurdly large modulus.
3411    // The result fits in u32: the largest practical RSA key is 16384 bits (2048 bytes),
3412    // well within u32::MAX. u32::try_from is used to make the bound explicit.
3413    u32::try_from(modulus_byte_len.saturating_mul(8)).ok()
3414}
3415
3416// ---------------------------------------------------------------------------
3417// Chain walk loop — signature verification and name linkage (PKIX-vxf)
3418// ---------------------------------------------------------------------------
3419
3420/// Walk the chain from issuer to leaf, applying all RFC 5280 §6.1 per-cert checks.
3421///
3422/// Path-length and anchor-matching are handled by the caller (`validate_path`).
3423/// This function walks `chain` in reverse (issuer-to-leaf) against `anchor`:
3424///
3425///    a. Verify signature with the current issuer's SPKI.
3426///    b. Verify issuer/subject name linkage.
3427///    c. Check validity period against `policy.current_time_unix`.
3428///    d. Reject any unhandled critical extensions.
3429///    e. Check cert names (subject DN + SAN) against accumulated NC state.
3430///    f. For all certs except the leaf (i > 0): require `BasicConstraints` cA=TRUE.
3431///    g. For all certs except the leaf (i > 0): if `policy.enforce_key_usage`, require `keyCertSign`.
3432///    g'. For all certs except the leaf (i > 0): if `policy.require_crl_sign_on_cas`, require `cRLSign`.
3433///    h. For all certs except the leaf (i > 0): enforce `pathLenConstraint` if present.
3434///    i. For all certs except the leaf (i > 0): accumulate `NameConstraints` state
3435///       (INTERSECTION for permittedSubtrees, UNION for excludedSubtrees).
3436///
3437/// RFC 5280 §4.2.1.9 note on pathLenConstraint: for the cert at position `i`
3438/// (leaf at 0, root-adjacent at chain.len()-1), there are exactly `i-1`
3439/// intermediate certs below it. The constraint requires `i-1 ≤ pathLenConstraint`.
3440///
3441/// # Implementation notes
3442///
3443/// This function is intentionally structured as a single loop over the certificate
3444/// chain. The RFC 5280 §6.1 state machine has significant shared state (working
3445/// SPKI, name constraints, policy tree, inhibit flags) that must be threaded
3446/// through every step in a defined order. Decomposing the loop into smaller helpers
3447/// would require passing this state through many function boundaries without clarity
3448/// gain. The monolithic structure mirrors the RFC's sequential algorithm description
3449/// and keeps all state-mutation sites visible in one place for audit.
3450///
3451/// The per-walk mutable state is grouped into [`WorkingState`] to make the
3452/// state-machine inputs/outputs explicit at the call boundary. Future
3453/// per-substep helper extractions take a `&mut WorkingState` so that adding
3454/// helpers does not grow each helper's parameter list.
3455///
3456/// `working_spki` and `working_issuer_name` carry the borrow of either `anchor`
3457/// or some `chain[i]` and so the struct takes a single lifetime `'a` covering
3458/// both inputs. The lifetime is elided at the call site because `chain_walk`
3459/// constructs and consumes `WorkingState` within its own body.
3460///
3461/// RFC 5280 §6.1.2 maps to the struct fields as follows:
3462///
3463/// - `working_spki`, `working_issuer_name`, `working_issuer_is_san_identity`
3464///   — §6.1.2(d)/(f) `working_public_key` + §6.1.2(e) `working_issuer_name`,
3465///   plus the §4.2.1.6 SAN-identity escape hatch tracked separately so the
3466///   §6.1.3(a)(2) DN-linkage check can be skipped when the issuer's identity
3467///   came from a critical SAN over an empty Subject DN.
3468/// - `nc_permitted`, `nc_excluded`, `nc_constrained_types`
3469///   — §6.1.2(b)/(c) `permitted_subtrees`/`excluded_subtrees`. The
3470///   `nc_constrained_types` bitmask is a workspace addition: it tracks which
3471///   name types have *ever* been constrained by a CA so an empty post-
3472///   intersection set still rejects names of that type (not derivable from
3473///   `nc_permitted` contents alone).
3474/// - `explicit_policy`, `inhibit_any`, `policy_mapping`
3475///   — §6.1.2 `explicit_policy`, `inhibit_anyPolicy`, `policy_mapping` counters.
3476/// - `policy_tree`
3477///   — §6.1.2(a) `valid_policy_tree`. `None` represents the RFC NULL tree.
3478struct WorkingState<'a> {
3479    /// §6.1.2(d)/(f) `working_public_key`. Borrows from the trust anchor or a
3480    /// chain certificate; rebound to the just-validated cert's SPKI at the end
3481    /// of every loop iteration.
3482    working_spki: &'a spki::SubjectPublicKeyInfoOwned,
3483    /// §6.1.2(e) `working_issuer_name`. Borrows from the trust anchor or a
3484    /// chain certificate's subject; rebound at the end of every loop iteration.
3485    working_issuer_name: &'a x509_cert::name::Name,
3486    /// Whether the certificate that produced `working_issuer_name` identifies
3487    /// itself via a critical `SubjectAltName` over an empty Subject DN
3488    /// (RFC 5280 §4.2.1.6). When `true`, the §6.1.3(a)(2) DN-linkage check is
3489    /// skipped because comparing against an empty Subject would be meaningless;
3490    /// the §6.1.3(a)(1) signature check has already established the
3491    /// cryptographic binding.
3492    working_issuer_is_san_identity: bool,
3493    /// §6.1.2(b) `permitted_subtrees`. `None` means "no permitted constraint
3494    /// of any type has been imposed yet"; once any CA contributes a
3495    /// `permittedSubtrees`, this becomes `Some(...)` and only narrows
3496    /// (intersection per §6.1.4(g)).
3497    nc_permitted: Option<GeneralSubtrees>,
3498    /// §6.1.2(c) `excluded_subtrees`. Accumulates via union per §6.1.4(g).
3499    nc_excluded: GeneralSubtrees,
3500    /// Workspace-local invariant: bitmask of name types for which at least one
3501    /// CA has imposed a `permittedSubtrees` constraint. Bits are only ORed in,
3502    /// never cleared. Required for correct rejection when intersection of
3503    /// incompatible same-type constraints empties `nc_permitted` for a type
3504    /// while that type is still semantically forbidden. See the initialisation
3505    /// site in `chain_walk` for the long-form rationale.
3506    nc_constrained_types: NcTypeMask,
3507    /// §6.1.2 `explicit_policy` counter. Decremented by §6.1.4(h) on each
3508    /// non-self-issued intermediate; clamped by §6.1.4(i) PolicyConstraints
3509    /// `requireExplicitPolicy`; finalised by §6.1.5(a)+(b).
3510    explicit_policy: u32,
3511    /// §6.1.2 `inhibit_anyPolicy` counter. Decremented by §6.1.4(h);
3512    /// clamped by §6.1.4(j) `InhibitAnyPolicy`.
3513    inhibit_any: u32,
3514    /// §6.1.2 `policy_mapping` counter. Decremented by §6.1.4(h);
3515    /// clamped by §6.1.4(i) PolicyConstraints `inhibitPolicyMapping`.
3516    policy_mapping: u32,
3517    /// §6.1.2(a) `valid_policy_tree`. `None` represents the RFC's NULL tree
3518    /// (every transition that would empty the tree maps to `None`); a
3519    /// non-empty `Some(...)` carries the live policy graph. Returned to
3520    /// `validate_path` at §6.1.5 for post-validation qualifier extraction.
3521    policy_tree: Option<policy_graph::PolicyGraph>,
3522}
3523
3524/// RFC 5280 §6.1.3(a)(1) preface — project-policy signature-algorithm allowlist.
3525///
3526/// Fires before the cryptographic signature check so that a chain whose only
3527/// problem is a disallowed algorithm returns the diagnostic
3528/// [`Error::AlgorithmNotAllowed`] rather than the confusing
3529/// [`Error::SignatureInvalid`]. Applies to every cert in the chain (CA/B Forum
3530/// profile intent — there is no leaf/intermediate distinction here). Uses the
3531/// outer `signatureAlgorithm` OID; RFC 5280 §4.1.1.2 requires it to equal the
3532/// inner `TBSCertificate.signature` OID.
3533fn enforce_signature_alg_allowlist(
3534    cert: &Certificate,
3535    policy: &ValidationPolicy,
3536    index: usize,
3537) -> Result<()> {
3538    if let Some(allowed) = &policy.allowed_signature_algs {
3539        // O(n) over a typically 2–6 element list; acceptable for the common case.
3540        if !allowed.contains(&cert.signature_algorithm().oid) {
3541            return Err(Error::AlgorithmNotAllowed { index });
3542        }
3543    }
3544    Ok(())
3545}
3546
3547/// Project max-validity check.
3548///
3549/// Not part of RFC 5280 §6.1; this is a CA/B-Forum-style ceiling on the cert's
3550/// (notAfter − notBefore) duration. Applies to every cert in the chain.
3551///
3552/// `saturating_sub` avoids wrap on a malformed cert where `notAfter < notBefore`;
3553/// a resulting duration of 0 trivially passes the `> max_secs` test (safe — the
3554/// validity-period check in §6.1.3(a)(2) catches the malformed cert separately).
3555fn check_max_validity(cert: &Certificate, policy: &ValidationPolicy, index: usize) -> Result<()> {
3556    if let Some(max_secs) = policy.max_validity_secs {
3557        let not_before = cert
3558            .tbs_certificate()
3559            .validity()
3560            .not_before
3561            .to_unix_duration()
3562            .as_secs();
3563        let not_after = cert
3564            .tbs_certificate()
3565            .validity()
3566            .not_after
3567            .to_unix_duration()
3568            .as_secs();
3569        if not_after.saturating_sub(not_before) > max_secs {
3570            return Err(Error::ValidityPeriodExceedsMax { index });
3571        }
3572    }
3573    Ok(())
3574}
3575
3576/// Project minimum-RSA-key-bits check.
3577///
3578/// Not part of RFC 5280 §6.1; a deployment-policy floor on RSA modulus size.
3579/// Non-RSA keys are silently skipped (`rsa_public_key_bits` returns `None`),
3580/// so this is RSA-specific and inert for ECDSA/EdDSA chains. Applies to every
3581/// cert in the chain.
3582fn check_min_rsa_bits(cert: &Certificate, policy: &ValidationPolicy, index: usize) -> Result<()> {
3583    if let Some(min_bits) = policy.min_rsa_key_bits {
3584        if let Some(actual_bits) =
3585            rsa_public_key_bits(cert.tbs_certificate().subject_public_key_info())
3586        {
3587            if actual_bits < min_bits {
3588                return Err(Error::KeyTooSmall { index });
3589            }
3590        }
3591        // Non-RSA keys: rsa_public_key_bits returns None → check silently skipped.
3592    }
3593    Ok(())
3594}
3595
3596/// RFC 5280 §6.1.3(a)(2) — issuer/subject DN linkage with §4.2.1.6 SAN-identity exception.
3597///
3598/// Verifies that the cert's issuer DN matches the previously-validated cert's
3599/// (or trust anchor's) subject DN, unless that subject DN was empty and the
3600/// previous cert identified itself via a critical SubjectAltName (RFC 5280
3601/// §4.2.1.6). In the SAN-identity case the DN comparison is skipped because
3602/// comparing against an empty Subject is meaningless; the signature check in
3603/// §6.1.3(a)(1) has already established the cryptographic binding.
3604///
3605/// IMPORTANT (PKIX-als9 design §7): the *assignment* of
3606/// `working_issuer_is_san_identity` for the next iteration is the caller's
3607/// responsibility (see chain_walk's end-of-loop state update). Moving the
3608/// assignment into this helper would silently break the §4.2.1.6 exception
3609/// for chains where an intermediate (not the leaf) uses SAN identity, a case
3610/// PKITS does not cover.
3611fn check_issuer_linkage(
3612    cert: &Certificate,
3613    working_issuer_name: &x509_cert::name::Name,
3614    working_issuer_is_san_identity: bool,
3615    index: usize,
3616) -> Result<()> {
3617    if !working_issuer_is_san_identity
3618        && !names_match(working_issuer_name, cert.tbs_certificate().issuer())
3619    {
3620        return Err(Error::ChainBroken { index });
3621    }
3622    Ok(())
3623}
3624
3625/// Returns the DER encoding of `cert`'s `TBSCertificate`: the bytes its
3626/// issuer signed.
3627///
3628/// Use this, not `cert.tbs_certificate().to_der()`, to verify a
3629/// certificate signature. x509-cert 0.3 re-encodes the validity times of a
3630/// `Certificate` under the RFC 5280 profile (dates before 2050 become
3631/// `UTCTime`), so a certificate whose issuer used `GeneralizedTime` for such a
3632/// date would no longer match its signature. This function keeps each time
3633/// in the form it was parsed from; every other field is re-encoded as DER,
3634/// which reproduces the original bytes for any DER-encoded certificate.
3635///
3636/// # Errors
3637///
3638/// Returns [`DerError`] if a field cannot be encoded.
3639pub fn tbs_certificate_der(cert: &Certificate) -> core::result::Result<Vec<u8>, DerError> {
3640    encode_tbs_certificate(cert.tbs_certificate(), cert.tbs_certificate().extensions())
3641        .map_err(DerError::new)
3642}
3643
3644/// Encodes `tbs` with `extensions` in place of its own extensions and with
3645/// its validity times as parsed (see [`tbs_certificate_der`]).
3646///
3647/// `pkix-ct` uses the `extensions` override to rebuild a precertificate's
3648/// TBS without the SCT list (RFC 6962 §3.2).
3649#[doc(hidden)]
3650pub fn encode_tbs_certificate(
3651    tbs: &x509_cert::TbsCertificate,
3652    extensions: Option<&x509_cert::ext::Extensions>,
3653) -> der::Result<Vec<u8>> {
3654    use der::asn1::ContextSpecificRef;
3655    use der::{Encode as _, Header, Length, Tag, TagMode, TagNumber};
3656
3657    fn push_sequence(out: &mut Vec<u8>, body: &[u8]) -> der::Result<()> {
3658        Header::new(Tag::Sequence, Length::try_from(body.len())?).encode_to_vec(out)?;
3659        out.extend_from_slice(body);
3660        Ok(())
3661    }
3662
3663    let mut body = Vec::new();
3664    if tbs.version() != x509_cert::certificate::Version::V1 {
3665        ContextSpecificRef {
3666            tag_number: TagNumber(0),
3667            tag_mode: TagMode::Explicit,
3668            value: &tbs.version(),
3669        }
3670        .encode_to_vec(&mut body)?;
3671    }
3672    tbs.serial_number().encode_to_vec(&mut body)?;
3673    tbs.signature().encode_to_vec(&mut body)?;
3674    tbs.issuer().encode_to_vec(&mut body)?;
3675    let mut validity = Vec::new();
3676    tbs.validity().not_before.encode_to_vec(&mut validity)?;
3677    tbs.validity().not_after.encode_to_vec(&mut validity)?;
3678    push_sequence(&mut body, &validity)?;
3679    tbs.subject().encode_to_vec(&mut body)?;
3680    tbs.subject_public_key_info().encode_to_vec(&mut body)?;
3681    if let Some(id) = tbs.issuer_unique_id() {
3682        ContextSpecificRef {
3683            tag_number: TagNumber(1),
3684            tag_mode: TagMode::Implicit,
3685            value: id,
3686        }
3687        .encode_to_vec(&mut body)?;
3688    }
3689    if let Some(id) = tbs.subject_unique_id() {
3690        ContextSpecificRef {
3691            tag_number: TagNumber(2),
3692            tag_mode: TagMode::Implicit,
3693            value: id,
3694        }
3695        .encode_to_vec(&mut body)?;
3696    }
3697    if let Some(exts) = extensions {
3698        ContextSpecificRef {
3699            tag_number: TagNumber(3),
3700            tag_mode: TagMode::Explicit,
3701            value: exts,
3702        }
3703        .encode_to_vec(&mut body)?;
3704    }
3705    let mut out = Vec::with_capacity(body.len() + 6);
3706    push_sequence(&mut out, &body)?;
3707    Ok(out)
3708}
3709
3710/// RFC 5280 §6.1.3(a)(1) — cryptographic signature verification.
3711///
3712/// Re-encodes the cert's TBSCertificate (the canonical signed bytes) and asks
3713/// the pluggable [`SignatureVerifier`] to verify the cert's `signature` field
3714/// against the current `working_spki` (the previously-validated issuer's
3715/// public key). Returns [`Error::SignatureInvalid`] on failure.
3716///
3717/// Uses heap-backed encoding (`alloc::vec`) so that large certificates
3718/// (government, enterprise, HSM attestation certs > 8 KiB TBSCertificate)
3719/// encode without a fixed-buffer limit; the only `Error::Der` failure mode is
3720/// a genuine DER encoding error in a malformed certificate.
3721///
3722/// Does NOT update `working_spki` — that next-iteration state transition is
3723/// the caller's responsibility (chain_walk binds it at the end of each loop
3724/// iteration).
3725fn verify_cert_signature<V: SignatureVerifier>(
3726    cert: &Certificate,
3727    working_spki: &spki::SubjectPublicKeyInfoOwned,
3728    verifier: &V,
3729    index: usize,
3730) -> Result<()> {
3731    use spki::der::referenced::OwnedToRef as _;
3732    let tbs_bytes_owned =
3733        encode_tbs_certificate(cert.tbs_certificate(), cert.tbs_certificate().extensions())
3734            .map_err(|e| Error::Der(DerError::new(e)))?;
3735    let tbs_bytes: &[u8] = &tbs_bytes_owned;
3736    verifier
3737        .verify_signature(
3738            cert.signature_algorithm().owned_to_ref(),
3739            working_spki.owned_to_ref(),
3740            tbs_bytes,
3741            cert.signature().raw_bytes(),
3742        )
3743        .map_err(|e| match e.kind() {
3744            VerificationErrorKind::InvalidSignature => Error::SignatureInvalid { index },
3745            reason => Error::SignatureNotVerified { index, reason },
3746        })?;
3747    Ok(())
3748}
3749
3750fn chain_walk<V: SignatureVerifier>(
3751    chain: &[Certificate],
3752    anchor: &TrustAnchor,
3753    policy: &ValidationPolicy,
3754    verifier: &V,
3755) -> Result<Option<policy_graph::PolicyGraph>> {
3756    use x509_cert::ext::pkix::{InhibitAnyPolicy, PolicyConstraints, PolicyMappings};
3757
3758    // RFC 5280 §6.1.2 (b)+(c): seed the initial permitted/excluded subtrees
3759    // from the trust anchor. These initial constraints apply to ALL certs in
3760    // the chain (including intermediates), not just to leaves — the chain walk
3761    // enforces them from the first certificate onward.
3762    let (initial_nc_permitted, initial_nc_excluded) = match &anchor.name_constraints {
3763        None => (None, GeneralSubtrees::default()),
3764        Some(nc) => (
3765            // Clone necessary: nc_permitted and nc_excluded are mutated during the walk.
3766            nc.permitted_subtrees.clone(),
3767            nc.excluded_subtrees.clone().unwrap_or_default(),
3768        ),
3769    };
3770    // Bitmask of NcTypeMask bits for name types that have been explicitly
3771    // constrained by at least one permittedSubtrees entry in any CA cert seen so far.
3772    // Needed to detect violations when intersection empties the permitted set
3773    // for a type (e.g., two incompatible DN constraints → empty, but DN still forbidden).
3774    //
3775    // INVARIANT: bits are ORed in and never cleared. Once a type bit is set,
3776    // nc_permitted must contain zero entries of that type to represent "empty
3777    // intersection" (all names of that type are forbidden). Do NOT derive
3778    // "is type constrained?" from nc_permitted contents alone — that would
3779    // silently allow names of a type whose permitted set was emptied by
3780    // conflicting CA constraints.
3781    let initial_nc_constrained_types: NcTypeMask =
3782        initial_nc_permitted
3783            .as_ref()
3784            .map_or(NcTypeMask::EMPTY, |permitted| {
3785                let mut bits = NcTypeMask::EMPTY;
3786                for st in permitted {
3787                    bits |= name_type_bit(&st.base);
3788                }
3789                bits
3790            });
3791
3792    // RFC 5280 §6.1.2: initialise policy state variables (PKIX-mi3.3).
3793    //
3794    // The counters represent "skip N more non-self-issued certificates before
3795    // the constraint activates".  Setting a counter to `n + 1` means the
3796    // constraint never triggers unless a CA certificate forces it lower.
3797    let n = chain.len();
3798    // Convert n (usize) to u32 safely. Chains with >4 billion certs are not
3799    // realistic, but a truncating cast would produce a wrong counter value.
3800    // u32::MAX is safe: counters are only decremented (saturating), so u32::MAX
3801    // behaves identically to any value > the chain length for these semantics.
3802    let n_u32 = u32::try_from(n).unwrap_or(u32::MAX);
3803    let initial_explicit_policy: u32 = if policy.initial_explicit_policy {
3804        0
3805    } else {
3806        n_u32.saturating_add(1)
3807    };
3808    let initial_inhibit_any: u32 = if policy.initial_any_policy_inhibit {
3809        0
3810    } else {
3811        n_u32.saturating_add(1)
3812    };
3813    let initial_policy_mapping: u32 = if policy.initial_policy_mapping_inhibit {
3814        0
3815    } else {
3816        n_u32.saturating_add(1)
3817    };
3818
3819    // Group all per-walk mutable state into a single `WorkingState` for clarity
3820    // at the call boundaries of the per-substep helpers introduced in
3821    // subsequent commits.
3822    let mut state = WorkingState {
3823        working_spki: &anchor.subject_public_key_info,
3824        working_issuer_name: &anchor.subject,
3825        // RFC 5280 §4.2.1.6: when a CA cert has an empty Subject DN and a critical
3826        // SubjectAltName, the SAN is the cert's identity — the Subject DN is not used
3827        // for name matching. Track whether the current issuer was set from such a cert
3828        // so we can skip the DN linkage check below.
3829        working_issuer_is_san_identity: false,
3830        nc_permitted: initial_nc_permitted,
3831        nc_excluded: initial_nc_excluded,
3832        nc_constrained_types: initial_nc_constrained_types,
3833        explicit_policy: initial_explicit_policy,
3834        inhibit_any: initial_inhibit_any,
3835        policy_mapping: initial_policy_mapping,
3836        // §6.1.2(a): initial valid_policy_tree — single anyPolicy root node.
3837        policy_tree: Some(policy_graph::PolicyGraph::new()),
3838    };
3839
3840    for i in (0..chain.len()).rev() {
3841        let cert = &chain[i];
3842
3843        // (a0) Signature algorithm allowlist check (extracted to helper for
3844        //      readability; see `enforce_signature_alg_allowlist`).
3845        enforce_signature_alg_allowlist(cert, policy, i)?;
3846
3847        // (a) §6.1.3(a)(1) signature verification (extracted; see `verify_cert_signature`).
3848        verify_cert_signature(cert, state.working_spki, verifier, i)?;
3849
3850        // (b) §6.1.3(a)(2) issuer DN linkage (extracted; see `check_issuer_linkage`).
3851        //     NOTE: the `working_issuer_is_san_identity` assignment for the next
3852        //     iteration is updated at the end-of-loop state block below (PKIX-als9
3853        //     design §7 — must stay in chain_walk to preserve §4.2.1.6 handling
3854        //     across multi-intermediate chains).
3855        check_issuer_linkage(
3856            cert,
3857            state.working_issuer_name,
3858            state.working_issuer_is_san_identity,
3859            i,
3860        )?;
3861
3862        // (c) Validity period.
3863        check_validity(cert, policy.current_time_unix, i)?;
3864
3865        // (c2) Max validity period length check (extracted; see `check_max_validity`).
3866        check_max_validity(cert, policy, i)?;
3867
3868        // (c3) Minimum RSA key size check (extracted; see `check_min_rsa_bits`).
3869        check_min_rsa_bits(cert, policy, i)?;
3870
3871        // (d) Duplicate- and critical-extension guards. Duplicates are
3872        //     rejected first: every extension lookup below reads only the
3873        //     first instance of an OID.
3874        check_duplicate_extensions(cert, i)?;
3875        check_critical_extensions(cert, i)?;
3876
3877        // Decode the cert's CertificatePolicies extension once per cert.
3878        // Used in both step (d) (policy tree update) and step (a/b) (PolicyMappings
3879        // anyPolicy qualifier lookup).  Decoding here avoids a second parse inside
3880        // the mapping loop (b5r.12).
3881        // try_find_cert_ext (fail-closed): a malformed CertificatePolicies must
3882        // cause rejection rather than being silently treated as absent; silently
3883        // dropping it would leave the policy tree in an incorrect state (vjc.21).
3884        let cert_cp: Option<x509_cert::ext::pkix::certpolicy::CertificatePolicies> =
3885            try_find_cert_ext(cert, OID_CERTIFICATE_POLICIES)
3886                .map_err(|_| Error::MalformedCertificate { index: i })?;
3887
3888        // (policy-d) CertificatePolicies extension (RFC 5280 §6.1.3(d)/(e)).
3889        // Only processed while the policy graph is still alive.
3890        if let Some(graph) = &mut state.policy_tree {
3891            let became_null = match &cert_cp {
3892                Some(cp_ext) => {
3893                    // §6.1.3(d)(2) condition: inhibit_anyPolicy > 0, or a
3894                    // self-issued certificate other than the leaf.
3895                    let may_expand = state.inhibit_any > 0 || (i > 0 && is_self_issued_cert(cert));
3896                    graph.add_certificate_policies(cp_ext, may_expand)
3897                }
3898                // §6.1.3(e): CertificatePolicies absent → NULL.
3899                None => true,
3900            };
3901            if became_null {
3902                state.policy_tree = None;
3903            }
3904        }
3905
3906        // (policy-f) RFC 5280 §6.1.3(f): explicit_policy == 0 and tree NULL
3907        // → policy violation.
3908        if state.explicit_policy == 0 && state.policy_tree.is_none() {
3909            return Err(Error::PolicyViolation { index: i });
3910        }
3911
3912        // Decode SAN once per cert: used in both the NC name check (e) and
3913        // potentially cached for the NC state update (i). Avoids scanning the
3914        // extension list twice per cert when both checks are active (vjc.13).
3915        // Fail-closed: a malformed SAN returns MalformedCertificate (vjc.20).
3916        let san = cert_subject_alt_names(cert, i)?;
3917
3918        // (e) NameConstraints: check this cert's names against accumulated state.
3919        // RFC 5280 §6.1.3(b): self-issued non-leaf certs are exempt from NC name checking.
3920        // The NC state is still updated from their extensions in step (i).
3921        if i == 0 || !is_self_issued_cert(cert) {
3922            check_name_constraints(
3923                cert,
3924                san.as_ref(),
3925                state.nc_permitted.as_ref(),
3926                &state.nc_excluded,
3927                state.nc_constrained_types,
3928                i,
3929            )?;
3930        }
3931
3932        // (e2) Require non-empty SubjectAltName on leaf cert.
3933        //      Only when require_subject_alt_name is set; intermediate CA certs
3934        //      are NOT checked (i == 0 guard). The `san` variable is decoded above
3935        //      and is already available — no second extension scan needed.
3936        if i == 0 && policy.require_subject_alt_name {
3937            // san is None if the extension is absent; Some(v) where v.0 may be empty.
3938            let san_is_nonempty = san.as_ref().is_some_and(|s| !s.0.is_empty());
3939            if !san_is_nonempty {
3940                return Err(Error::MissingSan);
3941            }
3942        }
3943
3944        // (e3) Required leaf EKU OID check.
3945        //      Only when required_leaf_eku is Some; only on the leaf (i == 0).
3946        //      Uses try_find_cert_ext (fail-closed): malformed EKU DER on the leaf
3947        //      is mapped to MalformedCertificate rather than silently ignored.
3948        //      anyExtendedKeyUsage (OID 2.5.29.37.0) does NOT satisfy a specific
3949        //      OID requirement — only explicit listing in the cert's EKU counts.
3950        if i == 0 {
3951            if let Some(required_ekus) = &policy.required_leaf_eku {
3952                use x509_cert::ext::pkix::ExtendedKeyUsage;
3953                match try_find_cert_ext::<ExtendedKeyUsage>(cert, OID_EXTENDED_KEY_USAGE)
3954                    .map_err(|_| Error::MalformedCertificate { index: 0 })?
3955                {
3956                    None => {
3957                        // EKU extension absent; any non-empty requirement fails.
3958                        if !required_ekus.is_empty() {
3959                            return Err(Error::MissingEku);
3960                        }
3961                    }
3962                    Some(eku) => {
3963                        for req_oid in required_ekus {
3964                            if !eku.0.iter().any(|e| e == req_oid) {
3965                                return Err(Error::MissingEku);
3966                            }
3967                        }
3968                    }
3969                }
3970            }
3971        }
3972
3973        // (e3a) Required leaf CertificatePolicies OID check.
3974        //       Only when required_leaf_policy_oids is Some; only on the leaf
3975        //       (i == 0). Reuses `cert_cp` decoded above. `anyPolicy`
3976        //       (2.5.29.32.0) does NOT satisfy a specific OID requirement —
3977        //       only explicit listing in the cert's CertificatePolicies counts.
3978        //       Mirrors the (e3) EKU pattern.
3979        if i == 0 {
3980            if let Some(required_policy_oids) = &policy.required_leaf_policy_oids {
3981                match &cert_cp {
3982                    None => {
3983                        // CertificatePolicies extension absent; any non-empty
3984                        // requirement fails.
3985                        if let Some(first) = required_policy_oids.first() {
3986                            return Err(Error::MissingLeafPolicyOid { required: *first });
3987                        }
3988                    }
3989                    Some(cp_ext) => {
3990                        for req_oid in required_policy_oids {
3991                            if !cp_ext.0.iter().any(|pi| pi.policy_identifier == *req_oid) {
3992                                return Err(Error::MissingLeafPolicyOid { required: *req_oid });
3993                            }
3994                        }
3995                    }
3996                }
3997            }
3998        }
3999
4000        // (e3b) Required Subject DN attribute rule check.
4001        //       Only when required_leaf_subject_dn_attrs is Some; only on the
4002        //       leaf (i == 0). See [`DnAttrRule`] for the expression grammar
4003        //       and vacuity rules.
4004        if i == 0 {
4005            if let Some(dn_rule) = &policy.required_leaf_subject_dn_attrs {
4006                if !evaluate_dn_attr_rule(cert.tbs_certificate().subject(), dn_rule) {
4007                    return Err(Error::SubjectDnAttrRuleUnmet);
4008                }
4009            }
4010        }
4011
4012        // (e4) If require_rfc822_san is set, at least one rfc822Name entry must
4013        //      be present in the leaf's SAN extension.
4014        //      Only meaningful (and checked) when require_subject_alt_name is also
4015        //      true; the non-empty SAN check above (e2) already guards the absent
4016        //      / empty SAN case. EKU is checked first (e3) so that a cert with both
4017        //      wrong EKU and wrong SAN type reports MissingEku (more actionable).
4018        if i == 0 && policy.require_subject_alt_name && policy.require_rfc822_san {
4019            use x509_cert::ext::pkix::name::GeneralName;
4020            let has_rfc822 = san.as_ref().is_some_and(|s| {
4021                s.0.iter()
4022                    .any(|name| matches!(name, GeneralName::Rfc822Name(_)))
4023            });
4024            if !has_rfc822 {
4025                return Err(Error::MissingRfc822San);
4026            }
4027        }
4028
4029        // (f–h) CA-only checks: apply to every cert except the leaf (chain[0]).
4030        //        This includes any intermediate CAs and the root CA cert if it
4031        //        is included in the chain rather than supplied only as an anchor.
4032        if i > 0 {
4033            // (f) BasicConstraints cA=TRUE required; (h) pathLenConstraint.
4034            // Decode BasicConstraints once for both checks.
4035            //
4036            // Fail-closed: if the extension is structurally present but DER-malformed
4037            // on an intermediate CA, propagate MalformedCertificate rather than
4038            // treating it as absent (which would fall through to NotCA and hide the
4039            // real structural problem).
4040            let bc = try_find_cert_ext::<x509_cert::ext::pkix::BasicConstraints>(
4041                cert,
4042                OID_BASIC_CONSTRAINTS,
4043            )
4044            .map_err(|_| Error::MalformedCertificate { index: i })?;
4045            if !bc.as_ref().is_some_and(|b| b.ca) {
4046                return Err(Error::NotCA { index: i });
4047            }
4048
4049            // (g) KeyUsage keyCertSign required (when policy demands it).
4050            // RFC 5280 §6.1.4(n): "If a KeyUsage extension is present, verify that the
4051            // keyCertSign bit is set."  Only reject when KeyUsage IS present (Some(_)) and
4052            // keyCertSign is NOT set (== Some(false)).  Absent KeyUsage (None) is allowed.
4053            // has_key_cert_sign is fail-closed: a malformed critical KeyUsage returns
4054            // MalformedCertificate rather than being silently treated as absent (vjc.15).
4055            if policy.enforce_key_usage
4056                && has_key_cert_sign(cert).map_err(|_| Error::MalformedCertificate { index: i })?
4057                    == Some(false)
4058            {
4059                return Err(Error::KeyUsageMissing { index: i });
4060            }
4061
4062            // (g') KeyUsage cRLSign required (opt-in via require_crl_sign_on_cas).
4063            // RFC 5280 §6.1 does NOT require this check; it is a stricter policy
4064            // motivated by PKITS §4.7.4 / §4.7.5, which treat a CA cert without
4065            // cRLSign as unable to revoke certs it issued and therefore invalid.
4066            // Same fail-closed and absent-KeyUsage semantics as keyCertSign above.
4067            // Independent of `enforce_key_usage`: callers can opt into cRLSign
4068            // enforcement without also enabling keyCertSign enforcement, and
4069            // vice versa.
4070            if policy.require_crl_sign_on_cas
4071                && has_crl_sign(cert).map_err(|_| Error::MalformedCertificate { index: i })?
4072                    == Some(false)
4073            {
4074                return Err(Error::CrlSignMissing { index: i });
4075            }
4076
4077            // (h) pathLenConstraint: count only non-self-issued intermediates below position i
4078            // (RFC 5280 §4.2.1.9: "non-self-issued intermediate certificates").
4079            // chain[1..i] = the intermediate positions between the leaf (0) and this cert (i).
4080            if let Some(path_len) = bc.and_then(|b| b.path_len_constraint) {
4081                let effective_depth = chain[1..i]
4082                    .iter()
4083                    .filter(|c| !is_self_issued_cert(c))
4084                    .count();
4085                if effective_depth > path_len as usize {
4086                    return Err(Error::PathTooLong);
4087                }
4088            }
4089
4090            // (policy-a) PolicyMappings (RFC 5280 §6.1.4(a)): anyPolicy must
4091            // not appear on either side of a mapping.
4092            // (policy-b) Apply mappings to the tree or delete mapped nodes.
4093            // NOTE: Policy mappings use the current policy_mapping counter value
4094            // (before decrement); the decrement happens in §6.1.4(h) below.
4095            // try_find_cert_ext (fail-closed): a malformed PolicyMappings extension
4096            // must cause rejection rather than silent ignore; a silently-discarded
4097            // mapping could allow a policy bypass (e.g., inhibit_policy_mapping bypass).
4098            if let Some(pm) = try_find_cert_ext::<PolicyMappings>(cert, OID_POLICY_MAPPINGS)
4099                .map_err(|_| Error::MalformedCertificate { index: i })?
4100            {
4101                // §6.1.4(a): reject anyPolicy as issuer or subject domain.
4102                for mapping in &pm.0 {
4103                    if mapping.issuer_domain_policy == OID_ANY_POLICY
4104                        || mapping.subject_domain_policy == OID_ANY_POLICY
4105                    {
4106                        return Err(Error::PolicyViolation { index: i });
4107                    }
4108                }
4109
4110                // §6.1.4(b)(1) if policy_mapping > 0, else §6.1.4(b)(2).
4111                if let Some(graph) = &mut state.policy_tree {
4112                    // §6.1.4(b)(1) synthesized nodes take the qualifiers of
4113                    // this certificate's anyPolicy entry (none if it has no
4114                    // certificatePolicies, in which case the graph is
4115                    // already NULL and this branch is not reached).
4116                    let ap_q = cert_cp
4117                        .as_ref()
4118                        .map(policy_graph::any_policy_qualifiers)
4119                        .unwrap_or_default();
4120                    if graph.apply_policy_mappings(&pm, state.policy_mapping > 0, &ap_q) {
4121                        state.policy_tree = None;
4122                    }
4123                }
4124            }
4125
4126            // (policy-h) RFC 5280 §6.1.4(h): decrement policy counters for
4127            // non-self-issued intermediate certificates.
4128            // This happens AFTER policy mappings processing (§6.1.4(b)) and
4129            // BEFORE clamping from extensions (§6.1.4(i)/(j)).
4130            if !is_self_issued_cert(cert) {
4131                state.explicit_policy = state.explicit_policy.saturating_sub(1);
4132                state.policy_mapping = state.policy_mapping.saturating_sub(1);
4133                state.inhibit_any = state.inhibit_any.saturating_sub(1);
4134            }
4135
4136            // (policy-i) PolicyConstraints (RFC 5280 §6.1.4(c)): clamp
4137            // explicit_policy and policy_mapping from the extension.
4138            // try_find_cert_ext (fail-closed): malformed PolicyConstraints must reject;
4139            // silently ignoring it could allow explicit_policy bypass.
4140            if let Some(pc) = try_find_cert_ext::<PolicyConstraints>(cert, OID_POLICY_CONSTRAINTS)
4141                .map_err(|_| Error::MalformedCertificate { index: i })?
4142            {
4143                if let Some(req) = pc.require_explicit_policy {
4144                    state.explicit_policy = state.explicit_policy.min(req);
4145                }
4146                if let Some(ipm) = pc.inhibit_policy_mapping {
4147                    state.policy_mapping = state.policy_mapping.min(ipm);
4148                }
4149            }
4150
4151            // (policy-j) InhibitAnyPolicy (RFC 5280 §6.1.4(d)): clamp inhibit_any.
4152            // try_find_cert_ext (fail-closed): malformed InhibitAnyPolicy must reject;
4153            // silently ignoring it could allow anyPolicy through when it should be inhibited.
4154            if let Some(iap) = try_find_cert_ext::<InhibitAnyPolicy>(cert, OID_INHIBIT_ANY_POLICY)
4155                .map_err(|_| Error::MalformedCertificate { index: i })?
4156            {
4157                state.inhibit_any = state.inhibit_any.min(iap.0);
4158            }
4159
4160            // (i) NC update: NameConstraints state update (RFC 5280 §6.1.4(b)).
4161            //     INTERSECTION for permitted, UNION for excluded.
4162            //     cert_name_constraints is fail-closed: a malformed or non-conformant
4163            //     NC extension (e.g., non-zero minimum/maximum) returns MalformedCertificate
4164            //     rather than silently ignoring the constraints (vjc.7, vjc.8).
4165            if let Some(nc) = cert_name_constraints(cert, i)? {
4166                // permittedSubtrees: intersect with current state.
4167                if let Some(new_permitted) = nc.permitted_subtrees {
4168                    // Track which types this CA is constraining.
4169                    for entry in &new_permitted {
4170                        state.nc_constrained_types |= name_type_bit(&entry.base);
4171                    }
4172                    match state.nc_permitted.as_mut() {
4173                        None => {
4174                            // First constraint seen; adopt it directly.
4175                            state.nc_permitted = Some(new_permitted);
4176                        }
4177                        Some(current) => {
4178                            // Type-aware intersection of two permitted-subtrees sets.
4179                            //
4180                            // RFC 5280 §6.1.4(b): intersect entry-by-entry, but only
4181                            // compare entries of the SAME name type. Entries of types
4182                            // not present in new_permitted are unchanged (new doesn't
4183                            // constrain that type). Entries of types not in current
4184                            // are added directly (new adds a fresh constraint).
4185                            //
4186                            // For entries of matching type, keep:
4187                            //   1. new entries within (⊆) some same-type current entry.
4188                            //   2. current entries within (⊆) some same-type new entry.
4189                            // Containment is decided by `subtree_within`, which
4190                            // compares two constraints (address+mask, bare host,
4191                            // `.domain`) rather than treating one as a cert name.
4192                            // (If neither is within the other the intersection for that
4193                            // type is empty — tracked via nc_constrained_types.)
4194                            let mut result = GeneralSubtrees::default();
4195
4196                            // For each new entry, pre-filter current entries of the
4197                            // same type to avoid calling same_nc_variant twice per
4198                            // pair (vjc.16: duplicated guard + containment check).
4199                            for n in &new_permitted {
4200                                let same_type_in_current: GeneralSubtrees = current
4201                                    .iter()
4202                                    .filter(|c| same_nc_variant(&c.base, &n.base))
4203                                    .cloned()
4204                                    .collect();
4205                                if same_type_in_current.is_empty() {
4206                                    // Type not previously constrained → add directly.
4207                                    result.push(n.clone());
4208                                } else if same_type_in_current
4209                                    .iter()
4210                                    .any(|c| subtree_within(&n.base, &c.base))
4211                                {
4212                                    // n is within some same-type current entry → keep.
4213                                    result.push(n.clone());
4214                                }
4215                                // else: n is not within any current entry of same type → drop.
4216                            }
4217
4218                            for c in current.iter() {
4219                                let same_type_in_new: GeneralSubtrees = new_permitted
4220                                    .iter()
4221                                    .filter(|n| same_nc_variant(&n.base, &c.base))
4222                                    .cloned()
4223                                    .collect();
4224                                if same_type_in_new.is_empty() {
4225                                    // Type not in new_permitted → keep unchanged.
4226                                    result.push(c.clone());
4227                                } else if same_type_in_new
4228                                    .iter()
4229                                    .any(|n| subtree_within(&c.base, &n.base))
4230                                {
4231                                    // c is more specific than some new entry; keep unless
4232                                    // an equivalent entry is already in result (dedup
4233                                    // within the result set for this type).
4234                                    let same_type_in_result: &[_] = result.as_slice();
4235                                    let already_in_result = same_type_in_result.iter().any(|e| {
4236                                        same_nc_variant(&e.base, &c.base)
4237                                            && subtree_within(&e.base, &c.base)
4238                                            && subtree_within(&c.base, &e.base)
4239                                    });
4240                                    if !already_in_result {
4241                                        result.push(c.clone());
4242                                    }
4243                                }
4244                                // else: c is not within any new entry of same type → drop.
4245                            }
4246
4247                            *current = result;
4248                        }
4249                    }
4250                }
4251                // excludedSubtrees: union — append only entries not already present,
4252                // avoiding monotonic growth that would make per-cert NC checks O(chain²)
4253                // when the same excluded subtrees are repeated across multiple CAs (vjc.12).
4254                if let Some(new_excluded) = nc.excluded_subtrees {
4255                    for new_entry in &new_excluded {
4256                        // Deduplication uses subtree_within as a two-way equality
4257                        // check: two entries are considered the same subtree when each
4258                        // contains the other (i.e., they are semantically equivalent, not
4259                        // just byte-equal).
4260                        let already_present = state.nc_excluded.iter().any(|existing| {
4261                            same_nc_variant(&existing.base, &new_entry.base)
4262                                && subtree_within(&existing.base, &new_entry.base)
4263                                && subtree_within(&new_entry.base, &existing.base)
4264                        });
4265                        if !already_present {
4266                            state.nc_excluded.push(new_entry.clone());
4267                        }
4268                    }
4269                }
4270            }
4271        }
4272
4273        // Update state for next iteration.
4274        state.working_spki = cert.tbs_certificate().subject_public_key_info();
4275        state.working_issuer_name = cert.tbs_certificate().subject();
4276        // Determine whether the cert we just processed presents itself via SAN
4277        // identity (empty Subject + critical SAN). This affects the chain-linkage
4278        // check for the certificate immediately below it in the next iteration.
4279        state.working_issuer_is_san_identity = cert_has_san_identity(cert);
4280    }
4281
4282    // RFC 5280 §6.1.5(a-b): post-loop leaf policy finalisation.
4283    //
4284    // §6.1.5 is a post-loop step in the RFC.  These operations apply only to
4285    // the leaf certificate (chain[0]), which was the last iteration (i == 0).
4286    // Placing them here rather than inside the loop at i == 0 matches the RFC
4287    // section numbering and makes clear that they happen after all per-cert
4288    // §6.1.3/§6.1.4 steps have completed.
4289    {
4290        let leaf = &chain[0];
4291        // §6.1.5(a): if the leaf is not self-issued, decrement counters.
4292        // inhibit_any and policy_mapping are decremented per RFC 5280 §6.1.5(a)
4293        // but are not used after this point in the algorithm — only explicit_policy
4294        // is tested in §6.1.5(g) and the final check.
4295        if !is_self_issued_cert(leaf) {
4296            state.explicit_policy = state.explicit_policy.saturating_sub(1);
4297            // Per §6.1.5(a): RFC also decrements inhibit_any and policy_mapping here,
4298            // but neither is read after §6.1.5(a) in our implementation.
4299        }
4300        // §6.1.5(b): if PolicyConstraints requireExplicitPolicy == 0,
4301        // force explicit_policy to 0.
4302        // try_find_cert_ext (fail-closed): consistent with per-loop treatment of
4303        // PolicyConstraints; a malformed extension on the leaf must also reject.
4304        if let Some(pc) = try_find_cert_ext::<PolicyConstraints>(leaf, OID_POLICY_CONSTRAINTS)
4305            .map_err(|_| Error::MalformedCertificate { index: 0 })?
4306        {
4307            if let Some(req) = pc.require_explicit_policy {
4308                state.explicit_policy = state.explicit_policy.min(req);
4309            }
4310        }
4311    }
4312
4313    // RFC 5280 §6.1.5(g): intersect the valid_policy_graph with the
4314    // user-initial-policy-set.
4315    //
4316    // (g)(i): a NULL graph stays NULL. (g)(ii): an empty set (this crate's
4317    // spelling of the default) or any set containing anyPolicy is
4318    // any-policy, and the intersection is the whole graph. (g)(iii)
4319    // otherwise.
4320    if !policy.initial_policy_set.is_empty() && !policy.initial_policy_set.contains(&OID_ANY_POLICY)
4321    {
4322        if let Some(graph) = &mut state.policy_tree {
4323            if graph.intersect_user_policy_set(&policy.initial_policy_set) {
4324                state.policy_tree = None;
4325            }
4326        }
4327    }
4328
4329    // §6.1.5 final check: path is valid iff explicit_policy > 0 OR tree
4330    // is non-NULL.
4331    if state.explicit_policy == 0 && state.policy_tree.is_none() {
4332        return Err(Error::PolicyViolation { index: 0 });
4333    }
4334
4335    // Return the final valid_policy_tree to `validate_path` so it can be
4336    // surfaced on `ValidatedPath` for post-validation qualifier extraction.
4337    // `None` propagates through unchanged when the tree was reduced to NULL
4338    // during validation; callers that rely on §6.1.5 outputs MUST treat
4339    // `None` as "no policy information available", not as a validation
4340    // failure (the policy-success check above already happened).
4341    Ok(state.policy_tree)
4342}
4343
4344// ---------------------------------------------------------------------------
4345// NameConstraints enforcement (PKIX-xji)
4346// ---------------------------------------------------------------------------
4347
4348/// Whether a name-constraint check requires a match (permitted) or forbids a
4349/// match (excluded).
4350///
4351/// Using an explicit enum instead of a bare `bool` makes call sites
4352/// self-documenting: `CheckMode::Excluded` / `CheckMode::Permitted` vs
4353/// opaque `false` / `true` (vjc.25).
4354#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4355enum CheckMode {
4356    /// Excluded subtrees: any name that matches is a violation.
4357    Excluded,
4358    /// Permitted subtrees: a constrained name type that matches *no* entry is a violation.
4359    Permitted,
4360}
4361
4362/// Check the cert's subject DN against `subtrees` in the given `mode`.
4363///
4364/// Skipped entirely when the subject DN is empty (RFC 5280 §6.1.3(b)).
4365///
4366/// Avoids constructing a `GeneralName::DirectoryName` (which would require a
4367/// clone) by handling `DirectoryName` constraints inline: pull `DirectoryName`
4368/// entries from `subtrees` and test directly against the subject `Name`
4369/// (vjc.24).
4370///
4371/// - `CheckMode::Excluded`: any DN match is a violation.
4372/// - `CheckMode::Permitted`: only enforced if some CA in the path has
4373///   contributed a `DirectoryName` permitted-subtree (tracked in
4374///   `nc_constrained_types`); then a non-match is a violation.
4375fn check_subject_dn_against_subtrees(
4376    subject: &x509_cert::name::Name,
4377    subject_is_empty: bool,
4378    subtrees: &[x509_cert::ext::pkix::constraints::name::GeneralSubtree],
4379    mode: CheckMode,
4380    nc_constrained_types: NcTypeMask,
4381    index: usize,
4382) -> crate::Result<()> {
4383    use x509_cert::ext::pkix::name::GeneralName;
4384
4385    if subject_is_empty {
4386        return Ok(());
4387    }
4388    let subject_constrained = nc_constrained_types.intersects(NcTypeMask::DIRECTORY_NAME);
4389    let dn_matches_any = subtrees.iter().any(|st| {
4390        if let GeneralName::DirectoryName(constr) = &st.base {
4391            dn_within_subtree(subject, constr)
4392        } else {
4393            false
4394        }
4395    });
4396    match mode {
4397        CheckMode::Excluded => {
4398            if dn_matches_any {
4399                return Err(Error::NameConstraintViolation { index });
4400            }
4401        }
4402        CheckMode::Permitted => {
4403            if subject_constrained && !dn_matches_any {
4404                return Err(Error::NameConstraintViolation { index });
4405            }
4406        }
4407    }
4408    Ok(())
4409}
4410
4411/// Check each SAN entry of the cert against `subtrees` in the given `mode`.
4412///
4413/// - `CheckMode::Excluded`: any SAN entry that matches any subtree is a
4414///   violation.
4415/// - `CheckMode::Permitted`: a SAN entry whose type has been constrained
4416///   somewhere in the path (per `nc_constrained_types`) must match at least
4417///   one subtree entry; unconstrained types are accepted.
4418///
4419/// A `None` SAN extension is a no-op.
4420fn check_san_against_subtrees(
4421    san: Option<&x509_cert::ext::pkix::SubjectAltName>,
4422    subtrees: &[x509_cert::ext::pkix::constraints::name::GeneralSubtree],
4423    mode: CheckMode,
4424    nc_constrained_types: NcTypeMask,
4425    index: usize,
4426) -> crate::Result<()> {
4427    use x509_cert::ext::pkix::name::GeneralName;
4428
4429    let Some(san_ext) = san else {
4430        return Ok(());
4431    };
4432    let type_constrained =
4433        |name: &GeneralName| -> bool { nc_constrained_types.intersects(name_type_bit(name)) };
4434
4435    for name in &san_ext.0 {
4436        match mode {
4437            CheckMode::Excluded => {
4438                if subtrees.iter().any(|st| name_matches_subtree(name, st)) {
4439                    return Err(Error::NameConstraintViolation { index });
4440                }
4441            }
4442            CheckMode::Permitted => {
4443                if type_constrained(name)
4444                    && !subtrees.iter().any(|st| name_matches_subtree(name, st))
4445                {
4446                    return Err(Error::NameConstraintViolation { index });
4447                }
4448            }
4449        }
4450    }
4451    Ok(())
4452}
4453
4454/// Check that all names in `cert` satisfy the current `NameConstraints` state.
4455///
4456/// Called once per certificate during `chain_walk`, BEFORE updating the NC
4457/// state from that certificate's own `NameConstraints` extension.
4458///
4459/// `san` is the pre-decoded `SubjectAltName` for this cert (pass `None` if the
4460/// extension is absent). Decoding it before the call avoids a second scan of
4461/// the extension list when both NC check and NC update are needed (vjc.13).
4462///
4463/// RFC 5280 §6.1.4(b)(1)–(2): check excluded subtrees first, then
4464/// permitted subtrees.
4465fn check_name_constraints(
4466    cert: &x509_cert::Certificate,
4467    san: Option<&x509_cert::ext::pkix::SubjectAltName>,
4468    nc_permitted: Option<&GeneralSubtrees>,
4469    nc_excluded: &GeneralSubtrees,
4470    nc_constrained_types: NcTypeMask,
4471    index: usize,
4472) -> crate::Result<()> {
4473    let subject = cert.tbs_certificate().subject();
4474    let subject_is_empty = subject.is_empty();
4475
4476    // Dispatch the subject DN and the SAN entries against `subtrees` in the
4477    // requested mode. See `check_subject_dn_against_subtrees` and
4478    // `check_san_against_subtrees` for the per-name-class logic.
4479    let check_names = |subtrees: &[x509_cert::ext::pkix::constraints::name::GeneralSubtree],
4480                       mode: CheckMode|
4481     -> crate::Result<()> {
4482        check_subject_dn_against_subtrees(
4483            subject,
4484            subject_is_empty,
4485            subtrees,
4486            mode,
4487            nc_constrained_types,
4488            index,
4489        )?;
4490        check_san_against_subtrees(san, subtrees, mode, nc_constrained_types, index)?;
4491        Ok(())
4492    };
4493
4494    // (0) Name forms the generic matchers cannot decide. A form is "in
4495    //     effect" when some permitted subtree of that form has been seen in
4496    //     the path (`nc_constrained_types`, which survives an emptied
4497    //     intersection) or the excluded set holds an entry of that form.
4498    let excluded_forms = nc_excluded
4499        .iter()
4500        .fold(NcTypeMask::EMPTY, |m, st| m | name_type_bit(&st.base));
4501    let forms_in_effect = nc_constrained_types | excluded_forms;
4502    let rfc822_permitted_active = nc_constrained_types.intersects(NcTypeMask::RFC822);
4503    if let Some(san_ext) = san {
4504        for name in &san_ext.0 {
4505            check_san_name_form(
4506                name,
4507                forms_in_effect,
4508                nc_permitted,
4509                nc_excluded,
4510                rfc822_permitted_active,
4511                index,
4512            )?;
4513        }
4514    }
4515
4516    // (1) Excluded check: any excluded subtree match → violation.
4517    check_names(nc_excluded.as_slice(), CheckMode::Excluded)?;
4518
4519    // (2) Permitted check: if permitted set is constrained, every name must
4520    //     match at least one permitted subtree.
4521    if let Some(permitted) = nc_permitted {
4522        check_names(permitted.as_slice(), CheckMode::Permitted)?;
4523    }
4524
4525    // (3) RFC 5280 §4.2.1.10: emailAddress attributes in the subject DN MUST
4526    //     be checked against the rfc822Name constraint.
4527    //     Guard: only enter the RDN walk if RFC822 constraints are actually
4528    //     in effect — a permitted RFC822 entry has been seen, OR at least one
4529    //     excluded entry is an Rfc822Name (vjc.11).
4530    if forms_in_effect.intersects(NcTypeMask::RFC822) && !subject_is_empty {
4531        for rdn in subject.iter_rdn() {
4532            for ava in rdn.iter() {
4533                if ava.oid != OID_EMAIL_ADDRESS {
4534                    continue;
4535                }
4536                // PKCS #9 defines emailAddress as IA5String. Any other
4537                // encoding cannot be checked, so it fails closed instead of
4538                // silently skipping the constraint.
4539                let Ok(email_ia5) = ava.value.decode_as::<der::asn1::Ia5StringRef<'_>>() else {
4540                    return Err(Error::NameConstraintViolation { index });
4541                };
4542                check_mailbox_against_rfc822(
4543                    email_ia5.as_str(),
4544                    nc_permitted,
4545                    nc_excluded,
4546                    rfc822_permitted_active,
4547                    index,
4548                )?;
4549            }
4550        }
4551    }
4552
4553    Ok(())
4554}
4555
4556/// OID for the `SmtpUTF8Mailbox` otherName (RFC 8398 §3), `id-on-SmtpUTF8Mailbox`.
4557const OID_SMTP_UTF8_MAILBOX: der::asn1::ObjectIdentifier =
4558    der::asn1::ObjectIdentifier::new_unwrap("1.3.6.1.5.5.7.8.9");
4559
4560/// Pre-check one SAN entry whose form the generic subtree matchers cannot
4561/// decide on their own (RFC 5280 §4.2.1.10, RFC 8398 §6).
4562///
4563/// - `otherName(SmtpUTF8Mailbox)`: checked against rfc822Name constraints
4564///   when any are in effect (RFC 8398 §6 extends them to this form). The
4565///   value must be a UTF8String and its domain part must be ASCII; a
4566///   U-label domain would need IDNA mapping, which this `no_std` crate
4567///   does not carry, so it fails closed.
4568/// - `otherName` (any type-id, including SmtpUTF8Mailbox), `ediPartyName`,
4569///   `registeredID`: `pkix-path` does not process constraints of these
4570///   forms, so the name is rejected when a constraint of the same form is
4571///   in effect ("MUST either process the constraint or reject the
4572///   certificate"). The `otherName` check is per form, not per type-id: an
4573///   otherName constraint of one type-id rejects otherName SANs of every
4574///   type-id.
4575/// - `uniformResourceIdentifier`: when a URI constraint is in effect, a URI
4576///   without an authority, or whose host is an IP address, is rejected
4577///   (see [`uri_host`]).
4578fn check_san_name_form(
4579    name: &x509_cert::ext::pkix::name::GeneralName,
4580    forms_in_effect: NcTypeMask,
4581    nc_permitted: Option<&GeneralSubtrees>,
4582    nc_excluded: &GeneralSubtrees,
4583    rfc822_permitted_active: bool,
4584    index: usize,
4585) -> crate::Result<()> {
4586    use x509_cert::ext::pkix::name::GeneralName;
4587
4588    let violation = Err(Error::NameConstraintViolation { index });
4589    match name {
4590        GeneralName::OtherName(other) => {
4591            if forms_in_effect.intersects(NcTypeMask::OTHER_NAME) {
4592                return violation;
4593            }
4594            if other.type_id == OID_SMTP_UTF8_MAILBOX
4595                && forms_in_effect.intersects(NcTypeMask::RFC822)
4596            {
4597                let Ok(mailbox) = der::asn1::Utf8StringRef::try_from(&other.value) else {
4598                    return violation;
4599                };
4600                check_mailbox_against_rfc822(
4601                    mailbox.as_str(),
4602                    nc_permitted,
4603                    nc_excluded,
4604                    rfc822_permitted_active,
4605                    index,
4606                )?;
4607            }
4608        }
4609        GeneralName::EdiPartyName(_) | GeneralName::RegisteredId(_)
4610            if forms_in_effect.intersects(name_type_bit(name)) =>
4611        {
4612            return violation;
4613        }
4614        GeneralName::UniformResourceIdentifier(uri)
4615            if forms_in_effect.intersects(NcTypeMask::URI) && uri_host(uri.as_str()).is_none() =>
4616        {
4617            return violation;
4618        }
4619        _ => {}
4620    }
4621    Ok(())
4622}
4623
4624/// Check a mailbox that does not arrive as an rfc822Name SAN (a subject
4625/// `emailAddress` attribute or an `SmtpUTF8Mailbox` otherName) against the
4626/// rfc822Name subtrees.
4627///
4628/// Excluded entries always apply; permitted entries apply when
4629/// `rfc822_permitted_active` (some CA in the path permitted rfc822Name
4630/// subtrees). The domain part (after the last `@`) must be ASCII, otherwise
4631/// the mailbox cannot be compared and the check fails closed.
4632fn check_mailbox_against_rfc822(
4633    mailbox: &str,
4634    nc_permitted: Option<&GeneralSubtrees>,
4635    nc_excluded: &GeneralSubtrees,
4636    rfc822_permitted_active: bool,
4637    index: usize,
4638) -> crate::Result<()> {
4639    use x509_cert::ext::pkix::name::GeneralName;
4640
4641    let violation = Err(Error::NameConstraintViolation { index });
4642    match mailbox.rsplit_once('@') {
4643        Some((_, domain)) if domain.is_ascii() => {}
4644        _ => return violation,
4645    }
4646    for st in nc_excluded {
4647        if let GeneralName::Rfc822Name(c) = &st.base {
4648            if matches_rfc822_name(mailbox, c.as_str()) {
4649                return violation;
4650            }
4651        }
4652    }
4653    if rfc822_permitted_active {
4654        let permitted = nc_permitted.map_or(&[][..], |p| p.as_slice());
4655        let ok = permitted.iter().any(|st| match &st.base {
4656            GeneralName::Rfc822Name(c) => matches_rfc822_name(mailbox, c.as_str()),
4657            _ => false,
4658        });
4659        if !ok {
4660            return violation;
4661        }
4662    }
4663    Ok(())
4664}
4665
4666// ---------------------------------------------------------------------------
4667// Send + Sync compile-time assertions
4668// ---------------------------------------------------------------------------
4669//
4670// AGENTS.md non-negotiable #6 requires load-bearing result types to be
4671// `Send + Sync` so callers can move values across thread boundaries and
4672// store them in shared caches. The auto-derive does the right thing today
4673// (no `Rc<T>`, `RefCell<T>`, or raw pointers in any of these types), but
4674// the rule is currently aspirational. These `const _:` assertions promote
4675// it to a compile-time invariant — a future field that breaks `Send` or
4676// `Sync` (e.g. someone adds an `Rc<T>` variant to `Error`) fails the
4677// workspace build, not a runtime test. Tracked at PKIX-2l0v.2.
4678
4679const _: fn() = || {
4680    fn _assert_send_sync<T: Send + Sync>() {}
4681    _assert_send_sync::<ValidatedPath>();
4682    _assert_send_sync::<Error>();
4683    _assert_send_sync::<TrustAnchor>();
4684    _assert_send_sync::<ValidationPolicy>();
4685};
4686
4687// ---------------------------------------------------------------------------
4688// Tests
4689// ---------------------------------------------------------------------------
4690
4691#[cfg(all(test, feature = "p256"))]
4692mod tests_ecdsa_p256 {
4693    use super::*;
4694    use der::Decode;
4695
4696    /// Test vector: a real P-256/SHA-256 self-signed cert generated by OpenSSL.
4697    /// Oracle: `openssl verify -CAfile ec.pem ec.pem` returns OK.
4698    #[test]
4699    fn verify_p256_self_signed() {
4700        use der::Encode as _;
4701        use spki::der::referenced::OwnedToRef as _;
4702        let der = include_bytes!("../tests/fixtures/ec-p256-sha256.der");
4703        let cert = Certificate::from_der(der).expect("parse cert");
4704
4705        let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
4706        let sig_bytes = cert.signature().raw_bytes();
4707
4708        // Self-signed cert: signer SPKI is the cert's own SPKI.
4709        let spki_ref = cert
4710            .tbs_certificate()
4711            .subject_public_key_info()
4712            .owned_to_ref();
4713
4714        let verifier = EcdsaP256Verifier;
4715        assert!(
4716            verifier
4717                .verify_signature(
4718                    cert.signature_algorithm().owned_to_ref(),
4719                    spki_ref,
4720                    &tbs_der,
4721                    sig_bytes,
4722                )
4723                .is_ok(),
4724            "self-signed P-256 cert should verify"
4725        );
4726    }
4727}
4728
4729#[cfg(all(test, feature = "p384"))]
4730mod tests_ecdsa_p384 {
4731    //! Test vectors for ECDSA P-384 / SHA-384 (PKIX-gphz.2).
4732    //!
4733    //! Oracle: `openssl verify -CAfile ec-p384-sha384.pem ec-p384-sha384.pem`
4734    //! returns OK against the same fixture (the PEM form lives at
4735    //! `tests/fixtures/ec-p384-sha384.der`; regenerate with the recipe in the
4736    //! commit that introduced this file). Independent oracle — pkix-path was
4737    //! not used to compute the expected verdict.
4738    use super::*;
4739    use der::Decode;
4740
4741    const FIXTURE: &[u8] = include_bytes!("../tests/fixtures/ec-p384-sha384.der");
4742
4743    #[test]
4744    fn verify_p384_self_signed() {
4745        use der::Encode as _;
4746        use spki::der::referenced::OwnedToRef as _;
4747        let cert = Certificate::from_der(FIXTURE).expect("parse cert");
4748
4749        let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
4750        let sig_bytes = cert.signature().raw_bytes();
4751
4752        // Self-signed cert: signer SPKI is the cert's own SPKI.
4753        let spki_ref = cert
4754            .tbs_certificate()
4755            .subject_public_key_info()
4756            .owned_to_ref();
4757
4758        let verifier = EcdsaP384Verifier;
4759        verifier
4760            .verify_signature(
4761                cert.signature_algorithm().owned_to_ref(),
4762                spki_ref,
4763                &tbs_der,
4764                sig_bytes,
4765            )
4766            .expect("self-signed P-384 cert should verify");
4767    }
4768
4769    #[test]
4770    fn tampered_signature_rejected() {
4771        // Flip a bit in the signature and confirm verification fails. This
4772        // exercises the actual cryptographic check, not just the OID and
4773        // SPKI parse paths.
4774        use der::Encode as _;
4775        use spki::der::referenced::OwnedToRef as _;
4776        let cert = Certificate::from_der(FIXTURE).expect("parse cert");
4777
4778        let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
4779        let mut sig_bytes = cert.signature().raw_bytes().to_vec();
4780        // Tamper a byte well inside the DER signature (any byte after the
4781        // initial SEQUENCE header). The DerSignature decoder rejects most
4782        // structural corruption with try_from, which is also a valid
4783        // verification failure — either way the result must be Err.
4784        let mid = sig_bytes.len() / 2;
4785        sig_bytes[mid] ^= 0x01;
4786
4787        let spki_ref = cert
4788            .tbs_certificate()
4789            .subject_public_key_info()
4790            .owned_to_ref();
4791
4792        let verifier = EcdsaP384Verifier;
4793        assert!(
4794            verifier
4795                .verify_signature(
4796                    cert.signature_algorithm().owned_to_ref(),
4797                    spki_ref,
4798                    &tbs_der,
4799                    &sig_bytes,
4800                )
4801                .is_err(),
4802            "tampered signature must not verify"
4803        );
4804    }
4805
4806    #[test]
4807    fn wrong_oid_rejected() {
4808        // The fixture was signed with SHA-384. Relabelling it as
4809        // ecdsa-with-SHA256 makes the verifier hash with SHA-256 (the
4810        // digest comes from the OID, the curve from the key), so the
4811        // signature must not verify.
4812        use der::Encode as _;
4813        use spki::der::referenced::OwnedToRef as _;
4814        let cert = Certificate::from_der(FIXTURE).expect("parse cert");
4815        let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
4816        let sig_bytes = cert.signature().raw_bytes();
4817        let spki_ref = cert
4818            .tbs_certificate()
4819            .subject_public_key_info()
4820            .owned_to_ref();
4821
4822        let wrong_alg = spki::AlgorithmIdentifierRef {
4823            oid: der::asn1::ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.2"), // ecdsa-with-SHA256
4824            parameters: None,
4825        };
4826        let verifier = EcdsaP384Verifier;
4827        assert!(
4828            verifier
4829                .verify_signature(wrong_alg, spki_ref, &tbs_der, sig_bytes)
4830                .is_err(),
4831            "a SHA-384 signature must not verify as ecdsa-with-SHA256"
4832        );
4833    }
4834
4835    #[test]
4836    fn default_verifier_dispatches_to_p384() {
4837        // DefaultVerifier's OID dispatch should route ecdsa-with-SHA384 to
4838        // EcdsaP384Verifier when the `p384` feature is active. Confirm the
4839        // same fixture verifies under DefaultVerifier too.
4840        use der::Encode as _;
4841        use spki::der::referenced::OwnedToRef as _;
4842        let cert = Certificate::from_der(FIXTURE).expect("parse cert");
4843        let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
4844        let sig_bytes = cert.signature().raw_bytes();
4845        let spki_ref = cert
4846            .tbs_certificate()
4847            .subject_public_key_info()
4848            .owned_to_ref();
4849
4850        DefaultVerifier
4851            .verify_signature(
4852                cert.signature_algorithm().owned_to_ref(),
4853                spki_ref,
4854                &tbs_der,
4855                sig_bytes,
4856            )
4857            .expect("DefaultVerifier must dispatch to EcdsaP384Verifier for ecdsa-with-SHA384");
4858    }
4859}
4860
4861#[cfg(all(test, feature = "rsa"))]
4862mod tests_rsa {
4863    use super::*;
4864    use der::Decode;
4865
4866    /// Test vector: a real RSA-2048/SHA-256 self-signed cert generated by OpenSSL.
4867    /// Oracle: `openssl verify -CAfile rsa.pem rsa.pem` returns OK.
4868    #[test]
4869    fn verify_rsa_pkcs1v15_sha256_self_signed() {
4870        use der::Encode as _;
4871        use spki::der::referenced::OwnedToRef as _;
4872        let der = include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha256.der");
4873        let cert = Certificate::from_der(der).expect("parse cert");
4874
4875        let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
4876        let sig_bytes = cert.signature().raw_bytes();
4877
4878        // Self-signed cert: signer SPKI is the cert's own SPKI.
4879        let spki_ref = cert
4880            .tbs_certificate()
4881            .subject_public_key_info()
4882            .owned_to_ref();
4883
4884        let verifier = RsaPkcs1v15Sha256Verifier;
4885        assert!(
4886            verifier
4887                .verify_signature(
4888                    cert.signature_algorithm().owned_to_ref(),
4889                    spki_ref,
4890                    &tbs_der,
4891                    sig_bytes,
4892                )
4893                .is_ok(),
4894            "self-signed RSA cert should verify"
4895        );
4896    }
4897
4898    /// RSA-PKCS1v15 SHA-384 verifier (PKIX-gphz.4).
4899    ///
4900    /// Independent oracle: `openssl verify -CAfile rsa-pkcs1v15-sha384.pem
4901    /// rsa-pkcs1v15-sha384.pem` returns OK against the same fixture
4902    /// (generated by `openssl req -new -x509 -sha384 ...`).
4903    #[test]
4904    fn verify_rsa_pkcs1v15_sha384_self_signed() {
4905        use der::Encode as _;
4906        use spki::der::referenced::OwnedToRef as _;
4907        let der = include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha384.der");
4908        let cert = Certificate::from_der(der).expect("parse cert");
4909        let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
4910        let sig_bytes = cert.signature().raw_bytes();
4911        let spki_ref = cert
4912            .tbs_certificate()
4913            .subject_public_key_info()
4914            .owned_to_ref();
4915
4916        RsaPkcs1v15Sha384Verifier
4917            .verify_signature(
4918                cert.signature_algorithm().owned_to_ref(),
4919                spki_ref,
4920                &tbs_der,
4921                sig_bytes,
4922            )
4923            .expect("self-signed RSA SHA-384 cert should verify");
4924    }
4925
4926    /// Tamper-rejection for SHA-384 variant.
4927    #[test]
4928    fn rsa_pkcs1v15_sha384_tampered_signature_rejected() {
4929        use der::Encode as _;
4930        use spki::der::referenced::OwnedToRef as _;
4931        let der = include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha384.der");
4932        let cert = Certificate::from_der(der).expect("parse cert");
4933        let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
4934        let mut sig_bytes = cert.signature().raw_bytes().to_vec();
4935        let mid = sig_bytes.len() / 2;
4936        sig_bytes[mid] ^= 0x01;
4937        let spki_ref = cert
4938            .tbs_certificate()
4939            .subject_public_key_info()
4940            .owned_to_ref();
4941
4942        assert!(
4943            RsaPkcs1v15Sha384Verifier
4944                .verify_signature(
4945                    cert.signature_algorithm().owned_to_ref(),
4946                    spki_ref,
4947                    &tbs_der,
4948                    &sig_bytes,
4949                )
4950                .is_err(),
4951            "tampered RSA SHA-384 signature must not verify"
4952        );
4953    }
4954
4955    /// RSA-PKCS1v15 SHA-512 verifier (PKIX-gphz.4).
4956    #[test]
4957    fn verify_rsa_pkcs1v15_sha512_self_signed() {
4958        use der::Encode as _;
4959        use spki::der::referenced::OwnedToRef as _;
4960        let der = include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha512.der");
4961        let cert = Certificate::from_der(der).expect("parse cert");
4962        let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
4963        let sig_bytes = cert.signature().raw_bytes();
4964        let spki_ref = cert
4965            .tbs_certificate()
4966            .subject_public_key_info()
4967            .owned_to_ref();
4968
4969        RsaPkcs1v15Sha512Verifier
4970            .verify_signature(
4971                cert.signature_algorithm().owned_to_ref(),
4972                spki_ref,
4973                &tbs_der,
4974                sig_bytes,
4975            )
4976            .expect("self-signed RSA SHA-512 cert should verify");
4977    }
4978
4979    /// Tamper-rejection for SHA-512 variant.
4980    #[test]
4981    fn rsa_pkcs1v15_sha512_tampered_signature_rejected() {
4982        use der::Encode as _;
4983        use spki::der::referenced::OwnedToRef as _;
4984        let der = include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha512.der");
4985        let cert = Certificate::from_der(der).expect("parse cert");
4986        let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
4987        let mut sig_bytes = cert.signature().raw_bytes().to_vec();
4988        let mid = sig_bytes.len() / 2;
4989        sig_bytes[mid] ^= 0x01;
4990        let spki_ref = cert
4991            .tbs_certificate()
4992            .subject_public_key_info()
4993            .owned_to_ref();
4994
4995        assert!(
4996            RsaPkcs1v15Sha512Verifier
4997                .verify_signature(
4998                    cert.signature_algorithm().owned_to_ref(),
4999                    spki_ref,
5000                    &tbs_der,
5001                    &sig_bytes,
5002                )
5003                .is_err(),
5004            "tampered RSA SHA-512 signature must not verify"
5005        );
5006    }
5007
5008    /// Wrong-OID rejection: SHA-384 verifier must reject SHA-512 OID and
5009    /// vice versa, and both must reject SHA-256 OID.
5010    #[test]
5011    fn rsa_pkcs1v15_wrong_oid_rejected() {
5012        use der::Encode as _;
5013        use spki::der::referenced::OwnedToRef as _;
5014        let der = include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha384.der");
5015        let cert = Certificate::from_der(der).expect("parse cert");
5016        let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
5017        let sig_bytes = cert.signature().raw_bytes();
5018        let spki_ref = cert
5019            .tbs_certificate()
5020            .subject_public_key_info()
5021            .owned_to_ref();
5022
5023        // SHA-512 verifier must refuse the SHA-384 OID.
5024        let sha384_alg = cert.signature_algorithm().owned_to_ref();
5025        assert!(RsaPkcs1v15Sha512Verifier
5026            .verify_signature(sha384_alg, spki_ref.clone(), &tbs_der, sig_bytes)
5027            .is_err());
5028        // SHA-256 verifier must refuse the SHA-384 OID.
5029        assert!(RsaPkcs1v15Sha256Verifier
5030            .verify_signature(sha384_alg, spki_ref, &tbs_der, sig_bytes)
5031            .is_err());
5032    }
5033
5034    /// `DefaultVerifier` dispatches the SHA-384 and SHA-512 RSA OIDs.
5035    #[test]
5036    fn default_verifier_dispatches_to_rsa_sha384_and_sha512() {
5037        use der::Encode as _;
5038        use spki::der::referenced::OwnedToRef as _;
5039
5040        for fixture in [
5041            &include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha384.der")[..],
5042            &include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha512.der")[..],
5043        ] {
5044            let cert = Certificate::from_der(fixture).expect("parse cert");
5045            let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
5046            let sig_bytes = cert.signature().raw_bytes();
5047            let spki_ref = cert
5048                .tbs_certificate()
5049                .subject_public_key_info()
5050                .owned_to_ref();
5051            DefaultVerifier
5052                .verify_signature(
5053                    cert.signature_algorithm().owned_to_ref(),
5054                    spki_ref,
5055                    &tbs_der,
5056                    sig_bytes,
5057                )
5058                .expect("DefaultVerifier must dispatch RSA SHA-384/512 by OID");
5059        }
5060    }
5061
5062    /// Regression (PKIX-5u0): `spki_key_matches` ignores the NULL-vs-absent
5063    /// parameter encoding difference that exists for RSA SPKIs.
5064    ///
5065    /// RFC 3279 §2.3.1 allows both explicit NULL parameters and absent
5066    /// parameters for `rsaEncryption`. The derived `PartialEq` in the `spki`
5067    /// crate treats `Some(NULL) ≠ None`, so using `==` in the self-issued
5068    /// anchor guard would wrongly reject a valid anchor.
5069    #[test]
5070    fn spki_key_matches_ignores_null_vs_absent_params() {
5071        let der_bytes = include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha256.der");
5072        let cert = Certificate::from_der(der_bytes).expect("parse cert");
5073        let cert_spki = cert.tbs_certificate().subject_public_key_info();
5074
5075        // Same OID and key bytes, but parameters: None instead of Some(NULL).
5076        let spki_no_params: spki::SubjectPublicKeyInfoOwned = spki::SubjectPublicKeyInfoOwned {
5077            algorithm: spki::AlgorithmIdentifier {
5078                oid: cert_spki.algorithm.oid,
5079                parameters: None,
5080            },
5081            subject_public_key: cert_spki.subject_public_key.clone(),
5082        };
5083
5084        // PartialEq distinguishes Some(NULL) from None — document this behavior.
5085        assert_ne!(cert_spki, &spki_no_params);
5086
5087        // spki_key_matches must return true: same OID + same key bytes.
5088        assert!(super::spki_key_matches(cert_spki, &spki_no_params));
5089    }
5090
5091    /// Integration regression (PKIX-5u0): the self-issued anchor guard must not
5092    /// return `NoTrustedPath` when an anchor has absent parameters (None) and the
5093    /// cert in the chain has explicit NULL parameters — both are valid per RFC 3279
5094    /// §2.3.1 for rsaEncryption.
5095    ///
5096    /// The guard compares anchor and cert SPKIs with `spki_key_matches` (OID + key
5097    /// bytes only). Before the fix, using `==` caused `NoTrustedPath` because
5098    /// `Some(NULL) != None` under derived `PartialEq`.
5099    ///
5100    /// Note: the anchor with `parameters: None` will fail signature verification
5101    /// (the `rsa` crate rejects absent params during key parsing), so the result
5102    /// is `Err(SignatureInvalid)`, not `Ok`. What this test verifies is that the
5103    /// guard does NOT skip the anchor and return `NoTrustedPath`. The anchor is
5104    /// tried; the failure is at a later stage, not the guard.
5105    #[test]
5106    fn self_issued_rsa_anchor_absent_params_not_no_trusted_path() {
5107        // 2026-06-01 — within rsa-pkcs1v15-sha256.der validity window
5108        // (notBefore=2026-05-02, notAfter=2036-04-29).
5109        const NOW: u64 = 1_780_272_000;
5110
5111        let der_bytes = include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha256.der");
5112        let cert = Certificate::from_der(der_bytes).expect("parse cert");
5113        let cert_spki = cert.tbs_certificate().subject_public_key_info();
5114
5115        // Construct an anchor from the same cert but with parameters: None.
5116        // Simulates a trust store that was populated from a source omitting the
5117        // explicit NULL — a common DER encoding variation for rsaEncryption.
5118        let anchor = TrustAnchor::new(
5119            cert.tbs_certificate().subject().clone(),
5120            spki::SubjectPublicKeyInfoOwned {
5121                algorithm: spki::AlgorithmIdentifier {
5122                    oid: cert_spki.algorithm.oid,
5123                    parameters: None,
5124                },
5125                subject_public_key: cert_spki.subject_public_key.clone(),
5126            },
5127        );
5128
5129        let policy = ValidationPolicy {
5130            current_time_unix: NOW,
5131            ..ValidationPolicy::new(0)
5132        };
5133        let result = validate_path(&[cert], &[anchor], &policy, &RsaPkcs1v15Sha256Verifier);
5134        // The guard must not skip the anchor (which would return NoTrustedPath).
5135        // SignatureInvalid is expected: the anchor was tried but the rsa crate
5136        // rejects absent params during key parsing.
5137        assert!(
5138            !matches!(result, Err(Error::NoTrustedPath)),
5139            "guard must not return NoTrustedPath for same key with different param encoding; got: {result:?}"
5140        );
5141    }
5142}
5143
5144// ---------------------------------------------------------------------------
5145// NormalizedIter / names_match unit tests
5146// ---------------------------------------------------------------------------
5147#[cfg(test)]
5148mod tests_normalized_iter {
5149    use super::{any_to_str_bytes, normalized_eq, NormalizedIter};
5150
5151    /// At most `n` bytes of what `iter` yields.
5152    ///
5153    /// The bound is the point. Every existing test of these two iterators
5154    /// goes through `normalized_eq` or `bmp_string_to_utf8`, which compare
5155    /// or collect the whole stream, so an iterator that never returns
5156    /// `None` hangs the test rather than failing it -- a mutation sweep
5157    /// reports that as a timeout and leaves the test binary spinning. A
5158    /// prefix comparison answers in one step.
5159    fn prefix<I: Iterator<Item = u8>>(iter: I, n: usize) -> Vec<u8> {
5160        iter.take(n).collect()
5161    }
5162
5163    /// The first `n` bytes `NormalizedIter` yields for `input`.
5164    fn normalized(input: &[u8], n: usize) -> Vec<u8> {
5165        prefix(NormalizedIter::new(input.iter().copied()), n)
5166    }
5167
5168    /// RFC 4518 §2 prep, read off the iterator directly and bounded.
5169    ///
5170    /// The asserted values are shorter than the bound, so an iterator that
5171    /// keeps yielding -- the shape every one of its mutants takes -- fails
5172    /// on length before anything else.
5173    #[test]
5174    fn the_normalizing_iterator_yields_exactly_the_prepared_bytes() {
5175        assert_eq!(
5176            normalized(b"  Hello   World  ", 32),
5177            b"hello world".to_vec()
5178        );
5179        assert_eq!(normalized(b"a b", 16), b"a b".to_vec());
5180        assert_eq!(normalized(b"", 8), b"".to_vec());
5181        assert_eq!(
5182            normalized(b"   ", 8),
5183            b"".to_vec(),
5184            "spaces alone prepare to nothing"
5185        );
5186        assert_eq!(
5187            normalized(b" a", 8),
5188            b"a".to_vec(),
5189            "a leading run is dropped"
5190        );
5191        assert_eq!(
5192            normalized(b"a ", 8),
5193            b"a".to_vec(),
5194            "a trailing run is dropped"
5195        );
5196    }
5197
5198    /// `DirectoryString` content reaches the comparison as UTF-8 bytes.
5199    ///
5200    /// The `BmpString` case transcodes one UCS-2 unit at a time through a
5201    /// four-byte buffer, so the bytes of a multi-byte character come out on
5202    /// successive calls and the position has to advance between them. The
5203    /// three units below encode to one, two and three UTF-8 bytes, which
5204    /// is every width a BMP scalar value takes.
5205    #[test]
5206    fn a_directory_string_yields_its_utf8_bytes_and_then_stops() {
5207        let utf8 = der::Any::new(der::Tag::Utf8String, &b"ab"[..]).expect("utf8 value");
5208        assert_eq!(
5209            prefix(any_to_str_bytes(&utf8).expect("a UTF8String is text"), 8),
5210            b"ab".to_vec()
5211        );
5212
5213        // U+0041 A, U+00E9 e-acute, U+20AC euro sign.
5214        let ucs2 = [0x00, 0x41, 0x00, 0xE9, 0x20, 0xAC];
5215        let bmp = der::Any::new(der::Tag::BmpString, &ucs2[..]).expect("bmp value");
5216        assert_eq!(
5217            prefix(any_to_str_bytes(&bmp).expect("a BMPString is text"), 16),
5218            [0x41, 0xC3, 0xA9, 0xE2, 0x82, 0xAC],
5219            "one, two and three UTF-8 bytes in that order"
5220        );
5221    }
5222
5223    /// Identical ASCII strings must compare equal.
5224    #[test]
5225    fn identical_strings_equal() {
5226        assert!(normalized_eq(b"hello", b"hello"));
5227    }
5228
5229    /// Case is folded to lowercase.
5230    #[test]
5231    fn case_folding() {
5232        assert!(normalized_eq(b"Hello", b"hello"));
5233        assert!(normalized_eq(b"HELLO WORLD", b"hello world"));
5234    }
5235
5236    /// Leading spaces are stripped.
5237    #[test]
5238    fn leading_spaces_stripped() {
5239        assert!(normalized_eq(b"  hello", b"hello"));
5240    }
5241
5242    /// Trailing spaces are stripped.
5243    ///
5244    /// Regression test: `NormalizedIter` must not emit a trailing space for
5245    /// input that ends with a space sequence.
5246    #[test]
5247    fn trailing_spaces_stripped() {
5248        assert!(normalized_eq(b"hello  ", b"hello"));
5249        assert!(normalized_eq(b"hello ", b"hello"));
5250    }
5251
5252    /// Multiple consecutive internal spaces are collapsed to a single space.
5253    ///
5254    /// Regression test for the double-space bug: `pending_space` must not
5255    /// cause two spaces to be emitted for a single space in the input.
5256    #[test]
5257    fn internal_spaces_collapsed() {
5258        assert!(normalized_eq(b"hello  world", b"hello world"));
5259        assert!(normalized_eq(b"hello   world", b"hello world"));
5260    }
5261
5262    /// Combined: leading + trailing + internal spaces, case folding.
5263    #[test]
5264    fn combined_normalization() {
5265        assert!(normalized_eq(b"  Hello   World  ", b"hello world"));
5266    }
5267
5268    /// Empty string and all-spaces string must both yield zero bytes.
5269    #[test]
5270    fn empty_and_whitespace_only() {
5271        assert!(normalized_eq(b"", b""));
5272        assert!(normalized_eq(b"   ", b""));
5273        assert!(normalized_eq(b"   ", b"   "));
5274    }
5275
5276    /// Different strings must NOT compare equal after normalization.
5277    #[test]
5278    fn different_strings_not_equal() {
5279        assert!(!normalized_eq(b"hello", b"world"));
5280        assert!(!normalized_eq(b"ab", b"abc"));
5281    }
5282
5283    /// `NormalizedIter`: input ending with an internal space sequence followed by
5284    /// trailing spaces must emit the space and then stop (no double space, no
5285    /// trailing space).
5286    #[test]
5287    fn internal_then_trailing_space_no_trailing_emit() {
5288        assert!(
5289            normalized_eq(b"ab  ", b"ab"),
5290            "trailing spaces must not be emitted"
5291        );
5292        assert!(
5293            normalized_eq(b"ab  cd  ", b"ab cd"),
5294            "internal double-space collapses; trailing spaces stripped"
5295        );
5296    }
5297}
5298
5299// ---------------------------------------------------------------------------
5300// PKIX-l63j.1: BMPString transcoding tests
5301// ---------------------------------------------------------------------------
5302#[cfg(test)]
5303mod tests_bmp_string {
5304    use super::Vec;
5305    use super::{ava_values_match, bmp_string_to_utf8};
5306    use der::asn1::Any;
5307    use der::Tag;
5308
5309    /// Construct UCS-2-BE bytes for an ASCII-only string.
5310    ///
5311    /// Each ASCII byte `b` becomes the two-byte sequence `[0x00, b]` since
5312    /// ASCII code points are in the range U+0000..=U+007F and the
5313    /// big-endian UCS-2 encoding of U+00XX is `0x00, 0xXX`.
5314    ///
5315    /// Independent oracle: this construction matches the literal
5316    /// description in X.680 Annex B and ITU-T X.690 §8.6 ("BMPString
5317    /// is encoded as a sequence of two-octet code units in big-endian
5318    /// order, with each unit representing one Unicode code point").
5319    fn ucs2_be_ascii(s: &str) -> Vec<u8> {
5320        let mut v = Vec::with_capacity(s.len() * 2);
5321        for b in s.bytes() {
5322            assert!(
5323                b.is_ascii(),
5324                "ucs2_be_ascii test helper only supports ASCII input"
5325            );
5326            v.push(0x00);
5327            v.push(b);
5328        }
5329        v
5330    }
5331
5332    /// `bmp_string_to_utf8` round-trip for ASCII-only input.
5333    ///
5334    /// Independent oracle: ASCII Unicode code points (U+0000..=U+007F)
5335    /// are encoded identically as a single byte in UTF-8 and as a
5336    /// two-byte big-endian unit `[0x00, X]` in UCS-2. Decoding the
5337    /// UCS-2 form must yield bytes byte-equal to the original ASCII.
5338    #[test]
5339    fn ascii_round_trip() {
5340        let src = "Foo Co";
5341        let ucs2 = ucs2_be_ascii(src);
5342        let utf8 = bmp_string_to_utf8(&ucs2).expect("well-formed UCS-2 ASCII");
5343        assert_eq!(utf8, src.as_bytes());
5344    }
5345
5346    /// `bmp_string_to_utf8` for a non-ASCII BMP code point.
5347    ///
5348    /// Independent oracle: the Hiragana letter A (U+3042) has well-known
5349    /// encodings — UTF-8: `0xE3 0x81 0x82`; UCS-2-BE: `0x30 0x42`. Both
5350    /// are tabulated in the Unicode Character Database. Citing the
5351    /// Unicode codepoint is the external oracle here, not our own code.
5352    #[test]
5353    fn non_ascii_bmp_code_point() {
5354        // U+3042 (HIRAGANA LETTER A): UCS-2-BE bytes 0x30 0x42.
5355        let ucs2 = vec![0x30, 0x42];
5356        let utf8 = bmp_string_to_utf8(&ucs2).expect("U+3042 is a valid BMP code point");
5357        // U+3042 in UTF-8 is the well-known three-byte sequence E3 81 82.
5358        assert_eq!(utf8, vec![0xE3, 0x81, 0x82]);
5359    }
5360
5361    /// Odd-length UCS-2 input is malformed (each unit must be 2 bytes).
5362    /// Fail-closed: return None.
5363    #[test]
5364    fn odd_length_returns_none() {
5365        let malformed = vec![0x00, 0x46, 0x00]; // 3 bytes, not a multiple of 2
5366        assert_eq!(bmp_string_to_utf8(&malformed), None);
5367    }
5368
5369    /// UTF-16 surrogate values (U+D800..=U+DFFF) are not valid Unicode
5370    /// scalar values and must not appear in `BMPString`. Fail-closed:
5371    /// return None.
5372    ///
5373    /// Independent oracle: Unicode Standard §3.8 explicitly defines
5374    /// surrogates as non-scalar; `core::char::from_u32(0xD800..=0xDFFF)`
5375    /// returns None.
5376    #[test]
5377    fn surrogate_returns_none() {
5378        // U+D800 (high surrogate, first surrogate code point).
5379        assert_eq!(bmp_string_to_utf8(&[0xD8, 0x00]), None);
5380        // U+DC00 (low surrogate).
5381        assert_eq!(bmp_string_to_utf8(&[0xDC, 0x00]), None);
5382        // U+DFFF (last surrogate code point).
5383        assert_eq!(bmp_string_to_utf8(&[0xDF, 0xFF]), None);
5384    }
5385
5386    /// Empty BMPString content is well-formed (zero code points) and
5387    /// transcodes to an empty UTF-8 byte vector.
5388    #[test]
5389    fn empty_input_round_trip() {
5390        let utf8 = bmp_string_to_utf8(&[]).expect("empty UCS-2 is well-formed (zero units)");
5391        assert!(utf8.is_empty());
5392    }
5393
5394    /// `ava_values_match`: a BMPString-encoded "Foo Co" must compare
5395    /// equal to a UTF8String-encoded "Foo Co".
5396    ///
5397    /// This is the core PKIX-l63j.1 invariant: same Unicode code points
5398    /// in different DER string types compare equal under DN matching.
5399    #[test]
5400    fn bmp_matches_utf8_same_text() {
5401        let bmp = Any::new(Tag::BmpString, ucs2_be_ascii("Foo Co")).unwrap();
5402        let utf8 = Any::new(Tag::Utf8String, b"Foo Co".to_vec()).unwrap();
5403        assert!(ava_values_match(&bmp, &utf8));
5404        // Symmetry: order of arguments must not matter.
5405        assert!(ava_values_match(&utf8, &bmp));
5406    }
5407
5408    /// `ava_values_match`: BMPString and PrintableString comparisons
5409    /// must succeed for ASCII content with the same Unicode code points.
5410    #[test]
5411    fn bmp_matches_printable_same_text() {
5412        let bmp = Any::new(Tag::BmpString, ucs2_be_ascii("Acme CA")).unwrap();
5413        let printable = Any::new(Tag::PrintableString, b"Acme CA".to_vec()).unwrap();
5414        assert!(ava_values_match(&bmp, &printable));
5415        assert!(ava_values_match(&printable, &bmp));
5416    }
5417
5418    /// `ava_values_match`: ASCII case-folding still applies to
5419    /// BMPString-derived UTF-8 bytes after transcoding (since BMP code
5420    /// points U+0041..=U+005A round-trip to ASCII bytes 0x41..=0x5A).
5421    #[test]
5422    fn bmp_matches_utf8_case_insensitive_ascii() {
5423        let bmp_upper = Any::new(Tag::BmpString, ucs2_be_ascii("FOO CO")).unwrap();
5424        let utf8_lower = Any::new(Tag::Utf8String, b"foo co".to_vec()).unwrap();
5425        assert!(ava_values_match(&bmp_upper, &utf8_lower));
5426    }
5427
5428    /// `ava_values_match`: whitespace collapsing still applies to
5429    /// BMPString-derived UTF-8 bytes (BMP space U+0020 → byte 0x20).
5430    #[test]
5431    fn bmp_matches_utf8_whitespace_collapsed() {
5432        let bmp = Any::new(Tag::BmpString, ucs2_be_ascii("  Foo   Co  ")).unwrap();
5433        let utf8 = Any::new(Tag::Utf8String, b"foo co".to_vec()).unwrap();
5434        assert!(ava_values_match(&bmp, &utf8));
5435    }
5436
5437    /// `ava_values_match`: different Unicode content must NOT match
5438    /// across encodings.
5439    #[test]
5440    fn bmp_does_not_match_utf8_different_text() {
5441        let bmp = Any::new(Tag::BmpString, ucs2_be_ascii("Foo Co")).unwrap();
5442        let utf8 = Any::new(Tag::Utf8String, b"Bar Co".to_vec()).unwrap();
5443        assert!(!ava_values_match(&bmp, &utf8));
5444    }
5445
5446    /// `ava_values_match`: malformed BMPString (odd length) is treated
5447    /// as a non-string type by the dispatcher (`any_to_str_bytes` returns
5448    /// None). It must therefore NOT match a well-formed UTF8String of
5449    /// any content. Fail-closed.
5450    #[test]
5451    fn malformed_bmp_does_not_match_well_formed_utf8() {
5452        // 3-byte content: malformed UCS-2.
5453        let malformed_bmp = Any::new(Tag::BmpString, vec![0x00, 0x46, 0x00]).unwrap();
5454        let utf8 = Any::new(Tag::Utf8String, b"F".to_vec()).unwrap();
5455        assert!(!ava_values_match(&malformed_bmp, &utf8));
5456        assert!(!ava_values_match(&utf8, &malformed_bmp));
5457    }
5458
5459    /// `ava_values_match`: non-ASCII Unicode code points compare equal
5460    /// when both AVAs encode the same code points (BMPString vs
5461    /// UTF8String).
5462    ///
5463    /// Independent oracle: the UCS-2-BE bytes for U+3042 are 0x30 0x42
5464    /// and the UTF-8 bytes are 0xE3 0x81 0x82, both per the Unicode
5465    /// Standard.
5466    #[test]
5467    fn bmp_matches_utf8_non_ascii() {
5468        // U+3042 HIRAGANA LETTER A.
5469        let bmp = Any::new(Tag::BmpString, vec![0x30, 0x42]).unwrap();
5470        let utf8 = Any::new(Tag::Utf8String, vec![0xE3, 0x81, 0x82]).unwrap();
5471        assert!(ava_values_match(&bmp, &utf8));
5472    }
5473
5474    /// Sanity: two BMPString-encoded values with the same Unicode code
5475    /// points compare equal (this exercises the BMPString-on-both-sides
5476    /// path through `any_to_str_bytes`, where both sides allocate).
5477    #[test]
5478    fn bmp_matches_bmp_same_text() {
5479        let a = Any::new(Tag::BmpString, ucs2_be_ascii("Acme")).unwrap();
5480        let b = Any::new(Tag::BmpString, ucs2_be_ascii("acme")).unwrap();
5481        assert!(ava_values_match(&a, &b));
5482    }
5483}
5484
5485// Review A1: NameConstraints helper unit tests (URI host extraction,
5486// constraint containment, streaming DN normalization).
5487#[cfg(test)]
5488mod tests_nc_review_a1 {
5489    use super::{
5490        dns_constraint_within, ip_constraint_within, matches_dns_name, matches_rfc822_name,
5491        normalized_eq, rfc822_constraint_within, uri_constraint_within, uri_host,
5492    };
5493
5494    #[test]
5495    fn uri_host_extraction() {
5496        assert_eq!(uri_host("https://good.com/x"), Some("good.com"));
5497        assert_eq!(
5498            uri_host("HTTPS://u:p@Good.com:443/a@b?c@d#e@f"),
5499            Some("Good.com")
5500        );
5501        assert_eq!(uri_host("https://evil.com/@good.com"), Some("evil.com"));
5502        assert_eq!(uri_host("https://evil.com#@good.com"), Some("evil.com"));
5503        assert_eq!(uri_host("https://evil.com./"), Some("evil.com"));
5504        // RFC 5280 §4.2.1.10 "MUST reject" shapes.
5505        assert_eq!(uri_host("urn:example:x"), None);
5506        assert_eq!(uri_host("mailto:a@b.example"), None);
5507        assert_eq!(uri_host("file:///etc/passwd"), None);
5508        assert_eq!(uri_host("https://192.0.2.1/"), None);
5509        assert_eq!(uri_host("https://[2001:db8::1]:8443/"), None);
5510        assert_eq!(uri_host("https://good.com:x/"), None);
5511        assert_eq!(uri_host("1http://good.com/"), None);
5512        assert_eq!(uri_host("://good.com/"), None);
5513    }
5514
5515    #[test]
5516    fn dns_matching_edges() {
5517        assert!(matches_dns_name("anything.example", ""));
5518        assert!(matches_dns_name("www.evil.com.", "evil.com"));
5519        assert!(matches_dns_name("www.evil.com", "evil.com."));
5520        assert!(!matches_dns_name("evil.com", ".evil.com"));
5521        assert!(!matches_dns_name("notevil.com", "evil.com"));
5522    }
5523
5524    #[test]
5525    fn rfc822_uses_last_at() {
5526        assert!(matches_rfc822_name("\"x@good.com\"@evil.com", "evil.com"));
5527        assert!(!matches_rfc822_name("\"x@good.com\"@evil.com", "good.com"));
5528    }
5529
5530    #[test]
5531    fn constraint_containment() {
5532        // DNS: x = {x} ∪ subdomains(x); .x = subdomains(x).
5533        assert!(dns_constraint_within(".example.com", "example.com"));
5534        assert!(!dns_constraint_within("example.com", ".example.com"));
5535        assert!(dns_constraint_within("a.example.com", ".example.com"));
5536        assert!(dns_constraint_within("example.com", ""));
5537        assert!(!dns_constraint_within("", "example.com"));
5538        // rfc822
5539        assert!(rfc822_constraint_within("host.example.com", ".example.com"));
5540        assert!(rfc822_constraint_within(
5541            "a@host.example.com",
5542            "host.example.com"
5543        ));
5544        assert!(!rfc822_constraint_within(
5545            ".example.com",
5546            "host.example.com"
5547        ));
5548        assert!(!rfc822_constraint_within(
5549            "host.example.com",
5550            "a@host.example.com"
5551        ));
5552        assert!(rfc822_constraint_within(".a.example.com", ".example.com"));
5553        // URI: no-dot = exact host only.
5554        assert!(uri_constraint_within("example.com", "example.com"));
5555        assert!(!uri_constraint_within("a.example.com", "example.com"));
5556        assert!(uri_constraint_within("a.example.com", ".example.com"));
5557        assert!(!uri_constraint_within(".example.com", "example.com"));
5558        // IP
5559        let v4 = |a: [u8; 4], m: [u8; 4]| [a, m].concat();
5560        assert!(ip_constraint_within(
5561            &v4([10, 1, 0, 0], [255, 255, 0, 0]),
5562            &v4([10, 0, 0, 0], [255, 0, 0, 0])
5563        ));
5564        assert!(!ip_constraint_within(
5565            &v4([10, 0, 0, 0], [255, 0, 0, 0]),
5566            &v4([10, 1, 0, 0], [255, 255, 0, 0])
5567        ));
5568        assert!(!ip_constraint_within(
5569            &v4([11, 1, 0, 0], [255, 255, 0, 0]),
5570            &v4([10, 0, 0, 0], [255, 0, 0, 0])
5571        ));
5572        assert!(!ip_constraint_within(
5573            &v4([10, 0, 0, 0], [255, 0, 0, 0]),
5574            &[0u8; 32]
5575        ));
5576    }
5577
5578    #[test]
5579    fn streaming_normalization_matches_slice_semantics() {
5580        assert!(normalized_eq(b"  a  B   c ", b"a b c"));
5581        assert!(normalized_eq(b" ", b""));
5582        assert!(!normalized_eq(b"a b", b"ab"));
5583    }
5584}
5585
5586// PKIX-h6z: validate_path public API tests.
5587#[cfg(all(test, feature = "p256"))]
5588mod tests_validate_path {
5589    use super::*;
5590    use der::Decode;
5591
5592    // Fixtures and time constants reused from tests_chain_walk.
5593    const GRY_NOW: u64 = 1_780_272_000; // 2026-06-01
5594
5595    fn load(bytes: &[u8]) -> Certificate {
5596        Certificate::from_der(bytes).expect("parse cert")
5597    }
5598
5599    fn policy_at(t: u64) -> ValidationPolicy {
5600        ValidationPolicy::new(t)
5601    }
5602
5603    /// Happy-path 1-cert chain: self-signed cert is both chain and anchor.
5604    ///
5605    /// Expected: Ok(ValidatedPath { `anchor_index`: 0, depth: 0 })
5606    #[test]
5607    fn one_cert_chain_ok() {
5608        let cert = load(include_bytes!("../tests/fixtures/ec-p256-sha256.der"));
5609        let anchors = [TrustAnchor::from_cert(cert.clone())];
5610        let result = validate_path(&[cert], &anchors, &policy_at(GRY_NOW), &EcdsaP256Verifier)
5611            .expect("1-cert chain must validate");
5612        assert_eq!(result.anchor_index, 0);
5613        assert_eq!(result.depth, 0);
5614    }
5615
5616    /// Happy-path 2-cert chain: leaf + intermediate, with root anchor.
5617    ///
5618    /// Oracle: openssl verify -`CAfile` gry-root.pem -untrusted gry-int.pem gry-leaf.pem → OK
5619    /// Expected: Ok(ValidatedPath { `anchor_index`: 0, depth: 1 })
5620    #[test]
5621    fn two_cert_chain_ok() {
5622        let root = load(include_bytes!("../tests/fixtures/gry-root.der"));
5623        let int_cert = load(include_bytes!("../tests/fixtures/gry-int.der"));
5624        let leaf = load(include_bytes!("../tests/fixtures/gry-leaf.der"));
5625        let anchors = [TrustAnchor::from_cert(root)];
5626        let result = validate_path(
5627            &[leaf, int_cert],
5628            &anchors,
5629            &policy_at(GRY_NOW),
5630            &EcdsaP256Verifier,
5631        )
5632        .expect("2-cert chain must validate");
5633        assert_eq!(result.anchor_index, 0);
5634        assert_eq!(result.depth, 1);
5635    }
5636
5637    /// §6.1.5 leaf-intrinsic outputs are populated correctly from `chain[0]`.
5638    ///
5639    /// Independent oracle: parse the leaf fixture a second time via
5640    /// `Certificate::from_der` (a different code path from `validate_path`'s
5641    /// chain[0] access). Compare each `ValidatedPath` accessor field against
5642    /// the independently-parsed leaf's `tbs_certificate` field. Catches:
5643    /// - Field swaps (e.g. `leaf_subject` accidentally populated from `issuer`).
5644    /// - Wrong cert in chain (e.g. `chain[1].subject` instead of `chain[0]`).
5645    /// - Forgotten field assignments.
5646    ///
5647    /// Does NOT validate x509-cert's parser correctness (that's tested
5648    /// upstream); it validates the wiring between `validate_path` and
5649    /// `ValidatedPath`.
5650    #[test]
5651    fn validated_path_exposes_leaf_subject_issuer_serial_spki() {
5652        let root = load(include_bytes!("../tests/fixtures/gry-root.der"));
5653        let int_cert = load(include_bytes!("../tests/fixtures/gry-int.der"));
5654        let leaf_bytes = include_bytes!("../tests/fixtures/gry-leaf.der");
5655        let leaf = load(leaf_bytes);
5656
5657        // Independent oracle: re-parse the leaf via Certificate::from_der.
5658        // x509-cert's parser is the upstream oracle for the field values.
5659        let oracle_leaf =
5660            Certificate::from_der(leaf_bytes).expect("oracle: leaf fixture must parse");
5661
5662        let anchors = [TrustAnchor::from_cert(root)];
5663        let result = validate_path(
5664            &[leaf, int_cert],
5665            &anchors,
5666            &policy_at(GRY_NOW),
5667            &EcdsaP256Verifier,
5668        )
5669        .expect("2-cert chain must validate");
5670
5671        // The four §6.1.5 leaf-intrinsic outputs must match the
5672        // independently-parsed leaf's corresponding tbs_certificate fields.
5673        assert_eq!(
5674            &result.leaf_subject,
5675            oracle_leaf.tbs_certificate().subject(),
5676            "ValidatedPath.leaf_subject must equal chain[0].tbs_certificate().subject()"
5677        );
5678        assert_eq!(
5679            &result.leaf_issuer,
5680            oracle_leaf.tbs_certificate().issuer(),
5681            "ValidatedPath.leaf_issuer must equal chain[0].tbs_certificate().issuer()"
5682        );
5683        assert_eq!(
5684            &result.leaf_serial,
5685            oracle_leaf.tbs_certificate().serial_number(),
5686            "ValidatedPath.leaf_serial must equal chain[0].tbs_certificate().serial_number()"
5687        );
5688        assert_eq!(
5689            &result.leaf_spki, oracle_leaf.tbs_certificate().subject_public_key_info(),
5690            "ValidatedPath.leaf_spki must equal chain[0].tbs_certificate().subject_public_key_info()"
5691        );
5692
5693        // Sanity: leaf_subject != leaf_issuer for a real (non-self-signed)
5694        // leaf. This catches the swap-subject-with-issuer regression: a
5695        // subject-issuer copy bug would leave both fields equal to whichever
5696        // one was used.
5697        assert_ne!(
5698            result.leaf_subject, result.leaf_issuer,
5699            "non-self-signed leaf must have distinct subject and issuer DNs (regression: swap)"
5700        );
5701    }
5702
5703    /// §6.1.5 outputs for a 1-cert (self-signed) chain.
5704    ///
5705    /// Self-signed certs have `subject == issuer`. This documents that
5706    /// `leaf_subject` and `leaf_issuer` ARE expected to be equal in this
5707    /// case — the previous test's `assert_ne!` is for non-self-signed
5708    /// chains only.
5709    #[test]
5710    fn validated_path_outputs_for_self_signed_chain() {
5711        let cert_bytes = include_bytes!("../tests/fixtures/ec-p256-sha256.der");
5712        let cert = load(cert_bytes);
5713        let oracle = Certificate::from_der(cert_bytes).expect("oracle: cert must parse");
5714        let anchors = [TrustAnchor::from_cert(cert.clone())];
5715
5716        let result = validate_path(&[cert], &anchors, &policy_at(GRY_NOW), &EcdsaP256Verifier)
5717            .expect("1-cert self-signed chain must validate");
5718
5719        assert_eq!(&result.leaf_subject, oracle.tbs_certificate().subject());
5720        assert_eq!(&result.leaf_issuer, oracle.tbs_certificate().issuer());
5721        assert_eq!(
5722            &result.leaf_serial,
5723            oracle.tbs_certificate().serial_number()
5724        );
5725        assert_eq!(
5726            &result.leaf_spki,
5727            oracle.tbs_certificate().subject_public_key_info()
5728        );
5729        // Self-signed: subject == issuer by definition.
5730        assert_eq!(
5731            result.leaf_subject, result.leaf_issuer,
5732            "self-signed cert must have equal subject and issuer DNs"
5733        );
5734    }
5735
5736    /// Multiple anchors: correct anchor is second in the slice.
5737    ///
5738    /// Expected: Ok(ValidatedPath { `anchor_index`: 1, depth: 0 })
5739    #[test]
5740    fn correct_anchor_index_when_multiple_anchors() {
5741        let p256 = load(include_bytes!("../tests/fixtures/ec-p256-sha256.der"));
5742        let rsa = load(include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha256.der"));
5743        // First anchor is the RSA cert (wrong name and SPKI for the P-256 chain).
5744        // Second anchor matches.
5745        let anchors = [
5746            TrustAnchor::from_cert(rsa),
5747            TrustAnchor::from_cert(p256.clone()),
5748        ];
5749        let result = validate_path(&[p256], &anchors, &policy_at(GRY_NOW), &EcdsaP256Verifier)
5750            .expect("must find second anchor");
5751        assert_eq!(result.anchor_index, 1);
5752        assert_eq!(result.depth, 0);
5753    }
5754
5755    /// Empty chain returns `NoTrustedPath`.
5756    #[test]
5757    fn empty_chain_returns_error() {
5758        let anchors = [TrustAnchor::from_cert(load(include_bytes!(
5759            "../tests/fixtures/ec-p256-sha256.der"
5760        )))];
5761        assert!(
5762            matches!(
5763                validate_path(&[], &anchors, &policy_at(GRY_NOW), &EcdsaP256Verifier),
5764                Err(Error::NoTrustedPath)
5765            ),
5766            "empty chain must fail"
5767        );
5768    }
5769
5770    /// Duplicate certificate in chain returns `DuplicateCertificate` error.
5771    ///
5772    /// Oracle: RFC 5280 does not define behavior for duplicate certs; we reject
5773    /// early with a diagnostic error rather than failing later with a confusing
5774    /// `SignatureInvalid` or `ChainBroken`.
5775    ///
5776    /// Duplicate is detected by (issuer DN, serial number) identity per RFC 5280
5777    /// §4.1.2.2 — the same cert appearing twice has the same issuer+serial.
5778    /// SPKI equality is intentionally NOT used (cross-signed CAs share a key but
5779    /// have distinct issuer+serial and must not be rejected).
5780    #[test]
5781    fn duplicate_cert_in_chain_returns_error() {
5782        let cert = load(include_bytes!("../tests/fixtures/ec-p256-sha256.der"));
5783        let anchors = [TrustAnchor::from_cert(cert.clone())];
5784        // Chain [cert, cert]: same cert at index 0 and index 1 — same issuer+serial.
5785        let result = validate_path(
5786            &[cert.clone(), cert],
5787            &anchors,
5788            &policy_at(GRY_NOW),
5789            &EcdsaP256Verifier,
5790        );
5791        assert!(
5792            matches!(
5793                result,
5794                Err(Error::DuplicateCertificate {
5795                    first: 0,
5796                    second: 1
5797                })
5798            ),
5799            "duplicate cert must return DuplicateCertificate{{first:0, second:1}}, got {result:?}"
5800        );
5801    }
5802
5803    /// `path_too_long`: vxf chain [leaf, int] with `max_path_len` = 0.
5804    ///
5805    /// chain.len()=2 → 1 intermediate. 1 > `max_path_len(0)` → `PathTooLong`.
5806    #[test]
5807    fn path_too_long_returns_error() {
5808        let root = load(include_bytes!("../tests/fixtures/vxf-root.der"));
5809        let int_cert = load(include_bytes!("../tests/fixtures/vxf-int.der"));
5810        let leaf = load(include_bytes!("../tests/fixtures/vxf-leaf.der"));
5811        let anchors = [TrustAnchor::from_cert(root)];
5812        let policy = ValidationPolicy {
5813            current_time_unix: GRY_NOW,
5814            max_path_len: 0,
5815            ..ValidationPolicy::new(0)
5816        };
5817        assert!(
5818            matches!(
5819                validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
5820                Err(Error::PathTooLong)
5821            ),
5822            "1 intermediate with max_path_len=0 must return PathTooLong"
5823        );
5824    }
5825
5826    /// `no_trusted_path`: vxf chain presented to an unrelated anchor (gry-root).
5827    ///
5828    /// vxf's last cert issuer name does not match gry-root's subject name.
5829    #[test]
5830    fn no_trusted_path_unrelated_anchor_returns_error() {
5831        let gry_root = load(include_bytes!("../tests/fixtures/gry-root.der"));
5832        let vxf_int = load(include_bytes!("../tests/fixtures/vxf-int.der"));
5833        let vxf_leaf = load(include_bytes!("../tests/fixtures/vxf-leaf.der"));
5834        let anchors = [TrustAnchor::from_cert(gry_root)];
5835        assert!(
5836            matches!(
5837                validate_path(
5838                    &[vxf_leaf, vxf_int],
5839                    &anchors,
5840                    &policy_at(GRY_NOW),
5841                    &EcdsaP256Verifier
5842                ),
5843                Err(Error::NoTrustedPath)
5844            ),
5845            "vxf chain with gry anchor must return NoTrustedPath"
5846        );
5847    }
5848
5849    /// `oid_mismatch`: outer signatureAlgorithm OID differs from inner TBS signature OID.
5850    ///
5851    /// Patch the SECOND occurrence of the ECDSA-with-SHA256 OID bytes in vxf-leaf.der
5852    /// to ECDSA-with-SHA384. The inner TBS.signature remains SHA256.
5853    /// `check_oid_consistency` detects this → `MalformedCertificate` { index: 0 }.
5854    ///
5855    /// Oracle: RFC 5280 §4.1.1.2 requires outer and inner `AlgorithmIdentifiers` to be identical.
5856    #[test]
5857    fn oid_mismatch_outer_returns_malformed_certificate() {
5858        let mut leaf_der = include_bytes!("../tests/fixtures/vxf-leaf.der").to_vec();
5859        // ECDSA-with-SHA256 OID content bytes: 1.2.840.10045.4.3.2
5860        let oid_sha256: &[u8] = &[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02];
5861        // ECDSA-with-SHA384 OID content bytes: 1.2.840.10045.4.3.3 (same length, last byte differs)
5862        let oid_sha384: &[u8] = &[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x03];
5863        // In Certificate DER the inner TBS.signature OID appears FIRST (inside TBSCertificate)
5864        // and the outer signatureAlgorithm OID appears SECOND (after TBSCertificate). Patching
5865        // only the second occurrence changes the outer OID while leaving the inner intact.
5866        let first = leaf_der
5867            .windows(8)
5868            .position(|w| w == oid_sha256)
5869            .expect("inner SHA256 OID must be present in vxf-leaf.der");
5870        let second = leaf_der[first + 8..]
5871            .windows(8)
5872            .position(|w| w == oid_sha256)
5873            .map(|p| first + 8 + p)
5874            .expect("outer SHA256 OID must be present in vxf-leaf.der");
5875        leaf_der[second..second + 8].copy_from_slice(oid_sha384);
5876        let leaf = Certificate::from_der(&leaf_der).expect("patched DER must parse");
5877        assert_ne!(
5878            leaf.signature_algorithm(),
5879            leaf.tbs_certificate().signature(),
5880            "outer/inner OIDs must differ after patch"
5881        );
5882        let int_cert = load(include_bytes!("../tests/fixtures/vxf-int.der"));
5883        let root = load(include_bytes!("../tests/fixtures/vxf-root.der"));
5884        let anchors = [TrustAnchor::from_cert(root)];
5885        assert!(
5886            matches!(
5887                validate_path(
5888                    &[leaf, int_cert],
5889                    &anchors,
5890                    &policy_at(GRY_NOW),
5891                    &EcdsaP256Verifier
5892                ),
5893                Err(Error::MalformedCertificate { index: 0 })
5894            ),
5895            "outer/inner OID mismatch must return MalformedCertificate {{ index: 0 }}"
5896        );
5897    }
5898
5899    /// `intermediate_not_ca`: nca-int has no `BasicConstraints` extension.
5900    ///
5901    /// Oracle: pyca/cryptography — nca-int built without any extensions.
5902    /// cert_is_ca(nca-int) returns None → `NotCA` { index: 1 }.
5903    #[test]
5904    fn intermediate_not_ca_returns_not_ca() {
5905        let root = load(include_bytes!("../tests/fixtures/nca-root.der"));
5906        let int_cert = load(include_bytes!("../tests/fixtures/nca-int.der"));
5907        let leaf = load(include_bytes!("../tests/fixtures/nca-leaf.der"));
5908        let anchors = [TrustAnchor::from_cert(root)];
5909        assert!(
5910            matches!(
5911                validate_path(
5912                    &[leaf, int_cert],
5913                    &anchors,
5914                    &policy_at(GRY_NOW),
5915                    &EcdsaP256Verifier
5916                ),
5917                Err(Error::NotCA { index: 1 })
5918            ),
5919            "intermediate without BasicConstraints CA flag must return NotCA {{ index: 1 }}"
5920        );
5921    }
5922
5923    /// `key_usage_missing_cert_sign`: kuf-int has `KeyUsage` with digitalSignature only.
5924    ///
5925    /// Oracle: pyca/cryptography — kuf-int KeyUsage.keyCertSign = False.
5926    /// Default policy has `enforce_key_usage` = true; `chain_walk` checks at i=1.
5927    #[test]
5928    fn key_usage_missing_cert_sign_returns_error() {
5929        let root = load(include_bytes!("../tests/fixtures/kuf-root.der"));
5930        let int_cert = load(include_bytes!("../tests/fixtures/kuf-int.der"));
5931        let leaf = load(include_bytes!("../tests/fixtures/kuf-leaf.der"));
5932        let anchors = [TrustAnchor::from_cert(root)];
5933        assert!(
5934            matches!(
5935                validate_path(&[leaf, int_cert], &anchors, &policy_at(GRY_NOW), &EcdsaP256Verifier),
5936                Err(Error::KeyUsageMissing { index: 1 })
5937            ),
5938            "intermediate with KeyUsage but no keyCertSign must return KeyUsageMissing {{ index: 1 }}"
5939        );
5940    }
5941
5942    /// `absent_key_usage_intermediate_accepted`: nku-int has NO `KeyUsage` extension at all.
5943    ///
5944    /// RFC 5280 §6.1.4(n): "If a `KeyUsage` extension is **present**, verify that the
5945    /// keyCertSign bit is set." Absent `KeyUsage` must not be rejected by `enforce_key_usage`.
5946    ///
5947    /// Oracle: pyca/cryptography — nku-int has only `BasicConstraints` (OID 2.5.29.19),
5948    /// no `KeyUsage` extension.
5949    #[test]
5950    fn absent_key_usage_intermediate_accepted() {
5951        let root = load(include_bytes!("../tests/fixtures/nku-root.der"));
5952        let int_cert = load(include_bytes!("../tests/fixtures/nku-int.der"));
5953        let leaf = load(include_bytes!("../tests/fixtures/nku-leaf.der"));
5954        let anchors = [TrustAnchor::from_cert(root)];
5955        // Default policy has enforce_key_usage = true.
5956        // nku-int has no KeyUsage — must NOT trigger KeyUsageMissing per RFC 5280 §6.1.4(n).
5957        let now: u64 = 1_720_000_000; // 2024-07-03, within nku-int validity (2024-2030)
5958        let policy = ValidationPolicy {
5959            current_time_unix: now,
5960            ..ValidationPolicy::new(0)
5961        };
5962        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier).expect(
5963            "intermediate with absent KeyUsage must be accepted when enforce_key_usage=true",
5964        );
5965    }
5966
5967    /// Leaf with critical `ExtendedKeyUsage` → `validate_path` must accept it.
5968    ///
5969    /// EKU is in `HANDLED_CRITICAL_OIDS`; its value is not inspected.
5970    /// Oracle: pyca/cryptography — eku-critical-self-signed.der, critical=True, serverAuth.
5971    #[test]
5972    fn critical_eku_accepted() {
5973        let cert = load(include_bytes!(
5974            "../tests/fixtures/eku-critical-self-signed.der"
5975        ));
5976        let anchors = [TrustAnchor::from_cert(cert.clone())];
5977        validate_path(&[cert], &anchors, &policy_at(GRY_NOW), &EcdsaP256Verifier)
5978            .expect("cert with critical EKU must be accepted");
5979    }
5980
5981    /// Security test: anchor with matching name but wrong SPKI must be rejected.
5982    ///
5983    /// Guards against a name-collision attack: an attacker who creates a root cert
5984    /// with the same DN as a trusted anchor but a different key must not be accepted.
5985    /// The self-issued SPKI guard in `validate_path` catches this.
5986    #[test]
5987    fn forged_anchor_name_match_spki_mismatch_rejected() {
5988        use der::Decode as _;
5989        let p256 = Certificate::from_der(include_bytes!("../tests/fixtures/ec-p256-sha256.der"))
5990            .expect("parse P-256 cert");
5991        let rsa =
5992            Certificate::from_der(include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha256.der"))
5993                .expect("parse RSA cert");
5994        // Forged anchor: P-256 cert's subject name + RSA cert's SPKI.
5995        let forged = TrustAnchor::new(
5996            p256.tbs_certificate().subject().clone(),
5997            rsa.tbs_certificate().subject_public_key_info().clone(),
5998        );
5999        let anchors = [forged];
6000        assert!(
6001            matches!(
6002                validate_path(&[p256], &anchors, &policy_at(GRY_NOW), &EcdsaP256Verifier),
6003                Err(Error::NoTrustedPath)
6004            ),
6005            "anchor with matching name but wrong SPKI must return NoTrustedPath"
6006        );
6007    }
6008
6009    /// Verify that `validate_path` handles large certs without `Error::Der`.
6010    ///
6011    /// The previous fixed 8 KiB stack buffer returned `Error::Der` for any cert
6012    /// whose `TBSCertificate` DER exceeded 8 KiB. The heap-backed encoding path
6013    /// introduced in v0.2 removes that limit. This test verifies that a normally-
6014    /// sized cert (well under 8 KiB) still validates correctly, confirming the
6015    /// heap path is wired up correctly and not just a dead code path.
6016    ///
6017    /// Oracle: the gry-leaf fixture validates correctly via openssl verify.
6018    #[test]
6019    fn large_cert_encoding_does_not_fail_with_der_error() {
6020        // We don't have an actual > 8 KiB TBSCertificate fixture in the test suite,
6021        // but we can verify the heap path is taken by confirming normal certs still pass.
6022        // The regression test for the bug is: this path no longer returns Error::Der
6023        // for legitimately-sized certs.
6024        let cert = load(include_bytes!("../tests/fixtures/ec-p256-sha256.der"));
6025        let anchors = [TrustAnchor::from_cert(cert.clone())];
6026        // Must not return Err(Error::Der(...)) — the heap encoding path must succeed.
6027        let result = validate_path(&[cert], &anchors, &policy_at(GRY_NOW), &EcdsaP256Verifier);
6028        assert!(
6029            !matches!(result, Err(Error::Der(_))),
6030            "heap-backed encoding must not return Error::Der for a normal cert"
6031        );
6032    }
6033
6034    /// Verify `cert_has_san_identity` returns false for normal certs (non-empty Subject).
6035    ///
6036    /// Oracle: RFC 5280 §4.2.1.6 — `cert_has_san_identity` must return true only when
6037    /// Subject is empty AND SAN is critical. Normal certs have non-empty Subject.
6038    #[test]
6039    fn cert_has_san_identity_false_for_normal_cert() {
6040        let cert = load(include_bytes!("../tests/fixtures/ec-p256-sha256.der"));
6041        // This is a normal self-signed cert with a non-empty Subject DN.
6042        assert!(
6043            !cert_has_san_identity(&cert),
6044            "normal cert with non-empty Subject must not be SAN-identity"
6045        );
6046    }
6047}
6048
6049// PKIX-vxf + PKIX-gry: chain_walk tests require the p256 feature.
6050#[cfg(all(test, feature = "p256"))]
6051mod tests_chain_walk {
6052    use super::*;
6053    use der::Decode;
6054
6055    // Fixtures (PKIX-vxf):
6056    //   vxf-root.der — self-signed root CA, CN=PKIX-vxf-root  (P-256)
6057    //   vxf-int.der  — intermediate CA, CN=PKIX-vxf-int, signed by vxf-root
6058    //   vxf-leaf.der — leaf cert, CN=PKIX-vxf-leaf, signed by vxf-int
6059    //   chk-root.der / chk-int.der / chk-leaf-wrong-issuer.der — ChainBroken test chain
6060    //
6061    // Fixtures (PKIX-gry):
6062    //   gry-root.der                  — root CA, CN=PKIX-gry-root (P-256)
6063    //   gry-int.der                   — intermediate CA, CN=PKIX-gry-int, valid 2026-2036
6064    //   gry-leaf.der                  — leaf, CN=PKIX-gry-leaf, valid 2026-2027 (short-lived)
6065    //   gry-leaf-unknown-crit.der     — leaf with unknown critical extension
6066    //
6067    // Unix timestamp constants for gry validity tests:
6068    //   GRY_NOW     = 1780272000  (2026-06-01, all gry certs valid)
6069    //   GRY_EXPIRED = 1830384000  (2028-01-02, gry-leaf expired; gry-int still valid)
6070    //   GRY_NOTYET  = 0           (1970-01-01, all gry certs not-yet-valid)
6071    //
6072    // Oracle:
6073    //   vxf chain: openssl verify -CAfile vxf-root.pem -untrusted vxf-int.pem vxf-leaf.pem → OK
6074    //   gry chain: pyca/cryptography; chain verifies at GRY_NOW
6075    //   chk-leaf-wrong-issuer: signature valid under chk-int key (pyca); issuer = PKIX-WRONG-ISSUER by design
6076
6077    const GRY_NOW: u64 = 1_780_272_000;
6078    const GRY_EXPIRED: u64 = 1_830_384_000;
6079    const GRY_NOTYET: u64 = 0;
6080
6081    fn load(bytes: &[u8]) -> Certificate {
6082        Certificate::from_der(bytes).expect("parse cert")
6083    }
6084
6085    fn policy_at(t: u64) -> ValidationPolicy {
6086        ValidationPolicy::new(t)
6087    }
6088
6089    /// 1-cert chain: self-signed P-256 cert as both chain and anchor.
6090    #[test]
6091    fn single_cert_chain_ok() {
6092        let p256 = load(include_bytes!("../tests/fixtures/ec-p256-sha256.der"));
6093        let policy = policy_at(GRY_NOW);
6094        let anchor = TrustAnchor::from_cert(p256.clone());
6095        chain_walk(&[p256], &anchor, &policy, &EcdsaP256Verifier)
6096            .expect("1-cert chain must pass chain_walk");
6097    }
6098
6099    /// 2-cert chain (leaf + intermediate) with root as anchor.
6100    ///
6101    /// Oracle: openssl verify -`CAfile` vxf-root.pem -untrusted vxf-int.pem vxf-leaf.pem → OK
6102    #[test]
6103    fn two_cert_chain_ok() {
6104        let root = load(include_bytes!("../tests/fixtures/vxf-root.der"));
6105        let int_cert = load(include_bytes!("../tests/fixtures/vxf-int.der"));
6106        let leaf = load(include_bytes!("../tests/fixtures/vxf-leaf.der"));
6107        let policy = policy_at(GRY_NOW);
6108        let anchor = TrustAnchor::from_cert(root);
6109        chain_walk(&[leaf, int_cert], &anchor, &policy, &EcdsaP256Verifier)
6110            .expect("2-cert chain must pass chain_walk");
6111    }
6112
6113    /// Leaf with corrupted signature — last byte flipped.
6114    ///
6115    /// The DER structure remains valid; only the BIT STRING content is wrong.
6116    /// Expect `SignatureInvalid` at chain index 0.
6117    #[test]
6118    fn corrupted_signature_returns_signature_invalid() {
6119        let mut leaf_der = include_bytes!("../tests/fixtures/vxf-leaf.der").to_vec();
6120        *leaf_der.last_mut().unwrap() ^= 0xFF;
6121        let leaf = Certificate::from_der(&leaf_der).expect("parse still succeeds after bit flip");
6122        let int_cert = load(include_bytes!("../tests/fixtures/vxf-int.der"));
6123        let anchor = TrustAnchor::from_cert(load(include_bytes!("../tests/fixtures/vxf-root.der")));
6124        let policy = policy_at(GRY_NOW);
6125        assert!(
6126            matches!(
6127                chain_walk(&[leaf, int_cert], &anchor, &policy, &EcdsaP256Verifier),
6128                Err(Error::SignatureInvalid { index: 0 })
6129            ),
6130            "corrupted leaf signature must return SignatureInvalid {{ index: 0 }}"
6131        );
6132    }
6133
6134    /// Chain where the leaf's issuer field does not match the intermediate's subject.
6135    ///
6136    /// Oracle: chk-leaf-wrong-issuer was signed by chk-int's private key
6137    /// (signature IS valid), but its issuer field = "PKIX-WRONG-ISSUER" by design.
6138    #[test]
6139    fn wrong_issuer_name_returns_chain_broken() {
6140        let root = load(include_bytes!("../tests/fixtures/chk-root.der"));
6141        let int_cert = load(include_bytes!("../tests/fixtures/chk-int.der"));
6142        let leaf_wrong = load(include_bytes!(
6143            "../tests/fixtures/chk-leaf-wrong-issuer.der"
6144        ));
6145        let policy = policy_at(GRY_NOW);
6146        let anchor = TrustAnchor::from_cert(root);
6147        assert!(
6148            matches!(
6149                chain_walk(
6150                    &[leaf_wrong, int_cert],
6151                    &anchor,
6152                    &policy,
6153                    &EcdsaP256Verifier
6154                ),
6155                Err(Error::ChainBroken { index: 0 })
6156            ),
6157            "leaf with wrong issuer must return ChainBroken {{ index: 0 }}"
6158        );
6159    }
6160
6161    // --- PKIX-gry per-cert check tests ---
6162
6163    /// Expired leaf cert → `ValidityPeriod` at index 0.
6164    ///
6165    /// Oracle: gry-leaf.der has notAfter=2027-01-01; GRY_EXPIRED=2028-01-02.
6166    /// gry-int.der has notAfter=2036-01-01, which is still valid at `GRY_EXPIRED`.
6167    /// Reverse walk: i=1 (gry-int) passes validity, then i=0 (gry-leaf) fails.
6168    #[test]
6169    fn expired_leaf_returns_validity_period() {
6170        let root = load(include_bytes!("../tests/fixtures/gry-root.der"));
6171        let int_cert = load(include_bytes!("../tests/fixtures/gry-int.der"));
6172        let leaf = load(include_bytes!("../tests/fixtures/gry-leaf.der"));
6173        let policy = policy_at(GRY_EXPIRED);
6174        let anchor = TrustAnchor::from_cert(root);
6175        assert!(
6176            matches!(
6177                chain_walk(&[leaf, int_cert], &anchor, &policy, &EcdsaP256Verifier),
6178                Err(Error::ValidityPeriod { index: 0 })
6179            ),
6180            "expired leaf must return ValidityPeriod {{ index: 0 }}"
6181        );
6182    }
6183
6184    /// Not-yet-valid intermediate → `ValidityPeriod` at index 1.
6185    ///
6186    /// Oracle: gry-int.der has notBefore=2026-01-01; `GRY_NOTYET=0` (1970-01-01).
6187    /// Reverse walk processes chain[1] (gry-int) first; it is not yet valid at time 0.
6188    #[test]
6189    fn notyet_valid_intermediate_returns_validity_period() {
6190        let root = load(include_bytes!("../tests/fixtures/gry-root.der"));
6191        let int_cert = load(include_bytes!("../tests/fixtures/gry-int.der"));
6192        let leaf = load(include_bytes!("../tests/fixtures/gry-leaf.der"));
6193        let policy = policy_at(GRY_NOTYET);
6194        let anchor = TrustAnchor::from_cert(root);
6195        assert!(
6196            matches!(
6197                chain_walk(&[leaf, int_cert], &anchor, &policy, &EcdsaP256Verifier),
6198                Err(Error::ValidityPeriod { index: 1 })
6199            ),
6200            "not-yet-valid intermediate must return ValidityPeriod {{ index: 1 }}"
6201        );
6202    }
6203
6204    /// Leaf with unknown critical extension → `UnhandledCriticalExtension` at index 0.
6205    ///
6206    /// Oracle: gry-leaf-unknown-crit.der was generated with OID 1.3.6.1.5.5.7.99.99 critical=true
6207    /// (not in `HANDLED_CRITICAL_OIDS`) using pyca/cryptography.
6208    #[test]
6209    fn unknown_critical_extension_returns_unhandled() {
6210        let root = load(include_bytes!("../tests/fixtures/gry-root.der"));
6211        let int_cert = load(include_bytes!("../tests/fixtures/gry-int.der"));
6212        let leaf_unk = load(include_bytes!(
6213            "../tests/fixtures/gry-leaf-unknown-crit.der"
6214        ));
6215        let policy = policy_at(GRY_NOW);
6216        let anchor = TrustAnchor::from_cert(root);
6217        assert!(
6218            matches!(
6219                chain_walk(&[leaf_unk, int_cert], &anchor, &policy, &EcdsaP256Verifier),
6220                Err(Error::UnhandledCriticalExtension { index: 0 })
6221            ),
6222            "unknown critical ext must return UnhandledCriticalExtension {{ index: 0 }}"
6223        );
6224    }
6225}
6226
6227// ---------------------------------------------------------------------------
6228// Tests: ValidationPolicy profile-enforcement fields (PKIX-ken.1.9–1.13)
6229// ---------------------------------------------------------------------------
6230//
6231// Fixtures: pkix-path/tests/fixtures/policy-checks/
6232//   root-p256.der, int-p256.der — P-256 CA chain (ecdsa-sha256)
6233//   leaf-p256-365d-san-eku.der  — 365-day leaf, SAN=DNS:test.example.com, EKU=serverAuth
6234//   leaf-p256-400d-san-eku.der  — 400-day leaf, SAN, EKU=serverAuth
6235//   leaf-p256-365d-no-san.der   — 365-day leaf, no SAN extension
6236//   leaf-p256-365d-no-eku.der   — 365-day leaf, SAN, no EKU extension
6237//   leaf-p256-365d-wrong-eku.der— 365-day leaf, SAN, EKU=emailProtection only
6238//   root-rsa2048.der, int-rsa2048.der — RSA-2048 CA chain (sha256WithRSAEncryption)
6239//   leaf-rsa2048-365d-san-eku.der — RSA-2048 leaf, SAN, EKU=serverAuth
6240//   leaf-rsa1024-365d-san-eku.der — RSA-1024 leaf, SAN, EKU=serverAuth
6241//
6242// Oracle: pkix-path/tests/fixtures/policy-checks/gen.py (pyca/cryptography)
6243// Chain verification: openssl verify passed for P-256 and RSA-2048 happy paths.
6244// Time constant: PC_NOW = 2026-06-01T00:00:00Z = 1_780_272_000 (unix)
6245//   All fixtures have NOT_BEFORE=2026-01-01, valid at PC_NOW.
6246//
6247// All tests require the p256 feature for P-256 chain tests, and rsa for RSA chain tests.
6248//
6249// The P-256 chain uses the module-level const directly; RSA chain tests live inside
6250// a separate rsa-feature-gated block so clippy does not warn about unused imports.
6251
6252#[cfg(all(test, feature = "p256"))]
6253mod tests_policy_fields {
6254    use super::*;
6255    use der::Decode;
6256
6257    // GRY_NOW is also the test time for these fixtures (2026-06-01T00:00:00Z).
6258    const PC_NOW: u64 = 1_780_272_000;
6259
6260    // OID constants — values from const_oid spec, NOT derived from the code under test.
6261    // ecdsa-with-SHA256: 1.2.840.10045.4.3.2  (RFC 5912 §6)
6262    const ECDSA_SHA256_OID: der::asn1::ObjectIdentifier =
6263        der::asn1::ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.2");
6264    // sha256WithRSAEncryption: 1.2.840.113549.1.1.11  (RFC 5912 §2)
6265    const RSA_SHA256_OID: der::asn1::ObjectIdentifier =
6266        der::asn1::ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.11");
6267    // id-kp-serverAuth: 1.3.6.1.5.5.7.3.1  (RFC 5280 §4.2.1.12)
6268    const ID_KP_SERVER_AUTH: der::asn1::ObjectIdentifier =
6269        der::asn1::ObjectIdentifier::new_unwrap("1.3.6.1.5.5.7.3.1");
6270    // id-kp-emailProtection: 1.3.6.1.5.5.7.3.4  (RFC 5280 §4.2.1.12)
6271    const ID_KP_EMAIL_PROTECTION: der::asn1::ObjectIdentifier =
6272        der::asn1::ObjectIdentifier::new_unwrap("1.3.6.1.5.5.7.3.4");
6273
6274    fn load(bytes: &[u8]) -> Certificate {
6275        Certificate::from_der(bytes).expect("valid DER fixture")
6276    }
6277
6278    // -----------------------------------------------------------------------
6279    // max_validity_secs (PKIX-ken.1.9)
6280    // -----------------------------------------------------------------------
6281
6282    /// Oracle: all certs in the chain have validity ≤ 3652 days (10-year root/int,
6283    /// 365-day leaf). A cap of 4000 days allows all of them through.
6284    #[test]
6285    fn max_validity_passes_when_cert_within_limit() {
6286        let root = load(include_bytes!(
6287            "../tests/fixtures/policy-checks/root-p256.der"
6288        ));
6289        let int_cert = load(include_bytes!(
6290            "../tests/fixtures/policy-checks/int-p256.der"
6291        ));
6292        let leaf = load(include_bytes!(
6293            "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
6294        ));
6295        let mut policy = ValidationPolicy::new(PC_NOW);
6296        // 4000-day cap: root/int have ~3652 days, leaf has 365 days — all within limit.
6297        policy.max_validity_secs = Some(4_000 * 86_400);
6298        let anchors = [TrustAnchor::from_cert(root)];
6299        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
6300            .expect("all certs within 4000-day cap should validate");
6301    }
6302
6303    /// Oracle: root-p256.der and int-p256.der each have ~3652-day validity
6304    /// (NOT_BEFORE=2026-01-01, NOT_AFTER=2036-01-01 from gen.py).
6305    /// A cap of 400 days forces `ValidityPeriodExceedsMax` on the root (checked first
6306    /// by `chain_walk` which iterates from high index to low).
6307    ///
6308    /// Note: the check applies to every cert in the chain, not just the leaf.
6309    /// The root cert (highest index) is checked first and produces the error.
6310    #[test]
6311    fn max_validity_fails_when_cert_exceeds_limit() {
6312        let root = load(include_bytes!(
6313            "../tests/fixtures/policy-checks/root-p256.der"
6314        ));
6315        let int_cert = load(include_bytes!(
6316            "../tests/fixtures/policy-checks/int-p256.der"
6317        ));
6318        let leaf = load(include_bytes!(
6319            "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
6320        ));
6321        let mut policy = ValidationPolicy::new(PC_NOW);
6322        // 400-day cap: root/int have 3652-day validity → ValidityPeriodExceedsMax.
6323        // Wildcard index because the root (highest-index cert) is checked first.
6324        policy.max_validity_secs = Some(400 * 86_400);
6325        let anchors = [TrustAnchor::from_cert(root)];
6326        assert!(
6327            matches!(
6328                validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
6329                Err(Error::ValidityPeriodExceedsMax { .. })
6330            ),
6331            "certs with 3652-day validity over 400-day cap must return ValidityPeriodExceedsMax"
6332        );
6333    }
6334
6335    /// Isolates the leaf-only failure: use a 1-cert self-issued chain where
6336    /// the cert acts as both leaf and anchor. The 400-day cert fails a 398-day cap.
6337    ///
6338    /// Oracle: leaf-p256-400d-san-eku.der has notAfter-notBefore = 400 days = 34,560,000 s.
6339    /// 400 days > 398 days → `ValidityPeriodExceedsMax` { index: 0 }.
6340    #[test]
6341    fn max_validity_fails_at_leaf_index_zero() {
6342        // Use a single self-signed cert as both chain[0] and anchor so there is only
6343        // one cert in the chain, making index 0 the only possible failure point.
6344        // leaf-p256-400d-san-eku.der is NOT self-signed, so we use a known self-signed
6345        // cert from the existing fixture set (ec-p256-sha256.der) which has a long
6346        // validity, then set max to 1 day to force failure at index 0.
6347        let cert = Certificate::from_der(include_bytes!("../tests/fixtures/ec-p256-sha256.der"))
6348            .expect("parse ec-p256-sha256.der");
6349        let anchors = [TrustAnchor::from_cert(cert.clone())];
6350        let mut policy = ValidationPolicy::new(1_780_272_000); // PC_NOW: 2026-06-01
6351                                                               // 1-day cap: the cert has multi-year validity → fails at index 0.
6352        policy.max_validity_secs = Some(86_400);
6353        assert!(
6354            matches!(
6355                validate_path(&[cert], &anchors, &policy, &EcdsaP256Verifier),
6356                Err(Error::ValidityPeriodExceedsMax { index: 0 })
6357            ),
6358            "1-cert chain: long-validity cert with 1-day cap must return ValidityPeriodExceedsMax {{ index: 0 }}"
6359        );
6360    }
6361
6362    /// The cap is a maximum, so a cert whose validity is exactly the cap
6363    /// passes and one second more fails.
6364    ///
6365    /// Both bounds come from the fixture rather than from a constant here:
6366    /// the test asks "is the comparison inclusive at the documented end",
6367    /// and a hard-coded duration would make it ask whether the fixture
6368    /// still has the duration it had when the test was written. The other
6369    /// tests in this section are all orders of magnitude away from the
6370    /// boundary, so `>` read as `>=` left them all passing.
6371    #[test]
6372    fn max_validity_admits_a_cert_exactly_at_the_cap() {
6373        let cert = Certificate::from_der(include_bytes!("../tests/fixtures/ec-p256-sha256.der"))
6374            .expect("parse ec-p256-sha256.der");
6375        let validity = cert.tbs_certificate().validity();
6376        let exact = validity.not_after.to_unix_duration().as_secs()
6377            - validity.not_before.to_unix_duration().as_secs();
6378        let anchors = [TrustAnchor::from_cert(cert.clone())];
6379
6380        let mut policy = ValidationPolicy::new(1_780_272_000); // 2026-06-01
6381        policy.max_validity_secs = Some(exact);
6382        validate_path(
6383            core::slice::from_ref(&cert),
6384            &anchors,
6385            &policy,
6386            &EcdsaP256Verifier,
6387        )
6388        .expect("a validity period equal to the cap is within the cap");
6389
6390        policy.max_validity_secs = Some(exact - 1);
6391        assert!(
6392            matches!(
6393                validate_path(
6394                    core::slice::from_ref(&cert),
6395                    &anchors,
6396                    &policy,
6397                    &EcdsaP256Verifier
6398                ),
6399                Err(Error::ValidityPeriodExceedsMax { index: 0 })
6400            ),
6401            "one second over the cap must be refused"
6402        );
6403    }
6404
6405    /// Oracle: None = unconstrained, any validity length is accepted.
6406    #[test]
6407    fn max_validity_none_is_unconstrained() {
6408        let root = load(include_bytes!(
6409            "../tests/fixtures/policy-checks/root-p256.der"
6410        ));
6411        let int_cert = load(include_bytes!(
6412            "../tests/fixtures/policy-checks/int-p256.der"
6413        ));
6414        let leaf = load(include_bytes!(
6415            "../tests/fixtures/policy-checks/leaf-p256-400d-san-eku.der"
6416        ));
6417        let mut policy = ValidationPolicy::new(PC_NOW);
6418        policy.max_validity_secs = None; // default, but explicit for documentation
6419        let anchors = [TrustAnchor::from_cert(root)];
6420        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
6421            .expect("None cap must accept any validity length");
6422    }
6423
6424    // -----------------------------------------------------------------------
6425    // allowed_signature_algs (PKIX-ken.1.10)
6426    // -----------------------------------------------------------------------
6427
6428    /// Oracle: P-256 chain uses ecdsa-with-SHA256; allowlist contains that OID.
6429    #[test]
6430    fn alg_allowlist_passes_when_oid_in_list() {
6431        let root = load(include_bytes!(
6432            "../tests/fixtures/policy-checks/root-p256.der"
6433        ));
6434        let int_cert = load(include_bytes!(
6435            "../tests/fixtures/policy-checks/int-p256.der"
6436        ));
6437        let leaf = load(include_bytes!(
6438            "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
6439        ));
6440        let mut policy = ValidationPolicy::new(PC_NOW);
6441        policy.allowed_signature_algs = Some(vec![ECDSA_SHA256_OID]);
6442        let anchors = [TrustAnchor::from_cert(root)];
6443        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
6444            .expect("ECDSA-SHA256 chain with ECDSA-SHA256 allowlist should pass");
6445    }
6446
6447    /// Oracle: P-256 chain uses ecdsa-sha256; allowlist contains only RSA-sha256.
6448    /// `chain_walk` walks highest index first: leaf=[0], int=[1], root=[2].
6449    /// For a 3-cert chain, the root-adjacent cert is at index 2 in the slice.
6450    /// `chain_walk` iterates i from (chain.len()-1) down to 0, so i=2 (root) is checked
6451    /// first and fails with `AlgorithmNotAllowed` { index: 2 }.
6452    #[test]
6453    fn alg_allowlist_fails_when_oid_not_in_list() {
6454        let root = load(include_bytes!(
6455            "../tests/fixtures/policy-checks/root-p256.der"
6456        ));
6457        let int_cert = load(include_bytes!(
6458            "../tests/fixtures/policy-checks/int-p256.der"
6459        ));
6460        let leaf = load(include_bytes!(
6461            "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
6462        ));
6463        let mut policy = ValidationPolicy::new(PC_NOW);
6464        // Only RSA allowed, but chain uses ECDSA.
6465        policy.allowed_signature_algs = Some(vec![RSA_SHA256_OID]);
6466        let anchors = [TrustAnchor::from_cert(root)];
6467        assert!(
6468            matches!(
6469                validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
6470                Err(Error::AlgorithmNotAllowed { .. })
6471            ),
6472            "ECDSA chain with RSA-only allowlist must return AlgorithmNotAllowed"
6473        );
6474    }
6475
6476    /// Oracle: None = unconstrained, any algorithm is accepted.
6477    #[test]
6478    fn alg_allowlist_none_is_unconstrained() {
6479        let root = load(include_bytes!(
6480            "../tests/fixtures/policy-checks/root-p256.der"
6481        ));
6482        let int_cert = load(include_bytes!(
6483            "../tests/fixtures/policy-checks/int-p256.der"
6484        ));
6485        let leaf = load(include_bytes!(
6486            "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
6487        ));
6488        let mut policy = ValidationPolicy::new(PC_NOW);
6489        policy.allowed_signature_algs = None; // default
6490        let anchors = [TrustAnchor::from_cert(root)];
6491        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
6492            .expect("None allowlist must accept any algorithm");
6493    }
6494
6495    // -----------------------------------------------------------------------
6496    // require_subject_alt_name (PKIX-ken.1.12)
6497    // -----------------------------------------------------------------------
6498
6499    /// Oracle: leaf-p256-365d-san-eku.der has SAN=DNS:test.example.com.
6500    #[test]
6501    fn require_san_passes_when_san_present() {
6502        let root = load(include_bytes!(
6503            "../tests/fixtures/policy-checks/root-p256.der"
6504        ));
6505        let int_cert = load(include_bytes!(
6506            "../tests/fixtures/policy-checks/int-p256.der"
6507        ));
6508        let leaf = load(include_bytes!(
6509            "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
6510        ));
6511        let mut policy = ValidationPolicy::new(PC_NOW);
6512        policy.require_subject_alt_name = true;
6513        let anchors = [TrustAnchor::from_cert(root)];
6514        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
6515            .expect("leaf with SAN must pass require_subject_alt_name=true");
6516    }
6517
6518    /// Oracle: leaf-p256-365d-no-san.der has no SAN extension.
6519    #[test]
6520    fn require_san_fails_when_san_absent() {
6521        let root = load(include_bytes!(
6522            "../tests/fixtures/policy-checks/root-p256.der"
6523        ));
6524        let int_cert = load(include_bytes!(
6525            "../tests/fixtures/policy-checks/int-p256.der"
6526        ));
6527        let leaf = load(include_bytes!(
6528            "../tests/fixtures/policy-checks/leaf-p256-365d-no-san.der"
6529        ));
6530        let mut policy = ValidationPolicy::new(PC_NOW);
6531        policy.require_subject_alt_name = true;
6532        let anchors = [TrustAnchor::from_cert(root)];
6533        assert!(
6534            matches!(
6535                validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
6536                Err(Error::MissingSan)
6537            ),
6538            "leaf without SAN must return MissingSan when require_subject_alt_name=true"
6539        );
6540    }
6541
6542    /// Oracle: false = default = no SAN requirement; missing SAN is not an error.
6543    #[test]
6544    fn require_san_false_does_not_fail_on_missing_san() {
6545        let root = load(include_bytes!(
6546            "../tests/fixtures/policy-checks/root-p256.der"
6547        ));
6548        let int_cert = load(include_bytes!(
6549            "../tests/fixtures/policy-checks/int-p256.der"
6550        ));
6551        let leaf = load(include_bytes!(
6552            "../tests/fixtures/policy-checks/leaf-p256-365d-no-san.der"
6553        ));
6554        let mut policy = ValidationPolicy::new(PC_NOW);
6555        policy.require_subject_alt_name = false; // default, explicit for documentation
6556        let anchors = [TrustAnchor::from_cert(root)];
6557        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
6558            .expect("require_subject_alt_name=false must not fail on missing SAN");
6559    }
6560
6561    /// Regression guard for the i == 0 guard in `chain_walk`.
6562    ///
6563    /// int-p256.der has no SAN extension. With `require_subject_alt_name=true`,
6564    /// the check MUST NOT fail on the intermediate (i == 1). Only the leaf
6565    /// (i == 0) is checked.
6566    ///
6567    /// Oracle: openssl x509 -inform DER -in int-p256.der -text -noout | grep -i alt
6568    /// → empty output; int-p256.der has no SAN. Confirmed during fixture generation.
6569    #[test]
6570    fn require_san_only_checks_leaf_not_intermediates() {
6571        let root = load(include_bytes!(
6572            "../tests/fixtures/policy-checks/root-p256.der"
6573        ));
6574        let int_cert = load(include_bytes!(
6575            "../tests/fixtures/policy-checks/int-p256.der"
6576        ));
6577        // The leaf HAS a SAN; the intermediate does NOT.
6578        let leaf = load(include_bytes!(
6579            "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
6580        ));
6581        let mut policy = ValidationPolicy::new(PC_NOW);
6582        policy.require_subject_alt_name = true;
6583        let anchors = [TrustAnchor::from_cert(root)];
6584        // Must pass: the SAN-less intermediate is not checked, only the leaf.
6585        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
6586            .expect("i==0 guard must ensure only the leaf is checked for SAN presence");
6587    }
6588
6589    // -----------------------------------------------------------------------
6590    // required_leaf_eku (PKIX-ken.1.13)
6591    // -----------------------------------------------------------------------
6592
6593    /// Oracle: leaf-p256-365d-san-eku.der has EKU=serverAuth (1.3.6.1.5.5.7.3.1).
6594    #[test]
6595    fn required_eku_passes_when_all_oids_present() {
6596        let root = load(include_bytes!(
6597            "../tests/fixtures/policy-checks/root-p256.der"
6598        ));
6599        let int_cert = load(include_bytes!(
6600            "../tests/fixtures/policy-checks/int-p256.der"
6601        ));
6602        let leaf = load(include_bytes!(
6603            "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
6604        ));
6605        let mut policy = ValidationPolicy::new(PC_NOW);
6606        policy.required_leaf_eku = Some(vec![ID_KP_SERVER_AUTH]);
6607        let anchors = [TrustAnchor::from_cert(root)];
6608        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
6609            .expect("leaf with serverAuth EKU must pass required_leaf_eku=[serverAuth]");
6610    }
6611
6612    /// Oracle: leaf-p256-365d-no-eku.der has no EKU extension.
6613    /// `required_leaf_eku=Some`([serverAuth]) with absent EKU → `MissingEku`.
6614    #[test]
6615    fn required_eku_fails_when_eku_extension_absent() {
6616        let root = load(include_bytes!(
6617            "../tests/fixtures/policy-checks/root-p256.der"
6618        ));
6619        let int_cert = load(include_bytes!(
6620            "../tests/fixtures/policy-checks/int-p256.der"
6621        ));
6622        let leaf = load(include_bytes!(
6623            "../tests/fixtures/policy-checks/leaf-p256-365d-no-eku.der"
6624        ));
6625        let mut policy = ValidationPolicy::new(PC_NOW);
6626        policy.required_leaf_eku = Some(vec![ID_KP_SERVER_AUTH]);
6627        let anchors = [TrustAnchor::from_cert(root)];
6628        assert!(
6629            matches!(
6630                validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
6631                Err(Error::MissingEku)
6632            ),
6633            "leaf without EKU extension must return MissingEku when an EKU OID is required"
6634        );
6635    }
6636
6637    /// Oracle: leaf-p256-365d-wrong-eku.der has EKU=emailProtection only, not serverAuth.
6638    #[test]
6639    fn required_eku_fails_when_required_oid_not_in_list() {
6640        let root = load(include_bytes!(
6641            "../tests/fixtures/policy-checks/root-p256.der"
6642        ));
6643        let int_cert = load(include_bytes!(
6644            "../tests/fixtures/policy-checks/int-p256.der"
6645        ));
6646        let leaf = load(include_bytes!(
6647            "../tests/fixtures/policy-checks/leaf-p256-365d-wrong-eku.der"
6648        ));
6649        let mut policy = ValidationPolicy::new(PC_NOW);
6650        // Requires serverAuth; leaf only has emailProtection.
6651        policy.required_leaf_eku = Some(vec![ID_KP_SERVER_AUTH]);
6652        let anchors = [TrustAnchor::from_cert(root)];
6653        assert!(
6654            matches!(
6655                validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
6656                Err(Error::MissingEku)
6657            ),
6658            "leaf with wrong EKU must return MissingEku when required OID is absent"
6659        );
6660    }
6661
6662    /// Oracle: None = no EKU requirement; missing EKU is not an error.
6663    #[test]
6664    fn required_eku_none_is_unconstrained() {
6665        let root = load(include_bytes!(
6666            "../tests/fixtures/policy-checks/root-p256.der"
6667        ));
6668        let int_cert = load(include_bytes!(
6669            "../tests/fixtures/policy-checks/int-p256.der"
6670        ));
6671        let leaf = load(include_bytes!(
6672            "../tests/fixtures/policy-checks/leaf-p256-365d-no-eku.der"
6673        ));
6674        let mut policy = ValidationPolicy::new(PC_NOW);
6675        policy.required_leaf_eku = None; // default
6676        let anchors = [TrustAnchor::from_cert(root)];
6677        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
6678            .expect("None required_leaf_eku must accept leaf with no EKU");
6679    }
6680
6681    /// Oracle: Some([]) = require zero OIDs → trivially passes regardless of EKU content.
6682    #[test]
6683    fn required_eku_empty_vec_is_unconstrained() {
6684        let root = load(include_bytes!(
6685            "../tests/fixtures/policy-checks/root-p256.der"
6686        ));
6687        let int_cert = load(include_bytes!(
6688            "../tests/fixtures/policy-checks/int-p256.der"
6689        ));
6690        let leaf = load(include_bytes!(
6691            "../tests/fixtures/policy-checks/leaf-p256-365d-no-eku.der"
6692        ));
6693        let mut policy = ValidationPolicy::new(PC_NOW);
6694        // Empty vec: Some([]) requires zero OIDs → always passes.
6695        policy.required_leaf_eku = Some(vec![]);
6696        let anchors = [TrustAnchor::from_cert(root)];
6697        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
6698            .expect("Some([]) required_leaf_eku (empty) must accept any EKU configuration");
6699    }
6700
6701    /// Verify that emailProtection in `required_leaf_eku` does NOT match serverAuth in the cert.
6702    /// This guards against a hypothetical relaxed OID comparison bug.
6703    #[test]
6704    fn required_eku_emailprotection_does_not_match_serverauth() {
6705        let root = load(include_bytes!(
6706            "../tests/fixtures/policy-checks/root-p256.der"
6707        ));
6708        let int_cert = load(include_bytes!(
6709            "../tests/fixtures/policy-checks/int-p256.der"
6710        ));
6711        let leaf = load(include_bytes!(
6712            "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
6713        ));
6714        let mut policy = ValidationPolicy::new(PC_NOW);
6715        // Require emailProtection; leaf only has serverAuth.
6716        policy.required_leaf_eku = Some(vec![ID_KP_EMAIL_PROTECTION]);
6717        let anchors = [TrustAnchor::from_cert(root)];
6718        assert!(
6719            matches!(
6720                validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
6721                Err(Error::MissingEku)
6722            ),
6723            "OID comparison must be exact; emailProtection must not match serverAuth"
6724        );
6725    }
6726}
6727
6728// DnAttrRule + required_leaf_policy_oids + required_leaf_subject_dn_attrs tests (PKIX-jbvb.4).
6729//
6730// Coverage strategy:
6731// - `dn_attr_rule_*` tests exercise `evaluate_dn_attr_rule` and `dn_contains_oid`
6732//   directly against synthetic `Name` values constructed via RFC 4514 string
6733//   parsing. This isolates rule semantics from chain-validation wiring.
6734// - `validate_path_*` tests exercise the (e3a)/(e3b) enforcement sites in
6735//   `chain_walk` via existing committed P-256 fixtures. Existing fixtures lack
6736//   `CertificatePolicies` extensions and have CN-only Subject DNs, so they
6737//   naturally test the "required attribute missing" paths.
6738// - The `None`-case sanity tests confirm default behavior is unchanged.
6739//
6740// Positive `validate_path` cases for `required_leaf_policy_oids` (leaf asserts
6741// the required OID → pass) are covered indirectly: the (e3a) match arm with
6742// `Some(cp_ext)` is unit-tested via the `dn_contains_oid`-style helper logic on
6743// `policy_identifier`, and the wiring is exercised by the negative tests.
6744// Adding a new fixture solely for the positive path would duplicate that
6745// coverage without adding rigor; the bead's "existing fixtures cannot exercise"
6746// escape applies to the OID-list-walk shape, not the wiring.
6747#[cfg(test)]
6748mod tests_dn_attr_rule {
6749    use super::*;
6750    use core::str::FromStr;
6751
6752    // RFC 4519 / X.520 DN attribute OIDs (values from spec, not derived from code under test).
6753    const OID_CN: der::asn1::ObjectIdentifier = der::asn1::ObjectIdentifier::new_unwrap("2.5.4.3");
6754    const OID_SURNAME: der::asn1::ObjectIdentifier =
6755        der::asn1::ObjectIdentifier::new_unwrap("2.5.4.4");
6756    const OID_ORGANIZATION_NAME: der::asn1::ObjectIdentifier =
6757        der::asn1::ObjectIdentifier::new_unwrap("2.5.4.10");
6758    const OID_GIVEN_NAME: der::asn1::ObjectIdentifier =
6759        der::asn1::ObjectIdentifier::new_unwrap("2.5.4.42");
6760    const OID_PSEUDONYM: der::asn1::ObjectIdentifier =
6761        der::asn1::ObjectIdentifier::new_unwrap("2.5.4.65");
6762
6763    fn dn(s: &str) -> x509_cert::name::Name {
6764        x509_cert::name::Name::from_str(s).expect("valid RFC 4514 DN string")
6765    }
6766
6767    // ---- dn_contains_oid -----------------------------------------------------
6768
6769    #[test]
6770    fn dn_contains_oid_finds_present_attribute() {
6771        let subject = dn("CN=test,O=Test Org");
6772        assert!(dn_contains_oid(&subject, &OID_ORGANIZATION_NAME));
6773        assert!(dn_contains_oid(&subject, &OID_CN));
6774    }
6775
6776    #[test]
6777    fn dn_contains_oid_returns_false_for_absent_attribute() {
6778        let subject = dn("CN=test");
6779        assert!(!dn_contains_oid(&subject, &OID_ORGANIZATION_NAME));
6780        assert!(!dn_contains_oid(&subject, &OID_SURNAME));
6781    }
6782
6783    #[test]
6784    fn dn_contains_oid_empty_subject_matches_nothing() {
6785        let subject = x509_cert::name::Name::default();
6786        assert!(!dn_contains_oid(&subject, &OID_CN));
6787    }
6788
6789    // ---- evaluate_dn_attr_rule: Field ---------------------------------------
6790
6791    #[test]
6792    fn rule_field_matches_when_attribute_present() {
6793        let subject = dn("CN=test,O=Test Org");
6794        let rule = DnAttrRule::Field(OID_ORGANIZATION_NAME);
6795        assert!(evaluate_dn_attr_rule(&subject, &rule));
6796    }
6797
6798    #[test]
6799    fn rule_field_rejects_when_attribute_absent() {
6800        let subject = dn("CN=test");
6801        let rule = DnAttrRule::Field(OID_ORGANIZATION_NAME);
6802        assert!(!evaluate_dn_attr_rule(&subject, &rule));
6803    }
6804
6805    // ---- evaluate_dn_attr_rule: AllOf composition ---------------------------
6806
6807    #[test]
6808    fn rule_allof_matches_when_every_branch_satisfied() {
6809        let subject = dn("CN=test,givenName=Alice,surname=Smith");
6810        let rule = DnAttrRule::AllOf(vec![
6811            DnAttrRule::Field(OID_GIVEN_NAME),
6812            DnAttrRule::Field(OID_SURNAME),
6813        ]);
6814        assert!(evaluate_dn_attr_rule(&subject, &rule));
6815    }
6816
6817    #[test]
6818    fn rule_allof_rejects_when_any_branch_missing() {
6819        let subject = dn("CN=test,givenName=Alice");
6820        let rule = DnAttrRule::AllOf(vec![
6821            DnAttrRule::Field(OID_GIVEN_NAME),
6822            DnAttrRule::Field(OID_SURNAME),
6823        ]);
6824        assert!(!evaluate_dn_attr_rule(&subject, &rule));
6825    }
6826
6827    // ---- evaluate_dn_attr_rule: AnyOf composition ---------------------------
6828
6829    #[test]
6830    fn rule_anyof_matches_when_at_least_one_branch_satisfied() {
6831        let subject = dn("CN=test,pseudonym=BlueFox");
6832        let rule = DnAttrRule::AnyOf(vec![
6833            DnAttrRule::Field(OID_PSEUDONYM),
6834            DnAttrRule::AllOf(vec![
6835                DnAttrRule::Field(OID_GIVEN_NAME),
6836                DnAttrRule::Field(OID_SURNAME),
6837            ]),
6838        ]);
6839        assert!(evaluate_dn_attr_rule(&subject, &rule));
6840    }
6841
6842    #[test]
6843    fn rule_anyof_rejects_when_no_branch_satisfied() {
6844        let subject = dn("CN=test");
6845        let rule = DnAttrRule::AnyOf(vec![
6846            DnAttrRule::Field(OID_PSEUDONYM),
6847            DnAttrRule::AllOf(vec![
6848                DnAttrRule::Field(OID_GIVEN_NAME),
6849                DnAttrRule::Field(OID_SURNAME),
6850            ]),
6851        ]);
6852        assert!(!evaluate_dn_attr_rule(&subject, &rule));
6853    }
6854
6855    /// Sponsor-validated-style rule (pseudonym OR (givenName AND surname))
6856    /// also matches when both branches of the inner AllOf are present.
6857    #[test]
6858    fn rule_anyof_matches_when_inner_allof_branch_satisfied() {
6859        let subject = dn("CN=test,givenName=Alice,surname=Smith");
6860        let rule = DnAttrRule::AnyOf(vec![
6861            DnAttrRule::Field(OID_PSEUDONYM),
6862            DnAttrRule::AllOf(vec![
6863                DnAttrRule::Field(OID_GIVEN_NAME),
6864                DnAttrRule::Field(OID_SURNAME),
6865            ]),
6866        ]);
6867        assert!(evaluate_dn_attr_rule(&subject, &rule));
6868    }
6869
6870    // ---- evaluate_dn_attr_rule: vacuity -------------------------------------
6871
6872    /// RFC-conventional vacuity: AllOf with no branches is trivially true
6873    /// (the universal quantifier over an empty set is true).
6874    #[test]
6875    fn rule_allof_empty_accepts_everything() {
6876        let empty = x509_cert::name::Name::default();
6877        let cn_only = dn("CN=test");
6878        let rule = DnAttrRule::AllOf(Vec::new());
6879        assert!(evaluate_dn_attr_rule(&empty, &rule));
6880        assert!(evaluate_dn_attr_rule(&cn_only, &rule));
6881    }
6882
6883    /// RFC-conventional vacuity: AnyOf with no branches is trivially false
6884    /// (the existential quantifier over an empty set is false).
6885    #[test]
6886    fn rule_anyof_empty_rejects_everything() {
6887        let empty = x509_cert::name::Name::default();
6888        let cn_only = dn("CN=test");
6889        let rule = DnAttrRule::AnyOf(Vec::new());
6890        assert!(!evaluate_dn_attr_rule(&empty, &rule));
6891        assert!(!evaluate_dn_attr_rule(&cn_only, &rule));
6892    }
6893}
6894
6895// ---------------------------------------------------------------------------
6896// required_leaf_policy_oids + required_leaf_subject_dn_attrs validate_path wiring
6897// (PKIX-jbvb.4). Reuses existing P-256 fixtures (which carry single-attribute
6898// CN-only DNs and no CertificatePolicies extension) to cover the negative and
6899// disabled-default paths.
6900// ---------------------------------------------------------------------------
6901#[cfg(all(test, feature = "p256"))]
6902mod tests_required_leaf_policy_dn {
6903    use super::*;
6904    use der::Decode;
6905
6906    // GRY_NOW = 2026-06-01T00:00:00Z (matches the existing P-256 fixture timestamps).
6907    const PC_NOW: u64 = 1_780_272_000;
6908
6909    // 2.16.840.1.101.3.2.1.48.1 — a NIST test policy OID. The chosen value is
6910    // arbitrary; only its absence from any committed fixture matters.
6911    const TEST_POLICY_OID: der::asn1::ObjectIdentifier =
6912        der::asn1::ObjectIdentifier::new_unwrap("2.16.840.1.101.3.2.1.48.1");
6913    const OID_ORGANIZATION_NAME: der::asn1::ObjectIdentifier =
6914        der::asn1::ObjectIdentifier::new_unwrap("2.5.4.10");
6915
6916    fn load(bytes: &[u8]) -> Certificate {
6917        Certificate::from_der(bytes).expect("valid DER fixture")
6918    }
6919
6920    fn make_chain() -> (Certificate, Certificate, Certificate) {
6921        let root = load(include_bytes!(
6922            "../tests/fixtures/policy-checks/root-p256.der"
6923        ));
6924        let int_cert = load(include_bytes!(
6925            "../tests/fixtures/policy-checks/int-p256.der"
6926        ));
6927        let leaf = load(include_bytes!(
6928            "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
6929        ));
6930        (root, int_cert, leaf)
6931    }
6932
6933    /// Oracle: `leaf-p256-365d-san-eku.der` has no CertificatePolicies
6934    /// extension. Requiring any specific policy OID must fail.
6935    #[test]
6936    fn required_policy_oid_fails_when_extension_absent() {
6937        let (root, int_cert, leaf) = make_chain();
6938        let mut policy = ValidationPolicy::new(PC_NOW);
6939        policy.required_leaf_policy_oids = Some(vec![TEST_POLICY_OID]);
6940        let anchors = [TrustAnchor::from_cert(root)];
6941        let err = validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
6942            .expect_err("leaf without CertificatePolicies must fail when an OID is required");
6943        match err {
6944            Error::MissingLeafPolicyOid { required } => {
6945                assert_eq!(required, TEST_POLICY_OID, "reported OID must echo input");
6946            }
6947            other => panic!("expected MissingLeafPolicyOid, got {other:?}"),
6948        }
6949    }
6950
6951    /// Oracle: `None` requirement is unconstrained even when the leaf has no
6952    /// `CertificatePolicies` extension. Backward-compatible default.
6953    #[test]
6954    fn required_policy_oid_none_is_unconstrained() {
6955        let (root, int_cert, leaf) = make_chain();
6956        let mut policy = ValidationPolicy::new(PC_NOW);
6957        policy.required_leaf_policy_oids = None;
6958        let anchors = [TrustAnchor::from_cert(root)];
6959        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
6960            .expect("None required_leaf_policy_oids must not constrain validation");
6961    }
6962
6963    /// Oracle: `Some(vec![])` requires zero OIDs → trivially passes regardless
6964    /// of CertificatePolicies content (mirrors `required_leaf_eku = Some(vec![])`).
6965    #[test]
6966    fn required_policy_oid_empty_vec_is_unconstrained() {
6967        let (root, int_cert, leaf) = make_chain();
6968        let mut policy = ValidationPolicy::new(PC_NOW);
6969        policy.required_leaf_policy_oids = Some(vec![]);
6970        let anchors = [TrustAnchor::from_cert(root)];
6971        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
6972            .expect("Some([]) required_leaf_policy_oids must accept any CertificatePolicies");
6973    }
6974
6975    /// Oracle: `leaf-p256-365d-san-eku.der` has Subject DN
6976    /// `CN=PKIX-policy-checks-leaf-p256-365d-san-eku` (no organizationName).
6977    /// Requiring `organizationName` must fail with `SubjectDnAttrRuleUnmet`.
6978    #[test]
6979    fn required_dn_attr_field_fails_when_attribute_absent() {
6980        let (root, int_cert, leaf) = make_chain();
6981        let mut policy = ValidationPolicy::new(PC_NOW);
6982        policy.required_leaf_subject_dn_attrs = Some(DnAttrRule::Field(OID_ORGANIZATION_NAME));
6983        let anchors = [TrustAnchor::from_cert(root)];
6984        assert!(
6985            matches!(
6986                validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
6987                Err(Error::SubjectDnAttrRuleUnmet)
6988            ),
6989            "leaf without organizationName must return SubjectDnAttrRuleUnmet"
6990        );
6991    }
6992
6993    /// Oracle: `leaf-p256-365d-san-eku.der` has only `CN=...`.
6994    /// `Field(CN)` must succeed (the attribute is present).
6995    #[test]
6996    fn required_dn_attr_field_passes_when_attribute_present() {
6997        let (root, int_cert, leaf) = make_chain();
6998        let mut policy = ValidationPolicy::new(PC_NOW);
6999        // CN = 2.5.4.3
7000        let oid_cn: der::asn1::ObjectIdentifier =
7001            der::asn1::ObjectIdentifier::new_unwrap("2.5.4.3");
7002        policy.required_leaf_subject_dn_attrs = Some(DnAttrRule::Field(oid_cn));
7003        let anchors = [TrustAnchor::from_cert(root)];
7004        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
7005            .expect("leaf with CN must pass Field(CN) requirement");
7006    }
7007
7008    /// Oracle: AllOf(vec![]) is vacuously true; chain must validate without
7009    /// any DN constraints actually being checked.
7010    #[test]
7011    fn required_dn_attr_allof_empty_accepts_any_leaf() {
7012        let (root, int_cert, leaf) = make_chain();
7013        let mut policy = ValidationPolicy::new(PC_NOW);
7014        policy.required_leaf_subject_dn_attrs = Some(DnAttrRule::AllOf(Vec::new()));
7015        let anchors = [TrustAnchor::from_cert(root)];
7016        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
7017            .expect("AllOf(vec![]) is vacuously true; validation must succeed");
7018    }
7019
7020    /// Oracle: AnyOf(vec![]) is vacuously false; any leaf fails.
7021    #[test]
7022    fn required_dn_attr_anyof_empty_rejects_any_leaf() {
7023        let (root, int_cert, leaf) = make_chain();
7024        let mut policy = ValidationPolicy::new(PC_NOW);
7025        policy.required_leaf_subject_dn_attrs = Some(DnAttrRule::AnyOf(Vec::new()));
7026        let anchors = [TrustAnchor::from_cert(root)];
7027        assert!(
7028            matches!(
7029                validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
7030                Err(Error::SubjectDnAttrRuleUnmet)
7031            ),
7032            "AnyOf(vec![]) is vacuously false; validation must fail"
7033        );
7034    }
7035
7036    /// Oracle: `None` is the default and must not constrain validation.
7037    #[test]
7038    fn required_dn_attr_none_is_unconstrained() {
7039        let (root, int_cert, leaf) = make_chain();
7040        let mut policy = ValidationPolicy::new(PC_NOW);
7041        policy.required_leaf_subject_dn_attrs = None;
7042        let anchors = [TrustAnchor::from_cert(root)];
7043        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
7044            .expect("None required_leaf_subject_dn_attrs must not constrain validation");
7045    }
7046}
7047
7048// RSA-specific policy field tests — gated on the rsa feature.
7049#[cfg(all(test, feature = "p256", feature = "rsa"))]
7050mod tests_policy_fields_rsa {
7051    use super::*;
7052    use der::Decode;
7053
7054    const PC_NOW: u64 = 1_780_272_000;
7055
7056    // sha256WithRSAEncryption: 1.2.840.113549.1.1.11  (RFC 5912 §2)
7057    const RSA_SHA256_OID: der::asn1::ObjectIdentifier =
7058        der::asn1::ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.11");
7059    // ecdsa-with-SHA256: 1.2.840.10045.4.3.2  (RFC 5912 §6)
7060    const ECDSA_SHA256_OID: der::asn1::ObjectIdentifier =
7061        der::asn1::ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.2");
7062    // id-kp-serverAuth: 1.3.6.1.5.5.7.3.1
7063    const ID_KP_SERVER_AUTH: der::asn1::ObjectIdentifier =
7064        der::asn1::ObjectIdentifier::new_unwrap("1.3.6.1.5.5.7.3.1");
7065
7066    fn load(bytes: &[u8]) -> Certificate {
7067        Certificate::from_der(bytes).expect("valid DER fixture")
7068    }
7069
7070    // -----------------------------------------------------------------------
7071    // min_rsa_key_bits helper unit tests (PKIX-ken.1.11)
7072    // -----------------------------------------------------------------------
7073
7074    /// Direct unit test of `rsa_public_key_bits` helper.
7075    /// Oracle: openssl x509 -inform DER -in leaf-rsa2048.der -text -noout | grep 'Public-Key'
7076    /// → Public-Key: (2048 bit)
7077    #[test]
7078    fn rsa_key_bits_correct_for_2048_key() {
7079        let cert = load(include_bytes!(
7080            "../tests/fixtures/policy-checks/leaf-rsa2048-365d-san-eku.der"
7081        ));
7082        let result = rsa_public_key_bits(cert.tbs_certificate().subject_public_key_info());
7083        assert_eq!(
7084            result,
7085            Some(2048),
7086            "RSA-2048 key must return Some(2048) from rsa_public_key_bits"
7087        );
7088    }
7089
7090    /// Direct unit test of `rsa_public_key_bits` helper.
7091    /// Oracle: openssl x509 -inform DER -in leaf-rsa1024.der -text -noout | grep 'Public-Key'
7092    /// → Public-Key: (1024 bit)
7093    #[test]
7094    fn rsa_key_bits_correct_for_1024_key() {
7095        let cert = load(include_bytes!(
7096            "../tests/fixtures/policy-checks/leaf-rsa1024-365d-san-eku.der"
7097        ));
7098        let result = rsa_public_key_bits(cert.tbs_certificate().subject_public_key_info());
7099        assert_eq!(
7100            result,
7101            Some(1024),
7102            "RSA-1024 key must return Some(1024) from rsa_public_key_bits"
7103        );
7104    }
7105
7106    /// Direct unit test of `rsa_public_key_bits` helper.
7107    /// P-256 key is not RSA; must return None.
7108    #[test]
7109    fn rsa_key_bits_none_for_ec_key() {
7110        let cert = load(include_bytes!(
7111            "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
7112        ));
7113        let result = rsa_public_key_bits(cert.tbs_certificate().subject_public_key_info());
7114        assert_eq!(
7115            result, None,
7116            "EC key must return None from rsa_public_key_bits (not RSA)"
7117        );
7118    }
7119
7120    // -----------------------------------------------------------------------
7121    // min_rsa_key_bits validate_path tests (PKIX-ken.1.11)
7122    // -----------------------------------------------------------------------
7123
7124    /// Oracle: leaf-rsa2048-365d-san-eku.der has RSA-2048 leaf.
7125    /// 2048 >= 2048 → passes.
7126    #[test]
7127    fn min_rsa_key_bits_passes_when_key_meets_limit() {
7128        let root = load(include_bytes!(
7129            "../tests/fixtures/policy-checks/root-rsa2048.der"
7130        ));
7131        let int_cert = load(include_bytes!(
7132            "../tests/fixtures/policy-checks/int-rsa2048.der"
7133        ));
7134        let leaf = load(include_bytes!(
7135            "../tests/fixtures/policy-checks/leaf-rsa2048-365d-san-eku.der"
7136        ));
7137        let mut policy = ValidationPolicy::new(PC_NOW);
7138        policy.min_rsa_key_bits = Some(2048);
7139        let anchors = [TrustAnchor::from_cert(root)];
7140        validate_path(
7141            &[leaf, int_cert],
7142            &anchors,
7143            &policy,
7144            &RsaPkcs1v15Sha256Verifier,
7145        )
7146        .expect("RSA-2048 leaf with min=2048 should pass");
7147    }
7148
7149    /// Oracle: leaf-rsa1024-365d-san-eku.der has RSA-1024 leaf.
7150    /// 1024 < 2048 → `KeyTooSmall` { index: 0 }.
7151    #[test]
7152    fn min_rsa_key_bits_fails_when_key_too_small() {
7153        let root = load(include_bytes!(
7154            "../tests/fixtures/policy-checks/root-rsa2048.der"
7155        ));
7156        let int_cert = load(include_bytes!(
7157            "../tests/fixtures/policy-checks/int-rsa2048.der"
7158        ));
7159        let leaf = load(include_bytes!(
7160            "../tests/fixtures/policy-checks/leaf-rsa1024-365d-san-eku.der"
7161        ));
7162        let mut policy = ValidationPolicy::new(PC_NOW);
7163        policy.min_rsa_key_bits = Some(2048);
7164        let anchors = [TrustAnchor::from_cert(root)];
7165        assert!(
7166            matches!(
7167                validate_path(
7168                    &[leaf, int_cert],
7169                    &anchors,
7170                    &policy,
7171                    &RsaPkcs1v15Sha256Verifier
7172                ),
7173                Err(Error::KeyTooSmall { index: 0 })
7174            ),
7175            "RSA-1024 leaf with min=2048 must return KeyTooSmall {{ index: 0 }}"
7176        );
7177    }
7178
7179    /// Oracle: None = unconstrained; RSA-1024 leaf passes with no key size restriction.
7180    #[test]
7181    fn min_rsa_key_bits_none_is_unconstrained() {
7182        let root = load(include_bytes!(
7183            "../tests/fixtures/policy-checks/root-rsa2048.der"
7184        ));
7185        let int_cert = load(include_bytes!(
7186            "../tests/fixtures/policy-checks/int-rsa2048.der"
7187        ));
7188        let leaf = load(include_bytes!(
7189            "../tests/fixtures/policy-checks/leaf-rsa1024-365d-san-eku.der"
7190        ));
7191        let mut policy = ValidationPolicy::new(PC_NOW);
7192        policy.min_rsa_key_bits = None; // default
7193        let anchors = [TrustAnchor::from_cert(root)];
7194        validate_path(
7195            &[leaf, int_cert],
7196            &anchors,
7197            &policy,
7198            &RsaPkcs1v15Sha256Verifier,
7199        )
7200        .expect("None min_rsa_key_bits must accept RSA-1024 leaf");
7201    }
7202
7203    /// EC key must not be affected by `min_rsa_key_bits` regardless of the value.
7204    /// Oracle: P-256 key is not RSA; `rsa_public_key_bits` returns None → check skipped.
7205    #[test]
7206    fn min_rsa_key_bits_ec_key_passes_unconditionally() {
7207        let root = load(include_bytes!(
7208            "../tests/fixtures/policy-checks/root-p256.der"
7209        ));
7210        let int_cert = load(include_bytes!(
7211            "../tests/fixtures/policy-checks/int-p256.der"
7212        ));
7213        let leaf = load(include_bytes!(
7214            "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
7215        ));
7216        let mut policy = ValidationPolicy::new(PC_NOW);
7217        // Extremely high floor — would reject any RSA key, but P-256 is not RSA.
7218        policy.min_rsa_key_bits = Some(16384);
7219        let anchors = [TrustAnchor::from_cert(root)];
7220        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
7221            .expect("EC key must not be affected by min_rsa_key_bits");
7222    }
7223
7224    // -----------------------------------------------------------------------
7225    // allowed_signature_algs: RSA chain test (PKIX-ken.1.10)
7226    // -----------------------------------------------------------------------
7227
7228    /// Oracle: RSA chain uses sha256WithRSAEncryption; ECDSA-only allowlist must reject it.
7229    #[test]
7230    fn alg_allowlist_fails_on_rsa_chain_when_only_ecdsa_allowed() {
7231        let root = load(include_bytes!(
7232            "../tests/fixtures/policy-checks/root-rsa2048.der"
7233        ));
7234        let int_cert = load(include_bytes!(
7235            "../tests/fixtures/policy-checks/int-rsa2048.der"
7236        ));
7237        let leaf = load(include_bytes!(
7238            "../tests/fixtures/policy-checks/leaf-rsa2048-365d-san-eku.der"
7239        ));
7240        let mut policy = ValidationPolicy::new(PC_NOW);
7241        // Only ECDSA allowed; RSA chain must fail.
7242        policy.allowed_signature_algs = Some(vec![ECDSA_SHA256_OID]);
7243        let anchors = [TrustAnchor::from_cert(root)];
7244        assert!(
7245            matches!(
7246                validate_path(
7247                    &[leaf, int_cert],
7248                    &anchors,
7249                    &policy,
7250                    &RsaPkcs1v15Sha256Verifier
7251                ),
7252                Err(Error::AlgorithmNotAllowed { .. })
7253            ),
7254            "RSA chain with ECDSA-only allowlist must return AlgorithmNotAllowed"
7255        );
7256    }
7257
7258    /// Oracle: RSA chain with RSA in allowlist must pass.
7259    #[test]
7260    fn alg_allowlist_passes_for_rsa_chain() {
7261        let root = load(include_bytes!(
7262            "../tests/fixtures/policy-checks/root-rsa2048.der"
7263        ));
7264        let int_cert = load(include_bytes!(
7265            "../tests/fixtures/policy-checks/int-rsa2048.der"
7266        ));
7267        let leaf = load(include_bytes!(
7268            "../tests/fixtures/policy-checks/leaf-rsa2048-365d-san-eku.der"
7269        ));
7270        let mut policy = ValidationPolicy::new(PC_NOW);
7271        policy.allowed_signature_algs = Some(vec![RSA_SHA256_OID]);
7272        let anchors = [TrustAnchor::from_cert(root)];
7273        validate_path(
7274            &[leaf, int_cert],
7275            &anchors,
7276            &policy,
7277            &RsaPkcs1v15Sha256Verifier,
7278        )
7279        .expect("RSA chain with RSA-SHA256 in allowlist should pass");
7280    }
7281
7282    /// EKU tests for RSA chain are structurally identical to P-256; spot-check one.
7283    ///
7284    /// Oracle: leaf-rsa2048-365d-san-eku.der has EKU=serverAuth.
7285    #[test]
7286    fn required_eku_passes_for_rsa_chain() {
7287        let root = load(include_bytes!(
7288            "../tests/fixtures/policy-checks/root-rsa2048.der"
7289        ));
7290        let int_cert = load(include_bytes!(
7291            "../tests/fixtures/policy-checks/int-rsa2048.der"
7292        ));
7293        let leaf = load(include_bytes!(
7294            "../tests/fixtures/policy-checks/leaf-rsa2048-365d-san-eku.der"
7295        ));
7296        let mut policy = ValidationPolicy::new(PC_NOW);
7297        policy.required_leaf_eku = Some(vec![ID_KP_SERVER_AUTH]);
7298        let anchors = [TrustAnchor::from_cert(root)];
7299        validate_path(
7300            &[leaf, int_cert],
7301            &anchors,
7302            &policy,
7303            &RsaPkcs1v15Sha256Verifier,
7304        )
7305        .expect("RSA leaf with serverAuth EKU must pass required_leaf_eku=[serverAuth]");
7306    }
7307}
7308
7309/// `NcTypeMask`, the bitmask that records which name forms a path has
7310/// constrained.
7311///
7312/// RFC 5280 §4.2.1.10 requires a certificate carrying a name form this
7313/// implementation cannot match -- `otherName`, `ediPartyName`,
7314/// `registeredID` -- to be rejected when a constraint on that form is in
7315/// effect. The mask is how "in effect" is tracked, so a bit that does not
7316/// work is a certificate that slips through.
7317///
7318/// Nothing exercised the type directly: it is reached only through
7319/// `check_name_constraints`, and the PKITS corpus has no vector for the
7320/// unsupported forms, so the bits for them could all have been zero.
7321#[cfg(test)]
7322mod nc_type_mask_tests {
7323    use super::NcTypeMask;
7324
7325    /// Every name form, in bit order. Written out rather than derived, so
7326    /// the test is a statement about which forms have a bit at all.
7327    const ALL: [(&str, NcTypeMask); 8] = [
7328        ("rfc822Name", NcTypeMask::RFC822),
7329        ("dNSName", NcTypeMask::DNS),
7330        ("directoryName", NcTypeMask::DIRECTORY_NAME),
7331        ("uniformResourceIdentifier", NcTypeMask::URI),
7332        ("iPAddress", NcTypeMask::IP_ADDRESS),
7333        ("otherName", NcTypeMask::OTHER_NAME),
7334        ("ediPartyName", NcTypeMask::EDI_PARTY_NAME),
7335        ("registeredID", NcTypeMask::REGISTERED_ID),
7336    ];
7337
7338    /// Each form has a bit of its own, and that bit is set.
7339    ///
7340    /// A shifted-away constant is the failure that matters: `1 << 6`
7341    /// becoming zero makes `intersects` answer false for every mask, so an
7342    /// `ediPartyName` constraint stops counting as in effect and a
7343    /// certificate carrying that form is no longer refused.
7344    ///
7345    /// `RFC822`'s own shift is the exception, and not for want of a test:
7346    /// `1 << 0` and `1 >> 0` are the same number, so no test distinguishes
7347    /// them. Every other bit is covered here.
7348    #[test]
7349    fn each_name_form_has_its_own_bit() {
7350        for (name, mask) in ALL {
7351            assert!(
7352                mask.intersects(mask),
7353                "{name}'s bit is empty, so no constraint on it can register"
7354            );
7355            assert_ne!(
7356                mask,
7357                NcTypeMask::EMPTY,
7358                "{name} is indistinguishable from EMPTY"
7359            );
7360        }
7361
7362        for (i, (a_name, a)) in ALL.iter().enumerate() {
7363            for (b_name, b) in ALL.iter().skip(i + 1) {
7364                assert!(
7365                    !a.intersects(*b),
7366                    "{a_name} and {b_name} share a bit, so a constraint on one \
7367                     would register as a constraint on the other"
7368                );
7369            }
7370        }
7371    }
7372
7373    /// The empty mask intersects nothing, including itself.
7374    #[test]
7375    fn the_empty_mask_intersects_nothing() {
7376        assert!(!NcTypeMask::EMPTY.intersects(NcTypeMask::EMPTY));
7377        for (name, mask) in ALL {
7378            assert!(!NcTypeMask::EMPTY.intersects(mask), "EMPTY against {name}");
7379            assert!(!mask.intersects(NcTypeMask::EMPTY), "{name} against EMPTY");
7380        }
7381    }
7382
7383    /// Accumulating a form twice leaves it set.
7384    ///
7385    /// This is the one place the distinction between union and symmetric
7386    /// difference shows: on disjoint masks they agree, so a `^` in either
7387    /// operator passes every test built from distinct forms. Two CA
7388    /// certificates in one path constraining `dNSName` is an ordinary
7389    /// chain, and under symmetric difference the second would clear what
7390    /// the first recorded -- the constraint would stop being in effect
7391    /// because it was imposed twice.
7392    #[test]
7393    fn accumulating_one_form_twice_leaves_it_set() {
7394        assert_eq!(NcTypeMask::DNS | NcTypeMask::DNS, NcTypeMask::DNS);
7395
7396        let mut acc = NcTypeMask::EMPTY;
7397        acc |= NcTypeMask::DNS;
7398        acc |= NcTypeMask::RFC822;
7399        acc |= NcTypeMask::DNS;
7400        assert!(
7401            acc.intersects(NcTypeMask::DNS),
7402            "dNSName was constrained twice and must still be in effect"
7403        );
7404        assert!(
7405            acc.intersects(NcTypeMask::RFC822),
7406            "rfc822Name was constrained once and must still be in effect"
7407        );
7408        assert!(
7409            !acc.intersects(NcTypeMask::URI),
7410            "no constraint named uniformResourceIdentifier"
7411        );
7412    }
7413
7414    /// `BitOr` and `BitOrAssign` agree.
7415    ///
7416    /// They are written separately, so one could accumulate while the other
7417    /// replaced.
7418    #[test]
7419    fn the_two_union_operators_agree() {
7420        let by_value = NcTypeMask::DNS | NcTypeMask::OTHER_NAME;
7421        let mut by_assign = NcTypeMask::DNS;
7422        by_assign |= NcTypeMask::OTHER_NAME;
7423        assert_eq!(by_value, by_assign);
7424    }
7425}
7426
7427/// Rendering, equality, hashing and source chains of [`Error`] and
7428/// [`DerError`].
7429///
7430/// These impls have no caller inside the crate: a path validation returns
7431/// an `Error`, and whether it renders, compares or hashes is the consumer's
7432/// business. So nothing here was exercised, and the failure mode is quiet
7433/// in the way that matters for a diagnostic — a `Display` that writes
7434/// nothing still returns `Ok`, a `source` that returns `None` still
7435/// satisfies the trait, and an `eq` that answers `true` makes two different
7436/// DER failures the same value.
7437#[cfg(test)]
7438mod error_rendering_tests {
7439    use super::{DerError, Error, VerificationErrorKind};
7440    use core::hash::{Hash, Hasher};
7441
7442    /// FNV-1a, so the hash assertions do not need `std`'s `DefaultHasher`.
7443    ///
7444    /// Any deterministic hasher does: the question is whether `Hash` reads
7445    /// the field `PartialEq` compares, not what the digest is.
7446    struct Fnv(u64);
7447
7448    impl Fnv {
7449        fn of<T: Hash>(value: &T) -> u64 {
7450            let mut h = Self(0xcbf2_9ce4_8422_2325);
7451            value.hash(&mut h);
7452            h.finish()
7453        }
7454    }
7455
7456    impl Hasher for Fnv {
7457        fn write(&mut self, bytes: &[u8]) {
7458            for b in bytes {
7459                self.0 ^= u64::from(*b);
7460                self.0 = self.0.wrapping_mul(0x0100_0000_01b3);
7461            }
7462        }
7463        fn finish(&self) -> u64 {
7464            self.0
7465        }
7466    }
7467
7468    /// A `DerError` wrapping the failure `bytes` produces as an OID.
7469    fn der_error(bytes: &[u8]) -> DerError {
7470        use der::Decode as _;
7471        let failed: der::Result<der::asn1::ObjectIdentifier> =
7472            der::asn1::ObjectIdentifier::from_der(bytes);
7473        DerError::new(failed.expect_err("not a well-formed OID"))
7474    }
7475
7476    /// One of every [`Error`] variant.
7477    ///
7478    /// The index is the same throughout on purpose: the variants that carry
7479    /// only an index are otherwise indistinguishable, so holding it fixed
7480    /// makes the distinctness assertion below a statement about the
7481    /// messages rather than about the numbers in them.
7482    fn every_variant() -> [Error; 23] {
7483        const IDX: usize = 2;
7484        [
7485            Error::SignatureInvalid { index: IDX },
7486            Error::SignatureNotVerified {
7487                index: IDX,
7488                reason: VerificationErrorKind::UnsupportedAlgorithm,
7489            },
7490            Error::MalformedCertificate { index: IDX },
7491            Error::ValidityPeriod { index: IDX },
7492            Error::ChainBroken { index: IDX },
7493            Error::NoTrustedPath,
7494            Error::PathTooLong,
7495            Error::NotCA { index: IDX },
7496            Error::KeyUsageMissing { index: IDX },
7497            Error::CrlSignMissing { index: IDX },
7498            Error::UnhandledCriticalExtension { index: IDX },
7499            Error::NameConstraintViolation { index: IDX },
7500            Error::PolicyViolation { index: IDX },
7501            Error::Der(der_error(&[0x06, 0x01, 0x80])),
7502            Error::ValidityPeriodExceedsMax { index: IDX },
7503            Error::AlgorithmNotAllowed { index: IDX },
7504            Error::KeyTooSmall { index: IDX },
7505            Error::MissingSan,
7506            Error::MissingRfc822San,
7507            Error::MissingEku,
7508            Error::MissingLeafPolicyOid {
7509                required: der::asn1::ObjectIdentifier::new_unwrap("1.2.3.4"),
7510            },
7511            Error::SubjectDnAttrRuleUnmet,
7512            Error::DuplicateCertificate {
7513                first: IDX,
7514                second: IDX + 1,
7515            },
7516        ]
7517    }
7518
7519    /// Every variant renders something, and no two render the same thing.
7520    ///
7521    /// An `Error` whose message is empty, or shared with another variant,
7522    /// tells a caller nothing about what went wrong. The array is a fixed
7523    /// length so adding a variant without a message is a compile error
7524    /// here rather than a silent gap.
7525    #[test]
7526    fn every_error_variant_renders_a_distinct_message() {
7527        let variants = every_variant();
7528        let rendered: Vec<_> = variants.iter().map(|e| format!("{e}")).collect();
7529        for (variant, text) in variants.iter().zip(&rendered) {
7530            assert!(!text.is_empty(), "{variant:?} renders nothing");
7531        }
7532        for (i, a) in rendered.iter().enumerate() {
7533            for (j, b) in rendered.iter().enumerate().skip(i + 1) {
7534                assert_ne!(
7535                    a, b,
7536                    "{:?} and {:?} render the same message",
7537                    variants[i], variants[j]
7538                );
7539            }
7540        }
7541    }
7542
7543    /// Only `Error::Der` has an underlying cause, and it exposes it.
7544    ///
7545    /// A `source` that always answers `None` breaks `{:#}`-style chained
7546    /// reporting: the DER failure that explains the whole error is in the
7547    /// wrapped value and nowhere else.
7548    #[test]
7549    fn only_the_der_variant_has_a_source() {
7550        use core::error::Error as _;
7551        for variant in &every_variant() {
7552            let expected = matches!(variant, Error::Der(_));
7553            assert_eq!(
7554                variant.source().is_some(),
7555                expected,
7556                "{variant:?} source presence"
7557            );
7558        }
7559    }
7560
7561    /// `DerError` renders the message it cached, and exposes the
7562    /// `der::Error` it was built from.
7563    #[test]
7564    fn a_der_error_renders_and_exposes_its_cause() {
7565        use core::error::Error as _;
7566        let e = der_error(&[0x06, 0x01, 0x80]);
7567        let rendered = format!("{e}");
7568        assert!(!rendered.is_empty(), "DerError renders nothing");
7569        let source = e.source().expect("a DerError built from a der::Error");
7570        assert_eq!(
7571            format!("{source}"),
7572            rendered,
7573            "the cached message is the der::Error's own rendering"
7574        );
7575    }
7576
7577    /// Equality compares the cached message, so distinct DER failures are
7578    /// distinct values.
7579    ///
7580    /// `Error` derives `PartialEq`, so an `eq` that always answered `true`
7581    /// would make `Err(Error::Der(a)) == Err(Error::Der(b))` for any two
7582    /// DER failures — and a test asserting a particular error would pass
7583    /// for the wrong one.
7584    #[test]
7585    fn der_errors_with_different_messages_differ() {
7586        let wrong_tag = der_error(&[0x02, 0x01, 0x00]);
7587        let truncated = der_error(&[0x06, 0x01, 0x80]);
7588        assert_ne!(
7589            format!("{wrong_tag}"),
7590            format!("{truncated}"),
7591            "the two fixtures must fail differently for this test to mean anything"
7592        );
7593        assert_ne!(wrong_tag, truncated);
7594        assert_eq!(
7595            Error::Der(wrong_tag.clone()),
7596            Error::Der(wrong_tag.clone()),
7597            "the same failure twice"
7598        );
7599        assert_ne!(Error::Der(wrong_tag), Error::Der(truncated));
7600    }
7601
7602    /// `Hash` reads the field `PartialEq` compares.
7603    ///
7604    /// Equal values must hash equally, which a `hash` that writes nothing
7605    /// satisfies trivially — and then every `DerError` lands in one bucket,
7606    /// including inside the `Error` and `ValidatedPath` hashes that exist
7607    /// only because `DerError` is `Hash`.
7608    #[test]
7609    fn der_error_hashing_follows_its_equality() {
7610        let wrong_tag = der_error(&[0x02, 0x01, 0x00]);
7611        let truncated = der_error(&[0x06, 0x01, 0x80]);
7612        assert_eq!(
7613            Fnv::of(&wrong_tag),
7614            Fnv::of(&der_error(&[0x02, 0x01, 0x00])),
7615            "equal values hash equally"
7616        );
7617        assert_ne!(
7618            Fnv::of(&wrong_tag),
7619            Fnv::of(&truncated),
7620            "unequal values are not all one hash"
7621        );
7622    }
7623}