ic-bn-lib 0.11.0

Internet Computer Boundary Nodes shared modules
Documentation
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
use std::{net::SocketAddr, path::PathBuf, time::Duration};

use anyhow::anyhow;
use clap::Args;
use humantime::parse_duration;
use url::Url;

use crate::{
    parse_size,
    smtp::{ic::upload::IcSmtpUploadConfig, inbound::SessionConfig},
};

/// SMTP Server CLI
#[derive(Args, Clone, Debug, Eq, PartialEq)]
pub struct SmtpServerCli {
    /// Where to listen for SMTP connections.
    /// If specified - the SMTP feature is enabled.
    #[clap(env, long, requires = "smtp_server_hostname")]
    pub smtp_server_listen: Option<SocketAddr>,

    /// SMTP server hostname to use in greeting messages etc.
    /// Required if `smtp_server_listen` is specified.
    #[clap(env, long, requires = "smtp_server_listen")]
    pub smtp_server_hostname: Option<String>,

    /// Base domain to execute IC HTTP queries.
    /// Used when resolving SMTP canisters mapping.
    #[clap(env, long, default_value = "icp0.io")]
    pub smtp_server_ic_base_domain: String,

    /// How long to wait before sending greeting banner.
    /// This helps identify spammy clients that don't follow the protocol -
    /// if they send us anything before the banner - they get disconnected.
    #[clap(env, long, default_value = "2s", value_parser = parse_duration)]
    pub smtp_server_greeting_delay: Duration,

    /// Maximum number of recipient per message
    #[clap(env, long, default_value = "10")]
    pub smtp_server_max_recipients: usize,

    /// Maximum number of messages per single SMTP session
    #[clap(env, long, default_value = "5")]
    pub smtp_server_max_messages_per_session: usize,

    /// Maximum number of errors per single SMTP session
    #[clap(env, long, default_value = "5")]
    pub smtp_server_max_errors_per_session: usize,

    /// Maximum message size: the header block and the body together.
    /// `smtp_server_max_session_data` must be at least this value.
    #[clap(env, long, default_value = "1950KB", value_parser = parse_size)]
    pub smtp_server_max_message_size: u64,

    /// How much data can be ingested during a single SMTP session
    #[clap(env, long, default_value = "50MB", value_parser = parse_size)]
    pub smtp_server_max_session_data: u64,

    /// Maximum time that the session is allowed to be open
    #[clap(env, long, default_value = "2m", value_parser = parse_duration)]
    pub smtp_server_max_session_duration: Duration,

    /// Timeout for SMTP read calls (how long to keep idle session open)
    #[clap(env, long, default_value = "30s", value_parser = parse_duration)]
    pub smtp_server_timeout: Duration,

    /// For how long to cache Canister SMTP mappings
    #[clap(env, long, default_value = "10m", value_parser = parse_duration)]
    pub smtp_server_canister_cache_ttl: Duration,

    /// Maximum number of Canister SMTP mappings to keep in cache
    #[clap(env, long, default_value = "100k", value_parser = parse_size)]
    pub smtp_server_canister_cache_capacity: u64,

    /// The target subnet's `max_ingress_bytes_per_message`.
    /// 2MB is the safe default.
    #[clap(env, long, default_value = "2MB", value_parser = parse_size)]
    pub smtp_server_ic_max_ingress_size: u64,

    /// Body bytes per chunk for the IC chunked upload protocol.
    /// May be lowered by the measured Candid overhead of the first chunk,
    /// which carries the headers.
    #[clap(env, long, default_value = "1MB", value_parser = parse_size)]
    pub smtp_server_ic_upload_chunk_size: u64,

    /// How many payload bytes may be in flight to one destination canister.
    /// Upload concurrency is derived from this.
    #[clap(env, long, default_value = "2MB", value_parser = parse_size)]
    pub smtp_server_ic_max_inflight_bytes: u64,

    /// Ceiling on chunk uploads in flight across all sessions and destinations.
    /// Must be lower than the IC Agent's own concurrency limit.
    #[clap(env, long, default_value = "16")]
    pub smtp_server_ic_upload_global_concurrency: usize,

    /// How many times to retry a single chunk that failed transiently.
    #[clap(env, long, default_value = "2")]
    pub smtp_server_ic_upload_chunk_retries: usize,

    /// Timeout for delivering one message to all of its destinations,
    /// including every chunk, the commit and any retries.
    #[clap(env, long, default_value = "90s", value_parser = parse_duration)]
    pub smtp_server_ic_delivery_timeout: Duration,

    /// For how long to cache canister SMTP capabilities
    #[clap(env, long, default_value = "10m", value_parser = parse_duration)]
    pub smtp_server_ic_capabilities_cache_ttl: Duration,

    /// Path to the IC identity certificate file.
    /// If specified - the SMTP server will use this identity for the IC requests,
    /// anonymous identity will be used otherwise.
    #[clap(env, long)]
    pub smtp_server_ic_identity: Option<PathBuf>,

    /// Whether to enforce usage of STARTTLS.
    /// Be advised that it's effectively against standards/RFCs to do that.
    #[clap(env, long)]
    pub smtp_server_tls_required: bool,

    /// Whether to verify client's EHLO hostname.
    /// Checks that it's an FQDN & that an A/AAAA record exists.
    #[clap(env, long)]
    pub smtp_server_verify_ehlo_hostname: bool,

    /// Whether to verify reverse IP of SMTP clients.
    /// The IP needs to have a PTR record present.
    #[clap(env, long)]
    pub smtp_server_verify_reverse_ip: bool,

    /// Whether to apply stricter rules to the reverse IP of SMTP clients.
    /// The PTR record should resolve back to the client's IP.
    /// This also maps permanent validation errors to the permanent SMTP failures (5xx).
    #[clap(env, long)]
    pub smtp_server_verify_reverse_ip_strict: bool,

    /// Whether to verify the sender's domain (check it's an FQDN and look up MX records)
    #[clap(env, long)]
    pub smtp_server_verify_sender_domain: bool,

    /// Whether to verify the SPF records
    #[clap(env, long)]
    pub smtp_server_verify_spf: bool,

    /// Whether to verify the DKIM signatures
    #[clap(env, long)]
    pub smtp_server_verify_dkim: bool,

    /// Whether to require all DKIM signatures in the message to be valid.
    /// If disabled - at least one valid signature is enough to pass the DKIM
    /// validation.
    #[clap(env, long)]
    pub smtp_server_verify_dkim_strict: bool,

    /// Setting this enables logging of SMTP sessions/messages/errors to Vector using native protocol.
    /// The rest of the options are used from LOG_VECTOR_* parameters.
    #[clap(env, long)]
    pub smtp_server_vector_url: Option<Url>,

    /// SMTP Vector username
    #[clap(env, long)]
    pub smtp_server_vector_user: Option<String>,

    /// SMTP Vector password
    #[clap(env, long)]
    pub smtp_server_vector_pass: Option<String>,
}

impl TryFrom<&SmtpServerCli> for SessionConfig {
    type Error = anyhow::Error;

    fn try_from(v: &SmtpServerCli) -> Result<Self, Self::Error> {
        let Some(hostname) = &v.smtp_server_hostname else {
            return Err(anyhow!("`smtp_server_hostname` is required"));
        };

        // A misconfiguration has to fail at boot rather than at the last byte of
        // a transfer that was already accepted.
        if v.smtp_server_max_message_size > v.smtp_server_max_session_data {
            return Err(anyhow!(
                "`smtp_server_max_message_size` ({}) must not exceed \
                 `smtp_server_max_session_data` ({}): a single message of the \
                 advertised maximum size would abort the session mid-transfer",
                v.smtp_server_max_message_size,
                v.smtp_server_max_session_data
            ));
        }

        let mut cfg = Self::new(hostname, v.smtp_server_max_message_size as usize);
        cfg.greeting_delay = Some(v.smtp_server_greeting_delay);

        cfg.max_errors = v.smtp_server_max_errors_per_session;
        cfg.max_messages_per_session = v.smtp_server_max_messages_per_session;
        cfg.max_recipients = v.smtp_server_max_recipients;
        cfg.max_session_data = v.smtp_server_max_session_data as usize;
        cfg.max_session_duration = v.smtp_server_max_session_duration;

        cfg.timeout = v.smtp_server_timeout;

        cfg.verify_ehlo_hostname = v.smtp_server_verify_ehlo_hostname;
        cfg.verify_reverse_ip = v.smtp_server_verify_reverse_ip;
        cfg.verify_reverse_ip_strict = v.smtp_server_verify_reverse_ip_strict;
        cfg.verify_sender_domain = v.smtp_server_verify_sender_domain;
        cfg.verify_spf = v.smtp_server_verify_spf;
        cfg.verify_dkim = v.smtp_server_verify_dkim;
        cfg.verify_dkim_strict = v.smtp_server_verify_dkim_strict;

        Ok(cfg)
    }
}

impl TryFrom<&SmtpServerCli> for IcSmtpUploadConfig {
    type Error = anyhow::Error;

    fn try_from(v: &SmtpServerCli) -> Result<Self, Self::Error> {
        let max_ingress_size = v.smtp_server_ic_max_ingress_size as usize;
        let chunk_size = v.smtp_server_ic_upload_chunk_size as usize;

        if v.smtp_server_ic_upload_global_concurrency == 0 {
            return Err(anyhow!(
                "`smtp_server_ic_upload_global_concurrency` must be at least 1"
            ));
        }

        // How much of a chunk is actually payload is worked out per message from
        // the measured Candid overhead, but zero isn't good
        if chunk_size == 0 {
            return Err(anyhow!(
                "`smtp_server_ic_upload_chunk_size` must be at least 1"
            ));
        }

        Ok(Self {
            max_ingress_size,
            chunk_size,
            max_inflight_bytes: v.smtp_server_ic_max_inflight_bytes as usize,
            global_concurrency: v.smtp_server_ic_upload_global_concurrency,
            chunk_retries: v.smtp_server_ic_upload_chunk_retries,
            delivery_timeout: v.smtp_server_ic_delivery_timeout,
            capabilities_cache_ttl: v.smtp_server_ic_capabilities_cache_ttl,
        })
    }
}

#[cfg(test)]
mod test {
    use clap::{CommandFactory, Parser};

    use super::*;

    #[derive(Parser)]
    struct Cli {
        #[command(flatten)]
        smtp: SmtpServerCli,
    }

    fn parse(args: &[&str]) -> SmtpServerCli {
        let mut v = vec!["test"];
        v.extend_from_slice(args);
        Cli::try_parse_from(v).unwrap().smtp
    }

    fn try_parse(args: &[&str]) -> Result<SmtpServerCli, clap::Error> {
        let mut v = vec!["test"];
        v.extend_from_slice(args);
        Cli::try_parse_from(v).map(|x| x.smtp)
    }

    #[test]
    fn test_cli_definition_is_valid() {
        // Catches e.g. a `requires` pointing at a non-existent argument id
        Cli::command().debug_assert();
    }

    #[test]
    fn test_defaults() {
        let c = parse(&[]);

        assert_eq!(c.smtp_server_listen, None);
        assert_eq!(c.smtp_server_hostname, None);
        assert_eq!(c.smtp_server_ic_base_domain, "icp0.io");
        assert_eq!(c.smtp_server_greeting_delay, Duration::from_secs(2));
        assert_eq!(c.smtp_server_max_recipients, 10);
        assert_eq!(c.smtp_server_max_messages_per_session, 5);
        assert_eq!(c.smtp_server_max_errors_per_session, 5);
        // Sizes are parsed with binary multipliers
        assert_eq!(c.smtp_server_max_message_size, 1950 * 1024);
        assert_eq!(c.smtp_server_max_session_data, 50 * 1024 * 1024);
        assert_eq!(c.smtp_server_max_session_duration, Duration::from_secs(120));
        assert_eq!(c.smtp_server_timeout, Duration::from_secs(30));
        assert_eq!(c.smtp_server_canister_cache_ttl, Duration::from_secs(600));
        assert_eq!(c.smtp_server_canister_cache_capacity, 100 * 1024);

        assert!(!c.smtp_server_tls_required);
        assert!(!c.smtp_server_verify_ehlo_hostname);
        assert!(!c.smtp_server_verify_reverse_ip);
        assert!(!c.smtp_server_verify_reverse_ip_strict);
        assert!(!c.smtp_server_verify_sender_domain);
        assert!(!c.smtp_server_verify_spf);
        assert!(!c.smtp_server_verify_dkim);
        assert!(!c.smtp_server_verify_dkim_strict);

        assert_eq!(c.smtp_server_vector_url, None);
        assert_eq!(c.smtp_server_vector_user, None);
        assert_eq!(c.smtp_server_vector_pass, None);

        // Parsing the same (empty) args twice yields an equal struct
        assert_eq!(c, parse(&[]));
    }

    #[test]
    fn test_listen_requires_hostname() {
        // Both of these are mutually required
        assert!(try_parse(&["--smtp-server-listen", "127.0.0.1:2525"]).is_err());
        assert!(try_parse(&["--smtp-server-hostname", "mx.foo.bar"]).is_err());

        let c = parse(&[
            "--smtp-server-listen",
            "127.0.0.1:2525",
            "--smtp-server-hostname",
            "mx.foo.bar",
        ]);
        assert_eq!(
            c.smtp_server_listen,
            Some("127.0.0.1:2525".parse().unwrap())
        );
        assert_eq!(c.smtp_server_hostname.as_deref(), Some("mx.foo.bar"));
    }

    #[test]
    fn test_explicit_values() {
        let c = parse(&[
            "--smtp-server-listen",
            "[::1]:1025",
            "--smtp-server-hostname",
            "mx.example.com",
            "--smtp-server-ic-base-domain",
            "ic0.app",
            "--smtp-server-greeting-delay",
            "500ms",
            "--smtp-server-max-recipients",
            "1",
            "--smtp-server-max-messages-per-session",
            "0",
            "--smtp-server-max-errors-per-session",
            "100",
            "--smtp-server-max-message-size",
            "1KB",
            "--smtp-server-max-session-data",
            "3MB",
            "--smtp-server-max-session-duration",
            "1h30m",
            "--smtp-server-timeout",
            "1s",
            "--smtp-server-canister-cache-ttl",
            "0s",
            "--smtp-server-canister-cache-capacity",
            "4096",
            "--smtp-server-tls-required",
            "--smtp-server-verify-ehlo-hostname",
            "--smtp-server-verify-reverse-ip",
            "--smtp-server-verify-reverse-ip-strict",
            "--smtp-server-verify-sender-domain",
            "--smtp-server-verify-spf",
            "--smtp-server-verify-dkim",
            "--smtp-server-verify-dkim-strict",
            "--smtp-server-vector-url",
            "http://127.0.0.1:9999/vector",
            "--smtp-server-vector-user",
            "user",
            "--smtp-server-vector-pass",
            "pass",
        ]);

        assert_eq!(c.smtp_server_listen, Some("[::1]:1025".parse().unwrap()));
        assert_eq!(c.smtp_server_hostname.as_deref(), Some("mx.example.com"));
        assert_eq!(c.smtp_server_ic_base_domain, "ic0.app");
        assert_eq!(c.smtp_server_greeting_delay, Duration::from_millis(500));
        assert_eq!(c.smtp_server_max_recipients, 1);
        assert_eq!(c.smtp_server_max_messages_per_session, 0);
        assert_eq!(c.smtp_server_max_errors_per_session, 100);
        assert_eq!(c.smtp_server_max_message_size, 1024);
        assert_eq!(c.smtp_server_max_session_data, 3 * 1024 * 1024);
        assert_eq!(
            c.smtp_server_max_session_duration,
            Duration::from_secs(5400)
        );
        assert_eq!(c.smtp_server_timeout, Duration::from_secs(1));
        assert_eq!(c.smtp_server_canister_cache_ttl, Duration::ZERO);
        assert_eq!(c.smtp_server_canister_cache_capacity, 4096);

        assert!(c.smtp_server_tls_required);
        assert!(c.smtp_server_verify_ehlo_hostname);
        assert!(c.smtp_server_verify_reverse_ip);
        assert!(c.smtp_server_verify_reverse_ip_strict);
        assert!(c.smtp_server_verify_sender_domain);
        assert!(c.smtp_server_verify_spf);
        assert!(c.smtp_server_verify_dkim);
        assert!(c.smtp_server_verify_dkim_strict);

        assert_eq!(
            c.smtp_server_vector_url,
            Some(Url::parse("http://127.0.0.1:9999/vector").unwrap())
        );
        assert_eq!(c.smtp_server_vector_user.as_deref(), Some("user"));
        assert_eq!(c.smtp_server_vector_pass.as_deref(), Some("pass"));

        assert_ne!(c, parse(&[]));
    }

    #[test]
    fn test_invalid_values() {
        // Not a socket address (missing port)
        assert!(
            try_parse(&[
                "--smtp-server-listen",
                "127.0.0.1",
                "--smtp-server-hostname",
                "mx",
            ])
            .is_err()
        );
        // Not a duration
        assert!(try_parse(&["--smtp-server-timeout", "soon"]).is_err());
        assert!(try_parse(&["--smtp-server-timeout", "30"]).is_err());
        // Not a size
        assert!(try_parse(&["--smtp-server-max-message-size", "big"]).is_err());
        // Not a number
        assert!(try_parse(&["--smtp-server-max-recipients", "-1"]).is_err());
        // Not a URL
        assert!(try_parse(&["--smtp-server-vector-url", "not a url"]).is_err());
        // Flags take no value
        assert!(try_parse(&["--smtp-server-verify-spf", "true"]).is_err());
        // Unknown argument
        assert!(try_parse(&["--smtp-server-nonexistent"]).is_err());
    }

    #[test]
    fn test_session_config_requires_hostname() {
        let cli = parse(&[]);
        let Err(err) = SessionConfig::try_from(&cli) else {
            panic!("SessionConfig must not be built without a hostname");
        };
        assert_eq!(err.to_string(), "`smtp_server_hostname` is required");
    }

    #[test]
    fn test_session_config_mapping() {
        let cli = parse(&[
            "--smtp-server-listen",
            "127.0.0.1:2525",
            "--smtp-server-hostname",
            "mx.example.com",
            "--smtp-server-greeting-delay",
            "3s",
            "--smtp-server-max-recipients",
            "7",
            "--smtp-server-max-messages-per-session",
            "8",
            "--smtp-server-max-errors-per-session",
            "9",
            "--smtp-server-max-message-size",
            "512KB",
            // Deliberately different from the message size so that mixing the
            // two options up is caught, but still above it - a session cap
            // below the per-message cap is rejected at startup.
            "--smtp-server-max-session-data",
            "1MB",
            "--smtp-server-max-session-duration",
            "42s",
            "--smtp-server-timeout",
            "11s",
            "--smtp-server-verify-ehlo-hostname",
            "--smtp-server-verify-spf",
            "--smtp-server-verify-dkim-strict",
        ]);

        let cfg = SessionConfig::try_from(&cli).unwrap();

        assert_eq!(cfg.greeting_delay, Some(Duration::from_secs(3)));
        assert_eq!(cfg.max_recipients, 7);
        assert_eq!(cfg.max_messages_per_session, 8);
        assert_eq!(cfg.max_errors, 9);
        assert_eq!(cfg.max_session_data, 1024 * 1024);
        assert_eq!(cfg.max_session_duration, Duration::from_secs(42));
        assert_eq!(cfg.timeout, Duration::from_secs(11));

        assert!(cfg.verify_ehlo_hostname);
        assert!(cfg.verify_spf);
        assert!(cfg.verify_dkim_strict);
        // Not requested - must stay off
        assert!(!cfg.verify_reverse_ip);
        assert!(!cfg.verify_reverse_ip_strict);
        assert!(!cfg.verify_sender_domain);
        assert!(!cfg.verify_dkim);

        // Not wired through the CLI - keeps the `SessionConfig::new()` default
        assert_eq!(cfg.max_received_headers, 50);
        // TLS mode is set up elsewhere (needs a cert resolver)
        assert!(!cfg.tls_mode.enabled());
    }

    #[test]
    fn test_upload_defaults() {
        let c = parse(&[]);

        assert_eq!(c.smtp_server_ic_max_ingress_size, 2 * 1024 * 1024);
        assert_eq!(c.smtp_server_ic_upload_chunk_size, 1024 * 1024);
        assert_eq!(c.smtp_server_ic_max_inflight_bytes, 2 * 1024 * 1024);
        assert_eq!(c.smtp_server_ic_upload_global_concurrency, 16);
        assert_eq!(c.smtp_server_ic_upload_chunk_retries, 2);
        assert_eq!(c.smtp_server_ic_delivery_timeout, Duration::from_secs(90));
        assert_eq!(
            c.smtp_server_ic_capabilities_cache_ttl,
            Duration::from_secs(600)
        );

        // The shipped defaults must be usable as-is
        let cfg = IcSmtpUploadConfig::try_from(&c).unwrap();
        assert_eq!(cfg, IcSmtpUploadConfig::default());
    }

    #[test]
    fn test_upload_config_mapping() {
        let cli = parse(&[
            "--smtp-server-ic-max-ingress-size",
            "3MB",
            "--smtp-server-ic-upload-chunk-size",
            "512KB",
            "--smtp-server-ic-max-inflight-bytes",
            "4MB",
            "--smtp-server-ic-upload-global-concurrency",
            "8",
            "--smtp-server-ic-upload-chunk-retries",
            "5",
            "--smtp-server-ic-delivery-timeout",
            "45s",
            "--smtp-server-ic-capabilities-cache-ttl",
            "1m",
        ]);

        let cfg = IcSmtpUploadConfig::try_from(&cli).unwrap();
        assert_eq!(cfg.max_ingress_size, 3 * 1024 * 1024);
        assert_eq!(cfg.chunk_size, 512 * 1024);
        assert_eq!(cfg.max_inflight_bytes, 4 * 1024 * 1024);
        assert_eq!(cfg.global_concurrency, 8);
        assert_eq!(cfg.chunk_retries, 5);
        assert_eq!(cfg.delivery_timeout, Duration::from_secs(45));
        assert_eq!(cfg.capabilities_cache_ttl, Duration::from_secs(60));

        // 4 MiB in flight over 512 KiB chunks
        assert_eq!(cfg.concurrency(cfg.chunk_size), 8);
    }

    /// A session cap below the per-message cap means every maximum-size message
    /// aborts mid-transfer, so it must not start.
    #[test]
    fn test_session_data_below_message_size_is_rejected() {
        let cli = parse(&[
            "--smtp-server-listen",
            "127.0.0.1:2525",
            "--smtp-server-hostname",
            "mx.example.com",
            "--smtp-server-max-message-size",
            "10MB",
            "--smtp-server-max-session-data",
            "1MB",
        ]);

        // `SessionConfig` has no `Debug`, so `unwrap_err` is unavailable here
        let Err(e) = SessionConfig::try_from(&cli) else {
            panic!("expected a session-data validation error");
        };
        let err = e.to_string();
        assert!(err.contains("max_session_data"), "{err}");

        // Equal is fine - exactly one maximum-size message fits
        let cli = parse(&[
            "--smtp-server-listen",
            "127.0.0.1:2525",
            "--smtp-server-hostname",
            "mx.example.com",
            "--smtp-server-max-message-size",
            "1MB",
            "--smtp-server-max-session-data",
            "1MB",
        ]);
        assert!(SessionConfig::try_from(&cli).is_ok());
    }

    /// How much of a chunk is payload is decided per message from the measured
    /// Candid overhead, so the only thing left to reject here is a zero, which
    /// `plan_chunks` would otherwise round up to a 1-byte chunk.
    #[test]
    fn test_zero_chunk_size_is_rejected() {
        let cli = parse(&["--smtp-server-ic-upload-chunk-size", "0"]);
        let err = IcSmtpUploadConfig::try_from(&cli).unwrap_err().to_string();
        assert!(err.contains("upload_chunk_size"), "{err}");

        // A chunk larger than the ingress budget is fine - the per-message
        // measurement clamps it down.
        let cli = parse(&[
            "--smtp-server-ic-upload-chunk-size",
            "8MB",
            "--smtp-server-ic-max-ingress-size",
            "2MB",
        ]);
        assert!(IcSmtpUploadConfig::try_from(&cli).is_ok());
    }

    #[test]
    fn test_zero_global_concurrency_is_rejected() {
        let cli = parse(&["--smtp-server-ic-upload-global-concurrency", "0"]);
        assert!(IcSmtpUploadConfig::try_from(&cli).is_err());
    }

    #[test]
    fn test_session_config_mapping_defaults() {
        let cli = parse(&[
            "--smtp-server-listen",
            "127.0.0.1:2525",
            "--smtp-server-hostname",
            "mx.example.com",
        ]);
        let cfg = SessionConfig::try_from(&cli).unwrap();

        // The CLI always sets an explicit greeting delay, even the default one
        assert_eq!(cfg.greeting_delay, Some(Duration::from_secs(2)));
        assert_eq!(cfg.max_recipients, 10);
        assert_eq!(cfg.max_session_data, 50 * 1024 * 1024);
        assert_eq!(cfg.max_session_duration, Duration::from_secs(120));
        assert_eq!(cfg.timeout, Duration::from_secs(30));
    }
    /// `SessionConfig`'s `max_message_size` field is private and `SessionConfig`
    /// has no `Debug`, so the only way to observe that the CLI actually wires
    /// `--smtp-server-max-message-size` into it is the `SIZE` capability that a
    /// session advertises in its EHLO response.
    #[tokio::test]
    async fn test_session_config_max_message_size_is_advertised() {
        use prometheus::Registry;
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        use tokio::net::TcpStream;
        use tokio_util::sync::CancellationToken;

        use crate::{
            network::{ListenerOpts, listener::listen_tcp},
            smtp::{Metrics, server::Server},
        };

        let cli = parse(&[
            "--smtp-server-listen",
            "127.0.0.1:2525",
            "--smtp-server-hostname",
            "mx.example.com",
            "--smtp-server-max-message-size",
            "12KB",
            // Deliberately different from the message size so that mixing the
            // two options up is caught
            "--smtp-server-max-session-data",
            "7MB",
            "--smtp-server-greeting-delay",
            "0s",
        ]);
        assert_eq!(cli.smtp_server_max_message_size, 12 * 1024);
        assert_eq!(cli.smtp_server_max_session_data, 7 * 1024 * 1024);

        let cfg = SessionConfig::try_from(&cli).unwrap();

        let listener = listen_tcp("127.0.0.1:0".parse().unwrap(), ListenerOpts::default()).unwrap();
        let addr = listener.local_addr().unwrap();
        let server =
            Server::new_with_listener(listener, cfg, Metrics::new(&Registry::new())).unwrap();

        let token = CancellationToken::new();
        let handle = tokio::spawn({
            let token = token.child_token();
            async move { server.serve(token).await }
        });

        let mut stream = TcpStream::connect(addr).await.unwrap();
        let mut buf = [0; 4096];

        let n = stream.read(&mut buf).await.unwrap();
        let greeting = String::from_utf8_lossy(&buf[..n]).to_string();
        assert!(
            greeting.starts_with("220 mx.example.com"),
            "hostname must come from the CLI, got: {greeting:?}"
        );

        stream
            .write_all(b"EHLO client.example.com\r\n")
            .await
            .unwrap();

        // The EHLO reply is multi-line; the last line starts with "250 "
        let mut reply = String::new();
        loop {
            let n = stream.read(&mut buf).await.unwrap();
            if n == 0 {
                break;
            }
            reply.push_str(&String::from_utf8_lossy(&buf[..n]));
            if reply.lines().any(|x| x.starts_with("250 ")) {
                break;
            }
        }

        assert!(
            reply.contains("SIZE 12288"),
            "EHLO must advertise the CLI's max message size (12288), got:\n{reply}"
        );
        assert!(
            !reply.contains("7340032"),
            "max_session_data must not be advertised as SIZE, got:\n{reply}"
        );

        token.cancel();
        handle.await.unwrap().unwrap();
    }
}