Skip to main content

rusted_mail/api/
account.rs

1//! Credentials, server settings, provider discovery, and account builders.
2
3use super::{
4    Deserialize, Duration, Error, Serialize, discovered_server, duration_ms, fmt, invalid,
5    require_text, validate_server,
6};
7
8/// Authentication material for a mail account.
9///
10/// Debug formatting always redacts the secret value.
11#[derive(Clone, Serialize)]
12#[serde(tag = "type", rename_all = "camelCase")]
13pub enum Credentials {
14    /// Username/password authentication.
15    Password {
16        /// Password or application-specific password.
17        secret: String,
18    },
19    /// OAuth bearer-token authentication.
20    OAuth {
21        /// Current OAuth access token.
22        #[serde(rename = "accessToken")]
23        access_token: String,
24    },
25}
26
27impl Credentials {
28    /// Creates password credentials.
29    #[must_use]
30    pub fn password(secret: impl Into<String>) -> Self {
31        Self::Password {
32            secret: secret.into(),
33        }
34    }
35
36    /// Creates OAuth bearer-token credentials.
37    #[must_use]
38    pub fn oauth(access_token: impl Into<String>) -> Self {
39        Self::OAuth {
40            access_token: access_token.into(),
41        }
42    }
43
44    pub(crate) fn validate(&self) -> Result<(), Error> {
45        match self {
46            Self::Password { secret } => require_text("password", secret),
47            Self::OAuth { access_token } => require_text("OAuth access token", access_token),
48        }
49    }
50
51    pub(crate) fn password_secret(&self) -> Result<&str, Error> {
52        match self {
53            Self::Password { secret } => Ok(secret),
54            Self::OAuth { .. } => Err(Error::UnsupportedAuth(
55                "POP3 currently supports USER/PASS password authentication".to_string(),
56            )),
57        }
58    }
59}
60
61impl fmt::Debug for Credentials {
62    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
63        match self {
64            Self::Password { .. } => formatter.write_str("Password { secret: [REDACTED] }"),
65            Self::OAuth { .. } => formatter.write_str("OAuth { access_token: [REDACTED] }"),
66        }
67    }
68}
69
70/// TLS behavior for an IMAP or SMTP server.
71#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
72#[serde(rename_all = "camelCase")]
73pub enum TlsMode {
74    /// Establish TLS immediately after connecting.
75    Tls,
76    /// Connect in plaintext and upgrade with STARTTLS.
77    StartTls,
78}
79
80/// Connection settings for an IMAP or SMTP server.
81#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
82#[serde(rename_all = "camelCase")]
83pub struct ServerConfig {
84    pub(super) host: String,
85    pub(super) port: u16,
86    pub(super) tls: TlsMode,
87    pub(super) timeout_ms: u64,
88}
89
90impl ServerConfig {
91    /// Creates an implicit-TLS server configuration.
92    #[must_use]
93    pub fn tls(host: impl Into<String>, port: u16) -> Self {
94        Self::new(host, port, TlsMode::Tls)
95    }
96
97    /// Creates a STARTTLS server configuration.
98    #[must_use]
99    pub fn start_tls(host: impl Into<String>, port: u16) -> Self {
100        Self::new(host, port, TlsMode::StartTls)
101    }
102
103    /// Creates a server configuration with an explicit TLS mode.
104    #[must_use]
105    pub fn new(host: impl Into<String>, port: u16, tls: TlsMode) -> Self {
106        Self {
107            host: host.into(),
108            port,
109            tls,
110            timeout_ms: 30_000,
111        }
112    }
113
114    /// Overrides the server-specific connection timeout.
115    ///
116    /// # Errors
117    ///
118    /// Returns [`Error::InvalidRequest`](crate::Error::InvalidRequest) when the
119    /// duration is zero or cannot be represented in milliseconds.
120    pub fn timeout(mut self, timeout: Duration) -> Result<Self, Error> {
121        self.timeout_ms = duration_ms(timeout)?;
122        Ok(self)
123    }
124
125    /// Returns the configured hostname.
126    #[must_use]
127    pub fn host(&self) -> &str {
128        &self.host
129    }
130
131    /// Returns the configured port.
132    #[must_use]
133    pub fn port(&self) -> u16 {
134        self.port
135    }
136
137    /// Returns the configured TLS behavior.
138    #[must_use]
139    pub fn tls_mode(&self) -> TlsMode {
140        self.tls
141    }
142
143    /// Returns the server-specific timeout.
144    #[must_use]
145    pub fn connection_timeout(&self) -> Duration {
146        Duration::from_millis(self.timeout_ms)
147    }
148}
149
150/// Source that produced an automatically discovered provider configuration.
151#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
152#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
153#[non_exhaustive]
154pub enum ProviderDiscoverySource {
155    /// A provider definition bundled with the crate.
156    BuiltInPreset,
157    /// The provider's Thunderbird autoconfiguration endpoint.
158    ThunderbirdAutoconfig,
159    /// Mozilla's ISP database.
160    ThunderbirdIspdb,
161    /// DNS SRV records.
162    DnsSrv,
163    /// Probing conventional public mail hostnames.
164    HostProbe,
165}
166
167/// IMAP and SMTP settings discovered for an email address or domain.
168#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
169#[serde(rename_all = "camelCase")]
170pub struct ProviderDiscovery {
171    /// Human-readable provider identifier.
172    pub provider: String,
173    /// Domains associated with the provider.
174    pub domains: Vec<String>,
175    /// Discovered IMAP endpoint.
176    pub imap: ServerConfig,
177    /// Discovered SMTP endpoint.
178    pub smtp: ServerConfig,
179    /// Provider-specific authentication guidance.
180    pub auth_notes: String,
181    /// Mechanism that produced this result.
182    pub source: ProviderDiscoverySource,
183}
184
185impl From<crate::models::ProviderDiscovery> for ProviderDiscovery {
186    fn from(value: crate::models::ProviderDiscovery) -> Self {
187        Self {
188            provider: value.provider,
189            domains: value.domains,
190            imap: discovered_server(value.imap),
191            smtp: discovered_server(value.smtp),
192            auth_notes: value.auth_notes,
193            source: match value.source {
194                crate::models::ProviderDiscoverySource::BuiltInPreset => {
195                    ProviderDiscoverySource::BuiltInPreset
196                }
197                crate::models::ProviderDiscoverySource::ThunderbirdAutoconfig => {
198                    ProviderDiscoverySource::ThunderbirdAutoconfig
199                }
200                crate::models::ProviderDiscoverySource::ThunderbirdIspdb => {
201                    ProviderDiscoverySource::ThunderbirdIspdb
202                }
203                crate::models::ProviderDiscoverySource::DnsSrv => ProviderDiscoverySource::DnsSrv,
204                crate::models::ProviderDiscoverySource::HostProbe => {
205                    ProviderDiscoverySource::HostProbe
206                }
207            },
208        }
209    }
210}
211
212/// Typed IMAP/SMTP account configuration.
213#[derive(Clone, Serialize)]
214#[serde(rename_all = "camelCase")]
215pub struct AccountConfig {
216    email: String,
217    username: String,
218    credential: Credentials,
219    imap: ServerConfig,
220    #[serde(skip_serializing_if = "Option::is_none")]
221    smtp: Option<ServerConfig>,
222}
223
224impl AccountConfig {
225    /// Starts an account builder. The username initially matches the email.
226    pub fn builder(email: impl Into<String>) -> AccountConfigBuilder {
227        let email = email.into();
228        AccountConfigBuilder {
229            username: email.clone(),
230            email,
231            credentials: None,
232            imap: None,
233            smtp: None,
234        }
235    }
236
237    /// Returns the account email address.
238    #[must_use]
239    pub fn email(&self) -> &str {
240        &self.email
241    }
242
243    /// Returns the authentication username.
244    #[must_use]
245    pub fn username(&self) -> &str {
246        &self.username
247    }
248
249    /// Returns the IMAP server settings.
250    #[must_use]
251    pub fn imap(&self) -> &ServerConfig {
252        &self.imap
253    }
254
255    /// Returns the SMTP server settings, if sending is configured.
256    #[must_use]
257    pub fn smtp(&self) -> Option<&ServerConfig> {
258        self.smtp.as_ref()
259    }
260}
261
262impl fmt::Debug for AccountConfig {
263    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
264        formatter
265            .debug_struct("AccountConfig")
266            .field("email", &self.email)
267            .field("username", &self.username)
268            .field("credential", &self.credential)
269            .field("imap", &self.imap)
270            .field("smtp", &self.smtp)
271            .finish()
272    }
273}
274
275/// Builder for [`AccountConfig`].
276#[derive(Debug, Clone)]
277#[must_use]
278pub struct AccountConfigBuilder {
279    email: String,
280    username: String,
281    credentials: Option<Credentials>,
282    imap: Option<ServerConfig>,
283    smtp: Option<ServerConfig>,
284}
285
286impl AccountConfigBuilder {
287    /// Uses a login name different from the account email address.
288    pub fn username(mut self, username: impl Into<String>) -> Self {
289        self.username = username.into();
290        self
291    }
292
293    /// Sets the account credentials.
294    pub fn credentials(mut self, credentials: Credentials) -> Self {
295        self.credentials = Some(credentials);
296        self
297    }
298
299    /// Sets the required IMAP server.
300    pub fn imap(mut self, server: ServerConfig) -> Self {
301        self.imap = Some(server);
302        self
303    }
304
305    /// Sets the optional SMTP server used for outgoing mail.
306    pub fn smtp(mut self, server: ServerConfig) -> Self {
307        self.smtp = Some(server);
308        self
309    }
310
311    /// Validates and creates the account configuration.
312    ///
313    /// # Errors
314    ///
315    /// Returns [`Error::InvalidRequest`](crate::Error::InvalidRequest) when a
316    /// required value is missing or a server or credential is invalid.
317    pub fn build(self) -> Result<AccountConfig, Error> {
318        require_text("email", &self.email)?;
319        require_text("username", &self.username)?;
320        let credential = self
321            .credentials
322            .ok_or_else(|| invalid("credentials are required"))?;
323        credential.validate()?;
324        let imap = self
325            .imap
326            .ok_or_else(|| invalid("IMAP server is required"))?;
327        validate_server(&imap)?;
328        if let Some(smtp) = &self.smtp {
329            validate_server(smtp)?;
330        }
331        Ok(AccountConfig {
332            email: self.email,
333            username: self.username,
334            credential,
335            imap,
336            smtp: self.smtp,
337        })
338    }
339}
340
341/// Configuration for opening a JMAP session.
342#[derive(Clone, Serialize)]
343#[serde(rename_all = "camelCase")]
344pub struct JmapAccountConfig {
345    url: String,
346    credential: Credentials,
347    #[serde(skip_serializing_if = "Option::is_none")]
348    username: Option<String>,
349    timeout_ms: u64,
350    accept_invalid_certs: bool,
351    trusted_hosts: Vec<String>,
352    #[serde(skip_serializing_if = "Option::is_none")]
353    default_account_id: Option<String>,
354}
355
356impl JmapAccountConfig {
357    /// Starts a JMAP account builder for a session-discovery URL.
358    pub fn builder(url: impl Into<String>) -> JmapAccountConfigBuilder {
359        JmapAccountConfigBuilder {
360            url: url.into(),
361            credentials: None,
362            username: None,
363            timeout: Duration::from_secs(30),
364            trusted_hosts: Vec::new(),
365            default_account_id: None,
366        }
367    }
368}
369
370impl fmt::Debug for JmapAccountConfig {
371    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
372        formatter
373            .debug_struct("JmapAccountConfig")
374            .field("url", &self.url)
375            .field("credential", &self.credential)
376            .field("username", &self.username)
377            .field("timeout_ms", &self.timeout_ms)
378            .field("accept_invalid_certs", &self.accept_invalid_certs)
379            .field("trusted_hosts", &self.trusted_hosts)
380            .field("default_account_id", &self.default_account_id)
381            .finish()
382    }
383}
384
385/// Builder for [`JmapAccountConfig`].
386#[derive(Debug, Clone)]
387#[must_use]
388pub struct JmapAccountConfigBuilder {
389    url: String,
390    credentials: Option<Credentials>,
391    username: Option<String>,
392    timeout: Duration,
393    trusted_hosts: Vec<String>,
394    default_account_id: Option<String>,
395}
396
397impl JmapAccountConfigBuilder {
398    /// Sets credentials for the JMAP account.
399    pub fn credentials(mut self, credentials: Credentials) -> Self {
400        self.credentials = Some(credentials);
401        self
402    }
403
404    /// Sets the username required by basic authentication.
405    pub fn username(mut self, username: impl Into<String>) -> Self {
406        self.username = Some(username.into());
407        self
408    }
409
410    /// Sets the JMAP request timeout.
411    pub fn timeout(mut self, timeout: Duration) -> Self {
412        self.timeout = timeout;
413        self
414    }
415
416    /// Allows redirects to an additional trusted host.
417    pub fn trusted_host(mut self, host: impl Into<String>) -> Self {
418        self.trusted_hosts.push(host.into());
419        self
420    }
421
422    /// Overrides the server's default JMAP account identifier.
423    pub fn default_account_id(mut self, id: impl Into<String>) -> Self {
424        self.default_account_id = Some(id.into());
425        self
426    }
427
428    /// Validates and creates the JMAP account configuration.
429    ///
430    /// # Errors
431    ///
432    /// Returns [`Error::InvalidRequest`](crate::Error::InvalidRequest) when the
433    /// URL, credentials, username, or timeout is invalid.
434    pub fn build(self) -> Result<JmapAccountConfig, Error> {
435        require_text("url", &self.url)?;
436        let credential = self
437            .credentials
438            .ok_or_else(|| invalid("credentials are required"))?;
439        credential.validate()?;
440        if matches!(credential, Credentials::Password { .. }) && self.username.is_none() {
441            return Err(invalid(
442                "username is required for JMAP password authentication",
443            ));
444        }
445        Ok(JmapAccountConfig {
446            url: self.url,
447            credential,
448            username: self.username,
449            timeout_ms: duration_ms(self.timeout)?,
450            accept_invalid_certs: false,
451            trusted_hosts: self.trusted_hosts,
452            default_account_id: self.default_account_id,
453        })
454    }
455}