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, PKCS_RSA_SHA256,
905        date_time_ymd,
906    };
907
908    type TestIssuer = Issuer<'static, KeyPair>;
909
910    fn dn(cn: &str) -> DistinguishedName {
911        let mut d = DistinguishedName::new();
912        d.push(DnType::CommonName, cn);
913        d
914    }
915
916    fn ca_params(cn: &str, path_len: Option<u8>) -> CertificateParams {
917        let mut p = CertificateParams::new(Vec::<String>::new()).unwrap();
918        p.distinguished_name = dn(cn);
919        p.is_ca = match path_len {
920            Some(n) => IsCa::Ca(BasicConstraints::Constrained(n)),
921            None => IsCa::Ca(BasicConstraints::Unconstrained),
922        };
923        p.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign];
924        p
925    }
926
927    /// A self-signed root: (DER, issuer handle for signing children).
928    fn new_root(cn: &str) -> (Vec<u8>, TestIssuer) {
929        let key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
930        let params = ca_params(cn, None);
931        let cert = params.clone().self_signed(&key).unwrap();
932        (cert.der().to_vec(), Issuer::new(params, key))
933    }
934
935    /// An intermediate CA signed by `parent`: (DER, issuer handle).
936    fn new_intermediate(
937        cn: &str,
938        path_len: Option<u8>,
939        parent: &TestIssuer,
940    ) -> (Vec<u8>, TestIssuer) {
941        let key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
942        let params = ca_params(cn, path_len);
943        let cert = params.clone().signed_by(&key, parent).unwrap();
944        (cert.der().to_vec(), Issuer::new(params, key))
945    }
946
947    fn leaf_params(cn: &str) -> CertificateParams {
948        let mut p = CertificateParams::new(vec![format!("{cn}.example.test")]).unwrap();
949        p.distinguished_name = dn(cn);
950        p.key_usages = vec![KeyUsagePurpose::DigitalSignature];
951        p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth];
952        p
953    }
954
955    fn issue_leaf(cn: &str, issuer: &TestIssuer) -> Vec<u8> {
956        issue_leaf_with(leaf_params(cn), issuer)
957    }
958
959    fn issue_leaf_with(params: CertificateParams, issuer: &TestIssuer) -> Vec<u8> {
960        let key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
961        params.signed_by(&key, issuer).unwrap().der().to_vec()
962    }
963
964    fn pki_client(
965        client_id: &str,
966        subject_dn: Option<&str>,
967        pin: Option<&[u8]>,
968    ) -> MutualTlsClientConfig {
969        MutualTlsClientConfig {
970            client_id: client_id.to_string(),
971            auth_method: MutualTlsMethod::PkiMutualTls,
972            ca_certificates: Vec::new(),
973            client_certificate: pin.map(|p| p.to_vec()),
974            expected_subject_dn: subject_dn.map(str::to_string),
975            certificate_bound_access_tokens: false,
976        }
977    }
978
979    /// A manager that trusts `root_der` and has `client_id` registered bound to `CN=<client_id>`.
980    async fn manager_trusting(root_der: &[u8], client_ids: &[&str]) -> MutualTlsManager {
981        let mut m = MutualTlsManager::new();
982        m.add_ca_certificate(root_der.to_vec()).unwrap();
983        for id in client_ids {
984            m.register_client(pki_client(id, Some(&format!("CN={id}")), None))
985                .await
986                .unwrap();
987        }
988        m
989    }
990
991    async fn accepted(
992        m: &MutualTlsManager,
993        client_id: &str,
994        cert: &[u8],
995        chain: &[Vec<u8>],
996    ) -> bool {
997        let auth = m
998            .authenticate_client_with_chain(client_id, cert, chain)
999            .await
1000            .unwrap();
1001        let validated = m
1002            .validate_client_certificate_with_chain(cert, chain, client_id)
1003            .await;
1004        // The two entry points share one validator and must never disagree.
1005        assert_eq!(
1006            auth.is_valid,
1007            validated.is_ok(),
1008            "{:?}",
1009            auth.validation_errors
1010        );
1011        auth.is_valid
1012    }
1013
1014    #[tokio::test]
1015    async fn accepts_a_certificate_issued_by_the_trusted_ca() {
1016        let (root, issuer) = new_root("Trusted Root");
1017        let m = manager_trusting(&root, &["client-a"]).await;
1018        let leaf = issue_leaf("client-a", &issuer);
1019        assert!(accepted(&m, "client-a", &leaf, &[]).await);
1020    }
1021
1022    #[tokio::test]
1023    async fn rejects_a_forged_certificate_with_the_trusted_issuer_dn() {
1024        // A certificate that merely carries the CA's issuer DN, signed by another key, must fail.
1025        let (root, _) = new_root("Trusted Root");
1026        let (_, attacker_ca) = new_root("Trusted Root"); // same DN, different key
1027        let m = manager_trusting(&root, &["client-a"]).await;
1028        let forged = issue_leaf("client-a", &attacker_ca);
1029        assert!(!accepted(&m, "client-a", &forged, &[]).await);
1030    }
1031
1032    #[tokio::test]
1033    async fn rejects_a_self_signed_certificate_for_a_pki_client() {
1034        let (root, _) = new_root("Trusted Root");
1035        let m = manager_trusting(&root, &["client-a"]).await;
1036        let key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
1037        let selfsigned = leaf_params("client-a")
1038            .self_signed(&key)
1039            .unwrap()
1040            .der()
1041            .to_vec();
1042        assert!(!accepted(&m, "client-a", &selfsigned, &[]).await);
1043    }
1044
1045    #[tokio::test]
1046    async fn an_empty_trust_store_never_authenticates() {
1047        // With no trust anchor available nothing may authenticate.
1048        let m = MutualTlsManager::new();
1049        // Registration of a PKI client with no CA anywhere is refused...
1050        assert!(
1051            m.register_client(pki_client("client-a", Some("CN=client-a"), None))
1052                .await
1053                .is_err()
1054        );
1055        // ...and a store that is emptied of anchors cannot validate: a client that carries only
1056        // a per-client CA list validates against that list and nothing else.
1057        let (root, issuer) = new_root("Trusted Root");
1058        let mut cfg = pki_client("client-a", Some("CN=client-a"), None);
1059        cfg.ca_certificates = vec![root.clone()];
1060        m.register_client(cfg).await.unwrap();
1061        let good = issue_leaf("client-a", &issuer);
1062        assert!(accepted(&m, "client-a", &good, &[]).await);
1063        let (_, other_ca) = new_root("Other Root");
1064        let wrong_ca = issue_leaf("client-a", &other_ca);
1065        assert!(!accepted(&m, "client-a", &wrong_ca, &[]).await);
1066    }
1067
1068    #[tokio::test]
1069    async fn rejects_a_certificate_presented_as_a_different_client() {
1070        let (root, issuer) = new_root("Trusted Root");
1071        let m = manager_trusting(&root, &["client-a", "client-b"]).await;
1072        let leaf_a = issue_leaf("client-a", &issuer);
1073        assert!(accepted(&m, "client-a", &leaf_a, &[]).await);
1074        assert!(!accepted(&m, "client-b", &leaf_a, &[]).await);
1075    }
1076
1077    #[tokio::test]
1078    async fn subject_dn_must_match_exactly_not_as_a_substring() {
1079        let (root, issuer) = new_root("Trusted Root");
1080        let m = manager_trusting(&root, &["client-a"]).await;
1081        let evil = issue_leaf("client-a-evil", &issuer);
1082        assert!(!accepted(&m, "client-a", &evil, &[]).await);
1083    }
1084
1085    #[tokio::test]
1086    async fn a_pinned_certificate_must_match_byte_for_byte() {
1087        let (root, issuer) = new_root("Trusted Root");
1088        let pinned = issue_leaf("client-a", &issuer);
1089        let other = issue_leaf("client-a", &issuer); // same subject, different key
1090        let mut m = MutualTlsManager::new();
1091        m.add_ca_certificate(root).unwrap();
1092        m.register_client(pki_client("client-a", None, Some(&pinned)))
1093            .await
1094            .unwrap();
1095        assert!(accepted(&m, "client-a", &pinned, &[]).await);
1096        assert!(!accepted(&m, "client-a", &other, &[]).await);
1097    }
1098
1099    #[tokio::test]
1100    async fn a_pki_client_without_a_binding_cannot_be_registered() {
1101        let (root, _) = new_root("Trusted Root");
1102        let mut m = MutualTlsManager::new();
1103        m.add_ca_certificate(root).unwrap();
1104        assert!(
1105            m.register_client(pki_client("client-a", None, None))
1106                .await
1107                .is_err()
1108        );
1109    }
1110
1111    #[tokio::test]
1112    async fn rejects_a_server_auth_only_certificate() {
1113        let (root, issuer) = new_root("Trusted Root");
1114        let m = manager_trusting(&root, &["client-a"]).await;
1115        let mut p = leaf_params("client-a");
1116        p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth];
1117        let server_only = issue_leaf_with(p, &issuer);
1118        assert!(!accepted(&m, "client-a", &server_only, &[]).await);
1119    }
1120
1121    #[tokio::test]
1122    async fn a_ca_certificate_is_not_accepted_as_a_client_certificate() {
1123        let (root, issuer) = new_root("Trusted Root");
1124        let m = manager_trusting(&root, &["client-a"]).await;
1125        let mut p = ca_params("client-a", None);
1126        p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth];
1127        let ca_as_leaf = issue_leaf_with(p, &issuer);
1128        assert!(!accepted(&m, "client-a", &ca_as_leaf, &[]).await);
1129    }
1130
1131    #[tokio::test]
1132    async fn a_non_ca_leaf_cannot_issue_client_certificates() {
1133        let (root, issuer) = new_root("Trusted Root");
1134        let m = manager_trusting(&root, &["client-x"]).await;
1135        // A legitimate end-entity certificate (CA:false) tries to act as a CA.
1136        let leaf_key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
1137        let leaf_p = leaf_params("not-a-ca");
1138        let leaf_der = leaf_p
1139            .clone()
1140            .signed_by(&leaf_key, &issuer)
1141            .unwrap()
1142            .der()
1143            .to_vec();
1144        let leaf_issuer = Issuer::new(leaf_p, leaf_key);
1145        let x = issue_leaf("client-x", &leaf_issuer);
1146        assert!(!accepted(&m, "client-x", &x, &[]).await);
1147        assert!(!accepted(&m, "client-x", &x, std::slice::from_ref(&leaf_der)).await);
1148    }
1149
1150    #[tokio::test]
1151    async fn rejects_an_expired_ca() {
1152        let key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
1153        let mut params = ca_params("Old Root", None);
1154        params.not_before = date_time_ymd(2019, 1, 1);
1155        params.not_after = date_time_ymd(2021, 1, 1);
1156        let root = params.clone().self_signed(&key).unwrap().der().to_vec();
1157        let issuer = Issuer::new(params, key);
1158        let m = manager_trusting(&root, &["client-a"]).await;
1159        let leaf = issue_leaf("client-a", &issuer); // leaf itself is valid now
1160        assert!(!accepted(&m, "client-a", &leaf, &[]).await);
1161    }
1162
1163    #[tokio::test]
1164    async fn rejects_an_expired_client_certificate() {
1165        let (root, issuer) = new_root("Trusted Root");
1166        let m = manager_trusting(&root, &["client-a"]).await;
1167        let mut p = leaf_params("client-a");
1168        p.not_before = date_time_ymd(2019, 1, 1);
1169        p.not_after = date_time_ymd(2021, 1, 1);
1170        let expired = issue_leaf_with(p, &issuer);
1171        assert!(!accepted(&m, "client-a", &expired, &[]).await);
1172    }
1173
1174    #[tokio::test]
1175    async fn builds_a_chain_through_an_intermediate() {
1176        let (root, root_issuer) = new_root("Trusted Root");
1177        let (inter, inter_issuer) = new_intermediate("Intermediate", None, &root_issuer);
1178        let m = manager_trusting(&root, &["client-a"]).await;
1179        let leaf = issue_leaf("client-a", &inter_issuer);
1180        // Without the intermediate the path cannot be built.
1181        assert!(!accepted(&m, "client-a", &leaf, &[]).await);
1182        assert!(accepted(&m, "client-a", &leaf, std::slice::from_ref(&inter)).await);
1183    }
1184
1185    #[tokio::test]
1186    async fn enforces_the_path_length_constraint() {
1187        let (root, root_issuer) = new_root("Trusted Root");
1188        // pathLen 0: this intermediate may only issue end-entity certificates.
1189        let (inter1, inter1_issuer) = new_intermediate("Intermediate 1", Some(0), &root_issuer);
1190        let (inter2, inter2_issuer) = new_intermediate("Intermediate 2", None, &inter1_issuer);
1191        let m = manager_trusting(&root, &["client-a"]).await;
1192        let leaf = issue_leaf("client-a", &inter2_issuer);
1193        assert!(!accepted(&m, "client-a", &leaf, &[inter1, inter2]).await);
1194    }
1195
1196    #[tokio::test]
1197    async fn accepts_rsa_signed_chains() {
1198        let key = KeyPair::generate_for(&PKCS_RSA_SHA256).unwrap();
1199        let params = ca_params("RSA Root", None);
1200        let root = params.clone().self_signed(&key).unwrap().der().to_vec();
1201        let issuer = Issuer::new(params, key);
1202        let m = manager_trusting(&root, &["client-a"]).await;
1203        let leaf_key = KeyPair::generate_for(&PKCS_RSA_SHA256).unwrap();
1204        let leaf = leaf_params("client-a")
1205            .signed_by(&leaf_key, &issuer)
1206            .unwrap()
1207            .der()
1208            .to_vec();
1209        assert!(accepted(&m, "client-a", &leaf, &[]).await);
1210    }
1211
1212    #[tokio::test]
1213    async fn rejects_malformed_and_trailing_data() {
1214        let (root, issuer) = new_root("Trusted Root");
1215        let m = manager_trusting(&root, &["client-a"]).await;
1216        let leaf = issue_leaf("client-a", &issuer);
1217        assert!(
1218            m.authenticate_client("client-a", b"not a certificate")
1219                .await
1220                .is_err()
1221        );
1222        let mut padded = leaf.clone();
1223        padded.extend_from_slice(b"\x00\x00");
1224        assert!(m.authenticate_client("client-a", &padded).await.is_err());
1225        assert!(
1226            m.authenticate_client("unknown-client", &leaf)
1227                .await
1228                .is_err()
1229        );
1230    }
1231
1232    #[tokio::test]
1233    async fn only_ca_certificates_are_accepted_as_trust_anchors() {
1234        let (root, issuer) = new_root("Trusted Root");
1235        let leaf = issue_leaf("client-a", &issuer);
1236        let mut m = MutualTlsManager::new();
1237        assert!(m.add_ca_certificate(leaf.clone()).is_err());
1238        assert!(m.add_ca_certificate(root).is_ok());
1239        let mut cfg = pki_client("client-a", Some("CN=client-a"), None);
1240        cfg.ca_certificates = vec![leaf];
1241        assert!(m.register_client(cfg).await.is_err());
1242    }
1243
1244    #[tokio::test]
1245    async fn self_signed_client_auth_matches_the_registered_key() {
1246        let key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
1247        let cert = leaf_params("sc").self_signed(&key).unwrap().der().to_vec();
1248        let other_key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
1249        let other = leaf_params("sc")
1250            .self_signed(&other_key)
1251            .unwrap()
1252            .der()
1253            .to_vec();
1254
1255        let m = MutualTlsManager::new();
1256        m.register_client(MutualTlsClientConfig {
1257            client_id: "sc".to_string(),
1258            auth_method: MutualTlsMethod::SelfSignedTlsClientAuth,
1259            ca_certificates: Vec::new(),
1260            client_certificate: Some(cert.clone()),
1261            expected_subject_dn: Some("CN=sc".to_string()),
1262            certificate_bound_access_tokens: false,
1263        })
1264        .await
1265        .unwrap();
1266        assert!(accepted(&m, "sc", &cert, &[]).await);
1267        assert!(!accepted(&m, "sc", &other, &[]).await);
1268    }
1269
1270    // ---- distinguished-name binding is structural ----
1271
1272    /// A leaf whose subject is exactly the given (type, value) RDNs, one attribute per RDN, in
1273    /// certificate order.
1274    fn leaf_with_subject(rdns: &[(DnType, &str)], issuer: &TestIssuer) -> Vec<u8> {
1275        let mut p = leaf_params("unused");
1276        let mut d = DistinguishedName::new();
1277        for (ty, value) in rdns {
1278            d.push(ty.clone(), *value);
1279        }
1280        p.distinguished_name = d;
1281        issue_leaf_with(p, issuer)
1282    }
1283
1284    #[tokio::test]
1285    async fn one_cn_containing_a_comma_is_not_two_attributes() {
1286        // CN="Alice, O=Corp" (ONE attribute) renders like CN=Alice + O=Corp (TWO) as text, but
1287        // they are different subjects and must not be interchangeable.
1288        let (root, issuer) = new_root("Trusted Root");
1289        let single = leaf_with_subject(&[(DnType::CommonName, "Alice, O=Corp")], &issuer);
1290        let two = leaf_with_subject(
1291            &[
1292                (DnType::OrganizationName, "Corp"),
1293                (DnType::CommonName, "Alice"),
1294            ],
1295            &issuer,
1296        );
1297
1298        let mut m = MutualTlsManager::new();
1299        m.add_ca_certificate(root).unwrap();
1300        // Registered for the two-attribute subject (RFC 4514: most specific RDN first).
1301        m.register_client(pki_client("a", Some("CN=Alice,O=Corp"), None))
1302            .await
1303            .unwrap();
1304        assert!(accepted(&m, "a", &two, &[]).await);
1305        assert!(!accepted(&m, "a", &single, &[]).await);
1306
1307        // Registered for the single-attribute subject (the comma escaped).
1308        m.register_client(pki_client("b", Some(r"CN=Alice\, O=Corp"), None))
1309            .await
1310            .unwrap();
1311        assert!(accepted(&m, "b", &single, &[]).await);
1312        assert!(!accepted(&m, "b", &two, &[]).await);
1313    }
1314
1315    #[tokio::test]
1316    async fn the_self_signed_path_compares_the_subject_as_structure_too() {
1317        let single = {
1318            let key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
1319            let mut p = leaf_params("x");
1320            let mut d = DistinguishedName::new();
1321            d.push(DnType::CommonName, "Alice, O=Corp");
1322            p.distinguished_name = d;
1323            p.self_signed(&key).unwrap().der().to_vec()
1324        };
1325        let m = MutualTlsManager::new();
1326        m.register_client(MutualTlsClientConfig {
1327            client_id: "sc".to_string(),
1328            auth_method: MutualTlsMethod::SelfSignedTlsClientAuth,
1329            ca_certificates: Vec::new(),
1330            client_certificate: Some(single.clone()),
1331            expected_subject_dn: Some("CN=Alice,O=Corp".to_string()), // two attributes
1332            certificate_bound_access_tokens: false,
1333        })
1334        .await
1335        .unwrap();
1336        // Same key as the registered certificate, but the subject is a different structure.
1337        assert!(!accepted(&m, "sc", &single, &[]).await);
1338    }
1339
1340    #[tokio::test]
1341    async fn attribute_values_are_compared_exactly_including_case() {
1342        let (root, issuer) = new_root("Trusted Root");
1343        let leaf = issue_leaf("Client-A", &issuer);
1344        let mut m = MutualTlsManager::new();
1345        m.add_ca_certificate(root).unwrap();
1346        m.register_client(pki_client("exact", Some("CN=Client-A"), None))
1347            .await
1348            .unwrap();
1349        m.register_client(pki_client("lower", Some("CN=client-a"), None))
1350            .await
1351            .unwrap();
1352        // Attribute TYPES are case-insensitive keywords, VALUES are exact.
1353        m.register_client(pki_client("kw", Some("cn=Client-A"), None))
1354            .await
1355            .unwrap();
1356        assert!(accepted(&m, "exact", &leaf, &[]).await);
1357        assert!(accepted(&m, "kw", &leaf, &[]).await);
1358        assert!(!accepted(&m, "lower", &leaf, &[]).await);
1359    }
1360
1361    #[tokio::test]
1362    async fn registration_rejects_empty_or_unparsable_subject_dns() {
1363        let (root, _) = new_root("Trusted Root");
1364        let mut m = MutualTlsManager::new();
1365        m.add_ca_certificate(root).unwrap();
1366        for bad in [
1367            "",
1368            "   ",
1369            "Alice",
1370            "CN=",
1371            "CN=Alice,",
1372            "FOO=Alice",
1373            "CN=Alice;O=Corp",
1374            "CN=\"Alice\"",
1375            "CN=#0403414243",
1376            "CN=Alice\\",
1377            "CN= Alice",
1378            "CN=Alice ",
1379        ] {
1380            assert!(
1381                m.register_client(pki_client("c", Some(bad), None))
1382                    .await
1383                    .is_err(),
1384                "{bad:?} must not register"
1385            );
1386        }
1387        // The same rule applies to self-signed clients.
1388        let key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
1389        let cert = leaf_params("sc").self_signed(&key).unwrap().der().to_vec();
1390        let cfg = MutualTlsClientConfig {
1391            client_id: "sc".to_string(),
1392            auth_method: MutualTlsMethod::SelfSignedTlsClientAuth,
1393            ca_certificates: Vec::new(),
1394            client_certificate: Some(cert),
1395            expected_subject_dn: Some(String::new()),
1396            certificate_bound_access_tokens: false,
1397        };
1398        assert!(m.register_client(cfg).await.is_err());
1399        // An empty pin is as meaningless as an empty DN, and a PKI pin must be a certificate.
1400        assert!(
1401            m.register_client(pki_client("c", None, Some(&[])))
1402                .await
1403                .is_err()
1404        );
1405        assert!(
1406            m.register_client(pki_client("c", None, Some(b"not a certificate")))
1407                .await
1408                .is_err()
1409        );
1410    }
1411
1412    #[test]
1413    fn rfc4514_parsing_covers_escapes_multi_valued_rdns_and_order() {
1414        // Most specific RDN first in the string, last in the certificate.
1415        let parsed = parse_rfc4514("CN=Alice,OU=Eng,O=Corp").unwrap();
1416        let oid = |s: &str| s.to_string();
1417        assert_eq!(
1418            parsed,
1419            vec![
1420                vec![(oid("2.5.4.10"), "Corp".to_string())],
1421                vec![(oid("2.5.4.11"), "Eng".to_string())],
1422                vec![(oid("2.5.4.3"), "Alice".to_string())],
1423            ]
1424        );
1425        // A space after a separator, before the attribute type, is just layout; escaped edge
1426        // spaces belong to the value; interior spaces are kept.
1427        assert_eq!(
1428            parse_rfc4514(r"CN=a\ , O=b c").unwrap(),
1429            vec![
1430                vec![(oid("2.5.4.10"), "b c".to_string())],
1431                vec![(oid("2.5.4.3"), "a ".to_string())],
1432            ]
1433        );
1434        // Unescaped edge spaces in a value are refused, not normalised away.
1435        for bad in [
1436            "CN= Alice",
1437            "CN=Alice ",
1438            "CN=Alice , O=Corp",
1439            "CN =Alice",
1440            "O=Corp,CN= a",
1441        ] {
1442            assert!(parse_rfc4514(bad).is_err(), "{bad:?} must be refused");
1443        }
1444        let long = format!("CN={}", "x ".repeat(100));
1445        let err = parse_rfc4514(&long).unwrap_err();
1446        assert!(err.contains("chars)") && err.len() < 200, "{err}");
1447        // Escapes: special characters and hex pairs (UTF-8 bytes).
1448        assert_eq!(
1449            parse_rfc4514(r"CN=a\,b\+c\\d\3d\C3\A9").unwrap(),
1450            vec![vec![(oid("2.5.4.3"), "a,b+c\\d=é".to_string())]]
1451        );
1452        // '+' joins attributes of ONE RDN, order-insensitively.
1453        assert_eq!(
1454            parse_rfc4514("CN=Alice+O=Corp").unwrap(),
1455            parse_rfc4514("O=Corp+CN=Alice").unwrap()
1456        );
1457        assert_ne!(
1458            parse_rfc4514("CN=Alice+O=Corp").unwrap(),
1459            parse_rfc4514("CN=Alice,O=Corp").unwrap()
1460        );
1461        // Dotted OIDs are accepted.
1462        assert_eq!(
1463            parse_rfc4514("2.5.4.3=Alice").unwrap(),
1464            parse_rfc4514("CN=Alice").unwrap()
1465        );
1466    }
1467
1468    // ---- keyUsage, trust anchors ----
1469
1470    #[tokio::test]
1471    async fn key_usage_without_digital_signature_is_rejected() {
1472        // webpki does not look at keyUsage, so this rule is ours: a client certificate whose
1473        // keyUsage lacks digitalSignature (here keyEncipherment only) must fail even though it
1474        // chains to the CA and carries the clientAuth EKU.
1475        let (root, issuer) = new_root("Trusted Root");
1476        let m = manager_trusting(&root, &["client-a"]).await;
1477        let mut p = leaf_params("client-a");
1478        p.key_usages = vec![KeyUsagePurpose::KeyEncipherment];
1479        p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth];
1480        let cert = issue_leaf_with(p, &issuer);
1481        assert!(!accepted(&m, "client-a", &cert, &[]).await);
1482        // The same certificate with digitalSignature added passes.
1483        let mut ok = leaf_params("client-a");
1484        ok.key_usages = vec![
1485            KeyUsagePurpose::KeyEncipherment,
1486            KeyUsagePurpose::DigitalSignature,
1487        ];
1488        let good = issue_leaf_with(ok, &issuer);
1489        assert!(accepted(&m, "client-a", &good, &[]).await);
1490    }
1491
1492    #[tokio::test]
1493    async fn an_unusable_trust_anchor_is_refused_up_front() {
1494        let (_, issuer) = new_root("Trusted Root");
1495        let leaf = issue_leaf("client-a", &issuer);
1496        let mut m = MutualTlsManager::new();
1497        // Garbage, a non-CA and truncated DER never enter the store.
1498        assert!(m.add_ca_certificate(b"junk".to_vec()).is_err());
1499        assert!(m.add_ca_certificate(leaf).is_err());
1500        let (root, _) = new_root("Other Root");
1501        assert!(
1502            m.add_ca_certificate(root[..root.len() - 4].to_vec())
1503                .is_err()
1504        );
1505    }
1506
1507    #[tokio::test]
1508    async fn rdn_order_is_part_of_the_subject() {
1509        // Same attributes, opposite order: different subjects.
1510        let (root, issuer) = new_root("Trusted Root");
1511        let mut m = MutualTlsManager::new();
1512        m.add_ca_certificate(root).unwrap();
1513        // RFC 4514 string order is most specific first, so this is O=Corp then CN=Alice in the
1514        // certificate.
1515        m.register_client(pki_client("a", Some("CN=Alice,O=Corp"), None))
1516            .await
1517            .unwrap();
1518        let in_order = leaf_with_subject(
1519            &[
1520                (DnType::OrganizationName, "Corp"),
1521                (DnType::CommonName, "Alice"),
1522            ],
1523            &issuer,
1524        );
1525        let swapped = leaf_with_subject(
1526            &[
1527                (DnType::CommonName, "Alice"),
1528                (DnType::OrganizationName, "Corp"),
1529            ],
1530            &issuer,
1531        );
1532        assert!(accepted(&m, "a", &in_order, &[]).await);
1533        assert!(!accepted(&m, "a", &swapped, &[]).await);
1534    }
1535
1536    #[tokio::test]
1537    async fn a_malformed_key_usage_extension_never_passes() {
1538        let (root, issuer) = new_root("Trusted Root");
1539        let m = manager_trusting(&root, &["client-a"]).await;
1540        let mut p = leaf_params("client-a");
1541        p.key_usages = Vec::new();
1542        // keyUsage (2.5.29.15) whose value is an OCTET STRING instead of a BIT STRING.
1543        p.custom_extensions
1544            .push(rcgen::CustomExtension::from_oid_content(
1545                &[2, 5, 29, 15],
1546                vec![0x04, 0x01, 0xFF],
1547            ));
1548        let cert = issue_leaf_with(p, &issuer);
1549        assert!(!accepted(&m, "client-a", &cert, &[]).await);
1550    }
1551
1552    #[tokio::test]
1553    async fn edge_spaces_in_a_common_name_are_not_normalised_away() {
1554        let (root, issuer) = new_root("Trusted Root");
1555        let plain = issue_leaf("client-a", &issuer);
1556        let spaced = issue_leaf("client-a ", &issuer);
1557
1558        let mut m = MutualTlsManager::new();
1559        m.add_ca_certificate(root).unwrap();
1560        // "CN=client-a " with an unescaped trailing space cannot be registered at all...
1561        assert!(
1562            m.register_client(pki_client("x", Some("CN=client-a "), None))
1563                .await
1564                .is_err()
1565        );
1566        // ...a registration for the plain name matches only the plain certificate...
1567        m.register_client(pki_client("plain", Some("CN=client-a"), None))
1568            .await
1569            .unwrap();
1570        assert!(accepted(&m, "plain", &plain, &[]).await);
1571        assert!(!accepted(&m, "plain", &spaced, &[]).await);
1572        // ...and the escaped form matches only the spaced one.
1573        m.register_client(pki_client("spaced", Some(r"CN=client-a\ "), None))
1574            .await
1575            .unwrap();
1576        assert!(accepted(&m, "spaced", &spaced, &[]).await);
1577        assert!(!accepted(&m, "spaced", &plain, &[]).await);
1578    }
1579}