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