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