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