acmex 0.8.0

AcmeX: High-performance, extensible ACME v2 (RFC 8555) client and server in Rust, supporting multiple DNS providers, storage backends, and crypto libraries.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
use crate::ca::{CAConfig, CertificateAuthority, Environment};
/// Configuration management for AcmeX.
/// This module provides comprehensive configuration support, including TOML parsing,
/// environment variable overrides, and validation for multi-CA setups.
use crate::error::{AcmeError, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::env;
use std::path::Path;
use std::str::FromStr;
use std::time::Duration;

/// Main configuration structure for the AcmeX application.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Config {
    /// ACME protocol and CA settings.
    #[serde(default)]
    pub acme: AcmeSettings,

    /// Storage backend settings.
    #[serde(default)]
    pub storage: StorageSettings,

    /// Challenge solving settings.
    #[serde(default)]
    pub challenge: ChallengeSettings,

    /// Certificate renewal settings.
    #[serde(default)]
    pub renewal: RenewalSettings,

    /// Metrics and observability settings.
    #[serde(default)]
    pub metrics: Option<MetricsSettings>,

    /// Notification settings (Webhooks, Email).
    #[serde(default)]
    pub notifications: Option<NotificationSettings>,

    /// CLI-specific settings.
    #[serde(default)]
    pub cli: Option<CliSettings>,

    /// API server settings.
    #[serde(default)]
    pub server: Option<ServerSettings>,
}

/// ACME protocol and Certificate Authority (CA) settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AcmeSettings {
    /// Selected Certificate Authority: "letsencrypt", "google", "zerossl", or "custom".
    #[serde(default = "default_ca")]
    pub ca: String,

    /// CA environment: "production" or "staging".
    #[serde(default = "default_ca_env")]
    pub ca_environment: String,

    /// Custom CA directory URL (required if ca = "custom").
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ca_custom_url: Option<String>,

    /// Contact information (e.g., ["mailto:admin@example.com"]).
    #[serde(default)]
    pub contact: Vec<String>,

    /// Whether the Terms of Service (ToS) have been agreed to.
    #[serde(default = "default_true")]
    pub tos_agreed: bool,

    /// Optional External Account Binding (EAB) for CAs like Google or ZeroSSL.
    #[serde(default)]
    pub external_account_binding: Option<ExternalAccountBinding>,

    /// Internal cache for the resolved directory URL.
    #[serde(skip)]
    pub directory: String,
}

impl AcmeSettings {
    /// Converts the settings into a `CAConfig` for endpoint resolution.
    pub fn to_ca_config(&self) -> Result<CAConfig> {
        let ca_type = match self.ca.to_lowercase().as_str() {
            "letsencrypt" => CertificateAuthority::LetsEncrypt,
            "google" => {
                #[cfg(not(feature = "google-ca"))]
                return Err(AcmeError::configuration(
                    "Feature 'google-ca' is not enabled",
                ));
                #[cfg(feature = "google-ca")]
                CertificateAuthority::Google
            }
            "zerossl" => {
                #[cfg(not(feature = "zerossl-ca"))]
                return Err(AcmeError::configuration(
                    "Feature 'zerossl-ca' is not enabled",
                ));
                #[cfg(feature = "zerossl-ca")]
                CertificateAuthority::ZeroSSL
            }
            "custom" => CertificateAuthority::Custom,
            _ => {
                return Err(AcmeError::configuration(format!(
                    "Unsupported CA type: {}",
                    self.ca
                )));
            }
        };

        let env = match self.ca_environment.to_lowercase().as_str() {
            "production" | "prod" => Environment::Production,
            "staging" | "test" | "dev" => Environment::Staging,
            _ => {
                return Err(AcmeError::configuration(format!(
                    "Invalid environment: {}",
                    self.ca_environment
                )));
            }
        };

        let mut config = CAConfig::new(ca_type, env);
        if let Some(ref url) = self.ca_custom_url {
            config = config.with_custom_url(url.clone());
        }

        if let Some(first_contact) = self.contact.first() {
            config = config.with_contact_email(first_contact.clone());
        }

        Ok(config)
    }
}

/// External account binding configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExternalAccountBinding {
    pub key_id: String,
    pub hmac_key: String,
}

/// Storage backend settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StorageSettings {
    /// Storage backend type: "file", "redis", "encrypted".
    #[serde(default = "default_storage_backend")]
    pub backend: String,

    /// File storage configuration.
    #[serde(default)]
    pub file: Option<FileStorageConfig>,

    /// Redis storage configuration.
    #[serde(default)]
    pub redis: Option<RedisStorageConfig>,

    /// Encrypted storage configuration.
    #[serde(default)]
    pub encrypted: Option<EncryptedStorageConfig>,
}

/// File storage configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileStorageConfig {
    /// Directory path for certificates and account data.
    #[serde(default = "default_cert_path")]
    pub path: String,
}

/// Redis storage configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RedisStorageConfig {
    /// Redis connection URL.
    pub url: String,
    /// Connection pool size.
    #[serde(default = "default_pool_size")]
    pub connection_pool_size: usize,
    /// Database number.
    #[serde(default)]
    pub db: u32,
}

/// Encrypted storage configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EncryptedStorageConfig {
    /// The underlying backend to encrypt.
    pub inner_backend: String,
    /// Encryption key (supports ${VAR} syntax).
    pub encryption_key: String,
    /// Key format: "hex" or "base64".
    #[serde(default = "default_key_format")]
    pub key_format: String,
}

/// Challenge configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChallengeSettings {
    /// Default challenge type: "http-01", "dns-01", "tls-alpn-01".
    #[serde(default = "default_challenge_type")]
    pub challenge_type: String,
    /// HTTP-01 challenge configuration.
    #[serde(default)]
    pub http01: Option<Http01Config>,
    /// DNS-01 challenge configuration.
    #[serde(default)]
    pub dns01: Option<Dns01Config>,
    /// TLS-ALPN-01 challenge configuration.
    #[serde(default)]
    pub tls_alpn: Option<TlsAlpnConfig>,
}

/// HTTP-01 challenge configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Http01Config {
    /// Listen address for the temporary HTTP server.
    #[serde(default = "default_http_listen")]
    pub listen_addr: String,
    /// Domain for validation.
    pub domain: Option<String>,
    /// Path where the challenge token will be served.
    #[serde(default = "default_challenge_path")]
    pub challenge_path: String,
}

/// DNS-01 challenge configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Dns01Config {
    /// Primary DNS provider name.
    pub provider: Option<String>,
    /// API token/key.
    pub api_token: Option<String>,
    /// Zone ID or domain.
    pub zone_id: Option<String>,
    /// Multiple provider configurations.
    #[serde(default)]
    pub providers: Vec<DnsProviderConfig>,
    /// DNS propagation timeout in seconds.
    #[serde(default = "default_dns_timeout")]
    pub propagation_timeout_secs: u64,
}

/// DNS provider configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DnsProviderConfig {
    pub name: String,
    pub api_token: Option<String>,
    pub zone_id: Option<String>,
    #[serde(default)]
    pub extra: HashMap<String, String>,
}

/// TLS-ALPN-01 challenge configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TlsAlpnConfig {
    #[serde(default = "default_tls_listen")]
    pub listen_addr: String,
    pub cert_path: Option<String>,
    pub key_path: Option<String>,
}

/// Renewal settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RenewalSettings {
    /// Check interval in seconds.
    #[serde(default = "default_check_interval")]
    pub check_interval: u64,
    /// Days before expiry to trigger renewal.
    #[serde(default = "default_renew_before_days")]
    pub renew_before_days: u32,
    /// Maximum retry attempts.
    #[serde(default = "default_max_retries")]
    pub max_retries: u32,
    /// Retry delay in seconds.
    #[serde(default = "default_retry_delay")]
    pub retry_delay_secs: u64,
    /// Concurrency level for renewals.
    #[serde(default = "default_concurrency")]
    pub concurrency: u32,
    /// Renewal hooks.
    #[serde(default)]
    pub hooks: Option<RenewalHooks>,
}

/// Renewal hooks configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RenewalHooks {
    pub before: Option<String>,
    pub after: Option<String>,
    pub on_error: Option<String>,
}

/// Metrics settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MetricsSettings {
    #[serde(default = "default_true")]
    pub enabled: bool,
    #[serde(default = "default_metrics_listen")]
    pub listen_addr: String,
    #[serde(default = "default_metrics_prefix")]
    pub prefix: String,
}

/// Notification settings.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct NotificationSettings {
    #[serde(default)]
    pub webhooks: Vec<WebhookConfig>,
    #[serde(default)]
    pub email: Vec<EmailConfig>,
}

/// Webhook notification configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebhookConfig {
    pub name: Option<String>,
    pub url: String,
    #[serde(default)]
    pub events: Vec<String>,
    #[serde(default = "default_webhook_format")]
    pub format: String,
    pub auth_token: Option<String>,
    #[serde(default = "default_webhook_timeout")]
    pub timeout_secs: u64,
}

/// Email notification configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmailConfig {
    pub smtp_host: String,
    #[serde(default = "default_smtp_port")]
    pub smtp_port: u16,
    pub from: String,
    pub to: Vec<String>,
    #[serde(default)]
    pub events: Vec<String>,
    pub username: Option<String>,
    pub password: Option<String>,
}

/// CLI settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CliSettings {
    #[serde(default = "default_output_format")]
    pub output_format: String,
    #[serde(default = "default_true")]
    pub colors: bool,
    #[serde(default = "default_log_level")]
    pub log_level: String,
    pub log_file: Option<String>,
    #[serde(default = "default_log_max_size")]
    pub log_max_size: u64,
    #[serde(default = "default_log_backup_count")]
    pub log_backup_count: u32,
}

/// Server settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerSettings {
    #[serde(default = "default_server_listen")]
    pub listen_addr: String,
    #[serde(default = "default_true")]
    pub enable_api: bool,
    #[serde(default = "default_true")]
    pub enable_webhook: bool,
}

// Default value functions
fn default_ca() -> String {
    "letsencrypt".to_string()
}
fn default_ca_env() -> String {
    "production".to_string()
}
fn default_true() -> bool {
    true
}
fn default_storage_backend() -> String {
    "file".to_string()
}
fn default_cert_path() -> String {
    ".acmex/certs".to_string()
}
fn default_pool_size() -> usize {
    10
}
fn default_key_format() -> String {
    "hex".to_string()
}
fn default_challenge_type() -> String {
    "dns-01".to_string()
}
fn default_http_listen() -> String {
    "0.0.0.0:80".to_string()
}
fn default_challenge_path() -> String {
    ".well-known/acme-challenge".to_string()
}
fn default_tls_listen() -> String {
    "0.0.0.0:443".to_string()
}
fn default_dns_timeout() -> u64 {
    300
}
fn default_check_interval() -> u64 {
    3600
}
fn default_renew_before_days() -> u32 {
    30
}
fn default_max_retries() -> u32 {
    3
}
fn default_retry_delay() -> u64 {
    300
}
fn default_concurrency() -> u32 {
    5
}
fn default_metrics_listen() -> String {
    "127.0.0.1:9090".to_string()
}
fn default_metrics_prefix() -> String {
    "acmex".to_string()
}
fn default_webhook_format() -> String {
    "json".to_string()
}
fn default_webhook_timeout() -> u64 {
    30
}
fn default_smtp_port() -> u16 {
    587
}
fn default_output_format() -> String {
    "text".to_string()
}
fn default_log_level() -> String {
    "info".to_string()
}
fn default_log_max_size() -> u64 {
    100
}
fn default_log_backup_count() -> u32 {
    10
}
fn default_server_listen() -> String {
    "127.0.0.1:8080".to_string()
}

impl Default for AcmeSettings {
    fn default() -> Self {
        Self {
            ca: default_ca(),
            ca_environment: default_ca_env(),
            ca_custom_url: None,
            contact: Vec::new(),
            tos_agreed: true,
            external_account_binding: None,
            directory: String::new(),
        }
    }
}

impl Default for StorageSettings {
    fn default() -> Self {
        Self {
            backend: default_storage_backend(),
            file: Some(FileStorageConfig {
                path: default_cert_path(),
            }),
            redis: None,
            encrypted: None,
        }
    }
}

impl Default for ChallengeSettings {
    fn default() -> Self {
        Self {
            challenge_type: default_challenge_type(),
            http01: None,
            dns01: None,
            tls_alpn: None,
        }
    }
}

impl Default for RenewalSettings {
    fn default() -> Self {
        Self {
            check_interval: default_check_interval(),
            renew_before_days: default_renew_before_days(),
            max_retries: default_max_retries(),
            retry_delay_secs: default_retry_delay(),
            concurrency: default_concurrency(),
            hooks: None,
        }
    }
}

impl Default for MetricsSettings {
    fn default() -> Self {
        Self {
            enabled: false,
            listen_addr: default_metrics_listen(),
            prefix: default_metrics_prefix(),
        }
    }
}

impl Default for CliSettings {
    fn default() -> Self {
        Self {
            output_format: default_output_format(),
            colors: true,
            log_level: default_log_level(),
            log_file: None,
            log_max_size: default_log_max_size(),
            log_backup_count: default_log_backup_count(),
        }
    }
}

impl Default for ServerSettings {
    fn default() -> Self {
        Self {
            listen_addr: default_server_listen(),
            enable_api: true,
            enable_webhook: true,
        }
    }
}

impl Config {
    /// Creates a new configuration with default values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Loads configuration from a TOML file.
    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
        let content = std::fs::read_to_string(path).map_err(|e| {
            tracing::error!("Failed to read config file: {}", e);
            AcmeError::configuration(format!("Failed to read config file: {}", e))
        })?;
        content.parse()
    }
}

impl FromStr for Config {
    type Err = AcmeError;

    /// Loads configuration from a TOML string.
    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        let mut config: Config = toml::from_str(s).map_err(|e| {
            tracing::error!("Failed to parse TOML configuration: {}", e);
            AcmeError::configuration(format!("Failed to parse TOML: {}", e))
        })?;

        // Resolve the ACME directory URL immediately after loading
        let ca_config = config.acme.to_ca_config()?;
        config.acme.directory = ca_config
            .directory_url()
            .map_err(AcmeError::configuration)?;

        Ok(config)
    }
}

impl Config {
    /// High-standard environment variable override implementation: supports all parameters and ensures core state synchronization.
    pub fn apply_env_overrides(&mut self) -> Result<()> {
        tracing::debug!("Applying comprehensive environment variable overrides");

        // 1. Core CA configuration overrides
        if let Ok(ca) = env::var("ACMEX_ACME_CA") {
            self.acme.ca = ca;
        }
        if let Ok(env) = env::var("ACMEX_ACME_ENV") {
            self.acme.ca_environment = env;
        }
        if let Ok(url) = env::var("ACMEX_ACME_CUSTOM_URL") {
            self.acme.ca_custom_url = Some(url);
        }

        // 2. Storage backend overrides (solves the issue where Redis couldn't be initialized from scratch in the original code)
        if let Ok(backend) = env::var("ACMEX_STORAGE_BACKEND") {
            self.storage.backend = backend;
        }

        if let Ok(redis_url) = env::var("ACMEX_STORAGE_REDIS_URL") {
            // Initialize if it doesn't exist, ensuring environment variables can take effect independently
            if self.storage.redis.is_none() {
                self.storage.redis = Some(RedisStorageConfig {
                    url: redis_url,
                    connection_pool_size: 10,
                    db: 0,
                });
            } else if let Some(ref mut r) = self.storage.redis {
                r.url = redis_url;
            }
        }

        // 3. Business policy overrides
        if let Ok(ct) = env::var("ACMEX_CHALLENGE_TYPE") {
            self.challenge.challenge_type = ct;
        }

        if let Ok(interval) = env::var("ACMEX_RENEWAL_CHECK_INTERVAL")
            && let Ok(secs) = interval.parse::<u64>()
        {
            self.renewal.check_interval = secs;
        }

        if let Ok(days) = env::var("ACMEX_RENEWAL_BEFORE_DAYS")
            && let Ok(d) = days.parse::<u32>()
        {
            self.renewal.renew_before_days = d;
        }

        // 4. Critical: Re-trigger resolution of derived state
        // Regardless of what was modified, ensure the Directory URL aligns with the latest CA configuration
        let ca_config = self.acme.to_ca_config()?;
        self.acme.directory = ca_config.directory_url().map_err(|e| {
            AcmeError::configuration(format!(
                "Failed to re-resolve directory after overrides: {}",
                e
            ))
        })?;

        tracing::info!(
            "Configuration overrides applied. Active Directory: {}",
            self.acme.directory
        );
        Ok(())
    }

    /// Expands environment variables in the format `${VAR}` within a string.
    pub fn expand_env_var(value: &str) -> Result<String> {
        let re = regex::Regex::new(r"\$\{([^}]+)}")
            .map_err(|_| AcmeError::configuration("Invalid regex pattern"))?;

        let result = re
            .replace_all(value, |caps: &regex::Captures| {
                let var_name = &caps[1];
                env::var(var_name).unwrap_or_else(|_| format!("${{{}}}", var_name))
            })
            .to_string();

        Ok(result)
    }

    /// Validates the configuration settings.
    pub fn validate(&self) -> Result<()> {
        tracing::debug!("Validating configuration");

        if self.acme.directory.is_empty() {
            return Err(AcmeError::configuration(
                "ACME directory URL could not be resolved",
            ));
        }

        match self.storage.backend.as_str() {
            "file" => {
                if let Some(ref file_config) = self.storage.file
                    && file_config.path.is_empty()
                {
                    return Err(AcmeError::configuration(
                        "File storage path cannot be empty",
                    ));
                }
            }
            "redis" => {
                if let Some(ref redis_config) = self.storage.redis
                    && redis_config.url.is_empty()
                {
                    return Err(AcmeError::configuration("Redis URL cannot be empty"));
                }
            }
            _ => {}
        }

        Ok(())
    }

    /// Returns the resolved ACME directory URL.
    pub fn acme_directory(&self) -> &str {
        &self.acme.directory
    }

    /// Returns the storage backend type.
    pub fn storage_backend(&self) -> &str {
        &self.storage.backend
    }

    /// Returns the selected challenge type.
    pub fn challenge_type(&self) -> &str {
        &self.challenge.challenge_type
    }

    /// Returns the renewal check interval as a `Duration`.
    pub fn renewal_check_interval(&self) -> Duration {
        Duration::from_secs(self.renewal.check_interval)
    }

    /// Returns the number of days before expiry to trigger renewal.
    pub fn should_renew_days_before(&self) -> u32 {
        self.renewal.renew_before_days
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_default_config() {
        let config = Config::default();
        assert_eq!(config.acme.ca, "letsencrypt");
        assert_eq!(config.storage.backend, "file");
    }

    #[test]
    fn test_ca_resolution() {
        let toml = r#"
[acme]
ca = "letsencrypt"
ca_environment = "staging"
"#;
        let config = Config::from_str(toml).unwrap();
        assert_eq!(
            config.acme_directory(),
            "https://acme-staging-v02.api.letsencrypt.org/directory"
        );
    }
}