Skip to main content

auth_framework/server/security/
mtls.rs

1//! OAuth 2.0 Mutual-TLS Client Authentication and Certificate-Bound Access Tokens (RFC 8705)
2//!
3//! This module implements RFC 8705, which defines:
4//! 1. Mutual TLS client authentication methods
5//! 2. Certificate-bound access tokens for enhanced security
6//! 3. X.509 certificate validation and processing
7
8use crate::errors::{AuthError, Result};
9use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
10use rustls_pki_types::{CertificateDer, UnixTime};
11use serde::{Deserialize, Serialize};
12use std::collections::HashMap;
13use webpki::{ALL_VERIFICATION_ALGS, EndEntityCert, KeyUsage, anchor_from_trusted_cert};
14use x509_parser::{certificate::X509Certificate, parse_x509_certificate};
15
16/// Mutual TLS authentication methods
17#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18pub enum MutualTlsMethod {
19    /// PKI Mutual TLS - certificate validation against CA
20    PkiMutualTls,
21
22    /// Self-signed certificate authentication
23    SelfSignedTlsClientAuth,
24}
25
26/// X.509 Certificate information for OAuth 2.0
27#[derive(Debug, Clone, Serialize, Deserialize)]
28pub struct X509CertificateInfo {
29    /// Certificate fingerprint (SHA-256)
30    pub thumbprint: String,
31
32    /// Certificate subject Distinguished Name
33    pub subject_dn: String,
34
35    /// Certificate issuer Distinguished Name
36    pub issuer_dn: String,
37
38    /// Certificate serial number
39    pub serial_number: String,
40
41    /// Certificate validity period
42    pub not_before: chrono::DateTime<chrono::Utc>,
43    pub not_after: chrono::DateTime<chrono::Utc>,
44
45    /// Subject Alternative Names
46    pub san_dns: Vec<String>,
47    pub san_uri: Vec<String>,
48    pub san_email: Vec<String>,
49}
50
51/// Certificate-bound access token confirmation
52#[derive(Debug, Clone, Serialize, Deserialize)]
53pub struct CertificateConfirmation {
54    /// Certificate thumbprint (x5t#S256)
55    #[serde(rename = "x5t#S256")]
56    pub x5t_s256: String,
57}
58
59/// Mutual TLS client configuration
60#[derive(Debug, Clone)]
61pub struct MutualTlsClientConfig {
62    /// Client identifier
63    pub client_id: String,
64
65    /// Authentication method
66    pub auth_method: MutualTlsMethod,
67
68    /// For PKI method: DER trust anchors for this client. When empty, the manager's CA store
69    /// (see [`MutualTlsManager::add_ca_certificate`]) is used; at least one must exist.
70    pub ca_certificates: Vec<Vec<u8>>,
71
72    /// Registered certificate (DER). Self-signed method: its public key must match. PKI method:
73    /// an exact pin; the presented certificate must be byte-identical (takes precedence over
74    /// `expected_subject_dn`).
75    pub client_certificate: Option<Vec<u8>>,
76
77    /// Exact subject distinguished name the certificate must carry (compared case- and
78    /// whitespace-insensitively after rendering as `CN=a, O=b`, as in
79    /// [`X509CertificateInfo::subject_dn`]). A PKI client needs this or `client_certificate`.
80    pub expected_subject_dn: Option<String>,
81
82    /// Whether to bind access tokens to certificates
83    pub certificate_bound_access_tokens: bool,
84}
85
86/// Mutual TLS authentication result
87#[derive(Debug, Clone)]
88pub struct MutualTlsAuthResult {
89    /// Client identifier
90    pub client_id: String,
91
92    /// Certificate information
93    pub certificate_info: X509CertificateInfo,
94
95    /// Whether the certificate is valid
96    pub is_valid: bool,
97
98    /// Validation errors (if any)
99    pub validation_errors: Vec<String>,
100}
101
102/// Mutual TLS manager for OAuth 2.0
103#[derive(Debug)]
104pub struct MutualTlsManager {
105    /// Registered clients with mTLS configuration
106    clients: tokio::sync::RwLock<HashMap<String, MutualTlsClientConfig>>,
107
108    /// Trusted CA certificates for PKI validation
109    ca_store: Vec<Vec<u8>>,
110}
111
112impl MutualTlsManager {
113    /// Create a new Mutual TLS manager
114    pub fn new() -> Self {
115        Self {
116            clients: tokio::sync::RwLock::new(HashMap::new()),
117            ca_store: Vec::new(),
118        }
119    }
120
121    /// Add a trusted CA certificate (DER).
122    ///
123    /// Trust anchors are used as given: an anchor's own `pathLen` is not enforced by the
124    /// verifier, so constrain intermediates (not the anchor) with `pathLen`.
125    ///
126    /// The certificate must parse as a single X.509 certificate and assert
127    /// `basicConstraints: cA = TRUE`. It becomes a trust anchor for every PKI client
128    /// that does not carry its own `ca_certificates`.
129    pub fn add_ca_certificate(&mut self, ca_cert: Vec<u8>) -> Result<()> {
130        ensure_ca_certificate(&ca_cert)?;
131        self.ca_store.push(ca_cert);
132        Ok(())
133    }
134
135    /// Register a client for Mutual TLS authentication.
136    ///
137    /// A `PkiMutualTls` client must be bound to its certificate: set `client_certificate`
138    /// (exact certificate pin) or `expected_subject_dn` (exact subject DN), otherwise any
139    /// certificate issued by a trusted CA would authenticate as this client.
140    pub async fn register_client(&self, config: MutualTlsClientConfig) -> Result<()> {
141        self.validate_client_config(&config)?;
142
143        let mut clients = self.clients.write().await;
144        clients.insert(config.client_id.clone(), config);
145
146        Ok(())
147    }
148
149    /// Authenticate a client using Mutual TLS.
150    ///
151    /// # Security: where the certificate bytes come from
152    ///
153    /// This validates a certificate; it cannot tell whether the peer holds its private key.
154    /// Pass only the certificate that your TLS acceptor verified the client's possession of
155    /// (the handshake's peer certificate), or one forwarded by a terminating proxy that strips
156    /// any client-supplied copy of the header it uses. Never pass a certificate read from a
157    /// request header or body that the client controls: a public certificate is not a secret.
158    ///
159    /// Equivalent to [`authenticate_client_with_chain`](Self::authenticate_client_with_chain)
160    /// with no intermediate certificates.
161    pub async fn authenticate_client(
162        &self,
163        client_id: &str,
164        client_certificate: &[u8],
165    ) -> Result<MutualTlsAuthResult> {
166        self.authenticate_client_with_chain(client_id, client_certificate, &[])
167            .await
168    }
169
170    /// Authenticate a client using Mutual TLS, with the intermediate certificates the
171    /// client presented in the TLS handshake (DER, any order).
172    ///
173    /// For `PkiMutualTls` the chain is built and verified by `rustls-webpki` (signatures,
174    /// validity of every certificate, basicConstraints and pathLen, name constraints,
175    /// `clientAuth` extended key usage), the trust anchors are the client's own
176    /// `ca_certificates` when set and the manager's CA store otherwise (never empty), and the
177    /// certificate must be bound to the client (see [`register_client`](Self::register_client)).
178    pub async fn authenticate_client_with_chain(
179        &self,
180        client_id: &str,
181        client_certificate: &[u8],
182        intermediates: &[Vec<u8>],
183    ) -> Result<MutualTlsAuthResult> {
184        let clients = self.clients.read().await;
185        let client_config = clients
186            .get(client_id)
187            .ok_or_else(|| AuthError::auth_method("mtls", "Client not registered for mTLS"))?;
188
189        // Parse the client certificate (exactly one certificate, no trailing data)
190        let cert = parse_single_certificate(client_certificate)
191            .map_err(|_| AuthError::auth_method("mtls", "Invalid client certificate format"))?;
192
193        // Extract certificate information
194        let cert_info = self.extract_certificate_info(&cert, client_certificate)?;
195
196        // Validate based on authentication method
197        let (is_valid, validation_errors) = match client_config.auth_method {
198            MutualTlsMethod::PkiMutualTls => self.validate_pki_certificate(
199                &cert,
200                client_certificate,
201                intermediates,
202                client_config,
203            ),
204            MutualTlsMethod::SelfSignedTlsClientAuth => {
205                self.validate_self_signed_certificate(&cert, client_config)
206            }
207        };
208
209        Ok(MutualTlsAuthResult {
210            client_id: client_id.to_string(),
211            certificate_info: cert_info,
212            is_valid,
213            validation_errors,
214        })
215    }
216
217    /// Create certificate-bound access token confirmation
218    pub fn create_certificate_confirmation(
219        &self,
220        client_certificate: &[u8],
221    ) -> Result<CertificateConfirmation> {
222        let thumbprint = self.calculate_certificate_thumbprint(client_certificate)?;
223
224        Ok(CertificateConfirmation {
225            x5t_s256: thumbprint,
226        })
227    }
228
229    /// Validate certificate-bound access token
230    pub fn validate_certificate_bound_token(
231        &self,
232        token_confirmation: &CertificateConfirmation,
233        client_certificate: &[u8],
234    ) -> Result<bool> {
235        let current_thumbprint = self.calculate_certificate_thumbprint(client_certificate)?;
236
237        Ok(token_confirmation.x5t_s256 == current_thumbprint)
238    }
239
240    /// Validate a client certificate for mTLS authentication, returning an error unless
241    /// the certificate authenticates `client_id`.
242    ///
243    /// The same rule applies as for [`authenticate_client`](Self::authenticate_client): the
244    /// bytes must come from the TLS handshake (or a proxy that strips client-supplied copies),
245    /// never from data the client chose.
246    ///
247    /// Uses the same validation as [`authenticate_client`](Self::authenticate_client).
248    pub async fn validate_client_certificate(
249        &self,
250        client_certificate: &[u8],
251        client_id: &str,
252    ) -> Result<()> {
253        self.validate_client_certificate_with_chain(client_certificate, &[], client_id)
254            .await
255    }
256
257    /// Like [`validate_client_certificate`](Self::validate_client_certificate), with the
258    /// intermediate certificates presented by the client.
259    pub async fn validate_client_certificate_with_chain(
260        &self,
261        client_certificate: &[u8],
262        intermediates: &[Vec<u8>],
263        client_id: &str,
264    ) -> Result<()> {
265        let result = self
266            .authenticate_client_with_chain(client_id, client_certificate, intermediates)
267            .await?;
268        if result.is_valid {
269            Ok(())
270        } else {
271            Err(AuthError::auth_method(
272                "mtls",
273                format!(
274                    "Client certificate rejected: {}",
275                    result.validation_errors.join("; ")
276                ),
277            ))
278        }
279    }
280
281    /// Extract certificate information from X.509 certificate
282    fn extract_certificate_info(
283        &self,
284        cert: &X509Certificate,
285        cert_der: &[u8],
286    ) -> Result<X509CertificateInfo> {
287        // Calculate SHA-256 thumbprint
288        let thumbprint = self.calculate_certificate_thumbprint(cert_der)?;
289
290        // Extract subject and issuer DN
291        let subject_dn = cert.subject().to_string();
292        let issuer_dn = cert.issuer().to_string();
293
294        // Extract serial number
295        let serial_number = hex::encode(cert.serial.to_bytes_be());
296
297        // Extract validity period
298        let not_before =
299            chrono::DateTime::from_timestamp(cert.validity().not_before.timestamp(), 0)
300                .unwrap_or_default();
301        let not_after = chrono::DateTime::from_timestamp(cert.validity().not_after.timestamp(), 0)
302            .unwrap_or_default();
303
304        // Extract Subject Alternative Names
305        let mut san_dns = Vec::new();
306        let mut san_uri = Vec::new();
307        let mut san_email = Vec::new();
308
309        // Parse Subject Alternative Names using current x509-parser API
310        if let Ok(Some(san_ext)) = cert.subject_alternative_name() {
311            for name in &san_ext.value.general_names {
312                match name {
313                    x509_parser::extensions::GeneralName::DNSName(dns) => {
314                        san_dns.push(dns.to_string());
315                    }
316                    x509_parser::extensions::GeneralName::URI(uri) => {
317                        san_uri.push(uri.to_string());
318                    }
319                    x509_parser::extensions::GeneralName::RFC822Name(email) => {
320                        san_email.push(email.to_string());
321                    }
322                    x509_parser::extensions::GeneralName::IPAddress(ip) => {
323                        // Optionally handle IP addresses as well
324                        if ip.len() == 4 {
325                            // IPv4
326                            let ip_addr = format!("{}.{}.{}.{}", ip[0], ip[1], ip[2], ip[3]);
327                            san_dns.push(ip_addr); // Add to DNS list for simplicity
328                        } else if ip.len() == 16 {
329                            // IPv6 - basic formatting
330                            let ip_addr = format!(
331                                "{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}",
332                                ip[0],
333                                ip[1],
334                                ip[2],
335                                ip[3],
336                                ip[4],
337                                ip[5],
338                                ip[6],
339                                ip[7],
340                                ip[8],
341                                ip[9],
342                                ip[10],
343                                ip[11],
344                                ip[12],
345                                ip[13],
346                                ip[14],
347                                ip[15]
348                            );
349                            san_dns.push(ip_addr);
350                        }
351                    }
352                    _ => {
353                        // Ignore other name types for now
354                    }
355                }
356            }
357        }
358
359        Ok(X509CertificateInfo {
360            thumbprint,
361            subject_dn,
362            issuer_dn,
363            serial_number,
364            not_before,
365            not_after,
366            san_dns,
367            san_uri,
368            san_email,
369        })
370    }
371
372    /// Calculate SHA-256 thumbprint of certificate
373    fn calculate_certificate_thumbprint(&self, cert_der: &[u8]) -> Result<String> {
374        use sha2::{Digest, Sha256};
375
376        let mut hasher = Sha256::new();
377        hasher.update(cert_der);
378        let hash = hasher.finalize();
379
380        Ok(URL_SAFE_NO_PAD.encode(hash))
381    }
382
383    /// Validate a PKI certificate: verified chain to a trusted anchor, then identity binding.
384    fn validate_pki_certificate(
385        &self,
386        cert: &X509Certificate<'_>,
387        cert_der: &[u8],
388        intermediates: &[Vec<u8>],
389        client_config: &MutualTlsClientConfig,
390    ) -> (bool, Vec<String>) {
391        let mut errors = Vec::new();
392
393        // Trust anchors: the client's own CA list when set, otherwise the manager's store.
394        let anchors: &[Vec<u8>] = if client_config.ca_certificates.is_empty() {
395            &self.ca_store
396        } else {
397            &client_config.ca_certificates
398        };
399
400        if let Err(e) = verify_certificate_chain(cert_der, intermediates, anchors) {
401            errors.push(e);
402        }
403
404        // keyUsage (webpki does not look at it): when present it must allow digital signatures
405        // (TLS client authentication); a malformed extension is a rejection, never a pass.
406        match cert.key_usage() {
407            Ok(None) => {}
408            Ok(Some(key_usage)) if key_usage.value.digital_signature() => {}
409            Ok(Some(_)) => errors.push("Certificate does not allow digital signatures".to_string()),
410            Err(_) => errors.push("Certificate has a malformed keyUsage extension".to_string()),
411        }
412
413        // The certificate must belong to THIS client, not merely to some client of the CA.
414        if let Err(e) = check_identity_binding(cert, cert_der, client_config) {
415            errors.push(e);
416        }
417
418        (errors.is_empty(), errors)
419    }
420
421    /// Validate self-signed certificate
422    fn validate_self_signed_certificate(
423        &self,
424        cert: &X509Certificate<'_>,
425        client_config: &MutualTlsClientConfig,
426    ) -> (bool, Vec<String>) {
427        let mut errors = Vec::new();
428
429        // Check certificate validity period
430        let now = chrono::Utc::now().timestamp();
431        if cert.validity().not_before.timestamp() > now {
432            errors.push("Certificate is not yet valid".to_string());
433        }
434        if cert.validity().not_after.timestamp() < now {
435            errors.push("Certificate has expired".to_string());
436        }
437
438        // For self-signed, check if it matches the registered certificate
439        if let Some(registered_cert_der) = &client_config.client_certificate {
440            if let Ok((_, registered_cert)) = parse_x509_certificate(registered_cert_der) {
441                // Compare public keys
442                if cert.public_key().raw != registered_cert.public_key().raw {
443                    errors.push("Certificate does not match registered certificate".to_string());
444                }
445            } else {
446                errors.push("Invalid registered certificate".to_string());
447            }
448        } else {
449            errors.push("No registered certificate for self-signed authentication".to_string());
450        }
451
452        // Check subject DN if specified (structural, exact match)
453        if let Some(expected_subject) = &client_config.expected_subject_dn {
454            match subject_matches(cert, expected_subject) {
455                Ok(true) => {}
456                Ok(false) => errors.push(format!(
457                    "Subject DN does not match the registered subject: {expected_subject}"
458                )),
459                Err(e) => errors.push(e),
460            }
461        }
462
463        (errors.is_empty(), errors)
464    }
465
466    /// Validate client configuration
467    fn validate_client_config(&self, config: &MutualTlsClientConfig) -> Result<()> {
468        // A registered DN must parse as RFC 4514 and be non-empty, for every method: an
469        // unparsable or empty value must never end up meaning "matches anything".
470        if let Some(dn) = &config.expected_subject_dn {
471            parse_rfc4514(dn).map_err(|e| AuthError::auth_method("mtls", e))?;
472        }
473        if let Some(pin) = &config.client_certificate
474            && pin.is_empty()
475        {
476            return Err(AuthError::auth_method(
477                "mtls",
478                "client_certificate must not be empty",
479            ));
480        }
481
482        match config.auth_method {
483            MutualTlsMethod::PkiMutualTls => {
484                if config.ca_certificates.is_empty() && self.ca_store.is_empty() {
485                    return Err(AuthError::auth_method(
486                        "mtls",
487                        "PKI authentication requires CA certificates",
488                    ));
489                }
490                for ca in &config.ca_certificates {
491                    ensure_ca_certificate(ca)?;
492                }
493                if config.client_certificate.is_none() && config.expected_subject_dn.is_none() {
494                    return Err(AuthError::auth_method(
495                        "mtls",
496                        "PKI authentication requires binding the client to its certificate: \
497                         set client_certificate (pin) or expected_subject_dn",
498                    ));
499                }
500                if let Some(pin) = &config.client_certificate
501                    && parse_single_certificate(pin).is_err()
502                {
503                    return Err(AuthError::auth_method(
504                        "mtls",
505                        "client_certificate must be a single DER certificate",
506                    ));
507                }
508            }
509            MutualTlsMethod::SelfSignedTlsClientAuth => {
510                if config.client_certificate.is_none() {
511                    return Err(AuthError::auth_method(
512                        "mtls",
513                        "Self-signed authentication requires registered client certificate",
514                    ));
515                }
516            }
517        }
518
519        Ok(())
520    }
521}
522
523/// Parse exactly one DER certificate; trailing bytes are rejected.
524fn parse_single_certificate(der: &[u8]) -> std::result::Result<X509Certificate<'_>, ()> {
525    match parse_x509_certificate(der) {
526        Ok(([], cert)) => Ok(cert),
527        _ => Err(()),
528    }
529}
530
531/// Require a parseable certificate that asserts `basicConstraints: cA = TRUE`.
532fn ensure_ca_certificate(ca_der: &[u8]) -> Result<()> {
533    let cert = parse_single_certificate(ca_der)
534        .map_err(|_| AuthError::auth_method("mtls", "Invalid CA certificate format"))?;
535
536    if !cert
537        .basic_constraints()
538        .map(|bc| bc.map(|b| b.value.ca).unwrap_or(false))
539        .unwrap_or(false)
540    {
541        return Err(AuthError::auth_method(
542            "mtls",
543            "Certificate is not a CA certificate",
544        ));
545    }
546
547    // It must also be usable as a trust anchor by the verifier: one anchor webpki cannot parse
548    // would otherwise make every authentication that uses this store fail at validation time.
549    // (webpki does not enforce an anchor's own pathLen; set pathLen on intermediates instead.)
550    let der = CertificateDer::from(ca_der);
551    anchor_from_trusted_cert(&der).map_err(|e| {
552        AuthError::auth_method(
553            "mtls",
554            format!("CA certificate is not a usable trust anchor: {e}"),
555        )
556    })?;
557    Ok(())
558}
559
560/// Build and verify the certification path of a TLS client certificate with `rustls-webpki`
561/// (ring backend): signature algorithms RSA PKCS#1/PSS, ECDSA P-256/P-384 and Ed25519,
562/// validity of every certificate on the path (the anchors included), basicConstraints and
563/// pathLen, name constraints and the `clientAuth` extended key usage. The result is
564/// fail-closed: an empty anchor list is an error, never a pass.
565fn verify_certificate_chain(
566    leaf_der: &[u8],
567    intermediates_der: &[Vec<u8>],
568    anchors_der: &[Vec<u8>],
569) -> std::result::Result<(), String> {
570    verify_chain_for_usage(
571        leaf_der,
572        intermediates_der,
573        anchors_der,
574        KeyUsage::client_auth(),
575    )
576}
577
578/// [`verify_certificate_chain`] for any purpose: the path to a trust anchor is built and
579/// verified the same way, with `usage` as the extended key usage the path must permit.
580pub(crate) fn verify_chain_for_usage(
581    leaf_der: &[u8],
582    intermediates_der: &[Vec<u8>],
583    anchors_der: &[Vec<u8>],
584    usage: KeyUsage,
585) -> std::result::Result<(), String> {
586    if anchors_der.is_empty() {
587        return Err("No trusted CA certificates configured".to_string());
588    }
589
590    // webpki checks the validity period of every certificate on the path EXCEPT the trust
591    // anchor (an anchor is just a name, a key and constraints to it), so an expired CA would
592    // stay trusted forever. Drop anchors that are not valid right now.
593    let now = chrono::Utc::now().timestamp();
594    let current_anchors: Vec<&Vec<u8>> = anchors_der
595        .iter()
596        .filter(|der| {
597            parse_x509_certificate(der)
598                .map(|(_, ca)| {
599                    ca.validity().not_before.timestamp() <= now
600                        && now <= ca.validity().not_after.timestamp()
601                })
602                .unwrap_or(false)
603        })
604        .collect();
605    if current_anchors.is_empty() {
606        return Err(
607            "No currently valid trusted CA certificate (expired or not yet valid)".to_string(),
608        );
609    }
610
611    let leaf = CertificateDer::from(leaf_der);
612    let end_entity =
613        EndEntityCert::try_from(&leaf).map_err(|e| format!("Invalid client certificate: {e}"))?;
614
615    let anchor_ders: Vec<CertificateDer<'_>> = current_anchors
616        .iter()
617        .map(|der| CertificateDer::from(der.as_slice()))
618        .collect();
619    let anchors = anchor_ders
620        .iter()
621        .map(|der| {
622            anchor_from_trusted_cert(der)
623                .map_err(|e| format!("Invalid trusted CA certificate: {e}"))
624        })
625        .collect::<std::result::Result<Vec<_>, _>>()?;
626
627    let intermediates: Vec<CertificateDer<'_>> = intermediates_der
628        .iter()
629        .map(|der| CertificateDer::from(der.as_slice()))
630        .collect();
631
632    end_entity
633        .verify_for_usage(
634            ALL_VERIFICATION_ALGS,
635            &anchors,
636            &intermediates,
637            UnixTime::now(),
638            usage,
639            None,
640            None,
641        )
642        .map(|_| ())
643        .map_err(|e| format!("Certificate chain validation failed: {e}"))
644}
645
646/// A distinguished name as structure: RDNs in certificate (DER) order, each RDN a sorted list of
647/// `(attribute OID, value)`.
648type RdnList = Vec<Vec<(String, String)>>;
649
650/// OID of an RFC 4514 attribute keyword (or a dotted OID, passed through).
651fn attribute_oid(name: &str) -> Option<String> {
652    let upper = name.to_ascii_uppercase();
653    let oid = match upper.as_str() {
654        "CN" => "2.5.4.3",
655        "SN" => "2.5.4.4",
656        "SERIALNUMBER" => "2.5.4.5",
657        "C" => "2.5.4.6",
658        "L" => "2.5.4.7",
659        "ST" => "2.5.4.8",
660        "STREET" => "2.5.4.9",
661        "O" => "2.5.4.10",
662        "OU" => "2.5.4.11",
663        "T" | "TITLE" => "2.5.4.12",
664        "GN" => "2.5.4.42",
665        "DC" => "0.9.2342.19200300.100.1.25",
666        "UID" => "0.9.2342.19200300.100.1.1",
667        "EMAILADDRESS" => "1.2.840.113549.1.9.1",
668        other => {
669            let dotted = other.split('.').count() >= 2
670                && other
671                    .split('.')
672                    .all(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_digit()));
673            return dotted.then(|| other.to_string());
674        }
675    };
676    Some(oid.to_string())
677}
678
679/// Parse an RFC 4514 distinguished-name string (`CN=Alice,O=Corp`, most specific RDN first,
680/// `\,` `\+` `\"` `\\` `\<` `\>` `\;` `\=` `\ ` `\#` and `\XX` hex escapes, `+` joins attributes
681/// of one RDN) into structure, returned in certificate (DER) order. Anything it cannot parse
682/// exactly is an error; there is no lenient mode.
683fn parse_rfc4514(dn: &str) -> std::result::Result<RdnList, String> {
684    let shown: String = dn.chars().take(80).collect();
685    let suffix = if dn.chars().count() > 80 {
686        format!("... ({} chars)", dn.chars().count())
687    } else {
688        String::new()
689    };
690    let bad = |why: &str| format!("Invalid distinguished name '{shown}{suffix}': {why}");
691    if dn.trim().is_empty() {
692        return Err(bad("empty"));
693    }
694    let chars: Vec<char> = dn.chars().collect();
695    let mut i = 0;
696    let mut rdns: RdnList = Vec::new();
697    let mut rdn: Vec<(String, String)> = Vec::new();
698
699    loop {
700        while i < chars.len() && chars[i] == ' ' {
701            i += 1;
702        }
703        let start = i;
704        while i < chars.len() && chars[i] != '=' {
705            if matches!(chars[i], ',' | '+' | '\\' | '"') {
706                return Err(bad("attribute type expected before '='"));
707            }
708            i += 1;
709        }
710        if i >= chars.len() {
711            return Err(bad("missing '='"));
712        }
713        let keyword: String = chars[start..i].iter().collect();
714        let oid = attribute_oid(&keyword)
715            .ok_or_else(|| bad(&format!("unknown attribute type '{}'", keyword.trim())))?;
716        i += 1; // '='
717
718        let mut value: Vec<u8> = Vec::new();
719        let mut leading = true;
720        let mut trailing_spaces = 0usize;
721        while i < chars.len() {
722            match chars[i] {
723                ',' | '+' => break,
724                '"' | '<' | '>' | ';' => return Err(bad("unescaped special character in value")),
725                '\\' => {
726                    i += 1;
727                    let next = *chars.get(i).ok_or_else(|| bad("dangling backslash"))?;
728                    if next.is_ascii_hexdigit() {
729                        let second = *chars.get(i + 1).ok_or_else(|| bad("bad hex escape"))?;
730                        if !second.is_ascii_hexdigit() {
731                            return Err(bad("bad hex escape"));
732                        }
733                        let byte = u8::from_str_radix(&format!("{next}{second}"), 16)
734                            .map_err(|_| bad("bad hex escape"))?;
735                        value.push(byte);
736                        i += 2;
737                    } else if matches!(
738                        next,
739                        ',' | '+' | '"' | '\\' | '<' | '>' | ';' | '=' | ' ' | '#'
740                    ) {
741                        let mut buf = [0u8; 4];
742                        value.extend_from_slice(next.encode_utf8(&mut buf).as_bytes());
743                        i += 1;
744                    } else {
745                        return Err(bad("invalid escape"));
746                    }
747                    leading = false;
748                    trailing_spaces = 0;
749                }
750                ' ' if leading => {
751                    return Err(bad(
752                        "unescaped leading space in a value; escape edge spaces as '\\ '",
753                    ));
754                }
755                ' ' => {
756                    value.push(b' ');
757                    trailing_spaces += 1;
758                    i += 1;
759                }
760                '#' if leading => return Err(bad("hex-string values are not supported")),
761                c => {
762                    let mut buf = [0u8; 4];
763                    value.extend_from_slice(c.encode_utf8(&mut buf).as_bytes());
764                    leading = false;
765                    trailing_spaces = 0;
766                    i += 1;
767                }
768            }
769        }
770        if trailing_spaces > 0 {
771            return Err(bad(
772                "unescaped trailing space in a value; escape edge spaces as '\\ '",
773            ));
774        }
775        let value = String::from_utf8(value).map_err(|_| bad("value is not valid UTF-8"))?;
776        if value.is_empty() {
777            return Err(bad("empty attribute value"));
778        }
779        rdn.push((oid, value));
780
781        if i < chars.len() && chars[i] == '+' {
782            i += 1;
783            continue;
784        }
785        rdn.sort();
786        rdns.push(std::mem::take(&mut rdn));
787        if i >= chars.len() {
788            break;
789        }
790        i += 1; // ','
791    }
792    rdns.reverse(); // RFC 4514 lists the most specific RDN first; certificates store it last
793    Ok(rdns)
794}
795
796/// The subject of a certificate as structure (see [`RdnList`]). An attribute whose value
797/// x509-parser cannot read as a string (BMPString, T61String, binary values) makes the subject
798/// unmatchable: it is refused (fail closed), never skipped or guessed at.
799fn subject_rdns(cert: &X509Certificate<'_>) -> std::result::Result<RdnList, String> {
800    cert.subject()
801        .iter_rdn()
802        .map(|rdn| {
803            let mut attrs = rdn
804                .iter()
805                .map(|attr| {
806                    attr.as_str()
807                        .map(|v| (attr.attr_type().to_id_string(), v.to_string()))
808                        .map_err(|_| "Certificate subject has a non-string attribute".to_string())
809                })
810                .collect::<std::result::Result<Vec<_>, _>>()?;
811            attrs.sort();
812            Ok(attrs)
813        })
814        .collect()
815}
816
817/// Does the certificate subject equal the RFC 4514 string `expected`? Compared as structure:
818/// the same RDNs in the same order, attribute types by OID, attribute values EXACTLY (case-
819/// and whitespace-sensitive), so one CN containing ", O=Corp" never equals the two attributes
820/// CN and O. Rendering the subject to text and comparing text would conflate those.
821fn subject_matches(
822    cert: &X509Certificate<'_>,
823    expected: &str,
824) -> std::result::Result<bool, String> {
825    Ok(subject_rdns(cert)? == parse_rfc4514(expected)?)
826}
827
828/// A certificate that chains to a trusted CA only proves the CA issued it; this ties it to the
829/// registered client: exact pin if `client_certificate` is set, else the exact subject DN
830/// (compared as structure, see [`subject_matches`]).
831fn check_identity_binding(
832    cert: &X509Certificate<'_>,
833    cert_der: &[u8],
834    client_config: &MutualTlsClientConfig,
835) -> std::result::Result<(), String> {
836    if let Some(pinned) = &client_config.client_certificate {
837        return if pinned.as_slice() == cert_der {
838            Ok(())
839        } else {
840            Err("Client certificate does not match the registered certificate".to_string())
841        };
842    }
843    if let Some(expected) = &client_config.expected_subject_dn {
844        return if subject_matches(cert, expected)? {
845            Ok(())
846        } else {
847            Err(format!(
848                "Certificate subject does not match the registered subject: {expected}"
849            ))
850        };
851    }
852    Err(
853        "Client has no certificate binding configured (client_certificate or expected_subject_dn)"
854            .to_string(),
855    )
856}
857
858impl Default for MutualTlsManager {
859    fn default() -> Self {
860        Self::new()
861    }
862}
863
864#[cfg(test)]
865mod tests {
866    use super::*;
867
868    fn create_test_client_config() -> MutualTlsClientConfig {
869        MutualTlsClientConfig {
870            client_id: "test_client".to_string(),
871            auth_method: MutualTlsMethod::SelfSignedTlsClientAuth,
872            ca_certificates: Vec::new(),
873            client_certificate: Some(b"dummy_cert".to_vec()), // Would be real cert in practice
874            expected_subject_dn: Some("CN=test_client".to_string()),
875            certificate_bound_access_tokens: true,
876        }
877    }
878
879    #[tokio::test]
880    async fn test_mtls_manager_creation() {
881        let manager = MutualTlsManager::new();
882        assert!(manager.ca_store.is_empty());
883    }
884
885    #[tokio::test]
886    async fn test_client_registration() {
887        let manager = MutualTlsManager::new();
888        let config = create_test_client_config();
889        manager.register_client(config).await.unwrap();
890    }
891
892    #[test]
893    fn test_certificate_confirmation() {
894        let manager = MutualTlsManager::new();
895
896        // Test with dummy certificate data
897        let cert_data = b"dummy_certificate_data";
898        let confirmation = manager.create_certificate_confirmation(cert_data).unwrap();
899
900        assert!(!confirmation.x5t_s256.is_empty());
901
902        // Validate the same certificate
903        let is_valid = manager
904            .validate_certificate_bound_token(&confirmation, cert_data)
905            .unwrap();
906        assert!(is_valid);
907
908        // Validate different certificate (should fail)
909        let different_cert = b"different_certificate_data";
910        let is_valid = manager
911            .validate_certificate_bound_token(&confirmation, different_cert)
912            .unwrap();
913        assert!(!is_valid);
914    }
915
916    // ---- Certificate validation tests built on real rcgen certificate chains ----
917
918    use rcgen::{
919        BasicConstraints, CertificateParams, DistinguishedName, DnType, ExtendedKeyUsagePurpose,
920        IsCa, Issuer, KeyPair, KeyUsagePurpose, PKCS_ECDSA_P256_SHA256, PKCS_RSA_SHA256,
921        date_time_ymd,
922    };
923
924    type TestIssuer = Issuer<'static, KeyPair>;
925
926    fn dn(cn: &str) -> DistinguishedName {
927        let mut d = DistinguishedName::new();
928        d.push(DnType::CommonName, cn);
929        d
930    }
931
932    fn ca_params(cn: &str, path_len: Option<u8>) -> CertificateParams {
933        let mut p = CertificateParams::new(Vec::<String>::new()).unwrap();
934        p.distinguished_name = dn(cn);
935        p.is_ca = match path_len {
936            Some(n) => IsCa::Ca(BasicConstraints::Constrained(n)),
937            None => IsCa::Ca(BasicConstraints::Unconstrained),
938        };
939        p.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign];
940        p
941    }
942
943    /// A self-signed root: (DER, issuer handle for signing children).
944    fn new_root(cn: &str) -> (Vec<u8>, TestIssuer) {
945        let key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
946        let params = ca_params(cn, None);
947        let cert = params.clone().self_signed(&key).unwrap();
948        (cert.der().to_vec(), Issuer::new(params, key))
949    }
950
951    /// An intermediate CA signed by `parent`: (DER, issuer handle).
952    fn new_intermediate(
953        cn: &str,
954        path_len: Option<u8>,
955        parent: &TestIssuer,
956    ) -> (Vec<u8>, TestIssuer) {
957        let key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
958        let params = ca_params(cn, path_len);
959        let cert = params.clone().signed_by(&key, parent).unwrap();
960        (cert.der().to_vec(), Issuer::new(params, key))
961    }
962
963    fn leaf_params(cn: &str) -> CertificateParams {
964        let mut p = CertificateParams::new(vec![format!("{cn}.example.test")]).unwrap();
965        p.distinguished_name = dn(cn);
966        p.key_usages = vec![KeyUsagePurpose::DigitalSignature];
967        p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth];
968        p
969    }
970
971    fn issue_leaf(cn: &str, issuer: &TestIssuer) -> Vec<u8> {
972        issue_leaf_with(leaf_params(cn), issuer)
973    }
974
975    fn issue_leaf_with(params: CertificateParams, issuer: &TestIssuer) -> Vec<u8> {
976        let key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
977        params.signed_by(&key, issuer).unwrap().der().to_vec()
978    }
979
980    fn pki_client(
981        client_id: &str,
982        subject_dn: Option<&str>,
983        pin: Option<&[u8]>,
984    ) -> MutualTlsClientConfig {
985        MutualTlsClientConfig {
986            client_id: client_id.to_string(),
987            auth_method: MutualTlsMethod::PkiMutualTls,
988            ca_certificates: Vec::new(),
989            client_certificate: pin.map(|p| p.to_vec()),
990            expected_subject_dn: subject_dn.map(str::to_string),
991            certificate_bound_access_tokens: false,
992        }
993    }
994
995    /// A manager that trusts `root_der` and has `client_id` registered bound to `CN=<client_id>`.
996    async fn manager_trusting(root_der: &[u8], client_ids: &[&str]) -> MutualTlsManager {
997        let mut m = MutualTlsManager::new();
998        m.add_ca_certificate(root_der.to_vec()).unwrap();
999        for id in client_ids {
1000            m.register_client(pki_client(id, Some(&format!("CN={id}")), None))
1001                .await
1002                .unwrap();
1003        }
1004        m
1005    }
1006
1007    async fn accepted(
1008        m: &MutualTlsManager,
1009        client_id: &str,
1010        cert: &[u8],
1011        chain: &[Vec<u8>],
1012    ) -> bool {
1013        let auth = m
1014            .authenticate_client_with_chain(client_id, cert, chain)
1015            .await
1016            .unwrap();
1017        let validated = m
1018            .validate_client_certificate_with_chain(cert, chain, client_id)
1019            .await;
1020        // The two entry points share one validator and must never disagree.
1021        assert_eq!(
1022            auth.is_valid,
1023            validated.is_ok(),
1024            "{:?}",
1025            auth.validation_errors
1026        );
1027        auth.is_valid
1028    }
1029
1030    #[tokio::test]
1031    async fn accepts_a_certificate_issued_by_the_trusted_ca() {
1032        let (root, issuer) = new_root("Trusted Root");
1033        let m = manager_trusting(&root, &["client-a"]).await;
1034        let leaf = issue_leaf("client-a", &issuer);
1035        assert!(accepted(&m, "client-a", &leaf, &[]).await);
1036    }
1037
1038    #[tokio::test]
1039    async fn rejects_a_forged_certificate_with_the_trusted_issuer_dn() {
1040        // A certificate that merely carries the CA's issuer DN, signed by another key, must fail.
1041        let (root, _) = new_root("Trusted Root");
1042        let (_, attacker_ca) = new_root("Trusted Root"); // same DN, different key
1043        let m = manager_trusting(&root, &["client-a"]).await;
1044        let forged = issue_leaf("client-a", &attacker_ca);
1045        assert!(!accepted(&m, "client-a", &forged, &[]).await);
1046    }
1047
1048    #[tokio::test]
1049    async fn rejects_a_self_signed_certificate_for_a_pki_client() {
1050        let (root, _) = new_root("Trusted Root");
1051        let m = manager_trusting(&root, &["client-a"]).await;
1052        let key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
1053        let selfsigned = leaf_params("client-a")
1054            .self_signed(&key)
1055            .unwrap()
1056            .der()
1057            .to_vec();
1058        assert!(!accepted(&m, "client-a", &selfsigned, &[]).await);
1059    }
1060
1061    #[tokio::test]
1062    async fn an_empty_trust_store_never_authenticates() {
1063        // With no trust anchor available nothing may authenticate.
1064        let m = MutualTlsManager::new();
1065        // Registration of a PKI client with no CA anywhere is refused...
1066        assert!(
1067            m.register_client(pki_client("client-a", Some("CN=client-a"), None))
1068                .await
1069                .is_err()
1070        );
1071        // ...and a store that is emptied of anchors cannot validate: a client that carries only
1072        // a per-client CA list validates against that list and nothing else.
1073        let (root, issuer) = new_root("Trusted Root");
1074        let mut cfg = pki_client("client-a", Some("CN=client-a"), None);
1075        cfg.ca_certificates = vec![root.clone()];
1076        m.register_client(cfg).await.unwrap();
1077        let good = issue_leaf("client-a", &issuer);
1078        assert!(accepted(&m, "client-a", &good, &[]).await);
1079        let (_, other_ca) = new_root("Other Root");
1080        let wrong_ca = issue_leaf("client-a", &other_ca);
1081        assert!(!accepted(&m, "client-a", &wrong_ca, &[]).await);
1082    }
1083
1084    #[tokio::test]
1085    async fn rejects_a_certificate_presented_as_a_different_client() {
1086        let (root, issuer) = new_root("Trusted Root");
1087        let m = manager_trusting(&root, &["client-a", "client-b"]).await;
1088        let leaf_a = issue_leaf("client-a", &issuer);
1089        assert!(accepted(&m, "client-a", &leaf_a, &[]).await);
1090        assert!(!accepted(&m, "client-b", &leaf_a, &[]).await);
1091    }
1092
1093    #[tokio::test]
1094    async fn subject_dn_must_match_exactly_not_as_a_substring() {
1095        let (root, issuer) = new_root("Trusted Root");
1096        let m = manager_trusting(&root, &["client-a"]).await;
1097        let evil = issue_leaf("client-a-evil", &issuer);
1098        assert!(!accepted(&m, "client-a", &evil, &[]).await);
1099    }
1100
1101    #[tokio::test]
1102    async fn a_pinned_certificate_must_match_byte_for_byte() {
1103        let (root, issuer) = new_root("Trusted Root");
1104        let pinned = issue_leaf("client-a", &issuer);
1105        let other = issue_leaf("client-a", &issuer); // same subject, different key
1106        let mut m = MutualTlsManager::new();
1107        m.add_ca_certificate(root).unwrap();
1108        m.register_client(pki_client("client-a", None, Some(&pinned)))
1109            .await
1110            .unwrap();
1111        assert!(accepted(&m, "client-a", &pinned, &[]).await);
1112        assert!(!accepted(&m, "client-a", &other, &[]).await);
1113    }
1114
1115    #[tokio::test]
1116    async fn a_pki_client_without_a_binding_cannot_be_registered() {
1117        let (root, _) = new_root("Trusted Root");
1118        let mut m = MutualTlsManager::new();
1119        m.add_ca_certificate(root).unwrap();
1120        assert!(
1121            m.register_client(pki_client("client-a", None, None))
1122                .await
1123                .is_err()
1124        );
1125    }
1126
1127    #[tokio::test]
1128    async fn rejects_a_server_auth_only_certificate() {
1129        let (root, issuer) = new_root("Trusted Root");
1130        let m = manager_trusting(&root, &["client-a"]).await;
1131        let mut p = leaf_params("client-a");
1132        p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth];
1133        let server_only = issue_leaf_with(p, &issuer);
1134        assert!(!accepted(&m, "client-a", &server_only, &[]).await);
1135    }
1136
1137    #[tokio::test]
1138    async fn a_ca_certificate_is_not_accepted_as_a_client_certificate() {
1139        let (root, issuer) = new_root("Trusted Root");
1140        let m = manager_trusting(&root, &["client-a"]).await;
1141        let mut p = ca_params("client-a", None);
1142        p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth];
1143        let ca_as_leaf = issue_leaf_with(p, &issuer);
1144        assert!(!accepted(&m, "client-a", &ca_as_leaf, &[]).await);
1145    }
1146
1147    #[tokio::test]
1148    async fn a_non_ca_leaf_cannot_issue_client_certificates() {
1149        let (root, issuer) = new_root("Trusted Root");
1150        let m = manager_trusting(&root, &["client-x"]).await;
1151        // A legitimate end-entity certificate (CA:false) tries to act as a CA.
1152        let leaf_key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
1153        let leaf_p = leaf_params("not-a-ca");
1154        let leaf_der = leaf_p
1155            .clone()
1156            .signed_by(&leaf_key, &issuer)
1157            .unwrap()
1158            .der()
1159            .to_vec();
1160        let leaf_issuer = Issuer::new(leaf_p, leaf_key);
1161        let x = issue_leaf("client-x", &leaf_issuer);
1162        assert!(!accepted(&m, "client-x", &x, &[]).await);
1163        assert!(!accepted(&m, "client-x", &x, std::slice::from_ref(&leaf_der)).await);
1164    }
1165
1166    #[tokio::test]
1167    async fn rejects_an_expired_ca() {
1168        let key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
1169        let mut params = ca_params("Old Root", None);
1170        params.not_before = date_time_ymd(2019, 1, 1);
1171        params.not_after = date_time_ymd(2021, 1, 1);
1172        let root = params.clone().self_signed(&key).unwrap().der().to_vec();
1173        let issuer = Issuer::new(params, key);
1174        let m = manager_trusting(&root, &["client-a"]).await;
1175        let leaf = issue_leaf("client-a", &issuer); // leaf itself is valid now
1176        assert!(!accepted(&m, "client-a", &leaf, &[]).await);
1177    }
1178
1179    #[tokio::test]
1180    async fn rejects_an_expired_client_certificate() {
1181        let (root, issuer) = new_root("Trusted Root");
1182        let m = manager_trusting(&root, &["client-a"]).await;
1183        let mut p = leaf_params("client-a");
1184        p.not_before = date_time_ymd(2019, 1, 1);
1185        p.not_after = date_time_ymd(2021, 1, 1);
1186        let expired = issue_leaf_with(p, &issuer);
1187        assert!(!accepted(&m, "client-a", &expired, &[]).await);
1188    }
1189
1190    #[tokio::test]
1191    async fn builds_a_chain_through_an_intermediate() {
1192        let (root, root_issuer) = new_root("Trusted Root");
1193        let (inter, inter_issuer) = new_intermediate("Intermediate", None, &root_issuer);
1194        let m = manager_trusting(&root, &["client-a"]).await;
1195        let leaf = issue_leaf("client-a", &inter_issuer);
1196        // Without the intermediate the path cannot be built.
1197        assert!(!accepted(&m, "client-a", &leaf, &[]).await);
1198        assert!(accepted(&m, "client-a", &leaf, std::slice::from_ref(&inter)).await);
1199    }
1200
1201    #[tokio::test]
1202    async fn enforces_the_path_length_constraint() {
1203        let (root, root_issuer) = new_root("Trusted Root");
1204        // pathLen 0: this intermediate may only issue end-entity certificates.
1205        let (inter1, inter1_issuer) = new_intermediate("Intermediate 1", Some(0), &root_issuer);
1206        let (inter2, inter2_issuer) = new_intermediate("Intermediate 2", None, &inter1_issuer);
1207        let m = manager_trusting(&root, &["client-a"]).await;
1208        let leaf = issue_leaf("client-a", &inter2_issuer);
1209        assert!(!accepted(&m, "client-a", &leaf, &[inter1, inter2]).await);
1210    }
1211
1212    #[tokio::test]
1213    async fn accepts_rsa_signed_chains() {
1214        let key = KeyPair::generate_for(&PKCS_RSA_SHA256).unwrap();
1215        let params = ca_params("RSA Root", None);
1216        let root = params.clone().self_signed(&key).unwrap().der().to_vec();
1217        let issuer = Issuer::new(params, key);
1218        let m = manager_trusting(&root, &["client-a"]).await;
1219        let leaf_key = KeyPair::generate_for(&PKCS_RSA_SHA256).unwrap();
1220        let leaf = leaf_params("client-a")
1221            .signed_by(&leaf_key, &issuer)
1222            .unwrap()
1223            .der()
1224            .to_vec();
1225        assert!(accepted(&m, "client-a", &leaf, &[]).await);
1226    }
1227
1228    #[tokio::test]
1229    async fn rejects_malformed_and_trailing_data() {
1230        let (root, issuer) = new_root("Trusted Root");
1231        let m = manager_trusting(&root, &["client-a"]).await;
1232        let leaf = issue_leaf("client-a", &issuer);
1233        assert!(
1234            m.authenticate_client("client-a", b"not a certificate")
1235                .await
1236                .is_err()
1237        );
1238        let mut padded = leaf.clone();
1239        padded.extend_from_slice(b"\x00\x00");
1240        assert!(m.authenticate_client("client-a", &padded).await.is_err());
1241        assert!(
1242            m.authenticate_client("unknown-client", &leaf)
1243                .await
1244                .is_err()
1245        );
1246    }
1247
1248    #[tokio::test]
1249    async fn only_ca_certificates_are_accepted_as_trust_anchors() {
1250        let (root, issuer) = new_root("Trusted Root");
1251        let leaf = issue_leaf("client-a", &issuer);
1252        let mut m = MutualTlsManager::new();
1253        assert!(m.add_ca_certificate(leaf.clone()).is_err());
1254        assert!(m.add_ca_certificate(root).is_ok());
1255        let mut cfg = pki_client("client-a", Some("CN=client-a"), None);
1256        cfg.ca_certificates = vec![leaf];
1257        assert!(m.register_client(cfg).await.is_err());
1258    }
1259
1260    #[tokio::test]
1261    async fn self_signed_client_auth_matches_the_registered_key() {
1262        let key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
1263        let cert = leaf_params("sc").self_signed(&key).unwrap().der().to_vec();
1264        let other_key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
1265        let other = leaf_params("sc")
1266            .self_signed(&other_key)
1267            .unwrap()
1268            .der()
1269            .to_vec();
1270
1271        let m = MutualTlsManager::new();
1272        m.register_client(MutualTlsClientConfig {
1273            client_id: "sc".to_string(),
1274            auth_method: MutualTlsMethod::SelfSignedTlsClientAuth,
1275            ca_certificates: Vec::new(),
1276            client_certificate: Some(cert.clone()),
1277            expected_subject_dn: Some("CN=sc".to_string()),
1278            certificate_bound_access_tokens: false,
1279        })
1280        .await
1281        .unwrap();
1282        assert!(accepted(&m, "sc", &cert, &[]).await);
1283        assert!(!accepted(&m, "sc", &other, &[]).await);
1284    }
1285
1286    // ---- distinguished-name binding is structural ----
1287
1288    /// A leaf whose subject is exactly the given (type, value) RDNs, one attribute per RDN, in
1289    /// certificate order.
1290    fn leaf_with_subject(rdns: &[(DnType, &str)], issuer: &TestIssuer) -> Vec<u8> {
1291        let mut p = leaf_params("unused");
1292        let mut d = DistinguishedName::new();
1293        for (ty, value) in rdns {
1294            d.push(ty.clone(), *value);
1295        }
1296        p.distinguished_name = d;
1297        issue_leaf_with(p, issuer)
1298    }
1299
1300    #[tokio::test]
1301    async fn one_cn_containing_a_comma_is_not_two_attributes() {
1302        // CN="Alice, O=Corp" (ONE attribute) renders like CN=Alice + O=Corp (TWO) as text, but
1303        // they are different subjects and must not be interchangeable.
1304        let (root, issuer) = new_root("Trusted Root");
1305        let single = leaf_with_subject(&[(DnType::CommonName, "Alice, O=Corp")], &issuer);
1306        let two = leaf_with_subject(
1307            &[
1308                (DnType::OrganizationName, "Corp"),
1309                (DnType::CommonName, "Alice"),
1310            ],
1311            &issuer,
1312        );
1313
1314        let mut m = MutualTlsManager::new();
1315        m.add_ca_certificate(root).unwrap();
1316        // Registered for the two-attribute subject (RFC 4514: most specific RDN first).
1317        m.register_client(pki_client("a", Some("CN=Alice,O=Corp"), None))
1318            .await
1319            .unwrap();
1320        assert!(accepted(&m, "a", &two, &[]).await);
1321        assert!(!accepted(&m, "a", &single, &[]).await);
1322
1323        // Registered for the single-attribute subject (the comma escaped).
1324        m.register_client(pki_client("b", Some(r"CN=Alice\, O=Corp"), None))
1325            .await
1326            .unwrap();
1327        assert!(accepted(&m, "b", &single, &[]).await);
1328        assert!(!accepted(&m, "b", &two, &[]).await);
1329    }
1330
1331    #[tokio::test]
1332    async fn the_self_signed_path_compares_the_subject_as_structure_too() {
1333        let single = {
1334            let key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
1335            let mut p = leaf_params("x");
1336            let mut d = DistinguishedName::new();
1337            d.push(DnType::CommonName, "Alice, O=Corp");
1338            p.distinguished_name = d;
1339            p.self_signed(&key).unwrap().der().to_vec()
1340        };
1341        let m = MutualTlsManager::new();
1342        m.register_client(MutualTlsClientConfig {
1343            client_id: "sc".to_string(),
1344            auth_method: MutualTlsMethod::SelfSignedTlsClientAuth,
1345            ca_certificates: Vec::new(),
1346            client_certificate: Some(single.clone()),
1347            expected_subject_dn: Some("CN=Alice,O=Corp".to_string()), // two attributes
1348            certificate_bound_access_tokens: false,
1349        })
1350        .await
1351        .unwrap();
1352        // Same key as the registered certificate, but the subject is a different structure.
1353        assert!(!accepted(&m, "sc", &single, &[]).await);
1354    }
1355
1356    #[tokio::test]
1357    async fn attribute_values_are_compared_exactly_including_case() {
1358        let (root, issuer) = new_root("Trusted Root");
1359        let leaf = issue_leaf("Client-A", &issuer);
1360        let mut m = MutualTlsManager::new();
1361        m.add_ca_certificate(root).unwrap();
1362        m.register_client(pki_client("exact", Some("CN=Client-A"), None))
1363            .await
1364            .unwrap();
1365        m.register_client(pki_client("lower", Some("CN=client-a"), None))
1366            .await
1367            .unwrap();
1368        // Attribute TYPES are case-insensitive keywords, VALUES are exact.
1369        m.register_client(pki_client("kw", Some("cn=Client-A"), None))
1370            .await
1371            .unwrap();
1372        assert!(accepted(&m, "exact", &leaf, &[]).await);
1373        assert!(accepted(&m, "kw", &leaf, &[]).await);
1374        assert!(!accepted(&m, "lower", &leaf, &[]).await);
1375    }
1376
1377    #[tokio::test]
1378    async fn registration_rejects_empty_or_unparsable_subject_dns() {
1379        let (root, _) = new_root("Trusted Root");
1380        let mut m = MutualTlsManager::new();
1381        m.add_ca_certificate(root).unwrap();
1382        for bad in [
1383            "",
1384            "   ",
1385            "Alice",
1386            "CN=",
1387            "CN=Alice,",
1388            "FOO=Alice",
1389            "CN=Alice;O=Corp",
1390            "CN=\"Alice\"",
1391            "CN=#0403414243",
1392            "CN=Alice\\",
1393            "CN= Alice",
1394            "CN=Alice ",
1395        ] {
1396            assert!(
1397                m.register_client(pki_client("c", Some(bad), None))
1398                    .await
1399                    .is_err(),
1400                "{bad:?} must not register"
1401            );
1402        }
1403        // The same rule applies to self-signed clients.
1404        let key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
1405        let cert = leaf_params("sc").self_signed(&key).unwrap().der().to_vec();
1406        let cfg = MutualTlsClientConfig {
1407            client_id: "sc".to_string(),
1408            auth_method: MutualTlsMethod::SelfSignedTlsClientAuth,
1409            ca_certificates: Vec::new(),
1410            client_certificate: Some(cert),
1411            expected_subject_dn: Some(String::new()),
1412            certificate_bound_access_tokens: false,
1413        };
1414        assert!(m.register_client(cfg).await.is_err());
1415        // An empty pin is as meaningless as an empty DN, and a PKI pin must be a certificate.
1416        assert!(
1417            m.register_client(pki_client("c", None, Some(&[])))
1418                .await
1419                .is_err()
1420        );
1421        assert!(
1422            m.register_client(pki_client("c", None, Some(b"not a certificate")))
1423                .await
1424                .is_err()
1425        );
1426    }
1427
1428    #[test]
1429    fn rfc4514_parsing_covers_escapes_multi_valued_rdns_and_order() {
1430        // Most specific RDN first in the string, last in the certificate.
1431        let parsed = parse_rfc4514("CN=Alice,OU=Eng,O=Corp").unwrap();
1432        let oid = |s: &str| s.to_string();
1433        assert_eq!(
1434            parsed,
1435            vec![
1436                vec![(oid("2.5.4.10"), "Corp".to_string())],
1437                vec![(oid("2.5.4.11"), "Eng".to_string())],
1438                vec![(oid("2.5.4.3"), "Alice".to_string())],
1439            ]
1440        );
1441        // A space after a separator, before the attribute type, is just layout; escaped edge
1442        // spaces belong to the value; interior spaces are kept.
1443        assert_eq!(
1444            parse_rfc4514(r"CN=a\ , O=b c").unwrap(),
1445            vec![
1446                vec![(oid("2.5.4.10"), "b c".to_string())],
1447                vec![(oid("2.5.4.3"), "a ".to_string())],
1448            ]
1449        );
1450        // Unescaped edge spaces in a value are refused, not normalised away.
1451        for bad in [
1452            "CN= Alice",
1453            "CN=Alice ",
1454            "CN=Alice , O=Corp",
1455            "CN =Alice",
1456            "O=Corp,CN= a",
1457        ] {
1458            assert!(parse_rfc4514(bad).is_err(), "{bad:?} must be refused");
1459        }
1460        let long = format!("CN={}", "x ".repeat(100));
1461        let err = parse_rfc4514(&long).unwrap_err();
1462        assert!(err.contains("chars)") && err.len() < 200, "{err}");
1463        // Escapes: special characters and hex pairs (UTF-8 bytes).
1464        assert_eq!(
1465            parse_rfc4514(r"CN=a\,b\+c\\d\3d\C3\A9").unwrap(),
1466            vec![vec![(oid("2.5.4.3"), "a,b+c\\d=é".to_string())]]
1467        );
1468        // '+' joins attributes of ONE RDN, order-insensitively.
1469        assert_eq!(
1470            parse_rfc4514("CN=Alice+O=Corp").unwrap(),
1471            parse_rfc4514("O=Corp+CN=Alice").unwrap()
1472        );
1473        assert_ne!(
1474            parse_rfc4514("CN=Alice+O=Corp").unwrap(),
1475            parse_rfc4514("CN=Alice,O=Corp").unwrap()
1476        );
1477        // Dotted OIDs are accepted.
1478        assert_eq!(
1479            parse_rfc4514("2.5.4.3=Alice").unwrap(),
1480            parse_rfc4514("CN=Alice").unwrap()
1481        );
1482    }
1483
1484    // ---- keyUsage, trust anchors ----
1485
1486    #[tokio::test]
1487    async fn key_usage_without_digital_signature_is_rejected() {
1488        // webpki does not look at keyUsage, so this rule is ours: a client certificate whose
1489        // keyUsage lacks digitalSignature (here keyEncipherment only) must fail even though it
1490        // chains to the CA and carries the clientAuth EKU.
1491        let (root, issuer) = new_root("Trusted Root");
1492        let m = manager_trusting(&root, &["client-a"]).await;
1493        let mut p = leaf_params("client-a");
1494        p.key_usages = vec![KeyUsagePurpose::KeyEncipherment];
1495        p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth];
1496        let cert = issue_leaf_with(p, &issuer);
1497        assert!(!accepted(&m, "client-a", &cert, &[]).await);
1498        // The same certificate with digitalSignature added passes.
1499        let mut ok = leaf_params("client-a");
1500        ok.key_usages = vec![
1501            KeyUsagePurpose::KeyEncipherment,
1502            KeyUsagePurpose::DigitalSignature,
1503        ];
1504        let good = issue_leaf_with(ok, &issuer);
1505        assert!(accepted(&m, "client-a", &good, &[]).await);
1506    }
1507
1508    #[tokio::test]
1509    async fn an_unusable_trust_anchor_is_refused_up_front() {
1510        let (_, issuer) = new_root("Trusted Root");
1511        let leaf = issue_leaf("client-a", &issuer);
1512        let mut m = MutualTlsManager::new();
1513        // Garbage, a non-CA and truncated DER never enter the store.
1514        assert!(m.add_ca_certificate(b"junk".to_vec()).is_err());
1515        assert!(m.add_ca_certificate(leaf).is_err());
1516        let (root, _) = new_root("Other Root");
1517        assert!(
1518            m.add_ca_certificate(root[..root.len() - 4].to_vec())
1519                .is_err()
1520        );
1521    }
1522
1523    #[tokio::test]
1524    async fn rdn_order_is_part_of_the_subject() {
1525        // Same attributes, opposite order: different subjects.
1526        let (root, issuer) = new_root("Trusted Root");
1527        let mut m = MutualTlsManager::new();
1528        m.add_ca_certificate(root).unwrap();
1529        // RFC 4514 string order is most specific first, so this is O=Corp then CN=Alice in the
1530        // certificate.
1531        m.register_client(pki_client("a", Some("CN=Alice,O=Corp"), None))
1532            .await
1533            .unwrap();
1534        let in_order = leaf_with_subject(
1535            &[
1536                (DnType::OrganizationName, "Corp"),
1537                (DnType::CommonName, "Alice"),
1538            ],
1539            &issuer,
1540        );
1541        let swapped = leaf_with_subject(
1542            &[
1543                (DnType::CommonName, "Alice"),
1544                (DnType::OrganizationName, "Corp"),
1545            ],
1546            &issuer,
1547        );
1548        assert!(accepted(&m, "a", &in_order, &[]).await);
1549        assert!(!accepted(&m, "a", &swapped, &[]).await);
1550    }
1551
1552    #[tokio::test]
1553    async fn a_malformed_key_usage_extension_never_passes() {
1554        let (root, issuer) = new_root("Trusted Root");
1555        let m = manager_trusting(&root, &["client-a"]).await;
1556        let mut p = leaf_params("client-a");
1557        p.key_usages = Vec::new();
1558        // keyUsage (2.5.29.15) whose value is an OCTET STRING instead of a BIT STRING.
1559        p.custom_extensions
1560            .push(rcgen::CustomExtension::from_oid_content(
1561                &[2, 5, 29, 15],
1562                vec![0x04, 0x01, 0xFF],
1563            ));
1564        let cert = issue_leaf_with(p, &issuer);
1565        assert!(!accepted(&m, "client-a", &cert, &[]).await);
1566    }
1567
1568    #[tokio::test]
1569    async fn edge_spaces_in_a_common_name_are_not_normalised_away() {
1570        let (root, issuer) = new_root("Trusted Root");
1571        let plain = issue_leaf("client-a", &issuer);
1572        let spaced = issue_leaf("client-a ", &issuer);
1573
1574        let mut m = MutualTlsManager::new();
1575        m.add_ca_certificate(root).unwrap();
1576        // "CN=client-a " with an unescaped trailing space cannot be registered at all...
1577        assert!(
1578            m.register_client(pki_client("x", Some("CN=client-a "), None))
1579                .await
1580                .is_err()
1581        );
1582        // ...a registration for the plain name matches only the plain certificate...
1583        m.register_client(pki_client("plain", Some("CN=client-a"), None))
1584            .await
1585            .unwrap();
1586        assert!(accepted(&m, "plain", &plain, &[]).await);
1587        assert!(!accepted(&m, "plain", &spaced, &[]).await);
1588        // ...and the escaped form matches only the spaced one.
1589        m.register_client(pki_client("spaced", Some(r"CN=client-a\ "), None))
1590            .await
1591            .unwrap();
1592        assert!(accepted(&m, "spaced", &spaced, &[]).await);
1593        assert!(!accepted(&m, "spaced", &plain, &[]).await);
1594    }
1595}