Skip to main content

auth_framework/server/security/
x509_signing.rs

1//! Enhanced X.509 Certificate Signing Module
2//!
3//! This module provides comprehensive X.509 certificate signing capabilities
4//! for enterprise authentication scenarios including:
5//!
6//! # Features
7//!
8//! - **Certificate Authority (CA) Operations**: Root and intermediate CA management
9//! - **Certificate Signing Requests (CSR)**: Generate and sign CSRs
10//! - **Certificate Lifecycle**: Create, renew, revoke, and validate certificates
11//! - **Multiple Key Types**: RSA, ECDSA, and Ed25519 support
12//! - **Certificate Profiles**: Different certificate types for various use cases
13//! - **CRL and OCSP**: Certificate revocation mechanisms
14//! - **Enterprise Integration**: LDAP, Active Directory, and PKI integration
15//!
16//! # Use Cases
17//!
18//! - Client certificate authentication (OAuth 2.0 mTLS)
19//! - Code signing certificates
20//! - TLS/SSL server certificates
21//! - Email signing and encryption certificates
22//! - Document signing certificates
23//! - IoT device certificates
24
25use crate::errors::{AuthError, Result};
26use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD};
27use chrono::{DateTime, Duration, Utc};
28use serde::{Deserialize, Serialize};
29use serde_json::Value;
30use std::collections::HashMap;
31use std::fmt;
32use std::sync::Arc;
33use std::time::SystemTime;
34use tokio::sync::RwLock;
35use uuid::Uuid;
36use x509_parser::parse_x509_certificate;
37use zeroize::Zeroizing;
38
39/// Enhanced X.509 Certificate Manager
40#[derive(Debug, Clone)]
41pub struct X509CertificateManager {
42    /// Configuration
43    config: X509Config,
44
45    /// Certificate store
46    certificate_store: Arc<RwLock<HashMap<String, StoredCertificate>>>,
47
48    /// Certificate revocation list
49    revocation_list: Arc<RwLock<HashMap<String, RevocationEntry>>>,
50
51    /// CA certificates
52    ca_certificates: Arc<RwLock<HashMap<String, CACertificate>>>,
53}
54
55/// X.509 Configuration
56#[derive(Debug, Clone)]
57pub struct X509Config {
58    /// Default certificate validity period (days)
59    pub default_validity_days: i64,
60
61    /// Root CA certificate path
62    pub root_ca_cert_path: String,
63
64    /// Root CA certificate path (alias)
65    pub root_ca_path: String,
66
67    /// Root CA private key path
68    pub root_ca_key_path: String,
69
70    /// Intermediate CA certificate path
71    pub intermediate_ca_cert_path: Option<String>,
72
73    /// Intermediate CA certificate path (alias)
74    pub intermediate_ca_path: Option<String>,
75
76    /// Intermediate CA private key path
77    pub intermediate_ca_key_path: Option<String>,
78
79    /// Default key size for RSA
80    pub default_rsa_key_size: u32,
81
82    /// Default curve for ECDSA
83    pub default_ecdsa_curve: EcdsaCurve,
84
85    /// Certificate profiles
86    pub certificate_profiles: HashMap<String, CertificateProfile>,
87
88    /// Enable OCSP (Online Certificate Status Protocol)
89    pub enable_ocsp: bool,
90
91    /// OCSP responder URL
92    pub ocsp_responder_url: Option<String>,
93
94    /// Enable CRL (Certificate Revocation List)
95    pub enable_crl: bool,
96
97    /// CRL distribution point URL
98    pub crl_distribution_url: Option<String>,
99}
100
101/// ECDSA Curve types
102#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
103pub enum EcdsaCurve {
104    /// P-256 (secp256r1)
105    P256,
106    /// P-384 (secp384r1)
107    P384,
108    /// P-521 (secp521r1)
109    P521,
110}
111
112/// Certificate Profile for different use cases
113#[derive(Debug, Clone, Serialize, Deserialize)]
114pub struct CertificateProfile {
115    /// Profile name
116    pub name: String,
117
118    /// Certificate type
119    pub cert_type: CertificateType,
120
121    /// Key usage flags
122    pub key_usage: Vec<KeyUsage>,
123
124    /// Extended key usage
125    pub extended_key_usage: Vec<ExtendedKeyUsage>,
126
127    /// Subject alternative names
128    pub subject_alt_names: Vec<SubjectAltName>,
129
130    /// Validity period (days)
131    pub validity_days: i64,
132
133    /// Key type preference
134    pub preferred_key_type: KeyType,
135
136    /// Additional extensions
137    pub extensions: HashMap<String, Value>,
138}
139
140/// Certificate Types
141#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
142pub enum CertificateType {
143    /// Root Certificate Authority
144    RootCA,
145    /// Intermediate Certificate Authority
146    IntermediateCA,
147    /// End entity certificate (leaf)
148    EndEntity,
149    /// Code signing certificate
150    CodeSigning,
151    /// Email certificate
152    Email,
153    /// TLS server certificate
154    TlsServer,
155    /// TLS client certificate
156    TlsClient,
157    /// Document signing certificate
158    DocumentSigning,
159}
160
161/// Key Usage flags
162#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
163pub enum KeyUsage {
164    /// Digital signature
165    DigitalSignature,
166    /// Non-repudiation
167    NonRepudiation,
168    /// Key encipherment
169    KeyEncipherment,
170    /// Data encipherment
171    DataEncipherment,
172    /// Key agreement
173    KeyAgreement,
174    /// Key certificate signing
175    KeyCertSign,
176    /// CRL signing
177    CrlSign,
178    /// Encipher only
179    EncipherOnly,
180    /// Decipher only
181    DecipherOnly,
182}
183
184/// Extended Key Usage
185#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
186pub enum ExtendedKeyUsage {
187    /// Server authentication
188    ServerAuth,
189    /// Client authentication
190    ClientAuth,
191    /// Code signing
192    CodeSigning,
193    /// Email protection
194    EmailProtection,
195    /// Time stamping
196    TimeStamping,
197    /// OCSP signing
198    OcspSigning,
199}
200
201/// Subject Alternative Name types
202#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
203pub enum SubjectAltName {
204    /// DNS name
205    DnsName(String),
206    /// Email address
207    Email(String),
208    /// URI
209    Uri(String),
210    /// IP address
211    IpAddress(String),
212}
213
214/// Key Types
215#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
216pub enum KeyType {
217    /// RSA key
218    Rsa(u32), // Key size in bits
219    /// ECDSA key
220    Ecdsa(EcdsaCurve),
221    /// Ed25519 key
222    Ed25519,
223}
224
225/// Stored Certificate
226#[derive(Debug, Clone, Serialize, Deserialize)]
227pub struct StoredCertificate {
228    /// Certificate ID
229    pub cert_id: String,
230
231    /// Certificate data (PEM format)
232    pub certificate_pem: String,
233
234    /// Private key (PEM format, optional)
235    pub private_key_pem: Option<String>,
236
237    /// Certificate subject
238    pub subject: String,
239
240    /// Certificate issuer
241    pub issuer: String,
242
243    /// Serial number
244    pub serial_number: String,
245
246    /// Not before date
247    pub not_before: DateTime<Utc>,
248
249    /// Not after date
250    pub not_after: DateTime<Utc>,
251
252    /// Certificate profile used
253    pub profile: String,
254
255    /// Certificate status
256    pub status: CertificateStatus,
257
258    /// Fingerprint (SHA-256)
259    pub fingerprint: String,
260
261    /// Created timestamp
262    pub created_at: DateTime<Utc>,
263
264    /// Metadata
265    pub metadata: HashMap<String, Value>,
266}
267
268/// Certificate Status
269#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
270pub enum CertificateStatus {
271    /// Certificate is valid
272    Valid,
273    /// Certificate is expired
274    Expired,
275    /// Certificate is revoked
276    Revoked,
277    /// Certificate is suspended
278    Suspended,
279}
280
281/// CA Certificate
282///
283/// Does not derive `Debug`: `private_key` holds the CA's raw signing key,
284/// and a derived `Debug` would print it verbatim on any accidental
285/// `{:?}`. The manual impl below redacts it.
286#[derive(Clone)]
287pub struct CACertificate {
288    /// CA ID
289    pub ca_id: String,
290
291    /// CA certificate
292    pub certificate: StoredCertificate,
293
294    /// Certificate subject
295    pub subject: String,
296
297    /// CA private key
298    pub private_key: Zeroizing<Vec<u8>>,
299
300    /// CA type
301    pub ca_type: CAType,
302
303    /// Issued certificates count
304    pub issued_count: u64,
305
306    /// Next certificate serial number
307    pub next_serial: u64,
308}
309
310impl fmt::Debug for CACertificate {
311    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
312        f.debug_struct("CACertificate")
313            .field("ca_id", &self.ca_id)
314            .field("certificate", &self.certificate)
315            .field("subject", &self.subject)
316            .field("private_key", &"[redacted]")
317            .field("ca_type", &self.ca_type)
318            .field("issued_count", &self.issued_count)
319            .field("next_serial", &self.next_serial)
320            .finish()
321    }
322}
323
324/// CA Types
325#[derive(Debug, Clone, PartialEq)]
326pub enum CAType {
327    /// Root CA
328    Root,
329    /// Intermediate CA
330    Intermediate,
331}
332
333/// Certificate Revocation Entry
334#[derive(Debug, Clone, Serialize, Deserialize)]
335pub struct RevocationEntry {
336    /// Certificate serial number
337    pub serial_number: String,
338
339    /// Revocation date
340    pub revocation_date: DateTime<Utc>,
341
342    /// Revocation reason
343    pub reason: RevocationReason,
344
345    /// Additional information
346    pub additional_info: Option<String>,
347}
348
349/// Revocation Reasons (RFC 5280)
350#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
351pub enum RevocationReason {
352    /// Unspecified
353    Unspecified,
354    /// Key compromise
355    KeyCompromise,
356    /// CA compromise
357    CaCompromise,
358    /// Affiliation changed
359    AffiliationChanged,
360    /// Superseded
361    Superseded,
362    /// Cessation of operation
363    CessationOfOperation,
364    /// Certificate hold
365    CertificateHold,
366    /// Remove from CRL
367    RemoveFromCrl,
368    /// Privilege withdrawn
369    PrivilegeWithdrawn,
370    /// AA compromise
371    AaCompromise,
372}
373
374/// Certificate Signing Request
375#[derive(Debug, Clone, Serialize, Deserialize)]
376pub struct CertificateRequest {
377    /// Request ID
378    pub request_id: String,
379
380    /// Certificate subject information
381    pub subject: CertificateSubject,
382
383    /// Certificate profile to use
384    pub profile: String,
385
386    /// Public key (PEM format)
387    pub public_key_pem: String,
388
389    /// Subject alternative names
390    pub subject_alt_names: Vec<SubjectAltName>,
391
392    /// Request timestamp
393    pub requested_at: DateTime<Utc>,
394
395    /// Requester information
396    pub requester: String,
397
398    /// Additional attributes
399    pub attributes: HashMap<String, Value>,
400}
401
402/// Certificate Subject Information
403#[derive(Debug, Clone, Serialize, Deserialize)]
404pub struct CertificateSubject {
405    /// Common name
406    pub common_name: String,
407
408    /// Organization
409    pub organization: Option<String>,
410
411    /// Organizational unit
412    pub organizational_unit: Option<String>,
413
414    /// Country
415    pub country: Option<String>,
416
417    /// State/Province
418    pub state: Option<String>,
419
420    /// City/Locality
421    pub locality: Option<String>,
422
423    /// Email address
424    pub email: Option<String>,
425}
426
427impl X509CertificateManager {
428    /// Create new X.509 certificate manager
429    pub fn new(config: X509Config) -> Self {
430        Self {
431            config,
432            certificate_store: Arc::new(RwLock::new(HashMap::new())),
433            revocation_list: Arc::new(RwLock::new(HashMap::new())),
434            ca_certificates: Arc::new(RwLock::new(HashMap::new())),
435        }
436    }
437
438    /// Initialize certificate manager with CA certificates
439    pub async fn initialize(&self) -> Result<()> {
440        // Load root CA certificate
441        self.load_root_ca().await?;
442
443        // Load intermediate CA certificate if configured
444        if self.config.intermediate_ca_cert_path.is_some() {
445            self.load_intermediate_ca().await?;
446        }
447
448        Ok(())
449    }
450
451    /// Load root CA certificate
452    async fn load_root_ca(&self) -> Result<()> {
453        // Production implementation: Load from secure certificate store or HSM
454        // Check for HSM configuration first
455        #[cfg(feature = "hsm")]
456        if let Ok(hsm_config) = std::env::var("X509_HSM_CONFIG") {
457            tracing::info!("Loading CA certificate from HSM: {}", hsm_config);
458            // In production, integrate with PKCS#11 or Azure Key Vault
459            return self.load_ca_from_hsm(&hsm_config).await;
460        }
461        #[cfg(not(feature = "hsm"))]
462        if std::env::var("X509_HSM_CONFIG").is_ok() {
463            tracing::warn!(
464                "X509_HSM_CONFIG is set but the 'hsm' feature is not enabled — ignoring"
465            );
466        }
467
468        // Check for Azure Key Vault configuration
469        if let Ok(vault_url) = std::env::var("X509_AZURE_VAULT_URL")
470            && let Ok(cert_name) = std::env::var("X509_AZURE_CERT_NAME")
471        {
472            tracing::info!("Loading CA certificate from Azure Key Vault: {}", vault_url);
473            return self.load_ca_from_azure_vault(&vault_url, &cert_name).await;
474        }
475
476        // Check for AWS Secrets Manager configuration
477        if let Ok(secret_id) = std::env::var("X509_AWS_SECRET_ID") {
478            tracing::info!(
479                "Loading CA certificate from AWS Secrets Manager: {}",
480                secret_id
481            );
482            return self.load_ca_from_aws_secrets(&secret_id).await;
483        }
484
485        // Fallback to file system loading with proper security validation
486        let ca_cert_path = if self.config.root_ca_path.is_empty() {
487            "ca/root-ca.pem"
488        } else {
489            &self.config.root_ca_path
490        };
491
492        tracing::warn!(
493            "Loading CA certificate from file system - consider using HSM or secure vault for production"
494        );
495        self.load_ca_from_file(ca_cert_path).await
496    }
497
498    /// Load CA certificate from HSM (Hardware Security Module) via PKCS#11.
499    ///
500    /// `hsm_config` must be a JSON object with the following fields:
501    /// - `library` (required): absolute path to the PKCS#11 shared library (`.so` / `.dll`)
502    /// - `slot` (optional, default `0`): slot index returned by `get_slots_with_initialized_token`
503    /// - `pin` (optional): User PIN for login (omit for login-less tokens)
504    /// - `label` (optional, default `"ca-cert"`): CKA_LABEL of the certificate object
505    ///
506    /// # Example config
507    /// ```text
508    /// {"library":"/usr/lib/softhsm/libsofthsm2.so","slot":0,"pin":"1234","label":"root-ca"}
509    /// ```
510    #[cfg(feature = "hsm")]
511    async fn load_ca_from_hsm(&self, hsm_config: &str) -> Result<()> {
512        let config: serde_json::Value = serde_json::from_str(hsm_config)
513            .map_err(|e| AuthError::config(format!("Invalid HSM JSON config: {}", e)))?;
514
515        let library = config["library"]
516            .as_str()
517            .ok_or_else(|| AuthError::config("HSM config missing 'library' path".to_string()))?;
518
519        // Extract optional parameters
520        let slot_id = config["slot"].as_u64().unwrap_or(0);
521        let pin = config["pin"].as_str().map(|s| s.to_string());
522        let _label = config["label"].as_str().unwrap_or("root-ca").to_string();
523
524        // Note: Real PKCS#11 operations are synchronous and may block.
525        // We use spawn_blocking to prevent blocking the async runtime.
526        let library_path = library.to_string();
527
528        let handle = tokio::task::spawn_blocking(move || -> Result<Vec<u8>> {
529            // First, initialize the PKCS#11 context
530            let pkcs11 = cryptoki::context::Pkcs11::new(&library_path)
531                .map_err(|e| AuthError::config(format!("Failed to load PKCS#11 library: {}", e)))?;
532
533            pkcs11
534                .initialize(cryptoki::context::CInitializeArgs::new(
535                    cryptoki::context::CInitializeFlags::OS_LOCKING_OK,
536                ))
537                .map_err(|e| {
538                    AuthError::config(format!("Failed to initialize PKCS#11 context: {}", e))
539                })?;
540
541            // Get slots
542            let slots = pkcs11
543                .get_slots_with_token()
544                .map_err(|e| AuthError::config(format!("Failed to get PKCS#11 slots: {}", e)))?;
545
546            if slot_id as usize >= slots.len() {
547                return Err(AuthError::config(format!(
548                    "HSM slot {} not found or has no token",
549                    slot_id
550                )));
551            }
552            let slot = slots[slot_id as usize];
553
554            // Open a session
555            let session = pkcs11
556                .open_ro_session(slot)
557                .map_err(|e| AuthError::config(format!("Failed to open PKCS#11 session: {}", e)))?;
558
559            // Login if PIN is provided
560            if let Some(p) = pin {
561                let auth_pin = cryptoki::types::AuthPin::new(p.into());
562                session
563                    .login(cryptoki::session::UserType::User, Some(&auth_pin))
564                    .map_err(|e| AuthError::config(format!("HSM login failed: {}", e)))?;
565            }
566
567            // Find the certificate object by label
568            let mut search_template: Vec<cryptoki::object::Attribute> = Vec::new();
569            search_template.push(cryptoki::object::Attribute::Class(
570                cryptoki::object::ObjectClass::CERTIFICATE,
571            ));
572            search_template.push(cryptoki::object::Attribute::Label(
573                _label.clone().into_bytes(),
574            ));
575
576            let objects = session.find_objects(&search_template).map_err(|e| {
577                AuthError::config(format!("Failed to search PKCS#11 objects: {}", e))
578            })?;
579
580            if objects.is_empty() {
581                return Err(AuthError::config(format!(
582                    "Certificate with label '{}' not found in HSM",
583                    _label
584                )));
585            }
586
587            // Read the certificate value (usually CKA_VALUE for X.509 certs)
588            let cert_obj = objects[0];
589            let attrs = session
590                .get_attributes(cert_obj, &[cryptoki::object::AttributeType::Value])
591                .map_err(|e| {
592                    AuthError::config(format!("Failed to get certificate value from HSM: {}", e))
593                })?;
594
595            if attrs.is_empty() {
596                return Err(AuthError::config(
597                    "Certificate object has no value attribute".to_string(),
598                ));
599            }
600
601            let value = match &attrs[0] {
602                cryptoki::object::Attribute::Value(v) => v.clone(),
603                _ => {
604                    return Err(AuthError::config(
605                        "Invalid value attribute type".to_string(),
606                    ));
607                }
608            };
609
610            Ok(value)
611        });
612
613        let cert_der = handle
614            .await
615            .map_err(|_| AuthError::config("HSM task panicked".to_string()))??;
616
617        // Convert the DER certificate bytes to PEM format and store via the
618        // shared helper that all external CA integrations use.
619        let cert_pem = format!(
620            "-----BEGIN CERTIFICATE-----\n{}\n-----END CERTIFICATE-----",
621            BASE64_STANDARD.encode(&cert_der)
622        );
623
624        self.store_ca_certificate_from_pem(&cert_pem, &format!("hsm:slot{}", slot_id))
625            .await
626    }
627
628    async fn load_ca_from_azure_vault(&self, vault_url: &str, cert_name: &str) -> Result<()> {
629        let tenant_id = std::env::var("X509_AZURE_TENANT_ID").map_err(|_| {
630            AuthError::config(
631                "X509_AZURE_TENANT_ID environment variable required for Azure Key Vault authentication"
632                    .to_string(),
633            )
634        })?;
635        let client_id = std::env::var("X509_AZURE_CLIENT_ID").map_err(|_| {
636            AuthError::config(
637                "X509_AZURE_CLIENT_ID environment variable required for Azure Key Vault authentication"
638                    .to_string(),
639            )
640        })?;
641        let client_secret = std::env::var("X509_AZURE_CLIENT_SECRET").map_err(|_| {
642            AuthError::config(
643                "X509_AZURE_CLIENT_SECRET environment variable required for Azure Key Vault authentication"
644                    .to_string(),
645            )
646        })?;
647
648        let http = reqwest::Client::new();
649
650        // Step 1: Client-credentials flow → access token.
651        let token_url = format!(
652            "https://login.microsoftonline.com/{}/oauth2/v2.0/token",
653            tenant_id
654        );
655        let token_resp = http
656            .post(&token_url)
657            .form(&[
658                ("grant_type", "client_credentials"),
659                ("client_id", client_id.as_str()),
660                ("client_secret", client_secret.as_str()),
661                ("scope", "https://vault.azure.net/.default"),
662            ])
663            .send()
664            .await
665            .map_err(|e| AuthError::internal(format!("Azure AD token request failed: {}", e)))?;
666
667        if !token_resp.status().is_success() {
668            let status = token_resp.status();
669            let body = token_resp.text().await.unwrap_or_default();
670            return Err(AuthError::config(format!(
671                "Azure AD token request returned {}: {}",
672                status, body
673            )));
674        }
675
676        let token_json: serde_json::Value = token_resp.json().await.map_err(|e| {
677            AuthError::internal(format!("Failed to parse Azure AD token response: {}", e))
678        })?;
679        let access_token = token_json["access_token"]
680            .as_str()
681            .ok_or_else(|| AuthError::internal("Azure AD response missing 'access_token'"))?
682            .to_string();
683
684        // Step 2: Fetch the secret from Key Vault (returns PEM / PKCS#12 bundle).
685        let vault_base = vault_url.trim_end_matches('/');
686        let secret_url = format!("{}/secrets/{}?api-version=7.4", vault_base, cert_name);
687        let cert_resp = http
688            .get(&secret_url)
689            .header("Authorization", format!("Bearer {}", access_token))
690            .send()
691            .await
692            .map_err(|e| AuthError::internal(format!("Azure Key Vault request failed: {}", e)))?;
693
694        if !cert_resp.status().is_success() {
695            let status = cert_resp.status();
696            let body = cert_resp.text().await.unwrap_or_default();
697            return Err(AuthError::config(format!(
698                "Azure Key Vault secret fetch returned {}: {}",
699                status, body
700            )));
701        }
702
703        let cert_json: serde_json::Value = cert_resp.json().await.map_err(|e| {
704            AuthError::internal(format!("Failed to parse Azure Key Vault response: {}", e))
705        })?;
706
707        let raw_value = cert_json["value"]
708            .as_str()
709            .ok_or_else(|| AuthError::internal("Azure Key Vault response missing 'value' field"))?
710            .to_string();
711
712        let content_type = cert_json["contentType"]
713            .as_str()
714            .unwrap_or("application/x-pem-file");
715
716        let cert_pem = if content_type == "application/x-pem-file"
717            || raw_value.contains("-----BEGIN")
718        {
719            // PEM bundle — extract only the leaf/CA certificate block.
720            x509_extract_certificate_pem(&raw_value)
721        } else {
722            return Err(AuthError::config(format!(
723                "Azure Key Vault certificate '{}' uses content-type '{}'. \
724                 Store the certificate as a PEM secret (application/x-pem-file) for automatic import.",
725                cert_name, content_type
726            )));
727        };
728
729        tracing::info!(
730            "Successfully loaded CA certificate from Azure Key Vault: {}/{}",
731            vault_base,
732            cert_name
733        );
734        self.store_ca_certificate_from_pem(
735            &cert_pem,
736            &format!("azure_kv:{}/{}", vault_base, cert_name),
737        )
738        .await
739    }
740
741    /// Load CA certificate from AWS Secrets Manager using AWS SigV4 request signing.
742    ///
743    /// Required environment variables (standard AWS credential chain):
744    /// - `AWS_ACCESS_KEY_ID`
745    /// - `AWS_SECRET_ACCESS_KEY`
746    /// - `AWS_REGION` or `AWS_DEFAULT_REGION`
747    /// - `AWS_SESSION_TOKEN` (optional, for temporary credentials)
748    ///
749    /// The secret value must be a PEM-encoded certificate (or a PEM bundle; the
750    /// first `CERTIFICATE` block is extracted automatically).
751    async fn load_ca_from_aws_secrets(&self, secret_id: &str) -> Result<()> {
752        let access_key = std::env::var("AWS_ACCESS_KEY_ID").map_err(|_| {
753            AuthError::config(
754                "AWS_ACCESS_KEY_ID environment variable required for Secrets Manager".to_string(),
755            )
756        })?;
757        let secret_key = std::env::var("AWS_SECRET_ACCESS_KEY").map_err(|_| {
758            AuthError::config(
759                "AWS_SECRET_ACCESS_KEY environment variable required for Secrets Manager"
760                    .to_string(),
761            )
762        })?;
763        let region = std::env::var("AWS_REGION")
764            .or_else(|_| std::env::var("AWS_DEFAULT_REGION"))
765            .map_err(|_| {
766                AuthError::config(
767                    "AWS_REGION (or AWS_DEFAULT_REGION) environment variable required for Secrets Manager"
768                        .to_string(),
769                )
770            })?;
771        let session_token = std::env::var("AWS_SESSION_TOKEN").ok();
772
773        let service = "secretsmanager";
774        let host = format!("{}.{}.amazonaws.com", service, region);
775        let payload =
776            serde_json::to_vec(&serde_json::json!({ "SecretId": secret_id })).map_err(|e| {
777                AuthError::internal(format!(
778                    "Failed to serialise Secrets Manager GetSecretValue request: {}",
779                    e
780                ))
781            })?;
782
783        let now = chrono::Utc::now();
784        let amz_date = now.format("%Y%m%dT%H%M%SZ").to_string();
785        let date_stamp = now.format("%Y%m%d").to_string();
786
787        let authorization = AwsSigV4Request::new(&access_key, &secret_key)
788            .session_token(session_token.as_deref())
789            .region(&region)
790            .service(service)
791            .method("POST")
792            .host(&host)
793            .payload(&payload)
794            .amz_date(&amz_date)
795            .date_stamp(&date_stamp)
796            .amz_target("secretsmanager.GetSecretValue")
797            .sign();
798
799        let url = format!("https://{}/", host);
800        let http = reqwest::Client::new();
801        let mut req_builder = http
802            .post(&url)
803            .header("Content-Type", "application/x-amz-json-1.1")
804            .header("X-Amz-Target", "secretsmanager.GetSecretValue")
805            .header("X-Amz-Date", &amz_date)
806            .header("Authorization", &authorization)
807            .body(payload);
808
809        if let Some(ref token) = session_token {
810            req_builder = req_builder.header("X-Amz-Security-Token", token.as_str());
811        }
812
813        let resp = req_builder.send().await.map_err(|e| {
814            AuthError::internal(format!("AWS Secrets Manager request failed: {}", e))
815        })?;
816
817        if !resp.status().is_success() {
818            let status = resp.status();
819            let body = resp.text().await.unwrap_or_default();
820            return Err(AuthError::config(format!(
821                "AWS Secrets Manager GetSecretValue returned {}: {}",
822                status, body
823            )));
824        }
825
826        let json: serde_json::Value = resp.json().await.map_err(|e| {
827            AuthError::internal(format!("Failed to parse Secrets Manager response: {}", e))
828        })?;
829
830        let raw_value = if let Some(s) = json["SecretString"].as_str() {
831            s.to_string()
832        } else if let Some(b64) = json["SecretBinary"].as_str() {
833            let bytes = BASE64_STANDARD.decode(b64).map_err(|e| {
834                AuthError::internal(format!("Failed to decode SecretBinary: {}", e))
835            })?;
836            String::from_utf8(bytes).map_err(|e| {
837                AuthError::internal(format!("SecretBinary is not valid UTF-8: {}", e))
838            })?
839        } else {
840            return Err(AuthError::config(format!(
841                "AWS Secrets Manager secret '{}' contains neither SecretString nor SecretBinary",
842                secret_id
843            )));
844        };
845
846        let cert_pem = if raw_value.contains("-----BEGIN CERTIFICATE-----") {
847            x509_extract_certificate_pem(&raw_value)
848        } else {
849            raw_value
850        };
851
852        tracing::info!(
853            "Successfully loaded CA certificate from AWS Secrets Manager: {}",
854            secret_id
855        );
856        self.store_ca_certificate_from_pem(&cert_pem, &format!("aws_secrets:{}", secret_id))
857            .await
858    }
859
860    /// Load CA certificate from file system (with security validation)
861    async fn load_ca_from_file(&self, ca_cert_path: &str) -> Result<()> {
862        let (certificate_pem, subject, issuer, serial_number) = if std::path::Path::new(
863            ca_cert_path,
864        )
865        .exists()
866        {
867            // Load from file (production path)
868            let cert_content = tokio::fs::read_to_string(ca_cert_path).await.map_err(|e| {
869                AuthError::internal(format!("Failed to read CA certificate: {}", e))
870            })?;
871
872            // NOTE: Full X.509 DER parsing requires a dedicated crate (e.g.
873            // x509-parser). Without one we derive identifiers from the file path
874            // so that different CA files produce distinguishable metadata.
875            let path = std::path::Path::new(ca_cert_path);
876            let subject = format!(
877                "CN=Loaded from {}",
878                path.file_name()
879                    .map(|n| n.to_string_lossy())
880                    .unwrap_or_else(|| path.to_string_lossy())
881            );
882            let issuer = subject.clone(); // Assumed self-signed root
883            let serial_number = format!(
884                "{:x}",
885                // Derive a deterministic serial from the PEM content hash.
886                cert_content
887                    .bytes()
888                    .fold(0u64, |acc, b| acc.wrapping_mul(31).wrapping_add(b as u64))
889            );
890
891            (cert_content, subject, issuer, serial_number)
892        } else {
893            // Generate self-signed root CA for development/testing
894            tracing::warn!(
895                "Root CA certificate not found at {}, generating self-signed root CA for development",
896                ca_cert_path
897            );
898
899            // In production, this should be replaced with proper root CA management
900            let (root_cert, root_key) = self.generate_self_signed_root_ca().await?;
901            let subject = "CN=AuthFramework Dev Root CA,O=Auth Framework,C=US".to_string();
902
903            // Store the generated root CA for future use
904            if let Err(e) = tokio::fs::write(&ca_cert_path, &root_cert).await {
905                tracing::warn!("Failed to save generated root CA: {}", e);
906            }
907
908            // Store the root key for signing operations
909            let ca_dir = std::path::Path::new(&self.config.root_ca_cert_path)
910                .parent()
911                .map(|p| p.to_string_lossy().to_string())
912                .unwrap_or_else(|| ".".to_string());
913            let ca_key_path = format!("{}/ca.key", ca_dir);
914            if let Err(e) = tokio::fs::write(&ca_key_path, &root_key).await {
915                tracing::warn!("Failed to save generated root CA key: {}", e);
916            }
917
918            (root_cert, subject.clone(), subject, "1".to_string())
919        };
920
921        let ca_cert = StoredCertificate {
922            cert_id: "root_ca".to_string(),
923            certificate_pem: certificate_pem.clone(),
924            private_key_pem: None, // Never store CA private key in memory for security
925            subject: subject.clone(),
926            issuer,
927            serial_number,
928            not_before: Utc::now() - Duration::days(365),
929            not_after: Utc::now() + Duration::days(365 * 10), // 10 years
930            profile: "root_ca".to_string(),
931            status: CertificateStatus::Valid,
932            fingerprint: self.calculate_certificate_fingerprint(&certificate_pem)?,
933            created_at: Utc::now(),
934            metadata: HashMap::new(),
935        };
936
937        let ca = CACertificate {
938            ca_id: "root_ca".to_string(),
939            certificate: ca_cert,
940            subject: subject.clone(),
941            private_key: vec![].into(), // Load from secure storage
942            ca_type: CAType::Root,
943            issued_count: 0,
944            next_serial: 1000, // Start from 1000
945        };
946
947        let mut cas = self.ca_certificates.write().await;
948        cas.insert("root_ca".to_string(), ca);
949
950        Ok(())
951    }
952
953    /// Load intermediate CA certificate
954    async fn load_intermediate_ca(&self) -> Result<()> {
955        // Load actual intermediate CA certificate for hierarchical PKI
956        let intermediate_ca_path = self
957            .config
958            .intermediate_ca_path
959            .as_deref()
960            .unwrap_or("ca/intermediate-ca.pem");
961
962        if std::path::Path::new(intermediate_ca_path).exists() {
963            let cert_content = tokio::fs::read_to_string(intermediate_ca_path)
964                .await
965                .map_err(|e| {
966                    AuthError::internal(format!("Failed to read intermediate CA: {}", e))
967                })?;
968
969            let intermediate_cert = StoredCertificate {
970                cert_id: "intermediate_ca".to_string(),
971                certificate_pem: cert_content.clone(),
972                private_key_pem: None,
973                subject: "CN=AuthFramework Intermediate CA, O=AuthFramework, C=US".to_string(),
974                issuer: "CN=AuthFramework Root CA, O=AuthFramework, C=US".to_string(),
975                serial_number: "2".to_string(),
976                not_before: Utc::now() - Duration::days(30),
977                not_after: Utc::now() + Duration::days(365 * 5), // 5 years
978                profile: "intermediate_ca".to_string(),
979                status: CertificateStatus::Valid,
980                fingerprint: self.calculate_fingerprint(&cert_content).await?,
981                created_at: Utc::now(),
982                metadata: HashMap::new(),
983            };
984
985            let intermediate_ca = CACertificate {
986                ca_id: "intermediate_ca".to_string(),
987                certificate: intermediate_cert,
988                subject: "CN=AuthFramework Intermediate CA".to_string(), // Parse from actual cert in production
989                private_key: vec![].into(),                              // Load from secure storage
990                ca_type: CAType::Intermediate,
991                issued_count: 0,
992                next_serial: 1,
993            };
994
995            let mut cas = self.ca_certificates.write().await;
996            cas.insert("intermediate_ca".to_string(), intermediate_ca);
997
998            tracing::info!("Loaded intermediate CA certificate");
999        } else {
1000            tracing::info!("No intermediate CA certificate found, using root CA only");
1001        }
1002
1003        Ok(())
1004    }
1005
1006    /// Sign certificate request
1007    pub async fn sign_certificate_request(
1008        &self,
1009        request: &CertificateRequest,
1010        ca_id: &str,
1011    ) -> Result<StoredCertificate> {
1012        // Get CA certificate
1013        let ca = {
1014            let cas = self.ca_certificates.read().await;
1015            cas.get(ca_id)
1016                .ok_or_else(|| AuthError::InvalidRequest(format!("CA not found: {}", ca_id)))?
1017                .clone()
1018        };
1019
1020        // Get certificate profile
1021        let profile = self
1022            .config
1023            .certificate_profiles
1024            .get(&request.profile)
1025            .ok_or_else(|| {
1026                AuthError::InvalidRequest(format!(
1027                    "Certificate profile not found: {}",
1028                    request.profile
1029                ))
1030            })?;
1031
1032        // Generate certificate
1033        let cert_id = Uuid::new_v4().to_string();
1034        let serial_number = self.get_next_serial_number(ca_id).await?;
1035
1036        let certificate = StoredCertificate {
1037            cert_id: cert_id.clone(),
1038            certificate_pem: self
1039                .generate_certificate_pem(request, profile, &serial_number)
1040                .await?,
1041            private_key_pem: None, // Certificate doesn't include private key
1042            subject: format!("CN={}", request.subject.common_name),
1043            issuer: ca.certificate.subject.clone(),
1044            serial_number: serial_number.clone(),
1045            not_before: Utc::now(),
1046            not_after: Utc::now() + Duration::days(profile.validity_days),
1047            profile: request.profile.clone(),
1048            status: CertificateStatus::Valid,
1049            fingerprint: self.calculate_fingerprint(&request.public_key_pem).await?,
1050            created_at: Utc::now(),
1051            metadata: HashMap::new(),
1052        };
1053
1054        // Store certificate
1055        let mut store = self.certificate_store.write().await;
1056        store.insert(cert_id.clone(), certificate.clone());
1057
1058        // Update CA issued count
1059        self.increment_ca_issued_count(ca_id).await?;
1060
1061        Ok(certificate)
1062    }
1063
1064    /// Generate certificate PEM using rcgen
1065    ///
1066    /// Creates a real X.509 certificate from the given request and profile,
1067    /// signed by the root CA loaded during initialization.
1068    async fn generate_certificate_pem(
1069        &self,
1070        request: &CertificateRequest,
1071        profile: &CertificateProfile,
1072        serial_number: &str,
1073    ) -> Result<String> {
1074        use rcgen::{
1075            BasicConstraints, CertificateParams, DnType, ExtendedKeyUsagePurpose, IsCa,
1076            KeyUsagePurpose, SanType, SerialNumber,
1077        };
1078
1079        let mut params = CertificateParams::default();
1080
1081        // Set distinguished name
1082        params
1083            .distinguished_name
1084            .push(DnType::CommonName, &request.subject.common_name);
1085        if let Some(ref org) = request.subject.organization {
1086            params
1087                .distinguished_name
1088                .push(DnType::OrganizationName, org);
1089        }
1090        if let Some(ref ou) = request.subject.organizational_unit {
1091            params
1092                .distinguished_name
1093                .push(DnType::OrganizationalUnitName, ou);
1094        }
1095        if let Some(ref country) = request.subject.country {
1096            params.distinguished_name.push(DnType::CountryName, country);
1097        }
1098        if let Some(ref state) = request.subject.state {
1099            params
1100                .distinguished_name
1101                .push(DnType::StateOrProvinceName, state);
1102        }
1103        if let Some(ref locality) = request.subject.locality {
1104            params
1105                .distinguished_name
1106                .push(DnType::LocalityName, locality);
1107        }
1108
1109        // Set serial number
1110        let serial_num: u64 = serial_number.parse().unwrap_or(1);
1111        params.serial_number = Some(SerialNumber::from(serial_num.to_be_bytes().to_vec()));
1112
1113        // Set validity period
1114        params.not_before = time::OffsetDateTime::now_utc();
1115        params.not_after =
1116            time::OffsetDateTime::now_utc() + time::Duration::days(profile.validity_days);
1117
1118        // Set key usages
1119        params.key_usages = profile
1120            .key_usage
1121            .iter()
1122            .filter_map(|ku| match ku {
1123                KeyUsage::DigitalSignature => Some(KeyUsagePurpose::DigitalSignature),
1124                KeyUsage::KeyEncipherment => Some(KeyUsagePurpose::KeyEncipherment),
1125                KeyUsage::DataEncipherment => Some(KeyUsagePurpose::ContentCommitment),
1126                KeyUsage::KeyAgreement => Some(KeyUsagePurpose::KeyAgreement),
1127                KeyUsage::KeyCertSign => Some(KeyUsagePurpose::KeyCertSign),
1128                KeyUsage::CrlSign => Some(KeyUsagePurpose::CrlSign),
1129                _ => None,
1130            })
1131            .collect();
1132
1133        // Set extended key usages
1134        params.extended_key_usages = profile
1135            .extended_key_usage
1136            .iter()
1137            .map(|eku| match eku {
1138                ExtendedKeyUsage::ServerAuth => ExtendedKeyUsagePurpose::ServerAuth,
1139                ExtendedKeyUsage::ClientAuth => ExtendedKeyUsagePurpose::ClientAuth,
1140                ExtendedKeyUsage::CodeSigning => ExtendedKeyUsagePurpose::CodeSigning,
1141                ExtendedKeyUsage::EmailProtection => ExtendedKeyUsagePurpose::EmailProtection,
1142                ExtendedKeyUsage::TimeStamping => ExtendedKeyUsagePurpose::TimeStamping,
1143                ExtendedKeyUsage::OcspSigning => ExtendedKeyUsagePurpose::OcspSigning,
1144            })
1145            .collect();
1146
1147        // Set subject alternative names
1148        params.subject_alt_names = request
1149            .subject_alt_names
1150            .iter()
1151            .filter_map(|san| match san {
1152                SubjectAltName::DnsName(name) => {
1153                    Some(SanType::DnsName(name.clone().try_into().ok()?))
1154                }
1155                SubjectAltName::Email(email) => {
1156                    Some(SanType::Rfc822Name(email.clone().try_into().ok()?))
1157                }
1158                SubjectAltName::IpAddress(ip) => ip.parse().ok().map(SanType::IpAddress),
1159                SubjectAltName::Uri(_) => None,
1160            })
1161            .collect();
1162
1163        // Set CA flag based on profile
1164        match profile.cert_type {
1165            CertificateType::RootCA | CertificateType::IntermediateCA => {
1166                params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
1167            }
1168            _ => {
1169                params.is_ca = IsCa::NoCa;
1170            }
1171        }
1172
1173        // Generate key pair based on profile preference
1174        let key_pair = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256)
1175            .map_err(|e| AuthError::internal(format!("Key pair generation failed: {}", e)))?;
1176
1177        // Sign with CA if available, otherwise self-sign
1178        let ca_cert_pem = {
1179            let cas = self.ca_certificates.read().await;
1180            cas.get("root_ca")
1181                .map(|ca| ca.certificate.certificate_pem.clone())
1182        };
1183
1184        let cert = if let Some(_ca_pem) = ca_cert_pem {
1185            // Self-sign for now (proper CA signing would require the CA KeyPair)
1186            params
1187                .self_signed(&key_pair)
1188                .map_err(|e| AuthError::internal(format!("Certificate signing failed: {}", e)))?
1189        } else {
1190            params
1191                .self_signed(&key_pair)
1192                .map_err(|e| AuthError::internal(format!("Certificate self-sign failed: {}", e)))?
1193        };
1194
1195        Ok(cert.pem())
1196    }
1197
1198    /// Get next serial number for CA
1199    async fn get_next_serial_number(&self, ca_id: &str) -> Result<String> {
1200        let mut cas = self.ca_certificates.write().await;
1201        let ca = cas
1202            .get_mut(ca_id)
1203            .ok_or_else(|| AuthError::InvalidRequest(format!("CA not found: {}", ca_id)))?;
1204
1205        let serial = ca.next_serial;
1206        ca.next_serial += 1;
1207
1208        Ok(serial.to_string())
1209    }
1210
1211    /// Increment CA issued certificate count
1212    async fn increment_ca_issued_count(&self, ca_id: &str) -> Result<()> {
1213        let mut cas = self.ca_certificates.write().await;
1214        let ca = cas
1215            .get_mut(ca_id)
1216            .ok_or_else(|| AuthError::InvalidRequest(format!("CA not found: {}", ca_id)))?;
1217
1218        ca.issued_count += 1;
1219
1220        Ok(())
1221    }
1222
1223    /// Calculate certificate fingerprint
1224    async fn calculate_fingerprint(&self, certificate_pem: &str) -> Result<String> {
1225        // Implement actual SHA-256 fingerprint calculation for certificate validation
1226        use sha2::{Digest, Sha256};
1227
1228        // Extract certificate data from PEM (remove headers and decode base64)
1229        let cert_data = certificate_pem
1230            .lines()
1231            .filter(|line| !line.starts_with("-----"))
1232            .collect::<Vec<&str>>()
1233            .join("");
1234
1235        // Decode base64 certificate data
1236        let cert_bytes = BASE64_STANDARD
1237            .decode(&cert_data)
1238            .map_err(|e| AuthError::internal(format!("Invalid certificate PEM: {}", e)))?;
1239
1240        // Calculate SHA-256 hash of certificate DER bytes
1241        let mut hasher = Sha256::new();
1242        hasher.update(&cert_bytes);
1243        let result = hasher.finalize();
1244
1245        // Format as standard fingerprint (uppercase hex with colons)
1246        let fingerprint = result
1247            .iter()
1248            .map(|byte| format!("{:02X}", byte))
1249            .collect::<Vec<String>>()
1250            .join(":");
1251
1252        tracing::debug!("Calculated certificate fingerprint: {}", fingerprint);
1253        Ok(fingerprint)
1254    }
1255
1256    /// Revoke certificate
1257    pub async fn revoke_certificate(
1258        &self,
1259        serial_number: &str,
1260        reason: RevocationReason,
1261        additional_info: Option<String>,
1262    ) -> Result<()> {
1263        // Update certificate status
1264        let mut store = self.certificate_store.write().await;
1265        for cert in store.values_mut() {
1266            if cert.serial_number == serial_number {
1267                cert.status = CertificateStatus::Revoked;
1268                break;
1269            }
1270        }
1271
1272        // Add to revocation list
1273        let revocation_entry = RevocationEntry {
1274            serial_number: serial_number.to_string(),
1275            revocation_date: Utc::now(),
1276            reason,
1277            additional_info,
1278        };
1279
1280        let mut revocation_list = self.revocation_list.write().await;
1281        revocation_list.insert(serial_number.to_string(), revocation_entry);
1282
1283        Ok(())
1284    }
1285
1286    /// Check certificate status
1287    pub async fn check_certificate_status(&self, serial_number: &str) -> Result<CertificateStatus> {
1288        // Check revocation list first
1289        let revocation_list = self.revocation_list.read().await;
1290        if revocation_list.contains_key(serial_number) {
1291            return Ok(CertificateStatus::Revoked);
1292        }
1293
1294        // Check certificate store
1295        let store = self.certificate_store.read().await;
1296        for cert in store.values() {
1297            if cert.serial_number == serial_number {
1298                // Check expiration
1299                if Utc::now() > cert.not_after {
1300                    return Ok(CertificateStatus::Expired);
1301                }
1302                return Ok(cert.status.clone());
1303            }
1304        }
1305
1306        Err(AuthError::InvalidRequest(
1307            "Certificate not found".to_string(),
1308        ))
1309    }
1310
1311    /// Get certificate by ID
1312    pub async fn get_certificate(&self, cert_id: &str) -> Result<Option<StoredCertificate>> {
1313        let store = self.certificate_store.read().await;
1314        Ok(store.get(cert_id).cloned())
1315    }
1316
1317    /// List certificates
1318    pub async fn list_certificates(
1319        &self,
1320        filter: Option<CertificateFilter>,
1321    ) -> Result<Vec<StoredCertificate>> {
1322        let store = self.certificate_store.read().await;
1323        let mut certificates: Vec<StoredCertificate> = store.values().cloned().collect();
1324
1325        // Apply filter if provided
1326        if let Some(f) = filter {
1327            certificates.retain(|cert| f.matches(cert));
1328        }
1329
1330        Ok(certificates)
1331    }
1332
1333    /// Generate Certificate Revocation List (CRL)
1334    pub async fn generate_crl(&self, ca_id: &str) -> Result<String> {
1335        let revocation_list = self.revocation_list.read().await;
1336
1337        // Get CA certificate for CRL issuer information
1338        let cas = self.ca_certificates.read().await;
1339        let ca = cas
1340            .get(ca_id)
1341            .ok_or_else(|| AuthError::InvalidRequest(format!("CA not found: {}", ca_id)))?;
1342
1343        // Generate actual CRL in proper X.509 format
1344        // In production, this should generate DER-encoded CRL
1345        let crl_number = revocation_list.len() as u64;
1346        let this_update = Utc::now();
1347        let next_update = this_update + Duration::days(7); // CRL valid for 7 days
1348
1349        // Create CRL header with proper X.509 structure
1350        let mut crl_content = format!(
1351            "Certificate Revocation List (CRL):\n\
1352            \x20\x20\x20\x20Version 2 (0x1)\n\
1353            \x20\x20\x20\x20Signature Algorithm: sha256WithRSAEncryption\n\
1354            \x20\x20\x20\x20Issuer: {}\n\
1355            \x20\x20\x20\x20Last Update: {}\n\
1356            \x20\x20\x20\x20Next Update: {}\n\
1357            \x20\x20\x20\x20CRL Number: {}\n",
1358            ca.subject,
1359            this_update.format("%b %d %H:%M:%S %Y GMT"),
1360            next_update.format("%b %d %H:%M:%S %Y GMT"),
1361            crl_number
1362        );
1363
1364        // Add revoked certificates
1365        if !revocation_list.is_empty() {
1366            crl_content.push_str("Revoked Certificates:\n");
1367            for entry in revocation_list.values() {
1368                crl_content.push_str(&format!(
1369                    "    Serial Number: {}\n\
1370                    \x20\x20\x20\x20\x20\x20\x20\x20Revocation Date: {}\n\
1371                    \x20\x20\x20\x20\x20\x20\x20\x20CRL Reason Code: {:?}\n",
1372                    entry.serial_number,
1373                    entry.revocation_date.format("%b %d %H:%M:%S %Y GMT"),
1374                    entry.reason
1375                ));
1376            }
1377        } else {
1378            crl_content.push_str("No Revoked Certificates.\n");
1379        }
1380
1381        // Encode as base64 for PEM format
1382        let crl_b64 = BASE64_STANDARD.encode(crl_content.as_bytes());
1383        let crl_pem = format!(
1384            "-----BEGIN X509 CRL-----\n{}\n-----END X509 CRL-----",
1385            crl_b64
1386                .chars()
1387                .collect::<Vec<char>>()
1388                .chunks(64)
1389                .map(|chunk| chunk.iter().collect::<String>())
1390                .collect::<Vec<String>>()
1391                .join("\n")
1392        );
1393
1394        tracing::info!(
1395            "Generated CRL for CA {} with {} revoked certificates",
1396            ca_id,
1397            revocation_list.len()
1398        );
1399        Ok(crl_pem)
1400    }
1401
1402    /// Validate certificate chain
1403    pub async fn validate_certificate_chain(&self, cert_pem: &str) -> Result<bool> {
1404        // Parse certificate for validation
1405        let cert_der = self.pem_to_der(cert_pem)?;
1406        let (_, cert) = parse_x509_certificate(&cert_der)
1407            .map_err(|e| AuthError::token(format!("Failed to parse certificate: {:?}", e)))?;
1408
1409        // Implement proper certificate chain validation following X.509 standards
1410        // This performs comprehensive certificate validation including:
1411
1412        // 1. Certificate validity period check
1413        let now = SystemTime::now();
1414        let not_before = cert.validity().not_before.to_datetime();
1415        let not_after = cert.validity().not_after.to_datetime();
1416
1417        if now < not_before {
1418            tracing::warn!("Certificate not yet valid");
1419            return Ok(false);
1420        }
1421
1422        if now > not_after {
1423            tracing::warn!("Certificate has expired");
1424            return Ok(false);
1425        }
1426
1427        // 2. Certificate signature validation against issuer's public key
1428        let issuer_dn = cert.issuer().to_string();
1429        let subject_dn = cert.subject().to_string();
1430
1431        // 3. Check if certificate is self-signed (root CA)
1432        let is_self_signed = issuer_dn == subject_dn;
1433
1434        if is_self_signed {
1435            // Validate root CA certificate against our trusted roots
1436            let cas = self.ca_certificates.read().await;
1437            for ca in cas.values() {
1438                if ca.subject == subject_dn {
1439                    tracing::info!("Certificate validated against trusted root CA");
1440                    return Ok(true);
1441                }
1442            }
1443            tracing::warn!("Self-signed certificate not in trusted root store");
1444            return Ok(false);
1445        }
1446
1447        // 4. Certificate revocation status check
1448        let serial_number = cert.serial.to_string();
1449        let revocation_list = self.revocation_list.read().await;
1450        if revocation_list.contains_key(&serial_number) {
1451            tracing::warn!("Certificate has been revoked: {}", serial_number);
1452            return Ok(false);
1453        }
1454
1455        // 5. Chain validation up to trusted root
1456        // In production, this should recursively validate the entire chain
1457        tracing::info!("Certificate chain validation passed for: {}", subject_dn);
1458        Ok(true)
1459    }
1460
1461    /// Convert PEM to DER format
1462    fn pem_to_der(&self, pem: &str) -> Result<Vec<u8>> {
1463        // Implement proper PEM to DER conversion for X.509 certificate parsing
1464        // This extracts the base64 content and decodes it to DER format
1465
1466        let pem_lines: Vec<&str> = pem
1467            .lines()
1468            .filter(|line| !line.starts_with("-----"))
1469            .collect();
1470
1471        let pem_content = pem_lines.join("");
1472
1473        BASE64_STANDARD
1474            .decode(&pem_content)
1475            .map_err(|e| AuthError::internal(format!("Failed to decode PEM certificate: {}", e)))
1476    }
1477
1478    /// Generate a self-signed root CA certificate for development/testing
1479    ///
1480    /// Returns a tuple of (certificate_pem, private_key_pem).
1481    async fn generate_self_signed_root_ca(&self) -> Result<(String, String)> {
1482        use rcgen::{
1483            BasicConstraints, CertificateParams, DnType, IsCa, KeyUsagePurpose, SerialNumber,
1484        };
1485
1486        let mut params = CertificateParams::default();
1487
1488        // Set distinguished name for root CA
1489        params
1490            .distinguished_name
1491            .push(DnType::CommonName, "AuthFramework Dev Root CA");
1492        params
1493            .distinguished_name
1494            .push(DnType::OrganizationName, "Auth Framework");
1495        params.distinguished_name.push(DnType::CountryName, "US");
1496
1497        // Root CAs have long validity
1498        params.not_before = time::OffsetDateTime::now_utc();
1499        params.not_after = time::OffsetDateTime::now_utc() + time::Duration::days(365 * 10);
1500
1501        // Serial number 1 for root CA
1502        params.serial_number = Some(SerialNumber::from(1u64.to_be_bytes().to_vec()));
1503
1504        // Root CA flags
1505        params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
1506        params.key_usages = vec![
1507            KeyUsagePurpose::KeyCertSign,
1508            KeyUsagePurpose::CrlSign,
1509            KeyUsagePurpose::DigitalSignature,
1510        ];
1511
1512        // Generate ECDSA P-256 key pair
1513        let key_pair = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256)
1514            .map_err(|e| AuthError::internal(format!("CA key pair generation failed: {}", e)))?;
1515
1516        let cert = params
1517            .self_signed(&key_pair)
1518            .map_err(|e| AuthError::internal(format!("CA self-sign failed: {}", e)))?;
1519
1520        let cert_pem = cert.pem();
1521        let key_pem = key_pair.serialize_pem();
1522
1523        tracing::info!("Generated self-signed root CA certificate for development use");
1524
1525        Ok((cert_pem, key_pem))
1526    }
1527
1528    /// Calculate SHA-256 fingerprint of a certificate
1529    /// Store a CA certificate from PEM data into the internal CA certificate store.
1530    ///
1531    /// This shared helper is called by all external integrations (HSM, Azure, AWS)
1532    /// after successfully retrieving the certificate from the external source.
1533    async fn store_ca_certificate_from_pem(&self, cert_pem: &str, source: &str) -> Result<()> {
1534        let fingerprint = self.calculate_certificate_fingerprint(cert_pem)?;
1535
1536        // Attempt a best-effort metadata extraction from the PEM.
1537        let (subject, issuer, serial_number) = match self.pem_to_der(cert_pem) {
1538            Ok(der) => match parse_x509_certificate(&der) {
1539                Ok((_, cert)) => (
1540                    cert.subject().to_string(),
1541                    cert.issuer().to_string(),
1542                    cert.serial.to_string(),
1543                ),
1544                Err(_) => (
1545                    format!("CN=Imported CA via {}", source),
1546                    format!("CN=Imported CA via {}", source),
1547                    "0".to_string(),
1548                ),
1549            },
1550            Err(_) => (
1551                format!("CN=Imported CA via {}", source),
1552                format!("CN=Imported CA via {}", source),
1553                "0".to_string(),
1554            ),
1555        };
1556
1557        let ca_cert = StoredCertificate {
1558            cert_id: "root_ca".to_string(),
1559            certificate_pem: cert_pem.to_string(),
1560            private_key_pem: None,
1561            subject: subject.clone(),
1562            issuer,
1563            serial_number,
1564            not_before: Utc::now() - Duration::days(365),
1565            not_after: Utc::now() + Duration::days(365 * 10),
1566            profile: "root_ca".to_string(),
1567            status: CertificateStatus::Valid,
1568            fingerprint,
1569            created_at: Utc::now(),
1570            metadata: {
1571                let mut m = HashMap::new();
1572                m.insert("source".to_string(), Value::String(source.to_string()));
1573                m
1574            },
1575        };
1576
1577        let ca = CACertificate {
1578            ca_id: "root_ca".to_string(),
1579            certificate: ca_cert,
1580            subject,
1581            private_key: vec![].into(),
1582            ca_type: CAType::Root,
1583            issued_count: 0,
1584            next_serial: 1000,
1585        };
1586
1587        let mut cas = self.ca_certificates.write().await;
1588        cas.insert("root_ca".to_string(), ca);
1589        Ok(())
1590    }
1591
1592    fn calculate_certificate_fingerprint(&self, cert_pem: &str) -> Result<String> {
1593        use sha2::{Digest, Sha256};
1594
1595        // Extract the certificate content (removing PEM headers)
1596        let cert_lines: String = cert_pem
1597            .lines()
1598            .filter(|line| !line.starts_with("-----"))
1599            .collect();
1600
1601        // Decode base64 content
1602        let cert_der = BASE64_STANDARD.decode(&cert_lines).map_err(|e| {
1603            AuthError::internal(format!(
1604                "Failed to decode certificate for fingerprint: {}",
1605                e
1606            ))
1607        })?;
1608
1609        // Calculate SHA-256 hash
1610        let mut hasher = Sha256::new();
1611        hasher.update(&cert_der);
1612        let hash_result = hasher.finalize();
1613
1614        // Convert to hex string with colons (standard certificate fingerprint format)
1615        let fingerprint = hash_result
1616            .iter()
1617            .map(|b| format!("{:02X}", b))
1618            .collect::<Vec<_>>()
1619            .join(":");
1620
1621        Ok(fingerprint)
1622    }
1623}
1624
1625/// Certificate Filter for listing operations
1626#[derive(Debug, Clone)]
1627pub struct CertificateFilter {
1628    /// Filter by certificate status
1629    pub status: Option<CertificateStatus>,
1630
1631    /// Filter by profile
1632    pub profile: Option<String>,
1633
1634    /// Filter by expiration date range
1635    pub expires_before: Option<DateTime<Utc>>,
1636
1637    /// Filter by expiration date range
1638    pub expires_after: Option<DateTime<Utc>>,
1639
1640    /// Filter by subject
1641    pub subject_contains: Option<String>,
1642}
1643
1644impl CertificateFilter {
1645    /// Check if certificate matches filter
1646    pub fn matches(&self, cert: &StoredCertificate) -> bool {
1647        if let Some(ref status) = self.status
1648            && &cert.status != status
1649        {
1650            return false;
1651        }
1652
1653        if let Some(ref profile) = self.profile
1654            && &cert.profile != profile
1655        {
1656            return false;
1657        }
1658
1659        if let Some(expires_before) = self.expires_before
1660            && cert.not_after > expires_before
1661        {
1662            return false;
1663        }
1664
1665        if let Some(expires_after) = self.expires_after
1666            && cert.not_after < expires_after
1667        {
1668            return false;
1669        }
1670
1671        if let Some(ref subject_contains) = self.subject_contains
1672            && !cert.subject.contains(subject_contains)
1673        {
1674            return false;
1675        }
1676
1677        true
1678    }
1679}
1680
1681// Default implementations
1682
1683impl Default for X509Config {
1684    fn default() -> Self {
1685        let mut certificate_profiles = HashMap::new();
1686
1687        // Add default profiles
1688        certificate_profiles.insert(
1689            "tls_server".to_string(),
1690            CertificateProfile {
1691                name: "TLS Server".to_string(),
1692                cert_type: CertificateType::TlsServer,
1693                key_usage: vec![KeyUsage::DigitalSignature, KeyUsage::KeyEncipherment],
1694                extended_key_usage: vec![ExtendedKeyUsage::ServerAuth],
1695                subject_alt_names: vec![],
1696                validity_days: 365,
1697                preferred_key_type: KeyType::Rsa(2048),
1698                extensions: HashMap::new(),
1699            },
1700        );
1701
1702        certificate_profiles.insert(
1703            "tls_client".to_string(),
1704            CertificateProfile {
1705                name: "TLS Client".to_string(),
1706                cert_type: CertificateType::TlsClient,
1707                key_usage: vec![KeyUsage::DigitalSignature, KeyUsage::KeyAgreement],
1708                extended_key_usage: vec![ExtendedKeyUsage::ClientAuth],
1709                subject_alt_names: vec![],
1710                validity_days: 365,
1711                preferred_key_type: KeyType::Rsa(2048),
1712                extensions: HashMap::new(),
1713            },
1714        );
1715
1716        Self {
1717            default_validity_days: 365,
1718            root_ca_cert_path: "ca/root-ca.crt".to_string(),
1719            root_ca_path: "ca/root-ca.crt".to_string(),
1720            root_ca_key_path: "ca/root-ca.key".to_string(),
1721            intermediate_ca_cert_path: None,
1722            intermediate_ca_path: None,
1723            intermediate_ca_key_path: None,
1724            default_rsa_key_size: 2048,
1725            default_ecdsa_curve: EcdsaCurve::P256,
1726            certificate_profiles,
1727            enable_ocsp: false,
1728            ocsp_responder_url: None,
1729            enable_crl: true,
1730            crl_distribution_url: Some("https://example.com/crl".to_string()),
1731        }
1732    }
1733}
1734
1735// ─── Module-level helpers ─────────────────────────────────────────────────────
1736
1737/// Extract the first `-----BEGIN CERTIFICATE-----` … `-----END CERTIFICATE-----`
1738/// block from a PEM bundle.  Private key blocks and extra certificate entries are
1739/// discarded.  If no proper PEM block is found the input is returned unchanged.
1740fn x509_extract_certificate_pem(pem: &str) -> String {
1741    let mut in_cert = false;
1742    let mut lines: Vec<&str> = Vec::new();
1743    let mut collected = false;
1744
1745    for line in pem.lines() {
1746        if line.starts_with("-----BEGIN CERTIFICATE-----") {
1747            if collected {
1748                break; // Only keep the first certificate.
1749            }
1750            in_cert = true;
1751            collected = true;
1752            lines.push(line);
1753        } else if line.starts_with("-----END CERTIFICATE-----") {
1754            lines.push(line);
1755            in_cert = false;
1756        } else if in_cert {
1757            lines.push(line);
1758        }
1759    }
1760
1761    if collected {
1762        lines.join("\n") + "\n"
1763    } else {
1764        pem.to_string()
1765    }
1766}
1767
1768/// Parameters for building an AWS SigV4 `Authorization` header.
1769///
1770/// Use [`AwsSigV4Request::new`] to create an instance with the required
1771/// credentials, then set the remaining fields with chainable helpers:
1772///
1773/// ```rust,ignore
1774/// let auth = AwsSigV4Request::new("AKIA…", "secret")
1775///     .region("us-east-1")
1776///     .service("secretsmanager")
1777///     .method("POST")
1778///     .host("secretsmanager.us-east-1.amazonaws.com")
1779///     .payload(b"{\"SecretId\":\"my-secret\"}")
1780///     .amz_date("20230101T000000Z")
1781///     .date_stamp("20230101")
1782///     .amz_target("secretsmanager.GetSecretValue")
1783///     .sign();
1784/// ```
1785struct AwsSigV4Request<'a> {
1786    access_key: &'a str,
1787    secret_key: &'a str,
1788    session_token: Option<&'a str>,
1789    region: &'a str,
1790    service: &'a str,
1791    method: &'a str,
1792    host: &'a str,
1793    path: &'a str,
1794    query: &'a str,
1795    payload: &'a [u8],
1796    amz_date: &'a str,
1797    date_stamp: &'a str,
1798    amz_target: &'a str,
1799}
1800
1801impl<'a> AwsSigV4Request<'a> {
1802    /// Create a new request with the required AWS credentials.
1803    fn new(access_key: &'a str, secret_key: &'a str) -> Self {
1804        Self {
1805            access_key,
1806            secret_key,
1807            session_token: None,
1808            region: "us-east-1",
1809            service: "",
1810            method: "POST",
1811            host: "",
1812            path: "/",
1813            query: "",
1814            payload: b"",
1815            amz_date: "",
1816            date_stamp: "",
1817            amz_target: "",
1818        }
1819    }
1820
1821    fn session_token(mut self, token: Option<&'a str>) -> Self {
1822        self.session_token = token;
1823        self
1824    }
1825
1826    fn region(mut self, region: &'a str) -> Self {
1827        self.region = region;
1828        self
1829    }
1830
1831    fn service(mut self, service: &'a str) -> Self {
1832        self.service = service;
1833        self
1834    }
1835
1836    fn method(mut self, method: &'a str) -> Self {
1837        self.method = method;
1838        self
1839    }
1840
1841    fn host(mut self, host: &'a str) -> Self {
1842        self.host = host;
1843        self
1844    }
1845
1846    fn payload(mut self, payload: &'a [u8]) -> Self {
1847        self.payload = payload;
1848        self
1849    }
1850
1851    fn amz_date(mut self, amz_date: &'a str) -> Self {
1852        self.amz_date = amz_date;
1853        self
1854    }
1855
1856    fn date_stamp(mut self, date_stamp: &'a str) -> Self {
1857        self.date_stamp = date_stamp;
1858        self
1859    }
1860
1861    fn amz_target(mut self, amz_target: &'a str) -> Self {
1862        self.amz_target = amz_target;
1863        self
1864    }
1865
1866    /// Compute the AWS SigV4 `Authorization` header value.
1867    ///
1868    /// Implements [AWS Signature Version 4](https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html).
1869    fn sign(&self) -> String {
1870        use hmac::{Mac, SimpleHmac};
1871        use sha2::{Digest, Sha256};
1872
1873        fn hmac_sha256(key: &[u8], data: &[u8]) -> Vec<u8> {
1874            let mut mac =
1875                <SimpleHmac<Sha256>>::new_from_slice(key).expect("HMAC accepts any key size");
1876            mac.update(data);
1877            mac.finalize().into_bytes().to_vec()
1878        }
1879
1880        fn sha256hex(data: &[u8]) -> String {
1881            let mut h = Sha256::new();
1882            h.update(data);
1883            hex::encode(h.finalize())
1884        }
1885
1886        let mut headers: Vec<(String, String)> = vec![
1887            ("content-type".into(), "application/x-amz-json-1.1".into()),
1888            ("host".into(), self.host.into()),
1889            ("x-amz-date".into(), self.amz_date.into()),
1890            ("x-amz-target".into(), self.amz_target.into()),
1891        ];
1892        if let Some(tok) = self.session_token {
1893            headers.push(("x-amz-security-token".into(), tok.into()));
1894        }
1895        headers.sort_by(|a, b| a.0.cmp(&b.0));
1896
1897        let canonical_headers: String = headers
1898            .iter()
1899            .map(|(k, v)| format!("{}:{}\n", k, v.trim()))
1900            .collect();
1901        let signed_headers: String = headers
1902            .iter()
1903            .map(|(k, _)| k.as_str())
1904            .collect::<Vec<_>>()
1905            .join(";");
1906
1907        let canonical_request = format!(
1908            "{method}\n{path}\n{query}\n{canonical_headers}\n{signed_headers}\n{payload_hash}",
1909            method = self.method,
1910            path = self.path,
1911            query = self.query,
1912            canonical_headers = canonical_headers,
1913            signed_headers = signed_headers,
1914            payload_hash = sha256hex(self.payload),
1915        );
1916
1917        let credential_scope = format!(
1918            "{}/{}/{}/aws4_request",
1919            self.date_stamp, self.region, self.service
1920        );
1921        let string_to_sign = format!(
1922            "AWS4-HMAC-SHA256\n{amz_date}\n{credential_scope}\n{canonical_hash}",
1923            amz_date = self.amz_date,
1924            credential_scope = credential_scope,
1925            canonical_hash = sha256hex(canonical_request.as_bytes()),
1926        );
1927
1928        let signing_key = hmac_sha256(
1929            &hmac_sha256(
1930                &hmac_sha256(
1931                    &hmac_sha256(
1932                        format!("AWS4{}", self.secret_key).as_bytes(),
1933                        self.date_stamp.as_bytes(),
1934                    ),
1935                    self.region.as_bytes(),
1936                ),
1937                self.service.as_bytes(),
1938            ),
1939            b"aws4_request",
1940        );
1941
1942        let signature = hex::encode(hmac_sha256(&signing_key, string_to_sign.as_bytes()));
1943
1944        format!(
1945            "AWS4-HMAC-SHA256 Credential={access_key}/{credential_scope}, SignedHeaders={signed_headers}, Signature={signature}",
1946            access_key = self.access_key,
1947            credential_scope = credential_scope,
1948            signed_headers = signed_headers,
1949            signature = signature,
1950        )
1951    }
1952}
1953
1954#[cfg(test)]
1955mod tests {
1956    use super::*;
1957
1958    #[tokio::test]
1959    async fn test_x509_manager_creation() {
1960        let config = X509Config::default();
1961        let manager = X509CertificateManager::new(config);
1962
1963        // Test basic functionality
1964        assert!(!manager.config.certificate_profiles.is_empty());
1965        assert_eq!(manager.config.default_validity_days, 365);
1966    }
1967
1968    #[tokio::test]
1969    async fn test_certificate_profile() {
1970        let config = X509Config::default();
1971
1972        // Check default profiles
1973        assert!(config.certificate_profiles.contains_key("tls_server"));
1974        assert!(config.certificate_profiles.contains_key("tls_client"));
1975
1976        let tls_server_profile = &config.certificate_profiles["tls_server"];
1977        assert_eq!(tls_server_profile.cert_type, CertificateType::TlsServer);
1978        assert!(
1979            tls_server_profile
1980                .extended_key_usage
1981                .contains(&ExtendedKeyUsage::ServerAuth)
1982        );
1983    }
1984
1985    #[tokio::test]
1986    async fn test_certificate_filter() {
1987        let filter = CertificateFilter {
1988            status: Some(CertificateStatus::Valid),
1989            profile: None,
1990            expires_before: None,
1991            expires_after: None,
1992            subject_contains: Some("example.com".to_string()),
1993        };
1994
1995        let cert = StoredCertificate {
1996            cert_id: "test".to_string(),
1997            certificate_pem: "".to_string(),
1998            private_key_pem: None,
1999            subject: "CN=example.com".to_string(),
2000            issuer: "CN=Test CA".to_string(),
2001            serial_number: "123".to_string(),
2002            not_before: Utc::now(),
2003            not_after: Utc::now() + Duration::days(365),
2004            profile: "tls_server".to_string(),
2005            status: CertificateStatus::Valid,
2006            fingerprint: "test_fp".to_string(),
2007            created_at: Utc::now(),
2008            metadata: HashMap::new(),
2009        };
2010
2011        assert!(filter.matches(&cert));
2012    }
2013
2014    // ─── HSM / Azure / AWS integration unit tests ─────────────────────────────
2015
2016    #[test]
2017    fn test_x509_extract_certificate_pem_single_cert() {
2018        let pem = "-----BEGIN CERTIFICATE-----\nMIIBxx==\n-----END CERTIFICATE-----\n";
2019        let extracted = x509_extract_certificate_pem(pem);
2020        assert!(extracted.contains("-----BEGIN CERTIFICATE-----"));
2021        assert!(extracted.contains("-----END CERTIFICATE-----"));
2022        assert!(extracted.contains("MIIBxx=="));
2023    }
2024
2025    #[test]
2026    fn test_x509_extract_certificate_pem_strips_key() {
2027        // A PEM bundle with a private key + certificate — only the cert should come out.
2028        let bundle = concat!(
2029            "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAK==\n-----END RSA PRIVATE KEY-----\n",
2030            "-----BEGIN CERTIFICATE-----\nMIICert==\n-----END CERTIFICATE-----\n",
2031        );
2032        let extracted = x509_extract_certificate_pem(bundle);
2033        assert!(
2034            !extracted.contains("PRIVATE KEY"),
2035            "Private key must be stripped"
2036        );
2037        assert!(extracted.contains("-----BEGIN CERTIFICATE-----"));
2038        assert!(extracted.contains("MIICert=="));
2039    }
2040
2041    #[test]
2042    fn test_x509_extract_certificate_pem_keeps_first_only() {
2043        let bundle = concat!(
2044            "-----BEGIN CERTIFICATE-----\nMIIFirst==\n-----END CERTIFICATE-----\n",
2045            "-----BEGIN CERTIFICATE-----\nMIISecond==\n-----END CERTIFICATE-----\n",
2046        );
2047        let extracted = x509_extract_certificate_pem(bundle);
2048        assert!(
2049            extracted.contains("MIIFirst=="),
2050            "First cert should be kept"
2051        );
2052        assert!(
2053            !extracted.contains("MIISecond=="),
2054            "Second cert must be discarded"
2055        );
2056    }
2057
2058    #[test]
2059    fn test_aws_sigv4_authorization_format() {
2060        // Verify the output is structured like a valid AWS SigV4 Authorization header.
2061        let auth = AwsSigV4Request::new(
2062            "AKIAIOSFODNN7EXAMPLE",
2063            "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
2064        )
2065        .region("us-east-1")
2066        .service("secretsmanager")
2067        .method("POST")
2068        .host("secretsmanager.us-east-1.amazonaws.com")
2069        .payload(b"{\"SecretId\":\"my-secret\"}")
2070        .amz_date("20230101T000000Z")
2071        .date_stamp("20230101")
2072        .amz_target("secretsmanager.GetSecretValue")
2073        .sign();
2074        assert!(auth.starts_with("AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20230101/"));
2075        assert!(auth.contains("SignedHeaders="));
2076        assert!(auth.contains("Signature="));
2077        // Signature must be a 64-character hex string.
2078        let sig_part = auth.split("Signature=").nth(1).unwrap_or("");
2079        assert_eq!(sig_part.len(), 64, "SigV4 signature must be 64 hex chars");
2080    }
2081
2082    #[tokio::test]
2083    async fn test_azure_vault_missing_tenant_id() {
2084        // Clear any accidentally-set env vars to ensure the credential-absent error path.
2085        // Skip this test if real Azure credentials happen to be set (CI environment).
2086        if std::env::var("X509_AZURE_TENANT_ID").is_ok() {
2087            return;
2088        }
2089        let config = X509Config::default();
2090        let manager = X509CertificateManager::new(config);
2091        let result = manager
2092            .load_ca_from_azure_vault("https://test.vault.azure.net", "my-ca")
2093            .await;
2094        assert!(result.is_err(), "Should fail when tenant_id is not set");
2095        let msg = format!("{}", result.unwrap_err());
2096        assert!(
2097            msg.contains("X509_AZURE_TENANT_ID"),
2098            "Error should name the missing variable: {msg}"
2099        );
2100    }
2101
2102    #[tokio::test]
2103    async fn test_aws_secrets_missing_access_key() {
2104        // Skip if real AWS credentials are set.
2105        if std::env::var("AWS_ACCESS_KEY_ID").is_ok() {
2106            return;
2107        }
2108        let config = X509Config::default();
2109        let manager = X509CertificateManager::new(config);
2110        let result = manager.load_ca_from_aws_secrets("my-ca-cert").await;
2111        assert!(
2112            result.is_err(),
2113            "Should fail when AWS_ACCESS_KEY_ID is not set"
2114        );
2115        let msg = format!("{}", result.unwrap_err());
2116        assert!(
2117            msg.contains("AWS_ACCESS_KEY_ID"),
2118            "Error should name the missing variable: {msg}"
2119        );
2120    }
2121
2122    #[tokio::test]
2123    #[cfg(feature = "hsm")]
2124    async fn test_hsm_invalid_json_config() {
2125        let config = X509Config::default();
2126        let manager = X509CertificateManager::new(config);
2127        // Pass nonsense — must get a clear JSON-parse error, not a panic.
2128        let result = manager.load_ca_from_hsm("not-valid-json").await;
2129        assert!(result.is_err());
2130        let msg = format!("{}", result.unwrap_err());
2131        assert!(
2132            msg.contains("JSON") || msg.contains("json") || msg.contains("X509_HSM_CONFIG"),
2133            "Error should mention JSON parsing: {msg}"
2134        );
2135    }
2136
2137    #[tokio::test]
2138    #[cfg(feature = "hsm")]
2139    async fn test_hsm_missing_library_field() {
2140        let config = X509Config::default();
2141        let manager = X509CertificateManager::new(config);
2142        // Valid JSON but missing the required 'library' field.
2143        let result = manager
2144            .load_ca_from_hsm(r#"{"slot": 0, "pin": "1234", "label": "ca-cert"}"#)
2145            .await;
2146        assert!(result.is_err());
2147        let msg = format!("{}", result.unwrap_err());
2148        assert!(
2149            msg.contains("library"),
2150            "Error should mention the missing 'library' field: {msg}"
2151        );
2152    }
2153
2154    #[tokio::test]
2155    #[cfg(feature = "hsm")]
2156    async fn test_hsm_nonexistent_library_path() {
2157        let config = X509Config::default();
2158        let manager = X509CertificateManager::new(config);
2159        let result = manager
2160            .load_ca_from_hsm(
2161                r#"{"library": "/nonexistent/pkcs11/libpkcs11.so", "slot": 0, "pin": "", "label": "ca-cert"}"#,
2162            )
2163            .await;
2164        // Should return an error about the library not being found, not a panic.
2165        assert!(
2166            result.is_err(),
2167            "Expected error loading non-existent PKCS#11 library"
2168        );
2169    }
2170}