1use 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18pub enum MutualTlsMethod {
19 PkiMutualTls,
21
22 SelfSignedTlsClientAuth,
24}
25
26#[derive(Debug, Clone, Serialize, Deserialize)]
28pub struct X509CertificateInfo {
29 pub thumbprint: String,
31
32 pub subject_dn: String,
34
35 pub issuer_dn: String,
37
38 pub serial_number: String,
40
41 pub not_before: chrono::DateTime<chrono::Utc>,
43 pub not_after: chrono::DateTime<chrono::Utc>,
44
45 pub san_dns: Vec<String>,
47 pub san_uri: Vec<String>,
48 pub san_email: Vec<String>,
49}
50
51#[derive(Debug, Clone, Serialize, Deserialize)]
53pub struct CertificateConfirmation {
54 #[serde(rename = "x5t#S256")]
56 pub x5t_s256: String,
57}
58
59#[derive(Debug, Clone)]
61pub struct MutualTlsClientConfig {
62 pub client_id: String,
64
65 pub auth_method: MutualTlsMethod,
67
68 pub ca_certificates: Vec<Vec<u8>>,
71
72 pub client_certificate: Option<Vec<u8>>,
76
77 pub expected_subject_dn: Option<String>,
81
82 pub certificate_bound_access_tokens: bool,
84}
85
86#[derive(Debug, Clone)]
88pub struct MutualTlsAuthResult {
89 pub client_id: String,
91
92 pub certificate_info: X509CertificateInfo,
94
95 pub is_valid: bool,
97
98 pub validation_errors: Vec<String>,
100}
101
102#[derive(Debug)]
104pub struct MutualTlsManager {
105 clients: tokio::sync::RwLock<HashMap<String, MutualTlsClientConfig>>,
107
108 ca_store: Vec<Vec<u8>>,
110}
111
112impl MutualTlsManager {
113 pub fn new() -> Self {
115 Self {
116 clients: tokio::sync::RwLock::new(HashMap::new()),
117 ca_store: Vec::new(),
118 }
119 }
120
121 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 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 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 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 let cert = parse_single_certificate(client_certificate)
191 .map_err(|_| AuthError::auth_method("mtls", "Invalid client certificate format"))?;
192
193 let cert_info = self.extract_certificate_info(&cert, client_certificate)?;
195
196 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 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 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 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 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 fn extract_certificate_info(
283 &self,
284 cert: &X509Certificate,
285 cert_der: &[u8],
286 ) -> Result<X509CertificateInfo> {
287 let thumbprint = self.calculate_certificate_thumbprint(cert_der)?;
289
290 let subject_dn = cert.subject().to_string();
292 let issuer_dn = cert.issuer().to_string();
293
294 let serial_number = hex::encode(cert.serial.to_bytes_be());
296
297 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 let mut san_dns = Vec::new();
306 let mut san_uri = Vec::new();
307 let mut san_email = Vec::new();
308
309 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 if ip.len() == 4 {
325 let ip_addr = format!("{}.{}.{}.{}", ip[0], ip[1], ip[2], ip[3]);
327 san_dns.push(ip_addr); } else if ip.len() == 16 {
329 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 }
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 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 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 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 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 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 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 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 if let Some(registered_cert_der) = &client_config.client_certificate {
440 if let Ok((_, registered_cert)) = parse_x509_certificate(registered_cert_der) {
441 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 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 fn validate_client_config(&self, config: &MutualTlsClientConfig) -> Result<()> {
468 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
523fn 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
531fn 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 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
560fn 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 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
630type RdnList = Vec<Vec<(String, String)>>;
633
634fn 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
663fn 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; 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; }
776 rdns.reverse(); Ok(rdns)
778}
779
780fn 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
801fn subject_matches(
806 cert: &X509Certificate<'_>,
807 expected: &str,
808) -> std::result::Result<bool, String> {
809 Ok(subject_rdns(cert)? == parse_rfc4514(expected)?)
810}
811
812fn 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()), 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 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 let is_valid = manager
888 .validate_certificate_bound_token(&confirmation, cert_data)
889 .unwrap();
890 assert!(is_valid);
891
892 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 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 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 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 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 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 let (root, _) = new_root("Trusted Root");
1025 let (_, attacker_ca) = new_root("Trusted Root"); 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 let m = MutualTlsManager::new();
1048 assert!(
1050 m.register_client(pki_client("client-a", Some("CN=client-a"), None))
1051 .await
1052 .is_err()
1053 );
1054 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); 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 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); 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 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 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 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 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 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 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()), certificate_bound_access_tokens: false,
1316 })
1317 .await
1318 .unwrap();
1319 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 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 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 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 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 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 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 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 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 assert_eq!(
1446 parse_rfc4514("2.5.4.3=Alice").unwrap(),
1447 parse_rfc4514("CN=Alice").unwrap()
1448 );
1449 }
1450
1451 #[tokio::test]
1454 async fn key_usage_without_digital_signature_is_rejected() {
1455 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 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 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 let (root, issuer) = new_root("Trusted Root");
1494 let mut m = MutualTlsManager::new();
1495 m.add_ca_certificate(root).unwrap();
1496 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 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 assert!(
1545 m.register_client(pki_client("x", Some("CN=client-a "), None))
1546 .await
1547 .is_err()
1548 );
1549 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 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}