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