rusmes-core 0.1.2

Mailet processing engine for RusMES — composable mail processing pipeline with matchers, mailets, DKIM/SPF/DMARC, spam filtering, and AI integration
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
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
//! SPF (Sender Policy Framework) verification mailet
//!
//! Implements RFC 7208 - Sender Policy Framework (SPF)

use crate::mailet::{Mailet, MailetAction, MailetConfig};
use anyhow::{anyhow, Result};
use async_trait::async_trait;
use hickory_resolver::TokioResolver;
use ipnetwork::{Ipv4Network, Ipv6Network};
use rusmes_proto::Mail;
use std::net::IpAddr;

/// SPF mechanism types
#[derive(Debug, Clone)]
#[allow(clippy::upper_case_acronyms)]
enum SpfMechanism {
    /// a[:domain][/prefix]
    A {
        domain: Option<String>,
        prefix: Option<u8>,
    },
    /// mx[:domain][/prefix]
    MX {
        domain: Option<String>,
        prefix: Option<u8>,
    },
    /// ip4:network[/prefix]
    IP4 { network: Ipv4Network },
    /// ip6:network[/prefix]
    IP6 { network: Ipv6Network },
    /// include:domain
    Include { domain: String },
    /// all
    All,
    /// exists:domain
    Exists { domain: String },
    /// ptr[:domain]
    Ptr {
        #[allow(dead_code)]
        domain: Option<String>,
    },
}

/// SPF qualifier (result modifier)
#[derive(Debug, Clone, Copy)]
enum SpfQualifier {
    /// + (Pass)
    Pass,
    /// - (Fail)
    Fail,
    /// ~ (SoftFail)
    SoftFail,
    /// ? (Neutral)
    Neutral,
}

/// SPF evaluation result
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SpfResult {
    /// SPF check passed
    Pass,
    /// SPF check failed (hard fail)
    Fail,
    /// SPF check failed (soft fail)
    SoftFail,
    /// SPF is neutral (not pass, not fail)
    Neutral,
    /// Temporary DNS error
    TempError,
    /// Permanent error in SPF record
    PermError,
    /// No SPF record found
    None,
}

impl SpfResult {
    /// Convert to string representation
    pub fn as_str(&self) -> &'static str {
        match self {
            SpfResult::Pass => "pass",
            SpfResult::Fail => "fail",
            SpfResult::SoftFail => "softfail",
            SpfResult::Neutral => "neutral",
            SpfResult::TempError => "temperror",
            SpfResult::PermError => "permerror",
            SpfResult::None => "none",
        }
    }
}

/// SPF policy checking mailet
pub struct SpfCheckMailet {
    name: String,
    reject_on_fail: bool,
    max_dns_lookups: usize,
}

impl SpfCheckMailet {
    /// Create a new SPF check mailet
    pub fn new() -> Self {
        Self {
            name: "SpfCheck".to_string(),
            reject_on_fail: false,
            max_dns_lookups: 10, // RFC 7208 limit
        }
    }

    /// Lookup SPF record from DNS TXT records
    async fn lookup_spf_record(resolver: &TokioResolver, domain: &str) -> Result<Option<String>> {
        match resolver.txt_lookup(domain).await {
            Ok(txt_records) => {
                // Find the SPF record (starts with "v=spf1")
                for record in txt_records.iter() {
                    // Concatenate all strings in the TXT record
                    let txt = record
                        .txt_data()
                        .iter()
                        .map(|data| String::from_utf8_lossy(data))
                        .collect::<Vec<_>>()
                        .join("");

                    if txt.starts_with("v=spf1") {
                        return Ok(Some(txt));
                    }
                }
                Ok(None)
            }
            Err(e) => {
                if e.to_string().contains("no records found") {
                    Ok(None)
                } else {
                    Err(anyhow!("DNS lookup error: {}", e))
                }
            }
        }
    }

    /// Parse qualifier from mechanism string
    fn parse_qualifier(s: &str) -> (SpfQualifier, &str) {
        match s.chars().next() {
            Some('+') => (SpfQualifier::Pass, &s[1..]),
            Some('-') => (SpfQualifier::Fail, &s[1..]),
            Some('~') => (SpfQualifier::SoftFail, &s[1..]),
            Some('?') => (SpfQualifier::Neutral, &s[1..]),
            _ => (SpfQualifier::Pass, s), // Default is Pass
        }
    }

    /// Parse SPF mechanism from string
    fn parse_mechanism(s: &str) -> Result<SpfMechanism> {
        if s == "all" {
            return Ok(SpfMechanism::All);
        }

        if let Some(domain) = s.strip_prefix("include:") {
            return Ok(SpfMechanism::Include {
                domain: domain.to_string(),
            });
        }

        if let Some(network_str) = s.strip_prefix("ip4:") {
            let network = if network_str.contains('/') {
                network_str.parse::<Ipv4Network>()?
            } else {
                Ipv4Network::new(network_str.parse()?, 32)?
            };
            return Ok(SpfMechanism::IP4 { network });
        }

        if let Some(network_str) = s.strip_prefix("ip6:") {
            let network = if network_str.contains('/') {
                network_str.parse::<Ipv6Network>()?
            } else {
                Ipv6Network::new(network_str.parse()?, 128)?
            };
            return Ok(SpfMechanism::IP6 { network });
        }

        if let Some(domain_str) = s.strip_prefix("exists:") {
            return Ok(SpfMechanism::Exists {
                domain: domain_str.to_string(),
            });
        }

        if s.starts_with("a:") || s.starts_with("a/") || s == "a" {
            let (domain, prefix) = Self::parse_domain_and_prefix(&s[1..])?;
            return Ok(SpfMechanism::A { domain, prefix });
        }

        if s.starts_with("mx:") || s.starts_with("mx/") || s == "mx" {
            let (domain, prefix) = Self::parse_domain_and_prefix(&s[2..])?;
            return Ok(SpfMechanism::MX { domain, prefix });
        }

        if s.starts_with("ptr:") || s == "ptr" {
            let domain = if s.len() > 4 {
                Some(s[4..].to_string())
            } else {
                None
            };
            return Ok(SpfMechanism::Ptr { domain });
        }

        Err(anyhow!("Unknown SPF mechanism: {}", s))
    }

    /// Parse domain and prefix from mechanism string
    fn parse_domain_and_prefix(s: &str) -> Result<(Option<String>, Option<u8>)> {
        if s.is_empty() {
            return Ok((None, None));
        }

        if let Some(rest) = s.strip_prefix(':') {
            if let Some((domain, prefix_str)) = rest.split_once('/') {
                let prefix = prefix_str.parse()?;
                Ok((Some(domain.to_string()), Some(prefix)))
            } else {
                Ok((Some(rest.to_string()), None))
            }
        } else if let Some(stripped) = s.strip_prefix('/') {
            let prefix = stripped.parse()?;
            Ok((None, Some(prefix)))
        } else {
            Err(anyhow!("Invalid domain/prefix format: {}", s))
        }
    }

    /// Parse SPF record into list of mechanisms with qualifiers
    fn parse_spf_record(record: &str) -> Result<Vec<(SpfQualifier, SpfMechanism)>> {
        let parts: Vec<&str> = record.split_whitespace().collect();
        let mut mechanisms = Vec::new();

        for part in parts.iter().skip(1) {
            // Skip "v=spf1"
            // Skip modifiers (redirect=, exp=)
            if part.contains('=') && !part.starts_with("ip4:") && !part.starts_with("ip6:") {
                continue;
            }

            let (qualifier, mechanism_str) = Self::parse_qualifier(part);
            match Self::parse_mechanism(mechanism_str) {
                Ok(mechanism) => {
                    mechanisms.push((qualifier, mechanism));
                }
                Err(e) => {
                    tracing::warn!("Failed to parse SPF mechanism '{}': {}", part, e);
                    // Continue parsing other mechanisms
                }
            }
        }

        Ok(mechanisms)
    }

    /// Check if IP matches A record mechanism
    async fn check_a_mechanism(
        resolver: &TokioResolver,
        sender_ip: IpAddr,
        domain: &str,
        prefix: Option<u8>,
        lookup_count: &mut usize,
    ) -> Result<bool> {
        *lookup_count += 1;
        if *lookup_count > 10 {
            return Err(anyhow!("Too many DNS lookups"));
        }

        match sender_ip {
            IpAddr::V4(v4) => {
                let a_records = resolver.ipv4_lookup(domain).await?;
                for record in a_records.iter() {
                    let ip = record.0;
                    let network = if let Some(prefix_len) = prefix {
                        Ipv4Network::new(ip, prefix_len)?
                    } else {
                        Ipv4Network::new(ip, 32)?
                    };
                    if network.contains(v4) {
                        return Ok(true);
                    }
                }
            }
            IpAddr::V6(v6) => {
                let aaaa_records = resolver.ipv6_lookup(domain).await?;
                for record in aaaa_records.iter() {
                    let ip = record.0;
                    let network = if let Some(prefix_len) = prefix {
                        Ipv6Network::new(ip, prefix_len)?
                    } else {
                        Ipv6Network::new(ip, 128)?
                    };
                    if network.contains(v6) {
                        return Ok(true);
                    }
                }
            }
        }

        Ok(false)
    }

    /// Check if IP matches MX record mechanism
    async fn check_mx_mechanism(
        resolver: &TokioResolver,
        sender_ip: IpAddr,
        domain: &str,
        prefix: Option<u8>,
        lookup_count: &mut usize,
    ) -> Result<bool> {
        *lookup_count += 1;
        if *lookup_count > 10 {
            return Err(anyhow!("Too many DNS lookups"));
        }

        let mx_records = resolver.mx_lookup(domain).await?;

        for mx in mx_records.iter() {
            let mx_host = mx.exchange().to_string();
            // Remove trailing dot
            let mx_host = mx_host.trim_end_matches('.');

            // Lookup A/AAAA records for MX host
            if Self::check_a_mechanism(resolver, sender_ip, mx_host, prefix, lookup_count)
                .await
                .unwrap_or(false)
            {
                return Ok(true);
            }
        }

        Ok(false)
    }

    /// Check if domain exists (for exists: mechanism)
    async fn check_exists(
        resolver: &TokioResolver,
        domain: &str,
        lookup_count: &mut usize,
    ) -> Result<bool> {
        *lookup_count += 1;
        if *lookup_count > 10 {
            return Err(anyhow!("Too many DNS lookups"));
        }

        // Check if domain has any A records
        match resolver.ipv4_lookup(domain).await {
            Ok(records) => Ok(records.iter().count() > 0),
            Err(_) => Ok(false),
        }
    }

    /// Evaluate SPF for given sender IP and domain
    #[allow(clippy::too_many_arguments)]
    async fn evaluate_spf_internal(
        resolver: &TokioResolver,
        sender_ip: IpAddr,
        sender_domain: &str,
        lookup_count: &mut usize,
        recursion_depth: usize,
    ) -> Result<SpfResult> {
        // Prevent infinite recursion
        if recursion_depth > 10 {
            return Ok(SpfResult::PermError);
        }

        // Lookup SPF record
        let spf_record = match Self::lookup_spf_record(resolver, sender_domain).await {
            Ok(Some(record)) => record,
            Ok(None) => return Ok(SpfResult::None),
            Err(e) => {
                tracing::warn!("SPF lookup error for {}: {}", sender_domain, e);
                return Ok(SpfResult::TempError);
            }
        };

        tracing::debug!("Found SPF record for {}: {}", sender_domain, spf_record);

        // Parse mechanisms
        let mechanisms = match Self::parse_spf_record(&spf_record) {
            Ok(m) => m,
            Err(e) => {
                tracing::warn!("Failed to parse SPF record: {}", e);
                return Ok(SpfResult::PermError);
            }
        };

        // Evaluate each mechanism
        for (qualifier, mechanism) in mechanisms {
            let matches = match mechanism {
                SpfMechanism::A { domain, prefix } => {
                    let check_domain = domain.as_deref().unwrap_or(sender_domain);
                    Self::check_a_mechanism(resolver, sender_ip, check_domain, prefix, lookup_count)
                        .await
                        .unwrap_or(false)
                }
                SpfMechanism::MX { domain, prefix } => {
                    let check_domain = domain.as_deref().unwrap_or(sender_domain);
                    Self::check_mx_mechanism(
                        resolver,
                        sender_ip,
                        check_domain,
                        prefix,
                        lookup_count,
                    )
                    .await
                    .unwrap_or(false)
                }
                SpfMechanism::IP4 { network } => match sender_ip {
                    IpAddr::V4(v4) => network.contains(v4),
                    IpAddr::V6(_) => false,
                },
                SpfMechanism::IP6 { network } => match sender_ip {
                    IpAddr::V6(v6) => network.contains(v6),
                    IpAddr::V4(_) => false,
                },
                SpfMechanism::Include { domain } => {
                    let result = Box::pin(Self::evaluate_spf_internal(
                        resolver,
                        sender_ip,
                        &domain,
                        lookup_count,
                        recursion_depth + 1,
                    ))
                    .await
                    .unwrap_or(SpfResult::TempError);

                    matches!(result, SpfResult::Pass)
                }
                SpfMechanism::Exists { domain } => {
                    Self::check_exists(resolver, &domain, lookup_count)
                        .await
                        .unwrap_or(false)
                }
                SpfMechanism::Ptr { .. } => {
                    // Ptr mechanism is deprecated and not recommended
                    // We'll skip it for now
                    tracing::warn!("Ptr mechanism is deprecated and not supported");
                    false
                }
                SpfMechanism::All => true,
            };

            if matches {
                return Ok(match qualifier {
                    SpfQualifier::Pass => SpfResult::Pass,
                    SpfQualifier::Fail => SpfResult::Fail,
                    SpfQualifier::SoftFail => SpfResult::SoftFail,
                    SpfQualifier::Neutral => SpfResult::Neutral,
                });
            }
        }

        // No mechanisms matched
        Ok(SpfResult::Neutral)
    }

    /// Evaluate SPF for given sender IP and domain
    async fn evaluate_spf(sender_ip: IpAddr, sender_domain: &str) -> Result<SpfResult> {
        let resolver = TokioResolver::builder_tokio()
            .map_err(|e| anyhow!("Failed to create DNS resolver: {}", e))?
            .build();

        let mut lookup_count = 0;
        Self::evaluate_spf_internal(&resolver, sender_ip, sender_domain, &mut lookup_count, 0).await
    }
}

impl Default for SpfCheckMailet {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl Mailet for SpfCheckMailet {
    async fn init(&mut self, config: MailetConfig) -> Result<()> {
        if let Some(reject_str) = config.get_param("reject_on_fail") {
            self.reject_on_fail = reject_str.parse()?;
        }

        if let Some(max_lookups_str) = config.get_param("max_dns_lookups") {
            self.max_dns_lookups = max_lookups_str.parse()?;
        }

        tracing::info!(
            "Initialized SpfCheckMailet (reject on fail: {}, max DNS lookups: {})",
            self.reject_on_fail,
            self.max_dns_lookups
        );
        Ok(())
    }

    async fn service(&self, mail: &mut Mail) -> Result<MailetAction> {
        tracing::debug!("Checking SPF for mail {}", mail.id());

        // Get sender IP address
        let sender_ip = match mail.remote_addr() {
            Some(ip) => *ip,
            None => {
                tracing::warn!(
                    "No remote address for mail {}, skipping SPF check",
                    mail.id()
                );
                mail.set_attribute("spf.result", SpfResult::None.as_str());
                return Ok(MailetAction::Continue);
            }
        };

        // Get sender domain from envelope sender
        let sender_domain = match mail.sender() {
            Some(addr) => addr.domain().as_str().to_string(),
            None => {
                tracing::debug!(
                    "No sender for mail {} (bounce?), skipping SPF check",
                    mail.id()
                );
                mail.set_attribute("spf.result", SpfResult::None.as_str());
                return Ok(MailetAction::Continue);
            }
        };

        // Evaluate SPF
        let result = Self::evaluate_spf(sender_ip, &sender_domain).await;

        let spf_result = match result {
            Ok(r) => r,
            Err(e) => {
                tracing::error!("SPF evaluation error for mail {}: {}", mail.id(), e);
                SpfResult::TempError
            }
        };

        // Set attributes
        mail.set_attribute("spf.result", spf_result.as_str());
        mail.set_attribute("spf.client_ip", sender_ip.to_string());
        mail.set_attribute("spf.sender_domain", sender_domain.clone());

        // Handle result
        match spf_result {
            SpfResult::Pass => {
                tracing::info!(
                    "SPF check passed for mail {} (domain: {}, ip: {})",
                    mail.id(),
                    sender_domain,
                    sender_ip
                );
            }
            SpfResult::Fail => {
                tracing::warn!(
                    "SPF check failed for mail {} (domain: {}, ip: {})",
                    mail.id(),
                    sender_domain,
                    sender_ip
                );
                if self.reject_on_fail {
                    mail.state = rusmes_proto::MailState::Error;
                    return Ok(MailetAction::Drop);
                }
            }
            SpfResult::SoftFail => {
                tracing::info!(
                    "SPF soft fail for mail {} (domain: {}, ip: {})",
                    mail.id(),
                    sender_domain,
                    sender_ip
                );
            }
            SpfResult::Neutral => {
                tracing::debug!(
                    "SPF neutral for mail {} (domain: {}, ip: {})",
                    mail.id(),
                    sender_domain,
                    sender_ip
                );
            }
            SpfResult::TempError => {
                tracing::warn!(
                    "SPF temporary error for mail {} (domain: {}, ip: {})",
                    mail.id(),
                    sender_domain,
                    sender_ip
                );
            }
            SpfResult::PermError => {
                tracing::warn!(
                    "SPF permanent error for mail {} (domain: {}, ip: {})",
                    mail.id(),
                    sender_domain,
                    sender_ip
                );
            }
            SpfResult::None => {
                tracing::debug!(
                    "No SPF record for mail {} (domain: {})",
                    mail.id(),
                    sender_domain
                );
            }
        }

        Ok(MailetAction::Continue)
    }

    fn name(&self) -> &str {
        &self.name
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use bytes::Bytes;
    use rusmes_proto::{HeaderMap, MailAddress, MessageBody, MimeMessage};
    use std::net::IpAddr;
    use std::str::FromStr;

    fn create_test_mail(sender: &str, recipients: Vec<&str>, remote_ip: Option<IpAddr>) -> Mail {
        let sender_addr = MailAddress::from_str(sender).ok();
        let recipient_addrs: Vec<MailAddress> = recipients
            .iter()
            .filter_map(|r| MailAddress::from_str(r).ok())
            .collect();

        let message = MimeMessage::new(
            HeaderMap::new(),
            MessageBody::Small(Bytes::from("Test message")),
        );

        Mail::new(sender_addr, recipient_addrs, message, remote_ip, None)
    }

    #[tokio::test]
    async fn test_spf_check_mailet_creation() {
        let mailet = SpfCheckMailet::new();
        assert_eq!(mailet.name(), "SpfCheck");
        assert!(!mailet.reject_on_fail);
        assert_eq!(mailet.max_dns_lookups, 10);
    }

    #[tokio::test]
    async fn test_spf_check_mailet_default() {
        let mailet = SpfCheckMailet::default();
        assert_eq!(mailet.name(), "SpfCheck");
    }

    #[tokio::test]
    async fn test_spf_check_init_with_config() {
        let mut mailet = SpfCheckMailet::new();
        let mut config = MailetConfig::new("SpfCheck");
        config = config.with_param("reject_on_fail".to_string(), "true".to_string());
        config = config.with_param("max_dns_lookups".to_string(), "15".to_string());

        let result = mailet.init(config).await;
        assert!(result.is_ok());
        assert!(mailet.reject_on_fail);
        assert_eq!(mailet.max_dns_lookups, 15);
    }

    #[tokio::test]
    async fn test_spf_check_no_remote_address() {
        let mailet = SpfCheckMailet::new();
        let mut mail = create_test_mail("sender@example.com", vec!["recipient@test.com"], None);

        let action = mailet.service(&mut mail).await.unwrap();
        assert!(matches!(action, MailetAction::Continue));

        let spf_result = mail.get_attribute("spf.result").and_then(|v| v.as_str());
        assert_eq!(spf_result, Some("none"));
    }

    #[tokio::test]
    async fn test_spf_check_no_sender() {
        let mailet = SpfCheckMailet::new();
        let remote_ip = IpAddr::from_str("192.0.2.1").unwrap();
        let recipient_addrs = vec![MailAddress::from_str("recipient@test.com").unwrap()];

        let message = MimeMessage::new(
            HeaderMap::new(),
            MessageBody::Small(Bytes::from("Test message")),
        );

        let mut mail = Mail::new(None, recipient_addrs, message, Some(remote_ip), None);

        let action = mailet.service(&mut mail).await.unwrap();
        assert!(matches!(action, MailetAction::Continue));

        let spf_result = mail.get_attribute("spf.result").and_then(|v| v.as_str());
        assert_eq!(spf_result, Some("none"));
    }

    #[tokio::test]
    async fn test_spf_result_as_str() {
        assert_eq!(SpfResult::Pass.as_str(), "pass");
        assert_eq!(SpfResult::Fail.as_str(), "fail");
        assert_eq!(SpfResult::SoftFail.as_str(), "softfail");
        assert_eq!(SpfResult::Neutral.as_str(), "neutral");
        assert_eq!(SpfResult::TempError.as_str(), "temperror");
        assert_eq!(SpfResult::PermError.as_str(), "permerror");
        assert_eq!(SpfResult::None.as_str(), "none");
    }

    #[test]
    fn test_parse_qualifier_pass() {
        let (qual, rest) = SpfCheckMailet::parse_qualifier("+ip4:192.0.2.0/24");
        assert!(matches!(qual, SpfQualifier::Pass));
        assert_eq!(rest, "ip4:192.0.2.0/24");
    }

    #[test]
    fn test_parse_qualifier_fail() {
        let (qual, rest) = SpfCheckMailet::parse_qualifier("-all");
        assert!(matches!(qual, SpfQualifier::Fail));
        assert_eq!(rest, "all");
    }

    #[test]
    fn test_parse_qualifier_softfail() {
        let (qual, rest) = SpfCheckMailet::parse_qualifier("~all");
        assert!(matches!(qual, SpfQualifier::SoftFail));
        assert_eq!(rest, "all");
    }

    #[test]
    fn test_parse_qualifier_neutral() {
        let (qual, rest) = SpfCheckMailet::parse_qualifier("?all");
        assert!(matches!(qual, SpfQualifier::Neutral));
        assert_eq!(rest, "all");
    }

    #[test]
    fn test_parse_qualifier_default() {
        let (qual, rest) = SpfCheckMailet::parse_qualifier("ip4:192.0.2.0/24");
        assert!(matches!(qual, SpfQualifier::Pass));
        assert_eq!(rest, "ip4:192.0.2.0/24");
    }

    #[test]
    fn test_parse_mechanism_all() {
        let mechanism = SpfCheckMailet::parse_mechanism("all").unwrap();
        assert!(matches!(mechanism, SpfMechanism::All));
    }

    #[test]
    fn test_parse_mechanism_ip4() {
        let mechanism = SpfCheckMailet::parse_mechanism("ip4:192.0.2.0/24").unwrap();
        if let SpfMechanism::IP4 { network } = mechanism {
            assert_eq!(network.to_string(), "192.0.2.0/24");
        } else {
            panic!("Expected IP4 mechanism");
        }
    }

    #[test]
    fn test_parse_mechanism_ip4_single() {
        let mechanism = SpfCheckMailet::parse_mechanism("ip4:192.0.2.1").unwrap();
        if let SpfMechanism::IP4 { network } = mechanism {
            assert_eq!(network.to_string(), "192.0.2.1/32");
        } else {
            panic!("Expected IP4 mechanism");
        }
    }

    #[test]
    fn test_parse_mechanism_ip6() {
        let mechanism = SpfCheckMailet::parse_mechanism("ip6:2001:db8::/32").unwrap();
        if let SpfMechanism::IP6 { network } = mechanism {
            assert_eq!(network.to_string(), "2001:db8::/32");
        } else {
            panic!("Expected IP6 mechanism");
        }
    }

    #[test]
    fn test_parse_mechanism_ip6_single() {
        let mechanism = SpfCheckMailet::parse_mechanism("ip6:2001:db8::1").unwrap();
        if let SpfMechanism::IP6 { network } = mechanism {
            assert_eq!(network.to_string(), "2001:db8::1/128");
        } else {
            panic!("Expected IP6 mechanism");
        }
    }

    #[test]
    fn test_parse_mechanism_include() {
        let mechanism = SpfCheckMailet::parse_mechanism("include:example.com").unwrap();
        if let SpfMechanism::Include { domain } = mechanism {
            assert_eq!(domain, "example.com");
        } else {
            panic!("Expected Include mechanism");
        }
    }

    #[test]
    fn test_parse_mechanism_a() {
        let mechanism = SpfCheckMailet::parse_mechanism("a").unwrap();
        if let SpfMechanism::A { domain, prefix } = mechanism {
            assert_eq!(domain, None);
            assert_eq!(prefix, None);
        } else {
            panic!("Expected A mechanism");
        }
    }

    #[test]
    fn test_parse_mechanism_a_with_domain() {
        let mechanism = SpfCheckMailet::parse_mechanism("a:example.com").unwrap();
        if let SpfMechanism::A { domain, prefix } = mechanism {
            assert_eq!(domain, Some("example.com".to_string()));
            assert_eq!(prefix, None);
        } else {
            panic!("Expected A mechanism with domain");
        }
    }

    #[test]
    fn test_parse_mechanism_a_with_prefix() {
        let mechanism = SpfCheckMailet::parse_mechanism("a/24").unwrap();
        if let SpfMechanism::A { domain, prefix } = mechanism {
            assert_eq!(domain, None);
            assert_eq!(prefix, Some(24));
        } else {
            panic!("Expected A mechanism with prefix");
        }
    }

    #[test]
    fn test_parse_mechanism_a_with_domain_and_prefix() {
        let mechanism = SpfCheckMailet::parse_mechanism("a:example.com/24").unwrap();
        if let SpfMechanism::A { domain, prefix } = mechanism {
            assert_eq!(domain, Some("example.com".to_string()));
            assert_eq!(prefix, Some(24));
        } else {
            panic!("Expected A mechanism with domain and prefix");
        }
    }

    #[test]
    fn test_parse_mechanism_mx() {
        let mechanism = SpfCheckMailet::parse_mechanism("mx").unwrap();
        if let SpfMechanism::MX { domain, prefix } = mechanism {
            assert_eq!(domain, None);
            assert_eq!(prefix, None);
        } else {
            panic!("Expected MX mechanism");
        }
    }

    #[test]
    fn test_parse_mechanism_mx_with_domain() {
        let mechanism = SpfCheckMailet::parse_mechanism("mx:example.com").unwrap();
        if let SpfMechanism::MX { domain, prefix } = mechanism {
            assert_eq!(domain, Some("example.com".to_string()));
            assert_eq!(prefix, None);
        } else {
            panic!("Expected MX mechanism with domain");
        }
    }

    #[test]
    fn test_parse_mechanism_exists() {
        let mechanism = SpfCheckMailet::parse_mechanism("exists:example.com").unwrap();
        if let SpfMechanism::Exists { domain } = mechanism {
            assert_eq!(domain, "example.com");
        } else {
            panic!("Expected Exists mechanism");
        }
    }

    #[test]
    fn test_parse_mechanism_ptr() {
        let mechanism = SpfCheckMailet::parse_mechanism("ptr").unwrap();
        if let SpfMechanism::Ptr { domain } = mechanism {
            assert_eq!(domain, None);
        } else {
            panic!("Expected Ptr mechanism");
        }
    }

    #[test]
    fn test_parse_mechanism_ptr_with_domain() {
        let mechanism = SpfCheckMailet::parse_mechanism("ptr:example.com").unwrap();
        if let SpfMechanism::Ptr { domain } = mechanism {
            assert_eq!(domain, Some("example.com".to_string()));
        } else {
            panic!("Expected Ptr mechanism with domain");
        }
    }

    #[test]
    fn test_parse_mechanism_unknown() {
        let result = SpfCheckMailet::parse_mechanism("unknown:test");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_spf_record_simple() {
        let record = "v=spf1 ip4:192.0.2.0/24 -all";
        let mechanisms = SpfCheckMailet::parse_spf_record(record).unwrap();

        assert_eq!(mechanisms.len(), 2);

        assert!(matches!(mechanisms[0].0, SpfQualifier::Pass));
        assert!(matches!(mechanisms[0].1, SpfMechanism::IP4 { .. }));

        assert!(matches!(mechanisms[1].0, SpfQualifier::Fail));
        assert!(matches!(mechanisms[1].1, SpfMechanism::All));
    }

    #[test]
    fn test_parse_spf_record_complex() {
        let record = "v=spf1 +ip4:192.0.2.0/24 a mx include:example.com ~all";
        let mechanisms = SpfCheckMailet::parse_spf_record(record).unwrap();

        assert_eq!(mechanisms.len(), 5);
        assert!(matches!(mechanisms[0].1, SpfMechanism::IP4 { .. }));
        assert!(matches!(mechanisms[1].1, SpfMechanism::A { .. }));
        assert!(matches!(mechanisms[2].1, SpfMechanism::MX { .. }));
        assert!(matches!(mechanisms[3].1, SpfMechanism::Include { .. }));
        assert!(matches!(mechanisms[4].1, SpfMechanism::All));
        assert!(matches!(mechanisms[4].0, SpfQualifier::SoftFail));
    }

    #[test]
    fn test_parse_spf_record_with_modifiers() {
        let record = "v=spf1 ip4:192.0.2.0/24 redirect=example.com -all";
        let mechanisms = SpfCheckMailet::parse_spf_record(record).unwrap();

        // Should skip redirect= modifier
        assert_eq!(mechanisms.len(), 2);
    }

    #[test]
    fn test_parse_spf_record_with_exp() {
        let record = "v=spf1 ip4:192.0.2.0/24 exp=explain.example.com -all";
        let mechanisms = SpfCheckMailet::parse_spf_record(record).unwrap();

        // Should skip exp= modifier
        assert_eq!(mechanisms.len(), 2);
    }

    #[test]
    fn test_parse_domain_and_prefix_empty() {
        let result = SpfCheckMailet::parse_domain_and_prefix("").unwrap();
        assert_eq!(result, (None, None));
    }

    #[test]
    fn test_parse_domain_and_prefix_domain_only() {
        let result = SpfCheckMailet::parse_domain_and_prefix(":example.com").unwrap();
        assert_eq!(result, (Some("example.com".to_string()), None));
    }

    #[test]
    fn test_parse_domain_and_prefix_prefix_only() {
        let result = SpfCheckMailet::parse_domain_and_prefix("/24").unwrap();
        assert_eq!(result, (None, Some(24)));
    }

    #[test]
    fn test_parse_domain_and_prefix_both() {
        let result = SpfCheckMailet::parse_domain_and_prefix(":example.com/24").unwrap();
        assert_eq!(result, (Some("example.com".to_string()), Some(24)));
    }

    #[test]
    fn test_parse_domain_and_prefix_invalid() {
        let result = SpfCheckMailet::parse_domain_and_prefix("invalid");
        assert!(result.is_err());
    }
}