spf-milter 0.6.0

Milter for SPF verification
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
719
720
721
722
723
724
725
726
727
728
729
730
// SPF Milter – milter for SPF verification
// Copyright © 2020–2023 David Bürgin <dbuergin@gluet.ch>
//
// This program is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation, either version 3 of the License, or (at your option) any later
// version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
// details.
//
// You should have received a copy of the GNU General Public License along with
// this program. If not, see <https://www.gnu.org/licenses/>.

pub mod cli_opts;
pub mod model;
pub mod read;

use crate::{
    config::{
        cli_opts::CliOptions,
        model::{
            DefinitiveHeloResults, EnhancedStatusCode, ExpExplainString, ExplainStringMod, Header,
            HeaderType, LogDestination, LogLevel, ReasonExplainString, RejectResults, ReplyCode,
            SkipSenders, Socket, SyslogFacility, TrustedNetworks,
        },
        read::ReadConfigError,
    },
    resolver::{DomainResolver, Resolver},
};
use log::{error, info, warn};
use once_cell::sync::Lazy;
use std::{
    error::Error,
    fmt::{self, Display, Formatter},
    mem,
    sync::{Arc, RwLock},
    time::Duration,
};
use viaspf::{lookup::Lookup, record::ExplainString};

/// A session configuration, containing immutable configuration and resolver.
pub struct SessionConfig {
    pub config: Config,
    pub resolver: Resolver,
}

impl SessionConfig {
    pub fn new(config: Config) -> Self {
        let resolver = Resolver::Live(DomainResolver::new(config.timeout()));
        Self { config, resolver }
    }

    pub fn with_mock_resolver(config: Config, resolver: Box<dyn Lookup>) -> Self {
        let resolver = Resolver::Mock(Arc::new(resolver));
        Self { config, resolver }
    }
}

/// Reloads the configuration from the configuration file.
pub async fn reload(current_session_config: &RwLock<Arc<SessionConfig>>, opts: &CliOptions) {
    let config_file = opts.config_file();

    let config = match read::read_config(opts).await {
        Ok(config) => config,
        Err(e) => {
            error!(
                "failed to reload configuration from {}: {}",
                config_file.display(),
                read::focus_error(&e)
            );
            return;
        }
    };

    // Extract values of parameters that cannot be reloaded, reset the
    // configuration, then log a warning.
    let new_log_destination = config.log_destination();
    let new_log_level = config.log_level();
    let new_socket = config.socket().clone();
    let new_syslog_facility = config.syslog_facility();

    let old_session_config = {
        let mut locked_session_config = current_session_config
            .write()
            .expect("could not get configuration write lock");

        let resolver = match &locked_session_config.resolver {
            Resolver::Live(_) => Resolver::Live(DomainResolver::new(config.timeout())),
            Resolver::Mock(m) => Resolver::Mock(m.clone()),
        };
        let session_config = SessionConfig { config, resolver };

        mem::replace(&mut *locked_session_config, Arc::new(session_config))
    };

    info!("configuration reloaded from {}", config_file.display());

    if new_log_destination != old_session_config.config.log_destination() {
        warn_changed_param("log_destination");
    }
    if new_log_level != old_session_config.config.log_level() {
        warn_changed_param("log_level");
    }
    if new_socket != *old_session_config.config.socket() {
        warn_changed_param("socket");
    }
    if new_syslog_facility != old_session_config.config.syslog_facility() {
        warn_changed_param("syslog_facility");
    }
}

fn warn_changed_param(name: &str) {
    warn!("parameter \"{name}\" changed, restart needed");
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Config {
    authserv_id: Option<String>,
    definitive_helo_results: DefinitiveHeloResults,
    delete_incoming_authentication_results: bool,
    dry_run: bool,
    fail_reply_code: ReplyCode,
    fail_reply_text: ExplainString,
    fail_reply_text_exp: ExpExplainString,
    fail_status_code: EnhancedStatusCode,
    header: Header,
    hostname: Option<String>,
    include_all_results: bool,
    include_mailfrom_local_part: bool,
    log_destination: LogDestination,
    log_level: LogLevel,
    max_lookups: usize,
    max_void_lookups: usize,
    permerror_reply_code: ReplyCode,
    permerror_reply_text: ReasonExplainString,
    permerror_status_code: EnhancedStatusCode,
    reject_helo_results: RejectResults,
    reject_results: RejectResults,
    skip_senders: SkipSenders,
    socket: Socket,
    softfail_reply_code: ReplyCode,
    softfail_reply_text: ExplainString,
    softfail_status_code: EnhancedStatusCode,
    syslog_facility: SyslogFacility,
    temperror_reply_code: ReplyCode,
    temperror_reply_text: ReasonExplainString,
    temperror_status_code: EnhancedStatusCode,
    timeout: Duration,
    trust_authenticated_senders: bool,
    trusted_networks: TrustedNetworks,
    verify_helo: bool,
}

impl Config {
    pub fn builder(socket: Socket) -> ConfigBuilder {
        ConfigBuilder::new(socket)
    }

    pub fn authserv_id(&self) -> Option<&str> {
        self.authserv_id.as_deref()
    }

    pub fn definitive_helo_results(&self) -> &DefinitiveHeloResults {
        &self.definitive_helo_results
    }

    pub fn delete_incoming_authentication_results(&self) -> bool {
        self.delete_incoming_authentication_results
    }

    pub fn dry_run(&self) -> bool {
        self.dry_run
    }

    pub fn fail_reply_code(&self) -> &ReplyCode {
        &self.fail_reply_code
    }

    pub fn fail_reply_text(&self) -> &ExplainString {
        &self.fail_reply_text
    }

    pub fn fail_reply_text_exp(&self) -> &ExpExplainString {
        &self.fail_reply_text_exp
    }

    pub fn fail_status_code(&self) -> &EnhancedStatusCode {
        &self.fail_status_code
    }

    pub fn header(&self) -> &Header {
        &self.header
    }

    pub fn hostname(&self) -> Option<&str> {
        self.hostname.as_deref()
    }

    pub fn include_all_results(&self) -> bool {
        self.include_all_results
    }

    pub fn include_mailfrom_local_part(&self) -> bool {
        self.include_mailfrom_local_part
    }

    pub fn log_destination(&self) -> LogDestination {
        self.log_destination
    }

    pub fn log_level(&self) -> LogLevel {
        self.log_level
    }

    pub fn max_lookups(&self) -> usize {
        self.max_lookups
    }

    pub fn max_void_lookups(&self) -> usize {
        self.max_void_lookups
    }

    pub fn permerror_reply_code(&self) -> &ReplyCode {
        &self.permerror_reply_code
    }

    pub fn permerror_reply_text(&self) -> &ReasonExplainString {
        &self.permerror_reply_text
    }

    pub fn permerror_status_code(&self) -> &EnhancedStatusCode {
        &self.permerror_status_code
    }

    pub fn reject_helo_results(&self) -> &RejectResults {
        &self.reject_helo_results
    }

    pub fn reject_results(&self) -> &RejectResults {
        &self.reject_results
    }

    pub fn skip_senders(&self) -> &SkipSenders {
        &self.skip_senders
    }

    pub fn socket(&self) -> &Socket {
        &self.socket
    }

    pub fn softfail_reply_code(&self) -> &ReplyCode {
        &self.softfail_reply_code
    }

    pub fn softfail_reply_text(&self) -> &ExplainString {
        &self.softfail_reply_text
    }

    pub fn softfail_status_code(&self) -> &EnhancedStatusCode {
        &self.softfail_status_code
    }

    pub fn syslog_facility(&self) -> SyslogFacility {
        self.syslog_facility
    }

    pub fn temperror_reply_code(&self) -> &ReplyCode {
        &self.temperror_reply_code
    }

    pub fn temperror_reply_text(&self) -> &ReasonExplainString {
        &self.temperror_reply_text
    }

    pub fn temperror_status_code(&self) -> &EnhancedStatusCode {
        &self.temperror_status_code
    }

    pub fn timeout(&self) -> Duration {
        self.timeout
    }

    pub fn trust_authenticated_senders(&self) -> bool {
        self.trust_authenticated_senders
    }

    pub fn trusted_networks(&self) -> &TrustedNetworks {
        &self.trusted_networks
    }

    pub fn verify_helo(&self) -> bool {
        self.verify_helo
    }
}

#[derive(Debug)]
pub enum ConfigError {
    ReadConfig(ReadConfigError),
    MissingMandatoryParam(String),
    TypeConversion(String),
    IncompatibleStatusCodes(ReplyCode, EnhancedStatusCode, String),
}

impl Error for ConfigError {}

impl Display for ConfigError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::ReadConfig(e) => write!(f, "failed to read configuration: {e}"),
            Self::MissingMandatoryParam(s) => {
                write!(f, "missing mandatory configuration parameter \"{s}\"")
            }
            Self::TypeConversion(s) => {
                write!(f, "failed to convert value of configuration parameter \"{s}\"")
            }
            Self::IncompatibleStatusCodes(rc, esc, s) => {
                write!(f, "incompatible reply status codes {rc} {esc} for result \"{s}\"")
            }
        }
    }
}

// Note: Status codes in RFC 7208 were updated in RFC 7372.
static DEFAULT_ERROR_REPLY_CODE: Lazy<ReplyCode> = Lazy::new(|| "550".parse().unwrap());
static DEFAULT_TEMPERROR_REPLY_CODE: Lazy<ReplyCode> = Lazy::new(|| "451".parse().unwrap());
static DEFAULT_FAIL_STATUS_CODE: Lazy<EnhancedStatusCode> = Lazy::new(|| "5.7.23".parse().unwrap());
static DEFAULT_PERMERROR_STATUS_CODE: Lazy<EnhancedStatusCode> = Lazy::new(|| "5.7.24".parse().unwrap());
static DEFAULT_TEMPERROR_STATUS_CODE: Lazy<EnhancedStatusCode> = Lazy::new(|| "4.7.24".parse().unwrap());

static DEFAULT_FAIL_REPLY_TEXT: Lazy<ExplainString> =
    Lazy::new(|| "SPF validation failed".parse().unwrap());
static DEFAULT_FAIL_REPLY_TEXT_EXP_PREFIX: Lazy<ExplainString> =
    Lazy::new(|| "SPF validation failed: %{o} explains: ".parse().unwrap());
static DEFAULT_ERROR_REPLY_TEXT_PREFIX: Lazy<ExplainString> =
    Lazy::new(|| "SPF validation error: ".parse().unwrap());

/// A builder for configurations.
///
/// This builder’s methods don’t validate inputs, instead all work is postponed
/// until `build` is called. Instantiation of the builder does not instantiate
/// values eagerly, default values are only created in `build`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ConfigBuilder {
    authserv_id: Option<String>,
    definitive_helo_results: Option<DefinitiveHeloResults>,
    delete_incoming_authentication_results: Option<bool>,
    dry_run: Option<bool>,
    fail_reply_code: Option<ReplyCode>,
    fail_reply_text: Option<ExplainString>,
    fail_reply_text_exp: Option<ExpExplainString>,
    fail_status_code: Option<EnhancedStatusCode>,
    header: Option<Header>,
    hostname: Option<String>,
    include_all_results: Option<bool>,
    include_mailfrom_local_part: Option<bool>,
    log_destination: Option<LogDestination>,
    log_level: Option<LogLevel>,
    max_lookups: Option<usize>,
    max_void_lookups: Option<usize>,
    permerror_reply_code: Option<ReplyCode>,
    permerror_reply_text: Option<ReasonExplainString>,
    permerror_status_code: Option<EnhancedStatusCode>,
    reject_helo_results: Option<RejectResults>,
    reject_results: Option<RejectResults>,
    skip_senders: Option<SkipSenders>,
    socket: Socket,
    softfail_reply_code: Option<ReplyCode>,
    softfail_reply_text: Option<ExplainString>,
    softfail_status_code: Option<EnhancedStatusCode>,
    syslog_facility: Option<SyslogFacility>,
    temperror_reply_code: Option<ReplyCode>,
    temperror_reply_text: Option<ReasonExplainString>,
    temperror_status_code: Option<EnhancedStatusCode>,
    timeout: Option<Duration>,
    trust_authenticated_senders: Option<bool>,
    trusted_networks: Option<TrustedNetworks>,
    verify_helo: Option<bool>,
}

// The builder methods use `Into` with non-`Copy` type arguments, where a
// sensible `From` implementation exists.
impl ConfigBuilder {
    pub fn new(socket: Socket) -> Self {
        Self {
            authserv_id: Default::default(),
            definitive_helo_results: Default::default(),
            delete_incoming_authentication_results: Default::default(),
            dry_run: Default::default(),
            fail_reply_code: Default::default(),
            fail_reply_text: Default::default(),
            fail_reply_text_exp: Default::default(),
            fail_status_code: Default::default(),
            header: Default::default(),
            hostname: Default::default(),
            include_all_results: Default::default(),
            include_mailfrom_local_part: Default::default(),
            log_destination: Default::default(),
            log_level: Default::default(),
            max_lookups: Default::default(),
            max_void_lookups: Default::default(),
            permerror_reply_code: Default::default(),
            permerror_reply_text: Default::default(),
            permerror_status_code: Default::default(),
            reject_helo_results: Default::default(),
            reject_results: Default::default(),
            skip_senders: Default::default(),
            socket,
            softfail_reply_code: Default::default(),
            softfail_reply_text: Default::default(),
            softfail_status_code: Default::default(),
            syslog_facility: Default::default(),
            temperror_reply_code: Default::default(),
            temperror_reply_text: Default::default(),
            temperror_status_code: Default::default(),
            timeout: Default::default(),
            trust_authenticated_senders: Default::default(),
            trusted_networks: Default::default(),
            verify_helo: Default::default(),
        }
    }

    pub fn authserv_id<S: Into<String>>(mut self, value: S) -> Self {
        self.authserv_id = Some(value.into());
        self
    }

    pub fn definitive_helo_results<T: Into<DefinitiveHeloResults>>(mut self, value: T) -> Self {
        self.definitive_helo_results = Some(value.into());
        self
    }

    pub fn delete_incoming_authentication_results(mut self, value: bool) -> Self {
        self.delete_incoming_authentication_results = Some(value);
        self
    }

    pub fn dry_run(mut self, value: bool) -> Self {
        self.dry_run = Some(value);
        self
    }

    pub fn fail_reply_code(mut self, value: ReplyCode) -> Self {
        self.fail_reply_code = Some(value);
        self
    }

    pub fn fail_reply_text<S: Into<ExplainString>>(mut self, value: S) -> Self {
        self.fail_reply_text = Some(value.into());
        self
    }

    pub fn fail_reply_text_exp<S: Into<ExpExplainString>>(mut self, value: S) -> Self {
        self.fail_reply_text_exp = Some(value.into());
        self
    }

    pub fn fail_status_code(mut self, value: EnhancedStatusCode) -> Self {
        self.fail_status_code = Some(value);
        self
    }

    pub fn header<T: Into<Header>>(mut self, value: T) -> Self {
        self.header = Some(value.into());
        self
    }

    pub fn hostname<S: Into<String>>(mut self, value: S) -> Self {
        self.hostname = Some(value.into());
        self
    }

    pub fn include_all_results(mut self, value: bool) -> Self {
        self.include_all_results = Some(value);
        self
    }

    pub fn include_mailfrom_local_part(mut self, value: bool) -> Self {
        self.include_mailfrom_local_part = Some(value);
        self
    }

    pub fn log_destination(mut self, value: LogDestination) -> Self {
        self.log_destination = Some(value);
        self
    }

    pub fn log_level(mut self, value: LogLevel) -> Self {
        self.log_level = Some(value);
        self
    }

    pub fn max_lookups(mut self, value: usize) -> Self {
        self.max_lookups = Some(value);
        self
    }

    pub fn max_void_lookups(mut self, value: usize) -> Self {
        self.max_void_lookups = Some(value);
        self
    }

    pub fn permerror_reply_code(mut self, value: ReplyCode) -> Self {
        self.permerror_reply_code = Some(value);
        self
    }

    pub fn permerror_reply_text<S: Into<ReasonExplainString>>(mut self, value: S) -> Self {
        self.permerror_reply_text = Some(value.into());
        self
    }

    pub fn permerror_status_code(mut self, value: EnhancedStatusCode) -> Self {
        self.permerror_status_code = Some(value);
        self
    }

    pub fn reject_helo_results<T: Into<RejectResults>>(mut self, value: T) -> Self {
        self.reject_helo_results = Some(value.into());
        self
    }

    pub fn reject_results<T: Into<RejectResults>>(mut self, value: T) -> Self {
        self.reject_results = Some(value.into());
        self
    }

    pub fn skip_senders<S: Into<SkipSenders>>(mut self, value: S) -> Self {
        self.skip_senders = Some(value.into());
        self
    }

    pub fn softfail_reply_code(mut self, value: ReplyCode) -> Self {
        self.softfail_reply_code = Some(value);
        self
    }

    pub fn softfail_reply_text(mut self, value: ExplainString) -> Self {
        self.softfail_reply_text = Some(value);
        self
    }

    pub fn softfail_status_code(mut self, value: EnhancedStatusCode) -> Self {
        self.softfail_status_code = Some(value);
        self
    }

    pub fn syslog_facility(mut self, value: SyslogFacility) -> Self {
        self.syslog_facility = Some(value);
        self
    }

    pub fn temperror_reply_code(mut self, value: ReplyCode) -> Self {
        self.temperror_reply_code = Some(value);
        self
    }

    pub fn temperror_reply_text<S: Into<ReasonExplainString>>(mut self, value: S) -> Self {
        self.temperror_reply_text = Some(value.into());
        self
    }

    pub fn temperror_status_code(mut self, value: EnhancedStatusCode) -> Self {
        self.temperror_status_code = Some(value);
        self
    }

    pub fn timeout(mut self, value: Duration) -> Self {
        self.timeout = Some(value);
        self
    }

    pub fn trust_authenticated_senders(mut self, value: bool) -> Self {
        self.trust_authenticated_senders = Some(value);
        self
    }

    pub fn trusted_networks(mut self, value: TrustedNetworks) -> Self {
        self.trusted_networks = Some(value);
        self
    }

    pub fn verify_helo(mut self, value: bool) -> Self {
        self.verify_helo = Some(value);
        self
    }

    pub fn build(self) -> Result<Config, ConfigError> {
        let max_lookups = self.max_lookups.unwrap_or(10);
        let max_void_lookups = self.max_void_lookups.unwrap_or(2);
        let timeout = self.timeout.unwrap_or_else(|| Duration::from_secs(20));
        let trust_authenticated_senders = self.trust_authenticated_senders.unwrap_or(true);
        let verify_helo = self.verify_helo.unwrap_or(true);

        let header = self.header.unwrap_or_default();
        let delete_incoming_authentication_results = self
            .delete_incoming_authentication_results
            .unwrap_or_else(|| {
                header.iter().any(|&h| h == HeaderType::AuthenticationResults)
            });

        let reject_results = self.reject_results.unwrap_or_default();
        let reject_helo_results = self
            .reject_helo_results
            .unwrap_or_else(|| reject_results.clone());

        let (fail_reply_code, fail_status_code) = ensure_compatible(
            self.fail_reply_code.unwrap_or_else(|| DEFAULT_ERROR_REPLY_CODE.clone()),
            self.fail_status_code.unwrap_or_else(|| DEFAULT_FAIL_STATUS_CODE.clone()),
            "fail",
        )?;
        let fail_reply_text = self
            .fail_reply_text
            .unwrap_or_else(|| DEFAULT_FAIL_REPLY_TEXT.clone());
        let fail_reply_text_exp = self
            .fail_reply_text_exp
            .unwrap_or_else(|| ExpExplainString(ExplainStringMod::Decorate {
                prefix: DEFAULT_FAIL_REPLY_TEXT_EXP_PREFIX.clone(),
                suffix: Default::default(),
            }));

        let (softfail_reply_code, softfail_status_code) = ensure_compatible(
            self.softfail_reply_code.unwrap_or_else(|| DEFAULT_ERROR_REPLY_CODE.clone()),
            self.softfail_status_code.unwrap_or_else(|| DEFAULT_FAIL_STATUS_CODE.clone()),
            "softfail",
        )?;
        let softfail_reply_text = self
            .softfail_reply_text
            .unwrap_or_else(|| DEFAULT_FAIL_REPLY_TEXT.clone());

        let (temperror_reply_code, temperror_status_code) = ensure_compatible(
            self.temperror_reply_code.unwrap_or_else(|| DEFAULT_TEMPERROR_REPLY_CODE.clone()),
            self.temperror_status_code.unwrap_or_else(|| DEFAULT_TEMPERROR_STATUS_CODE.clone()),
            "temperror",
        )?;
        let temperror_reply_text = self
            .temperror_reply_text
            .unwrap_or_else(|| ReasonExplainString(ExplainStringMod::Decorate {
                prefix: DEFAULT_ERROR_REPLY_TEXT_PREFIX.clone(),
                suffix: Default::default(),
            }));

        let (permerror_reply_code, permerror_status_code) = ensure_compatible(
            self.permerror_reply_code.unwrap_or_else(|| DEFAULT_ERROR_REPLY_CODE.clone()),
            self.permerror_status_code.unwrap_or_else(|| DEFAULT_PERMERROR_STATUS_CODE.clone()),
            "permerror",
        )?;
        let permerror_reply_text = self
            .permerror_reply_text
            .unwrap_or_else(|| ReasonExplainString(ExplainStringMod::Decorate {
                prefix: DEFAULT_ERROR_REPLY_TEXT_PREFIX.clone(),
                suffix: Default::default(),
            }));

        Ok(Config {
            authserv_id: self.authserv_id,
            definitive_helo_results: self.definitive_helo_results.unwrap_or_default(),
            delete_incoming_authentication_results,
            dry_run: self.dry_run.unwrap_or_default(),
            fail_reply_code,
            fail_reply_text,
            fail_reply_text_exp,
            fail_status_code,
            header,
            hostname: self.hostname,
            include_all_results: self.include_all_results.unwrap_or_default(),
            include_mailfrom_local_part: self.include_mailfrom_local_part.unwrap_or_default(),
            log_destination: self.log_destination.unwrap_or_default(),
            log_level: self.log_level.unwrap_or_default(),
            max_lookups,
            max_void_lookups,
            permerror_reply_code,
            permerror_reply_text,
            permerror_status_code,
            reject_helo_results,
            reject_results,
            skip_senders: self.skip_senders.unwrap_or_default(),
            socket: self.socket,
            softfail_reply_code,
            softfail_reply_text,
            softfail_status_code,
            syslog_facility: self.syslog_facility.unwrap_or_default(),
            temperror_reply_code,
            temperror_reply_text,
            temperror_status_code,
            timeout,
            trust_authenticated_senders,
            trusted_networks: self.trusted_networks.unwrap_or_default(),
            verify_helo,
        })
    }
}

fn ensure_compatible(
    reply_code: ReplyCode,
    status_code: EnhancedStatusCode,
    result_kind: &str,
) -> Result<(ReplyCode, EnhancedStatusCode), ConfigError> {
    if status_code.is_compatible_with(&reply_code) {
        Ok((reply_code, status_code))
    } else {
        Err(ConfigError::IncompatibleStatusCodes(
            reply_code,
            status_code,
            result_kind.into(),
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn delete_incoming_authentication_results_default_ok() {
        let config = Config::builder("unix:unused".parse().unwrap())
            .header(HeaderType::ReceivedSpf)
            .build()
            .unwrap();
        assert!(!config.delete_incoming_authentication_results());

        let config = Config::builder("unix:unused".parse().unwrap())
            .header(HeaderType::AuthenticationResults)
            .build()
            .unwrap();
        assert!(config.delete_incoming_authentication_results());
    }
}