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