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