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