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    if anchors_der.is_empty() {
571        return Err("No trusted CA certificates configured".to_string());
572    }
573
574    // webpki checks the validity period of every certificate on the path EXCEPT the trust
575    // anchor (an anchor is just a name, a key and constraints to it), so an expired CA would
576    // stay trusted forever. Drop anchors that are not valid right now.
577    let now = chrono::Utc::now().timestamp();
578    let current_anchors: Vec<&Vec<u8>> = anchors_der
579        .iter()
580        .filter(|der| {
581            parse_x509_certificate(der)
582                .map(|(_, ca)| {
583                    ca.validity().not_before.timestamp() <= now
584                        && now <= ca.validity().not_after.timestamp()
585                })
586                .unwrap_or(false)
587        })
588        .collect();
589    if current_anchors.is_empty() {
590        return Err(
591            "No currently valid trusted CA certificate (expired or not yet valid)".to_string(),
592        );
593    }
594
595    let leaf = CertificateDer::from(leaf_der);
596    let end_entity =
597        EndEntityCert::try_from(&leaf).map_err(|e| format!("Invalid client certificate: {e}"))?;
598
599    let anchor_ders: Vec<CertificateDer<'_>> = current_anchors
600        .iter()
601        .map(|der| CertificateDer::from(der.as_slice()))
602        .collect();
603    let anchors = anchor_ders
604        .iter()
605        .map(|der| {
606            anchor_from_trusted_cert(der)
607                .map_err(|e| format!("Invalid trusted CA certificate: {e}"))
608        })
609        .collect::<std::result::Result<Vec<_>, _>>()?;
610
611    let intermediates: Vec<CertificateDer<'_>> = intermediates_der
612        .iter()
613        .map(|der| CertificateDer::from(der.as_slice()))
614        .collect();
615
616    end_entity
617        .verify_for_usage(
618            ALL_VERIFICATION_ALGS,
619            &anchors,
620            &intermediates,
621            UnixTime::now(),
622            KeyUsage::client_auth(),
623            None,
624            None,
625        )
626        .map(|_| ())
627        .map_err(|e| format!("Certificate chain validation failed: {e}"))
628}
629
630/// A distinguished name as structure: RDNs in certificate (DER) order, each RDN a sorted list of
631/// `(attribute OID, value)`.
632type RdnList = Vec<Vec<(String, String)>>;
633
634/// OID of an RFC 4514 attribute keyword (or a dotted OID, passed through).
635fn attribute_oid(name: &str) -> Option<String> {
636    let upper = name.to_ascii_uppercase();
637    let oid = match upper.as_str() {
638        "CN" => "2.5.4.3",
639        "SN" => "2.5.4.4",
640        "SERIALNUMBER" => "2.5.4.5",
641        "C" => "2.5.4.6",
642        "L" => "2.5.4.7",
643        "ST" => "2.5.4.8",
644        "STREET" => "2.5.4.9",
645        "O" => "2.5.4.10",
646        "OU" => "2.5.4.11",
647        "T" | "TITLE" => "2.5.4.12",
648        "GN" => "2.5.4.42",
649        "DC" => "0.9.2342.19200300.100.1.25",
650        "UID" => "0.9.2342.19200300.100.1.1",
651        "EMAILADDRESS" => "1.2.840.113549.1.9.1",
652        other => {
653            let dotted = other.split('.').count() >= 2
654                && other
655                    .split('.')
656                    .all(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_digit()));
657            return dotted.then(|| other.to_string());
658        }
659    };
660    Some(oid.to_string())
661}
662
663/// Parse an RFC 4514 distinguished-name string (`CN=Alice,O=Corp`, most specific RDN first,
664/// `\,` `\+` `\"` `\\` `\<` `\>` `\;` `\=` `\ ` `\#` and `\XX` hex escapes, `+` joins attributes
665/// of one RDN) into structure, returned in certificate (DER) order. Anything it cannot parse
666/// exactly is an error; there is no lenient mode.
667fn parse_rfc4514(dn: &str) -> std::result::Result<RdnList, String> {
668    let shown: String = dn.chars().take(80).collect();
669    let suffix = if dn.chars().count() > 80 {
670        format!("... ({} chars)", dn.chars().count())
671    } else {
672        String::new()
673    };
674    let bad = |why: &str| format!("Invalid distinguished name '{shown}{suffix}': {why}");
675    if dn.trim().is_empty() {
676        return Err(bad("empty"));
677    }
678    let chars: Vec<char> = dn.chars().collect();
679    let mut i = 0;
680    let mut rdns: RdnList = Vec::new();
681    let mut rdn: Vec<(String, String)> = Vec::new();
682
683    loop {
684        while i < chars.len() && chars[i] == ' ' {
685            i += 1;
686        }
687        let start = i;
688        while i < chars.len() && chars[i] != '=' {
689            if matches!(chars[i], ',' | '+' | '\\' | '"') {
690                return Err(bad("attribute type expected before '='"));
691            }
692            i += 1;
693        }
694        if i >= chars.len() {
695            return Err(bad("missing '='"));
696        }
697        let keyword: String = chars[start..i].iter().collect();
698        let oid = attribute_oid(&keyword)
699            .ok_or_else(|| bad(&format!("unknown attribute type '{}'", keyword.trim())))?;
700        i += 1; // '='
701
702        let mut value: Vec<u8> = Vec::new();
703        let mut leading = true;
704        let mut trailing_spaces = 0usize;
705        while i < chars.len() {
706            match chars[i] {
707                ',' | '+' => break,
708                '"' | '<' | '>' | ';' => return Err(bad("unescaped special character in value")),
709                '\\' => {
710                    i += 1;
711                    let next = *chars.get(i).ok_or_else(|| bad("dangling backslash"))?;
712                    if next.is_ascii_hexdigit() {
713                        let second = *chars.get(i + 1).ok_or_else(|| bad("bad hex escape"))?;
714                        if !second.is_ascii_hexdigit() {
715                            return Err(bad("bad hex escape"));
716                        }
717                        let byte = u8::from_str_radix(&format!("{next}{second}"), 16)
718                            .map_err(|_| bad("bad hex escape"))?;
719                        value.push(byte);
720                        i += 2;
721                    } else if matches!(
722                        next,
723                        ',' | '+' | '"' | '\\' | '<' | '>' | ';' | '=' | ' ' | '#'
724                    ) {
725                        let mut buf = [0u8; 4];
726                        value.extend_from_slice(next.encode_utf8(&mut buf).as_bytes());
727                        i += 1;
728                    } else {
729                        return Err(bad("invalid escape"));
730                    }
731                    leading = false;
732                    trailing_spaces = 0;
733                }
734                ' ' if leading => {
735                    return Err(bad(
736                        "unescaped leading space in a value; escape edge spaces as '\\ '",
737                    ));
738                }
739                ' ' => {
740                    value.push(b' ');
741                    trailing_spaces += 1;
742                    i += 1;
743                }
744                '#' if leading => return Err(bad("hex-string values are not supported")),
745                c => {
746                    let mut buf = [0u8; 4];
747                    value.extend_from_slice(c.encode_utf8(&mut buf).as_bytes());
748                    leading = false;
749                    trailing_spaces = 0;
750                    i += 1;
751                }
752            }
753        }
754        if trailing_spaces > 0 {
755            return Err(bad(
756                "unescaped trailing space in a value; escape edge spaces as '\\ '",
757            ));
758        }
759        let value = String::from_utf8(value).map_err(|_| bad("value is not valid UTF-8"))?;
760        if value.is_empty() {
761            return Err(bad("empty attribute value"));
762        }
763        rdn.push((oid, value));
764
765        if i < chars.len() && chars[i] == '+' {
766            i += 1;
767            continue;
768        }
769        rdn.sort();
770        rdns.push(std::mem::take(&mut rdn));
771        if i >= chars.len() {
772            break;
773        }
774        i += 1; // ','
775    }
776    rdns.reverse(); // RFC 4514 lists the most specific RDN first; certificates store it last
777    Ok(rdns)
778}
779
780/// The subject of a certificate as structure (see [`RdnList`]). An attribute whose value
781/// x509-parser cannot read as a string (BMPString, T61String, binary values) makes the subject
782/// unmatchable: it is refused (fail closed), never skipped or guessed at.
783fn subject_rdns(cert: &X509Certificate<'_>) -> std::result::Result<RdnList, String> {
784    cert.subject()
785        .iter_rdn()
786        .map(|rdn| {
787            let mut attrs = rdn
788                .iter()
789                .map(|attr| {
790                    attr.as_str()
791                        .map(|v| (attr.attr_type().to_id_string(), v.to_string()))
792                        .map_err(|_| "Certificate subject has a non-string attribute".to_string())
793                })
794                .collect::<std::result::Result<Vec<_>, _>>()?;
795            attrs.sort();
796            Ok(attrs)
797        })
798        .collect()
799}
800
801/// Does the certificate subject equal the RFC 4514 string `expected`? Compared as structure:
802/// the same RDNs in the same order, attribute types by OID, attribute values EXACTLY (case-
803/// and whitespace-sensitive), so one CN containing ", O=Corp" never equals the two attributes
804/// CN and O. Rendering the subject to text and comparing text would conflate those.
805fn subject_matches(
806    cert: &X509Certificate<'_>,
807    expected: &str,
808) -> std::result::Result<bool, String> {
809    Ok(subject_rdns(cert)? == parse_rfc4514(expected)?)
810}
811
812/// A certificate that chains to a trusted CA only proves the CA issued it; this ties it to the
813/// registered client: exact pin if `client_certificate` is set, else the exact subject DN
814/// (compared as structure, see [`subject_matches`]).
815fn check_identity_binding(
816    cert: &X509Certificate<'_>,
817    cert_der: &[u8],
818    client_config: &MutualTlsClientConfig,
819) -> std::result::Result<(), String> {
820    if let Some(pinned) = &client_config.client_certificate {
821        return if pinned.as_slice() == cert_der {
822            Ok(())
823        } else {
824            Err("Client certificate does not match the registered certificate".to_string())
825        };
826    }
827    if let Some(expected) = &client_config.expected_subject_dn {
828        return if subject_matches(cert, expected)? {
829            Ok(())
830        } else {
831            Err(format!(
832                "Certificate subject does not match the registered subject: {expected}"
833            ))
834        };
835    }
836    Err(
837        "Client has no certificate binding configured (client_certificate or expected_subject_dn)"
838            .to_string(),
839    )
840}
841
842impl Default for MutualTlsManager {
843    fn default() -> Self {
844        Self::new()
845    }
846}
847
848#[cfg(test)]
849mod tests {
850    use super::*;
851
852    fn create_test_client_config() -> MutualTlsClientConfig {
853        MutualTlsClientConfig {
854            client_id: "test_client".to_string(),
855            auth_method: MutualTlsMethod::SelfSignedTlsClientAuth,
856            ca_certificates: Vec::new(),
857            client_certificate: Some(b"dummy_cert".to_vec()), // Would be real cert in practice
858            expected_subject_dn: Some("CN=test_client".to_string()),
859            certificate_bound_access_tokens: true,
860        }
861    }
862
863    #[tokio::test]
864    async fn test_mtls_manager_creation() {
865        let manager = MutualTlsManager::new();
866        assert!(manager.ca_store.is_empty());
867    }
868
869    #[tokio::test]
870    async fn test_client_registration() {
871        let manager = MutualTlsManager::new();
872        let config = create_test_client_config();
873        manager.register_client(config).await.unwrap();
874    }
875
876    #[test]
877    fn test_certificate_confirmation() {
878        let manager = MutualTlsManager::new();
879
880        // Test with dummy certificate data
881        let cert_data = b"dummy_certificate_data";
882        let confirmation = manager.create_certificate_confirmation(cert_data).unwrap();
883
884        assert!(!confirmation.x5t_s256.is_empty());
885
886        // Validate the same certificate
887        let is_valid = manager
888            .validate_certificate_bound_token(&confirmation, cert_data)
889            .unwrap();
890        assert!(is_valid);
891
892        // Validate different certificate (should fail)
893        let different_cert = b"different_certificate_data";
894        let is_valid = manager
895            .validate_certificate_bound_token(&confirmation, different_cert)
896            .unwrap();
897        assert!(!is_valid);
898    }
899
900    // ---- Certificate validation tests built on real rcgen certificate chains ----
901
902    use rcgen::{
903        BasicConstraints, CertificateParams, DistinguishedName, DnType, ExtendedKeyUsagePurpose,
904        IsCa, Issuer, KeyPair, KeyUsagePurpose, PKCS_ECDSA_P256_SHA256, date_time_ymd,
905    };
906
907    type TestIssuer = Issuer<'static, KeyPair>;
908
909    fn dn(cn: &str) -> DistinguishedName {
910        let mut d = DistinguishedName::new();
911        d.push(DnType::CommonName, cn);
912        d
913    }
914
915    fn ca_params(cn: &str, path_len: Option<u8>) -> CertificateParams {
916        let mut p = CertificateParams::new(Vec::<String>::new()).unwrap();
917        p.distinguished_name = dn(cn);
918        p.is_ca = match path_len {
919            Some(n) => IsCa::Ca(BasicConstraints::Constrained(n)),
920            None => IsCa::Ca(BasicConstraints::Unconstrained),
921        };
922        p.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign];
923        p
924    }
925
926    /// A self-signed root: (DER, issuer handle for signing children).
927    fn new_root(cn: &str) -> (Vec<u8>, TestIssuer) {
928        let key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
929        let params = ca_params(cn, None);
930        let cert = params.clone().self_signed(&key).unwrap();
931        (cert.der().to_vec(), Issuer::new(params, key))
932    }
933
934    /// An intermediate CA signed by `parent`: (DER, issuer handle).
935    fn new_intermediate(
936        cn: &str,
937        path_len: Option<u8>,
938        parent: &TestIssuer,
939    ) -> (Vec<u8>, TestIssuer) {
940        let key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
941        let params = ca_params(cn, path_len);
942        let cert = params.clone().signed_by(&key, parent).unwrap();
943        (cert.der().to_vec(), Issuer::new(params, key))
944    }
945
946    fn leaf_params(cn: &str) -> CertificateParams {
947        let mut p = CertificateParams::new(vec![format!("{cn}.example.test")]).unwrap();
948        p.distinguished_name = dn(cn);
949        p.key_usages = vec![KeyUsagePurpose::DigitalSignature];
950        p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth];
951        p
952    }
953
954    fn issue_leaf(cn: &str, issuer: &TestIssuer) -> Vec<u8> {
955        issue_leaf_with(leaf_params(cn), issuer)
956    }
957
958    fn issue_leaf_with(params: CertificateParams, issuer: &TestIssuer) -> Vec<u8> {
959        let key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
960        params.signed_by(&key, issuer).unwrap().der().to_vec()
961    }
962
963    fn pki_client(
964        client_id: &str,
965        subject_dn: Option<&str>,
966        pin: Option<&[u8]>,
967    ) -> MutualTlsClientConfig {
968        MutualTlsClientConfig {
969            client_id: client_id.to_string(),
970            auth_method: MutualTlsMethod::PkiMutualTls,
971            ca_certificates: Vec::new(),
972            client_certificate: pin.map(|p| p.to_vec()),
973            expected_subject_dn: subject_dn.map(str::to_string),
974            certificate_bound_access_tokens: false,
975        }
976    }
977
978    /// A manager that trusts `root_der` and has `client_id` registered bound to `CN=<client_id>`.
979    async fn manager_trusting(root_der: &[u8], client_ids: &[&str]) -> MutualTlsManager {
980        let mut m = MutualTlsManager::new();
981        m.add_ca_certificate(root_der.to_vec()).unwrap();
982        for id in client_ids {
983            m.register_client(pki_client(id, Some(&format!("CN={id}")), None))
984                .await
985                .unwrap();
986        }
987        m
988    }
989
990    async fn accepted(
991        m: &MutualTlsManager,
992        client_id: &str,
993        cert: &[u8],
994        chain: &[Vec<u8>],
995    ) -> bool {
996        let auth = m
997            .authenticate_client_with_chain(client_id, cert, chain)
998            .await
999            .unwrap();
1000        let validated = m
1001            .validate_client_certificate_with_chain(cert, chain, client_id)
1002            .await;
1003        // The two entry points share one validator and must never disagree.
1004        assert_eq!(
1005            auth.is_valid,
1006            validated.is_ok(),
1007            "{:?}",
1008            auth.validation_errors
1009        );
1010        auth.is_valid
1011    }
1012
1013    #[tokio::test]
1014    async fn accepts_a_certificate_issued_by_the_trusted_ca() {
1015        let (root, issuer) = new_root("Trusted Root");
1016        let m = manager_trusting(&root, &["client-a"]).await;
1017        let leaf = issue_leaf("client-a", &issuer);
1018        assert!(accepted(&m, "client-a", &leaf, &[]).await);
1019    }
1020
1021    #[tokio::test]
1022    async fn rejects_a_forged_certificate_with_the_trusted_issuer_dn() {
1023        // A certificate that merely carries the CA's issuer DN, signed by another key, must fail.
1024        let (root, _) = new_root("Trusted Root");
1025        let (_, attacker_ca) = new_root("Trusted Root"); // same DN, different key
1026        let m = manager_trusting(&root, &["client-a"]).await;
1027        let forged = issue_leaf("client-a", &attacker_ca);
1028        assert!(!accepted(&m, "client-a", &forged, &[]).await);
1029    }
1030
1031    #[tokio::test]
1032    async fn rejects_a_self_signed_certificate_for_a_pki_client() {
1033        let (root, _) = new_root("Trusted Root");
1034        let m = manager_trusting(&root, &["client-a"]).await;
1035        let key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
1036        let selfsigned = leaf_params("client-a")
1037            .self_signed(&key)
1038            .unwrap()
1039            .der()
1040            .to_vec();
1041        assert!(!accepted(&m, "client-a", &selfsigned, &[]).await);
1042    }
1043
1044    #[tokio::test]
1045    async fn an_empty_trust_store_never_authenticates() {
1046        // With no trust anchor available nothing may authenticate.
1047        let m = MutualTlsManager::new();
1048        // Registration of a PKI client with no CA anywhere is refused...
1049        assert!(
1050            m.register_client(pki_client("client-a", Some("CN=client-a"), None))
1051                .await
1052                .is_err()
1053        );
1054        // ...and a store that is emptied of anchors cannot validate: a client that carries only
1055        // a per-client CA list validates against that list and nothing else.
1056        let (root, issuer) = new_root("Trusted Root");
1057        let mut cfg = pki_client("client-a", Some("CN=client-a"), None);
1058        cfg.ca_certificates = vec![root.clone()];
1059        m.register_client(cfg).await.unwrap();
1060        let good = issue_leaf("client-a", &issuer);
1061        assert!(accepted(&m, "client-a", &good, &[]).await);
1062        let (_, other_ca) = new_root("Other Root");
1063        let wrong_ca = issue_leaf("client-a", &other_ca);
1064        assert!(!accepted(&m, "client-a", &wrong_ca, &[]).await);
1065    }
1066
1067    #[tokio::test]
1068    async fn rejects_a_certificate_presented_as_a_different_client() {
1069        let (root, issuer) = new_root("Trusted Root");
1070        let m = manager_trusting(&root, &["client-a", "client-b"]).await;
1071        let leaf_a = issue_leaf("client-a", &issuer);
1072        assert!(accepted(&m, "client-a", &leaf_a, &[]).await);
1073        assert!(!accepted(&m, "client-b", &leaf_a, &[]).await);
1074    }
1075
1076    #[tokio::test]
1077    async fn subject_dn_must_match_exactly_not_as_a_substring() {
1078        let (root, issuer) = new_root("Trusted Root");
1079        let m = manager_trusting(&root, &["client-a"]).await;
1080        let evil = issue_leaf("client-a-evil", &issuer);
1081        assert!(!accepted(&m, "client-a", &evil, &[]).await);
1082    }
1083
1084    #[tokio::test]
1085    async fn a_pinned_certificate_must_match_byte_for_byte() {
1086        let (root, issuer) = new_root("Trusted Root");
1087        let pinned = issue_leaf("client-a", &issuer);
1088        let other = issue_leaf("client-a", &issuer); // same subject, different key
1089        let mut m = MutualTlsManager::new();
1090        m.add_ca_certificate(root).unwrap();
1091        m.register_client(pki_client("client-a", None, Some(&pinned)))
1092            .await
1093            .unwrap();
1094        assert!(accepted(&m, "client-a", &pinned, &[]).await);
1095        assert!(!accepted(&m, "client-a", &other, &[]).await);
1096    }
1097
1098    #[tokio::test]
1099    async fn a_pki_client_without_a_binding_cannot_be_registered() {
1100        let (root, _) = new_root("Trusted Root");
1101        let mut m = MutualTlsManager::new();
1102        m.add_ca_certificate(root).unwrap();
1103        assert!(
1104            m.register_client(pki_client("client-a", None, None))
1105                .await
1106                .is_err()
1107        );
1108    }
1109
1110    #[tokio::test]
1111    async fn rejects_a_server_auth_only_certificate() {
1112        let (root, issuer) = new_root("Trusted Root");
1113        let m = manager_trusting(&root, &["client-a"]).await;
1114        let mut p = leaf_params("client-a");
1115        p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth];
1116        let server_only = issue_leaf_with(p, &issuer);
1117        assert!(!accepted(&m, "client-a", &server_only, &[]).await);
1118    }
1119
1120    #[tokio::test]
1121    async fn a_ca_certificate_is_not_accepted_as_a_client_certificate() {
1122        let (root, issuer) = new_root("Trusted Root");
1123        let m = manager_trusting(&root, &["client-a"]).await;
1124        let mut p = ca_params("client-a", None);
1125        p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth];
1126        let ca_as_leaf = issue_leaf_with(p, &issuer);
1127        assert!(!accepted(&m, "client-a", &ca_as_leaf, &[]).await);
1128    }
1129
1130    #[tokio::test]
1131    async fn a_non_ca_leaf_cannot_issue_client_certificates() {
1132        let (root, issuer) = new_root("Trusted Root");
1133        let m = manager_trusting(&root, &["client-x"]).await;
1134        // A legitimate end-entity certificate (CA:false) tries to act as a CA.
1135        let leaf_key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
1136        let leaf_p = leaf_params("not-a-ca");
1137        let leaf_der = leaf_p
1138            .clone()
1139            .signed_by(&leaf_key, &issuer)
1140            .unwrap()
1141            .der()
1142            .to_vec();
1143        let leaf_issuer = Issuer::new(leaf_p, leaf_key);
1144        let x = issue_leaf("client-x", &leaf_issuer);
1145        assert!(!accepted(&m, "client-x", &x, &[]).await);
1146        assert!(!accepted(&m, "client-x", &x, std::slice::from_ref(&leaf_der)).await);
1147    }
1148
1149    #[tokio::test]
1150    async fn rejects_an_expired_ca() {
1151        let key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
1152        let mut params = ca_params("Old Root", None);
1153        params.not_before = date_time_ymd(2019, 1, 1);
1154        params.not_after = date_time_ymd(2021, 1, 1);
1155        let root = params.clone().self_signed(&key).unwrap().der().to_vec();
1156        let issuer = Issuer::new(params, key);
1157        let m = manager_trusting(&root, &["client-a"]).await;
1158        let leaf = issue_leaf("client-a", &issuer); // leaf itself is valid now
1159        assert!(!accepted(&m, "client-a", &leaf, &[]).await);
1160    }
1161
1162    #[tokio::test]
1163    async fn rejects_an_expired_client_certificate() {
1164        let (root, issuer) = new_root("Trusted Root");
1165        let m = manager_trusting(&root, &["client-a"]).await;
1166        let mut p = leaf_params("client-a");
1167        p.not_before = date_time_ymd(2019, 1, 1);
1168        p.not_after = date_time_ymd(2021, 1, 1);
1169        let expired = issue_leaf_with(p, &issuer);
1170        assert!(!accepted(&m, "client-a", &expired, &[]).await);
1171    }
1172
1173    #[tokio::test]
1174    async fn builds_a_chain_through_an_intermediate() {
1175        let (root, root_issuer) = new_root("Trusted Root");
1176        let (inter, inter_issuer) = new_intermediate("Intermediate", None, &root_issuer);
1177        let m = manager_trusting(&root, &["client-a"]).await;
1178        let leaf = issue_leaf("client-a", &inter_issuer);
1179        // Without the intermediate the path cannot be built.
1180        assert!(!accepted(&m, "client-a", &leaf, &[]).await);
1181        assert!(accepted(&m, "client-a", &leaf, std::slice::from_ref(&inter)).await);
1182    }
1183
1184    #[tokio::test]
1185    async fn enforces_the_path_length_constraint() {
1186        let (root, root_issuer) = new_root("Trusted Root");
1187        // pathLen 0: this intermediate may only issue end-entity certificates.
1188        let (inter1, inter1_issuer) = new_intermediate("Intermediate 1", Some(0), &root_issuer);
1189        let (inter2, inter2_issuer) = new_intermediate("Intermediate 2", None, &inter1_issuer);
1190        let m = manager_trusting(&root, &["client-a"]).await;
1191        let leaf = issue_leaf("client-a", &inter2_issuer);
1192        assert!(!accepted(&m, "client-a", &leaf, &[inter1, inter2]).await);
1193    }
1194
1195    #[tokio::test]
1196    async fn rejects_malformed_and_trailing_data() {
1197        let (root, issuer) = new_root("Trusted Root");
1198        let m = manager_trusting(&root, &["client-a"]).await;
1199        let leaf = issue_leaf("client-a", &issuer);
1200        assert!(
1201            m.authenticate_client("client-a", b"not a certificate")
1202                .await
1203                .is_err()
1204        );
1205        let mut padded = leaf.clone();
1206        padded.extend_from_slice(b"\x00\x00");
1207        assert!(m.authenticate_client("client-a", &padded).await.is_err());
1208        assert!(
1209            m.authenticate_client("unknown-client", &leaf)
1210                .await
1211                .is_err()
1212        );
1213    }
1214
1215    #[tokio::test]
1216    async fn only_ca_certificates_are_accepted_as_trust_anchors() {
1217        let (root, issuer) = new_root("Trusted Root");
1218        let leaf = issue_leaf("client-a", &issuer);
1219        let mut m = MutualTlsManager::new();
1220        assert!(m.add_ca_certificate(leaf.clone()).is_err());
1221        assert!(m.add_ca_certificate(root).is_ok());
1222        let mut cfg = pki_client("client-a", Some("CN=client-a"), None);
1223        cfg.ca_certificates = vec![leaf];
1224        assert!(m.register_client(cfg).await.is_err());
1225    }
1226
1227    #[tokio::test]
1228    async fn self_signed_client_auth_matches_the_registered_key() {
1229        let key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
1230        let cert = leaf_params("sc").self_signed(&key).unwrap().der().to_vec();
1231        let other_key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
1232        let other = leaf_params("sc")
1233            .self_signed(&other_key)
1234            .unwrap()
1235            .der()
1236            .to_vec();
1237
1238        let m = MutualTlsManager::new();
1239        m.register_client(MutualTlsClientConfig {
1240            client_id: "sc".to_string(),
1241            auth_method: MutualTlsMethod::SelfSignedTlsClientAuth,
1242            ca_certificates: Vec::new(),
1243            client_certificate: Some(cert.clone()),
1244            expected_subject_dn: Some("CN=sc".to_string()),
1245            certificate_bound_access_tokens: false,
1246        })
1247        .await
1248        .unwrap();
1249        assert!(accepted(&m, "sc", &cert, &[]).await);
1250        assert!(!accepted(&m, "sc", &other, &[]).await);
1251    }
1252
1253    // ---- distinguished-name binding is structural ----
1254
1255    /// A leaf whose subject is exactly the given (type, value) RDNs, one attribute per RDN, in
1256    /// certificate order.
1257    fn leaf_with_subject(rdns: &[(DnType, &str)], issuer: &TestIssuer) -> Vec<u8> {
1258        let mut p = leaf_params("unused");
1259        let mut d = DistinguishedName::new();
1260        for (ty, value) in rdns {
1261            d.push(ty.clone(), *value);
1262        }
1263        p.distinguished_name = d;
1264        issue_leaf_with(p, issuer)
1265    }
1266
1267    #[tokio::test]
1268    async fn one_cn_containing_a_comma_is_not_two_attributes() {
1269        // CN="Alice, O=Corp" (ONE attribute) renders like CN=Alice + O=Corp (TWO) as text, but
1270        // they are different subjects and must not be interchangeable.
1271        let (root, issuer) = new_root("Trusted Root");
1272        let single = leaf_with_subject(&[(DnType::CommonName, "Alice, O=Corp")], &issuer);
1273        let two = leaf_with_subject(
1274            &[
1275                (DnType::OrganizationName, "Corp"),
1276                (DnType::CommonName, "Alice"),
1277            ],
1278            &issuer,
1279        );
1280
1281        let mut m = MutualTlsManager::new();
1282        m.add_ca_certificate(root).unwrap();
1283        // Registered for the two-attribute subject (RFC 4514: most specific RDN first).
1284        m.register_client(pki_client("a", Some("CN=Alice,O=Corp"), None))
1285            .await
1286            .unwrap();
1287        assert!(accepted(&m, "a", &two, &[]).await);
1288        assert!(!accepted(&m, "a", &single, &[]).await);
1289
1290        // Registered for the single-attribute subject (the comma escaped).
1291        m.register_client(pki_client("b", Some(r"CN=Alice\, O=Corp"), None))
1292            .await
1293            .unwrap();
1294        assert!(accepted(&m, "b", &single, &[]).await);
1295        assert!(!accepted(&m, "b", &two, &[]).await);
1296    }
1297
1298    #[tokio::test]
1299    async fn the_self_signed_path_compares_the_subject_as_structure_too() {
1300        let single = {
1301            let key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
1302            let mut p = leaf_params("x");
1303            let mut d = DistinguishedName::new();
1304            d.push(DnType::CommonName, "Alice, O=Corp");
1305            p.distinguished_name = d;
1306            p.self_signed(&key).unwrap().der().to_vec()
1307        };
1308        let m = MutualTlsManager::new();
1309        m.register_client(MutualTlsClientConfig {
1310            client_id: "sc".to_string(),
1311            auth_method: MutualTlsMethod::SelfSignedTlsClientAuth,
1312            ca_certificates: Vec::new(),
1313            client_certificate: Some(single.clone()),
1314            expected_subject_dn: Some("CN=Alice,O=Corp".to_string()), // two attributes
1315            certificate_bound_access_tokens: false,
1316        })
1317        .await
1318        .unwrap();
1319        // Same key as the registered certificate, but the subject is a different structure.
1320        assert!(!accepted(&m, "sc", &single, &[]).await);
1321    }
1322
1323    #[tokio::test]
1324    async fn attribute_values_are_compared_exactly_including_case() {
1325        let (root, issuer) = new_root("Trusted Root");
1326        let leaf = issue_leaf("Client-A", &issuer);
1327        let mut m = MutualTlsManager::new();
1328        m.add_ca_certificate(root).unwrap();
1329        m.register_client(pki_client("exact", Some("CN=Client-A"), None))
1330            .await
1331            .unwrap();
1332        m.register_client(pki_client("lower", Some("CN=client-a"), None))
1333            .await
1334            .unwrap();
1335        // Attribute TYPES are case-insensitive keywords, VALUES are exact.
1336        m.register_client(pki_client("kw", Some("cn=Client-A"), None))
1337            .await
1338            .unwrap();
1339        assert!(accepted(&m, "exact", &leaf, &[]).await);
1340        assert!(accepted(&m, "kw", &leaf, &[]).await);
1341        assert!(!accepted(&m, "lower", &leaf, &[]).await);
1342    }
1343
1344    #[tokio::test]
1345    async fn registration_rejects_empty_or_unparsable_subject_dns() {
1346        let (root, _) = new_root("Trusted Root");
1347        let mut m = MutualTlsManager::new();
1348        m.add_ca_certificate(root).unwrap();
1349        for bad in [
1350            "",
1351            "   ",
1352            "Alice",
1353            "CN=",
1354            "CN=Alice,",
1355            "FOO=Alice",
1356            "CN=Alice;O=Corp",
1357            "CN=\"Alice\"",
1358            "CN=#0403414243",
1359            "CN=Alice\\",
1360            "CN= Alice",
1361            "CN=Alice ",
1362        ] {
1363            assert!(
1364                m.register_client(pki_client("c", Some(bad), None))
1365                    .await
1366                    .is_err(),
1367                "{bad:?} must not register"
1368            );
1369        }
1370        // The same rule applies to self-signed clients.
1371        let key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
1372        let cert = leaf_params("sc").self_signed(&key).unwrap().der().to_vec();
1373        let cfg = MutualTlsClientConfig {
1374            client_id: "sc".to_string(),
1375            auth_method: MutualTlsMethod::SelfSignedTlsClientAuth,
1376            ca_certificates: Vec::new(),
1377            client_certificate: Some(cert),
1378            expected_subject_dn: Some(String::new()),
1379            certificate_bound_access_tokens: false,
1380        };
1381        assert!(m.register_client(cfg).await.is_err());
1382        // An empty pin is as meaningless as an empty DN, and a PKI pin must be a certificate.
1383        assert!(
1384            m.register_client(pki_client("c", None, Some(&[])))
1385                .await
1386                .is_err()
1387        );
1388        assert!(
1389            m.register_client(pki_client("c", None, Some(b"not a certificate")))
1390                .await
1391                .is_err()
1392        );
1393    }
1394
1395    #[test]
1396    fn rfc4514_parsing_covers_escapes_multi_valued_rdns_and_order() {
1397        // Most specific RDN first in the string, last in the certificate.
1398        let parsed = parse_rfc4514("CN=Alice,OU=Eng,O=Corp").unwrap();
1399        let oid = |s: &str| s.to_string();
1400        assert_eq!(
1401            parsed,
1402            vec![
1403                vec![(oid("2.5.4.10"), "Corp".to_string())],
1404                vec![(oid("2.5.4.11"), "Eng".to_string())],
1405                vec![(oid("2.5.4.3"), "Alice".to_string())],
1406            ]
1407        );
1408        // A space after a separator, before the attribute type, is just layout; escaped edge
1409        // spaces belong to the value; interior spaces are kept.
1410        assert_eq!(
1411            parse_rfc4514(r"CN=a\ , O=b c").unwrap(),
1412            vec![
1413                vec![(oid("2.5.4.10"), "b c".to_string())],
1414                vec![(oid("2.5.4.3"), "a ".to_string())],
1415            ]
1416        );
1417        // Unescaped edge spaces in a value are refused, not normalised away.
1418        for bad in [
1419            "CN= Alice",
1420            "CN=Alice ",
1421            "CN=Alice , O=Corp",
1422            "CN =Alice",
1423            "O=Corp,CN= a",
1424        ] {
1425            assert!(parse_rfc4514(bad).is_err(), "{bad:?} must be refused");
1426        }
1427        let long = format!("CN={}", "x ".repeat(100));
1428        let err = parse_rfc4514(&long).unwrap_err();
1429        assert!(err.contains("chars)") && err.len() < 200, "{err}");
1430        // Escapes: special characters and hex pairs (UTF-8 bytes).
1431        assert_eq!(
1432            parse_rfc4514(r"CN=a\,b\+c\\d\3d\C3\A9").unwrap(),
1433            vec![vec![(oid("2.5.4.3"), "a,b+c\\d=é".to_string())]]
1434        );
1435        // '+' joins attributes of ONE RDN, order-insensitively.
1436        assert_eq!(
1437            parse_rfc4514("CN=Alice+O=Corp").unwrap(),
1438            parse_rfc4514("O=Corp+CN=Alice").unwrap()
1439        );
1440        assert_ne!(
1441            parse_rfc4514("CN=Alice+O=Corp").unwrap(),
1442            parse_rfc4514("CN=Alice,O=Corp").unwrap()
1443        );
1444        // Dotted OIDs are accepted.
1445        assert_eq!(
1446            parse_rfc4514("2.5.4.3=Alice").unwrap(),
1447            parse_rfc4514("CN=Alice").unwrap()
1448        );
1449    }
1450
1451    // ---- keyUsage, trust anchors ----
1452
1453    #[tokio::test]
1454    async fn key_usage_without_digital_signature_is_rejected() {
1455        // webpki does not look at keyUsage, so this rule is ours: a client certificate whose
1456        // keyUsage lacks digitalSignature (here keyEncipherment only) must fail even though it
1457        // chains to the CA and carries the clientAuth EKU.
1458        let (root, issuer) = new_root("Trusted Root");
1459        let m = manager_trusting(&root, &["client-a"]).await;
1460        let mut p = leaf_params("client-a");
1461        p.key_usages = vec![KeyUsagePurpose::KeyEncipherment];
1462        p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth];
1463        let cert = issue_leaf_with(p, &issuer);
1464        assert!(!accepted(&m, "client-a", &cert, &[]).await);
1465        // The same certificate with digitalSignature added passes.
1466        let mut ok = leaf_params("client-a");
1467        ok.key_usages = vec![
1468            KeyUsagePurpose::KeyEncipherment,
1469            KeyUsagePurpose::DigitalSignature,
1470        ];
1471        let good = issue_leaf_with(ok, &issuer);
1472        assert!(accepted(&m, "client-a", &good, &[]).await);
1473    }
1474
1475    #[tokio::test]
1476    async fn an_unusable_trust_anchor_is_refused_up_front() {
1477        let (_, issuer) = new_root("Trusted Root");
1478        let leaf = issue_leaf("client-a", &issuer);
1479        let mut m = MutualTlsManager::new();
1480        // Garbage, a non-CA and truncated DER never enter the store.
1481        assert!(m.add_ca_certificate(b"junk".to_vec()).is_err());
1482        assert!(m.add_ca_certificate(leaf).is_err());
1483        let (root, _) = new_root("Other Root");
1484        assert!(
1485            m.add_ca_certificate(root[..root.len() - 4].to_vec())
1486                .is_err()
1487        );
1488    }
1489
1490    #[tokio::test]
1491    async fn rdn_order_is_part_of_the_subject() {
1492        // Same attributes, opposite order: different subjects.
1493        let (root, issuer) = new_root("Trusted Root");
1494        let mut m = MutualTlsManager::new();
1495        m.add_ca_certificate(root).unwrap();
1496        // RFC 4514 string order is most specific first, so this is O=Corp then CN=Alice in the
1497        // certificate.
1498        m.register_client(pki_client("a", Some("CN=Alice,O=Corp"), None))
1499            .await
1500            .unwrap();
1501        let in_order = leaf_with_subject(
1502            &[
1503                (DnType::OrganizationName, "Corp"),
1504                (DnType::CommonName, "Alice"),
1505            ],
1506            &issuer,
1507        );
1508        let swapped = leaf_with_subject(
1509            &[
1510                (DnType::CommonName, "Alice"),
1511                (DnType::OrganizationName, "Corp"),
1512            ],
1513            &issuer,
1514        );
1515        assert!(accepted(&m, "a", &in_order, &[]).await);
1516        assert!(!accepted(&m, "a", &swapped, &[]).await);
1517    }
1518
1519    #[tokio::test]
1520    async fn a_malformed_key_usage_extension_never_passes() {
1521        let (root, issuer) = new_root("Trusted Root");
1522        let m = manager_trusting(&root, &["client-a"]).await;
1523        let mut p = leaf_params("client-a");
1524        p.key_usages = Vec::new();
1525        // keyUsage (2.5.29.15) whose value is an OCTET STRING instead of a BIT STRING.
1526        p.custom_extensions
1527            .push(rcgen::CustomExtension::from_oid_content(
1528                &[2, 5, 29, 15],
1529                vec![0x04, 0x01, 0xFF],
1530            ));
1531        let cert = issue_leaf_with(p, &issuer);
1532        assert!(!accepted(&m, "client-a", &cert, &[]).await);
1533    }
1534
1535    #[tokio::test]
1536    async fn edge_spaces_in_a_common_name_are_not_normalised_away() {
1537        let (root, issuer) = new_root("Trusted Root");
1538        let plain = issue_leaf("client-a", &issuer);
1539        let spaced = issue_leaf("client-a ", &issuer);
1540
1541        let mut m = MutualTlsManager::new();
1542        m.add_ca_certificate(root).unwrap();
1543        // "CN=client-a " with an unescaped trailing space cannot be registered at all...
1544        assert!(
1545            m.register_client(pki_client("x", Some("CN=client-a "), None))
1546                .await
1547                .is_err()
1548        );
1549        // ...a registration for the plain name matches only the plain certificate...
1550        m.register_client(pki_client("plain", Some("CN=client-a"), None))
1551            .await
1552            .unwrap();
1553        assert!(accepted(&m, "plain", &plain, &[]).await);
1554        assert!(!accepted(&m, "plain", &spaced, &[]).await);
1555        // ...and the escaped form matches only the spaced one.
1556        m.register_client(pki_client("spaced", Some(r"CN=client-a\ "), None))
1557            .await
1558            .unwrap();
1559        assert!(accepted(&m, "spaced", &spaced, &[]).await);
1560        assert!(!accepted(&m, "spaced", &plain, &[]).await);
1561    }
1562}