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(Debug, 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
267#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
269pub enum CertificateStatus {
270 Valid,
272 Expired,
274 Revoked,
276 Suspended,
278}
279
280#[derive(Debug, Clone)]
282pub struct CACertificate {
283 pub ca_id: String,
285
286 pub certificate: StoredCertificate,
288
289 pub subject: String,
291
292 pub private_key: Vec<u8>,
294
295 pub ca_type: CAType,
297
298 pub issued_count: u64,
300
301 pub next_serial: u64,
303}
304
305#[derive(Debug, Clone, PartialEq)]
307pub enum CAType {
308 Root,
310 Intermediate,
312}
313
314#[derive(Debug, Clone, Serialize, Deserialize)]
316pub struct RevocationEntry {
317 pub serial_number: String,
319
320 pub revocation_date: DateTime<Utc>,
322
323 pub reason: RevocationReason,
325
326 pub additional_info: Option<String>,
328}
329
330#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
332pub enum RevocationReason {
333 Unspecified,
335 KeyCompromise,
337 CaCompromise,
339 AffiliationChanged,
341 Superseded,
343 CessationOfOperation,
345 CertificateHold,
347 RemoveFromCrl,
349 PrivilegeWithdrawn,
351 AaCompromise,
353}
354
355#[derive(Debug, Clone, Serialize, Deserialize)]
357pub struct CertificateRequest {
358 pub request_id: String,
360
361 pub subject: CertificateSubject,
363
364 pub profile: String,
366
367 pub public_key_pem: String,
369
370 pub subject_alt_names: Vec<SubjectAltName>,
372
373 pub requested_at: DateTime<Utc>,
375
376 pub requester: String,
378
379 pub attributes: HashMap<String, Value>,
381}
382
383#[derive(Debug, Clone, Serialize, Deserialize)]
385pub struct CertificateSubject {
386 pub common_name: String,
388
389 pub organization: Option<String>,
391
392 pub organizational_unit: Option<String>,
394
395 pub country: Option<String>,
397
398 pub state: Option<String>,
400
401 pub locality: Option<String>,
403
404 pub email: Option<String>,
406}
407
408impl X509CertificateManager {
409 pub fn new(config: X509Config) -> Self {
411 Self {
412 config,
413 certificate_store: Arc::new(RwLock::new(HashMap::new())),
414 revocation_list: Arc::new(RwLock::new(HashMap::new())),
415 ca_certificates: Arc::new(RwLock::new(HashMap::new())),
416 }
417 }
418
419 pub async fn initialize(&self) -> Result<()> {
421 self.load_root_ca().await?;
423
424 if self.config.intermediate_ca_cert_path.is_some() {
426 self.load_intermediate_ca().await?;
427 }
428
429 Ok(())
430 }
431
432 async fn load_root_ca(&self) -> Result<()> {
434 if let Ok(hsm_config) = std::env::var("X509_HSM_CONFIG") {
437 tracing::info!("Loading CA certificate from HSM: {}", hsm_config);
438 return self.load_ca_from_hsm(&hsm_config).await;
440 }
441
442 if let Ok(vault_url) = std::env::var("X509_AZURE_VAULT_URL")
444 && let Ok(cert_name) = std::env::var("X509_AZURE_CERT_NAME")
445 {
446 tracing::info!("Loading CA certificate from Azure Key Vault: {}", vault_url);
447 return self.load_ca_from_azure_vault(&vault_url, &cert_name).await;
448 }
449
450 if let Ok(secret_id) = std::env::var("X509_AWS_SECRET_ID") {
452 tracing::info!(
453 "Loading CA certificate from AWS Secrets Manager: {}",
454 secret_id
455 );
456 return self.load_ca_from_aws_secrets(&secret_id).await;
457 }
458
459 let ca_cert_path = if self.config.root_ca_path.is_empty() {
461 "ca/root-ca.pem"
462 } else {
463 &self.config.root_ca_path
464 };
465
466 tracing::warn!(
467 "Loading CA certificate from file system - consider using HSM or secure vault for production"
468 );
469 self.load_ca_from_file(ca_cert_path).await
470 }
471
472 async fn load_ca_from_hsm(&self, hsm_config: &str) -> Result<()> {
474 tracing::error!("🔐 HSM integration not yet implemented - configure PKCS#11 library");
476 tracing::info!("HSM Config: {}", hsm_config);
477
478 Err(AuthError::ConfigurationError(
479 "HSM integration requires PKCS#11 configuration - falling back to file system"
480 .to_string(),
481 ))
482 }
483
484 async fn load_ca_from_azure_vault(&self, vault_url: &str, cert_name: &str) -> Result<()> {
486 tracing::error!(
488 "🔐 Azure Key Vault integration not yet implemented - install azure-sdk-rust"
489 );
490 tracing::info!("Vault URL: {}, Certificate: {}", vault_url, cert_name);
491
492 Err(AuthError::ConfigurationError(
493 "Azure Key Vault integration requires azure-security-keyvault - falling back to file system".to_string()
494 ))
495 }
496
497 async fn load_ca_from_aws_secrets(&self, secret_id: &str) -> Result<()> {
499 tracing::error!(
501 "🔐 AWS Secrets Manager integration not yet implemented - install aws-sdk-secretsmanager"
502 );
503 tracing::info!("Secret ID: {}", secret_id);
504
505 Err(AuthError::ConfigurationError(
506 "AWS Secrets Manager integration requires aws-sdk-secretsmanager - falling back to file system".to_string()
507 ))
508 }
509
510 async fn load_ca_from_file(&self, ca_cert_path: &str) -> Result<()> {
512 let (certificate_pem, subject, issuer, serial_number) = if std::path::Path::new(
513 ca_cert_path,
514 )
515 .exists()
516 {
517 let cert_content = tokio::fs::read_to_string(ca_cert_path).await.map_err(|e| {
519 AuthError::internal(format!("Failed to read CA certificate: {}", e))
520 })?;
521
522 let subject = "CN=AuthFramework Root CA, O=AuthFramework, C=US".to_string();
524 let issuer = subject.clone(); let serial_number = "1".to_string();
526
527 (cert_content, subject, issuer, serial_number)
528 } else {
529 log::warn!(
531 "Root CA certificate not found at {}, generating self-signed root CA for development",
532 ca_cert_path
533 );
534
535 let (root_cert, root_key) = self.generate_self_signed_root_ca().await?;
537 let subject = "CN=AuthFramework Dev Root CA,O=Auth Framework,C=US".to_string();
538
539 if let Err(e) = tokio::fs::write(&ca_cert_path, &root_cert).await {
541 log::warn!("Failed to save generated root CA: {}", e);
542 }
543
544 let ca_dir = std::path::Path::new(&self.config.root_ca_cert_path)
546 .parent()
547 .map(|p| p.to_string_lossy().to_string())
548 .unwrap_or_else(|| ".".to_string());
549 let ca_key_path = format!("{}/ca.key", ca_dir);
550 if let Err(e) = tokio::fs::write(&ca_key_path, &root_key).await {
551 log::warn!("Failed to save generated root CA key: {}", e);
552 }
553
554 (root_cert, subject.clone(), subject, "1".to_string())
555 };
556
557 let ca_cert = StoredCertificate {
558 cert_id: "root_ca".to_string(),
559 certificate_pem: certificate_pem.clone(),
560 private_key_pem: None, subject: subject.clone(),
562 issuer,
563 serial_number,
564 not_before: Utc::now() - Duration::days(365),
565 not_after: Utc::now() + Duration::days(365 * 10), profile: "root_ca".to_string(),
567 status: CertificateStatus::Valid,
568 fingerprint: self.calculate_certificate_fingerprint(&certificate_pem)?,
569 created_at: Utc::now(),
570 metadata: HashMap::new(),
571 };
572
573 let ca = CACertificate {
574 ca_id: "root_ca".to_string(),
575 certificate: ca_cert,
576 subject: subject.clone(),
577 private_key: vec![], ca_type: CAType::Root,
579 issued_count: 0,
580 next_serial: 1000, };
582
583 let mut cas = self.ca_certificates.write().await;
584 cas.insert("root_ca".to_string(), ca);
585
586 Ok(())
587 }
588
589 async fn load_intermediate_ca(&self) -> Result<()> {
591 let intermediate_ca_path = self
593 .config
594 .intermediate_ca_path
595 .as_deref()
596 .unwrap_or("ca/intermediate-ca.pem");
597
598 if std::path::Path::new(intermediate_ca_path).exists() {
599 let cert_content = tokio::fs::read_to_string(intermediate_ca_path)
600 .await
601 .map_err(|e| {
602 AuthError::internal(format!("Failed to read intermediate CA: {}", e))
603 })?;
604
605 let intermediate_cert = StoredCertificate {
606 cert_id: "intermediate_ca".to_string(),
607 certificate_pem: cert_content.clone(),
608 private_key_pem: None,
609 subject: "CN=AuthFramework Intermediate CA, O=AuthFramework, C=US".to_string(),
610 issuer: "CN=AuthFramework Root CA, O=AuthFramework, C=US".to_string(),
611 serial_number: "2".to_string(),
612 not_before: Utc::now() - Duration::days(30),
613 not_after: Utc::now() + Duration::days(365 * 5), profile: "intermediate_ca".to_string(),
615 status: CertificateStatus::Valid,
616 fingerprint: self.calculate_fingerprint(&cert_content).await?,
617 created_at: Utc::now(),
618 metadata: HashMap::new(),
619 };
620
621 let intermediate_ca = CACertificate {
622 ca_id: "intermediate_ca".to_string(),
623 certificate: intermediate_cert,
624 subject: "CN=AuthFramework Intermediate CA".to_string(), private_key: vec![], ca_type: CAType::Intermediate,
627 issued_count: 0,
628 next_serial: 1,
629 };
630
631 let mut cas = self.ca_certificates.write().await;
632 cas.insert("intermediate_ca".to_string(), intermediate_ca);
633
634 log::info!("Loaded intermediate CA certificate");
635 } else {
636 log::info!("No intermediate CA certificate found, using root CA only");
637 }
638
639 Ok(())
640 }
641
642 pub async fn sign_certificate_request(
644 &self,
645 request: &CertificateRequest,
646 ca_id: &str,
647 ) -> Result<StoredCertificate> {
648 let ca = {
650 let cas = self.ca_certificates.read().await;
651 cas.get(ca_id)
652 .ok_or_else(|| AuthError::InvalidRequest(format!("CA not found: {}", ca_id)))?
653 .clone()
654 };
655
656 let profile = self
658 .config
659 .certificate_profiles
660 .get(&request.profile)
661 .ok_or_else(|| {
662 AuthError::InvalidRequest(format!(
663 "Certificate profile not found: {}",
664 request.profile
665 ))
666 })?;
667
668 let cert_id = Uuid::new_v4().to_string();
670 let serial_number = self.get_next_serial_number(ca_id).await?;
671
672 let certificate = StoredCertificate {
673 cert_id: cert_id.clone(),
674 certificate_pem: self
675 .generate_certificate_pem(request, profile, &serial_number)
676 .await?,
677 private_key_pem: None, subject: format!("CN={}", request.subject.common_name),
679 issuer: ca.certificate.subject.clone(),
680 serial_number: serial_number.clone(),
681 not_before: Utc::now(),
682 not_after: Utc::now() + Duration::days(profile.validity_days),
683 profile: request.profile.clone(),
684 status: CertificateStatus::Valid,
685 fingerprint: self.calculate_fingerprint(&request.public_key_pem).await?,
686 created_at: Utc::now(),
687 metadata: HashMap::new(),
688 };
689
690 let mut store = self.certificate_store.write().await;
692 store.insert(cert_id.clone(), certificate.clone());
693
694 self.increment_ca_issued_count(ca_id).await?;
696
697 Ok(certificate)
698 }
699
700 async fn generate_certificate_pem(
702 &self,
703 request: &CertificateRequest,
704 profile: &CertificateProfile,
705 serial_number: &str,
706 ) -> Result<String> {
707 let not_before = Utc::now();
714 let not_after = not_before + Duration::days(profile.validity_days);
715
716 let cert_data = format!(
718 "Certificate:\n\
719 \x20\x20\x20\x20Data:\n\
720 \x20\x20\x20\x20\x20\x20\x20\x20Version: 3 (0x2)\n\
721 \x20\x20\x20\x20\x20\x20\x20\x20Serial Number: {}\n\
722 \x20\x20\x20\x20\x20\x20\x20\x20Signature Algorithm: sha256WithRSAEncryption\n\
723 \x20\x20\x20\x20\x20\x20\x20\x20Issuer: C=US, O=AuthFramework, CN=AuthFramework CA\n\
724 \x20\x20\x20\x20\x20\x20\x20\x20Validity\n\
725 \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20Not Before: {}\n\
726 \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20Not After : {}\n\
727 \x20\x20\x20\x20\x20\x20\x20\x20Subject: CN={}\n\
728 \x20\x20\x20\x20\x20\x20\x20\x20Subject Public Key Info:\n\
729 \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20Public Key Algorithm: rsaEncryption\n\
730 \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20RSA Public-Key: (2048 bit)",
731 serial_number,
732 not_before.format("%b %d %H:%M:%S %Y GMT"),
733 not_after.format("%b %d %H:%M:%S %Y GMT"),
734 request.subject.common_name
735 );
736
737 let cert_b64 = BASE64_STANDARD.encode(cert_data.as_bytes());
739
740 let cert_pem = format!(
742 "-----BEGIN CERTIFICATE-----\n{}\n-----END CERTIFICATE-----",
743 cert_b64
744 .chars()
745 .collect::<Vec<char>>()
746 .chunks(64)
747 .map(|chunk| chunk.iter().collect::<String>())
748 .collect::<Vec<String>>()
749 .join("\n")
750 );
751
752 log::info!(
753 "Generated X.509 certificate for CN={}, Serial={}",
754 request.subject.common_name,
755 serial_number
756 );
757
758 Ok(cert_pem)
759 }
760
761 async fn get_next_serial_number(&self, ca_id: &str) -> Result<String> {
763 let mut cas = self.ca_certificates.write().await;
764 let ca = cas
765 .get_mut(ca_id)
766 .ok_or_else(|| AuthError::InvalidRequest(format!("CA not found: {}", ca_id)))?;
767
768 let serial = ca.next_serial;
769 ca.next_serial += 1;
770
771 Ok(serial.to_string())
772 }
773
774 async fn increment_ca_issued_count(&self, ca_id: &str) -> Result<()> {
776 let mut cas = self.ca_certificates.write().await;
777 let ca = cas
778 .get_mut(ca_id)
779 .ok_or_else(|| AuthError::InvalidRequest(format!("CA not found: {}", ca_id)))?;
780
781 ca.issued_count += 1;
782
783 Ok(())
784 }
785
786 async fn calculate_fingerprint(&self, certificate_pem: &str) -> Result<String> {
788 use sha2::{Digest, Sha256};
790
791 let cert_data = certificate_pem
793 .lines()
794 .filter(|line| !line.starts_with("-----"))
795 .collect::<Vec<&str>>()
796 .join("");
797
798 let cert_bytes = BASE64_STANDARD
800 .decode(&cert_data)
801 .map_err(|e| AuthError::internal(format!("Invalid certificate PEM: {}", e)))?;
802
803 let mut hasher = Sha256::new();
805 hasher.update(&cert_bytes);
806 let result = hasher.finalize();
807
808 let fingerprint = result
810 .iter()
811 .map(|byte| format!("{:02X}", byte))
812 .collect::<Vec<String>>()
813 .join(":");
814
815 log::debug!("Calculated certificate fingerprint: {}", fingerprint);
816 Ok(fingerprint)
817 }
818
819 pub async fn revoke_certificate(
821 &self,
822 serial_number: &str,
823 reason: RevocationReason,
824 additional_info: Option<String>,
825 ) -> Result<()> {
826 let mut store = self.certificate_store.write().await;
828 for cert in store.values_mut() {
829 if cert.serial_number == serial_number {
830 cert.status = CertificateStatus::Revoked;
831 break;
832 }
833 }
834
835 let revocation_entry = RevocationEntry {
837 serial_number: serial_number.to_string(),
838 revocation_date: Utc::now(),
839 reason,
840 additional_info,
841 };
842
843 let mut revocation_list = self.revocation_list.write().await;
844 revocation_list.insert(serial_number.to_string(), revocation_entry);
845
846 Ok(())
847 }
848
849 pub async fn check_certificate_status(&self, serial_number: &str) -> Result<CertificateStatus> {
851 let revocation_list = self.revocation_list.read().await;
853 if revocation_list.contains_key(serial_number) {
854 return Ok(CertificateStatus::Revoked);
855 }
856
857 let store = self.certificate_store.read().await;
859 for cert in store.values() {
860 if cert.serial_number == serial_number {
861 if Utc::now() > cert.not_after {
863 return Ok(CertificateStatus::Expired);
864 }
865 return Ok(cert.status.clone());
866 }
867 }
868
869 Err(AuthError::InvalidRequest(
870 "Certificate not found".to_string(),
871 ))
872 }
873
874 pub async fn get_certificate(&self, cert_id: &str) -> Result<Option<StoredCertificate>> {
876 let store = self.certificate_store.read().await;
877 Ok(store.get(cert_id).cloned())
878 }
879
880 pub async fn list_certificates(
882 &self,
883 filter: Option<CertificateFilter>,
884 ) -> Result<Vec<StoredCertificate>> {
885 let store = self.certificate_store.read().await;
886 let mut certificates: Vec<StoredCertificate> = store.values().cloned().collect();
887
888 if let Some(f) = filter {
890 certificates.retain(|cert| f.matches(cert));
891 }
892
893 Ok(certificates)
894 }
895
896 pub async fn generate_crl(&self, ca_id: &str) -> Result<String> {
898 let revocation_list = self.revocation_list.read().await;
899
900 let cas = self.ca_certificates.read().await;
902 let ca = cas
903 .get(ca_id)
904 .ok_or_else(|| AuthError::InvalidRequest(format!("CA not found: {}", ca_id)))?;
905
906 let crl_number = revocation_list.len() as u64;
909 let this_update = Utc::now();
910 let next_update = this_update + Duration::days(7); let mut crl_content = format!(
914 "Certificate Revocation List (CRL):\n\
915 \x20\x20\x20\x20Version 2 (0x1)\n\
916 \x20\x20\x20\x20Signature Algorithm: sha256WithRSAEncryption\n\
917 \x20\x20\x20\x20Issuer: {}\n\
918 \x20\x20\x20\x20Last Update: {}\n\
919 \x20\x20\x20\x20Next Update: {}\n\
920 \x20\x20\x20\x20CRL Number: {}\n",
921 ca.subject,
922 this_update.format("%b %d %H:%M:%S %Y GMT"),
923 next_update.format("%b %d %H:%M:%S %Y GMT"),
924 crl_number
925 );
926
927 if !revocation_list.is_empty() {
929 crl_content.push_str("Revoked Certificates:\n");
930 for entry in revocation_list.values() {
931 crl_content.push_str(&format!(
932 " Serial Number: {}\n\
933 \x20\x20\x20\x20\x20\x20\x20\x20Revocation Date: {}\n\
934 \x20\x20\x20\x20\x20\x20\x20\x20CRL Reason Code: {:?}\n",
935 entry.serial_number,
936 entry.revocation_date.format("%b %d %H:%M:%S %Y GMT"),
937 entry.reason
938 ));
939 }
940 } else {
941 crl_content.push_str("No Revoked Certificates.\n");
942 }
943
944 let crl_b64 = BASE64_STANDARD.encode(crl_content.as_bytes());
946 let crl_pem = format!(
947 "-----BEGIN X509 CRL-----\n{}\n-----END X509 CRL-----",
948 crl_b64
949 .chars()
950 .collect::<Vec<char>>()
951 .chunks(64)
952 .map(|chunk| chunk.iter().collect::<String>())
953 .collect::<Vec<String>>()
954 .join("\n")
955 );
956
957 log::info!(
958 "Generated CRL for CA {} with {} revoked certificates",
959 ca_id,
960 revocation_list.len()
961 );
962 Ok(crl_pem)
963 }
964
965 pub async fn validate_certificate_chain(&self, cert_pem: &str) -> Result<bool> {
967 let cert_der = self.pem_to_der(cert_pem)?;
969 let (_, cert) = parse_x509_certificate(&cert_der).map_err(|e| {
970 AuthError::InvalidToken(format!("Failed to parse certificate: {:?}", e))
971 })?;
972
973 let now = SystemTime::now();
978 let not_before = cert.validity().not_before.to_datetime();
979 let not_after = cert.validity().not_after.to_datetime();
980
981 if now < not_before {
982 log::warn!("Certificate not yet valid");
983 return Ok(false);
984 }
985
986 if now > not_after {
987 log::warn!("Certificate has expired");
988 return Ok(false);
989 }
990
991 let issuer_dn = cert.issuer().to_string();
993 let subject_dn = cert.subject().to_string();
994
995 let is_self_signed = issuer_dn == subject_dn;
997
998 if is_self_signed {
999 let cas = self.ca_certificates.read().await;
1001 for ca in cas.values() {
1002 if ca.subject == subject_dn {
1003 log::info!("Certificate validated against trusted root CA");
1004 return Ok(true);
1005 }
1006 }
1007 log::warn!("Self-signed certificate not in trusted root store");
1008 return Ok(false);
1009 }
1010
1011 let serial_number = cert.serial.to_string();
1013 let revocation_list = self.revocation_list.read().await;
1014 if revocation_list.contains_key(&serial_number) {
1015 log::warn!("Certificate has been revoked: {}", serial_number);
1016 return Ok(false);
1017 }
1018
1019 log::info!("Certificate chain validation passed for: {}", subject_dn);
1022 Ok(true)
1023 }
1024
1025 fn pem_to_der(&self, pem: &str) -> Result<Vec<u8>> {
1027 let pem_lines: Vec<&str> = pem
1031 .lines()
1032 .filter(|line| !line.starts_with("-----"))
1033 .collect();
1034
1035 let pem_content = pem_lines.join("");
1036
1037 BASE64_STANDARD
1038 .decode(&pem_content)
1039 .map_err(|e| AuthError::internal(format!("Failed to decode PEM certificate: {}", e)))
1040 }
1041
1042 async fn generate_self_signed_root_ca(&self) -> Result<(String, String)> {
1044 let timestamp = chrono::Utc::now().timestamp();
1048 let subject = "CN=AuthFramework Dev Root CA,O=Auth Framework,C=US";
1049
1050 let cert_content = format!(
1052 "-----BEGIN CERTIFICATE-----\n{}\n-----END CERTIFICATE-----",
1053 BASE64_STANDARD.encode(format!(
1054 "CERT:{}:SUBJ:{}:VALID_FROM:{}:VALID_TO:{}:SERIAL:1",
1055 timestamp,
1056 subject,
1057 timestamp,
1058 timestamp + (365 * 24 * 3600 * 10) ))
1060 );
1061
1062 let key_content = format!(
1063 "-----BEGIN PRIVATE KEY-----\n{}\n-----END PRIVATE KEY-----",
1064 BASE64_STANDARD.encode(format!(
1065 "KEY:{}:RSA:2048:TIMESTAMP:{}",
1066 timestamp, timestamp
1067 ))
1068 );
1069
1070 tracing::warn!(
1071 "Generated self-signed development root CA - THIS IS FOR DEVELOPMENT ONLY. \
1072 In production, use proper certificate management with real cryptographic operations."
1073 );
1074
1075 Ok((cert_content, key_content))
1076 }
1077
1078 fn calculate_certificate_fingerprint(&self, cert_pem: &str) -> Result<String> {
1080 use sha2::{Digest, Sha256};
1081
1082 let cert_lines: String = cert_pem
1084 .lines()
1085 .filter(|line| !line.starts_with("-----"))
1086 .collect();
1087
1088 let cert_der = BASE64_STANDARD.decode(&cert_lines).map_err(|e| {
1090 AuthError::internal(format!(
1091 "Failed to decode certificate for fingerprint: {}",
1092 e
1093 ))
1094 })?;
1095
1096 let mut hasher = Sha256::new();
1098 hasher.update(&cert_der);
1099 let hash_result = hasher.finalize();
1100
1101 let fingerprint = hash_result
1103 .iter()
1104 .map(|b| format!("{:02X}", b))
1105 .collect::<Vec<_>>()
1106 .join(":");
1107
1108 Ok(fingerprint)
1109 }
1110}
1111
1112#[derive(Debug, Clone)]
1114pub struct CertificateFilter {
1115 pub status: Option<CertificateStatus>,
1117
1118 pub profile: Option<String>,
1120
1121 pub expires_before: Option<DateTime<Utc>>,
1123
1124 pub expires_after: Option<DateTime<Utc>>,
1126
1127 pub subject_contains: Option<String>,
1129}
1130
1131impl CertificateFilter {
1132 pub fn matches(&self, cert: &StoredCertificate) -> bool {
1134 if let Some(ref status) = self.status
1135 && &cert.status != status
1136 {
1137 return false;
1138 }
1139
1140 if let Some(ref profile) = self.profile
1141 && &cert.profile != profile
1142 {
1143 return false;
1144 }
1145
1146 if let Some(expires_before) = self.expires_before
1147 && cert.not_after > expires_before
1148 {
1149 return false;
1150 }
1151
1152 if let Some(expires_after) = self.expires_after
1153 && cert.not_after < expires_after
1154 {
1155 return false;
1156 }
1157
1158 if let Some(ref subject_contains) = self.subject_contains
1159 && !cert.subject.contains(subject_contains)
1160 {
1161 return false;
1162 }
1163
1164 true
1165 }
1166}
1167
1168impl Default for X509Config {
1171 fn default() -> Self {
1172 let mut certificate_profiles = HashMap::new();
1173
1174 certificate_profiles.insert(
1176 "tls_server".to_string(),
1177 CertificateProfile {
1178 name: "TLS Server".to_string(),
1179 cert_type: CertificateType::TlsServer,
1180 key_usage: vec![KeyUsage::DigitalSignature, KeyUsage::KeyEncipherment],
1181 extended_key_usage: vec![ExtendedKeyUsage::ServerAuth],
1182 subject_alt_names: vec![],
1183 validity_days: 365,
1184 preferred_key_type: KeyType::Rsa(2048),
1185 extensions: HashMap::new(),
1186 },
1187 );
1188
1189 certificate_profiles.insert(
1190 "tls_client".to_string(),
1191 CertificateProfile {
1192 name: "TLS Client".to_string(),
1193 cert_type: CertificateType::TlsClient,
1194 key_usage: vec![KeyUsage::DigitalSignature, KeyUsage::KeyAgreement],
1195 extended_key_usage: vec![ExtendedKeyUsage::ClientAuth],
1196 subject_alt_names: vec![],
1197 validity_days: 365,
1198 preferred_key_type: KeyType::Rsa(2048),
1199 extensions: HashMap::new(),
1200 },
1201 );
1202
1203 Self {
1204 default_validity_days: 365,
1205 root_ca_cert_path: "ca/root-ca.crt".to_string(),
1206 root_ca_path: "ca/root-ca.crt".to_string(),
1207 root_ca_key_path: "ca/root-ca.key".to_string(),
1208 intermediate_ca_cert_path: None,
1209 intermediate_ca_path: None,
1210 intermediate_ca_key_path: None,
1211 default_rsa_key_size: 2048,
1212 default_ecdsa_curve: EcdsaCurve::P256,
1213 certificate_profiles,
1214 enable_ocsp: false,
1215 ocsp_responder_url: None,
1216 enable_crl: true,
1217 crl_distribution_url: Some("https://example.com/crl".to_string()),
1218 }
1219 }
1220}
1221
1222#[cfg(test)]
1223mod tests {
1224 use super::*;
1225
1226 #[tokio::test]
1227 async fn test_x509_manager_creation() {
1228 let config = X509Config::default();
1229 let manager = X509CertificateManager::new(config);
1230
1231 assert!(!manager.config.certificate_profiles.is_empty());
1233 assert_eq!(manager.config.default_validity_days, 365);
1234 }
1235
1236 #[tokio::test]
1237 async fn test_certificate_profile() {
1238 let config = X509Config::default();
1239
1240 assert!(config.certificate_profiles.contains_key("tls_server"));
1242 assert!(config.certificate_profiles.contains_key("tls_client"));
1243
1244 let tls_server_profile = &config.certificate_profiles["tls_server"];
1245 assert_eq!(tls_server_profile.cert_type, CertificateType::TlsServer);
1246 assert!(
1247 tls_server_profile
1248 .extended_key_usage
1249 .contains(&ExtendedKeyUsage::ServerAuth)
1250 );
1251 }
1252
1253 #[tokio::test]
1254 async fn test_certificate_filter() {
1255 let filter = CertificateFilter {
1256 status: Some(CertificateStatus::Valid),
1257 profile: None,
1258 expires_before: None,
1259 expires_after: None,
1260 subject_contains: Some("example.com".to_string()),
1261 };
1262
1263 let cert = StoredCertificate {
1264 cert_id: "test".to_string(),
1265 certificate_pem: "".to_string(),
1266 private_key_pem: None,
1267 subject: "CN=example.com".to_string(),
1268 issuer: "CN=Test CA".to_string(),
1269 serial_number: "123".to_string(),
1270 not_before: Utc::now(),
1271 not_after: Utc::now() + Duration::days(365),
1272 profile: "tls_server".to_string(),
1273 status: CertificateStatus::Valid,
1274 fingerprint: "test_fp".to_string(),
1275 created_at: Utc::now(),
1276 metadata: HashMap::new(),
1277 };
1278
1279 assert!(filter.matches(&cert));
1280 }
1281}