-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathconfig.rs
More file actions
289 lines (253 loc) · 8.96 KB
/
Copy pathconfig.rs
File metadata and controls
289 lines (253 loc) · 8.96 KB
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
//! HTTPS configuration domain type
//!
//! This module defines the domain-level HTTPS configuration that is stored
//! in the environment and used to configure Caddy TLS termination.
//!
//! ## Domain vs DTO
//!
//! This is the domain type. The DTO version (`HttpsSection`) is in the
//! application layer at `src/application/command_handlers/create/config/https.rs`.
//!
//! The domain type is validated when created from the DTO and carries
//! the configuration through the environment lifecycle.
use serde::{Deserialize, Serialize};
use thiserror::Error;
use crate::shared::Email;
/// Error type for `HttpsConfig` construction failures
///
/// Contains validation errors that can occur when constructing an `HttpsConfig`.
#[derive(Debug, Clone, Error, PartialEq, Eq)]
pub enum HttpsConfigError {
/// The admin email address is invalid
#[error("Invalid admin email '{email}': {reason}")]
InvalidEmail {
/// The invalid email that was provided
email: String,
/// The reason why the email is invalid
reason: String,
},
}
impl HttpsConfigError {
/// Returns actionable help text for this error
///
/// Provides detailed guidance on how to fix the configuration issue.
#[must_use]
pub fn help(&self) -> &'static str {
match self {
Self::InvalidEmail { .. } => {
"Invalid admin email format.\n\
\n\
The admin email is used by Let's Encrypt to send:\n\
- Certificate expiration warnings\n\
- Renewal failure notifications\n\
- Important security updates\n\
\n\
Requirements:\n\
- Must be a valid email format (e.g., admin@example.com)\n\
- Should be a monitored mailbox for security alerts\n\
\n\
Fix:\n\
Update the admin_email in your HTTPS configuration:\n\
\n\
\"https\": {\n\
\"admin_email\": \"admin@yourdomain.com\",\n\
\"use_staging\": false\n\
}"
}
}
}
}
/// Domain-level HTTPS configuration for TLS termination
///
/// Contains validated HTTPS settings used for Caddy reverse proxy configuration.
/// This type is created from the application-layer DTO (`HttpsSection`) after
/// validation and stored in the environment.
///
/// # Let's Encrypt Environments
///
/// - **Production** (default): Trusted certificates, rate-limited
/// - **Staging**: Untrusted test certificates, higher rate limits
///
/// # Example
///
/// ```rust
/// use torrust_tracker_deployer_lib::domain::https::HttpsConfig;
///
/// let config = HttpsConfig::new("admin@example.com", false).unwrap();
/// assert_eq!(config.admin_email(), "admin@example.com");
/// assert!(!config.use_staging());
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct HttpsConfig {
/// Admin email for Let's Encrypt notifications
///
/// Receives certificate expiration warnings and renewal failure notifications.
admin_email: String,
/// Whether to use Let's Encrypt staging environment
///
/// - `true`: Use staging CA (for testing, certificates not trusted)
/// - `false`: Use production CA (trusted certificates)
use_staging: bool,
}
impl HttpsConfig {
/// Creates a new HTTPS configuration with validated email
///
/// Validates the admin email format at construction time, ensuring
/// the configuration is always valid.
///
/// # Arguments
///
/// * `admin_email` - Admin email for Let's Encrypt notifications
/// * `use_staging` - Whether to use staging environment
///
/// # Errors
///
/// Returns `HttpsConfigError::InvalidEmail` if the email format is invalid.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::domain::https::HttpsConfig;
///
/// // Production configuration
/// let config = HttpsConfig::new("admin@example.com", false).unwrap();
/// assert!(!config.use_staging());
///
/// // Staging configuration (for testing)
/// let staging = HttpsConfig::new("admin@example.com", true).unwrap();
/// assert!(staging.use_staging());
///
/// // Invalid email is rejected
/// let result = HttpsConfig::new("invalid-email", false);
/// assert!(result.is_err());
/// ```
pub fn new(
admin_email: impl Into<String>,
use_staging: bool,
) -> Result<Self, HttpsConfigError> {
let email_str = admin_email.into();
// Validate email format using the shared Email type
Email::new(&email_str).map_err(|e| HttpsConfigError::InvalidEmail {
email: email_str.clone(),
reason: e.to_string(),
})?;
Ok(Self {
admin_email: email_str,
use_staging,
})
}
/// Creates an HTTPS config from a validated email
///
/// This is the preferred factory method when working with validated
/// email addresses from the application layer. Since the email is
/// already validated, this method is infallible.
///
/// # Arguments
///
/// * `email` - Validated email address
/// * `use_staging` - Whether to use staging environment
#[must_use]
pub fn from_validated_email(email: &Email, use_staging: bool) -> Self {
Self {
admin_email: email.to_string(),
use_staging,
}
}
/// Returns the admin email address
#[must_use]
pub fn admin_email(&self) -> &str {
&self.admin_email
}
/// Returns whether to use Let's Encrypt staging environment
#[must_use]
pub fn use_staging(&self) -> bool {
self.use_staging
}
}
impl Default for HttpsConfig {
/// Creates a default HTTPS configuration
///
/// Uses a placeholder email that should be replaced before deployment.
fn default() -> Self {
Self {
admin_email: "admin@example.com".to_string(),
use_staging: false,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_should_create_https_config_with_production_ca() {
let config = HttpsConfig::new("admin@tracker.example.com", false)
.expect("valid email should succeed");
assert_eq!(config.admin_email(), "admin@tracker.example.com");
assert!(!config.use_staging());
}
#[test]
fn it_should_create_https_config_with_staging_ca() {
let config = HttpsConfig::new("admin@tracker.example.com", true)
.expect("valid email should succeed");
assert_eq!(config.admin_email(), "admin@tracker.example.com");
assert!(config.use_staging());
}
#[test]
fn it_should_reject_invalid_email() {
let result = HttpsConfig::new("invalid-email", false);
assert!(result.is_err());
let err = result.unwrap_err();
assert!(matches!(err, HttpsConfigError::InvalidEmail { .. }));
}
#[test]
fn it_should_reject_email_without_at_symbol() {
let result = HttpsConfig::new("admin.example.com", false);
assert!(result.is_err());
}
#[test]
fn it_should_create_default_https_config() {
let config = HttpsConfig::default();
assert_eq!(config.admin_email(), "admin@example.com");
assert!(!config.use_staging());
}
#[test]
fn it_should_serialize_to_json() {
let config =
HttpsConfig::new("admin@example.com", true).expect("valid email should succeed");
let json = serde_json::to_string(&config).expect("serialization should succeed");
assert!(json.contains("\"admin_email\":\"admin@example.com\""));
assert!(json.contains("\"use_staging\":true"));
}
#[test]
fn it_should_deserialize_from_json() {
let json = r#"{"admin_email":"test@example.com","use_staging":false}"#;
let config: HttpsConfig =
serde_json::from_str(json).expect("deserialization should succeed");
assert_eq!(config.admin_email(), "test@example.com");
assert!(!config.use_staging());
}
#[test]
fn it_should_be_cloneable() {
let config =
HttpsConfig::new("admin@example.com", true).expect("valid email should succeed");
let cloned = config.clone();
assert_eq!(config, cloned);
}
#[test]
fn it_should_create_from_validated_email() {
let email = Email::new("admin@example.com").expect("valid email");
let config = HttpsConfig::from_validated_email(&email, false);
assert_eq!(config.admin_email(), "admin@example.com");
assert!(!config.use_staging());
}
#[test]
fn it_should_provide_help_for_invalid_email_error() {
let err = HttpsConfigError::InvalidEmail {
email: "bad".to_string(),
reason: "missing @".to_string(),
};
let help = err.help();
assert!(help.contains("Invalid admin email format"));
assert!(help.contains("Let's Encrypt"));
}
}