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