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