Skip to main content

capy_core/
mail_config.rs

1use crate::{AppError, Result};
2use serde::{Deserialize, Serialize};
3
4/// A configuration credential. Debug is redacted; serialization is for config merging.
5#[derive(Clone, Default, Deserialize, Serialize)]
6#[serde(transparent)]
7pub struct MailSecret(String);
8impl MailSecret {
9    /// Explicitly access the credential for transport initialization.
10    pub fn expose(&self) -> &str {
11        &self.0
12    }
13}
14impl From<String> for MailSecret {
15    fn from(value: String) -> Self {
16        Self(value)
17    }
18}
19impl std::fmt::Debug for MailSecret {
20    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21        f.write_str("[REDACTED]")
22    }
23}
24
25/// Conventional outbound mail settings; activated by `App::mail`.
26#[derive(Clone, Debug, Deserialize, Serialize)]
27#[serde(default, deny_unknown_fields)]
28pub struct MailSettings {
29    /// `log` (metadata only, development), or `smtp`.
30    pub driver: String,
31    /// Parsed by the mail subsystem before startup/delivery.
32    pub from_address: String,
33    /// Optional display name.
34    pub from_name: Option<String>,
35    /// Total transport deadline, including connection establishment (1..=300 seconds).
36    pub timeout_seconds: u64,
37    /// Maximum unencoded message content bytes (1..=26214400); default 10 MiB.
38    pub max_message_bytes: usize,
39    /// Logical queue for ordinary, explicitly queueable mail.
40    pub queue: String,
41    /// SMTP connection and authentication.
42    pub smtp: SmtpSettings,
43}
44impl Default for MailSettings {
45    fn default() -> Self {
46        Self {
47            driver: "log".into(),
48            from_address: "hello@localhost.test".into(),
49            from_name: Some("Capy".into()),
50            timeout_seconds: 15,
51            max_message_bytes: 10 * 1024 * 1024,
52            queue: "mail".into(),
53            smtp: SmtpSettings::default(),
54        }
55    }
56}
57/// SMTP settings. TLS is mandatory in production; no opportunistic downgrade.
58#[derive(Clone, Debug, Deserialize, Serialize)]
59#[serde(default, deny_unknown_fields)]
60pub struct SmtpSettings {
61    /// Hostname validated without network access.
62    pub host: String,
63    /// Server port.
64    pub port: u16,
65    /// `starttls`, `tls` (implicit TLS), or development-only `none`.
66    pub encryption: String,
67    /// Optional username; must be paired with password.
68    pub username: MailSecret,
69    /// Optional password; never include it in diagnostics.
70    pub password: MailSecret,
71}
72impl Default for SmtpSettings {
73    fn default() -> Self {
74        Self {
75            host: "localhost".into(),
76            port: 587,
77            encryption: "starttls".into(),
78            username: MailSecret::default(),
79            password: MailSecret::default(),
80        }
81    }
82}
83impl MailSettings {
84    /// Validate the configuration shape offline. Address parsing is done by capy-mail.
85    pub fn validate(&self) -> Result<()> {
86        if !matches!(self.driver.as_str(), "smtp" | "log")
87            || !(1..=300).contains(&self.timeout_seconds)
88            || !(1..=25 * 1024 * 1024).contains(&self.max_message_bytes)
89            || self.queue.is_empty()
90            || self.queue.len() > 128
91            || !self
92                .queue
93                .bytes()
94                .all(|c| c.is_ascii_alphanumeric() || b"_-.".contains(&c))
95        {
96            return Err(AppError::Configuration("Invalid mail settings: driver smtp/log, timeout_seconds 1..=300, max_message_bytes 1..=26214400, and a valid queue name are required.".into()));
97        }
98        if self.smtp.host.is_empty()
99            || self.smtp.host.len() > 253
100            || !self
101                .smtp
102                .host
103                .bytes()
104                .all(|c| c.is_ascii_alphanumeric() || b".-:".contains(&c))
105            || self.smtp.port == 0
106            || !matches!(self.smtp.encryption.as_str(), "starttls" | "tls" | "none")
107            || self.smtp.username.expose().is_empty() != self.smtp.password.expose().is_empty()
108        {
109            return Err(AppError::Configuration("Invalid SMTP settings: use a host, nonzero port, starttls/tls/none encryption and paired credentials.".into()));
110        }
111        if self.smtp.encryption == "none" && !self.smtp.password.expose().is_empty() {
112            return Err(AppError::Configuration(
113                "SMTP authentication requires TLS, including in development.".into(),
114            ));
115        }
116        Ok(())
117    }
118}