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//!
25//! # Honesty rules
26//!
27//! Nothing here claims cryptography it does not perform. A CA certificate is only
28//! accepted if it parses and is a usable CA; its metadata is read from the certificate
29//! itself; a CA can sign only if its private key was loaded (and matches the certificate);
30//! issued certificates carry the requester's public key and are signed by the CA; the
31//! revocation list is a signed DER CRL; and chain validation is done by `rustls-webpki`
32//! against the configured CAs. Where an operation cannot be done it returns an error, and a
33//! setting that is accepted is honoured or rejected rather than ignored, with the few
34//! exceptions listed under "Settings that are only labels or recorded".
35//!
36//! # Who authorises what
37//!
38//! The manager enforces *form*, not *entitlement*. A request is a bare public key plus
39//! requested names, so there is no proof that the requester holds the key and no check that the
40//! requester may have the names: **the caller must authenticate the requester and authorise the
41//! subject, the SANs, the profile and the key before calling `sign_certificate_request`.** What
42//! the manager does enforce is a policy on what can be asked for: text fields of bounded length
43//! without control or formatting (for example bidirectional) characters, a two-letter country
44//! code, DNS names that are real multi-label host names (no `localhost`, no bare labels),
45//! wildcard / IP address / URI / e-mail names only when the profile's [`SanPolicy`] allows
46//! them, URIs only with the schemes `http`, `https`, `urn` and `spiffe`, and subject keys that
47//! are well-formed RSA of 2048 to 16384 bits (odd modulus, odd public exponent of at least
48//! 65537), ECDSA P-256 / P-384 (a valid point on the curve) or Ed25519 (32 bytes), and at least
49//! as strong as the profile's `preferred_key_type`. Not checked: that the CN matches a SAN, and
50//! whether a wildcard sits under a public suffix (`*.co.uk`): leave `wildcard_dns` off unless
51//! the requester is trusted with it.
52//!
53//! # State
54//!
55//! **The certificate store and the revocation list live in memory.** Without
56//! [`X509Config::state_path`] a restart forgets every issued certificate and every revocation
57//! (`initialize` logs a warning); the stores are also unbounded, so a long-running issuer
58//! should rotate them. With `state_path` set the state is loaded at `initialize` and rewritten
59//! (to a temporary file that is synced and renamed over the old one, and the directory synced
60//! where the platform allows) after every issuance, revocation and CRL; if that fails the
61//! operation fails (a revocation that cannot be saved still stays in force in memory). A state
62//! file that exists but cannot be read or parsed stops `initialize`, so an unreadable file is
63//! never mistaken for an empty one. **A file that has been deleted or replaced by an older copy
64//! cannot be detected**: protect it like the CA key's directory, and back it up. The file is
65//! written by one manager at a time: **two managers or processes sharing one `state_path`
66//! overwrite each other's updates**; give each issuer its own file. Writing the whole file on
67//! every change is fine for hundreds of certificates, not for millions.
68//! [`load_state`](X509CertificateManager::load_state) merges (it never removes a revocation or
69//! lowers a CRL number). Without a state file, [`save_state`](X509CertificateManager::save_state)
70//! exports the state and
71//! [`revoke_certificate_pem`](X509CertificateManager::revoke_certificate_pem) revokes from the
72//! certificate itself.
73//!
74//! # Settings that are only labels or recorded
75//!
76//! `CertificateProfile::name` and `CertificateRequest::requested_at` are labels / recorded in
77//! the stored certificate's metadata (`request_id` is recorded after a length and character
78//! check); `CertificateProfile::cert_type` decides whether a profile is a CA profile (refused
79//! for issuance) and which extended key usage it must list. When `X509_HSM_CONFIG`,
80//! `X509_AZURE_VAULT_URL` or `X509_AWS_SECRET_ID` select an external root CA, `root_ca_path`,
81//! `root_ca_cert_path` and `root_ca_key_path` are not used (a warning is logged), the CA
82//! signs nothing (its key stays with the source), and the HSM configuration's `label` field is
83//! the PKCS#11 object label only.
84
85use crate::errors::{AuthError, Result};
86use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD};
87use chrono::{DateTime, Duration, Utc};
88use serde::{Deserialize, Serialize};
89use serde_json::Value;
90use std::collections::HashMap;
91use std::fmt;
92use std::sync::Arc;
93use tokio::sync::RwLock;
94use uuid::Uuid;
95use x509_parser::parse_x509_certificate;
96use zeroize::Zeroizing;
97
98/// Enhanced X.509 Certificate Manager
99#[derive(Debug, Clone)]
100pub struct X509CertificateManager {
101    /// Configuration
102    config: X509Config,
103
104    /// Certificate store
105    certificate_store: Arc<RwLock<HashMap<String, StoredCertificate>>>,
106
107    /// Certificate revocation list
108    revocation_list: Arc<RwLock<HashMap<String, RevocationEntry>>>,
109
110    /// CA certificates
111    ca_certificates: Arc<RwLock<HashMap<String, CACertificate>>>,
112
113    /// Last CRL number issued per CA
114    crl_numbers: Arc<RwLock<HashMap<String, u64>>>,
115
116    /// Serialises writes of the state file
117    persist_lock: Arc<tokio::sync::Mutex<()>>,
118}
119
120/// X.509 Configuration
121#[derive(Debug, Clone)]
122pub struct X509Config {
123    /// Validity period (days) for a profile that does not set its own (`validity_days == 0`)
124    pub default_validity_days: i64,
125
126    /// Root CA certificate path
127    pub root_ca_cert_path: String,
128
129    /// Root CA certificate path (alias)
130    pub root_ca_path: String,
131
132    /// Root CA private key path
133    pub root_ca_key_path: String,
134
135    /// Intermediate CA certificate path
136    pub intermediate_ca_cert_path: Option<String>,
137
138    /// Intermediate CA certificate path (alias)
139    pub intermediate_ca_path: Option<String>,
140
141    /// Intermediate CA private key path
142    pub intermediate_ca_key_path: Option<String>,
143
144    /// Certificate profiles
145    pub certificate_profiles: HashMap<String, CertificateProfile>,
146
147    /// OCSP is not implemented: `initialize` fails if this is `true`
148    pub enable_ocsp: bool,
149
150    /// OCSP responder URL (not implemented; must stay `None` while `enable_ocsp` is `false`)
151    pub ocsp_responder_url: Option<String>,
152
153    /// Enable CRL (Certificate Revocation List); `generate_crl` fails when `false`
154    pub enable_crl: bool,
155
156    /// CRL distribution point URL, placed in every issued certificate when set
157    /// (`http://` or `https://`)
158    pub crl_distribution_url: Option<String>,
159
160    /// File that keeps the certificate store, the revocation list and the CRL numbers across
161    /// restarts. Unset means the state is volatile (see the module documentation).
162    pub state_path: Option<String>,
163
164    /// Development only: allow `initialize` to create a root CA (certificate and key, written
165    /// to the configured paths) when the root certificate file does not exist. Off by default,
166    /// so a missing root file is an error and never silently becomes a new trust anchor.
167    pub generate_development_root_ca: bool,
168}
169
170/// ECDSA Curve types
171#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
172pub enum EcdsaCurve {
173    /// P-256 (secp256r1)
174    P256,
175    /// P-384 (secp384r1)
176    P384,
177    /// P-521 (secp521r1)
178    P521,
179}
180
181/// Certificate Profile for different use cases
182#[derive(Debug, Clone, Serialize, Deserialize)]
183pub struct CertificateProfile {
184    /// Profile name
185    pub name: String,
186
187    /// Certificate type
188    pub cert_type: CertificateType,
189
190    /// Key usage flags
191    pub key_usage: Vec<KeyUsage>,
192
193    /// Extended key usage
194    pub extended_key_usage: Vec<ExtendedKeyUsage>,
195
196    /// Subject alternative names added to every certificate of this profile (in addition to
197    /// the requested ones; each is checked by the same policy)
198    pub subject_alt_names: Vec<SubjectAltName>,
199
200    /// Which kinds of requested subject alternative names this profile accepts
201    #[serde(default)]
202    pub san_policy: SanPolicy,
203
204    /// Validity period (days); `0` means `X509Config::default_validity_days`, negative is refused
205    pub validity_days: i64,
206
207    /// Minimum key strength: a subject key is accepted if it is on the allow-list (RSA of at
208    /// least 2048 bits, ECDSA P-256 / P-384 / P-521, Ed25519) and at least as strong as this
209    pub preferred_key_type: KeyType,
210
211    /// Additional extensions (not supported: a profile with any is refused at issuance)
212    pub extensions: HashMap<String, Value>,
213}
214
215/// Which kinds of requested subject alternative names a profile accepts. Plain DNS names are
216/// always allowed (they must be real multi-label host names); everything else is opt-in.
217#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
218pub struct SanPolicy {
219    /// Allow a wildcard DNS name (`*.example.com`, left-most label only)
220    pub wildcard_dns: bool,
221    /// Allow IP address names (never unspecified, loopback or multicast addresses)
222    pub ip_address: bool,
223    /// Allow URI names
224    pub uri: bool,
225    /// Allow e-mail names, and the request's subject e-mail address
226    pub email: bool,
227}
228
229/// The purpose a certificate chain is validated for.
230#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
231pub enum CertificatePurpose {
232    /// TLS server authentication
233    ServerAuth,
234    /// TLS client authentication
235    ClientAuth,
236    /// Code signing
237    CodeSigning,
238    /// E-mail protection
239    EmailProtection,
240    /// Time stamping
241    TimeStamping,
242    /// OCSP response signing
243    OcspSigning,
244}
245
246/// Certificate Types
247#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
248pub enum CertificateType {
249    /// Root Certificate Authority
250    RootCA,
251    /// Intermediate Certificate Authority
252    IntermediateCA,
253    /// End entity certificate (leaf)
254    EndEntity,
255    /// Code signing certificate
256    CodeSigning,
257    /// Email certificate
258    Email,
259    /// TLS server certificate
260    TlsServer,
261    /// TLS client certificate
262    TlsClient,
263    /// Document signing certificate
264    DocumentSigning,
265}
266
267/// Key Usage flags
268#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
269pub enum KeyUsage {
270    /// Digital signature
271    DigitalSignature,
272    /// Non-repudiation
273    NonRepudiation,
274    /// Key encipherment
275    KeyEncipherment,
276    /// Data encipherment
277    DataEncipherment,
278    /// Key agreement
279    KeyAgreement,
280    /// Key certificate signing
281    KeyCertSign,
282    /// CRL signing
283    CrlSign,
284    /// Encipher only
285    EncipherOnly,
286    /// Decipher only
287    DecipherOnly,
288}
289
290/// Extended Key Usage
291#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
292pub enum ExtendedKeyUsage {
293    /// Server authentication
294    ServerAuth,
295    /// Client authentication
296    ClientAuth,
297    /// Code signing
298    CodeSigning,
299    /// Email protection
300    EmailProtection,
301    /// Time stamping
302    TimeStamping,
303    /// OCSP signing
304    OcspSigning,
305}
306
307/// Subject Alternative Name types
308#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
309pub enum SubjectAltName {
310    /// DNS name
311    DnsName(String),
312    /// Email address
313    Email(String),
314    /// URI
315    Uri(String),
316    /// IP address
317    IpAddress(String),
318}
319
320/// Key Types
321#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
322pub enum KeyType {
323    /// RSA key
324    Rsa(u32), // Key size in bits
325    /// ECDSA key
326    Ecdsa(EcdsaCurve),
327    /// Ed25519 key
328    Ed25519,
329}
330
331/// Stored Certificate
332#[derive(Debug, Clone, Serialize, Deserialize)]
333pub struct StoredCertificate {
334    /// Certificate ID
335    pub cert_id: String,
336
337    /// Certificate data (PEM format)
338    pub certificate_pem: String,
339
340    /// Private key (PEM format, optional)
341    pub private_key_pem: Option<String>,
342
343    /// Certificate subject
344    pub subject: String,
345
346    /// Certificate issuer
347    pub issuer: String,
348
349    /// Serial number
350    pub serial_number: String,
351
352    /// Not before date
353    pub not_before: DateTime<Utc>,
354
355    /// Not after date
356    pub not_after: DateTime<Utc>,
357
358    /// Certificate profile used
359    pub profile: String,
360
361    /// Certificate status
362    pub status: CertificateStatus,
363
364    /// Fingerprint (SHA-256)
365    pub fingerprint: String,
366
367    /// Created timestamp
368    pub created_at: DateTime<Utc>,
369
370    /// Metadata
371    pub metadata: HashMap<String, Value>,
372}
373
374/// Certificate Status
375#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
376pub enum CertificateStatus {
377    /// Certificate is valid
378    Valid,
379    /// Certificate is expired
380    Expired,
381    /// Certificate is revoked
382    Revoked,
383    /// Certificate is suspended
384    Suspended,
385}
386
387/// CA Certificate
388///
389/// Does not derive `Debug`: `private_key` holds the CA's raw signing key,
390/// and a derived `Debug` would print it verbatim on any accidental
391/// `{:?}`. The manual impl below redacts it.
392#[derive(Clone)]
393pub struct CACertificate {
394    /// CA ID
395    pub ca_id: String,
396
397    /// CA certificate
398    pub certificate: StoredCertificate,
399
400    /// Certificate subject
401    pub subject: String,
402
403    /// CA private key
404    pub private_key: Zeroizing<Vec<u8>>,
405
406    /// CA type
407    pub ca_type: CAType,
408
409    /// Issued certificates count
410    pub issued_count: u64,
411}
412
413impl fmt::Debug for CACertificate {
414    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
415        f.debug_struct("CACertificate")
416            .field("ca_id", &self.ca_id)
417            .field("certificate", &self.certificate)
418            .field("subject", &self.subject)
419            .field("private_key", &"[redacted]")
420            .field("ca_type", &self.ca_type)
421            .field("issued_count", &self.issued_count)
422            .finish()
423    }
424}
425
426/// CA Types
427#[derive(Debug, Clone, PartialEq)]
428pub enum CAType {
429    /// Root CA
430    Root,
431    /// Intermediate CA
432    Intermediate,
433}
434
435/// Certificate Revocation Entry
436#[derive(Debug, Clone, Serialize, Deserialize)]
437pub struct RevocationEntry {
438    /// Certificate serial number
439    pub serial_number: String,
440
441    /// Revocation date
442    pub revocation_date: DateTime<Utc>,
443
444    /// Revocation reason
445    pub reason: RevocationReason,
446
447    /// Additional information
448    pub additional_info: Option<String>,
449}
450
451/// Revocation Reasons (RFC 5280)
452#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
453pub enum RevocationReason {
454    /// Unspecified
455    Unspecified,
456    /// Key compromise
457    KeyCompromise,
458    /// CA compromise
459    CaCompromise,
460    /// Affiliation changed
461    AffiliationChanged,
462    /// Superseded
463    Superseded,
464    /// Cessation of operation
465    CessationOfOperation,
466    /// Certificate hold
467    CertificateHold,
468    /// Remove from CRL
469    RemoveFromCrl,
470    /// Privilege withdrawn
471    PrivilegeWithdrawn,
472    /// AA compromise
473    AaCompromise,
474}
475
476/// Certificate Signing Request
477#[derive(Debug, Clone, Serialize, Deserialize)]
478pub struct CertificateRequest {
479    /// Request ID
480    pub request_id: String,
481
482    /// Certificate subject information
483    pub subject: CertificateSubject,
484
485    /// Certificate profile to use
486    pub profile: String,
487
488    /// Public key (PEM format)
489    pub public_key_pem: String,
490
491    /// Subject alternative names
492    pub subject_alt_names: Vec<SubjectAltName>,
493
494    /// Request timestamp
495    pub requested_at: DateTime<Utc>,
496
497    /// Requester information
498    pub requester: String,
499
500    /// Additional attributes
501    pub attributes: HashMap<String, Value>,
502}
503
504/// Certificate Subject Information
505#[derive(Debug, Clone, Serialize, Deserialize)]
506pub struct CertificateSubject {
507    /// Common name
508    pub common_name: String,
509
510    /// Organization
511    pub organization: Option<String>,
512
513    /// Organizational unit
514    pub organizational_unit: Option<String>,
515
516    /// Country
517    pub country: Option<String>,
518
519    /// State/Province
520    pub state: Option<String>,
521
522    /// City/Locality
523    pub locality: Option<String>,
524
525    /// Email address
526    pub email: Option<String>,
527}
528
529impl X509CertificateManager {
530    /// Create new X.509 certificate manager
531    pub fn new(config: X509Config) -> Self {
532        Self {
533            config,
534            certificate_store: Arc::new(RwLock::new(HashMap::new())),
535            revocation_list: Arc::new(RwLock::new(HashMap::new())),
536            ca_certificates: Arc::new(RwLock::new(HashMap::new())),
537            crl_numbers: Arc::new(RwLock::new(HashMap::new())),
538            persist_lock: Arc::new(tokio::sync::Mutex::new(())),
539        }
540    }
541
542    /// Initialize certificate manager with CA certificates
543    ///
544    /// Fails if OCSP is enabled (not implemented), if a configured CA cannot be used, or if
545    /// `state_path` names a file that cannot be read back. Call it once, before issuing.
546    pub async fn initialize(&self) -> Result<()> {
547        if self.config.enable_ocsp || self.config.ocsp_responder_url.is_some() {
548            return Err(AuthError::config(
549                "OCSP is not implemented: set enable_ocsp = false and leave ocsp_responder_url unset"
550                    .to_string(),
551            ));
552        }
553        if let Some(url) = &self.config.crl_distribution_url {
554            check_distribution_url(url)?;
555        }
556        if self.config.intermediate_ca_key_path.is_some()
557            && self.config.intermediate_ca_cert_path.is_none()
558            && self.config.intermediate_ca_path.is_none()
559        {
560            return Err(AuthError::config(
561                "intermediate_ca_key_path is set but no intermediate CA certificate path is"
562                    .to_string(),
563            ));
564        }
565        for (name, profile) in &self.config.certificate_profiles {
566            validate_profile(name, profile)?;
567        }
568
569        // Load root CA certificate
570        self.load_root_ca().await?;
571
572        // Load intermediate CA certificate if configured
573        if self.config.intermediate_ca_cert_path.is_some()
574            || self.config.intermediate_ca_path.is_some()
575        {
576            self.load_intermediate_ca().await?;
577        }
578
579        match &self.config.state_path {
580            Some(path) => {
581                // `Path::exists` would turn a permission error into "no file", and an
582                // unreadable state file into an empty one.
583                match std::fs::exists(path) {
584                    Ok(true) => self.load_state(path).await?,
585                    Ok(false) => {}
586                    Err(e) => {
587                        return Err(AuthError::config(format!(
588                            "Cannot tell whether state file {} exists: {}",
589                            path, e
590                        )));
591                    }
592                }
593            }
594            None => tracing::warn!(
595                "X509CertificateManager has no state_path: issued certificates and revocations are \
596                 kept in memory only and are lost on restart"
597            ),
598        }
599        // Whatever the revocation list holds applies to the CAs just (re)loaded from files,
600        // with or without a state file.
601        self.refresh_after_revocation().await;
602
603        Ok(())
604    }
605
606    /// Mark the loaded CA certificates that the revocation list revokes.
607    async fn refresh_ca_revocations(&self) {
608        let cas: Vec<(String, Vec<u8>)> = self
609            .ca_certificates
610            .read()
611            .await
612            .values()
613            .filter_map(|ca| {
614                pem_certificates(&ca.certificate.certificate_pem)
615                    .ok()
616                    .map(|mut ders| (ca.ca_id.clone(), ders.remove(0)))
617            })
618            .collect();
619        for (ca_id, der) in cas {
620            if self.is_revoked(&der).await
621                && let Some(ca) = self.ca_certificates.write().await.get_mut(&ca_id)
622            {
623                ca.certificate.status = CertificateStatus::Revoked;
624            }
625        }
626    }
627
628    /// Make the stores agree with the revocation list: stored certificates and held CAs that
629    /// it revokes are marked revoked.
630    async fn refresh_after_revocation(&self) {
631        let revoked: std::collections::HashSet<(String, String)> = self
632            .revocation_list
633            .read()
634            .await
635            .keys()
636            .filter_map(|key| key.split_once('\u{0}'))
637            .map(|(ca_id, serial)| (ca_id.to_string(), serial.to_string()))
638            .collect();
639        for cert in self.certificate_store.write().await.values_mut() {
640            if let Some(ca_id) = cert.metadata.get("ca_id").and_then(|v| v.as_str())
641                && revoked.contains(&(ca_id.to_string(), cert.serial_number.clone()))
642            {
643                cert.status = CertificateStatus::Revoked;
644            }
645        }
646        self.refresh_ca_revocations().await;
647    }
648
649    /// Write the certificate store, the revocation list and the CRL numbers to `path`: to a
650    /// temporary file that is synced and then renamed over `path` (and the directory synced on
651    /// Unix). Only one write runs at a time; two managers sharing a path overwrite each other.
652    pub async fn save_state(&self, path: &str) -> Result<()> {
653        let _one_writer = self.persist_lock.lock().await;
654        let state = PersistedState {
655            version: 1,
656            certificates: self.certificate_store.read().await.clone(),
657            revocations: self.revocation_list.read().await.clone(),
658            crl_numbers: self.crl_numbers.read().await.clone(),
659        };
660        let json = serde_json::to_vec_pretty(&state)
661            .map_err(|e| AuthError::internal(format!("Failed to encode state: {e}")))?;
662        let target = path.to_string();
663        tokio::task::spawn_blocking(move || write_state_file(&target, &json))
664            .await
665            .map_err(|e| AuthError::internal(format!("State writer failed: {e}")))?
666    }
667
668    /// Merge the state saved in `path` into the current one: certificates and revocations are
669    /// added, a certificate revoked in either is revoked, and a CRL number is the larger of the
670    /// two. It can add but never remove a revocation or lower a number, so loading an old copy
671    /// cannot un-revoke. A file that cannot be read or parsed is an error and changes nothing.
672    pub async fn load_state(&self, path: &str) -> Result<()> {
673        let bytes = std::fs::read(path)
674            .map_err(|e| AuthError::config(format!("Failed to read state {}: {}", path, e)))?;
675        let state: PersistedState = serde_json::from_slice(&bytes)
676            .map_err(|e| AuthError::config(format!("State file {} is corrupt: {}", path, e)))?;
677        if state.version != 1 {
678            return Err(AuthError::config(format!(
679                "State file {} has unsupported version {}",
680                path, state.version
681            )));
682        }
683        {
684            let mut store = self.certificate_store.write().await;
685            for (id, loaded) in state.certificates {
686                match store.get_mut(&id) {
687                    Some(existing) => {
688                        if loaded.status == CertificateStatus::Revoked {
689                            existing.status = CertificateStatus::Revoked;
690                        }
691                    }
692                    None => {
693                        store.insert(id, loaded);
694                    }
695                }
696            }
697        }
698        {
699            let mut revocations = self.revocation_list.write().await;
700            for (key, entry) in state.revocations {
701                revocations.entry(key).or_insert(entry);
702            }
703        }
704        {
705            let mut numbers = self.crl_numbers.write().await;
706            for (ca_id, number) in state.crl_numbers {
707                let slot = numbers.entry(ca_id).or_insert(0);
708                *slot = (*slot).max(number);
709            }
710        }
711        self.refresh_after_revocation().await;
712        Ok(())
713    }
714
715    /// Write the state to `state_path` if one is configured.
716    async fn persist(&self) -> Result<()> {
717        match &self.config.state_path {
718            Some(path) => self.save_state(path).await,
719            None => Ok(()),
720        }
721    }
722
723    /// Load root CA certificate
724    async fn load_root_ca(&self) -> Result<()> {
725        // Production implementation: Load from secure certificate store or HSM
726        // Check for HSM configuration first
727        #[cfg(feature = "hsm")]
728        if let Ok(hsm_config) = std::env::var("X509_HSM_CONFIG") {
729            tracing::info!("Loading CA certificate from HSM: {}", hsm_config);
730            // In production, integrate with PKCS#11 or Azure Key Vault
731            return self.load_ca_from_hsm(&hsm_config).await;
732        }
733        #[cfg(not(feature = "hsm"))]
734        if std::env::var("X509_HSM_CONFIG").is_ok() {
735            tracing::warn!(
736                "X509_HSM_CONFIG is set but the 'hsm' feature is not enabled — ignoring"
737            );
738        }
739
740        // Check for Azure Key Vault configuration
741        if let Ok(vault_url) = std::env::var("X509_AZURE_VAULT_URL")
742            && let Ok(cert_name) = std::env::var("X509_AZURE_CERT_NAME")
743        {
744            tracing::warn!(
745                "X509_AZURE_VAULT_URL selects the root CA: root_ca_path / root_ca_cert_path / root_ca_key_path are not used"
746            );
747            tracing::info!("Loading CA certificate from Azure Key Vault: {}", vault_url);
748            return self.load_ca_from_azure_vault(&vault_url, &cert_name).await;
749        }
750
751        // Check for AWS Secrets Manager configuration
752        if let Ok(secret_id) = std::env::var("X509_AWS_SECRET_ID") {
753            tracing::warn!(
754                "X509_AWS_SECRET_ID selects the root CA: root_ca_path / root_ca_cert_path / root_ca_key_path are not used"
755            );
756            tracing::info!(
757                "Loading CA certificate from AWS Secrets Manager: {}",
758                secret_id
759            );
760            return self.load_ca_from_aws_secrets(&secret_id).await;
761        }
762
763        // Fallback to file system loading with proper security validation
764        let ca_cert_path = self.root_ca_certificate_path()?;
765
766        tracing::warn!(
767            "Loading CA certificate from file system - consider using HSM or secure vault for production"
768        );
769        self.load_ca_from_file(&ca_cert_path).await
770    }
771
772    /// Load CA certificate from HSM (Hardware Security Module) via PKCS#11.
773    ///
774    /// `hsm_config` must be a JSON object with the following fields:
775    /// - `library` (required): absolute path to the PKCS#11 shared library (`.so` / `.dll`)
776    /// - `slot` (optional, default `0`): slot index returned by `get_slots_with_initialized_token`
777    /// - `pin` (optional): User PIN for login (omit for login-less tokens)
778    /// - `label` (optional, default `"ca-cert"`): CKA_LABEL of the certificate object
779    ///
780    /// # Example config
781    /// ```text
782    /// {"library":"/usr/lib/softhsm/libsofthsm2.so","slot":0,"pin":"1234","label":"root-ca"}
783    /// ```
784    #[cfg(feature = "hsm")]
785    async fn load_ca_from_hsm(&self, hsm_config: &str) -> Result<()> {
786        let config: serde_json::Value = serde_json::from_str(hsm_config)
787            .map_err(|e| AuthError::config(format!("Invalid HSM JSON config: {}", e)))?;
788
789        let library = config["library"]
790            .as_str()
791            .ok_or_else(|| AuthError::config("HSM config missing 'library' path".to_string()))?;
792
793        // Extract optional parameters
794        let slot_id = config["slot"].as_u64().unwrap_or(0);
795        let pin = config["pin"].as_str().map(|s| s.to_string());
796        let _label = config["label"].as_str().unwrap_or("root-ca").to_string();
797
798        // Note: Real PKCS#11 operations are synchronous and may block.
799        // We use spawn_blocking to prevent blocking the async runtime.
800        let library_path = library.to_string();
801
802        let handle = tokio::task::spawn_blocking(move || -> Result<Vec<u8>> {
803            // First, initialize the PKCS#11 context
804            let pkcs11 = cryptoki::context::Pkcs11::new(&library_path)
805                .map_err(|e| AuthError::config(format!("Failed to load PKCS#11 library: {}", e)))?;
806
807            pkcs11
808                .initialize(cryptoki::context::CInitializeArgs::new(
809                    cryptoki::context::CInitializeFlags::OS_LOCKING_OK,
810                ))
811                .map_err(|e| {
812                    AuthError::config(format!("Failed to initialize PKCS#11 context: {}", e))
813                })?;
814
815            // Get slots
816            let slots = pkcs11
817                .get_slots_with_token()
818                .map_err(|e| AuthError::config(format!("Failed to get PKCS#11 slots: {}", e)))?;
819
820            if slot_id as usize >= slots.len() {
821                return Err(AuthError::config(format!(
822                    "HSM slot {} not found or has no token",
823                    slot_id
824                )));
825            }
826            let slot = slots[slot_id as usize];
827
828            // Open a session
829            let session = pkcs11
830                .open_ro_session(slot)
831                .map_err(|e| AuthError::config(format!("Failed to open PKCS#11 session: {}", e)))?;
832
833            // Login if PIN is provided
834            if let Some(p) = pin {
835                let auth_pin = cryptoki::types::AuthPin::new(p.into());
836                session
837                    .login(cryptoki::session::UserType::User, Some(&auth_pin))
838                    .map_err(|e| AuthError::config(format!("HSM login failed: {}", e)))?;
839            }
840
841            // Find the certificate object by label
842            let mut search_template: Vec<cryptoki::object::Attribute> = Vec::new();
843            search_template.push(cryptoki::object::Attribute::Class(
844                cryptoki::object::ObjectClass::CERTIFICATE,
845            ));
846            search_template.push(cryptoki::object::Attribute::Label(
847                _label.clone().into_bytes(),
848            ));
849
850            let objects = session.find_objects(&search_template).map_err(|e| {
851                AuthError::config(format!("Failed to search PKCS#11 objects: {}", e))
852            })?;
853
854            if objects.is_empty() {
855                return Err(AuthError::config(format!(
856                    "Certificate with label '{}' not found in HSM",
857                    _label
858                )));
859            }
860
861            // Read the certificate value (usually CKA_VALUE for X.509 certs)
862            let cert_obj = objects[0];
863            let attrs = session
864                .get_attributes(cert_obj, &[cryptoki::object::AttributeType::Value])
865                .map_err(|e| {
866                    AuthError::config(format!("Failed to get certificate value from HSM: {}", e))
867                })?;
868
869            if attrs.is_empty() {
870                return Err(AuthError::config(
871                    "Certificate object has no value attribute".to_string(),
872                ));
873            }
874
875            let value = match &attrs[0] {
876                cryptoki::object::Attribute::Value(v) => v.clone(),
877                _ => {
878                    return Err(AuthError::config(
879                        "Invalid value attribute type".to_string(),
880                    ));
881                }
882            };
883
884            Ok(value)
885        });
886
887        let cert_der = handle
888            .await
889            .map_err(|_| AuthError::config("HSM task panicked".to_string()))??;
890
891        // Convert the DER certificate bytes to PEM format and store via the
892        // shared helper that all external CA integrations use.
893        let cert_pem = format!(
894            "-----BEGIN CERTIFICATE-----\n{}\n-----END CERTIFICATE-----",
895            BASE64_STANDARD.encode(&cert_der)
896        );
897
898        self.store_ca_certificate_from_pem(&cert_pem, &format!("hsm:slot{}", slot_id))
899            .await
900    }
901
902    async fn load_ca_from_azure_vault(&self, vault_url: &str, cert_name: &str) -> Result<()> {
903        let tenant_id = std::env::var("X509_AZURE_TENANT_ID").map_err(|_| {
904            AuthError::config(
905                "X509_AZURE_TENANT_ID environment variable required for Azure Key Vault authentication"
906                    .to_string(),
907            )
908        })?;
909        let client_id = std::env::var("X509_AZURE_CLIENT_ID").map_err(|_| {
910            AuthError::config(
911                "X509_AZURE_CLIENT_ID environment variable required for Azure Key Vault authentication"
912                    .to_string(),
913            )
914        })?;
915        let client_secret = std::env::var("X509_AZURE_CLIENT_SECRET").map_err(|_| {
916            AuthError::config(
917                "X509_AZURE_CLIENT_SECRET environment variable required for Azure Key Vault authentication"
918                    .to_string(),
919            )
920        })?;
921
922        let http = reqwest::Client::new();
923
924        // Step 1: Client-credentials flow → access token.
925        let token_url = format!(
926            "https://login.microsoftonline.com/{}/oauth2/v2.0/token",
927            tenant_id
928        );
929        let token_resp = http
930            .post(&token_url)
931            .form(&[
932                ("grant_type", "client_credentials"),
933                ("client_id", client_id.as_str()),
934                ("client_secret", client_secret.as_str()),
935                ("scope", "https://vault.azure.net/.default"),
936            ])
937            .send()
938            .await
939            .map_err(|e| AuthError::internal(format!("Azure AD token request failed: {}", e)))?;
940
941        if !token_resp.status().is_success() {
942            let status = token_resp.status();
943            let body = token_resp.text().await.unwrap_or_default();
944            return Err(AuthError::config(format!(
945                "Azure AD token request returned {}: {}",
946                status, body
947            )));
948        }
949
950        let token_json: serde_json::Value = token_resp.json().await.map_err(|e| {
951            AuthError::internal(format!("Failed to parse Azure AD token response: {}", e))
952        })?;
953        let access_token = token_json["access_token"]
954            .as_str()
955            .ok_or_else(|| AuthError::internal("Azure AD response missing 'access_token'"))?
956            .to_string();
957
958        // Step 2: Fetch the secret from Key Vault (returns PEM / PKCS#12 bundle).
959        let vault_base = vault_url.trim_end_matches('/');
960        let secret_url = format!("{}/secrets/{}?api-version=7.4", vault_base, cert_name);
961        let cert_resp = http
962            .get(&secret_url)
963            .header("Authorization", format!("Bearer {}", access_token))
964            .send()
965            .await
966            .map_err(|e| AuthError::internal(format!("Azure Key Vault request failed: {}", e)))?;
967
968        if !cert_resp.status().is_success() {
969            let status = cert_resp.status();
970            let body = cert_resp.text().await.unwrap_or_default();
971            return Err(AuthError::config(format!(
972                "Azure Key Vault secret fetch returned {}: {}",
973                status, body
974            )));
975        }
976
977        let cert_json: serde_json::Value = cert_resp.json().await.map_err(|e| {
978            AuthError::internal(format!("Failed to parse Azure Key Vault response: {}", e))
979        })?;
980
981        let raw_value = cert_json["value"]
982            .as_str()
983            .ok_or_else(|| AuthError::internal("Azure Key Vault response missing 'value' field"))?
984            .to_string();
985
986        let content_type = cert_json["contentType"]
987            .as_str()
988            .unwrap_or("application/x-pem-file");
989
990        let cert_pem = if content_type == "application/x-pem-file"
991            || raw_value.contains("-----BEGIN")
992        {
993            // PEM bundle — extract only the leaf/CA certificate block.
994            x509_extract_certificate_pem(&raw_value)
995        } else {
996            return Err(AuthError::config(format!(
997                "Azure Key Vault certificate '{}' uses content-type '{}'. \
998                 Store the certificate as a PEM secret (application/x-pem-file) for automatic import.",
999                cert_name, content_type
1000            )));
1001        };
1002
1003        tracing::info!(
1004            "Successfully loaded CA certificate from Azure Key Vault: {}/{}",
1005            vault_base,
1006            cert_name
1007        );
1008        self.store_ca_certificate_from_pem(
1009            &cert_pem,
1010            &format!("azure_kv:{}/{}", vault_base, cert_name),
1011        )
1012        .await
1013    }
1014
1015    /// Load CA certificate from AWS Secrets Manager using AWS SigV4 request signing.
1016    ///
1017    /// Required environment variables (standard AWS credential chain):
1018    /// - `AWS_ACCESS_KEY_ID`
1019    /// - `AWS_SECRET_ACCESS_KEY`
1020    /// - `AWS_REGION` or `AWS_DEFAULT_REGION`
1021    /// - `AWS_SESSION_TOKEN` (optional, for temporary credentials)
1022    ///
1023    /// The secret value must be a PEM-encoded certificate (or a PEM bundle; the
1024    /// first `CERTIFICATE` block is extracted automatically).
1025    async fn load_ca_from_aws_secrets(&self, secret_id: &str) -> Result<()> {
1026        let access_key = std::env::var("AWS_ACCESS_KEY_ID").map_err(|_| {
1027            AuthError::config(
1028                "AWS_ACCESS_KEY_ID environment variable required for Secrets Manager".to_string(),
1029            )
1030        })?;
1031        let secret_key = std::env::var("AWS_SECRET_ACCESS_KEY").map_err(|_| {
1032            AuthError::config(
1033                "AWS_SECRET_ACCESS_KEY environment variable required for Secrets Manager"
1034                    .to_string(),
1035            )
1036        })?;
1037        let region = std::env::var("AWS_REGION")
1038            .or_else(|_| std::env::var("AWS_DEFAULT_REGION"))
1039            .map_err(|_| {
1040                AuthError::config(
1041                    "AWS_REGION (or AWS_DEFAULT_REGION) environment variable required for Secrets Manager"
1042                        .to_string(),
1043                )
1044            })?;
1045        let session_token = std::env::var("AWS_SESSION_TOKEN").ok();
1046
1047        let service = "secretsmanager";
1048        let host = format!("{}.{}.amazonaws.com", service, region);
1049        let payload =
1050            serde_json::to_vec(&serde_json::json!({ "SecretId": secret_id })).map_err(|e| {
1051                AuthError::internal(format!(
1052                    "Failed to serialise Secrets Manager GetSecretValue request: {}",
1053                    e
1054                ))
1055            })?;
1056
1057        let now = chrono::Utc::now();
1058        let amz_date = now.format("%Y%m%dT%H%M%SZ").to_string();
1059        let date_stamp = now.format("%Y%m%d").to_string();
1060
1061        let authorization = AwsSigV4Request::new(&access_key, &secret_key)
1062            .session_token(session_token.as_deref())
1063            .region(&region)
1064            .service(service)
1065            .method("POST")
1066            .host(&host)
1067            .payload(&payload)
1068            .amz_date(&amz_date)
1069            .date_stamp(&date_stamp)
1070            .amz_target("secretsmanager.GetSecretValue")
1071            .sign();
1072
1073        let url = format!("https://{}/", host);
1074        let http = reqwest::Client::new();
1075        let mut req_builder = http
1076            .post(&url)
1077            .header("Content-Type", "application/x-amz-json-1.1")
1078            .header("X-Amz-Target", "secretsmanager.GetSecretValue")
1079            .header("X-Amz-Date", &amz_date)
1080            .header("Authorization", &authorization)
1081            .body(payload);
1082
1083        if let Some(ref token) = session_token {
1084            req_builder = req_builder.header("X-Amz-Security-Token", token.as_str());
1085        }
1086
1087        let resp = req_builder.send().await.map_err(|e| {
1088            AuthError::internal(format!("AWS Secrets Manager request failed: {}", e))
1089        })?;
1090
1091        if !resp.status().is_success() {
1092            let status = resp.status();
1093            let body = resp.text().await.unwrap_or_default();
1094            return Err(AuthError::config(format!(
1095                "AWS Secrets Manager GetSecretValue returned {}: {}",
1096                status, body
1097            )));
1098        }
1099
1100        let json: serde_json::Value = resp.json().await.map_err(|e| {
1101            AuthError::internal(format!("Failed to parse Secrets Manager response: {}", e))
1102        })?;
1103
1104        let raw_value = if let Some(s) = json["SecretString"].as_str() {
1105            s.to_string()
1106        } else if let Some(b64) = json["SecretBinary"].as_str() {
1107            let bytes = BASE64_STANDARD.decode(b64).map_err(|e| {
1108                AuthError::internal(format!("Failed to decode SecretBinary: {}", e))
1109            })?;
1110            String::from_utf8(bytes).map_err(|e| {
1111                AuthError::internal(format!("SecretBinary is not valid UTF-8: {}", e))
1112            })?
1113        } else {
1114            return Err(AuthError::config(format!(
1115                "AWS Secrets Manager secret '{}' contains neither SecretString nor SecretBinary",
1116                secret_id
1117            )));
1118        };
1119
1120        let cert_pem = if raw_value.contains("-----BEGIN CERTIFICATE-----") {
1121            x509_extract_certificate_pem(&raw_value)
1122        } else {
1123            raw_value
1124        };
1125
1126        tracing::info!(
1127            "Successfully loaded CA certificate from AWS Secrets Manager: {}",
1128            secret_id
1129        );
1130        self.store_ca_certificate_from_pem(&cert_pem, &format!("aws_secrets:{}", secret_id))
1131            .await
1132    }
1133
1134    /// Path of the root CA certificate. `root_ca_path` and `root_ca_cert_path` name the same
1135    /// setting; if both are set they must agree.
1136    fn root_ca_certificate_path(&self) -> Result<String> {
1137        let (a, b) = (&self.config.root_ca_path, &self.config.root_ca_cert_path);
1138        match (a.is_empty(), b.is_empty()) {
1139            (true, true) => Ok("ca/root-ca.pem".to_string()),
1140            (false, true) => Ok(a.clone()),
1141            (true, false) => Ok(b.clone()),
1142            (false, false) if a == b => Ok(a.clone()),
1143            (false, false) => Err(AuthError::config(format!(
1144                "root_ca_path ({a}) and root_ca_cert_path ({b}) are the same setting and must agree"
1145            ))),
1146        }
1147    }
1148
1149    /// Read a CA certificate from PEM: the first certificate in the text must parse, be a
1150    /// usable CA, and be valid now. Returns its normalised PEM, DER and the facts read from it.
1151    fn parse_ca_pem(&self, pem: &str) -> Result<(String, Vec<u8>, CertificateFacts)> {
1152        let der = pem_certificates(pem)?.remove(0);
1153        ensure_ca_certificate(&der)?;
1154        let facts = certificate_facts(&der)?;
1155        Ok((der_to_pem(&der), der, facts))
1156    }
1157
1158    /// Load the CA signing key at `key_path`, if there is one. A key that exists must be
1159    /// usable and must belong to the certificate; a missing key leaves the CA verify-only.
1160    fn load_signing_key(key_path: &str, cert_der: &[u8]) -> Result<Zeroizing<Vec<u8>>> {
1161        if key_path.is_empty() || !std::path::Path::new(key_path).exists() {
1162            return Ok(Zeroizing::new(Vec::new()));
1163        }
1164        let bytes = Zeroizing::new(std::fs::read(key_path).map_err(|e| {
1165            AuthError::config(format!("Failed to read CA key {}: {}", key_path, e))
1166        })?);
1167        let text = std::str::from_utf8(&bytes)
1168            .map_err(|_| AuthError::config(format!("CA key {} is not PEM text", key_path)))?;
1169        let key = rcgen::KeyPair::from_pem(text).map_err(|e| {
1170            AuthError::config(format!(
1171                "CA key {} is not a usable private key: {}",
1172                key_path, e
1173            ))
1174        })?;
1175        let (_, cert) = parse_x509_certificate(cert_der)
1176            .map_err(|e| AuthError::config(format!("Invalid CA certificate: {e}")))?;
1177        if cert.public_key().subject_public_key.data.as_ref() != key.public_key_raw() {
1178            return Err(AuthError::config(format!(
1179                "CA key {} does not belong to the CA certificate",
1180                key_path
1181            )));
1182        }
1183        #[cfg(unix)]
1184        {
1185            use std::os::unix::fs::PermissionsExt;
1186            if let Ok(meta) = std::fs::metadata(key_path)
1187                && meta.permissions().mode() & 0o077 != 0
1188            {
1189                tracing::warn!("CA key {} is readable by group or others", key_path);
1190            }
1191        }
1192        Ok(bytes)
1193    }
1194
1195    /// Create a development root CA: the certificate at `cert_path` and its key at
1196    /// `key_path`. The key is written once, never over an existing file, owner-only on Unix,
1197    /// and is loaded back from there like any configured key, so a restart keeps the same
1198    /// root. With no `key_path` there is nowhere to keep the key, and nothing is generated.
1199    async fn generate_development_root_ca(&self, cert_path: &str, key_path: &str) -> Result<()> {
1200        if !self.config.generate_development_root_ca {
1201            return Err(AuthError::config(format!(
1202                "Root CA certificate not found at {cert_path}; set generate_development_root_ca                  to create a development root there (never for production)"
1203            )));
1204        }
1205        if key_path.is_empty() {
1206            return Err(AuthError::config(format!(
1207                "Root CA certificate not found at {cert_path} and no root_ca_key_path is configured; \
1208                 refusing to generate a CA whose key cannot be kept"
1209            )));
1210        }
1211        if std::path::Path::new(key_path).exists() {
1212            return Err(AuthError::config(format!(
1213                "Root CA certificate not found at {cert_path} but a key exists at {key_path}; \
1214                 refusing to overwrite it"
1215            )));
1216        }
1217        tracing::warn!(
1218            "Root CA certificate not found at {}, generating a development root CA (key at {})",
1219            cert_path,
1220            key_path
1221        );
1222        let (cert_pem, key_pem) = self.generate_self_signed_root_ca().await?;
1223        write_new_file(key_path, key_pem.as_bytes(), true)?;
1224        if let Err(e) = write_new_file(cert_path, cert_pem.as_bytes(), false) {
1225            let _ = std::fs::remove_file(key_path);
1226            return Err(e);
1227        }
1228        Ok(())
1229    }
1230
1231    /// Build a CA entry from a parsed certificate.
1232    fn ca_entry(
1233        ca_id: &str,
1234        ca_type: CAType,
1235        pem: String,
1236        facts: CertificateFacts,
1237        private_key: Zeroizing<Vec<u8>>,
1238        source: &str,
1239    ) -> CACertificate {
1240        let profile = match ca_type {
1241            CAType::Root => "root_ca",
1242            CAType::Intermediate => "intermediate_ca",
1243        };
1244        let mut metadata = HashMap::new();
1245        metadata.insert("source".to_string(), Value::String(source.to_string()));
1246        let certificate = StoredCertificate {
1247            cert_id: ca_id.to_string(),
1248            certificate_pem: pem,
1249            private_key_pem: None, // never kept on the certificate record
1250            subject: facts.subject.clone(),
1251            issuer: facts.issuer,
1252            serial_number: facts.serial,
1253            not_before: facts.not_before,
1254            not_after: facts.not_after,
1255            profile: profile.to_string(),
1256            status: CertificateStatus::Valid,
1257            fingerprint: facts.fingerprint,
1258            created_at: Utc::now(),
1259            metadata,
1260        };
1261        CACertificate {
1262            ca_id: ca_id.to_string(),
1263            certificate,
1264            subject: facts.subject,
1265            private_key,
1266            ca_type,
1267            issued_count: 0,
1268        }
1269    }
1270
1271    /// Load CA certificate from file system (with security validation)
1272    async fn load_ca_from_file(&self, ca_cert_path: &str) -> Result<()> {
1273        let key_path = self.config.root_ca_key_path.clone();
1274        if !std::path::Path::new(ca_cert_path).exists() {
1275            self.generate_development_root_ca(ca_cert_path, &key_path)
1276                .await?;
1277        }
1278
1279        let cert_content = tokio::fs::read_to_string(ca_cert_path)
1280            .await
1281            .map_err(|e| AuthError::internal(format!("Failed to read CA certificate: {}", e)))?;
1282        let (pem, der, facts) = self.parse_ca_pem(&cert_content).map_err(|e| {
1283            AuthError::config(format!(
1284                "CA certificate {} is not usable: {}",
1285                ca_cert_path, e
1286            ))
1287        })?;
1288        let private_key = Self::load_signing_key(&key_path, &der)?;
1289
1290        let ca = Self::ca_entry(
1291            "root_ca",
1292            CAType::Root,
1293            pem,
1294            facts,
1295            private_key,
1296            &format!("file:{}", ca_cert_path),
1297        );
1298        self.ca_certificates
1299            .write()
1300            .await
1301            .insert("root_ca".to_string(), ca);
1302        Ok(())
1303    }
1304
1305    /// Load intermediate CA certificate
1306    async fn load_intermediate_ca(&self) -> Result<()> {
1307        let path = match (
1308            &self.config.intermediate_ca_cert_path,
1309            &self.config.intermediate_ca_path,
1310        ) {
1311            (Some(a), Some(b)) if a != b => {
1312                return Err(AuthError::config(format!(
1313                    "intermediate_ca_cert_path ({a}) and intermediate_ca_path ({b}) are the same \
1314                     setting and must agree"
1315                )));
1316            }
1317            (Some(path), _) | (None, Some(path)) => path.clone(),
1318            (None, None) => return Ok(()),
1319        };
1320
1321        let cert_content = tokio::fs::read_to_string(&path).await.map_err(|e| {
1322            AuthError::config(format!("Failed to read intermediate CA {}: {}", path, e))
1323        })?;
1324        let (pem, der, facts) = self.parse_ca_pem(&cert_content).map_err(|e| {
1325            AuthError::config(format!("Intermediate CA {} is not usable: {}", path, e))
1326        })?;
1327
1328        // It must be issued under a CA we hold. (The signature itself is checked whenever a
1329        // path through this intermediate is validated, which is also done on every issuance.)
1330        let issuer_known = self
1331            .ca_certificates
1332            .read()
1333            .await
1334            .values()
1335            .any(|ca| ca.subject == facts.issuer);
1336        if !issuer_known {
1337            return Err(AuthError::config(format!(
1338                "Intermediate CA {} was issued by '{}', which is not a loaded CA",
1339                path, facts.issuer
1340            )));
1341        }
1342
1343        let key_path = self
1344            .config
1345            .intermediate_ca_key_path
1346            .clone()
1347            .unwrap_or_default();
1348        let private_key = Self::load_signing_key(&key_path, &der)?;
1349        let ca = Self::ca_entry(
1350            "intermediate_ca",
1351            CAType::Intermediate,
1352            pem,
1353            facts,
1354            private_key,
1355            &format!("file:{}", path),
1356        );
1357        self.ca_certificates
1358            .write()
1359            .await
1360            .insert("intermediate_ca".to_string(), ca);
1361
1362        tracing::info!("Loaded intermediate CA certificate");
1363        Ok(())
1364    }
1365
1366    /// Sign certificate request
1367    ///
1368    /// The certificate carries the public key in `request.public_key_pem` and is signed by the
1369    /// private key of CA `ca_id`, which must have been loaded (a CA without its key is
1370    /// verify-only and this returns an error) and must not be revoked. The request is a bare
1371    /// public key, not a CSR, so there is no proof that the requester holds the matching
1372    /// private key, and the names are only checked for form: **the caller must authenticate
1373    /// and authorise the requester, the names, the profile and the key.** Requests are refused
1374    /// (never partly honoured) when they ask for something the profile or the name and key
1375    /// policy does not allow, when they carry `attributes` (not supported), or when the profile
1376    /// uses `extensions` (not supported). CA profiles are not issuable here. The serial number
1377    /// is random (126 bits) and the issued certificate is verified to chain to the configured
1378    /// CAs before it is returned.
1379    pub async fn sign_certificate_request(
1380        &self,
1381        request: &CertificateRequest,
1382        ca_id: &str,
1383    ) -> Result<StoredCertificate> {
1384        // Get CA certificate
1385        let ca = {
1386            let cas = self.ca_certificates.read().await;
1387            cas.get(ca_id)
1388                .ok_or_else(|| AuthError::InvalidRequest(format!("CA not found: {}", ca_id)))?
1389                .clone()
1390        };
1391        let ca_revoked = match pem_certificates(&ca.certificate.certificate_pem) {
1392            Ok(mut ders) => self.is_revoked(&ders.remove(0)).await,
1393            Err(_) => true,
1394        };
1395        if ca.certificate.status == CertificateStatus::Revoked || ca_revoked {
1396            return Err(AuthError::InvalidRequest(format!(
1397                "CA '{}' has been revoked and cannot issue certificates",
1398                ca_id
1399            )));
1400        }
1401        if ca.private_key.is_empty() {
1402            return Err(AuthError::config(format!(
1403                "CA '{}' has no signing key loaded; it can validate certificates but not issue them",
1404                ca_id
1405            )));
1406        }
1407
1408        // Get certificate profile
1409        let profile = self
1410            .config
1411            .certificate_profiles
1412            .get(&request.profile)
1413            .ok_or_else(|| {
1414                AuthError::InvalidRequest(format!(
1415                    "Certificate profile not found: {}",
1416                    request.profile
1417                ))
1418            })?;
1419        if matches!(
1420            profile.cert_type,
1421            CertificateType::RootCA | CertificateType::IntermediateCA
1422        ) {
1423            return Err(AuthError::InvalidRequest(format!(
1424                "Profile '{}' is a CA profile; CA certificates are not issued through certificate requests",
1425                request.profile
1426            )));
1427        }
1428        validate_profile(&request.profile, profile)?;
1429        validate_request(request, profile)?;
1430        let validity_days = match profile.validity_days {
1431            days if days > 0 => days,
1432            0 => self.config.default_validity_days,
1433            days => {
1434                return Err(AuthError::config(format!(
1435                    "Profile '{}' has a negative validity ({days} days)",
1436                    request.profile
1437                )));
1438            }
1439        };
1440        if validity_days <= 0 {
1441            return Err(AuthError::config(
1442                "Neither the profile nor default_validity_days gives a positive validity"
1443                    .to_string(),
1444            ));
1445        }
1446
1447        let serial = self.new_serial(ca_id).await?;
1448        let certificate_pem =
1449            self.generate_certificate_pem(request, profile, &ca, &serial, validity_days)?;
1450
1451        // Never hand out a certificate that does not chain to the CAs we trust.
1452        let der = pem_certificates(&certificate_pem)?.remove(0);
1453        if let Err(reason) = self.verify_path(&der, &[], profile_purpose(profile)).await {
1454            return Err(AuthError::internal(format!(
1455                "Issued certificate does not validate against the configured CAs: {reason}"
1456            )));
1457        }
1458        let facts = certificate_facts(&der)?;
1459
1460        let mut metadata = HashMap::new();
1461        metadata.insert("ca_id".to_string(), Value::String(ca_id.to_string()));
1462        metadata.insert(
1463            "request_id".to_string(),
1464            Value::String(request.request_id.clone()),
1465        );
1466        metadata.insert(
1467            "requester".to_string(),
1468            Value::String(request.requester.clone()),
1469        );
1470        metadata.insert(
1471            "requested_at".to_string(),
1472            Value::String(request.requested_at.to_rfc3339()),
1473        );
1474        let certificate = StoredCertificate {
1475            cert_id: Uuid::new_v4().to_string(),
1476            certificate_pem,
1477            private_key_pem: None, // Certificate doesn't include private key
1478            subject: facts.subject,
1479            issuer: facts.issuer,
1480            serial_number: facts.serial,
1481            not_before: facts.not_before,
1482            not_after: facts.not_after,
1483            profile: request.profile.clone(),
1484            status: CertificateStatus::Valid,
1485            fingerprint: facts.fingerprint,
1486            created_at: Utc::now(),
1487            metadata,
1488        };
1489
1490        // Store certificate; if it cannot be recorded durably it is not handed out.
1491        self.certificate_store
1492            .write()
1493            .await
1494            .insert(certificate.cert_id.clone(), certificate.clone());
1495        if let Err(e) = self.persist().await {
1496            self.certificate_store
1497                .write()
1498                .await
1499                .remove(&certificate.cert_id);
1500            return Err(e);
1501        }
1502
1503        // Update CA issued count
1504        self.increment_ca_issued_count(ca_id).await?;
1505
1506        Ok(certificate)
1507    }
1508
1509    /// A fresh random serial number for `ca_id`: 16 bytes from the system RNG with the top bit
1510    /// clear and the next bit set (so it is positive and 126 bits wide), not already used by
1511    /// that CA.
1512    async fn new_serial(&self, ca_id: &str) -> Result<Vec<u8>> {
1513        use ring::rand::SecureRandom;
1514        let rng = ring::rand::SystemRandom::new();
1515        for _ in 0..8 {
1516            let mut bytes = [0u8; 16];
1517            rng.fill(&mut bytes)
1518                .map_err(|_| AuthError::internal("System random number generator failed"))?;
1519            bytes[0] = (bytes[0] & 0x7f) | 0x40;
1520            let decimal = x509_parser::num_bigint::BigUint::from_bytes_be(&bytes).to_string();
1521            let in_use = self.certificate_store.read().await.values().any(|cert| {
1522                cert.serial_number == decimal
1523                    && cert.metadata.get("ca_id").and_then(|v| v.as_str()) == Some(ca_id)
1524            });
1525            if !in_use {
1526                return Ok(bytes.to_vec());
1527            }
1528        }
1529        Err(AuthError::internal(
1530            "Could not find an unused serial number",
1531        ))
1532    }
1533
1534    /// Generate the certificate with rcgen: the requester's public key, signed by `ca`.
1535    fn generate_certificate_pem(
1536        &self,
1537        request: &CertificateRequest,
1538        profile: &CertificateProfile,
1539        ca: &CACertificate,
1540        serial: &[u8],
1541        validity_days: i64,
1542    ) -> Result<String> {
1543        use rcgen::{
1544            CertificateParams, DnType, ExtendedKeyUsagePurpose, IsCa, KeyUsagePurpose, SanType,
1545            SerialNumber,
1546        };
1547
1548        let invalid = |what: &str, e: &dyn fmt::Display| {
1549            AuthError::InvalidRequest(format!("Invalid {what}: {e}"))
1550        };
1551
1552        let subject_key = rcgen::SubjectPublicKeyInfo::from_pem(&request.public_key_pem)
1553            .map_err(|e| invalid("public_key_pem (expected a PEM SubjectPublicKeyInfo)", &e))?;
1554
1555        let ca_key_pem = std::str::from_utf8(&ca.private_key)
1556            .map_err(|_| AuthError::internal("CA signing key is not PEM text"))?;
1557        let ca_key = rcgen::KeyPair::from_pem(ca_key_pem)
1558            .map_err(|e| AuthError::internal(format!("CA signing key unusable: {e}")))?;
1559        let issuer = rcgen::Issuer::from_ca_cert_pem(&ca.certificate.certificate_pem, ca_key)
1560            .map_err(|e| AuthError::internal(format!("CA certificate unusable as issuer: {e}")))?;
1561
1562        let mut params = CertificateParams::default();
1563
1564        // Set distinguished name
1565        params
1566            .distinguished_name
1567            .push(DnType::CommonName, &request.subject.common_name);
1568        if let Some(ref org) = request.subject.organization {
1569            params
1570                .distinguished_name
1571                .push(DnType::OrganizationName, org);
1572        }
1573        if let Some(ref ou) = request.subject.organizational_unit {
1574            params
1575                .distinguished_name
1576                .push(DnType::OrganizationalUnitName, ou);
1577        }
1578        if let Some(ref country) = request.subject.country {
1579            params.distinguished_name.push(DnType::CountryName, country);
1580        }
1581        if let Some(ref state) = request.subject.state {
1582            params
1583                .distinguished_name
1584                .push(DnType::StateOrProvinceName, state);
1585        }
1586        if let Some(ref locality) = request.subject.locality {
1587            params
1588                .distinguished_name
1589                .push(DnType::LocalityName, locality);
1590        }
1591
1592        params.serial_number = Some(SerialNumber::from(serial.to_vec()));
1593
1594        // Validity: backdated a little for clock skew, never beyond the CA's own.
1595        let now = Utc::now();
1596        let not_before = (now - Duration::minutes(5)).max(ca.certificate.not_before);
1597        let not_after = chrono::TimeDelta::try_days(validity_days)
1598            .and_then(|span| now.checked_add_signed(span))
1599            .ok_or_else(|| {
1600                AuthError::InvalidRequest(format!(
1601                    "Validity of {validity_days} days is out of range"
1602                ))
1603            })?
1604            .min(ca.certificate.not_after);
1605        let to_time = |instant: DateTime<Utc>| {
1606            time::OffsetDateTime::from_unix_timestamp(instant.timestamp())
1607                .map_err(|e| AuthError::internal(format!("Invalid time: {e}")))
1608        };
1609        params.not_before = to_time(not_before)?;
1610        params.not_after = to_time(not_after)?;
1611        if params.not_after <= params.not_before {
1612            return Err(AuthError::InvalidRequest(
1613                "The CA certificate expires before any certificate could be issued".to_string(),
1614            ));
1615        }
1616
1617        // Set key usages
1618        params.key_usages = profile
1619            .key_usage
1620            .iter()
1621            .map(|ku| match ku {
1622                KeyUsage::DigitalSignature => KeyUsagePurpose::DigitalSignature,
1623                KeyUsage::NonRepudiation => KeyUsagePurpose::ContentCommitment,
1624                KeyUsage::KeyEncipherment => KeyUsagePurpose::KeyEncipherment,
1625                KeyUsage::DataEncipherment => KeyUsagePurpose::DataEncipherment,
1626                KeyUsage::KeyAgreement => KeyUsagePurpose::KeyAgreement,
1627                KeyUsage::KeyCertSign => KeyUsagePurpose::KeyCertSign,
1628                KeyUsage::CrlSign => KeyUsagePurpose::CrlSign,
1629                KeyUsage::EncipherOnly => KeyUsagePurpose::EncipherOnly,
1630                KeyUsage::DecipherOnly => KeyUsagePurpose::DecipherOnly,
1631            })
1632            .collect();
1633
1634        // Set extended key usages
1635        params.extended_key_usages = profile
1636            .extended_key_usage
1637            .iter()
1638            .map(|eku| match eku {
1639                ExtendedKeyUsage::ServerAuth => ExtendedKeyUsagePurpose::ServerAuth,
1640                ExtendedKeyUsage::ClientAuth => ExtendedKeyUsagePurpose::ClientAuth,
1641                ExtendedKeyUsage::CodeSigning => ExtendedKeyUsagePurpose::CodeSigning,
1642                ExtendedKeyUsage::EmailProtection => ExtendedKeyUsagePurpose::EmailProtection,
1643                ExtendedKeyUsage::TimeStamping => ExtendedKeyUsagePurpose::TimeStamping,
1644                ExtendedKeyUsage::OcspSigning => ExtendedKeyUsagePurpose::OcspSigning,
1645            })
1646            .collect();
1647
1648        // Subject alternative names (already checked by the policy): the profile's own, the
1649        // requested ones, and the subject e-mail address.
1650        let mut sans = Vec::new();
1651        for san in profile
1652            .subject_alt_names
1653            .iter()
1654            .chain(request.subject_alt_names.iter())
1655        {
1656            sans.push(match san {
1657                SubjectAltName::DnsName(name) => SanType::DnsName(
1658                    name.clone()
1659                        .try_into()
1660                        .map_err(|e| invalid("DNS subject alternative name", &e))?,
1661                ),
1662                SubjectAltName::Email(email) => SanType::Rfc822Name(
1663                    email
1664                        .clone()
1665                        .try_into()
1666                        .map_err(|e| invalid("email subject alternative name", &e))?,
1667                ),
1668                SubjectAltName::IpAddress(ip) => SanType::IpAddress(
1669                    ip.parse()
1670                        .map_err(|e| invalid("IP subject alternative name", &e))?,
1671                ),
1672                SubjectAltName::Uri(uri) => SanType::URI(
1673                    uri.clone()
1674                        .try_into()
1675                        .map_err(|e| invalid("URI subject alternative name", &e))?,
1676                ),
1677            });
1678        }
1679        if let Some(email) = &request.subject.email {
1680            sans.push(SanType::Rfc822Name(
1681                email
1682                    .clone()
1683                    .try_into()
1684                    .map_err(|e| invalid("subject email address", &e))?,
1685            ));
1686        }
1687        params.subject_alt_names = sans;
1688
1689        // End entity: basicConstraints cA=FALSE, subject and authority key identifiers, and the
1690        // CRL distribution point when one is configured.
1691        params.is_ca = IsCa::ExplicitNoCa;
1692        params.use_authority_key_identifier_extension = true;
1693        if let Some(url) = &self.config.crl_distribution_url {
1694            params.crl_distribution_points = vec![rcgen::CrlDistributionPoint {
1695                uris: vec![url.clone()],
1696            }];
1697        }
1698
1699        let cert = params
1700            .signed_by(&subject_key, &issuer)
1701            .map_err(|e| AuthError::internal(format!("Certificate signing failed: {}", e)))?;
1702        Ok(cert.pem())
1703    }
1704
1705    /// Increment CA issued certificate count
1706    async fn increment_ca_issued_count(&self, ca_id: &str) -> Result<()> {
1707        let mut cas = self.ca_certificates.write().await;
1708        let ca = cas
1709            .get_mut(ca_id)
1710            .ok_or_else(|| AuthError::InvalidRequest(format!("CA not found: {}", ca_id)))?;
1711
1712        ca.issued_count += 1;
1713
1714        Ok(())
1715    }
1716
1717    /// Key under which a revocation is kept: serial numbers are only unique per issuer.
1718    fn revocation_key(ca_id: &str, serial_number: &str) -> String {
1719        format!("{}\u{0}{}", ca_id, serial_number)
1720    }
1721
1722    /// `RemoveFromCrl` (reason 8) only means "un-revoke" in a delta CRL; it is not a reason
1723    /// to revoke.
1724    fn check_revocation_reason(reason: &RevocationReason) -> Result<()> {
1725        if *reason == RevocationReason::RemoveFromCrl {
1726            return Err(AuthError::InvalidRequest(
1727                "RemoveFromCrl is not a reason to revoke a certificate".to_string(),
1728            ));
1729        }
1730        Ok(())
1731    }
1732
1733    /// The CA that issued the one stored certificate with this serial number. A serial number
1734    /// is unique only within one issuer, so a serial held by certificates of two CAs (or by
1735    /// none) is an error; use the `*_issued_by` methods to name the issuer.
1736    async fn sole_issuer_of_serial(&self, serial_number: &str) -> Result<String> {
1737        let store = self.certificate_store.read().await;
1738        let mut issuers: Vec<String> = store
1739            .values()
1740            .filter(|cert| cert.serial_number == serial_number)
1741            .filter_map(|cert| {
1742                cert.metadata
1743                    .get("ca_id")
1744                    .and_then(|v| v.as_str())
1745                    .map(str::to_string)
1746            })
1747            .collect();
1748        issuers.sort();
1749        issuers.dedup();
1750        let mut issuers = issuers.into_iter();
1751        match (issuers.next(), issuers.next()) {
1752            (Some(only), None) => Ok(only),
1753            (None, _) => Err(AuthError::InvalidRequest(
1754                "Certificate not found".to_string(),
1755            )),
1756            (Some(_), Some(_)) => Err(AuthError::InvalidRequest(
1757                "Serial number is held by certificates of more than one CA; name the issuing CA"
1758                    .to_string(),
1759            )),
1760        }
1761    }
1762
1763    /// Revoke certificate
1764    ///
1765    /// Fails if no stored certificate has this serial number, or if certificates of more than
1766    /// one CA do (use [`revoke_certificate_issued_by`](Self::revoke_certificate_issued_by)).
1767    pub async fn revoke_certificate(
1768        &self,
1769        serial_number: &str,
1770        reason: RevocationReason,
1771        additional_info: Option<String>,
1772    ) -> Result<()> {
1773        let ca_id = self.sole_issuer_of_serial(serial_number).await?;
1774        self.revoke_certificate_issued_by(&ca_id, serial_number, reason, additional_info)
1775            .await
1776    }
1777
1778    /// Revoke the certificate with `serial_number` issued by CA `ca_id`. The revocation is
1779    /// written to `state_path` (when set) before this returns; if that fails, the revocation
1780    /// stays in force in memory and the error is returned.
1781    pub async fn revoke_certificate_issued_by(
1782        &self,
1783        ca_id: &str,
1784        serial_number: &str,
1785        reason: RevocationReason,
1786        additional_info: Option<String>,
1787    ) -> Result<()> {
1788        Self::check_revocation_reason(&reason)?;
1789
1790        // The serial may be that of a CA certificate this manager holds, issued by `ca_id`:
1791        // that is a CA revocation, and takes the CA out of service.
1792        let held_ca = {
1793            let cas = self.ca_certificates.read().await;
1794            let issuer_subject = cas.get(ca_id).map(|ca| ca.subject.clone());
1795            cas.values()
1796                .find(|ca| {
1797                    ca.certificate.serial_number == serial_number
1798                        && issuer_subject.as_deref() == Some(ca.certificate.issuer.as_str())
1799                })
1800                .map(|ca| ca.ca_id.clone())
1801        };
1802        if let Some(held_ca) = held_ca {
1803            return self
1804                .revoke_ca_certificate(&held_ca, reason, additional_info)
1805                .await;
1806        }
1807
1808        // Update certificate status
1809        {
1810            let mut store = self.certificate_store.write().await;
1811            let cert = store
1812                .values_mut()
1813                .find(|cert| {
1814                    cert.serial_number == serial_number
1815                        && cert.metadata.get("ca_id").and_then(|v| v.as_str()) == Some(ca_id)
1816                })
1817                .ok_or_else(|| AuthError::InvalidRequest("Certificate not found".to_string()))?;
1818            cert.status = CertificateStatus::Revoked;
1819        }
1820
1821        // Add to revocation list
1822        let revocation_entry = RevocationEntry {
1823            serial_number: serial_number.to_string(),
1824            revocation_date: Utc::now(),
1825            reason,
1826            additional_info,
1827        };
1828
1829        self.revocation_list
1830            .write()
1831            .await
1832            .insert(Self::revocation_key(ca_id, serial_number), revocation_entry);
1833
1834        self.refresh_after_revocation().await;
1835        self.persist().await
1836    }
1837
1838    /// Revoke a certificate given as PEM, without it having to be in the store (for example
1839    /// after a restart of a manager with no `state_path`). It must have been signed by one of
1840    /// this manager's CAs. A stored copy, if any, is marked revoked.
1841    pub async fn revoke_certificate_pem(
1842        &self,
1843        cert_pem: &str,
1844        reason: RevocationReason,
1845        additional_info: Option<String>,
1846    ) -> Result<()> {
1847        Self::check_revocation_reason(&reason)?;
1848        let der = pem_certificates(cert_pem)?.remove(0);
1849        let facts = certificate_facts(&der)?;
1850        let (_, cert) = parse_x509_certificate(&der)
1851            .map_err(|e| AuthError::InvalidRequest(format!("Not a valid certificate: {e}")))?;
1852
1853        let candidates: Vec<(String, String)> = self
1854            .ca_certificates
1855            .read()
1856            .await
1857            .values()
1858            .filter(|ca| ca.subject == facts.issuer)
1859            .map(|ca| (ca.ca_id.clone(), ca.certificate.certificate_pem.clone()))
1860            .collect();
1861        let mut issuing_ca = None;
1862        for (ca_id, ca_pem) in candidates {
1863            let Ok(mut ca_ders) = pem_certificates(&ca_pem) else {
1864                continue;
1865            };
1866            let ca_der = ca_ders.remove(0);
1867            if let Ok((_, ca_cert)) = parse_x509_certificate(&ca_der)
1868                && cert.verify_signature(Some(ca_cert.public_key())).is_ok()
1869            {
1870                issuing_ca = Some(ca_id);
1871                break;
1872            }
1873        }
1874        let ca_id = issuing_ca.ok_or_else(|| {
1875            AuthError::InvalidRequest(
1876                "Certificate was not issued by a CA of this manager".to_string(),
1877            )
1878        })?;
1879
1880        for stored in self.certificate_store.write().await.values_mut() {
1881            if stored.serial_number == facts.serial
1882                && stored.metadata.get("ca_id").and_then(|v| v.as_str()) == Some(ca_id.as_str())
1883            {
1884                stored.status = CertificateStatus::Revoked;
1885            }
1886        }
1887        self.revocation_list.write().await.insert(
1888            Self::revocation_key(&ca_id, &facts.serial),
1889            RevocationEntry {
1890                serial_number: facts.serial,
1891                revocation_date: Utc::now(),
1892                reason,
1893                additional_info,
1894            },
1895        );
1896        // The certificate may be one of this manager's own CAs: take it out of service.
1897        self.refresh_after_revocation().await;
1898        self.persist().await
1899    }
1900
1901    /// Revoke a CA certificate held by this manager. It is recorded against the CA(s) that
1902    /// issued it (for a root, itself), marked revoked, never used as a trust anchor or
1903    /// intermediate again, and can no longer issue.
1904    pub async fn revoke_ca_certificate(
1905        &self,
1906        ca_id: &str,
1907        reason: RevocationReason,
1908        additional_info: Option<String>,
1909    ) -> Result<()> {
1910        Self::check_revocation_reason(&reason)?;
1911        let (serial, issuer) = {
1912            let cas = self.ca_certificates.read().await;
1913            let ca = cas
1914                .get(ca_id)
1915                .ok_or_else(|| AuthError::InvalidRequest(format!("CA not found: {}", ca_id)))?;
1916            (
1917                ca.certificate.serial_number.clone(),
1918                ca.certificate.issuer.clone(),
1919            )
1920        };
1921        let issuers: Vec<String> = self
1922            .ca_certificates
1923            .read()
1924            .await
1925            .values()
1926            .filter(|ca| ca.subject == issuer)
1927            .map(|ca| ca.ca_id.clone())
1928            .collect();
1929        if issuers.is_empty() {
1930            return Err(AuthError::InvalidRequest(format!(
1931                "The issuer of CA '{}' is not a loaded CA, so there is no list to record the revocation in",
1932                ca_id
1933            )));
1934        }
1935        {
1936            let mut revoked = self.revocation_list.write().await;
1937            for issuer_id in &issuers {
1938                revoked.insert(
1939                    Self::revocation_key(issuer_id, &serial),
1940                    RevocationEntry {
1941                        serial_number: serial.clone(),
1942                        revocation_date: Utc::now(),
1943                        reason: reason.clone(),
1944                        additional_info: additional_info.clone(),
1945                    },
1946                );
1947            }
1948        }
1949        if let Some(ca) = self.ca_certificates.write().await.get_mut(ca_id) {
1950            ca.certificate.status = CertificateStatus::Revoked;
1951        }
1952        self.persist().await
1953    }
1954
1955    /// Check certificate status (see [`revoke_certificate`](Self::revoke_certificate) for how
1956    /// the serial number is resolved).
1957    pub async fn check_certificate_status(&self, serial_number: &str) -> Result<CertificateStatus> {
1958        let ca_id = self.sole_issuer_of_serial(serial_number).await?;
1959        self.check_certificate_status_issued_by(&ca_id, serial_number)
1960            .await
1961    }
1962
1963    /// Check the status of the certificate with `serial_number` issued by CA `ca_id`.
1964    pub async fn check_certificate_status_issued_by(
1965        &self,
1966        ca_id: &str,
1967        serial_number: &str,
1968    ) -> Result<CertificateStatus> {
1969        // Check revocation list first
1970        if self
1971            .revocation_list
1972            .read()
1973            .await
1974            .contains_key(&Self::revocation_key(ca_id, serial_number))
1975        {
1976            return Ok(CertificateStatus::Revoked);
1977        }
1978
1979        // Check certificate store
1980        let store = self.certificate_store.read().await;
1981        for cert in store.values() {
1982            if cert.serial_number == serial_number
1983                && cert.metadata.get("ca_id").and_then(|v| v.as_str()) == Some(ca_id)
1984            {
1985                // Check expiration
1986                if Utc::now() > cert.not_after {
1987                    return Ok(CertificateStatus::Expired);
1988                }
1989                return Ok(cert.status.clone());
1990            }
1991        }
1992
1993        Err(AuthError::InvalidRequest(
1994            "Certificate not found".to_string(),
1995        ))
1996    }
1997
1998    /// Get certificate by ID
1999    pub async fn get_certificate(&self, cert_id: &str) -> Result<Option<StoredCertificate>> {
2000        let store = self.certificate_store.read().await;
2001        Ok(store.get(cert_id).cloned())
2002    }
2003
2004    /// List certificates
2005    pub async fn list_certificates(
2006        &self,
2007        filter: Option<CertificateFilter>,
2008    ) -> Result<Vec<StoredCertificate>> {
2009        let store = self.certificate_store.read().await;
2010        let mut certificates: Vec<StoredCertificate> = store.values().cloned().collect();
2011
2012        // Apply filter if provided
2013        if let Some(f) = filter {
2014            certificates.retain(|cert| f.matches(cert));
2015        }
2016
2017        Ok(certificates)
2018    }
2019
2020    /// Generate a Certificate Revocation List (CRL) for CA `ca_id`: a DER CRL signed by the
2021    /// CA's key, as PEM, listing the certificates that CA issued and that were revoked. Fails
2022    /// if CRLs are disabled in the configuration or the CA has no signing key loaded. The CRL
2023    /// number increases with every CRL, across restarts when `state_path` is set.
2024    pub async fn generate_crl(&self, ca_id: &str) -> Result<String> {
2025        if !self.config.enable_crl {
2026            return Err(AuthError::config(
2027                "CRL generation is disabled (enable_crl = false)".to_string(),
2028            ));
2029        }
2030        let ca = {
2031            let cas = self.ca_certificates.read().await;
2032            cas.get(ca_id)
2033                .ok_or_else(|| AuthError::InvalidRequest(format!("CA not found: {}", ca_id)))?
2034                .clone()
2035        };
2036        if ca.private_key.is_empty() {
2037            return Err(AuthError::config(format!(
2038                "CA '{}' has no signing key loaded; it cannot sign a CRL",
2039                ca_id
2040            )));
2041        }
2042
2043        // The revocation snapshot and the CRL number are taken together: a CRL with a higher
2044        // number never lacks a revocation that a lower-numbered one had. (Strictly increasing
2045        // per CA, and never below the clock, so a restart without saved state moves forward.)
2046        let now = Utc::now();
2047        let revocations = self.revocation_list.read().await;
2048        let crl_number = {
2049            let mut numbers = self.crl_numbers.write().await;
2050            let last = numbers.get(ca_id).copied().unwrap_or(0);
2051            let next = last.saturating_add(1).max(now.timestamp().max(0) as u64);
2052            numbers.insert(ca_id.to_string(), next);
2053            next
2054        };
2055        let prefix = Self::revocation_key(ca_id, "");
2056        let mut revoked_certs = Vec::new();
2057        for (key, entry) in revocations.iter() {
2058            if !key.starts_with(&prefix) {
2059                continue;
2060            }
2061            let serial =
2062                x509_parser::num_bigint::BigUint::parse_bytes(entry.serial_number.as_bytes(), 10)
2063                    .ok_or_else(|| {
2064                    AuthError::internal(format!(
2065                        "Serial number {} is not numeric",
2066                        entry.serial_number
2067                    ))
2068                })?;
2069            revoked_certs.push(rcgen::RevokedCertParams {
2070                serial_number: rcgen::SerialNumber::from(serial.to_bytes_be()),
2071                revocation_time: time::OffsetDateTime::from_unix_timestamp(
2072                    entry.revocation_date.timestamp(),
2073                )
2074                .map_err(|e| AuthError::internal(format!("Invalid revocation time: {e}")))?,
2075                reason_code: match entry.reason {
2076                    // reasonCode 0 is the default and is left out (RFC 5280, 5.3.1)
2077                    RevocationReason::Unspecified => None,
2078                    RevocationReason::KeyCompromise => Some(rcgen::RevocationReason::KeyCompromise),
2079                    RevocationReason::CaCompromise => Some(rcgen::RevocationReason::CaCompromise),
2080                    RevocationReason::AffiliationChanged => {
2081                        Some(rcgen::RevocationReason::AffiliationChanged)
2082                    }
2083                    RevocationReason::Superseded => Some(rcgen::RevocationReason::Superseded),
2084                    RevocationReason::CessationOfOperation => {
2085                        Some(rcgen::RevocationReason::CessationOfOperation)
2086                    }
2087                    RevocationReason::CertificateHold => {
2088                        Some(rcgen::RevocationReason::CertificateHold)
2089                    }
2090                    RevocationReason::PrivilegeWithdrawn => {
2091                        Some(rcgen::RevocationReason::PrivilegeWithdrawn)
2092                    }
2093                    RevocationReason::AaCompromise => Some(rcgen::RevocationReason::AaCompromise),
2094                    RevocationReason::RemoveFromCrl => {
2095                        return Err(AuthError::internal(
2096                            "A revocation with reason RemoveFromCrl cannot be listed",
2097                        ));
2098                    }
2099                },
2100                invalidity_date: None,
2101            });
2102        }
2103        let revoked_count = revoked_certs.len();
2104        drop(revocations);
2105
2106        let ca_key_pem = std::str::from_utf8(&ca.private_key)
2107            .map_err(|_| AuthError::internal("CA signing key is not PEM text"))?;
2108        let ca_key = rcgen::KeyPair::from_pem(ca_key_pem)
2109            .map_err(|e| AuthError::internal(format!("CA signing key unusable: {e}")))?;
2110        let issuer = rcgen::Issuer::from_ca_cert_pem(&ca.certificate.certificate_pem, ca_key)
2111            .map_err(|e| AuthError::internal(format!("CA certificate unusable as issuer: {e}")))?;
2112
2113        let this_update =
2114            time::OffsetDateTime::from_unix_timestamp((now - Duration::minutes(5)).timestamp())
2115                .map_err(|e| AuthError::internal(format!("Invalid time: {e}")))?;
2116        let params = rcgen::CertificateRevocationListParams {
2117            this_update,
2118            next_update: this_update + time::Duration::days(7), // CRL valid for 7 days
2119            crl_number: rcgen::SerialNumber::from(crl_number.to_be_bytes().to_vec()),
2120            issuing_distribution_point: None,
2121            revoked_certs,
2122            key_identifier_method: rcgen::KeyIdMethod::Sha256,
2123        };
2124        let crl = params
2125            .signed_by(&issuer)
2126            .map_err(|e| AuthError::internal(format!("CRL signing failed: {e}")))?;
2127        let crl_pem = crl
2128            .pem()
2129            .map_err(|e| AuthError::internal(format!("CRL encoding failed: {e}")))?;
2130        self.persist().await?;
2131
2132        tracing::info!(
2133            "Generated CRL for CA {} with {} revoked certificates",
2134            ca_id,
2135            revoked_count
2136        );
2137        Ok(crl_pem)
2138    }
2139
2140    /// Build and verify the certification path of `leaf_der` against the configured CAs:
2141    /// the root CAs are the trust anchors; the loaded intermediate CAs and `extra` (certificates
2142    /// the caller presented with it) are candidate intermediates. Revoked CAs are not used.
2143    /// Signatures, validity of every certificate, basicConstraints / pathLen, name constraints
2144    /// and the extended key usage for `purpose` are checked by `rustls-webpki`.
2145    async fn verify_path(
2146        &self,
2147        leaf_der: &[u8],
2148        extra: &[Vec<u8>],
2149        purpose: CertificatePurpose,
2150    ) -> std::result::Result<(), String> {
2151        let (anchors, mut intermediates) = {
2152            let cas = self.ca_certificates.read().await;
2153            let mut anchors = Vec::new();
2154            let mut intermediates = Vec::new();
2155            for ca in cas.values() {
2156                if ca.certificate.status == CertificateStatus::Revoked {
2157                    continue;
2158                }
2159                let Ok(mut der) = pem_certificates(&ca.certificate.certificate_pem) else {
2160                    continue;
2161                };
2162                match ca.ca_type {
2163                    CAType::Root => anchors.push(der.remove(0)),
2164                    CAType::Intermediate => intermediates.push(der.remove(0)),
2165                }
2166            }
2167            (anchors, intermediates)
2168        };
2169        intermediates.extend(extra.iter().cloned());
2170
2171        crate::server::security::mtls::verify_chain_for_usage(
2172            leaf_der,
2173            &intermediates,
2174            &anchors,
2175            purpose_usage(purpose),
2176        )
2177    }
2178
2179    /// Whether this manager has revoked the certificate: a revocation recorded by any CA we
2180    /// hold whose subject is the certificate's issuer, for the certificate's serial number.
2181    async fn is_revoked(&self, cert_der: &[u8]) -> bool {
2182        let Ok(facts) = certificate_facts(cert_der) else {
2183            return true; // cannot be read: do not vouch for it
2184        };
2185        let issuer_ids: Vec<String> = self
2186            .ca_certificates
2187            .read()
2188            .await
2189            .values()
2190            .filter(|ca| ca.subject == facts.issuer)
2191            .map(|ca| ca.ca_id.clone())
2192            .collect();
2193        let revoked = self.revocation_list.read().await;
2194        issuer_ids
2195            .iter()
2196            .any(|ca_id| revoked.contains_key(&Self::revocation_key(ca_id, &facts.serial)))
2197    }
2198
2199    /// Validate certificate chain for `purpose`
2200    ///
2201    /// `cert_pem` is the certificate to validate, optionally followed by intermediate
2202    /// certificates. Returns `Ok(true)` only if it chains, with valid signatures, validity
2203    /// periods and constraints, to a root CA this manager holds, it may be used for `purpose`
2204    /// (a certificate with an extended key usage must list the purpose; one without is valid
2205    /// for any), and neither it nor an intermediate on the path has been revoked here. A
2206    /// certificate that merely names a trusted CA as its subject or issuer is not valid. A
2207    /// configured root CA validates as itself, unless it has been revoked.
2208    pub async fn validate_certificate_chain(
2209        &self,
2210        cert_pem: &str,
2211        purpose: CertificatePurpose,
2212    ) -> Result<bool> {
2213        let mut presented = pem_certificates(cert_pem)?;
2214        let leaf = presented.remove(0);
2215        certificate_facts(&leaf)?; // must parse
2216
2217        // A configured root CA, presented as itself, that is still valid and not revoked.
2218        let is_trusted_root = {
2219            let cas = self.ca_certificates.read().await;
2220            cas.values().any(|ca| {
2221                ca.ca_type == CAType::Root
2222                    && ca.certificate.status != CertificateStatus::Revoked
2223                    && pem_certificates(&ca.certificate.certificate_pem)
2224                        .is_ok_and(|ders| ders[0] == leaf)
2225            })
2226        };
2227        if is_trusted_root {
2228            return Ok(
2229                ensure_ca_certificate(&leaf).is_ok() && certificate_allows_purpose(&leaf, purpose)
2230            );
2231        }
2232
2233        if let Err(reason) = self.verify_path(&leaf, &presented, purpose).await {
2234            tracing::warn!("Certificate chain validation failed: {}", reason);
2235            return Ok(false);
2236        }
2237
2238        if self.is_revoked(&leaf).await {
2239            tracing::warn!("Certificate has been revoked");
2240            return Ok(false);
2241        }
2242        // The intermediates the path may have used: ours and the ones presented.
2243        let mut intermediates: Vec<Vec<u8>> = {
2244            let cas = self.ca_certificates.read().await;
2245            cas.values()
2246                .filter(|ca| ca.ca_type == CAType::Intermediate)
2247                .filter_map(|ca| pem_certificates(&ca.certificate.certificate_pem).ok())
2248                .map(|mut ders| ders.remove(0))
2249                .collect()
2250        };
2251        intermediates.extend(presented);
2252        for intermediate in &intermediates {
2253            if self.is_revoked(intermediate).await {
2254                tracing::warn!("An intermediate CA has been revoked");
2255                return Ok(false);
2256            }
2257        }
2258
2259        Ok(true)
2260    }
2261
2262    /// Generate a self-signed root CA certificate for development/testing
2263    ///
2264    /// Returns a tuple of (certificate_pem, private_key_pem).
2265    async fn generate_self_signed_root_ca(&self) -> Result<(String, String)> {
2266        use rcgen::{
2267            BasicConstraints, CertificateParams, DnType, IsCa, KeyUsagePurpose, SerialNumber,
2268        };
2269
2270        let mut params = CertificateParams::default();
2271
2272        // Set distinguished name for root CA
2273        params
2274            .distinguished_name
2275            .push(DnType::CommonName, "AuthFramework Dev Root CA");
2276        params
2277            .distinguished_name
2278            .push(DnType::OrganizationName, "Auth Framework");
2279        params.distinguished_name.push(DnType::CountryName, "US");
2280
2281        // Root CAs have long validity
2282        params.not_before = time::OffsetDateTime::now_utc();
2283        params.not_after = time::OffsetDateTime::now_utc() + time::Duration::days(365 * 10);
2284
2285        // Serial number 1 for root CA
2286        params.serial_number = Some(SerialNumber::from(1u64.to_be_bytes().to_vec()));
2287
2288        // Root CA flags
2289        params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
2290        params.key_usages = vec![
2291            KeyUsagePurpose::KeyCertSign,
2292            KeyUsagePurpose::CrlSign,
2293            KeyUsagePurpose::DigitalSignature,
2294        ];
2295
2296        // Generate ECDSA P-256 key pair
2297        let key_pair = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256)
2298            .map_err(|e| AuthError::internal(format!("CA key pair generation failed: {}", e)))?;
2299
2300        let cert = params
2301            .self_signed(&key_pair)
2302            .map_err(|e| AuthError::internal(format!("CA self-sign failed: {}", e)))?;
2303
2304        let cert_pem = cert.pem();
2305        let key_pem = key_pair.serialize_pem();
2306
2307        tracing::info!("Generated self-signed root CA certificate for development use");
2308
2309        Ok((cert_pem, key_pem))
2310    }
2311
2312    /// Store a CA certificate from PEM data into the internal CA certificate store.
2313    ///
2314    /// This shared helper is called by all external integrations (HSM, Azure, AWS)
2315    /// after successfully retrieving the certificate from the external source. The
2316    /// certificate must parse and be a usable, currently valid CA, and everything recorded
2317    /// about it is read from the certificate. The private key stays with the external
2318    /// source, so a CA stored this way validates but does not sign.
2319    async fn store_ca_certificate_from_pem(&self, cert_pem: &str, source: &str) -> Result<()> {
2320        let (pem, _der, facts) = self.parse_ca_pem(cert_pem).map_err(|e| {
2321            AuthError::config(format!(
2322                "CA certificate from {} is not usable: {}",
2323                source, e
2324            ))
2325        })?;
2326        let ca = Self::ca_entry(
2327            "root_ca",
2328            CAType::Root,
2329            pem,
2330            facts,
2331            Zeroizing::new(Vec::new()),
2332            source,
2333        );
2334        self.ca_certificates
2335            .write()
2336            .await
2337            .insert("root_ca".to_string(), ca);
2338        Ok(())
2339    }
2340}
2341
2342/// Certificate Filter for listing operations
2343#[derive(Debug, Clone)]
2344pub struct CertificateFilter {
2345    /// Filter by certificate status
2346    pub status: Option<CertificateStatus>,
2347
2348    /// Filter by profile
2349    pub profile: Option<String>,
2350
2351    /// Filter by expiration date range
2352    pub expires_before: Option<DateTime<Utc>>,
2353
2354    /// Filter by expiration date range
2355    pub expires_after: Option<DateTime<Utc>>,
2356
2357    /// Filter by subject
2358    pub subject_contains: Option<String>,
2359}
2360
2361impl CertificateFilter {
2362    /// Check if certificate matches filter
2363    pub fn matches(&self, cert: &StoredCertificate) -> bool {
2364        if let Some(ref status) = self.status
2365            && &cert.status != status
2366        {
2367            return false;
2368        }
2369
2370        if let Some(ref profile) = self.profile
2371            && &cert.profile != profile
2372        {
2373            return false;
2374        }
2375
2376        if let Some(expires_before) = self.expires_before
2377            && cert.not_after > expires_before
2378        {
2379            return false;
2380        }
2381
2382        if let Some(expires_after) = self.expires_after
2383            && cert.not_after < expires_after
2384        {
2385            return false;
2386        }
2387
2388        if let Some(ref subject_contains) = self.subject_contains
2389            && !cert.subject.contains(subject_contains)
2390        {
2391            return false;
2392        }
2393
2394        true
2395    }
2396}
2397
2398// Default implementations
2399
2400impl Default for X509Config {
2401    fn default() -> Self {
2402        let mut certificate_profiles = HashMap::new();
2403
2404        // Add default profiles
2405        certificate_profiles.insert(
2406            "tls_server".to_string(),
2407            CertificateProfile {
2408                name: "TLS Server".to_string(),
2409                cert_type: CertificateType::TlsServer,
2410                key_usage: vec![KeyUsage::DigitalSignature, KeyUsage::KeyEncipherment],
2411                extended_key_usage: vec![ExtendedKeyUsage::ServerAuth],
2412                subject_alt_names: vec![],
2413                san_policy: SanPolicy::default(),
2414                validity_days: 365,
2415                preferred_key_type: KeyType::Rsa(2048),
2416                extensions: HashMap::new(),
2417            },
2418        );
2419
2420        certificate_profiles.insert(
2421            "tls_client".to_string(),
2422            CertificateProfile {
2423                name: "TLS Client".to_string(),
2424                cert_type: CertificateType::TlsClient,
2425                key_usage: vec![KeyUsage::DigitalSignature, KeyUsage::KeyAgreement],
2426                extended_key_usage: vec![ExtendedKeyUsage::ClientAuth],
2427                subject_alt_names: vec![],
2428                san_policy: SanPolicy::default(),
2429                validity_days: 365,
2430                preferred_key_type: KeyType::Rsa(2048),
2431                extensions: HashMap::new(),
2432            },
2433        );
2434
2435        Self {
2436            default_validity_days: 365,
2437            root_ca_cert_path: "ca/root-ca.crt".to_string(),
2438            root_ca_path: "ca/root-ca.crt".to_string(),
2439            root_ca_key_path: "ca/root-ca.key".to_string(),
2440            intermediate_ca_cert_path: None,
2441            intermediate_ca_path: None,
2442            intermediate_ca_key_path: None,
2443            certificate_profiles,
2444            enable_ocsp: false,
2445            ocsp_responder_url: None,
2446            enable_crl: true,
2447            crl_distribution_url: None,
2448            state_path: None,
2449            generate_development_root_ca: false,
2450        }
2451    }
2452}
2453
2454// ─── Certificate reading and file helpers ─────────────────────────────────────
2455
2456/// What the manager records about a certificate, read from the certificate itself.
2457struct CertificateFacts {
2458    subject: String,
2459    issuer: String,
2460    /// Decimal serial number.
2461    serial: String,
2462    not_before: DateTime<Utc>,
2463    not_after: DateTime<Utc>,
2464    /// SHA-256 of the DER, uppercase hex with colons.
2465    fingerprint: String,
2466}
2467
2468/// DER of every `CERTIFICATE` block in `pem` (other blocks are skipped); at least one.
2469fn pem_certificates(pem: &str) -> Result<Vec<Vec<u8>>> {
2470    let mut certificates = Vec::new();
2471    for item in x509_parser::pem::Pem::iter_from_buffer(pem.as_bytes()) {
2472        let item =
2473            item.map_err(|e| AuthError::InvalidRequest(format!("Invalid PEM data: {}", e)))?;
2474        if item.label == "CERTIFICATE" {
2475            certificates.push(item.contents);
2476        }
2477    }
2478    if certificates.is_empty() {
2479        return Err(AuthError::InvalidRequest(
2480            "No PEM CERTIFICATE block found".to_string(),
2481        ));
2482    }
2483    Ok(certificates)
2484}
2485
2486/// PEM for one DER certificate.
2487fn der_to_pem(der: &[u8]) -> String {
2488    let body = BASE64_STANDARD.encode(der);
2489    let mut pem = String::from("-----BEGIN CERTIFICATE-----\n");
2490    for chunk in body.as_bytes().chunks(64) {
2491        pem.push_str(&String::from_utf8_lossy(chunk));
2492        pem.push('\n');
2493    }
2494    pem.push_str("-----END CERTIFICATE-----\n");
2495    pem
2496}
2497
2498/// Read the facts of a certificate. Fails unless `der` is exactly one parsable certificate.
2499fn certificate_facts(der: &[u8]) -> Result<CertificateFacts> {
2500    use sha2::{Digest, Sha256};
2501
2502    let (rest, cert) = parse_x509_certificate(der)
2503        .map_err(|e| AuthError::InvalidRequest(format!("Not a valid X.509 certificate: {}", e)))?;
2504    if !rest.is_empty() {
2505        return Err(AuthError::InvalidRequest(
2506            "Trailing data after the certificate".to_string(),
2507        ));
2508    }
2509    let instant = |timestamp: i64| {
2510        DateTime::from_timestamp(timestamp, 0)
2511            .ok_or_else(|| AuthError::InvalidRequest("Certificate time out of range".to_string()))
2512    };
2513    let fingerprint = Sha256::digest(der)
2514        .iter()
2515        .map(|byte| format!("{:02X}", byte))
2516        .collect::<Vec<_>>()
2517        .join(":");
2518    Ok(CertificateFacts {
2519        subject: cert.subject().to_string(),
2520        issuer: cert.issuer().to_string(),
2521        serial: cert.serial.to_string(),
2522        not_before: instant(cert.validity().not_before.timestamp())?,
2523        not_after: instant(cert.validity().not_after.timestamp())?,
2524        fingerprint,
2525    })
2526}
2527
2528/// A CA certificate must be a CA (basicConstraints), allow certificate signing if it states
2529/// key usage, be valid now, and be usable by the verifier as an anchor.
2530fn ensure_ca_certificate(der: &[u8]) -> Result<()> {
2531    let (rest, cert) = parse_x509_certificate(der)
2532        .map_err(|e| AuthError::InvalidRequest(format!("Not a valid X.509 certificate: {}", e)))?;
2533    if !rest.is_empty() {
2534        return Err(AuthError::InvalidRequest(
2535            "Trailing data after the certificate".to_string(),
2536        ));
2537    }
2538    let is_ca = matches!(cert.basic_constraints(), Ok(Some(bc)) if bc.value.ca);
2539    if !is_ca {
2540        return Err(AuthError::InvalidRequest(
2541            "Certificate is not a CA certificate".to_string(),
2542        ));
2543    }
2544    match cert.key_usage() {
2545        Ok(None) => {}
2546        Ok(Some(key_usage)) if key_usage.value.key_cert_sign() => {}
2547        Ok(Some(_)) => {
2548            return Err(AuthError::InvalidRequest(
2549                "CA certificate does not allow certificate signing".to_string(),
2550            ));
2551        }
2552        Err(_) => {
2553            return Err(AuthError::InvalidRequest(
2554                "CA certificate has a malformed keyUsage extension".to_string(),
2555            ));
2556        }
2557    }
2558    let now = Utc::now().timestamp();
2559    if now < cert.validity().not_before.timestamp() {
2560        return Err(AuthError::InvalidRequest(
2561            "CA certificate is not yet valid".to_string(),
2562        ));
2563    }
2564    if now > cert.validity().not_after.timestamp() {
2565        return Err(AuthError::InvalidRequest(
2566            "CA certificate has expired".to_string(),
2567        ));
2568    }
2569    webpki::anchor_from_trusted_cert(&rustls_pki_types::CertificateDer::from(der)).map_err(
2570        |e| {
2571            AuthError::InvalidRequest(format!(
2572                "CA certificate is not usable as a trust anchor: {e}"
2573            ))
2574        },
2575    )?;
2576    Ok(())
2577}
2578
2579/// The persisted part of the manager's state.
2580#[derive(Serialize, Deserialize)]
2581struct PersistedState {
2582    version: u32,
2583    certificates: HashMap<String, StoredCertificate>,
2584    revocations: HashMap<String, RevocationEntry>,
2585    crl_numbers: HashMap<String, u64>,
2586}
2587
2588// id-kp-codeSigning, id-kp-emailProtection, id-kp-timeStamping, id-kp-OCSPSigning
2589const EKU_CODE_SIGNING: &[u8] = &[0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x03];
2590const EKU_EMAIL_PROTECTION: &[u8] = &[0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x04];
2591const EKU_TIME_STAMPING: &[u8] = &[0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x08];
2592const EKU_OCSP_SIGNING: &[u8] = &[0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x09];
2593
2594/// The path requirement for a purpose: when the certificate carries an extended key usage it
2595/// must list the purpose; one without the extension is valid for any purpose.
2596fn purpose_usage(purpose: CertificatePurpose) -> webpki::KeyUsage {
2597    match purpose {
2598        CertificatePurpose::ServerAuth => webpki::KeyUsage::server_auth(),
2599        CertificatePurpose::ClientAuth => webpki::KeyUsage::client_auth(),
2600        CertificatePurpose::CodeSigning => webpki::KeyUsage::required_if_present(EKU_CODE_SIGNING),
2601        CertificatePurpose::EmailProtection => {
2602            webpki::KeyUsage::required_if_present(EKU_EMAIL_PROTECTION)
2603        }
2604        CertificatePurpose::TimeStamping => {
2605            webpki::KeyUsage::required_if_present(EKU_TIME_STAMPING)
2606        }
2607        CertificatePurpose::OcspSigning => webpki::KeyUsage::required_if_present(EKU_OCSP_SIGNING),
2608    }
2609}
2610
2611/// The purpose certificates of a profile are verified for after issuance: the first extended
2612/// key usage the profile lists, client authentication if it lists none.
2613fn profile_purpose(profile: &CertificateProfile) -> CertificatePurpose {
2614    match profile.extended_key_usage.first() {
2615        Some(ExtendedKeyUsage::ServerAuth) => CertificatePurpose::ServerAuth,
2616        Some(ExtendedKeyUsage::CodeSigning) => CertificatePurpose::CodeSigning,
2617        Some(ExtendedKeyUsage::EmailProtection) => CertificatePurpose::EmailProtection,
2618        Some(ExtendedKeyUsage::TimeStamping) => CertificatePurpose::TimeStamping,
2619        Some(ExtendedKeyUsage::OcspSigning) => CertificatePurpose::OcspSigning,
2620        Some(ExtendedKeyUsage::ClientAuth) | None => CertificatePurpose::ClientAuth,
2621    }
2622}
2623
2624/// A CRL distribution point must be an absolute `http://` or `https://` URL.
2625fn check_distribution_url(url: &str) -> Result<()> {
2626    let ok = (url.starts_with("http://") || url.starts_with("https://"))
2627        && url.len() <= 2048
2628        && url.chars().all(|c| c.is_ascii_graphic());
2629    if ok {
2630        Ok(())
2631    } else {
2632        Err(AuthError::config(format!(
2633            "crl_distribution_url must be an http:// or https:// URL without spaces or control characters: {url:?}"
2634        )))
2635    }
2636}
2637
2638fn policy_error(message: String) -> AuthError {
2639    AuthError::InvalidRequest(message)
2640}
2641
2642/// A subject text field: not empty, at most `max` characters, no control characters.
2643fn check_text(field: &str, value: &str, max: usize) -> Result<()> {
2644    if value.trim().is_empty() {
2645        return Err(policy_error(format!("{field} cannot be empty")));
2646    }
2647    if value.chars().count() > max {
2648        return Err(policy_error(format!(
2649            "{field} is longer than {max} characters"
2650        )));
2651    }
2652    if value.chars().any(|c| c.is_control() || is_format_char(c)) {
2653        return Err(policy_error(format!(
2654            "{field} contains control or formatting characters"
2655        )));
2656    }
2657    Ok(())
2658}
2659
2660/// Invisible formatting characters that can disguise a name: zero-width characters,
2661/// bidirectional controls and embeddings, word joiners, the byte-order mark.
2662fn is_format_char(c: char) -> bool {
2663    matches!(
2664        c,
2665        '\u{061c}'
2666            | '\u{200b}'..='\u{200f}'
2667            | '\u{202a}'..='\u{202e}'
2668            | '\u{2060}'..='\u{2064}'
2669            | '\u{2066}'..='\u{2069}'
2670            | '\u{feff}'
2671    )
2672}
2673
2674/// A DNS name: real multi-label host name, optionally with a left-most wildcard label.
2675fn check_dns_name(name: &str, allow_wildcard: bool) -> Result<()> {
2676    let (wildcard, host) = match name.strip_prefix("*.") {
2677        Some(rest) => (true, rest),
2678        None => (false, name),
2679    };
2680    if wildcard && !allow_wildcard {
2681        return Err(policy_error(format!(
2682            "wildcard name {name:?} is not allowed by the profile"
2683        )));
2684    }
2685    if name.len() > 253 {
2686        return Err(policy_error(
2687            "DNS name is longer than 253 characters".to_string(),
2688        ));
2689    }
2690    let labels: Vec<&str> = host.split('.').collect();
2691    let label_ok = |label: &&str| {
2692        !label.is_empty()
2693            && label.len() <= 63
2694            && !label.starts_with('-')
2695            && !label.ends_with('-')
2696            && label.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
2697    };
2698    if labels.len() < 2 || !labels.iter().all(label_ok) {
2699        return Err(policy_error(format!(
2700            "{name:?} is not a valid multi-label DNS name"
2701        )));
2702    }
2703    let last = labels[labels.len() - 1];
2704    if last.chars().all(|c| c.is_ascii_digit()) {
2705        return Err(policy_error(format!("{name:?} looks like an IP address")));
2706    }
2707    if last.eq_ignore_ascii_case("localhost") {
2708        return Err(policy_error(format!("{name:?} is a localhost name")));
2709    }
2710    Ok(())
2711}
2712
2713fn check_ip_name(ip: &str) -> Result<()> {
2714    let parsed: std::net::IpAddr = ip
2715        .parse()
2716        .map_err(|_| policy_error(format!("{ip:?} is not an IP address")))?;
2717    // An IPv4-mapped IPv6 address (::ffff:127.0.0.1) is judged as the IPv4 address it wraps.
2718    let address = parsed.to_canonical();
2719    let broadcast = matches!(address, std::net::IpAddr::V4(v4) if v4.is_broadcast());
2720    if address.is_unspecified() || address.is_loopback() || address.is_multicast() || broadcast {
2721        return Err(policy_error(format!(
2722            "{ip:?} is an unspecified, loopback, multicast or broadcast address"
2723        )));
2724    }
2725    Ok(())
2726}
2727
2728fn check_uri_name(uri: &str) -> Result<()> {
2729    let scheme_end = uri.find(':').unwrap_or(0);
2730    let scheme_ok = scheme_end > 0
2731        && uri[..scheme_end].starts_with(|c: char| c.is_ascii_alphabetic())
2732        && uri[..scheme_end]
2733            .chars()
2734            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
2735    let scheme = uri[..scheme_end].to_ascii_lowercase();
2736    if !matches!(scheme.as_str(), "http" | "https" | "urn" | "spiffe") {
2737        return Err(policy_error(format!(
2738            "URI scheme {scheme:?} is not allowed (http, https, urn, spiffe)"
2739        )));
2740    }
2741    if uri.len() > 2048
2742        || !scheme_ok
2743        || uri.len() == scheme_end + 1
2744        || !uri.chars().all(|c| c.is_ascii_graphic())
2745    {
2746        return Err(policy_error(format!("{uri:?} is not an acceptable URI")));
2747    }
2748    Ok(())
2749}
2750
2751fn check_email_name(email: &str) -> Result<()> {
2752    let (local, domain) = email
2753        .split_once('@')
2754        .ok_or_else(|| policy_error(format!("{email:?} is not an e-mail address")))?;
2755    if email.len() > 254
2756        || local.is_empty()
2757        || local.len() > 64
2758        || domain.contains('@')
2759        || !email.chars().all(|c| c.is_ascii_graphic())
2760    {
2761        return Err(policy_error(format!(
2762            "{email:?} is not an acceptable e-mail address"
2763        )));
2764    }
2765    check_dns_name(domain, false)
2766}
2767
2768/// Check one subject alternative name against the profile's policy.
2769fn check_san(san: &SubjectAltName, policy: &SanPolicy) -> Result<()> {
2770    match san {
2771        SubjectAltName::DnsName(name) => check_dns_name(name, policy.wildcard_dns),
2772        SubjectAltName::IpAddress(ip) if policy.ip_address => check_ip_name(ip),
2773        SubjectAltName::Uri(uri) if policy.uri => check_uri_name(uri),
2774        SubjectAltName::Email(email) if policy.email => check_email_name(email),
2775        other => Err(policy_error(format!(
2776            "{other:?} subject alternative names are not allowed by the profile"
2777        ))),
2778    }
2779}
2780
2781/// Security strength in bits of an RSA modulus of `bits` bits (NIST SP 800-57).
2782fn rsa_strength(bits: usize) -> u32 {
2783    match bits {
2784        0..=2047 => 0,
2785        2048..=3071 => 112,
2786        3072..=7679 => 128,
2787        _ => 192,
2788    }
2789}
2790
2791/// The strength a profile's `preferred_key_type` asks for as a minimum.
2792fn required_strength(minimum: &KeyType) -> u32 {
2793    match minimum {
2794        KeyType::Rsa(bits) => rsa_strength(*bits as usize).max(112),
2795        KeyType::Ecdsa(EcdsaCurve::P256) | KeyType::Ed25519 => 128,
2796        KeyType::Ecdsa(EcdsaCurve::P384) => 192,
2797        KeyType::Ecdsa(EcdsaCurve::P521) => 256,
2798    }
2799}
2800
2801/// A subject key must be well-formed, on the allow-list (RSA of 2048 to 16384 bits, ECDSA
2802/// P-256 / P-384, Ed25519) and at least as strong as the profile's minimum.
2803fn check_subject_key(public_key_pem: &str, minimum: &KeyType) -> Result<()> {
2804    use x509_parser::prelude::FromDer;
2805    use x509_parser::public_key::PublicKey;
2806
2807    let (_, pem) = x509_parser::pem::parse_x509_pem(public_key_pem.as_bytes())
2808        .map_err(|e| policy_error(format!("public_key_pem is not PEM: {e}")))?;
2809    if pem.label != "PUBLIC KEY" {
2810        return Err(policy_error(
2811            "public_key_pem must be a PEM PUBLIC KEY (SubjectPublicKeyInfo)".to_string(),
2812        ));
2813    }
2814    let (rest, spki) = x509_parser::x509::SubjectPublicKeyInfo::from_der(&pem.contents)
2815        .map_err(|e| policy_error(format!("public_key_pem is not a SubjectPublicKeyInfo: {e}")))?;
2816    if !rest.is_empty() {
2817        return Err(policy_error(
2818            "Trailing data after the public key".to_string(),
2819        ));
2820    }
2821    let key_bytes: &[u8] = spki.subject_public_key.data.as_ref();
2822    let strength = match spki.parsed() {
2823        Ok(PublicKey::RSA(rsa)) => {
2824            let bits = rsa.key_size();
2825            if bits < 2048 {
2826                return Err(policy_error(format!(
2827                    "RSA key of {bits} bits is below the 2048-bit minimum"
2828                )));
2829            }
2830            if bits > 16384 {
2831                return Err(policy_error(format!(
2832                    "RSA key of {bits} bits is above the 16384-bit maximum"
2833                )));
2834            }
2835            if rsa.modulus.last().is_none_or(|b| b % 2 == 0) {
2836                return Err(policy_error("RSA modulus is even".to_string()));
2837            }
2838            let exponent = rsa
2839                .exponent
2840                .iter()
2841                .skip_while(|b| **b == 0)
2842                .collect::<Vec<_>>();
2843            let exponent_value = exponent
2844                .iter()
2845                .try_fold(0u64, |acc, b| acc.checked_mul(256).map(|v| v | **b as u64));
2846            match exponent_value {
2847                Some(e) if exponent.len() <= 8 && e >= 65_537 && e % 2 == 1 => {}
2848                _ => {
2849                    return Err(policy_error(
2850                        "RSA public exponent must be odd and at least 65537".to_string(),
2851                    ));
2852                }
2853            }
2854            rsa_strength(bits)
2855        }
2856        Ok(PublicKey::EC(_)) => {
2857            let curve = spki
2858                .algorithm
2859                .parameters
2860                .as_ref()
2861                .and_then(|p| p.as_oid().ok())
2862                .map(|oid| oid.to_string());
2863            let (algorithm, point_len, strength) = match curve.as_deref() {
2864                Some("1.2.840.10045.3.1.7") => (&ring::agreement::ECDH_P256, 65, 128),
2865                Some("1.3.132.0.34") => (&ring::agreement::ECDH_P384, 97, 192),
2866                other => {
2867                    return Err(policy_error(format!(
2868                        "EC curve {other:?} is not allowed (P-256, P-384)"
2869                    )));
2870                }
2871            };
2872            if key_bytes.len() != point_len || key_bytes[0] != 0x04 {
2873                return Err(policy_error(
2874                    "EC public key must be an uncompressed point of the curve's size".to_string(),
2875                ));
2876            }
2877            // ring validates the peer's point (it must lie on the curve) when it is used.
2878            let rng = ring::rand::SystemRandom::new();
2879            let ephemeral = ring::agreement::EphemeralPrivateKey::generate(algorithm, &rng)
2880                .map_err(|_| AuthError::internal("System random number generator failed"))?;
2881            ring::agreement::agree_ephemeral(
2882                ephemeral,
2883                &ring::agreement::UnparsedPublicKey::new(algorithm, key_bytes),
2884                |_| (),
2885            )
2886            .map_err(|_| policy_error("EC public key is not a point on the curve".to_string()))?;
2887            strength
2888        }
2889        _ if spki.algorithm.algorithm.to_string() == "1.3.101.112" => {
2890            // Ed25519 (RFC 8410): 32-byte key, no algorithm parameters.
2891            if key_bytes.len() != 32 || spki.algorithm.parameters.is_some() {
2892                return Err(policy_error(
2893                    "Ed25519 public key must be 32 bytes without parameters".to_string(),
2894                ));
2895            }
2896            128
2897        }
2898        _ => {
2899            return Err(policy_error(
2900                "Only RSA, ECDSA (P-256, P-384) and Ed25519 subject keys are accepted".to_string(),
2901            ));
2902        }
2903    };
2904    if strength < required_strength(minimum) {
2905        return Err(policy_error(format!(
2906            "Subject key is weaker than the profile's minimum ({minimum:?})"
2907        )));
2908    }
2909    Ok(())
2910}
2911
2912/// A profile that contradicts itself is refused rather than half-honoured: an end-entity
2913/// profile may not ask for certificate or CRL signing, and the profile's type must be backed by
2914/// the extended key usage it implies.
2915fn validate_profile(name: &str, profile: &CertificateProfile) -> Result<()> {
2916    let bad = |why: &str| AuthError::config(format!("Certificate profile '{name}': {why}"));
2917    let ca_profile = matches!(
2918        profile.cert_type,
2919        CertificateType::RootCA | CertificateType::IntermediateCA
2920    );
2921    if !ca_profile
2922        && profile
2923            .key_usage
2924            .iter()
2925            .any(|ku| matches!(ku, KeyUsage::KeyCertSign | KeyUsage::CrlSign))
2926    {
2927        return Err(bad(
2928            "an end-entity profile cannot ask for keyCertSign or cRLSign (the certificate would be cA=FALSE)",
2929        ));
2930    }
2931    let required = match profile.cert_type {
2932        CertificateType::TlsServer => Some(ExtendedKeyUsage::ServerAuth),
2933        CertificateType::TlsClient => Some(ExtendedKeyUsage::ClientAuth),
2934        CertificateType::CodeSigning => Some(ExtendedKeyUsage::CodeSigning),
2935        CertificateType::Email => Some(ExtendedKeyUsage::EmailProtection),
2936        _ => None,
2937    };
2938    if let Some(required) = required
2939        && !profile.extended_key_usage.contains(&required)
2940    {
2941        return Err(bad(&format!(
2942            "its type needs {required:?} in extended_key_usage"
2943        )));
2944    }
2945    if profile.validity_days < 0 {
2946        return Err(bad("validity_days cannot be negative"));
2947    }
2948    Ok(())
2949}
2950
2951/// Whether a certificate may be used for `purpose` by its own extended key usage (none at
2952/// all: any purpose).
2953fn certificate_allows_purpose(der: &[u8], purpose: CertificatePurpose) -> bool {
2954    let Ok((_, cert)) = parse_x509_certificate(der) else {
2955        return false;
2956    };
2957    match cert.extended_key_usage() {
2958        Ok(None) => true,
2959        Ok(Some(eku)) => {
2960            let eku = &eku.value;
2961            eku.any
2962                || match purpose {
2963                    CertificatePurpose::ServerAuth => eku.server_auth,
2964                    CertificatePurpose::ClientAuth => eku.client_auth,
2965                    CertificatePurpose::CodeSigning => eku.code_signing,
2966                    CertificatePurpose::EmailProtection => eku.email_protection,
2967                    CertificatePurpose::TimeStamping => eku.time_stamping,
2968                    CertificatePurpose::OcspSigning => eku.ocsp_signing,
2969                }
2970        }
2971        Err(_) => false,
2972    }
2973}
2974
2975/// Write `contents` to `path` through a synced temporary file and a rename, then sync the
2976/// directory (Unix). Runs on a blocking thread.
2977fn write_state_file(path: &str, contents: &[u8]) -> Result<()> {
2978    use std::io::Write;
2979
2980    let fail = |what: &str, e: std::io::Error| {
2981        AuthError::internal(format!("Failed to {what} state file {path}: {e}"))
2982    };
2983    let target = std::path::Path::new(path);
2984    if let Some(parent) = target.parent()
2985        && !parent.as_os_str().is_empty()
2986    {
2987        std::fs::create_dir_all(parent).map_err(|e| fail("create the directory of", e))?;
2988    }
2989    let temporary = format!("{path}.tmp");
2990    let written = (|| -> std::io::Result<()> {
2991        let mut file = std::fs::File::create(&temporary)?;
2992        file.write_all(contents)?;
2993        file.sync_all()?;
2994        std::fs::rename(&temporary, path)
2995    })();
2996    if let Err(e) = written {
2997        let _ = std::fs::remove_file(&temporary);
2998        return Err(fail("write", e));
2999    }
3000    #[cfg(unix)]
3001    if let Some(parent) = target.parent() {
3002        let dir = if parent.as_os_str().is_empty() {
3003            std::path::Path::new(".")
3004        } else {
3005            parent
3006        };
3007        std::fs::File::open(dir)
3008            .and_then(|d| d.sync_all())
3009            .map_err(|e| fail("sync the directory of", e))?;
3010    }
3011    Ok(())
3012}
3013
3014/// Everything about a request that does not need the CA: unsupported inputs are refused,
3015/// names and key are checked against the profile. Nothing is issued or numbered before this.
3016fn validate_request(request: &CertificateRequest, profile: &CertificateProfile) -> Result<()> {
3017    if !request.attributes.is_empty() {
3018        return Err(policy_error(
3019            "request attributes are not supported and would be ignored".to_string(),
3020        ));
3021    }
3022    if !profile.extensions.is_empty() {
3023        return Err(policy_error(format!(
3024            "profile '{}' uses extensions, which are not supported",
3025            profile.name
3026        )));
3027    }
3028
3029    check_text("request id", &request.request_id, 128)?;
3030    let subject = &request.subject;
3031    check_text("common name", &subject.common_name, 64)?;
3032    for (field, value, max) in [
3033        ("organization", &subject.organization, 64),
3034        ("organizational unit", &subject.organizational_unit, 64),
3035        ("state", &subject.state, 128),
3036        ("locality", &subject.locality, 128),
3037    ] {
3038        if let Some(value) = value {
3039            check_text(field, value, max)?;
3040        }
3041    }
3042    if let Some(country) = &subject.country
3043        && !(country.len() == 2 && country.chars().all(|c| c.is_ascii_uppercase()))
3044    {
3045        return Err(policy_error(
3046            "country must be a two-letter upper-case code".to_string(),
3047        ));
3048    }
3049
3050    let names = profile.subject_alt_names.len() + request.subject_alt_names.len();
3051    if names > 25 {
3052        return Err(policy_error(
3053            "at most 25 subject alternative names are accepted".to_string(),
3054        ));
3055    }
3056    for san in profile
3057        .subject_alt_names
3058        .iter()
3059        .chain(request.subject_alt_names.iter())
3060    {
3061        check_san(san, &profile.san_policy)?;
3062    }
3063    if let Some(email) = &subject.email {
3064        check_san(&SubjectAltName::Email(email.clone()), &profile.san_policy)?;
3065    }
3066
3067    check_subject_key(&request.public_key_pem, &profile.preferred_key_type)
3068}
3069
3070/// Create a file that must not already exist and write `contents` to it; with `private` it is
3071/// readable by its owner only (on Unix; on other platforms the directory's ACL applies).
3072fn write_new_file(path: &str, contents: &[u8], private: bool) -> Result<()> {
3073    use std::io::Write;
3074
3075    if let Some(parent) = std::path::Path::new(path).parent()
3076        && !parent.as_os_str().is_empty()
3077    {
3078        std::fs::create_dir_all(parent).map_err(|e| {
3079            AuthError::internal(format!("Failed to create {}: {}", parent.display(), e))
3080        })?;
3081    }
3082    let mut options = std::fs::OpenOptions::new();
3083    options.write(true).create_new(true);
3084    #[cfg(unix)]
3085    if private {
3086        use std::os::unix::fs::OpenOptionsExt;
3087        options.mode(0o600);
3088    }
3089    #[cfg(not(unix))]
3090    let _ = private;
3091    let mut file = options
3092        .open(path)
3093        .map_err(|e| AuthError::internal(format!("Failed to create {}: {}", path, e)))?;
3094    file.write_all(contents)
3095        .map_err(|e| AuthError::internal(format!("Failed to write {}: {}", path, e)))
3096}
3097
3098// ─── Module-level helpers ─────────────────────────────────────────────────────
3099
3100/// Extract the first `-----BEGIN CERTIFICATE-----` … `-----END CERTIFICATE-----`
3101/// block from a PEM bundle.  Private key blocks and extra certificate entries are
3102/// discarded.  If no proper PEM block is found the input is returned unchanged.
3103fn x509_extract_certificate_pem(pem: &str) -> String {
3104    let mut in_cert = false;
3105    let mut lines: Vec<&str> = Vec::new();
3106    let mut collected = false;
3107
3108    for line in pem.lines() {
3109        if line.starts_with("-----BEGIN CERTIFICATE-----") {
3110            if collected {
3111                break; // Only keep the first certificate.
3112            }
3113            in_cert = true;
3114            collected = true;
3115            lines.push(line);
3116        } else if line.starts_with("-----END CERTIFICATE-----") {
3117            lines.push(line);
3118            in_cert = false;
3119        } else if in_cert {
3120            lines.push(line);
3121        }
3122    }
3123
3124    if collected {
3125        lines.join("\n") + "\n"
3126    } else {
3127        pem.to_string()
3128    }
3129}
3130
3131/// Parameters for building an AWS SigV4 `Authorization` header.
3132///
3133/// Use [`AwsSigV4Request::new`] to create an instance with the required
3134/// credentials, then set the remaining fields with chainable helpers:
3135///
3136/// ```rust,ignore
3137/// let auth = AwsSigV4Request::new("AKIA…", "secret")
3138///     .region("us-east-1")
3139///     .service("secretsmanager")
3140///     .method("POST")
3141///     .host("secretsmanager.us-east-1.amazonaws.com")
3142///     .payload(b"{\"SecretId\":\"my-secret\"}")
3143///     .amz_date("20230101T000000Z")
3144///     .date_stamp("20230101")
3145///     .amz_target("secretsmanager.GetSecretValue")
3146///     .sign();
3147/// ```
3148struct AwsSigV4Request<'a> {
3149    access_key: &'a str,
3150    secret_key: &'a str,
3151    session_token: Option<&'a str>,
3152    region: &'a str,
3153    service: &'a str,
3154    method: &'a str,
3155    host: &'a str,
3156    path: &'a str,
3157    query: &'a str,
3158    payload: &'a [u8],
3159    amz_date: &'a str,
3160    date_stamp: &'a str,
3161    amz_target: &'a str,
3162}
3163
3164impl<'a> AwsSigV4Request<'a> {
3165    /// Create a new request with the required AWS credentials.
3166    fn new(access_key: &'a str, secret_key: &'a str) -> Self {
3167        Self {
3168            access_key,
3169            secret_key,
3170            session_token: None,
3171            region: "us-east-1",
3172            service: "",
3173            method: "POST",
3174            host: "",
3175            path: "/",
3176            query: "",
3177            payload: b"",
3178            amz_date: "",
3179            date_stamp: "",
3180            amz_target: "",
3181        }
3182    }
3183
3184    fn session_token(mut self, token: Option<&'a str>) -> Self {
3185        self.session_token = token;
3186        self
3187    }
3188
3189    fn region(mut self, region: &'a str) -> Self {
3190        self.region = region;
3191        self
3192    }
3193
3194    fn service(mut self, service: &'a str) -> Self {
3195        self.service = service;
3196        self
3197    }
3198
3199    fn method(mut self, method: &'a str) -> Self {
3200        self.method = method;
3201        self
3202    }
3203
3204    fn host(mut self, host: &'a str) -> Self {
3205        self.host = host;
3206        self
3207    }
3208
3209    fn payload(mut self, payload: &'a [u8]) -> Self {
3210        self.payload = payload;
3211        self
3212    }
3213
3214    fn amz_date(mut self, amz_date: &'a str) -> Self {
3215        self.amz_date = amz_date;
3216        self
3217    }
3218
3219    fn date_stamp(mut self, date_stamp: &'a str) -> Self {
3220        self.date_stamp = date_stamp;
3221        self
3222    }
3223
3224    fn amz_target(mut self, amz_target: &'a str) -> Self {
3225        self.amz_target = amz_target;
3226        self
3227    }
3228
3229    /// Compute the AWS SigV4 `Authorization` header value.
3230    ///
3231    /// Implements [AWS Signature Version 4](https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html).
3232    fn sign(&self) -> String {
3233        use hmac::{Mac, SimpleHmac};
3234        use sha2::{Digest, Sha256};
3235
3236        fn hmac_sha256(key: &[u8], data: &[u8]) -> Vec<u8> {
3237            let mut mac =
3238                <SimpleHmac<Sha256>>::new_from_slice(key).expect("HMAC accepts any key size");
3239            mac.update(data);
3240            mac.finalize().into_bytes().to_vec()
3241        }
3242
3243        fn sha256hex(data: &[u8]) -> String {
3244            let mut h = Sha256::new();
3245            h.update(data);
3246            hex::encode(h.finalize())
3247        }
3248
3249        let mut headers: Vec<(String, String)> = vec![
3250            ("content-type".into(), "application/x-amz-json-1.1".into()),
3251            ("host".into(), self.host.into()),
3252            ("x-amz-date".into(), self.amz_date.into()),
3253            ("x-amz-target".into(), self.amz_target.into()),
3254        ];
3255        if let Some(tok) = self.session_token {
3256            headers.push(("x-amz-security-token".into(), tok.into()));
3257        }
3258        headers.sort_by(|a, b| a.0.cmp(&b.0));
3259
3260        let canonical_headers: String = headers
3261            .iter()
3262            .map(|(k, v)| format!("{}:{}\n", k, v.trim()))
3263            .collect();
3264        let signed_headers: String = headers
3265            .iter()
3266            .map(|(k, _)| k.as_str())
3267            .collect::<Vec<_>>()
3268            .join(";");
3269
3270        let canonical_request = format!(
3271            "{method}\n{path}\n{query}\n{canonical_headers}\n{signed_headers}\n{payload_hash}",
3272            method = self.method,
3273            path = self.path,
3274            query = self.query,
3275            canonical_headers = canonical_headers,
3276            signed_headers = signed_headers,
3277            payload_hash = sha256hex(self.payload),
3278        );
3279
3280        let credential_scope = format!(
3281            "{}/{}/{}/aws4_request",
3282            self.date_stamp, self.region, self.service
3283        );
3284        let string_to_sign = format!(
3285            "AWS4-HMAC-SHA256\n{amz_date}\n{credential_scope}\n{canonical_hash}",
3286            amz_date = self.amz_date,
3287            credential_scope = credential_scope,
3288            canonical_hash = sha256hex(canonical_request.as_bytes()),
3289        );
3290
3291        let signing_key = hmac_sha256(
3292            &hmac_sha256(
3293                &hmac_sha256(
3294                    &hmac_sha256(
3295                        format!("AWS4{}", self.secret_key).as_bytes(),
3296                        self.date_stamp.as_bytes(),
3297                    ),
3298                    self.region.as_bytes(),
3299                ),
3300                self.service.as_bytes(),
3301            ),
3302            b"aws4_request",
3303        );
3304
3305        let signature = hex::encode(hmac_sha256(&signing_key, string_to_sign.as_bytes()));
3306
3307        format!(
3308            "AWS4-HMAC-SHA256 Credential={access_key}/{credential_scope}, SignedHeaders={signed_headers}, Signature={signature}",
3309            access_key = self.access_key,
3310            credential_scope = credential_scope,
3311            signed_headers = signed_headers,
3312            signature = signature,
3313        )
3314    }
3315}
3316
3317#[cfg(test)]
3318mod tests {
3319    use super::*;
3320
3321    #[tokio::test]
3322    async fn test_x509_manager_creation() {
3323        let config = X509Config::default();
3324        let manager = X509CertificateManager::new(config);
3325
3326        // Test basic functionality
3327        assert!(!manager.config.certificate_profiles.is_empty());
3328        assert_eq!(manager.config.default_validity_days, 365);
3329    }
3330
3331    #[tokio::test]
3332    async fn test_certificate_profile() {
3333        let config = X509Config::default();
3334
3335        // Check default profiles
3336        assert!(config.certificate_profiles.contains_key("tls_server"));
3337        assert!(config.certificate_profiles.contains_key("tls_client"));
3338
3339        let tls_server_profile = &config.certificate_profiles["tls_server"];
3340        assert_eq!(tls_server_profile.cert_type, CertificateType::TlsServer);
3341        assert!(
3342            tls_server_profile
3343                .extended_key_usage
3344                .contains(&ExtendedKeyUsage::ServerAuth)
3345        );
3346    }
3347
3348    #[tokio::test]
3349    async fn test_certificate_filter() {
3350        let filter = CertificateFilter {
3351            status: Some(CertificateStatus::Valid),
3352            profile: None,
3353            expires_before: None,
3354            expires_after: None,
3355            subject_contains: Some("example.com".to_string()),
3356        };
3357
3358        let cert = StoredCertificate {
3359            cert_id: "test".to_string(),
3360            certificate_pem: "".to_string(),
3361            private_key_pem: None,
3362            subject: "CN=example.com".to_string(),
3363            issuer: "CN=Test CA".to_string(),
3364            serial_number: "123".to_string(),
3365            not_before: Utc::now(),
3366            not_after: Utc::now() + Duration::days(365),
3367            profile: "tls_server".to_string(),
3368            status: CertificateStatus::Valid,
3369            fingerprint: "test_fp".to_string(),
3370            created_at: Utc::now(),
3371            metadata: HashMap::new(),
3372        };
3373
3374        assert!(filter.matches(&cert));
3375    }
3376
3377    // ─── HSM / Azure / AWS integration unit tests ─────────────────────────────
3378
3379    #[test]
3380    fn test_x509_extract_certificate_pem_single_cert() {
3381        let pem = "-----BEGIN CERTIFICATE-----\nMIIBxx==\n-----END CERTIFICATE-----\n";
3382        let extracted = x509_extract_certificate_pem(pem);
3383        assert!(extracted.contains("-----BEGIN CERTIFICATE-----"));
3384        assert!(extracted.contains("-----END CERTIFICATE-----"));
3385        assert!(extracted.contains("MIIBxx=="));
3386    }
3387
3388    #[test]
3389    fn test_x509_extract_certificate_pem_strips_key() {
3390        // A PEM bundle with a private key + certificate — only the cert should come out.
3391        let bundle = concat!(
3392            "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAK==\n-----END RSA PRIVATE KEY-----\n",
3393            "-----BEGIN CERTIFICATE-----\nMIICert==\n-----END CERTIFICATE-----\n",
3394        );
3395        let extracted = x509_extract_certificate_pem(bundle);
3396        assert!(
3397            !extracted.contains("PRIVATE KEY"),
3398            "Private key must be stripped"
3399        );
3400        assert!(extracted.contains("-----BEGIN CERTIFICATE-----"));
3401        assert!(extracted.contains("MIICert=="));
3402    }
3403
3404    #[test]
3405    fn test_x509_extract_certificate_pem_keeps_first_only() {
3406        let bundle = concat!(
3407            "-----BEGIN CERTIFICATE-----\nMIIFirst==\n-----END CERTIFICATE-----\n",
3408            "-----BEGIN CERTIFICATE-----\nMIISecond==\n-----END CERTIFICATE-----\n",
3409        );
3410        let extracted = x509_extract_certificate_pem(bundle);
3411        assert!(
3412            extracted.contains("MIIFirst=="),
3413            "First cert should be kept"
3414        );
3415        assert!(
3416            !extracted.contains("MIISecond=="),
3417            "Second cert must be discarded"
3418        );
3419    }
3420
3421    #[test]
3422    fn test_aws_sigv4_authorization_format() {
3423        // Verify the output is structured like a valid AWS SigV4 Authorization header.
3424        let auth = AwsSigV4Request::new(
3425            "AKIAIOSFODNN7EXAMPLE",
3426            "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
3427        )
3428        .region("us-east-1")
3429        .service("secretsmanager")
3430        .method("POST")
3431        .host("secretsmanager.us-east-1.amazonaws.com")
3432        .payload(b"{\"SecretId\":\"my-secret\"}")
3433        .amz_date("20230101T000000Z")
3434        .date_stamp("20230101")
3435        .amz_target("secretsmanager.GetSecretValue")
3436        .sign();
3437        assert!(auth.starts_with("AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20230101/"));
3438        assert!(auth.contains("SignedHeaders="));
3439        assert!(auth.contains("Signature="));
3440        // Signature must be a 64-character hex string.
3441        let sig_part = auth.split("Signature=").nth(1).unwrap_or("");
3442        assert_eq!(sig_part.len(), 64, "SigV4 signature must be 64 hex chars");
3443    }
3444
3445    #[tokio::test]
3446    async fn test_azure_vault_missing_tenant_id() {
3447        // Clear any accidentally-set env vars to ensure the credential-absent error path.
3448        // Skip this test if real Azure credentials happen to be set (CI environment).
3449        if std::env::var("X509_AZURE_TENANT_ID").is_ok() {
3450            return;
3451        }
3452        let config = X509Config::default();
3453        let manager = X509CertificateManager::new(config);
3454        let result = manager
3455            .load_ca_from_azure_vault("https://test.vault.azure.net", "my-ca")
3456            .await;
3457        assert!(result.is_err(), "Should fail when tenant_id is not set");
3458        let msg = format!("{}", result.unwrap_err());
3459        assert!(
3460            msg.contains("X509_AZURE_TENANT_ID"),
3461            "Error should name the missing variable: {msg}"
3462        );
3463    }
3464
3465    #[tokio::test]
3466    async fn test_aws_secrets_missing_access_key() {
3467        // Skip if real AWS credentials are set.
3468        if std::env::var("AWS_ACCESS_KEY_ID").is_ok() {
3469            return;
3470        }
3471        let config = X509Config::default();
3472        let manager = X509CertificateManager::new(config);
3473        let result = manager.load_ca_from_aws_secrets("my-ca-cert").await;
3474        assert!(
3475            result.is_err(),
3476            "Should fail when AWS_ACCESS_KEY_ID is not set"
3477        );
3478        let msg = format!("{}", result.unwrap_err());
3479        assert!(
3480            msg.contains("AWS_ACCESS_KEY_ID"),
3481            "Error should name the missing variable: {msg}"
3482        );
3483    }
3484
3485    #[tokio::test]
3486    #[cfg(feature = "hsm")]
3487    async fn test_hsm_invalid_json_config() {
3488        let config = X509Config::default();
3489        let manager = X509CertificateManager::new(config);
3490        // Pass nonsense — must get a clear JSON-parse error, not a panic.
3491        let result = manager.load_ca_from_hsm("not-valid-json").await;
3492        assert!(result.is_err());
3493        let msg = format!("{}", result.unwrap_err());
3494        assert!(
3495            msg.contains("JSON") || msg.contains("json") || msg.contains("X509_HSM_CONFIG"),
3496            "Error should mention JSON parsing: {msg}"
3497        );
3498    }
3499
3500    #[tokio::test]
3501    #[cfg(feature = "hsm")]
3502    async fn test_hsm_missing_library_field() {
3503        let config = X509Config::default();
3504        let manager = X509CertificateManager::new(config);
3505        // Valid JSON but missing the required 'library' field.
3506        let result = manager
3507            .load_ca_from_hsm(r#"{"slot": 0, "pin": "1234", "label": "ca-cert"}"#)
3508            .await;
3509        assert!(result.is_err());
3510        let msg = format!("{}", result.unwrap_err());
3511        assert!(
3512            msg.contains("library"),
3513            "Error should mention the missing 'library' field: {msg}"
3514        );
3515    }
3516
3517    #[tokio::test]
3518    #[cfg(feature = "hsm")]
3519    async fn test_hsm_nonexistent_library_path() {
3520        let config = X509Config::default();
3521        let manager = X509CertificateManager::new(config);
3522        let result = manager
3523            .load_ca_from_hsm(
3524                r#"{"library": "/nonexistent/pkcs11/libpkcs11.so", "slot": 0, "pin": "", "label": "ca-cert"}"#,
3525            )
3526            .await;
3527        // Should return an error about the library not being found, not a panic.
3528        assert!(
3529            result.is_err(),
3530            "Expected error loading non-existent PKCS#11 library"
3531        );
3532    }
3533
3534    // ─── Real-certificate tests ────────────────────────────────────────────────
3535
3536    use rcgen::{
3537        BasicConstraints, CertificateParams, DistinguishedName, DnType, ExtendedKeyUsagePurpose,
3538        IsCa, Issuer, KeyPair, KeyUsagePurpose, PKCS_ECDSA_P256_SHA256,
3539    };
3540    use std::path::{Path, PathBuf};
3541    use x509_parser::prelude::FromDer;
3542
3543    /// A CA held by the test: its certificate and key.
3544    struct TestCa {
3545        cert_pem: String,
3546        key_pem: String,
3547    }
3548
3549    fn ca_params(cn: &str) -> CertificateParams {
3550        let mut params = CertificateParams::new(Vec::<String>::new()).unwrap();
3551        params.distinguished_name = DistinguishedName::new();
3552        params.distinguished_name.push(DnType::CommonName, cn);
3553        params
3554            .distinguished_name
3555            .push(DnType::OrganizationName, "Test Org");
3556        params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
3557        params.key_usages = vec![
3558            KeyUsagePurpose::KeyCertSign,
3559            KeyUsagePurpose::CrlSign,
3560            KeyUsagePurpose::DigitalSignature,
3561        ];
3562        params
3563    }
3564
3565    fn new_key() -> KeyPair {
3566        KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap()
3567    }
3568
3569    impl TestCa {
3570        fn root(cn: &str) -> Self {
3571            Self::root_with(ca_params(cn))
3572        }
3573
3574        fn root_with(params: CertificateParams) -> Self {
3575            let key = new_key();
3576            let cert = params.self_signed(&key).unwrap();
3577            TestCa {
3578                cert_pem: cert.pem(),
3579                key_pem: key.serialize_pem(),
3580            }
3581        }
3582
3583        fn issuer(&self) -> Issuer<'static, KeyPair> {
3584            Issuer::from_ca_cert_pem(&self.cert_pem, KeyPair::from_pem(&self.key_pem).unwrap())
3585                .unwrap()
3586        }
3587
3588        fn intermediate(&self, cn: &str) -> Self {
3589            let key = new_key();
3590            let cert = ca_params(cn).signed_by(&key, &self.issuer()).unwrap();
3591            TestCa {
3592                cert_pem: cert.pem(),
3593                key_pem: key.serialize_pem(),
3594            }
3595        }
3596
3597        /// A leaf signed by this CA; `adjust` can change its parameters.
3598        fn leaf(&self, cn: &str, adjust: impl FnOnce(&mut CertificateParams)) -> String {
3599            let key = new_key();
3600            let mut params = CertificateParams::new(vec![format!("{cn}.example")]).unwrap();
3601            params.distinguished_name = DistinguishedName::new();
3602            params.distinguished_name.push(DnType::CommonName, cn);
3603            adjust(&mut params);
3604            params.signed_by(&key, &self.issuer()).unwrap().pem()
3605        }
3606
3607        fn write(&self, dir: &Path, name: &str) -> (PathBuf, PathBuf) {
3608            let cert = dir.join(format!("{name}.crt"));
3609            let key = dir.join(format!("{name}.key"));
3610            std::fs::write(&cert, &self.cert_pem).unwrap();
3611            std::fs::write(&key, &self.key_pem).unwrap();
3612            (cert, key)
3613        }
3614    }
3615
3616    fn config_for(cert: &Path, key: &Path) -> X509Config {
3617        X509Config {
3618            root_ca_path: cert.to_string_lossy().to_string(),
3619            root_ca_cert_path: cert.to_string_lossy().to_string(),
3620            root_ca_key_path: key.to_string_lossy().to_string(),
3621            ..X509Config::default()
3622        }
3623    }
3624
3625    /// An initialised manager whose root is `root` (with its key unless `with_key` is false).
3626    async fn manager_with(dir: &Path, root: &TestCa, with_key: bool) -> X509CertificateManager {
3627        let (cert, key) = root.write(dir, "root");
3628        if !with_key {
3629            std::fs::remove_file(&key).unwrap();
3630        }
3631        let manager = X509CertificateManager::new(config_for(&cert, &key));
3632        manager.initialize().await.unwrap();
3633        manager
3634    }
3635
3636    fn request(cn: &str, key: &KeyPair, profile: &str) -> CertificateRequest {
3637        CertificateRequest {
3638            request_id: format!("req-{cn}"),
3639            subject: CertificateSubject {
3640                common_name: cn.to_string(),
3641                organization: None,
3642                organizational_unit: None,
3643                country: None,
3644                state: None,
3645                locality: None,
3646                email: None,
3647            },
3648            subject_alt_names: vec![SubjectAltName::DnsName(format!("{cn}.example"))],
3649            public_key_pem: key.public_key_pem(),
3650            profile: profile.to_string(),
3651            requested_at: Utc::now(),
3652            requester: "tester".to_string(),
3653            attributes: HashMap::new(),
3654        }
3655    }
3656
3657    fn der_of(pem: &str) -> Vec<u8> {
3658        pem_certificates(pem).unwrap().remove(0)
3659    }
3660
3661    async fn ca_subject(manager: &X509CertificateManager, ca_id: &str) -> String {
3662        manager.ca_certificates.read().await[ca_id].subject.clone()
3663    }
3664
3665    #[tokio::test]
3666    async fn root_ca_metadata_is_read_from_the_certificate() {
3667        use sha2::{Digest, Sha256};
3668        let dir = tempfile::tempdir().unwrap();
3669        let root = TestCa::root("Real Root");
3670        let manager = manager_with(dir.path(), &root, true).await;
3671
3672        let cas = manager.ca_certificates.read().await;
3673        let ca = &cas["root_ca"];
3674        let der = der_of(&root.cert_pem);
3675        let (_, parsed) = parse_x509_certificate(&der).unwrap();
3676        assert_eq!(ca.subject, parsed.subject().to_string());
3677        assert!(ca.subject.contains("Real Root"), "{}", ca.subject);
3678        assert_eq!(ca.certificate.issuer, parsed.issuer().to_string());
3679        assert_eq!(ca.certificate.serial_number, parsed.serial.to_string());
3680        assert_eq!(
3681            ca.certificate.not_after.timestamp(),
3682            parsed.validity().not_after.timestamp()
3683        );
3684        let expected = Sha256::digest(&der)
3685            .iter()
3686            .map(|b| format!("{b:02X}"))
3687            .collect::<Vec<_>>()
3688            .join(":");
3689        assert_eq!(ca.certificate.fingerprint, expected);
3690        assert!(!ca.private_key.is_empty(), "the CA key is loaded");
3691    }
3692
3693    #[tokio::test]
3694    async fn unusable_root_ca_files_are_refused() {
3695        let dir = tempfile::tempdir().unwrap();
3696        let key_path = dir.path().join("root.key");
3697
3698        // Not a certificate.
3699        let cert_path = dir.path().join("garbage.crt");
3700        std::fs::write(&cert_path, "this is not a certificate").unwrap();
3701        let manager = X509CertificateManager::new(config_for(&cert_path, &key_path));
3702        assert!(manager.initialize().await.is_err());
3703        assert!(manager.ca_certificates.read().await.is_empty());
3704
3705        // A certificate that is not a CA.
3706        let root = TestCa::root("Issuer");
3707        let leaf_path = dir.path().join("leaf.crt");
3708        std::fs::write(&leaf_path, root.leaf("not-a-ca", |_| {})).unwrap();
3709        let manager = X509CertificateManager::new(config_for(&leaf_path, &key_path));
3710        assert!(manager.initialize().await.is_err());
3711
3712        // An expired CA.
3713        let mut params = ca_params("Old Root");
3714        params.not_before = rcgen::date_time_ymd(2000, 1, 1);
3715        params.not_after = rcgen::date_time_ymd(2001, 1, 1);
3716        let expired = TestCa::root_with(params);
3717        let (cert, key) = expired.write(dir.path(), "expired");
3718        let manager = X509CertificateManager::new(config_for(&cert, &key));
3719        assert!(manager.initialize().await.is_err());
3720    }
3721
3722    #[tokio::test]
3723    async fn a_key_that_does_not_belong_to_the_ca_is_refused() {
3724        let dir = tempfile::tempdir().unwrap();
3725        let root = TestCa::root("Root");
3726        let (cert, key) = root.write(dir.path(), "root");
3727        std::fs::write(&key, new_key().serialize_pem()).unwrap();
3728        let manager = X509CertificateManager::new(config_for(&cert, &key));
3729        assert!(manager.initialize().await.is_err());
3730        std::fs::write(&key, "not a key").unwrap();
3731        assert!(manager.initialize().await.is_err());
3732    }
3733
3734    #[tokio::test]
3735    async fn a_missing_root_is_not_generated_without_a_place_for_its_key() {
3736        let dir = tempfile::tempdir().unwrap();
3737        let cert = dir.path().join("root.crt");
3738        let mut config = config_for(&cert, &dir.path().join("root.key"));
3739        config.root_ca_key_path = String::new();
3740        config.generate_development_root_ca = true;
3741        let manager = X509CertificateManager::new(config);
3742        assert!(manager.initialize().await.is_err());
3743        assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0);
3744    }
3745
3746    #[tokio::test]
3747    async fn a_development_root_keeps_its_key_only_at_the_configured_path() {
3748        let dir = tempfile::tempdir().unwrap();
3749        let cert = dir.path().join("pki").join("root.crt");
3750        let key = dir.path().join("keys").join("root.key");
3751
3752        // Without the explicit opt-in a missing root is an error, and nothing is created.
3753        let off = X509CertificateManager::new(config_for(&cert, &key));
3754        assert!(off.initialize().await.is_err());
3755        assert!(!cert.exists() && !key.exists());
3756
3757        let mut config = config_for(&cert, &key);
3758        config.generate_development_root_ca = true;
3759        let manager = X509CertificateManager::new(config);
3760        manager.initialize().await.unwrap();
3761
3762        assert!(cert.exists() && key.exists());
3763        // Nothing else was written, in particular no "ca.key" beside the certificate.
3764        let beside_cert: Vec<_> = std::fs::read_dir(cert.parent().unwrap())
3765            .unwrap()
3766            .map(|e| e.unwrap().file_name())
3767            .collect();
3768        assert_eq!(beside_cert.len(), 1, "{beside_cert:?}");
3769        #[cfg(unix)]
3770        {
3771            use std::os::unix::fs::PermissionsExt;
3772            assert_eq!(
3773                std::fs::metadata(&key).unwrap().permissions().mode() & 0o777,
3774                0o600
3775            );
3776        }
3777
3778        // It can sign, and a restart loads the same root rather than a new one.
3779        let leaf_key = new_key();
3780        manager
3781            .sign_certificate_request(&request("dev", &leaf_key, "tls_client"), "root_ca")
3782            .await
3783            .unwrap();
3784        let fingerprint = manager.ca_certificates.read().await["root_ca"]
3785            .certificate
3786            .fingerprint
3787            .clone();
3788        let restarted = X509CertificateManager::new(config_for(&cert, &key));
3789        restarted.initialize().await.unwrap(); // the files exist now: no opt-in needed
3790        assert_eq!(
3791            restarted.ca_certificates.read().await["root_ca"]
3792                .certificate
3793                .fingerprint,
3794            fingerprint
3795        );
3796
3797        // An existing key is never overwritten by generating a root.
3798        std::fs::remove_file(&cert).unwrap();
3799        let before = std::fs::read(&key).unwrap();
3800        let again = X509CertificateManager::new(config_for(&cert, &key));
3801        assert!(again.initialize().await.is_err());
3802        assert_eq!(std::fs::read(&key).unwrap(), before);
3803    }
3804
3805    #[tokio::test]
3806    async fn a_ca_certificate_that_may_not_sign_certificates_is_refused() {
3807        let dir = tempfile::tempdir().unwrap();
3808        let mut params = ca_params("No Signing");
3809        params.key_usages = vec![KeyUsagePurpose::DigitalSignature];
3810        let ca = TestCa::root_with(params);
3811        let (cert, key) = ca.write(dir.path(), "root");
3812        let manager = X509CertificateManager::new(config_for(&cert, &key));
3813        assert!(manager.initialize().await.is_err());
3814    }
3815
3816    #[tokio::test]
3817    async fn the_two_root_path_settings_must_agree() {
3818        let dir = tempfile::tempdir().unwrap();
3819        let root = TestCa::root("Root");
3820        let (cert, key) = root.write(dir.path(), "root");
3821
3822        let mut config = config_for(&cert, &key);
3823        // A different, perfectly good CA file: only the disagreement is wrong.
3824        let other = TestCa::root("Other Root");
3825        let (other_cert, _) = other.write(dir.path(), "other");
3826        config.root_ca_path = other_cert.to_string_lossy().to_string();
3827        config.root_ca_key_path = String::new();
3828        assert!(
3829            X509CertificateManager::new(config)
3830                .initialize()
3831                .await
3832                .is_err()
3833        );
3834
3835        // Either name alone is enough.
3836        let mut config = config_for(&cert, &key);
3837        config.root_ca_path = String::new();
3838        X509CertificateManager::new(config)
3839            .initialize()
3840            .await
3841            .unwrap();
3842    }
3843
3844    #[tokio::test]
3845    async fn the_intermediate_is_loaded_under_either_path_setting() {
3846        let dir = tempfile::tempdir().unwrap();
3847        let root = TestCa::root("Root");
3848        let intermediate = root.intermediate("Issuing CA");
3849        let (root_cert, root_key) = root.write(dir.path(), "root");
3850        let (inter_cert, _) = intermediate.write(dir.path(), "inter");
3851
3852        for as_cert_path in [true, false] {
3853            let mut config = config_for(&root_cert, &root_key);
3854            let path = Some(inter_cert.to_string_lossy().to_string());
3855            if as_cert_path {
3856                config.intermediate_ca_cert_path = path;
3857            } else {
3858                config.intermediate_ca_path = path;
3859            }
3860            let manager = X509CertificateManager::new(config);
3861            manager.initialize().await.unwrap();
3862            let subject = ca_subject(&manager, "intermediate_ca").await;
3863            assert!(subject.contains("Issuing CA"), "{subject}");
3864            let cas = manager.ca_certificates.read().await;
3865            assert!(cas["intermediate_ca"].certificate.issuer.contains("Root"));
3866            assert_eq!(cas["intermediate_ca"].ca_type, CAType::Intermediate);
3867        }
3868    }
3869
3870    #[tokio::test]
3871    async fn an_intermediate_from_an_unknown_ca_or_a_missing_file_is_refused() {
3872        let dir = tempfile::tempdir().unwrap();
3873        let root = TestCa::root("Root");
3874        let stranger = TestCa::root("Stranger").intermediate("Foreign CA");
3875        let (root_cert, root_key) = root.write(dir.path(), "root");
3876        let (foreign, _) = stranger.write(dir.path(), "foreign");
3877
3878        let mut config = config_for(&root_cert, &root_key);
3879        config.intermediate_ca_cert_path = Some(foreign.to_string_lossy().to_string());
3880        assert!(
3881            X509CertificateManager::new(config)
3882                .initialize()
3883                .await
3884                .is_err()
3885        );
3886
3887        let mut config = config_for(&root_cert, &root_key);
3888        config.intermediate_ca_cert_path =
3889            Some(dir.path().join("absent.crt").to_string_lossy().to_string());
3890        assert!(
3891            X509CertificateManager::new(config)
3892                .initialize()
3893                .await
3894                .is_err()
3895        );
3896    }
3897
3898    #[tokio::test]
3899    async fn an_issued_certificate_carries_the_requesters_key_and_is_signed_by_the_ca() {
3900        use sha2::{Digest, Sha256};
3901        let dir = tempfile::tempdir().unwrap();
3902        let root = TestCa::root("Signing Root");
3903        let manager = manager_with(dir.path(), &root, true).await;
3904
3905        for profile in ["tls_server", "tls_client"] {
3906            let purpose = if profile == "tls_server" {
3907                CertificatePurpose::ServerAuth
3908            } else {
3909                CertificatePurpose::ClientAuth
3910            };
3911            let requester_key = new_key();
3912            let stored = manager
3913                .sign_certificate_request(&request("svc", &requester_key, profile), "root_ca")
3914                .await
3915                .unwrap();
3916            let der = der_of(&stored.certificate_pem);
3917            let (_, cert) = parse_x509_certificate(&der).unwrap();
3918
3919            // The subject key is the requester's, not a throwaway.
3920            assert_eq!(
3921                cert.public_key().subject_public_key.data.as_ref(),
3922                requester_key.public_key_raw()
3923            );
3924            // Signed by the CA, not self-signed.
3925            assert_ne!(cert.subject().to_string(), cert.issuer().to_string());
3926            assert_eq!(
3927                cert.issuer().to_string(),
3928                ca_subject(&manager, "root_ca").await
3929            );
3930            assert!(!cert.is_ca());
3931            // The record describes the certificate.
3932            assert_eq!(stored.subject, cert.subject().to_string());
3933            assert_eq!(stored.issuer, cert.issuer().to_string());
3934            assert_eq!(stored.serial_number, cert.serial.to_string());
3935            assert_eq!(
3936                stored.not_after.timestamp(),
3937                cert.validity().not_after.timestamp()
3938            );
3939            let digest = Sha256::digest(&der)
3940                .iter()
3941                .map(|b| format!("{b:02X}"))
3942                .collect::<Vec<_>>()
3943                .join(":");
3944            assert_eq!(
3945                stored.fingerprint, digest,
3946                "fingerprint is of the certificate"
3947            );
3948            // And it validates against the CA.
3949            assert!(
3950                manager
3951                    .validate_certificate_chain(&stored.certificate_pem, purpose)
3952                    .await
3953                    .unwrap(),
3954                "{profile}"
3955            );
3956            assert!(
3957                manager
3958                    .get_certificate(&stored.cert_id)
3959                    .await
3960                    .unwrap()
3961                    .is_some()
3962            );
3963        }
3964    }
3965
3966    #[tokio::test]
3967    async fn an_issued_certificate_is_not_valid_beyond_its_ca() {
3968        let dir = tempfile::tempdir().unwrap();
3969        let mut params = ca_params("Short Root");
3970        params.not_before = time::OffsetDateTime::now_utc() - time::Duration::days(1);
3971        params.not_after = time::OffsetDateTime::now_utc() + time::Duration::days(3);
3972        let root = TestCa::root_with(params);
3973        let manager = manager_with(dir.path(), &root, true).await;
3974        let stored = manager
3975            .sign_certificate_request(&request("svc", &new_key(), "tls_client"), "root_ca")
3976            .await
3977            .unwrap();
3978        // The profile asks for 365 days; the CA has 3.
3979        let ca_not_after = manager.ca_certificates.read().await["root_ca"]
3980            .certificate
3981            .not_after;
3982        assert!(stored.not_after <= ca_not_after);
3983    }
3984
3985    #[tokio::test]
3986    async fn a_ca_without_its_key_validates_but_does_not_issue() {
3987        let dir = tempfile::tempdir().unwrap();
3988        let root = TestCa::root("Verify Only");
3989        let manager = manager_with(dir.path(), &root, false).await;
3990
3991        let err = manager
3992            .sign_certificate_request(&request("svc", &new_key(), "tls_client"), "root_ca")
3993            .await
3994            .unwrap_err();
3995        assert!(err.to_string().contains("no signing key"), "{err}");
3996        assert!(manager.generate_crl("root_ca").await.is_err());
3997
3998        let leaf = root.leaf("known", |_| {});
3999        assert!(
4000            manager
4001                .validate_certificate_chain(&leaf, CertificatePurpose::ClientAuth)
4002                .await
4003                .unwrap()
4004        );
4005    }
4006
4007    #[tokio::test]
4008    async fn bad_requests_are_refused_instead_of_being_partly_honoured() {
4009        let dir = tempfile::tempdir().unwrap();
4010        let root = TestCa::root("Root");
4011        let mut config = config_for(&dir.path().join("root.crt"), &dir.path().join("root.key"));
4012        root.write(dir.path(), "root");
4013        config.certificate_profiles.insert(
4014            "ca".to_string(),
4015            CertificateProfile {
4016                name: "CA".to_string(),
4017                cert_type: CertificateType::IntermediateCA,
4018                key_usage: vec![KeyUsage::KeyCertSign],
4019                extended_key_usage: vec![],
4020                subject_alt_names: vec![],
4021                san_policy: SanPolicy::default(),
4022                validity_days: 30,
4023                preferred_key_type: KeyType::Ed25519,
4024                extensions: HashMap::new(),
4025            },
4026        );
4027        let manager = X509CertificateManager::new(config);
4028        manager.initialize().await.unwrap();
4029        let key = new_key();
4030
4031        // A CA profile is not issuable through a request.
4032        assert!(
4033            manager
4034                .sign_certificate_request(&request("sub-ca", &key, "ca"), "root_ca")
4035                .await
4036                .is_err()
4037        );
4038        // Unknown profile / CA, garbage key, blank name, unusable names.
4039        assert!(
4040            manager
4041                .sign_certificate_request(&request("x", &key, "nope"), "root_ca")
4042                .await
4043                .is_err()
4044        );
4045        assert!(
4046            manager
4047                .sign_certificate_request(&request("x", &key, "tls_client"), "nope")
4048                .await
4049                .is_err()
4050        );
4051        let mut bad_key = request("x", &key, "tls_client");
4052        bad_key.public_key_pem = "not a key".to_string();
4053        assert!(
4054            manager
4055                .sign_certificate_request(&bad_key, "root_ca")
4056                .await
4057                .is_err()
4058        );
4059        let mut blank = request("  ", &key, "tls_client");
4060        blank.subject.common_name = "  ".to_string();
4061        assert!(
4062            manager
4063                .sign_certificate_request(&blank, "root_ca")
4064                .await
4065                .is_err()
4066        );
4067        let mut bad_san = request("x", &key, "tls_client");
4068        bad_san.subject_alt_names = vec![SubjectAltName::DnsName("münchen.example".to_string())];
4069        assert!(
4070            manager
4071                .sign_certificate_request(&bad_san, "root_ca")
4072                .await
4073                .is_err()
4074        );
4075        let mut bad_ip = request("x", &key, "tls_client");
4076        bad_ip.subject_alt_names = vec![SubjectAltName::IpAddress("999.1.1.1".to_string())];
4077        assert!(
4078            manager
4079                .sign_certificate_request(&bad_ip, "root_ca")
4080                .await
4081                .is_err()
4082        );
4083        assert!(manager.list_certificates(None).await.unwrap().is_empty());
4084    }
4085
4086    #[tokio::test]
4087    async fn certificates_that_only_look_like_ours_do_not_validate() {
4088        let dir = tempfile::tempdir().unwrap();
4089        let root = TestCa::root("Trusted Root");
4090        let manager = manager_with(dir.path(), &root, true).await;
4091        let root_der = der_of(&root.cert_pem);
4092        let (_, root_cert) = parse_x509_certificate(&root_der).unwrap();
4093
4094        // Genuine.
4095        assert!(
4096            manager
4097                .validate_certificate_chain(
4098                    &root.leaf("ok", |_| {}),
4099                    CertificatePurpose::ClientAuth
4100                )
4101                .await
4102                .unwrap()
4103        );
4104        // The configured root, as itself.
4105        assert!(
4106            manager
4107                .validate_certificate_chain(&root.cert_pem, CertificatePurpose::ClientAuth)
4108                .await
4109                .unwrap()
4110        );
4111
4112        // Self-signed with the root's exact subject, but the attacker's key.
4113        let mut forged_params = ca_params("Trusted Root");
4114        forged_params.distinguished_name = DistinguishedName::new();
4115        forged_params
4116            .distinguished_name
4117            .push(DnType::CommonName, "Trusted Root");
4118        forged_params
4119            .distinguished_name
4120            .push(DnType::OrganizationName, "Test Org");
4121        let forged = TestCa::root_with(forged_params);
4122        let forged_der = der_of(&forged.cert_pem);
4123        let (_, forged_cert) = parse_x509_certificate(&forged_der).unwrap();
4124        assert_eq!(
4125            forged_cert.subject().to_string(),
4126            root_cert.subject().to_string()
4127        );
4128        assert!(
4129            !manager
4130                .validate_certificate_chain(&forged.cert_pem, CertificatePurpose::ClientAuth)
4131                .await
4132                .unwrap()
4133        );
4134
4135        // A leaf issued by that forged CA, claiming the root's issuer name.
4136        assert!(
4137            !manager
4138                .validate_certificate_chain(
4139                    &forged.leaf("evil", |_| {}),
4140                    CertificatePurpose::ClientAuth
4141                )
4142                .await
4143                .unwrap()
4144        );
4145
4146        // An unrelated CA's certificate.
4147        let other = TestCa::root("Other CA");
4148        assert!(
4149            !manager
4150                .validate_certificate_chain(
4151                    &other.leaf("victim", |_| {}),
4152                    CertificatePurpose::ClientAuth
4153                )
4154                .await
4155                .unwrap()
4156        );
4157
4158        // Genuinely issued but expired.
4159        let expired = root.leaf("old", |p| {
4160            p.not_before = rcgen::date_time_ymd(2000, 1, 1);
4161            p.not_after = rcgen::date_time_ymd(2001, 1, 1);
4162        });
4163        assert!(
4164            !manager
4165                .validate_certificate_chain(&expired, CertificatePurpose::ClientAuth)
4166                .await
4167                .unwrap()
4168        );
4169
4170        // Not a certificate at all.
4171        assert!(
4172            manager
4173                .validate_certificate_chain("garbage", CertificatePurpose::ClientAuth)
4174                .await
4175                .is_err()
4176        );
4177    }
4178
4179    #[tokio::test]
4180    async fn a_chain_through_an_intermediate_validates_when_the_intermediate_is_known() {
4181        let dir = tempfile::tempdir().unwrap();
4182        let root = TestCa::root("Root");
4183        let intermediate = root.intermediate("Issuing CA");
4184        let manager = manager_with(dir.path(), &root, true).await; // root only
4185        let leaf = intermediate.leaf("deep", |p| {
4186            p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth];
4187        });
4188
4189        // The intermediate is unknown here: the path cannot be built.
4190        assert!(
4191            !manager
4192                .validate_certificate_chain(&leaf, CertificatePurpose::ServerAuth)
4193                .await
4194                .unwrap()
4195        );
4196        // Presented with the leaf, it is used as a candidate intermediate.
4197        let bundle = format!("{leaf}{}", intermediate.cert_pem);
4198        assert!(
4199            manager
4200                .validate_certificate_chain(&bundle, CertificatePurpose::ServerAuth)
4201                .await
4202                .unwrap()
4203        );
4204        // The same bundle under a different root does not validate.
4205        let other_dir = tempfile::tempdir().unwrap();
4206        let other = manager_with(other_dir.path(), &TestCa::root("Elsewhere"), true).await;
4207        assert!(
4208            !other
4209                .validate_certificate_chain(&bundle, CertificatePurpose::ServerAuth)
4210                .await
4211                .unwrap()
4212        );
4213    }
4214
4215    #[tokio::test]
4216    async fn serial_numbers_and_revocations_are_scoped_to_the_issuer() {
4217        let dir = tempfile::tempdir().unwrap();
4218        let root = TestCa::root("Root");
4219        let intermediate = root.intermediate("Issuing CA");
4220        let (root_cert, root_key) = root.write(dir.path(), "root");
4221        let (inter_cert, inter_key) = intermediate.write(dir.path(), "inter");
4222        let mut config = config_for(&root_cert, &root_key);
4223        config.intermediate_ca_cert_path = Some(inter_cert.to_string_lossy().to_string());
4224        config.intermediate_ca_key_path = Some(inter_key.to_string_lossy().to_string());
4225        let manager = X509CertificateManager::new(config);
4226        manager.initialize().await.unwrap();
4227
4228        let from_root = manager
4229            .sign_certificate_request(&request("a", &new_key(), "tls_client"), "root_ca")
4230            .await
4231            .unwrap();
4232        let from_inter = manager
4233            .sign_certificate_request(&request("b", &new_key(), "tls_client"), "intermediate_ca")
4234            .await
4235            .unwrap();
4236        assert_ne!(from_root.serial_number, from_inter.serial_number);
4237        // Force the situation that scoping exists for: another issuer holding the same serial.
4238        {
4239            let mut twin = from_inter.clone();
4240            twin.cert_id = "twin".to_string();
4241            twin.serial_number = from_root.serial_number.clone();
4242            manager
4243                .certificate_store
4244                .write()
4245                .await
4246                .insert("twin".to_string(), twin);
4247        }
4248        assert!(from_inter.issuer.contains("Issuing CA"));
4249        assert!(
4250            manager
4251                .validate_certificate_chain(
4252                    &from_inter.certificate_pem,
4253                    CertificatePurpose::ClientAuth
4254                )
4255                .await
4256                .unwrap()
4257        );
4258
4259        // The bare serial is ambiguous: refused, nothing revoked.
4260        let serial = from_root.serial_number.clone();
4261        assert!(
4262            manager
4263                .revoke_certificate(&serial, RevocationReason::KeyCompromise, None)
4264                .await
4265                .is_err()
4266        );
4267        assert!(manager.check_certificate_status(&serial).await.is_err());
4268        assert!(
4269            manager
4270                .validate_certificate_chain(
4271                    &from_root.certificate_pem,
4272                    CertificatePurpose::ClientAuth
4273                )
4274                .await
4275                .unwrap()
4276        );
4277
4278        // Naming the issuer revokes only that issuer's certificate.
4279        manager
4280            .revoke_certificate_issued_by("root_ca", &serial, RevocationReason::KeyCompromise, None)
4281            .await
4282            .unwrap();
4283        assert_eq!(
4284            manager
4285                .check_certificate_status_issued_by("root_ca", &serial)
4286                .await
4287                .unwrap(),
4288            CertificateStatus::Revoked
4289        );
4290        assert_eq!(
4291            manager
4292                .check_certificate_status_issued_by("intermediate_ca", &serial)
4293                .await
4294                .unwrap(),
4295            CertificateStatus::Valid
4296        );
4297        assert!(
4298            !manager
4299                .validate_certificate_chain(
4300                    &from_root.certificate_pem,
4301                    CertificatePurpose::ClientAuth
4302                )
4303                .await
4304                .unwrap()
4305        );
4306        assert!(
4307            manager
4308                .validate_certificate_chain(
4309                    &from_inter.certificate_pem,
4310                    CertificatePurpose::ClientAuth
4311                )
4312                .await
4313                .unwrap()
4314        );
4315
4316        // An unknown serial cannot be pre-revoked.
4317        assert!(
4318            manager
4319                .revoke_certificate_issued_by(
4320                    "root_ca",
4321                    "424242",
4322                    RevocationReason::Unspecified,
4323                    None
4324                )
4325                .await
4326                .is_err()
4327        );
4328
4329        // A serial held by one certificate only resolves without naming the issuer.
4330        let third = manager
4331            .sign_certificate_request(&request("c", &new_key(), "tls_client"), "root_ca")
4332            .await
4333            .unwrap();
4334        manager
4335            .revoke_certificate(
4336                &third.serial_number,
4337                RevocationReason::Superseded,
4338                Some("test".into()),
4339            )
4340            .await
4341            .unwrap();
4342        assert_eq!(
4343            manager
4344                .check_certificate_status(&third.serial_number)
4345                .await
4346                .unwrap(),
4347            CertificateStatus::Revoked
4348        );
4349    }
4350
4351    #[tokio::test]
4352    async fn a_revoked_intermediate_invalidates_what_it_issued() {
4353        let dir = tempfile::tempdir().unwrap();
4354        let root = TestCa::root("Root");
4355        let intermediate = root.intermediate("Issuing CA");
4356        let (root_cert, root_key) = root.write(dir.path(), "root");
4357        let (inter_cert, inter_key) = intermediate.write(dir.path(), "inter");
4358        let mut config = config_for(&root_cert, &root_key);
4359        config.intermediate_ca_cert_path = Some(inter_cert.to_string_lossy().to_string());
4360        config.intermediate_ca_key_path = Some(inter_key.to_string_lossy().to_string());
4361        let manager = X509CertificateManager::new(config);
4362        manager.initialize().await.unwrap();
4363        let issued = manager
4364            .sign_certificate_request(&request("a", &new_key(), "tls_client"), "intermediate_ca")
4365            .await
4366            .unwrap();
4367        assert!(
4368            manager
4369                .validate_certificate_chain(&issued.certificate_pem, CertificatePurpose::ClientAuth)
4370                .await
4371                .unwrap()
4372        );
4373
4374        // The root's CA revokes the intermediate through the public API.
4375        manager
4376            .revoke_ca_certificate("intermediate_ca", RevocationReason::CaCompromise, None)
4377            .await
4378            .unwrap();
4379        assert!(
4380            manager
4381                .sign_certificate_request(
4382                    &request("b", &new_key(), "tls_client"),
4383                    "intermediate_ca"
4384                )
4385                .await
4386                .is_err(),
4387            "a revoked CA cannot issue"
4388        );
4389        assert!(
4390            !manager
4391                .validate_certificate_chain(&issued.certificate_pem, CertificatePurpose::ClientAuth)
4392                .await
4393                .unwrap()
4394        );
4395    }
4396
4397    #[tokio::test]
4398    async fn the_crl_is_a_signed_der_crl_for_this_cas_revocations() {
4399        let dir = tempfile::tempdir().unwrap();
4400        let root = TestCa::root("CRL Root");
4401        let manager = manager_with(dir.path(), &root, true).await;
4402        let mut serials = Vec::new();
4403        for name in ["a", "b", "c"] {
4404            let stored = manager
4405                .sign_certificate_request(&request(name, &new_key(), "tls_client"), "root_ca")
4406                .await
4407                .unwrap();
4408            serials.push(stored.serial_number);
4409        }
4410        manager
4411            .revoke_certificate_issued_by(
4412                "root_ca",
4413                &serials[0],
4414                RevocationReason::KeyCompromise,
4415                None,
4416            )
4417            .await
4418            .unwrap();
4419        manager
4420            .revoke_certificate_issued_by(
4421                "root_ca",
4422                &serials[2],
4423                RevocationReason::Superseded,
4424                None,
4425            )
4426            .await
4427            .unwrap();
4428        // A revocation recorded for another CA is not on this CA's list.
4429        manager.revocation_list.write().await.insert(
4430            X509CertificateManager::revocation_key("someone_else", "1"),
4431            RevocationEntry {
4432                serial_number: "1".to_string(),
4433                revocation_date: Utc::now(),
4434                reason: RevocationReason::Unspecified,
4435                additional_info: None,
4436            },
4437        );
4438
4439        let crl_pem = manager.generate_crl("root_ca").await.unwrap();
4440        let (_, pem) = x509_parser::pem::parse_x509_pem(crl_pem.as_bytes()).unwrap();
4441        assert_eq!(pem.label, "X509 CRL");
4442        let (rest, crl) =
4443            x509_parser::revocation_list::CertificateRevocationList::from_der(&pem.contents)
4444                .unwrap();
4445        assert!(rest.is_empty());
4446        assert_eq!(
4447            crl.issuer().to_string(),
4448            ca_subject(&manager, "root_ca").await
4449        );
4450        let mut listed: Vec<String> = crl
4451            .iter_revoked_certificates()
4452            .map(|r| r.user_certificate.to_string())
4453            .collect();
4454        listed.sort();
4455        let mut expected = vec![serials[0].clone(), serials[2].clone()];
4456        expected.sort();
4457        assert_eq!(listed, expected);
4458        assert!(crl.next_update().is_some());
4459
4460        // The signature verifies under the CA's key, and not under another.
4461        let ca_der = der_of(&root.cert_pem);
4462        let (_, ca_cert) = parse_x509_certificate(&ca_der).unwrap();
4463        crl.verify_signature(ca_cert.public_key())
4464            .expect("signed by the CA");
4465        let other = TestCa::root("Other");
4466        let other_der = der_of(&other.cert_pem);
4467        let (_, other_cert) = parse_x509_certificate(&other_der).unwrap();
4468        assert!(crl.verify_signature(other_cert.public_key()).is_err());
4469    }
4470
4471    #[tokio::test]
4472    async fn an_imported_ca_certificate_is_parsed_or_refused() {
4473        let manager = X509CertificateManager::new(X509Config::default());
4474        assert!(
4475            manager
4476                .store_ca_certificate_from_pem(
4477                    "-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n",
4478                    "test"
4479                )
4480                .await
4481                .is_err()
4482        );
4483        assert!(manager.ca_certificates.read().await.is_empty());
4484
4485        let root = TestCa::root("Imported Root");
4486        manager
4487            .store_ca_certificate_from_pem(&root.cert_pem, "test")
4488            .await
4489            .unwrap();
4490        let cas = manager.ca_certificates.read().await;
4491        assert!(cas["root_ca"].subject.contains("Imported Root"));
4492        assert!(
4493            cas["root_ca"].private_key.is_empty(),
4494            "key stays with the source"
4495        );
4496        drop(cas);
4497        // It validates what it issued but cannot issue.
4498        assert!(
4499            manager
4500                .validate_certificate_chain(&root.leaf("x", |_| {}), CertificatePurpose::ClientAuth)
4501                .await
4502                .unwrap()
4503        );
4504        assert!(
4505            manager
4506                .sign_certificate_request(&request("svc", &new_key(), "tls_client"), "root_ca")
4507                .await
4508                .is_err()
4509        );
4510    }
4511
4512    // ─── Review round: policy, persistence, serials, CA revocation, purposes ───
4513
4514    fn open_profile(name: &str) -> CertificateProfile {
4515        CertificateProfile {
4516            name: name.to_string(),
4517            cert_type: CertificateType::TlsClient,
4518            key_usage: vec![KeyUsage::DigitalSignature],
4519            extended_key_usage: vec![ExtendedKeyUsage::ClientAuth],
4520            subject_alt_names: vec![],
4521            san_policy: SanPolicy {
4522                wildcard_dns: true,
4523                ip_address: true,
4524                uri: true,
4525                email: true,
4526            },
4527            validity_days: 30,
4528            preferred_key_type: KeyType::Ecdsa(EcdsaCurve::P256),
4529            extensions: HashMap::new(),
4530        }
4531    }
4532
4533    /// A manager with the default profiles plus `extra`, over a fresh root.
4534    async fn manager_with_profiles(
4535        dir: &Path,
4536        extra: Vec<(&str, CertificateProfile)>,
4537    ) -> (X509CertificateManager, TestCa) {
4538        let root = TestCa::root("Policy Root");
4539        let (cert, key) = root.write(dir, "root");
4540        let mut config = config_for(&cert, &key);
4541        for (name, profile) in extra {
4542            config
4543                .certificate_profiles
4544                .insert(name.to_string(), profile);
4545        }
4546        let manager = X509CertificateManager::new(config);
4547        manager.initialize().await.unwrap();
4548        (manager, root)
4549    }
4550
4551    async fn assert_refused(
4552        manager: &X509CertificateManager,
4553        request: &CertificateRequest,
4554        why: &str,
4555    ) {
4556        let before = manager.list_certificates(None).await.unwrap().len();
4557        assert!(
4558            manager
4559                .sign_certificate_request(request, "root_ca")
4560                .await
4561                .is_err(),
4562            "{why}"
4563        );
4564        assert_eq!(
4565            manager.list_certificates(None).await.unwrap().len(),
4566            before,
4567            "{why}: nothing may be stored"
4568        );
4569    }
4570
4571    #[tokio::test]
4572    async fn hostile_names_and_unsupported_inputs_are_refused() {
4573        let dir = tempfile::tempdir().unwrap();
4574        let mut with_extensions = open_profile("ext");
4575        with_extensions
4576            .extensions
4577            .insert("anything".to_string(), Value::Bool(true));
4578        let (manager, _) = manager_with_profiles(
4579            dir.path(),
4580            vec![("open", open_profile("open")), ("ext", with_extensions)],
4581        )
4582        .await;
4583        let key = new_key();
4584        let base = |profile: &str| request("host", &key, profile);
4585
4586        // Subject text.
4587        for (why, cn) in [
4588            ("newline in CN", "evil\nCN=admin".to_string()),
4589            ("NUL in CN", "evil\0".to_string()),
4590            ("tab in CN", "a\tb".to_string()),
4591            ("65-character CN", "a".repeat(65)),
4592            ("45,000-character CN", "a".repeat(45_000)),
4593        ] {
4594            let mut r = base("tls_client");
4595            r.subject.common_name = cn;
4596            assert_refused(&manager, &r, why).await;
4597        }
4598        for country in ["ZZZZZZ", "us", "U", ""] {
4599            let mut r = base("tls_client");
4600            r.subject.country = Some(country.to_string());
4601            assert_refused(&manager, &r, &format!("country {country:?}")).await;
4602        }
4603        let mut r = base("tls_client");
4604        r.subject.organization = Some("o\r\nx".to_string());
4605        assert_refused(&manager, &r, "control character in organization").await;
4606
4607        // Names the profile does not allow.
4608        for (why, san) in [
4609            (
4610                "wildcard",
4611                SubjectAltName::DnsName("*.example.com".to_string()),
4612            ),
4613            (
4614                "localhost",
4615                SubjectAltName::DnsName("localhost".to_string()),
4616            ),
4617            (
4618                "sub.localhost",
4619                SubjectAltName::DnsName("a.localhost".to_string()),
4620            ),
4621            (
4622                "bare label",
4623                SubjectAltName::DnsName("intranet".to_string()),
4624            ),
4625            (
4626                "numeric TLD",
4627                SubjectAltName::DnsName("1.2.3.4".to_string()),
4628            ),
4629            ("empty name", SubjectAltName::DnsName(String::new())),
4630            (
4631                "underscore",
4632                SubjectAltName::DnsName("a_b.example".to_string()),
4633            ),
4634            (
4635                "45,000-char name",
4636                SubjectAltName::DnsName(format!("{}.example", "a".repeat(45_000))),
4637            ),
4638            (
4639                "long label",
4640                SubjectAltName::DnsName(format!("{}.example", "a".repeat(64))),
4641            ),
4642            (
4643                "IP without policy",
4644                SubjectAltName::IpAddress("192.0.2.1".to_string()),
4645            ),
4646            (
4647                "URI without policy",
4648                SubjectAltName::Uri("https://svc.example/id".to_string()),
4649            ),
4650            (
4651                "e-mail without policy",
4652                SubjectAltName::Email("a@example.com".to_string()),
4653            ),
4654        ] {
4655            let mut r = base("tls_client");
4656            r.subject_alt_names = vec![san];
4657            assert_refused(&manager, &r, why).await;
4658        }
4659        // Names that are refused even where the profile allows the kind.
4660        for (why, san) in [
4661            (
4662                "loopback IP",
4663                SubjectAltName::IpAddress("127.0.0.1".to_string()),
4664            ),
4665            (
4666                "unspecified IP",
4667                SubjectAltName::IpAddress("0.0.0.0".to_string()),
4668            ),
4669            (
4670                "multicast IP",
4671                SubjectAltName::IpAddress("224.0.0.1".to_string()),
4672            ),
4673            (
4674                "garbage IP",
4675                SubjectAltName::IpAddress("999.1.1.1".to_string()),
4676            ),
4677            (
4678                "URI with space",
4679                SubjectAltName::Uri("https://a b".to_string()),
4680            ),
4681            (
4682                "URI without scheme",
4683                SubjectAltName::Uri("no-scheme".to_string()),
4684            ),
4685            (
4686                "e-mail without @",
4687                SubjectAltName::Email("nobody".to_string()),
4688            ),
4689            (
4690                "e-mail with two @",
4691                SubjectAltName::Email("a@b@example.com".to_string()),
4692            ),
4693            (
4694                "e-mail to localhost",
4695                SubjectAltName::Email("a@localhost".to_string()),
4696            ),
4697            (
4698                "non-ASCII DNS",
4699                SubjectAltName::DnsName("münchen.example".to_string()),
4700            ),
4701        ] {
4702            let mut r = base("open");
4703            r.subject_alt_names = vec![san];
4704            assert_refused(&manager, &r, why).await;
4705        }
4706        let mut r = base("open");
4707        r.subject_alt_names = (0..26)
4708            .map(|i| SubjectAltName::DnsName(format!("h{i}.example.com")))
4709            .collect();
4710        assert_refused(&manager, &r, "26 names").await;
4711
4712        // Inputs that would be accepted and ignored.
4713        let mut r = base("tls_client");
4714        r.attributes
4715            .insert("anything".to_string(), Value::Bool(true));
4716        assert_refused(&manager, &r, "request attributes").await;
4717        assert_refused(&manager, &base("ext"), "profile extensions").await;
4718
4719        // Subject keys: weak, wrong strength class, not a public key.
4720        let mut r = base("tls_client");
4721        r.public_key_pem = rsa_spki_pem(1024);
4722        assert_refused(&manager, &r, "RSA-1024").await;
4723        r.public_key_pem = rsa_spki_pem(512);
4724        assert_refused(&manager, &r, "RSA-512").await;
4725        let mut r = base("tls_client");
4726        r.public_key_pem =
4727            "-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n".to_string();
4728        assert_refused(&manager, &r, "not a public key").await;
4729
4730        // Accepted where allowed, with the names carried into the certificate.
4731        let mut ok = base("open");
4732        ok.subject_alt_names = vec![
4733            SubjectAltName::DnsName("*.example.com".to_string()),
4734            SubjectAltName::IpAddress("192.0.2.10".to_string()),
4735            SubjectAltName::Uri("https://svc.example/id".to_string()),
4736            SubjectAltName::Email("ops@example.com".to_string()),
4737        ];
4738        ok.subject.email = Some("owner@example.com".to_string());
4739        ok.subject.country = Some("US".to_string());
4740        let stored = manager
4741            .sign_certificate_request(&ok, "root_ca")
4742            .await
4743            .unwrap();
4744        let der = der_of(&stored.certificate_pem);
4745        let (_, cert) = parse_x509_certificate(&der).unwrap();
4746        let san = cert.subject_alternative_name().unwrap().unwrap();
4747        assert_eq!(
4748            san.value.general_names.len(),
4749            5,
4750            "{:?}",
4751            san.value.general_names
4752        );
4753    }
4754
4755    /// A SubjectPublicKeyInfo PEM for an RSA key of `bits` bits (the modulus is not a real
4756    /// product of primes: only its size is looked at).
4757    fn rsa_spki_pem(bits: usize) -> String {
4758        fn der(tag: u8, content: &[u8]) -> Vec<u8> {
4759            let mut out = vec![tag];
4760            match content.len() {
4761                n if n < 128 => out.push(n as u8),
4762                n if n < 256 => out.extend([0x81, n as u8]),
4763                n => out.extend([0x82, (n >> 8) as u8, n as u8]),
4764            }
4765            out.extend(content);
4766            out
4767        }
4768        let mut modulus = vec![0u8];
4769        modulus.extend(vec![0xC5u8; bits / 8]);
4770        let rsa_key = der(
4771            0x30,
4772            &[der(0x02, &modulus), der(0x02, &[0x01, 0x00, 0x01])].concat(),
4773        );
4774        let mut bit_string = vec![0u8];
4775        bit_string.extend(rsa_key);
4776        let algorithm = der(
4777            0x30,
4778            &[
4779                der(
4780                    0x06,
4781                    &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01],
4782                ),
4783                vec![0x05, 0x00],
4784            ]
4785            .concat(),
4786        );
4787        let spki = der(0x30, &[algorithm, der(0x03, &bit_string)].concat());
4788        format!(
4789            "-----BEGIN PUBLIC KEY-----\n{}\n-----END PUBLIC KEY-----\n",
4790            BASE64_STANDARD.encode(spki)
4791        )
4792    }
4793
4794    #[tokio::test]
4795    async fn the_profile_decides_the_minimum_key_strength() {
4796        let dir = tempfile::tempdir().unwrap();
4797        let mut strong = open_profile("strong");
4798        strong.preferred_key_type = KeyType::Ecdsa(EcdsaCurve::P384);
4799        let (manager, _) = manager_with_profiles(dir.path(), vec![("strong", strong)]).await;
4800        // P-256 is weaker than the profile's P-384 minimum; P-384 is enough.
4801        assert_refused(
4802            &manager,
4803            &request("a", &new_key(), "strong"),
4804            "P-256 under a P-384 minimum",
4805        )
4806        .await;
4807        let p384 = KeyPair::generate_for(&rcgen::PKCS_ECDSA_P384_SHA384).unwrap();
4808        manager
4809            .sign_certificate_request(&request("a", &p384, "strong"), "root_ca")
4810            .await
4811            .unwrap();
4812        // Ed25519 meets the default profiles' RSA-2048 minimum.
4813        let ed = KeyPair::generate_for(&rcgen::PKCS_ED25519).unwrap();
4814        manager
4815            .sign_certificate_request(&request("b", &ed, "tls_client"), "root_ca")
4816            .await
4817            .unwrap();
4818    }
4819
4820    #[tokio::test]
4821    async fn profile_settings_are_honoured_or_refused_never_ignored() {
4822        let dir = tempfile::tempdir().unwrap();
4823        let mut fixed = open_profile("fixed");
4824        fixed.subject_alt_names = vec![SubjectAltName::DnsName("fixed.example.com".to_string())];
4825        let mut default_days = open_profile("default-days");
4826        default_days.validity_days = 0;
4827        let mut huge = open_profile("huge");
4828        huge.validity_days = i64::MAX;
4829        let root = TestCa::root("Profiles");
4830        let (cert, key) = root.write(dir.path(), "root");
4831        let mut config = config_for(&cert, &key);
4832        config.default_validity_days = 7;
4833        for (name, p) in [
4834            ("fixed", fixed),
4835            ("default-days", default_days),
4836            ("huge", huge),
4837        ] {
4838            config.certificate_profiles.insert(name.to_string(), p);
4839        }
4840        let manager = X509CertificateManager::new(config);
4841        manager.initialize().await.unwrap();
4842        let key = new_key();
4843
4844        // The profile's own names are in the certificate.
4845        let stored = manager
4846            .sign_certificate_request(&request("one", &key, "fixed"), "root_ca")
4847            .await
4848            .unwrap();
4849        let der = der_of(&stored.certificate_pem);
4850        let (_, parsed) = parse_x509_certificate(&der).unwrap();
4851        let names = format!(
4852            "{:?}",
4853            parsed
4854                .subject_alternative_name()
4855                .unwrap()
4856                .unwrap()
4857                .value
4858                .general_names
4859        );
4860        assert!(
4861            names.contains("fixed.example.com") && names.contains("one.example"),
4862            "{names}"
4863        );
4864
4865        // default_validity_days applies when the profile has none.
4866        let stored = manager
4867            .sign_certificate_request(&request("two", &key, "default-days"), "root_ca")
4868            .await
4869            .unwrap();
4870        let days = (stored.not_after - Utc::now()).num_days();
4871        assert!((6..=7).contains(&days), "{days}");
4872        // Not-before is backdated for clock skew.
4873        assert!(stored.not_before <= Utc::now() - Duration::minutes(4));
4874
4875        // Nonsense validity is an error, not a panic.
4876        assert_refused(&manager, &request("three", &key, "huge"), "i64::MAX days").await;
4877    }
4878
4879    #[tokio::test]
4880    async fn unsupported_settings_stop_initialize() {
4881        let dir = tempfile::tempdir().unwrap();
4882        let root = TestCa::root("Settings");
4883        let (cert, key) = root.write(dir.path(), "root");
4884
4885        let mut config = config_for(&cert, &key);
4886        config.enable_ocsp = true;
4887        assert!(
4888            X509CertificateManager::new(config)
4889                .initialize()
4890                .await
4891                .is_err()
4892        );
4893        let mut config = config_for(&cert, &key);
4894        config.ocsp_responder_url = Some("https://ocsp.example.com".to_string());
4895        assert!(
4896            X509CertificateManager::new(config)
4897                .initialize()
4898                .await
4899                .is_err()
4900        );
4901        for bad in [
4902            "ldap://x",
4903            "https://a b",
4904            "https://x\ny",
4905            "javascript:alert(1)",
4906        ] {
4907            let mut config = config_for(&cert, &key);
4908            config.crl_distribution_url = Some(bad.to_string());
4909            assert!(
4910                X509CertificateManager::new(config)
4911                    .initialize()
4912                    .await
4913                    .is_err(),
4914                "{bad}"
4915            );
4916        }
4917    }
4918
4919    #[tokio::test]
4920    async fn the_crl_distribution_point_and_ca_false_reach_issued_certificates() {
4921        let dir = tempfile::tempdir().unwrap();
4922        let root = TestCa::root("DP Root");
4923        let (cert, key) = root.write(dir.path(), "root");
4924        let mut config = config_for(&cert, &key);
4925        config.crl_distribution_url = Some("https://crl.example.com/root.crl".to_string());
4926        let manager = X509CertificateManager::new(config);
4927        manager.initialize().await.unwrap();
4928        let stored = manager
4929            .sign_certificate_request(&request("svc", &new_key(), "tls_client"), "root_ca")
4930            .await
4931            .unwrap();
4932        let der = der_of(&stored.certificate_pem);
4933        let (_, parsed) = parse_x509_certificate(&der).unwrap();
4934        let has = |oid: &x509_parser::der_parser::oid::Oid| {
4935            parsed.extensions().iter().any(|e| &e.oid == oid)
4936        };
4937        assert!(has(
4938            &x509_parser::oid_registry::OID_X509_EXT_CRL_DISTRIBUTION_POINTS
4939        ));
4940        assert!(has(
4941            &x509_parser::oid_registry::OID_X509_EXT_SUBJECT_KEY_IDENTIFIER
4942        ));
4943        assert!(has(
4944            &x509_parser::oid_registry::OID_X509_EXT_AUTHORITY_KEY_IDENTIFIER
4945        ));
4946        let basic = parsed
4947            .basic_constraints()
4948            .unwrap()
4949            .expect("basicConstraints present");
4950        assert!(!basic.value.ca);
4951
4952        // With CRLs disabled there is no CRL.
4953        let mut config = config_for(&cert, &key);
4954        config.enable_crl = false;
4955        let manager = X509CertificateManager::new(config);
4956        manager.initialize().await.unwrap();
4957        assert!(manager.generate_crl("root_ca").await.is_err());
4958    }
4959
4960    #[tokio::test]
4961    async fn serial_numbers_are_random_wide_and_never_repeat() {
4962        let dir = tempfile::tempdir().unwrap();
4963        let (manager, _) = manager_with_profiles(dir.path(), vec![]).await;
4964        let mut tasks = Vec::new();
4965        for i in 0..40 {
4966            let manager = manager.clone();
4967            tasks.push(tokio::spawn(async move {
4968                manager
4969                    .sign_certificate_request(
4970                        &request(&format!("c{i}"), &new_key(), "tls_client"),
4971                        "root_ca",
4972                    )
4973                    .await
4974                    .unwrap()
4975                    .serial_number
4976            }));
4977        }
4978        let mut serials = Vec::new();
4979        for task in tasks {
4980            serials.push(task.await.unwrap());
4981        }
4982        // A second initialize (as after a restart in one process) must not reuse numbers.
4983        manager.initialize().await.unwrap();
4984        for i in 0..10 {
4985            serials.push(
4986                manager
4987                    .sign_certificate_request(
4988                        &request(&format!("d{i}"), &new_key(), "tls_client"),
4989                        "root_ca",
4990                    )
4991                    .await
4992                    .unwrap()
4993                    .serial_number,
4994            );
4995        }
4996        let unique: std::collections::HashSet<_> = serials.iter().collect();
4997        assert_eq!(unique.len(), serials.len(), "duplicate serial numbers");
4998        let floor = x509_parser::num_bigint::BigUint::from(1u8) << 120usize;
4999        for serial in &serials {
5000            let n = x509_parser::num_bigint::BigUint::parse_bytes(serial.as_bytes(), 10).unwrap();
5001            assert!(n > floor, "serial {serial} is not 120+ bits wide");
5002        }
5003    }
5004
5005    #[tokio::test]
5006    async fn revocations_survive_a_restart_when_a_state_file_is_set() {
5007        let dir = tempfile::tempdir().unwrap();
5008        let root = TestCa::root("State Root");
5009        let (cert, key) = root.write(dir.path(), "root");
5010        let state = dir.path().join("state").join("x509.json");
5011        let config = {
5012            let mut c = config_for(&cert, &key);
5013            c.state_path = Some(state.to_string_lossy().to_string());
5014            c
5015        };
5016        let first = X509CertificateManager::new(config.clone());
5017        first.initialize().await.unwrap();
5018        let issued = first
5019            .sign_certificate_request(&request("svc", &new_key(), "tls_client"), "root_ca")
5020            .await
5021            .unwrap();
5022        let other = first
5023            .sign_certificate_request(&request("keep", &new_key(), "tls_client"), "root_ca")
5024            .await
5025            .unwrap();
5026        first
5027            .revoke_certificate(&issued.serial_number, RevocationReason::KeyCompromise, None)
5028            .await
5029            .unwrap();
5030        let crl_one = first.generate_crl("root_ca").await.unwrap();
5031
5032        // "Restart": a new manager over the same files.
5033        let second = X509CertificateManager::new(config.clone());
5034        second.initialize().await.unwrap();
5035        assert_eq!(
5036            second
5037                .check_certificate_status(&issued.serial_number)
5038                .await
5039                .unwrap(),
5040            CertificateStatus::Revoked,
5041            "a restart must not un-revoke"
5042        );
5043        assert!(
5044            !second
5045                .validate_certificate_chain(&issued.certificate_pem, CertificatePurpose::ClientAuth)
5046                .await
5047                .unwrap()
5048        );
5049        assert!(
5050            second
5051                .validate_certificate_chain(&other.certificate_pem, CertificatePurpose::ClientAuth)
5052                .await
5053                .unwrap()
5054        );
5055        // An old certificate can still be revoked after the restart.
5056        second
5057            .revoke_certificate(&other.serial_number, RevocationReason::Superseded, None)
5058            .await
5059            .unwrap();
5060        // CRL numbers keep increasing.
5061        let number = |pem: &str| {
5062            use x509_parser::prelude::FromDer;
5063            let (_, p) = x509_parser::pem::parse_x509_pem(pem.as_bytes()).unwrap();
5064            let (_, crl) =
5065                x509_parser::revocation_list::CertificateRevocationList::from_der(&p.contents)
5066                    .unwrap();
5067            crl.crl_number().unwrap().clone()
5068        };
5069        let crl_two = second.generate_crl("root_ca").await.unwrap();
5070        let crl_three = second.generate_crl("root_ca").await.unwrap();
5071        assert!(number(&crl_two) > number(&crl_one));
5072        assert!(number(&crl_three) > number(&crl_two));
5073
5074        // A damaged state file stops initialize instead of starting empty.
5075        std::fs::write(&state, "{ not json").unwrap();
5076        assert!(
5077            X509CertificateManager::new(config)
5078                .initialize()
5079                .await
5080                .is_err()
5081        );
5082    }
5083
5084    #[tokio::test]
5085    async fn a_state_file_that_cannot_be_written_fails_the_operation() {
5086        let dir = tempfile::tempdir().unwrap();
5087        let root = TestCa::root("Unwritable");
5088        let (cert, key) = root.write(dir.path(), "root");
5089        let blocked = dir.path().join("blocked");
5090        std::fs::create_dir(&blocked).unwrap(); // a directory where the file should go
5091        let mut config = config_for(&cert, &key);
5092        config.state_path = Some(blocked.to_string_lossy().to_string());
5093        let manager = X509CertificateManager::new(config);
5094        // initialize sees the directory as "a state file" and refuses to read it.
5095        assert!(manager.initialize().await.is_err());
5096
5097        // A manager whose state path only became unwritable after it started.
5098        let state = dir.path().join("later.json");
5099        let mut config = config_for(&cert, &key);
5100        config.state_path = Some(state.to_string_lossy().to_string());
5101        let manager = X509CertificateManager::new(config);
5102        manager.initialize().await.unwrap();
5103        let issued = manager
5104            .sign_certificate_request(&request("a", &new_key(), "tls_client"), "root_ca")
5105            .await
5106            .unwrap();
5107        std::fs::remove_file(&state).ok();
5108        std::fs::create_dir(&state).unwrap();
5109        // Issuing now fails and records nothing...
5110        let before = manager.list_certificates(None).await.unwrap().len();
5111        assert!(
5112            manager
5113                .sign_certificate_request(&request("b", &new_key(), "tls_client"), "root_ca")
5114                .await
5115                .is_err()
5116        );
5117        assert_eq!(manager.list_certificates(None).await.unwrap().len(), before);
5118        // ...and a revocation that cannot be saved still takes effect, and says so.
5119        assert!(
5120            manager
5121                .revoke_certificate(&issued.serial_number, RevocationReason::KeyCompromise, None)
5122                .await
5123                .is_err()
5124        );
5125        assert!(
5126            !manager
5127                .validate_certificate_chain(&issued.certificate_pem, CertificatePurpose::ClientAuth)
5128                .await
5129                .unwrap()
5130        );
5131    }
5132
5133    #[tokio::test]
5134    async fn without_a_state_file_a_certificate_can_still_be_revoked_from_its_pem() {
5135        let dir = tempfile::tempdir().unwrap();
5136        let root = TestCa::root("Volatile");
5137        let (cert, key) = root.write(dir.path(), "root");
5138        let first = X509CertificateManager::new(config_for(&cert, &key));
5139        first.initialize().await.unwrap();
5140        let issued = first
5141            .sign_certificate_request(&request("old", &new_key(), "tls_client"), "root_ca")
5142            .await
5143            .unwrap();
5144
5145        // Restart without state: the store is empty and the serial is unknown...
5146        let second = X509CertificateManager::new(config_for(&cert, &key));
5147        second.initialize().await.unwrap();
5148        assert!(
5149            second
5150                .revoke_certificate(&issued.serial_number, RevocationReason::KeyCompromise, None)
5151                .await
5152                .is_err()
5153        );
5154        // ...but the certificate itself is enough.
5155        second
5156            .revoke_certificate_pem(
5157                &issued.certificate_pem,
5158                RevocationReason::KeyCompromise,
5159                None,
5160            )
5161            .await
5162            .unwrap();
5163        assert!(
5164            !second
5165                .validate_certificate_chain(&issued.certificate_pem, CertificatePurpose::ClientAuth)
5166                .await
5167                .unwrap()
5168        );
5169        // A certificate that carries OUR issuer name but was signed by someone else is refused.
5170        let mut forged_ca = ca_params("Volatile");
5171        forged_ca.distinguished_name = DistinguishedName::new();
5172        forged_ca
5173            .distinguished_name
5174            .push(DnType::CommonName, "Volatile");
5175        forged_ca
5176            .distinguished_name
5177            .push(DnType::OrganizationName, "Test Org");
5178        let impostor = TestCa::root_with(forged_ca).leaf("victim", |_| {});
5179        assert!(
5180            second
5181                .revoke_certificate_pem(&impostor, RevocationReason::KeyCompromise, None)
5182                .await
5183                .is_err(),
5184            "revoking needs a certificate our CA really signed"
5185        );
5186        // A certificate some other CA signed is refused.
5187        let stranger = TestCa::root("Stranger").leaf("x", |_| {});
5188        assert!(
5189            second
5190                .revoke_certificate_pem(&stranger, RevocationReason::KeyCompromise, None)
5191                .await
5192                .is_err()
5193        );
5194    }
5195
5196    #[tokio::test]
5197    async fn a_revoked_ca_stays_revoked_after_a_restart() {
5198        let dir = tempfile::tempdir().unwrap();
5199        let root = TestCa::root("Root");
5200        let intermediate = root.intermediate("Issuing CA");
5201        let (root_cert, root_key) = root.write(dir.path(), "root");
5202        let (inter_cert, inter_key) = intermediate.write(dir.path(), "inter");
5203        let state = dir.path().join("state.json");
5204        let mut config = config_for(&root_cert, &root_key);
5205        config.intermediate_ca_cert_path = Some(inter_cert.to_string_lossy().to_string());
5206        config.intermediate_ca_key_path = Some(inter_key.to_string_lossy().to_string());
5207        config.state_path = Some(state.to_string_lossy().to_string());
5208        let first = X509CertificateManager::new(config.clone());
5209        first.initialize().await.unwrap();
5210        let issued = first
5211            .sign_certificate_request(&request("a", &new_key(), "tls_client"), "intermediate_ca")
5212            .await
5213            .unwrap();
5214        first
5215            .revoke_ca_certificate("intermediate_ca", RevocationReason::CaCompromise, None)
5216            .await
5217            .unwrap();
5218
5219        let second = X509CertificateManager::new(config);
5220        second.initialize().await.unwrap();
5221        assert_eq!(
5222            second.ca_certificates.read().await["intermediate_ca"]
5223                .certificate
5224                .status,
5225            CertificateStatus::Revoked
5226        );
5227        assert!(
5228            second
5229                .sign_certificate_request(
5230                    &request("b", &new_key(), "tls_client"),
5231                    "intermediate_ca"
5232                )
5233                .await
5234                .is_err()
5235        );
5236        assert!(
5237            !second
5238                .validate_certificate_chain(&issued.certificate_pem, CertificatePurpose::ClientAuth)
5239                .await
5240                .unwrap()
5241        );
5242        // The root is untouched and still issues.
5243        second
5244            .sign_certificate_request(&request("c", &new_key(), "tls_client"), "root_ca")
5245            .await
5246            .unwrap();
5247
5248        // Revoking the root ends the whole tree.
5249        second
5250            .revoke_ca_certificate("root_ca", RevocationReason::CaCompromise, None)
5251            .await
5252            .unwrap();
5253        assert!(
5254            second
5255                .sign_certificate_request(&request("d", &new_key(), "tls_client"), "root_ca")
5256                .await
5257                .is_err()
5258        );
5259        assert!(
5260            !second
5261                .validate_certificate_chain(&root.leaf("e", |_| {}), CertificatePurpose::ClientAuth)
5262                .await
5263                .unwrap()
5264        );
5265        assert!(
5266            !second
5267                .validate_certificate_chain(&root.cert_pem, CertificatePurpose::ClientAuth)
5268                .await
5269                .unwrap()
5270        );
5271        assert!(
5272            second
5273                .revoke_ca_certificate("nobody", RevocationReason::Unspecified, None)
5274                .await
5275                .is_err()
5276        );
5277    }
5278
5279    #[tokio::test]
5280    async fn the_purpose_is_the_callers_not_the_certificates() {
5281        let dir = tempfile::tempdir().unwrap();
5282        let root = TestCa::root("Purposes");
5283        let manager = manager_with(dir.path(), &root, true).await;
5284        let server_only = root.leaf("srv", |p| {
5285            p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth];
5286        });
5287        let signing_only = root.leaf("sign", |p| {
5288            p.extended_key_usages = vec![ExtendedKeyUsagePurpose::CodeSigning];
5289        });
5290        let unrestricted = root.leaf("any", |_| {});
5291        let valid = |pem: &str, purpose| {
5292            let manager = manager.clone();
5293            let pem = pem.to_string();
5294            async move {
5295                manager
5296                    .validate_certificate_chain(&pem, purpose)
5297                    .await
5298                    .unwrap()
5299            }
5300        };
5301        use CertificatePurpose::*;
5302        assert!(valid(&server_only, ServerAuth).await);
5303        assert!(!valid(&server_only, ClientAuth).await);
5304        assert!(!valid(&server_only, CodeSigning).await);
5305        assert!(valid(&signing_only, CodeSigning).await);
5306        assert!(!valid(&signing_only, ServerAuth).await);
5307        assert!(!valid(&signing_only, ClientAuth).await);
5308        // No extended key usage at all: valid for any purpose.
5309        for purpose in [
5310            ServerAuth,
5311            ClientAuth,
5312            CodeSigning,
5313            EmailProtection,
5314            TimeStamping,
5315            OcspSigning,
5316        ] {
5317            assert!(valid(&unrestricted, purpose).await, "{purpose:?}");
5318        }
5319    }
5320
5321    #[tokio::test]
5322    async fn crl_numbers_increase_and_reason_codes_are_right() {
5323        use x509_parser::prelude::FromDer;
5324        let dir = tempfile::tempdir().unwrap();
5325        let (manager, _) = manager_with_profiles(dir.path(), vec![]).await;
5326        let mut issued = Vec::new();
5327        for name in ["a", "b"] {
5328            issued.push(
5329                manager
5330                    .sign_certificate_request(&request(name, &new_key(), "tls_client"), "root_ca")
5331                    .await
5332                    .unwrap(),
5333            );
5334        }
5335        // "Remove from CRL" is not a reason to revoke.
5336        assert!(
5337            manager
5338                .revoke_certificate(
5339                    &issued[0].serial_number,
5340                    RevocationReason::RemoveFromCrl,
5341                    None
5342                )
5343                .await
5344                .is_err()
5345        );
5346        manager
5347            .revoke_certificate(
5348                &issued[0].serial_number,
5349                RevocationReason::Unspecified,
5350                None,
5351            )
5352            .await
5353            .unwrap();
5354        manager
5355            .revoke_certificate(
5356                &issued[1].serial_number,
5357                RevocationReason::KeyCompromise,
5358                None,
5359            )
5360            .await
5361            .unwrap();
5362
5363        let parse = |pem: &str| {
5364            let (_, p) = x509_parser::pem::parse_x509_pem(pem.as_bytes()).unwrap();
5365            p.contents
5366        };
5367        let first = parse(&manager.generate_crl("root_ca").await.unwrap());
5368        let second = parse(&manager.generate_crl("root_ca").await.unwrap());
5369        let (_, first) =
5370            x509_parser::revocation_list::CertificateRevocationList::from_der(&first).unwrap();
5371        let (_, second) =
5372            x509_parser::revocation_list::CertificateRevocationList::from_der(&second).unwrap();
5373        assert!(second.crl_number().unwrap() > first.crl_number().unwrap());
5374        assert!(
5375            first.last_update().timestamp() <= Utc::now().timestamp() - 240,
5376            "backdated"
5377        );
5378        for entry in first.iter_revoked_certificates() {
5379            let code = entry.reason_code().map(|(_, c)| c.0);
5380            if entry.user_certificate.to_string() == issued[0].serial_number {
5381                assert_eq!(code, None, "reasonCode 0 is omitted");
5382            } else {
5383                assert_eq!(code, Some(1), "keyCompromise");
5384            }
5385        }
5386    }
5387
5388    // ─── Review round 3 ────────────────────────────────────────────────────────
5389
5390    /// A manager with a root and an intermediate (both with keys) and no state file.
5391    async fn two_level_manager(
5392        dir: &Path,
5393        state: Option<&Path>,
5394    ) -> (X509CertificateManager, TestCa, TestCa, X509Config) {
5395        let root = TestCa::root("Root");
5396        let intermediate = root.intermediate("Issuing CA");
5397        let (root_cert, root_key) = root.write(dir, "root");
5398        let (inter_cert, inter_key) = intermediate.write(dir, "inter");
5399        let mut config = config_for(&root_cert, &root_key);
5400        config.intermediate_ca_cert_path = Some(inter_cert.to_string_lossy().to_string());
5401        config.intermediate_ca_key_path = Some(inter_key.to_string_lossy().to_string());
5402        config.state_path = state.map(|p| p.to_string_lossy().to_string());
5403        let manager = X509CertificateManager::new(config.clone());
5404        manager.initialize().await.unwrap();
5405        (manager, root, intermediate, config)
5406    }
5407
5408    async fn can_issue(manager: &X509CertificateManager, ca_id: &str, name: &str) -> bool {
5409        manager
5410            .sign_certificate_request(&request(name, &new_key(), "tls_client"), ca_id)
5411            .await
5412            .is_ok()
5413    }
5414
5415    #[tokio::test]
5416    async fn revoking_a_held_ca_by_pem_or_serial_takes_it_out_of_service() {
5417        let dir = tempfile::tempdir().unwrap();
5418
5419        // Intermediate, by its certificate.
5420        let (manager, root, intermediate, _) = two_level_manager(dir.path(), None).await;
5421        let leaf = manager
5422            .sign_certificate_request(&request("a", &new_key(), "tls_client"), "intermediate_ca")
5423            .await
5424            .unwrap();
5425        assert!(
5426            manager
5427                .validate_certificate_chain(&leaf.certificate_pem, CertificatePurpose::ClientAuth)
5428                .await
5429                .unwrap()
5430        );
5431        manager
5432            .revoke_certificate_pem(&intermediate.cert_pem, RevocationReason::CaCompromise, None)
5433            .await
5434            .unwrap();
5435        assert!(
5436            !can_issue(&manager, "intermediate_ca", "b").await,
5437            "revoked intermediate issued"
5438        );
5439        assert!(
5440            !manager
5441                .validate_certificate_chain(&leaf.certificate_pem, CertificatePurpose::ClientAuth)
5442                .await
5443                .unwrap()
5444        );
5445        assert!(
5446            can_issue(&manager, "root_ca", "c").await,
5447            "the root is unaffected"
5448        );
5449
5450        // Root, by its certificate: it signs nothing and trusts nothing any more.
5451        manager
5452            .revoke_certificate_pem(&root.cert_pem, RevocationReason::CaCompromise, None)
5453            .await
5454            .unwrap();
5455        assert!(
5456            !can_issue(&manager, "root_ca", "d").await,
5457            "revoked root issued"
5458        );
5459        assert!(
5460            !manager
5461                .validate_certificate_chain(&root.cert_pem, CertificatePurpose::ClientAuth)
5462                .await
5463                .unwrap()
5464        );
5465        assert!(
5466            !manager
5467                .validate_certificate_chain(&root.leaf("e", |_| {}), CertificatePurpose::ClientAuth)
5468                .await
5469                .unwrap()
5470        );
5471
5472        // Intermediate, by serial number through the issuer-scoped call.
5473        let dir2 = tempfile::tempdir().unwrap();
5474        let (manager, _, _, _) = two_level_manager(dir2.path(), None).await;
5475        let serial = manager.ca_certificates.read().await["intermediate_ca"]
5476            .certificate
5477            .serial_number
5478            .clone();
5479        manager
5480            .revoke_certificate_issued_by("root_ca", &serial, RevocationReason::CaCompromise, None)
5481            .await
5482            .unwrap();
5483        assert!(!can_issue(&manager, "intermediate_ca", "f").await);
5484        assert_eq!(
5485            manager.ca_certificates.read().await["intermediate_ca"]
5486                .certificate
5487                .status,
5488            CertificateStatus::Revoked
5489        );
5490    }
5491
5492    #[tokio::test]
5493    async fn initialize_again_does_not_bring_a_revoked_ca_back() {
5494        let dir = tempfile::tempdir().unwrap();
5495        let (manager, _, _, _) = two_level_manager(dir.path(), None).await;
5496        manager
5497            .revoke_ca_certificate("intermediate_ca", RevocationReason::CaCompromise, None)
5498            .await
5499            .unwrap();
5500        manager.initialize().await.unwrap(); // no state file
5501        assert!(!can_issue(&manager, "intermediate_ca", "x").await);
5502        assert_eq!(
5503            manager.ca_certificates.read().await["intermediate_ca"]
5504                .certificate
5505                .status,
5506            CertificateStatus::Revoked
5507        );
5508    }
5509
5510    #[tokio::test]
5511    async fn loading_an_older_state_cannot_roll_back_a_revocation_or_a_crl_number() {
5512        let dir = tempfile::tempdir().unwrap();
5513        let state = dir.path().join("state.json");
5514        let (manager, _, _, _) = two_level_manager(dir.path(), Some(&state)).await;
5515        let a = manager
5516            .sign_certificate_request(&request("a", &new_key(), "tls_client"), "root_ca")
5517            .await
5518            .unwrap();
5519        let b = manager
5520            .sign_certificate_request(&request("b", &new_key(), "tls_client"), "root_ca")
5521            .await
5522            .unwrap();
5523        // A copy of the state before the revocation and before the second CRL.
5524        manager.generate_crl("root_ca").await.unwrap();
5525        let old_copy = dir.path().join("old.json");
5526        std::fs::copy(&state, &old_copy).unwrap();
5527        manager
5528            .revoke_certificate(&a.serial_number, RevocationReason::KeyCompromise, None)
5529            .await
5530            .unwrap();
5531        manager.generate_crl("root_ca").await.unwrap();
5532        let number = manager.crl_numbers.read().await["root_ca"];
5533
5534        manager
5535            .load_state(old_copy.to_str().unwrap())
5536            .await
5537            .unwrap();
5538        assert_eq!(
5539            manager
5540                .check_certificate_status(&a.serial_number)
5541                .await
5542                .unwrap(),
5543            CertificateStatus::Revoked,
5544            "an old copy must not un-revoke"
5545        );
5546        assert_eq!(manager.crl_numbers.read().await["root_ca"], number);
5547        assert_eq!(
5548            manager
5549                .check_certificate_status(&b.serial_number)
5550                .await
5551                .unwrap(),
5552            CertificateStatus::Valid
5553        );
5554
5555        // And the other direction: a newer file adds what this manager lacks.
5556        let fresh = X509CertificateManager::new(manager.config.clone());
5557        fresh.initialize().await.unwrap(); // loads the state file
5558        fresh.load_state(old_copy.to_str().unwrap()).await.unwrap();
5559        assert_eq!(
5560            fresh
5561                .check_certificate_status(&a.serial_number)
5562                .await
5563                .unwrap(),
5564            CertificateStatus::Revoked
5565        );
5566    }
5567
5568    #[tokio::test]
5569    async fn saving_state_leaves_no_temporary_file_and_survives_concurrent_writers() {
5570        let dir = tempfile::tempdir().unwrap();
5571        let state = dir.path().join("state.json");
5572        let (manager, _, _, _) = two_level_manager(dir.path(), Some(&state)).await;
5573        let mut tasks = Vec::new();
5574        for i in 0..12 {
5575            let manager = manager.clone();
5576            tasks.push(tokio::spawn(async move {
5577                manager
5578                    .sign_certificate_request(
5579                        &request(&format!("c{i}"), &new_key(), "tls_client"),
5580                        "root_ca",
5581                    )
5582                    .await
5583                    .unwrap();
5584            }));
5585        }
5586        for task in tasks {
5587            task.await.unwrap();
5588        }
5589        let text = std::fs::read_to_string(&state).unwrap();
5590        let parsed: serde_json::Value = serde_json::from_str(&text).expect("complete JSON");
5591        assert_eq!(parsed["certificates"].as_object().unwrap().len(), 12);
5592        let leftovers: Vec<_> = std::fs::read_dir(dir.path())
5593            .unwrap()
5594            .map(|e| e.unwrap().file_name().to_string_lossy().to_string())
5595            .filter(|n| n.ends_with(".tmp"))
5596            .collect();
5597        assert!(leftovers.is_empty(), "{leftovers:?}");
5598    }
5599
5600    #[tokio::test]
5601    async fn ip_names_that_wrap_or_hide_special_addresses_are_refused() {
5602        let dir = tempfile::tempdir().unwrap();
5603        let (manager, _) =
5604            manager_with_profiles(dir.path(), vec![("open", open_profile("open"))]).await;
5605        for ip in [
5606            "::ffff:127.0.0.1",
5607            "::ffff:0.0.0.0",
5608            "::ffff:224.0.0.1",
5609            "255.255.255.255",
5610            "::1",
5611            "::",
5612            "ff02::1",
5613        ] {
5614            let mut r = request("host", &new_key(), "open");
5615            r.subject_alt_names = vec![SubjectAltName::IpAddress(ip.to_string())];
5616            assert_refused(&manager, &r, ip).await;
5617        }
5618        let mut ok = request("host", &new_key(), "open");
5619        ok.subject_alt_names = vec![
5620            SubjectAltName::IpAddress("192.0.2.7".to_string()),
5621            SubjectAltName::IpAddress("2001:db8::7".to_string()),
5622        ];
5623        manager
5624            .sign_certificate_request(&ok, "root_ca")
5625            .await
5626            .unwrap();
5627    }
5628
5629    /// SubjectPublicKeyInfo PEM from raw parts.
5630    fn spki_pem(algorithm_oid: &[u8], parameters: Option<&[u8]>, key: &[u8]) -> String {
5631        fn der(tag: u8, content: &[u8]) -> Vec<u8> {
5632            let mut out = vec![tag];
5633            match content.len() {
5634                n if n < 128 => out.push(n as u8),
5635                n if n < 256 => out.extend([0x81, n as u8]),
5636                n if n < 65536 => out.extend([0x82, (n >> 8) as u8, n as u8]),
5637                n => out.extend([0x83, (n >> 16) as u8, (n >> 8) as u8, n as u8]),
5638            }
5639            out.extend(content);
5640            out
5641        }
5642        let mut algorithm = der(0x06, algorithm_oid);
5643        if let Some(parameters) = parameters {
5644            algorithm.extend(parameters);
5645        }
5646        let mut bits = vec![0u8];
5647        bits.extend(key);
5648        let spki = der(0x30, &[der(0x30, &algorithm), der(0x03, &bits)].concat());
5649        format!(
5650            "-----BEGIN PUBLIC KEY-----\n{}\n-----END PUBLIC KEY-----\n",
5651            BASE64_STANDARD.encode(spki)
5652        )
5653    }
5654
5655    fn rsa_pem_parts(modulus: &[u8], exponent: &[u8]) -> String {
5656        fn int(bytes: &[u8]) -> Vec<u8> {
5657            // Minimal DER: a leading zero only when the top bit would make it negative.
5658            let mut content = Vec::new();
5659            if bytes.first().is_some_and(|b| *b >= 0x80) {
5660                content.push(0);
5661            }
5662            content.extend(bytes);
5663            let mut out = vec![0x02];
5664            let n = content.len();
5665            match n {
5666                n if n < 128 => out.push(n as u8),
5667                n if n < 256 => out.extend([0x81, n as u8]),
5668                n => out.extend([0x82, (n >> 8) as u8, n as u8]),
5669            }
5670            out.extend(content);
5671            out
5672        }
5673        let body = [int(modulus), int(exponent)].concat();
5674        let mut key = vec![0x30];
5675        match body.len() {
5676            n if n < 128 => key.push(n as u8),
5677            n if n < 256 => key.extend([0x81, n as u8]),
5678            n => key.extend([0x82, (n >> 8) as u8, n as u8]),
5679        }
5680        key.extend(body);
5681        spki_pem(
5682            &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01],
5683            Some(&[0x05, 0x00]),
5684            &key,
5685        )
5686    }
5687
5688    #[tokio::test]
5689    #[allow(clippy::vec_init_then_push)] // the cases are built up in groups, with setup between
5690    async fn malformed_or_unusable_subject_keys_are_refused() {
5691        let dir = tempfile::tempdir().unwrap();
5692        let (manager, _) = manager_with_profiles(dir.path(), vec![]).await;
5693        let odd_modulus = |bytes: usize| {
5694            let mut m = vec![0xC5u8; bytes];
5695            *m.last_mut().unwrap() |= 1;
5696            m
5697        };
5698        let mut cases: Vec<(&str, String)> = Vec::new();
5699
5700        // RSA: exponent and modulus.
5701        cases.push(("exponent 1", rsa_pem_parts(&odd_modulus(256), &[1])));
5702        cases.push(("exponent 3", rsa_pem_parts(&odd_modulus(256), &[3])));
5703        cases.push((
5704            "even exponent",
5705            rsa_pem_parts(&odd_modulus(256), &[1, 0, 2]),
5706        ));
5707        cases.push(("zero exponent", rsa_pem_parts(&odd_modulus(256), &[0])));
5708        let mut even = odd_modulus(256);
5709        *even.last_mut().unwrap() &= !1;
5710        cases.push(("even modulus", rsa_pem_parts(&even, &[1, 0, 1])));
5711        cases.push((
5712            "32768-bit modulus",
5713            rsa_pem_parts(&odd_modulus(4096), &[1, 0, 1]),
5714        ));
5715        cases.push((
5716            "1024-bit modulus",
5717            rsa_pem_parts(&odd_modulus(128), &[1, 0, 1]),
5718        ));
5719
5720        // Ed25519: wrong length, parameters present.
5721        let ed_oid = [0x2b, 0x65, 0x70];
5722        cases.push(("1-byte Ed25519", spki_pem(&ed_oid, None, &[7])));
5723        cases.push(("33-byte Ed25519", spki_pem(&ed_oid, None, &[7u8; 33])));
5724        cases.push((
5725            "Ed25519 with parameters",
5726            spki_pem(&ed_oid, Some(&[0x05, 0x00]), &[7u8; 32]),
5727        ));
5728
5729        // EC: a real key with its point damaged, a compressed prefix, a wrong size.
5730        let real = new_key();
5731        let raw = real.public_key_raw().to_vec();
5732        let p256_oid = [0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01];
5733        let p256_params = [0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07];
5734        let mut off_curve = raw.clone();
5735        *off_curve.last_mut().unwrap() ^= 0x01;
5736        cases.push((
5737            "point not on the curve",
5738            spki_pem(&p256_oid, Some(&p256_params), &off_curve),
5739        ));
5740        let mut compressed = raw.clone();
5741        compressed[0] = 0x02;
5742        cases.push((
5743            "compressed prefix",
5744            spki_pem(&p256_oid, Some(&p256_params), &compressed),
5745        ));
5746        cases.push((
5747            "short point",
5748            spki_pem(&p256_oid, Some(&p256_params), &raw[..40]),
5749        ));
5750        let all_zero = {
5751            let mut z = vec![0u8; 65];
5752            z[0] = 4;
5753            z
5754        };
5755        cases.push((
5756            "zero point",
5757            spki_pem(&p256_oid, Some(&p256_params), &all_zero),
5758        ));
5759
5760        for (why, pem) in cases {
5761            let mut r = request("k", &real, "tls_client");
5762            r.public_key_pem = pem;
5763            assert_refused(&manager, &r, why).await;
5764        }
5765        // Positive controls: the same hand-built shapes, well-formed, are accepted (so the
5766        // refusals above are about the damage and not about the builder).
5767        let mut sound_rsa = request("k", &real, "tls_client");
5768        sound_rsa.public_key_pem = rsa_pem_parts(&odd_modulus(256), &[1, 0, 1]);
5769        manager
5770            .sign_certificate_request(&sound_rsa, "root_ca")
5771            .await
5772            .expect("a sound hand-built RSA key is accepted");
5773        let mut sound_ed = request("k", &real, "tls_client");
5774        sound_ed.public_key_pem = spki_pem(&ed_oid, None, &[7u8; 32]);
5775        manager
5776            .sign_certificate_request(&sound_ed, "root_ca")
5777            .await
5778            .expect("a sound hand-built Ed25519 key is accepted");
5779        // The undamaged key is fine.
5780        manager
5781            .sign_certificate_request(&request("k", &real, "tls_client"), "root_ca")
5782            .await
5783            .unwrap();
5784    }
5785
5786    #[tokio::test]
5787    async fn uris_formatting_characters_and_request_ids_are_policed() {
5788        let dir = tempfile::tempdir().unwrap();
5789        let (manager, _) =
5790            manager_with_profiles(dir.path(), vec![("open", open_profile("open"))]).await;
5791        for uri in [
5792            "file:///etc/passwd",
5793            "javascript:alert(1)",
5794            "ftp://host.example/x",
5795            "data:text/plain,hi",
5796            "ldap://host.example",
5797        ] {
5798            let mut r = request("u", &new_key(), "open");
5799            r.subject_alt_names = vec![SubjectAltName::Uri(uri.to_string())];
5800            assert_refused(&manager, &r, uri).await;
5801        }
5802        for uri in [
5803            "https://svc.example/id",
5804            "HTTP://svc.example/id",
5805            "urn:uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66",
5806            "spiffe://example.org/ns/a",
5807        ] {
5808            let mut r = request("u", &new_key(), "open");
5809            r.subject_alt_names = vec![SubjectAltName::Uri(uri.to_string())];
5810            manager
5811                .sign_certificate_request(&r, "root_ca")
5812                .await
5813                .unwrap_or_else(|e| panic!("{uri}: {e}"));
5814        }
5815        for (why, text) in [
5816            ("right-to-left override", "bank\u{202e}moc.evil"),
5817            ("zero-width space", "pay\u{200b}pal"),
5818            ("byte-order mark", "\u{feff}admin"),
5819            ("isolate", "a\u{2066}b"),
5820        ] {
5821            let mut r = request("f", &new_key(), "tls_client");
5822            r.subject.common_name = text.to_string();
5823            assert_refused(&manager, &r, why).await;
5824        }
5825        let mut r = request("id", &new_key(), "tls_client");
5826        r.request_id = "x".repeat(129);
5827        assert_refused(&manager, &r, "long request id").await;
5828        r.request_id = "bad\nid".to_string();
5829        assert_refused(&manager, &r, "control character in request id").await;
5830    }
5831
5832    #[tokio::test]
5833    async fn a_root_is_valid_as_itself_only_for_the_purposes_it_allows() {
5834        let dir = tempfile::tempdir().unwrap();
5835        let unrestricted = TestCa::root("Any Purpose Root");
5836        let manager = manager_with(dir.path(), &unrestricted, true).await;
5837        for purpose in [
5838            CertificatePurpose::ServerAuth,
5839            CertificatePurpose::CodeSigning,
5840        ] {
5841            assert!(
5842                manager
5843                    .validate_certificate_chain(&unrestricted.cert_pem, purpose)
5844                    .await
5845                    .unwrap(),
5846                "{purpose:?}"
5847            );
5848        }
5849
5850        let dir2 = tempfile::tempdir().unwrap();
5851        let mut params = ca_params("Signing Only Root");
5852        params.extended_key_usages = vec![ExtendedKeyUsagePurpose::CodeSigning];
5853        let restricted = TestCa::root_with(params);
5854        let manager = manager_with(dir2.path(), &restricted, true).await;
5855        assert!(
5856            manager
5857                .validate_certificate_chain(&restricted.cert_pem, CertificatePurpose::CodeSigning)
5858                .await
5859                .unwrap()
5860        );
5861        assert!(
5862            !manager
5863                .validate_certificate_chain(&restricted.cert_pem, CertificatePurpose::ServerAuth)
5864                .await
5865                .unwrap()
5866        );
5867    }
5868
5869    #[tokio::test]
5870    async fn contradictory_profiles_and_orphan_key_paths_stop_initialize() {
5871        let dir = tempfile::tempdir().unwrap();
5872        let root = TestCa::root("Config");
5873        let (cert, key) = root.write(dir.path(), "root");
5874
5875        // A TLS server profile without serverAuth.
5876        let mut config = config_for(&cert, &key);
5877        let mut profile = open_profile("bad");
5878        profile.cert_type = CertificateType::TlsServer; // but lists clientAuth only
5879        config
5880            .certificate_profiles
5881            .insert("bad".to_string(), profile);
5882        assert!(
5883            X509CertificateManager::new(config)
5884                .initialize()
5885                .await
5886                .is_err()
5887        );
5888
5889        // An end-entity profile asking for keyCertSign (it would still be cA=FALSE).
5890        let mut config = config_for(&cert, &key);
5891        let mut profile = open_profile("signer");
5892        profile.key_usage = vec![KeyUsage::DigitalSignature, KeyUsage::KeyCertSign];
5893        config
5894            .certificate_profiles
5895            .insert("signer".to_string(), profile);
5896        assert!(
5897            X509CertificateManager::new(config)
5898                .initialize()
5899                .await
5900                .is_err()
5901        );
5902
5903        // A negative validity.
5904        let mut config = config_for(&cert, &key);
5905        let mut profile = open_profile("negative");
5906        profile.validity_days = -1;
5907        config
5908            .certificate_profiles
5909            .insert("negative".to_string(), profile);
5910        assert!(
5911            X509CertificateManager::new(config)
5912                .initialize()
5913                .await
5914                .is_err()
5915        );
5916
5917        // An intermediate key path with no intermediate certificate.
5918        let mut config = config_for(&cert, &key);
5919        config.intermediate_ca_key_path = Some("ca/inter.key".to_string());
5920        assert!(
5921            X509CertificateManager::new(config)
5922                .initialize()
5923                .await
5924                .is_err()
5925        );
5926
5927        // The consistent configuration is fine.
5928        X509CertificateManager::new(config_for(&cert, &key))
5929            .initialize()
5930            .await
5931            .unwrap();
5932    }
5933
5934    #[cfg(unix)]
5935    #[tokio::test]
5936    async fn an_unreadable_state_location_stops_initialize_instead_of_starting_empty() {
5937        use std::os::unix::fs::PermissionsExt;
5938        let dir = tempfile::tempdir().unwrap();
5939        let root = TestCa::root("Perm");
5940        let (cert, key) = root.write(dir.path(), "root");
5941        let locked = dir.path().join("locked");
5942        std::fs::create_dir(&locked).unwrap();
5943        std::fs::write(locked.join("state.json"), "{}").unwrap();
5944        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
5945        let readable_anyway = std::fs::metadata(locked.join("state.json")).is_ok(); // running as root
5946        let mut config = config_for(&cert, &key);
5947        config.state_path = Some(locked.join("state.json").to_string_lossy().to_string());
5948        let outcome = X509CertificateManager::new(config).initialize().await;
5949        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o700)).unwrap();
5950        if !readable_anyway {
5951            assert!(
5952                outcome.is_err(),
5953                "a permission error must not read as \"no state yet\""
5954            );
5955        }
5956    }
5957}