himalaya 2.2.1

CLI to manage emails
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
//! # Account check
//!
//! The `account check` command, opening one connection per configured
//! backend so a credential or an endpoint fails here rather than in the
//! middle of a real command.

#[cfg(feature = "mbox")]
use std::fs::File;
use std::{fmt, path::PathBuf};

use anyhow::{Result, bail};
use clap::Parser;
#[cfg(feature = "imap")]
use io_sasl::mechanism::SaslMechanism;
use pimalaya_cli::printer::Printer;
use pimalaya_config::{secret::SecretResolver, toml::TomlConfig};
use schemars::JsonSchema;
use serde::Serialize;

#[cfg(feature = "imap")]
use crate::config::ImapConfig;
use crate::{
    backend::Backend,
    config::{AccountConfig, Config},
};

/// Validate the account configuration.
///
/// Every backend `--backend` allows is opened, which exercises the same
/// handshake and authentication paths a real command takes. The report
/// names each backend and whether it answered.
#[derive(Debug, Parser)]
pub struct AccountCheckCommand;

impl AccountCheckCommand {
    /// Checks every allowed backend of the account and prints the report.
    pub fn execute(
        self,
        printer: &mut impl Printer,
        config_paths: &[PathBuf],
        account_name: Option<&str>,
        backend: Backend,
    ) -> Result<()> {
        let mut config = match Config::from_paths_or_default(config_paths)? {
            Some(config) => config,
            None => bail!(
                "No configuration found. Run bare `himalaya` to launch the wizard \
                 and generate one."
            ),
        };

        let (name, account_config) = config
            .take_account(account_name)?
            .ok_or_else(|| anyhow::anyhow!("Cannot find account"))?;

        let mut report = CheckReport {
            account: name,
            backends: Vec::new(),
        };

        // NOTE: one resolver for the whole account, so a credential
        // command several blocks name is spawned once.
        #[cfg_attr(
            not(any(
                feature = "imap",
                feature = "jmap",
                feature = "gmail",
                feature = "msgraph",
                feature = "smtp",
                feature = "sieve"
            )),
            allow(unused_mut, unused_variables)
        )]
        let mut resolver = SecretResolver::new();

        #[cfg(feature = "imap")]
        if backend.allows_imap()
            && let Some(imap_config) = &account_config.imap
        {
            report.backends.push(BackendCheck::from(
                "imap",
                connect_imap(imap_config, &mut resolver),
            ));
        }

        #[cfg(feature = "jmap")]
        if backend.allows_jmap()
            && let Some(jmap_config) = &account_config.jmap
        {
            report.backends.push(BackendCheck::from(
                "jmap",
                connect_jmap(jmap_config, &mut resolver),
            ));
        }

        #[cfg(feature = "gmail")]
        if backend.allows_gmail()
            && let Some(gmail_config) = &account_config.gmail
        {
            report.backends.push(BackendCheck::from(
                "gmail",
                connect_gmail(gmail_config, &mut resolver),
            ));
        }

        #[cfg(feature = "msgraph")]
        if backend.allows_msgraph()
            && let Some(msgraph_config) = &account_config.msgraph
        {
            report.backends.push(BackendCheck::from(
                "msgraph",
                connect_msgraph(msgraph_config, &mut resolver),
            ));
        }

        #[cfg(feature = "maildir")]
        if backend.allows_maildir()
            && let Some(maildir_config) = &account_config.maildir
        {
            report.backends.push(BackendCheck::from(
                "maildir",
                connect_maildir(maildir_config),
            ));
        }

        #[cfg(feature = "m2dir")]
        if backend.allows_m2dir()
            && let Some(m2dir_config) = &account_config.m2dir
        {
            report
                .backends
                .push(BackendCheck::from("m2dir", connect_m2dir(m2dir_config)));
        }

        #[cfg(feature = "mbox")]
        if backend.allows_mbox()
            && let Some(mbox_config) = &account_config.mbox
        {
            report
                .backends
                .push(BackendCheck::from("mbox", connect_mbox(mbox_config)));
        }

        #[cfg(feature = "smtp")]
        if backend.allows_smtp()
            && let Some(smtp_config) = &account_config.smtp
        {
            report.backends.push(BackendCheck::from(
                "smtp",
                connect_smtp(smtp_config, &mut resolver),
            ));
        }

        #[cfg(feature = "sieve")]
        if backend.allows_sieve()
            && let Some(sieve_config) = &account_config.sieve
        {
            report.backends.push(BackendCheck::from(
                "sieve",
                connect_sieve(sieve_config, &mut resolver),
            ));
        }

        if report.backends.is_empty() {
            return Err(account_config.no_backend_error(
                &report.account,
                backend,
                Backend::COMPILED,
            ));
        }

        printer.out(report)
    }
}

/// Tests every configured backend, failing on the first error.
///
/// The wizard runs it over a freshly built account, so a bad credential
/// or endpoint stops it rather than yielding a configuration that cannot
/// connect.
pub fn test_account(account_config: &AccountConfig) -> Result<()> {
    // NOTE: one resolver for the whole account, as in `account check`.
    #[cfg_attr(
        not(any(
            feature = "imap",
            feature = "jmap",
            feature = "gmail",
            feature = "msgraph",
            feature = "smtp",
            feature = "sieve"
        )),
        allow(unused_mut, unused_variables)
    )]
    let mut resolver = SecretResolver::new();

    #[cfg(feature = "imap")]
    if let Some(imap_config) = &account_config.imap {
        connect_imap(imap_config, &mut resolver)?;
    }

    #[cfg(feature = "jmap")]
    if let Some(jmap_config) = &account_config.jmap {
        connect_jmap(jmap_config, &mut resolver)?;
    }

    #[cfg(feature = "gmail")]
    if let Some(gmail_config) = &account_config.gmail {
        connect_gmail(gmail_config, &mut resolver)?;
    }

    #[cfg(feature = "msgraph")]
    if let Some(msgraph_config) = &account_config.msgraph {
        connect_msgraph(msgraph_config, &mut resolver)?;
    }

    #[cfg(feature = "maildir")]
    if let Some(maildir_config) = &account_config.maildir {
        connect_maildir(maildir_config)?;
    }

    #[cfg(feature = "m2dir")]
    if let Some(m2dir_config) = &account_config.m2dir {
        connect_m2dir(m2dir_config)?;
    }

    #[cfg(feature = "mbox")]
    if let Some(mbox_config) = &account_config.mbox {
        connect_mbox(mbox_config)?;
    }

    #[cfg(feature = "smtp")]
    if let Some(smtp_config) = &account_config.smtp {
        connect_smtp(smtp_config, &mut resolver)?;
    }

    #[cfg(feature = "sieve")]
    if let Some(sieve_config) = &account_config.sieve {
        connect_sieve(sieve_config, &mut resolver)?;
    }

    Ok(())
}

/// Opens an authenticated IMAP session and drops it.
#[cfg(feature = "imap")]
pub(crate) fn connect_imap(imap_config: &ImapConfig, resolver: &mut SecretResolver) -> Result<()> {
    use io_imap::{
        client::{ImapClientStd, ImapClientStdConnectOptions, default_port},
        session::ImapSessionOpenOptions,
    };
    use io_sasl::mechanism::Sasl;

    use crate::{
        config::ProxyConfig,
        imap::{client::parse_imap_server, id::resolve_auto_id_params},
    };

    let auto_id = resolve_auto_id_params(&imap_config.id)?;
    let server = parse_imap_server(&imap_config.server)?;
    let sasl: Option<Sasl> = imap_config
        .sasl
        .clone()
        .map(|cfg| {
            let host = server.host_str().unwrap_or_default();
            let port = server.port().unwrap_or(default_port(server.scheme()));
            cfg.try_into_sasl(host, port, resolver)
        })
        .transpose()?;
    let opts = ImapClientStdConnectOptions {
        tls: imap_config.tls.clone().into_tls(imap_config.alpn.clone()),
        proxy: ProxyConfig::resolve(imap_config.proxy.clone(), resolver)?,
        sasl,
        session: ImapSessionOpenOptions {
            starttls: imap_config.starttls,
            auto_id,
            sasl_ir: imap_config.sasl_ir,
        },
    };
    let _ = ImapClientStd::connect(&server, opts)?;

    Ok(())
}

/// Reads a server's CAPABILITY over an unauthenticated connection and
/// returns the mechanisms it advertises, most preferred first.
///
/// The wizard offers what comes back rather than the whole list, and the
/// connection is dropped without ever authenticating.
#[cfg(feature = "imap")]
pub(crate) fn probe_imap_mechanisms(server: &str, starttls: bool) -> Result<Vec<SaslMechanism>> {
    use io_imap::{
        client::{ImapClientStd, ImapClientStdConnectOptions, default_alpn},
        rfc3501::capability::available_auth_mechanisms,
        session::ImapSessionOpenOptions,
    };

    use crate::{config::TlsConfig, imap::client::parse_imap_server};

    let server = parse_imap_server(server)?;
    let opts = ImapClientStdConnectOptions {
        tls: TlsConfig::default().into_tls(default_alpn()),
        session: ImapSessionOpenOptions {
            starttls,
            ..Default::default()
        },
        ..Default::default()
    };
    let (_client, capabilities) = ImapClientStd::connect(&server, opts)?;

    Ok(available_auth_mechanisms(&capabilities))
}

/// Opens a JMAP client and fetches the session object.
#[cfg(feature = "jmap")]
fn connect_jmap(
    jmap_config: &crate::config::JmapConfig,
    resolver: &mut SecretResolver,
) -> Result<()> {
    use io_jmap::client::JmapClientStd;

    use crate::jmap::client::{connect_options, jmap_http_auth, parse_server_url};

    let http_auth = jmap_http_auth(jmap_config.auth.clone(), resolver)?;
    let opts = connect_options(jmap_config, resolver)?;
    let url = parse_server_url(&jmap_config.server)?;
    let mut client = JmapClientStd::connect(&url, http_auth, opts)?;
    client.session_get(&url)?;

    Ok(())
}

/// Opens a Gmail client and fetches the account profile.
#[cfg(feature = "gmail")]
fn connect_gmail(
    gmail_config: &crate::config::GmailConfig,
    resolver: &mut SecretResolver,
) -> Result<()> {
    use io_gmail::v1::client::{GmailClientStd, GmailClientStdConnectOptions};
    use secrecy::ExposeSecret;

    use crate::{config::ProxyConfig, gmail::client::gmail_token};

    let token = gmail_token(gmail_config.auth.clone(), resolver)?;
    let options = GmailClientStdConnectOptions {
        tls: gmail_config.tls.clone().into_tls(gmail_config.alpn.clone()),
        proxy: ProxyConfig::resolve(gmail_config.proxy.clone(), resolver)?,
        user_id: gmail_config.user_id.clone(),
    };
    let mut client = GmailClientStd::connect(token.expose_secret(), options)?;
    client.profile_get()?;

    Ok(())
}

/// Opens a Microsoft Graph client and fetches the signed-in user.
#[cfg(feature = "msgraph")]
fn connect_msgraph(
    msgraph_config: &crate::config::MsgraphConfig,
    resolver: &mut SecretResolver,
) -> Result<()> {
    use io_msgraph::v1::client::{MsgraphClientStd, MsgraphClientStdConnectOptions};
    use secrecy::ExposeSecret;

    use crate::{config::ProxyConfig, msgraph::client::msgraph_token};

    let token = msgraph_token(msgraph_config.auth.clone(), resolver)?;
    let options = MsgraphClientStdConnectOptions {
        tls: msgraph_config
            .tls
            .clone()
            .into_tls(msgraph_config.alpn.clone()),
        proxy: ProxyConfig::resolve(msgraph_config.proxy.clone(), resolver)?,
        user_id: msgraph_config.user_id.clone(),
    };
    let mut client = MsgraphClientStd::connect(token.expose_secret(), options)?;
    client.me()?;

    Ok(())
}

/// Checks that the Maildir root is a directory.
#[cfg(feature = "maildir")]
fn connect_maildir(maildir_config: &crate::config::MaildirConfig) -> Result<()> {
    if !maildir_config.root.is_dir() {
        bail!(
            "Maildir root `{}` does not exist or is not a directory",
            maildir_config.root.display()
        );
    }

    Ok(())
}

/// Checks that the mbox root is a directory and the spool, when set, a
/// readable file.
#[cfg(feature = "mbox")]
fn connect_mbox(mbox_config: &crate::config::MboxConfig) -> Result<()> {
    if !mbox_config.root.is_dir() {
        bail!(
            "Mbox root `{}` does not exist or is not a directory",
            mbox_config.root.display()
        );
    }

    if let Some(inbox) = &mbox_config.inbox
        && let Err(err) = File::open(inbox)
    {
        bail!("Cannot open mbox spool `{}`: {err}", inbox.display());
    }

    Ok(())
}

/// Checks that the m2dir root is a directory.
#[cfg(feature = "m2dir")]
fn connect_m2dir(m2dir_config: &crate::config::M2dirConfig) -> Result<()> {
    if !m2dir_config.root.is_dir() {
        bail!(
            "m2dir root `{}` does not exist or is not a directory",
            m2dir_config.root.display()
        );
    }

    Ok(())
}

/// Opens an authenticated SMTP session and drops it.
#[cfg(feature = "smtp")]
pub(crate) fn connect_smtp(
    smtp_config: &crate::config::SmtpConfig,
    resolver: &mut SecretResolver,
) -> Result<()> {
    use std::net::Ipv4Addr;

    use io_sasl::mechanism::Sasl;
    use io_smtp::{
        client::{SmtpClientStd, SmtpClientStdConnectOptions},
        rfc5321::SmtpEhloDomain,
        session::SmtpSessionOpenOptions,
    };

    use crate::config::ProxyConfig;

    let domain: SmtpEhloDomain<'static> = Ipv4Addr::new(127, 0, 0, 1).into();
    let server = crate::smtp::client::parse_smtp_server(&smtp_config.server)?;
    let sasl: Option<Sasl> = smtp_config
        .sasl
        .clone()
        .map(|cfg| {
            let host = server.host_str().unwrap_or_default();
            let port = server
                .port()
                .unwrap_or(SmtpClientStd::default_port(server.scheme()));
            cfg.try_into_sasl(host, port, resolver)
        })
        .transpose()?;
    let opts = SmtpClientStdConnectOptions {
        tls: smtp_config.tls.clone().into_tls(smtp_config.alpn.clone()),
        proxy: ProxyConfig::resolve(smtp_config.proxy.clone(), resolver)?,
        sasl,
        session: SmtpSessionOpenOptions {
            starttls: smtp_config.starttls,
        },
    };
    let _client = SmtpClientStd::connect(&server, domain, opts)?;

    Ok(())
}

/// Opens an authenticated ManageSieve session and drops it.
#[cfg(feature = "sieve")]
pub(crate) fn connect_sieve(
    sieve_config: &crate::config::SieveConfig,
    resolver: &mut SecretResolver,
) -> Result<()> {
    let _client = crate::sieve::client::SieveClient::new(sieve_config.clone(), resolver)?;
    Ok(())
}

/// The `account check` output, one outcome per backend.
#[derive(Clone, Debug, Serialize, JsonSchema)]
pub struct CheckReport {
    /// The account that was checked.
    pub account: String,
    /// One entry per backend the account declares and `--backend` allows.
    pub backends: Vec<BackendCheck>,
}

/// Outcome of checking one backend's connection.
#[derive(Clone, Debug, Serialize, JsonSchema)]
pub struct BackendCheck {
    /// The backend that was checked.
    pub backend: &'static str,
    /// Whether it answered.
    pub ok: bool,
    /// Why it did not, when it did not.
    pub error: Option<String>,
}

impl BackendCheck {
    /// Folds a connection attempt into its outcome.
    fn from(backend: &'static str, result: Result<()>) -> Self {
        match result {
            Ok(()) => Self {
                backend,
                ok: true,
                error: None,
            },
            Err(err) => Self {
                backend,
                ok: false,
                error: Some(format!("{err:#}")),
            },
        }
    }
}

impl fmt::Display for CheckReport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "Account: {}", self.account)?;
        for check in &self.backends {
            match &check.error {
                None => writeln!(f, "  {}: OK", check.backend)?,
                Some(err) => writeln!(f, "  {}: FAIL ({err})", check.backend)?,
            }
        }
        Ok(())
    }
}