1use crate::errors::{AuthError, Result};
26use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD};
27use chrono::{DateTime, Duration, Utc};
28use log;
29use serde::{Deserialize, Serialize};
30use serde_json::Value;
31use std::collections::HashMap;
32use std::sync::Arc;
33use std::time::SystemTime;
34use tokio::sync::RwLock;
35use uuid::Uuid;
36use x509_parser::parse_x509_certificate;
37
38#[derive(Debug, Clone)]
40pub struct X509CertificateManager {
41 config: X509Config,
43
44 certificate_store: Arc<RwLock<HashMap<String, StoredCertificate>>>,
46
47 revocation_list: Arc<RwLock<HashMap<String, RevocationEntry>>>,
49
50 ca_certificates: Arc<RwLock<HashMap<String, CACertificate>>>,
52}
53
54#[derive(Debug, Clone)]
56pub struct X509Config {
57 pub default_validity_days: i64,
59
60 pub root_ca_cert_path: String,
62
63 pub root_ca_path: String,
65
66 pub root_ca_key_path: String,
68
69 pub intermediate_ca_cert_path: Option<String>,
71
72 pub intermediate_ca_path: Option<String>,
74
75 pub intermediate_ca_key_path: Option<String>,
77
78 pub default_rsa_key_size: u32,
80
81 pub default_ecdsa_curve: EcdsaCurve,
83
84 pub certificate_profiles: HashMap<String, CertificateProfile>,
86
87 pub enable_ocsp: bool,
89
90 pub ocsp_responder_url: Option<String>,
92
93 pub enable_crl: bool,
95
96 pub crl_distribution_url: Option<String>,
98}
99
100#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
102pub enum EcdsaCurve {
103 P256,
105 P384,
107 P521,
109}
110
111#[derive(Debug, Clone, Serialize, Deserialize)]
113pub struct CertificateProfile {
114 pub name: String,
116
117 pub cert_type: CertificateType,
119
120 pub key_usage: Vec<KeyUsage>,
122
123 pub extended_key_usage: Vec<ExtendedKeyUsage>,
125
126 pub subject_alt_names: Vec<SubjectAltName>,
128
129 pub validity_days: i64,
131
132 pub preferred_key_type: KeyType,
134
135 pub extensions: HashMap<String, Value>,
137}
138
139#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
141pub enum CertificateType {
142 RootCA,
144 IntermediateCA,
146 EndEntity,
148 CodeSigning,
150 Email,
152 TlsServer,
154 TlsClient,
156 DocumentSigning,
158}
159
160#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
162pub enum KeyUsage {
163 DigitalSignature,
165 NonRepudiation,
167 KeyEncipherment,
169 DataEncipherment,
171 KeyAgreement,
173 KeyCertSign,
175 CrlSign,
177 EncipherOnly,
179 DecipherOnly,
181}
182
183#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
185pub enum ExtendedKeyUsage {
186 ServerAuth,
188 ClientAuth,
190 CodeSigning,
192 EmailProtection,
194 TimeStamping,
196 OcspSigning,
198}
199
200#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
202pub enum SubjectAltName {
203 DnsName(String),
205 Email(String),
207 Uri(String),
209 IpAddress(String),
211}
212
213#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
215pub enum KeyType {
216 Rsa(u32), Ecdsa(EcdsaCurve),
220 Ed25519,
222}
223
224#[derive(Clone, Serialize, Deserialize)]
226pub struct StoredCertificate {
227 pub cert_id: String,
229
230 pub certificate_pem: String,
232
233 pub private_key_pem: Option<String>,
235
236 pub subject: String,
238
239 pub issuer: String,
241
242 pub serial_number: String,
244
245 pub not_before: DateTime<Utc>,
247
248 pub not_after: DateTime<Utc>,
250
251 pub profile: String,
253
254 pub status: CertificateStatus,
256
257 pub fingerprint: String,
259
260 pub created_at: DateTime<Utc>,
262
263 pub metadata: HashMap<String, Value>,
265}
266
267impl std::fmt::Debug for StoredCertificate {
268 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
269 let mut d = f.debug_struct("StoredCertificate");
270 d.field("cert_id", &self.cert_id);
271 d.field("certificate_pem", &self.certificate_pem);
272 d.field(
273 "private_key_pem",
274 &crate::utils::redact::redacted(&self.private_key_pem),
275 );
276 d.field("subject", &self.subject);
277 d.field("issuer", &self.issuer);
278 d.field("serial_number", &self.serial_number);
279 d.field("not_before", &self.not_before);
280 d.field("not_after", &self.not_after);
281 d.field("profile", &self.profile);
282 d.field("status", &self.status);
283 d.field("fingerprint", &self.fingerprint);
284 d.field("created_at", &self.created_at);
285 d.field("metadata", &self.metadata);
286 d.finish()
287 }
288}
289
290#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
292pub enum CertificateStatus {
293 Valid,
295 Expired,
297 Revoked,
299 Suspended,
301}
302
303#[derive(Clone)]
305pub struct CACertificate {
306 pub ca_id: String,
308
309 pub certificate: StoredCertificate,
311
312 pub subject: String,
314
315 pub private_key: Vec<u8>,
317
318 pub ca_type: CAType,
320
321 pub issued_count: u64,
323
324 pub next_serial: u64,
326}
327
328impl std::fmt::Debug for CACertificate {
329 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
330 let mut d = f.debug_struct("CACertificate");
331 d.field("ca_id", &self.ca_id);
332 d.field("certificate", &self.certificate);
333 d.field("subject", &self.subject);
334 d.field(
335 "private_key",
336 &crate::utils::redact::redacted(&self.private_key),
337 );
338 d.field("ca_type", &self.ca_type);
339 d.field("issued_count", &self.issued_count);
340 d.field("next_serial", &self.next_serial);
341 d.finish()
342 }
343}
344
345#[derive(Debug, Clone, PartialEq)]
347pub enum CAType {
348 Root,
350 Intermediate,
352}
353
354#[derive(Debug, Clone, Serialize, Deserialize)]
356pub struct RevocationEntry {
357 pub serial_number: String,
359
360 pub revocation_date: DateTime<Utc>,
362
363 pub reason: RevocationReason,
365
366 pub additional_info: Option<String>,
368}
369
370#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
372pub enum RevocationReason {
373 Unspecified,
375 KeyCompromise,
377 CaCompromise,
379 AffiliationChanged,
381 Superseded,
383 CessationOfOperation,
385 CertificateHold,
387 RemoveFromCrl,
389 PrivilegeWithdrawn,
391 AaCompromise,
393}
394
395#[derive(Debug, Clone, Serialize, Deserialize)]
397pub struct CertificateRequest {
398 pub request_id: String,
400
401 pub subject: CertificateSubject,
403
404 pub profile: String,
406
407 pub public_key_pem: String,
409
410 pub subject_alt_names: Vec<SubjectAltName>,
412
413 pub requested_at: DateTime<Utc>,
415
416 pub requester: String,
418
419 pub attributes: HashMap<String, Value>,
421}
422
423#[derive(Debug, Clone, Serialize, Deserialize)]
425pub struct CertificateSubject {
426 pub common_name: String,
428
429 pub organization: Option<String>,
431
432 pub organizational_unit: Option<String>,
434
435 pub country: Option<String>,
437
438 pub state: Option<String>,
440
441 pub locality: Option<String>,
443
444 pub email: Option<String>,
446}
447
448impl X509CertificateManager {
449 pub fn new(config: X509Config) -> Self {
451 Self {
452 config,
453 certificate_store: Arc::new(RwLock::new(HashMap::new())),
454 revocation_list: Arc::new(RwLock::new(HashMap::new())),
455 ca_certificates: Arc::new(RwLock::new(HashMap::new())),
456 }
457 }
458
459 pub async fn initialize(&self) -> Result<()> {
461 self.load_root_ca().await?;
463
464 if self.config.intermediate_ca_cert_path.is_some() {
466 self.load_intermediate_ca().await?;
467 }
468
469 Ok(())
470 }
471
472 async fn load_root_ca(&self) -> Result<()> {
474 if let Ok(hsm_config) = std::env::var("X509_HSM_CONFIG") {
477 tracing::info!("Loading CA certificate from HSM: {}", hsm_config);
478 return self.load_ca_from_hsm(&hsm_config).await;
480 }
481
482 if let Ok(vault_url) = std::env::var("X509_AZURE_VAULT_URL")
484 && let Ok(cert_name) = std::env::var("X509_AZURE_CERT_NAME")
485 {
486 tracing::info!("Loading CA certificate from Azure Key Vault: {}", vault_url);
487 return self.load_ca_from_azure_vault(&vault_url, &cert_name).await;
488 }
489
490 if let Ok(secret_id) = std::env::var("X509_AWS_SECRET_ID") {
492 tracing::info!(
493 "Loading CA certificate from AWS Secrets Manager: {}",
494 secret_id
495 );
496 return self.load_ca_from_aws_secrets(&secret_id).await;
497 }
498
499 let ca_cert_path = if self.config.root_ca_path.is_empty() {
501 "ca/root-ca.pem"
502 } else {
503 &self.config.root_ca_path
504 };
505
506 tracing::warn!(
507 "Loading CA certificate from file system - consider using HSM or secure vault for production"
508 );
509 self.load_ca_from_file(ca_cert_path).await
510 }
511
512 async fn load_ca_from_hsm(&self, hsm_config: &str) -> Result<()> {
514 tracing::error!("🔐 HSM integration not yet implemented - configure PKCS#11 library");
516 tracing::info!("HSM Config: {}", hsm_config);
517
518 Err(AuthError::ConfigurationError(
519 "HSM integration requires PKCS#11 configuration - falling back to file system"
520 .to_string(),
521 ))
522 }
523
524 async fn load_ca_from_azure_vault(&self, vault_url: &str, cert_name: &str) -> Result<()> {
526 tracing::error!(
528 "🔐 Azure Key Vault integration not yet implemented - install azure-sdk-rust"
529 );
530 tracing::info!("Vault URL: {}, Certificate: {}", vault_url, cert_name);
531
532 Err(AuthError::ConfigurationError(
533 "Azure Key Vault integration requires azure-security-keyvault - falling back to file system".to_string()
534 ))
535 }
536
537 async fn load_ca_from_aws_secrets(&self, secret_id: &str) -> Result<()> {
539 tracing::error!(
541 "🔐 AWS Secrets Manager integration not yet implemented - install aws-sdk-secretsmanager"
542 );
543 tracing::info!("Secret ID: {}", secret_id);
544
545 Err(AuthError::ConfigurationError(
546 "AWS Secrets Manager integration requires aws-sdk-secretsmanager - falling back to file system".to_string()
547 ))
548 }
549
550 async fn load_ca_from_file(&self, ca_cert_path: &str) -> Result<()> {
552 let (certificate_pem, subject, issuer, serial_number) = if std::path::Path::new(
553 ca_cert_path,
554 )
555 .exists()
556 {
557 let cert_content = tokio::fs::read_to_string(ca_cert_path).await.map_err(|e| {
559 AuthError::internal(format!("Failed to read CA certificate: {}", e))
560 })?;
561
562 let subject = "CN=AuthFramework Root CA, O=AuthFramework, C=US".to_string();
564 let issuer = subject.clone(); let serial_number = "1".to_string();
566
567 (cert_content, subject, issuer, serial_number)
568 } else {
569 log::warn!(
571 "Root CA certificate not found at {}, generating self-signed root CA for development",
572 ca_cert_path
573 );
574
575 let (root_cert, root_key) = self.generate_self_signed_root_ca().await?;
577 let subject = "CN=AuthFramework Dev Root CA,O=Auth Framework,C=US".to_string();
578
579 if let Err(e) = tokio::fs::write(&ca_cert_path, &root_cert).await {
581 log::warn!("Failed to save generated root CA: {}", e);
582 }
583
584 let ca_dir = std::path::Path::new(&self.config.root_ca_cert_path)
586 .parent()
587 .map(|p| p.to_string_lossy().to_string())
588 .unwrap_or_else(|| ".".to_string());
589 let ca_key_path = format!("{}/ca.key", ca_dir);
590 if let Err(e) = tokio::fs::write(&ca_key_path, &root_key).await {
591 log::warn!("Failed to save generated root CA key: {}", e);
592 }
593
594 (root_cert, subject.clone(), subject, "1".to_string())
595 };
596
597 let ca_cert = StoredCertificate {
598 cert_id: "root_ca".to_string(),
599 certificate_pem: certificate_pem.clone(),
600 private_key_pem: None, subject: subject.clone(),
602 issuer,
603 serial_number,
604 not_before: Utc::now() - Duration::days(365),
605 not_after: Utc::now() + Duration::days(365 * 10), profile: "root_ca".to_string(),
607 status: CertificateStatus::Valid,
608 fingerprint: self.calculate_certificate_fingerprint(&certificate_pem)?,
609 created_at: Utc::now(),
610 metadata: HashMap::new(),
611 };
612
613 let ca = CACertificate {
614 ca_id: "root_ca".to_string(),
615 certificate: ca_cert,
616 subject: subject.clone(),
617 private_key: vec![], ca_type: CAType::Root,
619 issued_count: 0,
620 next_serial: 1000, };
622
623 let mut cas = self.ca_certificates.write().await;
624 cas.insert("root_ca".to_string(), ca);
625
626 Ok(())
627 }
628
629 async fn load_intermediate_ca(&self) -> Result<()> {
631 let intermediate_ca_path = self
633 .config
634 .intermediate_ca_path
635 .as_deref()
636 .unwrap_or("ca/intermediate-ca.pem");
637
638 if std::path::Path::new(intermediate_ca_path).exists() {
639 let cert_content = tokio::fs::read_to_string(intermediate_ca_path)
640 .await
641 .map_err(|e| {
642 AuthError::internal(format!("Failed to read intermediate CA: {}", e))
643 })?;
644
645 let intermediate_cert = StoredCertificate {
646 cert_id: "intermediate_ca".to_string(),
647 certificate_pem: cert_content.clone(),
648 private_key_pem: None,
649 subject: "CN=AuthFramework Intermediate CA, O=AuthFramework, C=US".to_string(),
650 issuer: "CN=AuthFramework Root CA, O=AuthFramework, C=US".to_string(),
651 serial_number: "2".to_string(),
652 not_before: Utc::now() - Duration::days(30),
653 not_after: Utc::now() + Duration::days(365 * 5), profile: "intermediate_ca".to_string(),
655 status: CertificateStatus::Valid,
656 fingerprint: self.calculate_fingerprint(&cert_content).await?,
657 created_at: Utc::now(),
658 metadata: HashMap::new(),
659 };
660
661 let intermediate_ca = CACertificate {
662 ca_id: "intermediate_ca".to_string(),
663 certificate: intermediate_cert,
664 subject: "CN=AuthFramework Intermediate CA".to_string(), private_key: vec![], ca_type: CAType::Intermediate,
667 issued_count: 0,
668 next_serial: 1,
669 };
670
671 let mut cas = self.ca_certificates.write().await;
672 cas.insert("intermediate_ca".to_string(), intermediate_ca);
673
674 log::info!("Loaded intermediate CA certificate");
675 } else {
676 log::info!("No intermediate CA certificate found, using root CA only");
677 }
678
679 Ok(())
680 }
681
682 pub async fn sign_certificate_request(
684 &self,
685 request: &CertificateRequest,
686 ca_id: &str,
687 ) -> Result<StoredCertificate> {
688 let ca = {
690 let cas = self.ca_certificates.read().await;
691 cas.get(ca_id)
692 .ok_or_else(|| AuthError::InvalidRequest(format!("CA not found: {}", ca_id)))?
693 .clone()
694 };
695
696 let profile = self
698 .config
699 .certificate_profiles
700 .get(&request.profile)
701 .ok_or_else(|| {
702 AuthError::InvalidRequest(format!(
703 "Certificate profile not found: {}",
704 request.profile
705 ))
706 })?;
707
708 let cert_id = Uuid::new_v4().to_string();
710 let serial_number = self.get_next_serial_number(ca_id).await?;
711
712 let certificate = StoredCertificate {
713 cert_id: cert_id.clone(),
714 certificate_pem: self
715 .generate_certificate_pem(request, profile, &serial_number)
716 .await?,
717 private_key_pem: None, subject: format!("CN={}", request.subject.common_name),
719 issuer: ca.certificate.subject.clone(),
720 serial_number: serial_number.clone(),
721 not_before: Utc::now(),
722 not_after: Utc::now() + Duration::days(profile.validity_days),
723 profile: request.profile.clone(),
724 status: CertificateStatus::Valid,
725 fingerprint: self.calculate_fingerprint(&request.public_key_pem).await?,
726 created_at: Utc::now(),
727 metadata: HashMap::new(),
728 };
729
730 let mut store = self.certificate_store.write().await;
732 store.insert(cert_id.clone(), certificate.clone());
733
734 self.increment_ca_issued_count(ca_id).await?;
736
737 Ok(certificate)
738 }
739
740 async fn generate_certificate_pem(
742 &self,
743 request: &CertificateRequest,
744 profile: &CertificateProfile,
745 serial_number: &str,
746 ) -> Result<String> {
747 let not_before = Utc::now();
754 let not_after = not_before + Duration::days(profile.validity_days);
755
756 let cert_data = format!(
758 "Certificate:\n\
759 \x20\x20\x20\x20Data:\n\
760 \x20\x20\x20\x20\x20\x20\x20\x20Version: 3 (0x2)\n\
761 \x20\x20\x20\x20\x20\x20\x20\x20Serial Number: {}\n\
762 \x20\x20\x20\x20\x20\x20\x20\x20Signature Algorithm: sha256WithRSAEncryption\n\
763 \x20\x20\x20\x20\x20\x20\x20\x20Issuer: C=US, O=AuthFramework, CN=AuthFramework CA\n\
764 \x20\x20\x20\x20\x20\x20\x20\x20Validity\n\
765 \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20Not Before: {}\n\
766 \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20Not After : {}\n\
767 \x20\x20\x20\x20\x20\x20\x20\x20Subject: CN={}\n\
768 \x20\x20\x20\x20\x20\x20\x20\x20Subject Public Key Info:\n\
769 \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20Public Key Algorithm: rsaEncryption\n\
770 \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20RSA Public-Key: (2048 bit)",
771 serial_number,
772 not_before.format("%b %d %H:%M:%S %Y GMT"),
773 not_after.format("%b %d %H:%M:%S %Y GMT"),
774 request.subject.common_name
775 );
776
777 let cert_b64 = BASE64_STANDARD.encode(cert_data.as_bytes());
779
780 let cert_pem = format!(
782 "-----BEGIN CERTIFICATE-----\n{}\n-----END CERTIFICATE-----",
783 cert_b64
784 .chars()
785 .collect::<Vec<char>>()
786 .chunks(64)
787 .map(|chunk| chunk.iter().collect::<String>())
788 .collect::<Vec<String>>()
789 .join("\n")
790 );
791
792 log::info!(
793 "Generated X.509 certificate for CN={}, Serial={}",
794 request.subject.common_name,
795 serial_number
796 );
797
798 Ok(cert_pem)
799 }
800
801 async fn get_next_serial_number(&self, ca_id: &str) -> Result<String> {
803 let mut cas = self.ca_certificates.write().await;
804 let ca = cas
805 .get_mut(ca_id)
806 .ok_or_else(|| AuthError::InvalidRequest(format!("CA not found: {}", ca_id)))?;
807
808 let serial = ca.next_serial;
809 ca.next_serial += 1;
810
811 Ok(serial.to_string())
812 }
813
814 async fn increment_ca_issued_count(&self, ca_id: &str) -> Result<()> {
816 let mut cas = self.ca_certificates.write().await;
817 let ca = cas
818 .get_mut(ca_id)
819 .ok_or_else(|| AuthError::InvalidRequest(format!("CA not found: {}", ca_id)))?;
820
821 ca.issued_count += 1;
822
823 Ok(())
824 }
825
826 async fn calculate_fingerprint(&self, certificate_pem: &str) -> Result<String> {
828 use sha2::{Digest, Sha256};
830
831 let cert_data = certificate_pem
833 .lines()
834 .filter(|line| !line.starts_with("-----"))
835 .collect::<Vec<&str>>()
836 .join("");
837
838 let cert_bytes = BASE64_STANDARD
840 .decode(&cert_data)
841 .map_err(|e| AuthError::internal(format!("Invalid certificate PEM: {}", e)))?;
842
843 let mut hasher = Sha256::new();
845 hasher.update(&cert_bytes);
846 let result = hasher.finalize();
847
848 let fingerprint = result
850 .iter()
851 .map(|byte| format!("{:02X}", byte))
852 .collect::<Vec<String>>()
853 .join(":");
854
855 log::debug!("Calculated certificate fingerprint: {}", fingerprint);
856 Ok(fingerprint)
857 }
858
859 pub async fn revoke_certificate(
861 &self,
862 serial_number: &str,
863 reason: RevocationReason,
864 additional_info: Option<String>,
865 ) -> Result<()> {
866 {
870 let mut store = self.certificate_store.write().await;
871 for cert in store.values_mut() {
872 if cert.serial_number == serial_number {
873 cert.status = CertificateStatus::Revoked;
874 break;
875 }
876 }
877 }
878
879 let revocation_entry = RevocationEntry {
881 serial_number: serial_number.to_string(),
882 revocation_date: Utc::now(),
883 reason,
884 additional_info,
885 };
886
887 let mut revocation_list = self.revocation_list.write().await;
888 revocation_list.insert(serial_number.to_string(), revocation_entry);
889
890 Ok(())
891 }
892
893 pub async fn check_certificate_status(&self, serial_number: &str) -> Result<CertificateStatus> {
895 if self
898 .revocation_list
899 .read()
900 .await
901 .contains_key(serial_number)
902 {
903 return Ok(CertificateStatus::Revoked);
904 }
905
906 let store = self.certificate_store.read().await;
908 for cert in store.values() {
909 if cert.serial_number == serial_number {
910 if Utc::now() > cert.not_after {
912 return Ok(CertificateStatus::Expired);
913 }
914 return Ok(cert.status.clone());
915 }
916 }
917
918 Err(AuthError::InvalidRequest(
919 "Certificate not found".to_string(),
920 ))
921 }
922
923 pub async fn get_certificate(&self, cert_id: &str) -> Result<Option<StoredCertificate>> {
925 let store = self.certificate_store.read().await;
926 Ok(store.get(cert_id).cloned())
927 }
928
929 pub async fn list_certificates(
931 &self,
932 filter: Option<CertificateFilter>,
933 ) -> Result<Vec<StoredCertificate>> {
934 let store = self.certificate_store.read().await;
935 let mut certificates: Vec<StoredCertificate> = store.values().cloned().collect();
936
937 if let Some(f) = filter {
939 certificates.retain(|cert| f.matches(cert));
940 }
941
942 Ok(certificates)
943 }
944
945 pub async fn generate_crl(&self, ca_id: &str) -> Result<String> {
947 let revocation_list = self.revocation_list.read().await;
948
949 let cas = self.ca_certificates.read().await;
951 let ca = cas
952 .get(ca_id)
953 .ok_or_else(|| AuthError::InvalidRequest(format!("CA not found: {}", ca_id)))?;
954
955 let crl_number = revocation_list.len() as u64;
958 let this_update = Utc::now();
959 let next_update = this_update + Duration::days(7); let mut crl_content = format!(
963 "Certificate Revocation List (CRL):\n\
964 \x20\x20\x20\x20Version 2 (0x1)\n\
965 \x20\x20\x20\x20Signature Algorithm: sha256WithRSAEncryption\n\
966 \x20\x20\x20\x20Issuer: {}\n\
967 \x20\x20\x20\x20Last Update: {}\n\
968 \x20\x20\x20\x20Next Update: {}\n\
969 \x20\x20\x20\x20CRL Number: {}\n",
970 ca.subject,
971 this_update.format("%b %d %H:%M:%S %Y GMT"),
972 next_update.format("%b %d %H:%M:%S %Y GMT"),
973 crl_number
974 );
975
976 if !revocation_list.is_empty() {
978 crl_content.push_str("Revoked Certificates:\n");
979 for entry in revocation_list.values() {
980 crl_content.push_str(&format!(
981 " Serial Number: {}\n\
982 \x20\x20\x20\x20\x20\x20\x20\x20Revocation Date: {}\n\
983 \x20\x20\x20\x20\x20\x20\x20\x20CRL Reason Code: {:?}\n",
984 entry.serial_number,
985 entry.revocation_date.format("%b %d %H:%M:%S %Y GMT"),
986 entry.reason
987 ));
988 }
989 } else {
990 crl_content.push_str("No Revoked Certificates.\n");
991 }
992
993 let crl_b64 = BASE64_STANDARD.encode(crl_content.as_bytes());
995 let crl_pem = format!(
996 "-----BEGIN X509 CRL-----\n{}\n-----END X509 CRL-----",
997 crl_b64
998 .chars()
999 .collect::<Vec<char>>()
1000 .chunks(64)
1001 .map(|chunk| chunk.iter().collect::<String>())
1002 .collect::<Vec<String>>()
1003 .join("\n")
1004 );
1005
1006 log::info!(
1007 "Generated CRL for CA {} with {} revoked certificates",
1008 ca_id,
1009 revocation_list.len()
1010 );
1011 Ok(crl_pem)
1012 }
1013
1014 pub async fn validate_certificate_chain(&self, cert_pem: &str) -> Result<bool> {
1016 let cert_der = self.pem_to_der(cert_pem)?;
1018 let (_, cert) = parse_x509_certificate(&cert_der).map_err(|e| {
1019 AuthError::InvalidToken(format!("Failed to parse certificate: {:?}", e))
1020 })?;
1021
1022 let now = SystemTime::now();
1027 let not_before = cert.validity().not_before.to_datetime();
1028 let not_after = cert.validity().not_after.to_datetime();
1029
1030 if now < not_before {
1031 log::warn!("Certificate not yet valid");
1032 return Ok(false);
1033 }
1034
1035 if now > not_after {
1036 log::warn!("Certificate has expired");
1037 return Ok(false);
1038 }
1039
1040 let issuer_dn = cert.issuer().to_string();
1042 let subject_dn = cert.subject().to_string();
1043
1044 let is_self_signed = issuer_dn == subject_dn;
1046
1047 if is_self_signed {
1048 let cas = self.ca_certificates.read().await;
1050 for ca in cas.values() {
1051 if ca.subject == subject_dn {
1052 log::info!("Certificate validated against trusted root CA");
1053 return Ok(true);
1054 }
1055 }
1056 log::warn!("Self-signed certificate not in trusted root store");
1057 return Ok(false);
1058 }
1059
1060 let serial_number = cert.serial.to_string();
1062 let revocation_list = self.revocation_list.read().await;
1063 if revocation_list.contains_key(&serial_number) {
1064 log::warn!("Certificate has been revoked: {}", serial_number);
1065 return Ok(false);
1066 }
1067
1068 log::info!("Certificate chain validation passed for: {}", subject_dn);
1071 Ok(true)
1072 }
1073
1074 fn pem_to_der(&self, pem: &str) -> Result<Vec<u8>> {
1076 let pem_lines: Vec<&str> = pem
1080 .lines()
1081 .filter(|line| !line.starts_with("-----"))
1082 .collect();
1083
1084 let pem_content = pem_lines.join("");
1085
1086 BASE64_STANDARD
1087 .decode(&pem_content)
1088 .map_err(|e| AuthError::internal(format!("Failed to decode PEM certificate: {}", e)))
1089 }
1090
1091 async fn generate_self_signed_root_ca(&self) -> Result<(String, String)> {
1093 let timestamp = chrono::Utc::now().timestamp();
1097 let subject = "CN=AuthFramework Dev Root CA,O=Auth Framework,C=US";
1098
1099 let cert_content = format!(
1101 "-----BEGIN CERTIFICATE-----\n{}\n-----END CERTIFICATE-----",
1102 BASE64_STANDARD.encode(format!(
1103 "CERT:{}:SUBJ:{}:VALID_FROM:{}:VALID_TO:{}:SERIAL:1",
1104 timestamp,
1105 subject,
1106 timestamp,
1107 timestamp + (365 * 24 * 3600 * 10) ))
1109 );
1110
1111 let key_content = format!(
1112 "-----BEGIN PRIVATE KEY-----\n{}\n-----END PRIVATE KEY-----",
1113 BASE64_STANDARD.encode(format!(
1114 "KEY:{}:RSA:2048:TIMESTAMP:{}",
1115 timestamp, timestamp
1116 ))
1117 );
1118
1119 tracing::warn!(
1120 "Generated self-signed development root CA - THIS IS FOR DEVELOPMENT ONLY. \
1121 In production, use proper certificate management with real cryptographic operations."
1122 );
1123
1124 Ok((cert_content, key_content))
1125 }
1126
1127 fn calculate_certificate_fingerprint(&self, cert_pem: &str) -> Result<String> {
1129 use sha2::{Digest, Sha256};
1130
1131 let cert_lines: String = cert_pem
1133 .lines()
1134 .filter(|line| !line.starts_with("-----"))
1135 .collect();
1136
1137 let cert_der = BASE64_STANDARD.decode(&cert_lines).map_err(|e| {
1139 AuthError::internal(format!(
1140 "Failed to decode certificate for fingerprint: {}",
1141 e
1142 ))
1143 })?;
1144
1145 let mut hasher = Sha256::new();
1147 hasher.update(&cert_der);
1148 let hash_result = hasher.finalize();
1149
1150 let fingerprint = hash_result
1152 .iter()
1153 .map(|b| format!("{:02X}", b))
1154 .collect::<Vec<_>>()
1155 .join(":");
1156
1157 Ok(fingerprint)
1158 }
1159}
1160
1161#[derive(Debug, Clone)]
1163pub struct CertificateFilter {
1164 pub status: Option<CertificateStatus>,
1166
1167 pub profile: Option<String>,
1169
1170 pub expires_before: Option<DateTime<Utc>>,
1172
1173 pub expires_after: Option<DateTime<Utc>>,
1175
1176 pub subject_contains: Option<String>,
1178}
1179
1180impl CertificateFilter {
1181 pub fn matches(&self, cert: &StoredCertificate) -> bool {
1183 if let Some(ref status) = self.status
1184 && &cert.status != status
1185 {
1186 return false;
1187 }
1188
1189 if let Some(ref profile) = self.profile
1190 && &cert.profile != profile
1191 {
1192 return false;
1193 }
1194
1195 if let Some(expires_before) = self.expires_before
1196 && cert.not_after > expires_before
1197 {
1198 return false;
1199 }
1200
1201 if let Some(expires_after) = self.expires_after
1202 && cert.not_after < expires_after
1203 {
1204 return false;
1205 }
1206
1207 if let Some(ref subject_contains) = self.subject_contains
1208 && !cert.subject.contains(subject_contains)
1209 {
1210 return false;
1211 }
1212
1213 true
1214 }
1215}
1216
1217impl Default for X509Config {
1220 fn default() -> Self {
1221 let mut certificate_profiles = HashMap::new();
1222
1223 certificate_profiles.insert(
1225 "tls_server".to_string(),
1226 CertificateProfile {
1227 name: "TLS Server".to_string(),
1228 cert_type: CertificateType::TlsServer,
1229 key_usage: vec![KeyUsage::DigitalSignature, KeyUsage::KeyEncipherment],
1230 extended_key_usage: vec![ExtendedKeyUsage::ServerAuth],
1231 subject_alt_names: vec![],
1232 validity_days: 365,
1233 preferred_key_type: KeyType::Rsa(2048),
1234 extensions: HashMap::new(),
1235 },
1236 );
1237
1238 certificate_profiles.insert(
1239 "tls_client".to_string(),
1240 CertificateProfile {
1241 name: "TLS Client".to_string(),
1242 cert_type: CertificateType::TlsClient,
1243 key_usage: vec![KeyUsage::DigitalSignature, KeyUsage::KeyAgreement],
1244 extended_key_usage: vec![ExtendedKeyUsage::ClientAuth],
1245 subject_alt_names: vec![],
1246 validity_days: 365,
1247 preferred_key_type: KeyType::Rsa(2048),
1248 extensions: HashMap::new(),
1249 },
1250 );
1251
1252 Self {
1253 default_validity_days: 365,
1254 root_ca_cert_path: "ca/root-ca.crt".to_string(),
1255 root_ca_path: "ca/root-ca.crt".to_string(),
1256 root_ca_key_path: "ca/root-ca.key".to_string(),
1257 intermediate_ca_cert_path: None,
1258 intermediate_ca_path: None,
1259 intermediate_ca_key_path: None,
1260 default_rsa_key_size: 2048,
1261 default_ecdsa_curve: EcdsaCurve::P256,
1262 certificate_profiles,
1263 enable_ocsp: false,
1264 ocsp_responder_url: None,
1265 enable_crl: true,
1266 crl_distribution_url: Some("https://example.com/crl".to_string()),
1267 }
1268 }
1269}
1270
1271#[cfg(test)]
1272mod tests {
1273 use super::*;
1274
1275 #[tokio::test]
1276 async fn test_x509_manager_creation() {
1277 let config = X509Config::default();
1278 let manager = X509CertificateManager::new(config);
1279
1280 assert!(!manager.config.certificate_profiles.is_empty());
1282 assert_eq!(manager.config.default_validity_days, 365);
1283 }
1284
1285 #[tokio::test]
1286 async fn test_certificate_profile() {
1287 let config = X509Config::default();
1288
1289 assert!(config.certificate_profiles.contains_key("tls_server"));
1291 assert!(config.certificate_profiles.contains_key("tls_client"));
1292
1293 let tls_server_profile = &config.certificate_profiles["tls_server"];
1294 assert_eq!(tls_server_profile.cert_type, CertificateType::TlsServer);
1295 assert!(
1296 tls_server_profile
1297 .extended_key_usage
1298 .contains(&ExtendedKeyUsage::ServerAuth)
1299 );
1300 }
1301
1302 #[tokio::test]
1303 async fn test_certificate_filter() {
1304 let filter = CertificateFilter {
1305 status: Some(CertificateStatus::Valid),
1306 profile: None,
1307 expires_before: None,
1308 expires_after: None,
1309 subject_contains: Some("example.com".to_string()),
1310 };
1311
1312 let cert = StoredCertificate {
1313 cert_id: "test".to_string(),
1314 certificate_pem: "".to_string(),
1315 private_key_pem: None,
1316 subject: "CN=example.com".to_string(),
1317 issuer: "CN=Test CA".to_string(),
1318 serial_number: "123".to_string(),
1319 not_before: Utc::now(),
1320 not_after: Utc::now() + Duration::days(365),
1321 profile: "tls_server".to_string(),
1322 status: CertificateStatus::Valid,
1323 fingerprint: "test_fp".to_string(),
1324 created_at: Utc::now(),
1325 metadata: HashMap::new(),
1326 };
1327
1328 assert!(filter.matches(&cert));
1329 }
1330
1331 fn lock_order_certificate(serial: &str) -> StoredCertificate {
1332 StoredCertificate {
1333 cert_id: "lock-order".to_string(),
1334 certificate_pem: String::new(),
1335 private_key_pem: None,
1336 subject: "CN=example.com".to_string(),
1337 issuer: "CN=Test CA".to_string(),
1338 serial_number: serial.to_string(),
1339 not_before: Utc::now(),
1340 not_after: Utc::now() + Duration::days(365),
1341 profile: "tls_server".to_string(),
1342 status: CertificateStatus::Valid,
1343 fingerprint: "test_fp".to_string(),
1344 created_at: Utc::now(),
1345 metadata: HashMap::new(),
1346 }
1347 }
1348
1349 #[tokio::test]
1354 async fn revoke_and_status_check_do_not_deadlock() {
1355 let manager = Arc::new(X509CertificateManager::new(X509Config::default()));
1356 manager
1357 .certificate_store
1358 .write()
1359 .await
1360 .insert("lock-order".to_string(), lock_order_certificate("77"));
1361
1362 let store_guard = manager.certificate_store.write().await;
1363 let revoker = {
1364 let manager = manager.clone();
1365 tokio::spawn(async move {
1366 manager
1367 .revoke_certificate("77", RevocationReason::KeyCompromise, None)
1368 .await
1369 })
1370 };
1371 tokio::time::sleep(std::time::Duration::from_millis(100)).await;
1372 let checker = {
1373 let manager = manager.clone();
1374 tokio::spawn(async move { manager.check_certificate_status("77").await })
1375 };
1376 tokio::time::sleep(std::time::Duration::from_millis(100)).await;
1377 drop(store_guard);
1378
1379 let both = async {
1380 let revoked = revoker.await.expect("revoke task panicked");
1381 let status = checker.await.expect("status task panicked");
1382 (revoked, status)
1383 };
1384 let (revoked, status) = tokio::time::timeout(std::time::Duration::from_secs(10), both)
1385 .await
1386 .expect("revoke_certificate and check_certificate_status deadlocked");
1387 revoked.expect("revoke failed");
1388 status.expect("status check failed");
1389 assert_eq!(
1390 manager.check_certificate_status("77").await.unwrap(),
1391 CertificateStatus::Revoked
1392 );
1393 }
1394}