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 let mut store = self.certificate_store.write().await;
868 for cert in store.values_mut() {
869 if cert.serial_number == serial_number {
870 cert.status = CertificateStatus::Revoked;
871 break;
872 }
873 }
874
875 let revocation_entry = RevocationEntry {
877 serial_number: serial_number.to_string(),
878 revocation_date: Utc::now(),
879 reason,
880 additional_info,
881 };
882
883 let mut revocation_list = self.revocation_list.write().await;
884 revocation_list.insert(serial_number.to_string(), revocation_entry);
885
886 Ok(())
887 }
888
889 pub async fn check_certificate_status(&self, serial_number: &str) -> Result<CertificateStatus> {
891 let revocation_list = self.revocation_list.read().await;
893 if revocation_list.contains_key(serial_number) {
894 return Ok(CertificateStatus::Revoked);
895 }
896
897 let store = self.certificate_store.read().await;
899 for cert in store.values() {
900 if cert.serial_number == serial_number {
901 if Utc::now() > cert.not_after {
903 return Ok(CertificateStatus::Expired);
904 }
905 return Ok(cert.status.clone());
906 }
907 }
908
909 Err(AuthError::InvalidRequest(
910 "Certificate not found".to_string(),
911 ))
912 }
913
914 pub async fn get_certificate(&self, cert_id: &str) -> Result<Option<StoredCertificate>> {
916 let store = self.certificate_store.read().await;
917 Ok(store.get(cert_id).cloned())
918 }
919
920 pub async fn list_certificates(
922 &self,
923 filter: Option<CertificateFilter>,
924 ) -> Result<Vec<StoredCertificate>> {
925 let store = self.certificate_store.read().await;
926 let mut certificates: Vec<StoredCertificate> = store.values().cloned().collect();
927
928 if let Some(f) = filter {
930 certificates.retain(|cert| f.matches(cert));
931 }
932
933 Ok(certificates)
934 }
935
936 pub async fn generate_crl(&self, ca_id: &str) -> Result<String> {
938 let revocation_list = self.revocation_list.read().await;
939
940 let cas = self.ca_certificates.read().await;
942 let ca = cas
943 .get(ca_id)
944 .ok_or_else(|| AuthError::InvalidRequest(format!("CA not found: {}", ca_id)))?;
945
946 let crl_number = revocation_list.len() as u64;
949 let this_update = Utc::now();
950 let next_update = this_update + Duration::days(7); let mut crl_content = format!(
954 "Certificate Revocation List (CRL):\n\
955 \x20\x20\x20\x20Version 2 (0x1)\n\
956 \x20\x20\x20\x20Signature Algorithm: sha256WithRSAEncryption\n\
957 \x20\x20\x20\x20Issuer: {}\n\
958 \x20\x20\x20\x20Last Update: {}\n\
959 \x20\x20\x20\x20Next Update: {}\n\
960 \x20\x20\x20\x20CRL Number: {}\n",
961 ca.subject,
962 this_update.format("%b %d %H:%M:%S %Y GMT"),
963 next_update.format("%b %d %H:%M:%S %Y GMT"),
964 crl_number
965 );
966
967 if !revocation_list.is_empty() {
969 crl_content.push_str("Revoked Certificates:\n");
970 for entry in revocation_list.values() {
971 crl_content.push_str(&format!(
972 " Serial Number: {}\n\
973 \x20\x20\x20\x20\x20\x20\x20\x20Revocation Date: {}\n\
974 \x20\x20\x20\x20\x20\x20\x20\x20CRL Reason Code: {:?}\n",
975 entry.serial_number,
976 entry.revocation_date.format("%b %d %H:%M:%S %Y GMT"),
977 entry.reason
978 ));
979 }
980 } else {
981 crl_content.push_str("No Revoked Certificates.\n");
982 }
983
984 let crl_b64 = BASE64_STANDARD.encode(crl_content.as_bytes());
986 let crl_pem = format!(
987 "-----BEGIN X509 CRL-----\n{}\n-----END X509 CRL-----",
988 crl_b64
989 .chars()
990 .collect::<Vec<char>>()
991 .chunks(64)
992 .map(|chunk| chunk.iter().collect::<String>())
993 .collect::<Vec<String>>()
994 .join("\n")
995 );
996
997 log::info!(
998 "Generated CRL for CA {} with {} revoked certificates",
999 ca_id,
1000 revocation_list.len()
1001 );
1002 Ok(crl_pem)
1003 }
1004
1005 pub async fn validate_certificate_chain(&self, cert_pem: &str) -> Result<bool> {
1007 let cert_der = self.pem_to_der(cert_pem)?;
1009 let (_, cert) = parse_x509_certificate(&cert_der).map_err(|e| {
1010 AuthError::InvalidToken(format!("Failed to parse certificate: {:?}", e))
1011 })?;
1012
1013 let now = SystemTime::now();
1018 let not_before = cert.validity().not_before.to_datetime();
1019 let not_after = cert.validity().not_after.to_datetime();
1020
1021 if now < not_before {
1022 log::warn!("Certificate not yet valid");
1023 return Ok(false);
1024 }
1025
1026 if now > not_after {
1027 log::warn!("Certificate has expired");
1028 return Ok(false);
1029 }
1030
1031 let issuer_dn = cert.issuer().to_string();
1033 let subject_dn = cert.subject().to_string();
1034
1035 let is_self_signed = issuer_dn == subject_dn;
1037
1038 if is_self_signed {
1039 let cas = self.ca_certificates.read().await;
1041 for ca in cas.values() {
1042 if ca.subject == subject_dn {
1043 log::info!("Certificate validated against trusted root CA");
1044 return Ok(true);
1045 }
1046 }
1047 log::warn!("Self-signed certificate not in trusted root store");
1048 return Ok(false);
1049 }
1050
1051 let serial_number = cert.serial.to_string();
1053 let revocation_list = self.revocation_list.read().await;
1054 if revocation_list.contains_key(&serial_number) {
1055 log::warn!("Certificate has been revoked: {}", serial_number);
1056 return Ok(false);
1057 }
1058
1059 log::info!("Certificate chain validation passed for: {}", subject_dn);
1062 Ok(true)
1063 }
1064
1065 fn pem_to_der(&self, pem: &str) -> Result<Vec<u8>> {
1067 let pem_lines: Vec<&str> = pem
1071 .lines()
1072 .filter(|line| !line.starts_with("-----"))
1073 .collect();
1074
1075 let pem_content = pem_lines.join("");
1076
1077 BASE64_STANDARD
1078 .decode(&pem_content)
1079 .map_err(|e| AuthError::internal(format!("Failed to decode PEM certificate: {}", e)))
1080 }
1081
1082 async fn generate_self_signed_root_ca(&self) -> Result<(String, String)> {
1084 let timestamp = chrono::Utc::now().timestamp();
1088 let subject = "CN=AuthFramework Dev Root CA,O=Auth Framework,C=US";
1089
1090 let cert_content = format!(
1092 "-----BEGIN CERTIFICATE-----\n{}\n-----END CERTIFICATE-----",
1093 BASE64_STANDARD.encode(format!(
1094 "CERT:{}:SUBJ:{}:VALID_FROM:{}:VALID_TO:{}:SERIAL:1",
1095 timestamp,
1096 subject,
1097 timestamp,
1098 timestamp + (365 * 24 * 3600 * 10) ))
1100 );
1101
1102 let key_content = format!(
1103 "-----BEGIN PRIVATE KEY-----\n{}\n-----END PRIVATE KEY-----",
1104 BASE64_STANDARD.encode(format!(
1105 "KEY:{}:RSA:2048:TIMESTAMP:{}",
1106 timestamp, timestamp
1107 ))
1108 );
1109
1110 tracing::warn!(
1111 "Generated self-signed development root CA - THIS IS FOR DEVELOPMENT ONLY. \
1112 In production, use proper certificate management with real cryptographic operations."
1113 );
1114
1115 Ok((cert_content, key_content))
1116 }
1117
1118 fn calculate_certificate_fingerprint(&self, cert_pem: &str) -> Result<String> {
1120 use sha2::{Digest, Sha256};
1121
1122 let cert_lines: String = cert_pem
1124 .lines()
1125 .filter(|line| !line.starts_with("-----"))
1126 .collect();
1127
1128 let cert_der = BASE64_STANDARD.decode(&cert_lines).map_err(|e| {
1130 AuthError::internal(format!(
1131 "Failed to decode certificate for fingerprint: {}",
1132 e
1133 ))
1134 })?;
1135
1136 let mut hasher = Sha256::new();
1138 hasher.update(&cert_der);
1139 let hash_result = hasher.finalize();
1140
1141 let fingerprint = hash_result
1143 .iter()
1144 .map(|b| format!("{:02X}", b))
1145 .collect::<Vec<_>>()
1146 .join(":");
1147
1148 Ok(fingerprint)
1149 }
1150}
1151
1152#[derive(Debug, Clone)]
1154pub struct CertificateFilter {
1155 pub status: Option<CertificateStatus>,
1157
1158 pub profile: Option<String>,
1160
1161 pub expires_before: Option<DateTime<Utc>>,
1163
1164 pub expires_after: Option<DateTime<Utc>>,
1166
1167 pub subject_contains: Option<String>,
1169}
1170
1171impl CertificateFilter {
1172 pub fn matches(&self, cert: &StoredCertificate) -> bool {
1174 if let Some(ref status) = self.status
1175 && &cert.status != status
1176 {
1177 return false;
1178 }
1179
1180 if let Some(ref profile) = self.profile
1181 && &cert.profile != profile
1182 {
1183 return false;
1184 }
1185
1186 if let Some(expires_before) = self.expires_before
1187 && cert.not_after > expires_before
1188 {
1189 return false;
1190 }
1191
1192 if let Some(expires_after) = self.expires_after
1193 && cert.not_after < expires_after
1194 {
1195 return false;
1196 }
1197
1198 if let Some(ref subject_contains) = self.subject_contains
1199 && !cert.subject.contains(subject_contains)
1200 {
1201 return false;
1202 }
1203
1204 true
1205 }
1206}
1207
1208impl Default for X509Config {
1211 fn default() -> Self {
1212 let mut certificate_profiles = HashMap::new();
1213
1214 certificate_profiles.insert(
1216 "tls_server".to_string(),
1217 CertificateProfile {
1218 name: "TLS Server".to_string(),
1219 cert_type: CertificateType::TlsServer,
1220 key_usage: vec![KeyUsage::DigitalSignature, KeyUsage::KeyEncipherment],
1221 extended_key_usage: vec![ExtendedKeyUsage::ServerAuth],
1222 subject_alt_names: vec![],
1223 validity_days: 365,
1224 preferred_key_type: KeyType::Rsa(2048),
1225 extensions: HashMap::new(),
1226 },
1227 );
1228
1229 certificate_profiles.insert(
1230 "tls_client".to_string(),
1231 CertificateProfile {
1232 name: "TLS Client".to_string(),
1233 cert_type: CertificateType::TlsClient,
1234 key_usage: vec![KeyUsage::DigitalSignature, KeyUsage::KeyAgreement],
1235 extended_key_usage: vec![ExtendedKeyUsage::ClientAuth],
1236 subject_alt_names: vec![],
1237 validity_days: 365,
1238 preferred_key_type: KeyType::Rsa(2048),
1239 extensions: HashMap::new(),
1240 },
1241 );
1242
1243 Self {
1244 default_validity_days: 365,
1245 root_ca_cert_path: "ca/root-ca.crt".to_string(),
1246 root_ca_path: "ca/root-ca.crt".to_string(),
1247 root_ca_key_path: "ca/root-ca.key".to_string(),
1248 intermediate_ca_cert_path: None,
1249 intermediate_ca_path: None,
1250 intermediate_ca_key_path: None,
1251 default_rsa_key_size: 2048,
1252 default_ecdsa_curve: EcdsaCurve::P256,
1253 certificate_profiles,
1254 enable_ocsp: false,
1255 ocsp_responder_url: None,
1256 enable_crl: true,
1257 crl_distribution_url: Some("https://example.com/crl".to_string()),
1258 }
1259 }
1260}
1261
1262#[cfg(test)]
1263mod tests {
1264 use super::*;
1265
1266 #[tokio::test]
1267 async fn test_x509_manager_creation() {
1268 let config = X509Config::default();
1269 let manager = X509CertificateManager::new(config);
1270
1271 assert!(!manager.config.certificate_profiles.is_empty());
1273 assert_eq!(manager.config.default_validity_days, 365);
1274 }
1275
1276 #[tokio::test]
1277 async fn test_certificate_profile() {
1278 let config = X509Config::default();
1279
1280 assert!(config.certificate_profiles.contains_key("tls_server"));
1282 assert!(config.certificate_profiles.contains_key("tls_client"));
1283
1284 let tls_server_profile = &config.certificate_profiles["tls_server"];
1285 assert_eq!(tls_server_profile.cert_type, CertificateType::TlsServer);
1286 assert!(
1287 tls_server_profile
1288 .extended_key_usage
1289 .contains(&ExtendedKeyUsage::ServerAuth)
1290 );
1291 }
1292
1293 #[tokio::test]
1294 async fn test_certificate_filter() {
1295 let filter = CertificateFilter {
1296 status: Some(CertificateStatus::Valid),
1297 profile: None,
1298 expires_before: None,
1299 expires_after: None,
1300 subject_contains: Some("example.com".to_string()),
1301 };
1302
1303 let cert = StoredCertificate {
1304 cert_id: "test".to_string(),
1305 certificate_pem: "".to_string(),
1306 private_key_pem: None,
1307 subject: "CN=example.com".to_string(),
1308 issuer: "CN=Test CA".to_string(),
1309 serial_number: "123".to_string(),
1310 not_before: Utc::now(),
1311 not_after: Utc::now() + Duration::days(365),
1312 profile: "tls_server".to_string(),
1313 status: CertificateStatus::Valid,
1314 fingerprint: "test_fp".to_string(),
1315 created_at: Utc::now(),
1316 metadata: HashMap::new(),
1317 };
1318
1319 assert!(filter.matches(&cert));
1320 }
1321}