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