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), `capture` (local development inbox), or `smtp`.
30    pub driver: String,
31    /// Private local inbox directory for the development capture driver (default `.capy/mail`).
32    pub capture_directory: std::path::PathBuf,
33    /// Parsed by the mail subsystem before startup/delivery.
34    pub from_address: String,
35    /// Optional display name.
36    pub from_name: Option<String>,
37    /// Total transport deadline, including connection establishment (1..=300 seconds).
38    pub timeout_seconds: u64,
39    /// Maximum unencoded message content bytes (1..=26214400); default 10 MiB.
40    pub max_message_bytes: usize,
41    /// Logical queue for ordinary, explicitly queueable mail.
42    pub queue: String,
43    /// SMTP connection and authentication.
44    pub smtp: SmtpSettings,
45}
46impl Default for MailSettings {
47    fn default() -> Self {
48        Self {
49            driver: "log".into(),
50            capture_directory: ".capy/mail".into(),
51            from_address: "hello@localhost.test".into(),
52            from_name: Some("Capy".into()),
53            timeout_seconds: 15,
54            max_message_bytes: 10 * 1024 * 1024,
55            queue: "mail".into(),
56            smtp: SmtpSettings::default(),
57        }
58    }
59}
60/// SMTP settings. TLS is mandatory in production; no opportunistic downgrade.
61#[derive(Clone, Debug, Deserialize, Serialize)]
62#[serde(default, deny_unknown_fields)]
63pub struct SmtpSettings {
64    /// Hostname validated without network access.
65    pub host: String,
66    /// Server port.
67    pub port: u16,
68    /// `starttls`, `tls` (implicit TLS), or development-only `none`.
69    pub encryption: String,
70    /// Optional username; must be paired with password.
71    pub username: MailSecret,
72    /// Optional password; never include it in diagnostics.
73    pub password: MailSecret,
74}
75impl Default for SmtpSettings {
76    fn default() -> Self {
77        Self {
78            host: "localhost".into(),
79            port: 587,
80            encryption: "starttls".into(),
81            username: MailSecret::default(),
82            password: MailSecret::default(),
83        }
84    }
85}
86impl MailSettings {
87    /// Validate the configuration shape offline. Address parsing is done by capy-mail.
88    pub fn validate(&self) -> Result<()> {
89        if !matches!(self.driver.as_str(), "smtp" | "log" | "capture")
90            || self.capture_directory.as_os_str().is_empty()
91            || !(1..=300).contains(&self.timeout_seconds)
92            || !(1..=25 * 1024 * 1024).contains(&self.max_message_bytes)
93            || self.queue.is_empty()
94            || self.queue.len() > 128
95            || !self
96                .queue
97                .bytes()
98                .all(|c| c.is_ascii_alphanumeric() || b"_-.".contains(&c))
99        {
100            return Err(AppError::Configuration("Invalid mail settings: a nonempty capture_directory, driver smtp/log/capture, timeout_seconds 1..=300, max_message_bytes 1..=26214400, and a valid queue name are required.".into()));
101        }
102        if self.smtp.host.is_empty()
103            || self.smtp.host.len() > 253
104            || !self
105                .smtp
106                .host
107                .bytes()
108                .all(|c| c.is_ascii_alphanumeric() || b".-:".contains(&c))
109            || self.smtp.port == 0
110            || !matches!(self.smtp.encryption.as_str(), "starttls" | "tls" | "none")
111            || self.smtp.username.expose().is_empty() != self.smtp.password.expose().is_empty()
112        {
113            return Err(AppError::Configuration("Invalid SMTP settings: use a host, nonzero port, starttls/tls/none encryption and paired credentials.".into()));
114        }
115        if self.smtp.encryption == "none" && !self.smtp.password.expose().is_empty() {
116            return Err(AppError::Configuration(
117                "SMTP authentication requires TLS, including in development.".into(),
118            ));
119        }
120        Ok(())
121    }
122}