Skip to main content

auth_framework/methods/client_cert/
mod.rs

1//! Client certificate authentication (application-layer mTLS identity extraction).
2//!
3//! # Where this fits in the stack
4//!
5//! ```text
6//! TLS layer   ─── mTLS handshake ──► proves client holds the private key
7//! This module ─── cert inspection ──► extracts identity, applies policy
8//! ```
9//!
10//! The TLS handshake cryptographically proves that the client possesses the
11//! private key corresponding to the certificate it presented.  Once TLS is
12//! established, the server-side application receives the **verified** certificate
13//! as DER bytes.  This module's job is the *second* part: inspecting the certificate
14//! to answer "who is this client?" and "are they permitted?".
15//!
16//! # What this module covers
17//!
18//! Any PKI-based client authentication that delivers an X.509 certificate to
19//! the application layer:
20//! - Software client certificates (p12/pfx, PEM bundles)
21//! - Smart card client certificates (SC/PKCS#11, hardware-bound private key)
22//! - US government PIV (NIST SP 800-73) certificates
23//! - CAC (Common Access Card) certificates
24//!
25//! From this module's perspective a smart card certificate is just an X.509 DER
26//! byte string.  The PC/SC protocol that extracts it from the physical card is
27//! handled at the transport layer (PKCS#11 middleware, OS TLS stack, etc.).
28//!
29//! # What this module does NOT do
30//!
31//! - **Cryptographic signature verification of the cert chain**: that belongs in the
32//!   TLS library (rustls, native-tls).  `ClientCertConfig::trusted_ca_ders` is a
33//!   *defence-in-depth* post-TLS policy check (issuer DN matching), not a replacement
34//!   for TLS-level chain verification.
35//! - **OCSP / CRL revocation checking**: a future extension.  Rely on the TLS layer's
36//!   revocation configuration for now.
37//! - **PC/SC card reader access**: use a PKCS#11 middleware library at the transport
38//!   layer (e.g. OpenSC).
39
40use std::collections::HashSet;
41use std::sync::Arc;
42use std::time::SystemTime;
43
44use crate::{
45    authentication::credentials::Credential,
46    errors::{AuthError, Result},
47};
48
49// ─── Configuration ────────────────────────────────────────────────────────────
50
51/// Configuration for [`ClientCertAuthMethod`].
52#[derive(Debug, Clone)]
53pub struct ClientCertConfig {
54    /// DER-encoded trusted CA certificates.
55    ///
56    /// When non-empty, the presented certificate's issuer DN is matched against
57    /// the subjects of these CAs.  This provides a meaningful policy guard when
58    /// the list is kept to a small, curated set of CAs you actually trust.
59    ///
60    /// **Security note**: this is an *issuer DN equality check*, not a full
61    /// cryptographic path validation.  For cryptographic assurance configure your
62    /// TLS library's trusted CA store, then use this list as a second policy filter.
63    pub trusted_ca_ders: Vec<Vec<u8>>,
64
65    /// Subject DN substrings that are allowed.  An empty list accepts any subject
66    /// (given other checks pass).  Matching is case-sensitive substring search on
67    /// the full Distinguished Name string (e.g. `"CN=alice"` or just `"alice"`).
68    pub subject_allowlist: Vec<String>,
69
70    /// Issuer DN substrings that are allowed.  An empty list accepts any issuer.
71    pub issuer_allowlist: Vec<String>,
72
73    /// When `true`, the certificate must contain a Subject Alternative Name (SAN)
74    /// extension.  PIV and modern TLS certificates always carry one; older
75    /// enterprise CAs sometimes do not.
76    pub require_san: bool,
77
78    /// Lifetime of the session issued after successful authentication (seconds).
79    pub token_lifetime_secs: u64,
80}
81
82impl Default for ClientCertConfig {
83    fn default() -> Self {
84        Self {
85            trusted_ca_ders: Vec::new(),
86            subject_allowlist: Vec::new(),
87            issuer_allowlist: Vec::new(),
88            require_san: false,
89            token_lifetime_secs: 3600,
90        }
91    }
92}
93
94impl ClientCertConfig {
95    /// Create a permissive configuration with a 1-hour session lifetime.
96    pub fn new() -> Self {
97        Self::default()
98    }
99
100    /// Builder: add a trusted CA (DER-encoded).
101    pub fn trust_ca(mut self, ca_der: Vec<u8>) -> Self {
102        self.trusted_ca_ders.push(ca_der);
103        self
104    }
105
106    /// Builder: allow only subjects whose DN contains `pattern`.
107    pub fn allow_subject(mut self, pattern: impl Into<String>) -> Self {
108        self.subject_allowlist.push(pattern.into());
109        self
110    }
111
112    /// Builder: allow only issuers whose DN contains `pattern`.
113    pub fn allow_issuer(mut self, pattern: impl Into<String>) -> Self {
114        self.issuer_allowlist.push(pattern.into());
115        self
116    }
117
118    /// Builder: require a SAN extension.
119    pub fn with_require_san(mut self) -> Self {
120        self.require_san = true;
121        self
122    }
123}
124
125// ─── Identity type ────────────────────────────────────────────────────────────
126
127/// Identity extracted from a successfully validated client certificate.
128#[derive(Debug, Clone)]
129pub struct CertIdentity {
130    /// Full Distinguished Name of the subject (e.g. `"CN=alice, O=Example Corp"`).
131    pub subject_dn: String,
132    /// Common Name (CN) extracted from the subject, if present.
133    pub common_name: Option<String>,
134    /// Subject Alternative Names collected from the SAN extension, if present.
135    /// Each entry is prefixed with its type: `"dns:host.example.com"`,
136    /// `"email:user@example.com"`, `"ip:192.0.2.1"`.
137    pub sans: Vec<String>,
138    /// Full Distinguished Name of the issuer.
139    pub issuer_dn: String,
140}
141
142// ─── Method ───────────────────────────────────────────────────────────────────
143
144/// Application-layer client certificate authenticator.
145///
146/// Validates an X.509 client certificate presented after an mTLS handshake and
147/// extracts a [`CertIdentity`] that higher-level code can use to create a session.
148///
149/// ## Minimal usage
150///
151/// ```rust,no_run
152/// use auth_framework::methods::client_cert::{ClientCertAuthMethod, ClientCertConfig};
153/// use auth_framework::authentication::credentials::Credential;
154///
155/// # let cert_der: Vec<u8> = unimplemented!();
156/// let method = ClientCertAuthMethod::new(ClientCertConfig::new());
157///
158/// // `cert_der` comes from your HTTP framework's peer certificate extraction.
159/// let identity = method.authenticate(&Credential::client_cert_from_tls(cert_der))?;
160/// # Ok::<_, auth_framework::errors::AuthError>(())
161/// ```
162pub struct ClientCertAuthMethod {
163    config: ClientCertConfig,
164}
165
166impl ClientCertAuthMethod {
167    /// Create a new authenticator with the given configuration.
168    pub fn new(config: ClientCertConfig) -> Self {
169        Self { config }
170    }
171
172    /// Validate `credential` and return the caller's certificate identity.
173    ///
174    /// Accepts `Credential::Certificate { certificate, .. }`.  The `private_key`
175    /// field is **ignored** — key possession was already proved by the TLS
176    /// handshake.  Use [`Credential::client_cert_from_tls`] to construct the
177    /// credential without supplying a private key.
178    pub fn authenticate(&self, credential: &Credential) -> Result<CertIdentity> {
179        let cert_der = match credential {
180            Credential::Certificate {
181                certificate,
182                private_key,
183                ..
184            } => {
185                if !private_key.is_empty() {
186                    tracing::warn!(
187                        "ClientCertAuthMethod received a non-empty private_key — \
188                         it will be ignored.  For mTLS flows use \
189                         `Credential::client_cert_from_tls(der_bytes)`."
190                    );
191                }
192                certificate.as_slice()
193            }
194            other => {
195                return Err(AuthError::InvalidCredential {
196                    credential_type: other.credential_type().to_string(),
197                    message: "ClientCertAuthMethod requires a Credential::Certificate. \
198                              Use Credential::client_cert_from_tls(der_bytes) for mTLS flows."
199                        .to_string(),
200                });
201            }
202        };
203
204        self.validate_der(cert_der)
205    }
206
207    // ── Validation pipeline ───────────────────────────────────────────────────
208
209    fn validate_der(&self, cert_der: &[u8]) -> Result<CertIdentity> {
210        use x509_parser::prelude::*;
211
212        if cert_der.is_empty() {
213            return Err(AuthError::InvalidCredential {
214                credential_type: "certificate".to_string(),
215                message: "Certificate DER bytes are empty".to_string(),
216            });
217        }
218
219        let (_, cert) =
220            X509Certificate::from_der(cert_der).map_err(|_| AuthError::InvalidCredential {
221                credential_type: "certificate".to_string(),
222                message: "Failed to parse X.509 DER certificate — verify that the bytes \
223                          are DER-encoded (not PEM) and are not truncated."
224                    .to_string(),
225            })?;
226
227        self.check_validity(&cert)?;
228        self.check_subject_allowlist(&cert)?;
229        self.check_issuer_allowlist(&cert)?;
230        self.check_san_required(&cert)?;
231        self.check_trust_chain(cert_der)?;
232        self.extract_identity(&cert)
233    }
234
235    fn check_validity(&self, cert: &x509_parser::certificate::X509Certificate<'_>) -> Result<()> {
236        let now = SystemTime::now()
237            .duration_since(SystemTime::UNIX_EPOCH)
238            .unwrap_or_default()
239            .as_secs() as i64;
240
241        let not_before = cert.validity().not_before.timestamp();
242        let not_after = cert.validity().not_after.timestamp();
243
244        if now < not_before {
245            return Err(AuthError::InvalidCredential {
246                credential_type: "certificate".to_string(),
247                message: format!(
248                    "Certificate is not yet valid (valid from Unix timestamp {})",
249                    not_before
250                ),
251            });
252        }
253        if now > not_after {
254            return Err(AuthError::InvalidCredential {
255                credential_type: "certificate".to_string(),
256                message: "Certificate has expired".to_string(),
257            });
258        }
259        Ok(())
260    }
261
262    fn check_subject_allowlist(
263        &self,
264        cert: &x509_parser::certificate::X509Certificate<'_>,
265    ) -> Result<()> {
266        if self.config.subject_allowlist.is_empty() {
267            return Ok(());
268        }
269        let subject = cert.subject().to_string();
270        if !self
271            .config
272            .subject_allowlist
273            .iter()
274            .any(|p| subject.contains(p.as_str()))
275        {
276            return Err(AuthError::InvalidCredential {
277                credential_type: "certificate".to_string(),
278                message: format!("Subject DN '{}' is not in the subject allowlist", subject),
279            });
280        }
281        Ok(())
282    }
283
284    fn check_issuer_allowlist(
285        &self,
286        cert: &x509_parser::certificate::X509Certificate<'_>,
287    ) -> Result<()> {
288        if self.config.issuer_allowlist.is_empty() {
289            return Ok(());
290        }
291        let issuer = cert.issuer().to_string();
292        if !self
293            .config
294            .issuer_allowlist
295            .iter()
296            .any(|p| issuer.contains(p.as_str()))
297        {
298            return Err(AuthError::InvalidCredential {
299                credential_type: "certificate".to_string(),
300                message: format!("Issuer DN '{}' is not in the issuer allowlist", issuer),
301            });
302        }
303        Ok(())
304    }
305
306    fn check_san_required(
307        &self,
308        cert: &x509_parser::certificate::X509Certificate<'_>,
309    ) -> Result<()> {
310        if !self.config.require_san {
311            return Ok(());
312        }
313        // SAN extension OID: 2.5.29.17
314        let has_san = cert
315            .extensions()
316            .iter()
317            .any(|ext| ext.oid.to_id_string() == "2.5.29.17");
318        if !has_san {
319            return Err(AuthError::InvalidCredential {
320                credential_type: "certificate".to_string(),
321                message: "Certificate does not contain a Subject Alternative Name (SAN) \
322                          extension, but require_san is enabled in the configuration."
323                    .to_string(),
324            });
325        }
326        Ok(())
327    }
328
329    /// Issuer DN matching against trusted CAs.
330    ///
331    /// Finds a CA in `trusted_ca_ders` whose subject DN equals the end-entity
332    /// certificate's issuer DN.  This is effective as a policy filter when the CA
333    /// list is carefully maintained; it is NOT a cryptographic signature check.
334    fn check_trust_chain(&self, cert_der: &[u8]) -> Result<()> {
335        if self.config.trusted_ca_ders.is_empty() {
336            return Ok(());
337        }
338
339        use x509_parser::prelude::*;
340
341        let (_, cert) =
342            X509Certificate::from_der(cert_der).map_err(|_| AuthError::InvalidCredential {
343                credential_type: "certificate".to_string(),
344                message: "Failed to re-parse certificate for chain check".to_string(),
345            })?;
346        let issuer_dn = cert.issuer().to_string();
347
348        let found = self.config.trusted_ca_ders.iter().any(|ca_der| {
349            if let Ok((_, ca_cert)) = X509Certificate::from_der(ca_der) {
350                ca_cert.subject().to_string() == issuer_dn
351            } else {
352                false
353            }
354        });
355
356        if !found {
357            return Err(AuthError::InvalidCredential {
358                credential_type: "certificate".to_string(),
359                message: format!(
360                    "No trusted CA found for issuer '{}'. \
361                     Add the issuing CA's DER bytes to ClientCertConfig::trusted_ca_ders.",
362                    issuer_dn
363                ),
364            });
365        }
366        Ok(())
367    }
368
369    fn extract_identity(
370        &self,
371        cert: &x509_parser::certificate::X509Certificate<'_>,
372    ) -> Result<CertIdentity> {
373        let subject_dn = cert.subject().to_string();
374        let issuer_dn = cert.issuer().to_string();
375
376        // First CN attribute in the subject RDN sequence.
377        let common_name = cert
378            .subject()
379            .iter_common_name()
380            .next()
381            .and_then(|attr| attr.as_str().ok())
382            .map(str::to_string);
383
384        // Collect DNS, email, and IP SANs from the SAN extension (OID 2.5.29.17).
385        let mut sans: Vec<String> = Vec::new();
386        for ext in cert.extensions() {
387            if ext.oid.to_id_string() == "2.5.29.17"
388                && let x509_parser::extensions::ParsedExtension::SubjectAlternativeName(san) =
389                    ext.parsed_extension()
390            {
391                for gn in &san.general_names {
392                    let entry = match gn {
393                        x509_parser::extensions::GeneralName::DNSName(s) => {
394                            format!("dns:{s}")
395                        }
396                        x509_parser::extensions::GeneralName::RFC822Name(s) => {
397                            format!("email:{s}")
398                        }
399                        x509_parser::extensions::GeneralName::IPAddress(ip) => {
400                            format!("ip:{}", fmt_ip(ip))
401                        }
402                        _ => continue,
403                    };
404                    sans.push(entry);
405                }
406            }
407        }
408
409        Ok(CertIdentity {
410            subject_dn,
411            common_name,
412            sans,
413            issuer_dn,
414        })
415    }
416}
417
418/// Format raw IP bytes as dotted-decimal (IPv4) or colon-hex (IPv6).
419fn fmt_ip(bytes: &[u8]) -> String {
420    match bytes.len() {
421        4 => format!("{}.{}.{}.{}", bytes[0], bytes[1], bytes[2], bytes[3]),
422        16 => {
423            let parts: Vec<String> = bytes
424                .chunks(2)
425                .map(|c| format!("{:02x}{:02x}", c[0], c[1]))
426                .collect();
427            parts.join(":")
428        }
429        _ => format!("{:?}", bytes),
430    }
431}
432
433// ── Certificate Pinning ───────────────────────────────────────────────────────
434
435/// Certificate fingerprint for pinning.
436///
437/// Stores the SHA-256 hash of a DER-encoded certificate for pin comparison.
438#[derive(Debug, Clone, PartialEq, Eq, Hash)]
439pub struct CertPin {
440    /// SHA-256 fingerprint as a lowercase hex string.
441    pub sha256_hex: String,
442}
443
444impl CertPin {
445    /// Compute a pin from DER-encoded certificate bytes.
446    pub fn from_der(cert_der: &[u8]) -> Self {
447        use sha2::{Digest, Sha256};
448        let digest = Sha256::digest(cert_der);
449        Self {
450            sha256_hex: hex::encode(digest),
451        }
452    }
453
454    /// Create a pin from a known hex fingerprint.
455    pub fn from_hex(hex_fingerprint: impl Into<String>) -> Self {
456        Self {
457            sha256_hex: hex_fingerprint.into().to_lowercase(),
458        }
459    }
460}
461
462/// A certificate pin store for enforcing certificate pinning.
463///
464/// When pinning is enabled, only certificates whose SHA-256 fingerprint
465/// appears in this store are accepted.
466#[derive(Debug, Clone, Default)]
467pub struct CertPinStore {
468    pins: Arc<std::sync::RwLock<HashSet<String>>>,
469}
470
471impl CertPinStore {
472    /// Create a new empty pin store.
473    pub fn new() -> Self {
474        Self::default()
475    }
476
477    /// Add a pin by SHA-256 hex fingerprint.
478    pub fn add(&self, pin: &CertPin) {
479        self.pins
480            .write()
481            .expect("certificate pin store lock poisoned")
482            .insert(pin.sha256_hex.clone());
483    }
484
485    /// Remove a pin.
486    pub fn remove(&self, pin: &CertPin) -> bool {
487        self.pins
488            .write()
489            .expect("certificate pin store lock poisoned")
490            .remove(&pin.sha256_hex)
491    }
492
493    /// Check if a certificate (DER) matches any pinned fingerprint.
494    pub fn is_pinned(&self, cert_der: &[u8]) -> bool {
495        let pin = CertPin::from_der(cert_der);
496        self.pins
497            .read()
498            .expect("certificate pin store lock poisoned")
499            .contains(&pin.sha256_hex)
500    }
501
502    /// Number of stored pins.
503    pub fn count(&self) -> usize {
504        self.pins
505            .read()
506            .expect("certificate pin store lock poisoned")
507            .len()
508    }
509}
510
511// ── Revocation Checking ───────────────────────────────────────────────────────
512
513/// Revocation check result.
514#[derive(Debug, Clone, PartialEq, Eq)]
515pub enum RevocationStatus {
516    /// Certificate is known to be good (not revoked).
517    Good,
518    /// Certificate has been revoked.
519    Revoked {
520        /// RFC 5280 CRLReason (optional).
521        reason: Option<String>,
522    },
523    /// Revocation status is unknown (e.g., responder unavailable).
524    Unknown,
525}
526
527/// An in-memory CRL (Certificate Revocation List) store.
528///
529/// For production deployments, the TLS layer should handle CRL/OCSP. This
530/// provides an application-layer defence-in-depth check against known-revoked
531/// serial numbers.
532#[derive(Debug, Clone, Default)]
533pub struct CrlStore {
534    /// Revoked certificate serial numbers (hex-encoded), keyed by issuer DN.
535    revoked: Arc<std::sync::RwLock<std::collections::HashMap<String, HashSet<String>>>>,
536}
537
538impl CrlStore {
539    /// Create a new empty CRL store.
540    pub fn new() -> Self {
541        Self::default()
542    }
543
544    /// Mark a certificate serial number as revoked for a given issuer DN.
545    pub fn add_revoked(&self, issuer_dn: &str, serial_hex: &str) {
546        self.revoked
547            .write()
548            .expect("CRL store lock poisoned")
549            .entry(issuer_dn.to_string())
550            .or_default()
551            .insert(serial_hex.to_lowercase());
552    }
553
554    /// Check if a certificate (by issuer DN and serial hex) is revoked.
555    pub fn check(&self, issuer_dn: &str, serial_hex: &str) -> RevocationStatus {
556        let store = self.revoked.read().expect("CRL store lock poisoned");
557        if let Some(serials) = store.get(issuer_dn)
558            && serials.contains(&serial_hex.to_lowercase())
559        {
560            return RevocationStatus::Revoked { reason: None };
561        }
562        RevocationStatus::Good
563    }
564
565    /// Check a DER-encoded certificate against the CRL store.
566    pub fn check_der(&self, cert_der: &[u8]) -> RevocationStatus {
567        use x509_parser::prelude::*;
568        let Ok((_, cert)) = X509Certificate::from_der(cert_der) else {
569            return RevocationStatus::Unknown;
570        };
571        let issuer = cert.issuer().to_string();
572        let serial = cert.raw_serial_as_string().to_lowercase();
573        self.check(&issuer, &serial)
574    }
575
576    /// Total count of revoked serial numbers across all issuers.
577    pub fn revoked_count(&self) -> usize {
578        self.revoked
579            .read()
580            .expect("CRL store lock poisoned")
581            .values()
582            .map(|s| s.len())
583            .sum()
584    }
585
586    /// Remove all entries for an issuer.
587    pub fn clear_issuer(&self, issuer_dn: &str) {
588        self.revoked
589            .write()
590            .expect("CRL store lock poisoned")
591            .remove(issuer_dn);
592    }
593}
594
595// ── Certificate-Bound Access Tokens (RFC 8705) ───────────────────────────────
596
597/// Computes a certificate thumbprint for use in RFC 8705 certificate-bound
598/// access tokens (mTLS client certificate binding).
599///
600/// Returns the base64url-encoded SHA-256 hash of the DER-encoded certificate,
601/// suitable for the `x5t#S256` confirmation claim in JWT access tokens.
602pub fn cert_thumbprint_s256(cert_der: &[u8]) -> String {
603    use base64::Engine;
604    use sha2::{Digest, Sha256};
605    let digest = Sha256::digest(cert_der);
606    base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(digest)
607}
608
609/// Verify that a presented certificate matches the `x5t#S256` thumbprint
610/// bound to an access token (RFC 8705 §3).
611pub fn verify_cert_binding(cert_der: &[u8], expected_thumbprint: &str) -> Result<()> {
612    let actual = cert_thumbprint_s256(cert_der);
613    if actual == expected_thumbprint {
614        Ok(())
615    } else {
616        Err(AuthError::InvalidCredential {
617            credential_type: "certificate".to_string(),
618            message: format!(
619                "Certificate thumbprint mismatch: token bound to '{}', presented cert has '{}'",
620                expected_thumbprint, actual
621            ),
622        })
623    }
624}
625
626// ─── Tests ────────────────────────────────────────────────────────────────────
627
628#[cfg(test)]
629mod tests {
630    use super::*;
631
632    // ── Configuration ─────────────────────────────────────────────────────────
633
634    #[test]
635    fn test_config_default() {
636        let cfg = ClientCertConfig::default();
637        assert!(cfg.trusted_ca_ders.is_empty());
638        assert!(cfg.subject_allowlist.is_empty());
639        assert!(cfg.issuer_allowlist.is_empty());
640        assert!(!cfg.require_san);
641        assert_eq!(cfg.token_lifetime_secs, 3600);
642    }
643
644    #[test]
645    fn test_config_builder_chain() {
646        let cfg = ClientCertConfig::new()
647            .allow_subject("alice")
648            .allow_issuer("MyCA")
649            .with_require_san();
650        assert_eq!(cfg.subject_allowlist, ["alice"]);
651        assert_eq!(cfg.issuer_allowlist, ["MyCA"]);
652        assert!(cfg.require_san);
653    }
654
655    // ── Error paths (no real cert required) ───────────────────────────────────
656
657    #[test]
658    fn test_wrong_credential_type_rejected() {
659        let method = ClientCertAuthMethod::new(ClientCertConfig::new());
660        let cred = Credential::Password {
661            username: "u".into(),
662            password: "p".into(),
663        };
664        let err = method.authenticate(&cred).unwrap_err();
665        assert!(
666            format!("{err}").contains("Certificate"),
667            "unexpected: {err}"
668        );
669    }
670
671    #[test]
672    fn test_empty_der_rejected() {
673        let method = ClientCertAuthMethod::new(ClientCertConfig::new());
674        let cred = Credential::Certificate {
675            certificate: vec![],
676            private_key: vec![],
677            passphrase: None,
678        };
679        let err = method.authenticate(&cred).unwrap_err();
680        assert!(format!("{err}").contains("empty"), "unexpected: {err}");
681    }
682
683    #[test]
684    fn test_garbage_der_rejected() {
685        let method = ClientCertAuthMethod::new(ClientCertConfig::new());
686        let cred = Credential::Certificate {
687            certificate: vec![0xDE, 0xAD, 0xBE, 0xEF, 0x01, 0x02, 0x03, 0x04],
688            private_key: vec![],
689            passphrase: None,
690        };
691        assert!(method.authenticate(&cred).is_err());
692    }
693
694    // ── Certificate DER builder for tests ─────────────────────────────────────
695    //
696    // Constructs a minimal self-signed Ed25519 X.509v3 certificate in DER.
697    // Validity dates are hardcoded as UTCTime raw bytes (ISO 8601 compact form).
698    //
699    // To regenerate equivalent certs with openssl:
700    //   openssl req -x509 -newkey ed25519 -keyout /tmp/k.pem -out /tmp/c.pem \
701    //     -days 730 -nodes -subj "/CN=<cn>"
702    //   openssl x509 -in /tmp/c.pem -outform DER | xxd -i
703    fn build_cert_der(
704        cn: &str,
705        not_before_utc: &[u8; 13], // raw UTCTime bytes e.g. b"250101000000Z"
706        not_after_utc: &[u8; 13],
707    ) -> Vec<u8> {
708        use ring::rand::SystemRandom;
709        use ring::signature::{Ed25519KeyPair, KeyPair};
710
711        let rng = SystemRandom::new();
712        let pkcs8 = Ed25519KeyPair::generate_pkcs8(&rng).unwrap();
713        let kp = Ed25519KeyPair::from_pkcs8(pkcs8.as_ref()).unwrap();
714        let pub_key = kp.public_key().as_ref(); // 32 bytes
715
716        // Short-form TLV (content < 128 bytes)
717        let tlv = |tag: u8, content: &[u8]| -> Vec<u8> {
718            assert!(
719                content.len() < 128,
720                "content too large for short-form TLV: {} bytes",
721                content.len()
722            );
723            let mut v = vec![tag, content.len() as u8];
724            v.extend_from_slice(content);
725            v
726        };
727
728        // TLV with definite long form when content >= 128 bytes
729        let long_tlv = |tag: u8, content: &[u8]| -> Vec<u8> {
730            let len = content.len();
731            let mut v = vec![tag];
732            if len < 128 {
733                v.push(len as u8);
734            } else {
735                // Two-byte length (content < 65536)
736                v.push(0x81);
737                v.push(len as u8);
738            }
739            v.extend_from_slice(content);
740            v
741        };
742
743        // OID 1.3.101.112 (id-EdDSA / Ed25519)
744        let alg_id = tlv(0x30, &[0x06, 0x03, 0x2B, 0x65, 0x70]);
745
746        // Name: SEQUENCE { SET { SEQUENCE { OID 2.5.4.3, UTF8String cn } } }
747        let cn_bytes = cn.as_bytes();
748        let utf8_cn = tlv(0x0C, cn_bytes);
749        let oid_cn = [0x06u8, 0x03, 0x55, 0x04, 0x03];
750        let seq_atv = [oid_cn.as_slice(), utf8_cn.as_slice()].concat();
751        let name = tlv(0x30, &tlv(0x31, &tlv(0x30, &seq_atv)));
752
753        // Validity: SEQUENCE { UTCTime nb, UTCTime na }
754        let nb_der = tlv(0x17, not_before_utc);
755        let na_der = tlv(0x17, not_after_utc);
756        let validity = tlv(0x30, &[nb_der.as_slice(), na_der.as_slice()].concat());
757
758        // SubjectPublicKeyInfo: SEQUENCE { alg_id, BIT STRING { 0x00 || pub_key } }
759        let mut bit_content = vec![0x00u8];
760        bit_content.extend_from_slice(pub_key);
761        let bit_str = tlv(0x03, &bit_content);
762        let spki = tlv(0x30, &[alg_id.as_slice(), bit_str.as_slice()].concat());
763
764        // TBSCertificate
765        let version = [0xA0u8, 0x03, 0x02, 0x01, 0x02]; // [0] EXPLICIT INTEGER 2 (v3)
766        let serial = tlv(0x02, &[0x01]);
767        let tbs_body: Vec<u8> = [
768            version.as_slice(),
769            serial.as_slice(),
770            alg_id.as_slice(), // signatureAlgorithm
771            name.as_slice(),   // issuer
772            validity.as_slice(),
773            name.as_slice(), // subject (same as issuer: self-signed)
774            spki.as_slice(),
775        ]
776        .concat();
777        let tbs = long_tlv(0x30, &tbs_body);
778
779        // Self-sign the TBSCertificate bytes
780        let sig = kp.sign(&tbs);
781        let mut sig_content = vec![0x00u8]; // BIT STRING: 0 unused bits
782        sig_content.extend_from_slice(sig.as_ref()); // 64 bytes
783        let sig_bit_str = tlv(0x03, &sig_content);
784
785        // Certificate: SEQUENCE { tbs, signatureAlgorithm, signatureValue }
786        let cert_body: Vec<u8> =
787            [tbs.as_slice(), alg_id.as_slice(), sig_bit_str.as_slice()].concat();
788        long_tlv(0x30, &cert_body)
789    }
790
791    // Validity windows (UTCTime raw bytes):
792    //   Valid now (2025-01-01 → 2027-01-01)
793    fn valid_cert(cn: &str) -> Vec<u8> {
794        build_cert_der(cn, b"250101000000Z", b"270101000000Z")
795    }
796    //   Expired (2020-01-01 → 2021-01-01)
797    fn expired_cert(cn: &str) -> Vec<u8> {
798        build_cert_der(cn, b"200101000000Z", b"210101000000Z")
799    }
800    //   Future (2028-01-01 → 2030-01-01)
801    fn future_cert(cn: &str) -> Vec<u8> {
802        build_cert_der(cn, b"280101000000Z", b"300101000000Z")
803    }
804
805    fn cert_cred(der: Vec<u8>) -> Credential {
806        Credential::Certificate {
807            certificate: der,
808            private_key: vec![],
809            passphrase: None,
810        }
811    }
812
813    // ── Certificate-based tests ────────────────────────────────────────────────
814
815    #[test]
816    fn test_valid_cert_accepted() {
817        let method = ClientCertAuthMethod::new(ClientCertConfig::new());
818        let id = method
819            .authenticate(&cert_cred(valid_cert("alice")))
820            .expect("valid cert should be accepted");
821        assert!(
822            id.subject_dn.contains("alice"),
823            "subject should contain CN: {}",
824            id.subject_dn
825        );
826        assert_eq!(id.common_name.as_deref(), Some("alice"));
827    }
828
829    #[test]
830    fn test_expired_cert_rejected() {
831        let method = ClientCertAuthMethod::new(ClientCertConfig::new());
832        let err = method
833            .authenticate(&cert_cred(expired_cert("bob")))
834            .unwrap_err();
835        let msg = format!("{err}");
836        assert!(msg.contains("expired"), "expected 'expired' in: {msg}");
837    }
838
839    #[test]
840    fn test_future_cert_rejected() {
841        let method = ClientCertAuthMethod::new(ClientCertConfig::new());
842        let err = method
843            .authenticate(&cert_cred(future_cert("carol")))
844            .unwrap_err();
845        let msg = format!("{err}");
846        assert!(msg.contains("valid"), "expected 'valid' in: {msg}");
847    }
848
849    #[test]
850    fn test_subject_allowlist_permits_matching_cn() {
851        let cfg = ClientCertConfig::new().allow_subject("alice");
852        assert!(
853            ClientCertAuthMethod::new(cfg)
854                .authenticate(&cert_cred(valid_cert("alice")))
855                .is_ok()
856        );
857    }
858
859    #[test]
860    fn test_subject_allowlist_blocks_non_matching_cn() {
861        let cfg = ClientCertConfig::new().allow_subject("alice");
862        let err = ClientCertAuthMethod::new(cfg)
863            .authenticate(&cert_cred(valid_cert("mallory")))
864            .unwrap_err();
865        let msg = format!("{err}");
866        assert!(msg.contains("allowlist"), "expected 'allowlist' in: {msg}");
867    }
868
869    #[test]
870    fn test_issuer_allowlist_permits_self_signed_when_matches() {
871        // Self-signed: issuer DN == subject DN == "CN=alice"
872        let cfg = ClientCertConfig::new().allow_issuer("alice");
873        assert!(
874            ClientCertAuthMethod::new(cfg)
875                .authenticate(&cert_cred(valid_cert("alice")))
876                .is_ok()
877        );
878    }
879
880    #[test]
881    fn test_issuer_allowlist_blocks_unmatched_issuer() {
882        let cfg = ClientCertConfig::new().allow_issuer("TrustedCorp");
883        let err = ClientCertAuthMethod::new(cfg)
884            .authenticate(&cert_cred(valid_cert("alice")))
885            .unwrap_err();
886        let msg = format!("{err}");
887        assert!(msg.contains("allowlist"), "expected 'allowlist' in: {msg}");
888    }
889
890    #[test]
891    fn test_require_san_rejects_cert_without_san() {
892        // Our test cert builder produces no SAN extension.
893        let cfg = ClientCertConfig::new().with_require_san();
894        let err = ClientCertAuthMethod::new(cfg)
895            .authenticate(&cert_cred(valid_cert("alice")))
896            .unwrap_err();
897        let msg = format!("{err}");
898        assert!(
899            msg.contains("Subject Alternative Name") || msg.contains("SAN"),
900            "expected SAN mention in: {msg}"
901        );
902    }
903
904    #[test]
905    fn test_trusted_ca_accepts_when_issuer_dn_matches() {
906        // A self-signed cert is its own issuer; adding it to trusted_ca_ders
907        // means its own subject DN matches the issuer DN look-up.
908        let der = valid_cert("alice");
909        let cfg = ClientCertConfig::new().trust_ca(der.clone());
910        assert!(
911            ClientCertAuthMethod::new(cfg)
912                .authenticate(&cert_cred(der))
913                .is_ok()
914        );
915    }
916
917    #[test]
918    fn test_trusted_ca_rejects_when_no_ca_matches() {
919        let untrusted_cert = valid_cert("alice");
920        // Different self-signed cert = different subject DN
921        let different_ca = valid_cert("OtherCA");
922        let cfg = ClientCertConfig::new().trust_ca(different_ca);
923        let err = ClientCertAuthMethod::new(cfg)
924            .authenticate(&cert_cred(untrusted_cert))
925            .unwrap_err();
926        let msg = format!("{err}");
927        assert!(
928            msg.contains("trusted CA") || msg.contains("issuer"),
929            "expected CA/issuer mention in: {msg}"
930        );
931    }
932
933    #[test]
934    fn test_client_cert_from_tls_constructor() {
935        let der = valid_cert("sys");
936        let cred = Credential::client_cert_from_tls(der.clone());
937        match &cred {
938            Credential::Certificate {
939                certificate,
940                private_key,
941                passphrase,
942            } => {
943                assert_eq!(certificate, &der);
944                assert!(private_key.is_empty(), "private_key should be empty");
945                assert!(passphrase.is_none());
946            }
947            _ => panic!("Expected Credential::Certificate"),
948        }
949
950        // Also verify it authenticates successfully
951        let method = ClientCertAuthMethod::new(ClientCertConfig::new());
952        assert!(method.authenticate(&cred).is_ok());
953    }
954
955    #[test]
956    fn test_issuer_dn_populated_in_identity() {
957        let method = ClientCertAuthMethod::new(ClientCertConfig::new());
958        let id = method
959            .authenticate(&cert_cred(valid_cert("charlie")))
960            .unwrap();
961        // Self-signed: issuer == subject
962        assert_eq!(id.issuer_dn, id.subject_dn);
963    }
964
965    // ── Certificate Pinning ─────────────────────────────────────
966
967    #[test]
968    fn test_cert_pin_from_der() {
969        let der = valid_cert("pin-test");
970        let pin = CertPin::from_der(&der);
971        assert_eq!(pin.sha256_hex.len(), 64); // SHA-256 hex = 64 chars
972    }
973
974    #[test]
975    fn test_cert_pin_deterministic() {
976        let der = vec![0x30, 0x82, 0x01, 0x00];
977        let p1 = CertPin::from_der(&der);
978        let p2 = CertPin::from_der(&der);
979        assert_eq!(p1, p2);
980    }
981
982    #[test]
983    fn test_cert_pin_from_hex() {
984        let pin = CertPin::from_hex("AABB");
985        assert_eq!(pin.sha256_hex, "aabb"); // lowercase
986    }
987
988    #[test]
989    fn test_cert_pin_store_add_and_check() {
990        let store = CertPinStore::new();
991        let der = valid_cert("pinned");
992        let pin = CertPin::from_der(&der);
993        store.add(&pin);
994        assert_eq!(store.count(), 1);
995        assert!(store.is_pinned(&der));
996        assert!(!store.is_pinned(&valid_cert("not-pinned")));
997    }
998
999    #[test]
1000    fn test_cert_pin_store_remove() {
1001        let store = CertPinStore::new();
1002        let der = valid_cert("removable");
1003        let pin = CertPin::from_der(&der);
1004        store.add(&pin);
1005        assert!(store.remove(&pin));
1006        assert!(!store.is_pinned(&der));
1007        assert_eq!(store.count(), 0);
1008    }
1009
1010    // ── CRL Store ───────────────────────────────────────────────
1011
1012    #[test]
1013    fn test_crl_store_add_and_check() {
1014        let store = CrlStore::new();
1015        store.add_revoked("CN=TestCA", "0a1b2c");
1016        assert_eq!(
1017            store.check("CN=TestCA", "0a1b2c"),
1018            RevocationStatus::Revoked { reason: None }
1019        );
1020        assert_eq!(store.check("CN=TestCA", "ffffff"), RevocationStatus::Good);
1021        assert_eq!(store.check("CN=OtherCA", "0a1b2c"), RevocationStatus::Good);
1022    }
1023
1024    #[test]
1025    fn test_crl_store_case_insensitive_serial() {
1026        let store = CrlStore::new();
1027        store.add_revoked("CN=CA", "aAbBcC");
1028        assert_eq!(
1029            store.check("CN=CA", "AABBCC"),
1030            RevocationStatus::Revoked { reason: None }
1031        );
1032    }
1033
1034    #[test]
1035    fn test_crl_store_check_der() {
1036        let store = CrlStore::new();
1037        let der = valid_cert("crl-test");
1038        // Without any revocations → Good
1039        assert_eq!(store.check_der(&der), RevocationStatus::Good);
1040    }
1041
1042    #[test]
1043    fn test_crl_store_revoked_count() {
1044        let store = CrlStore::new();
1045        store.add_revoked("CN=CA1", "01");
1046        store.add_revoked("CN=CA1", "02");
1047        store.add_revoked("CN=CA2", "01");
1048        assert_eq!(store.revoked_count(), 3);
1049    }
1050
1051    #[test]
1052    fn test_crl_store_clear_issuer() {
1053        let store = CrlStore::new();
1054        store.add_revoked("CN=CA", "01");
1055        store.add_revoked("CN=CA", "02");
1056        store.clear_issuer("CN=CA");
1057        assert_eq!(store.revoked_count(), 0);
1058    }
1059
1060    // ── RFC 8705 Certificate-Bound Tokens ───────────────────────
1061
1062    #[test]
1063    fn test_cert_thumbprint_s256() {
1064        let der = valid_cert("rfc8705");
1065        let thumbprint = cert_thumbprint_s256(&der);
1066        // base64url-encoded SHA-256 = 43 chars
1067        assert_eq!(thumbprint.len(), 43);
1068    }
1069
1070    #[test]
1071    fn test_cert_thumbprint_deterministic() {
1072        let der = vec![0x30, 0x82, 0x00, 0x01];
1073        let t1 = cert_thumbprint_s256(&der);
1074        let t2 = cert_thumbprint_s256(&der);
1075        assert_eq!(t1, t2);
1076    }
1077
1078    #[test]
1079    fn test_verify_cert_binding_success() {
1080        let der = valid_cert("bound");
1081        let thumbprint = cert_thumbprint_s256(&der);
1082        assert!(verify_cert_binding(&der, &thumbprint).is_ok());
1083    }
1084
1085    #[test]
1086    fn test_verify_cert_binding_mismatch() {
1087        let der = valid_cert("bound");
1088        let err = verify_cert_binding(&der, "wrong-thumbprint").unwrap_err();
1089        let msg = format!("{err}");
1090        assert!(msg.contains("mismatch"), "expected 'mismatch' in: {msg}");
1091    }
1092}