mail-auth 0.15.1

DKIM, ARC, SPF and DMARC library for Rust
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
/*
 * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
 *
 * SPDX-License-Identifier: Apache-2.0 OR MIT
 */

//! DNS cache traits and the per-call [`Parameters`] wrapper.
//!
//! The crate does not ship a cache implementation. Applications supply one by
//! implementing [`ResolverCache`] for their cache type and [`DnsCache`] for a
//! type that groups one cache per record type. The cache is then passed to a
//! verifier through [`Parameters::with_cache`]. Keys are fully qualified,
//! lowercased domain names (see [`ToFqdn`](super::ToFqdn)), or IP addresses
//! for PTR records.
//!
//! # Example
//!
//! ```rust,no_run
//! use mail_auth::{
//!     AuthenticatedMessage, DnsCache, MessageAuthenticator, Mx, Negative, Parameters, RecordSet,
//!     ResolverCache, TxtRecord,
//! };
//! use std::{
//!     borrow::Borrow,
//!     collections::HashMap,
//!     hash::Hash,
//!     net::{IpAddr, Ipv4Addr, Ipv6Addr},
//!     sync::Mutex,
//!     time::Instant,
//! };
//!
//! struct MapCache<K, V>(Mutex<HashMap<K, (V, Instant)>>);
//!
//! impl<K: Hash + Eq, V: Clone> ResolverCache<K, V> for MapCache<K, V> {
//!     fn get<Q>(&self, name: &Q) -> Option<V>
//!     where
//!         K: Borrow<Q>,
//!         Q: Hash + Eq + ?Sized,
//!     {
//!         let map = self.0.lock().unwrap();
//!         let (value, expires) = map.get(name)?;
//!         (*expires > Instant::now()).then(|| value.clone())
//!     }
//!
//!     fn remove<Q>(&self, name: &Q) -> Option<V>
//!     where
//!         K: Borrow<Q>,
//!         Q: Hash + Eq + ?Sized,
//!     {
//!         self.0.lock().unwrap().remove(name).map(|(value, _)| value)
//!     }
//!
//!     fn insert(&self, key: K, value: V, valid_until: Instant) {
//!         self.0.lock().unwrap().insert(key, (value, valid_until));
//!     }
//! }
//!
//! type Answer<T> = Result<RecordSet<T>, Negative>;
//!
//! struct Caches {
//!     txt: MapCache<Box<str>, TxtRecord>,
//!     mx: MapCache<Box<str>, Answer<Mx>>,
//!     ipv4: MapCache<Box<str>, Answer<Ipv4Addr>>,
//!     ipv6: MapCache<Box<str>, Answer<Ipv6Addr>>,
//!     ptr: MapCache<IpAddr, Answer<Box<str>>>,
//! }
//!
//! impl DnsCache for Caches {
//!     type Txt = MapCache<Box<str>, TxtRecord>;
//!     type Mx = MapCache<Box<str>, Answer<Mx>>;
//!     type Ipv4 = MapCache<Box<str>, Answer<Ipv4Addr>>;
//!     type Ipv6 = MapCache<Box<str>, Answer<Ipv6Addr>>;
//!     type Ptr = MapCache<IpAddr, Answer<Box<str>>>;
//!
//!     fn txt(&self) -> Option<&Self::Txt> { Some(&self.txt) }
//!     fn mx(&self) -> Option<&Self::Mx> { Some(&self.mx) }
//!     fn ipv4(&self) -> Option<&Self::Ipv4> { Some(&self.ipv4) }
//!     fn ipv6(&self) -> Option<&Self::Ipv6> { Some(&self.ipv6) }
//!     fn ptr(&self) -> Option<&Self::Ptr> { Some(&self.ptr) }
//! }
//!
//! # async fn run(authenticator: &MessageAuthenticator, caches: &Caches, raw: &[u8]) {
//! let message = AuthenticatedMessage::parse(raw).unwrap();
//! let results = authenticator
//!     .verify_dkim(Parameters::new(&message).with_cache(caches))
//!     .await;
//! # }
//! ```

use super::{Mx, Negative, RecordSet, TxtRecord};
use crate::Instant;
use std::{
    borrow::Borrow,
    hash::Hash,
    net::{IpAddr, Ipv4Addr, Ipv6Addr},
};

/// A cache for one DNS record type, keyed by `K` and holding values of type
/// `V`.
///
/// Methods take `&self`, so implementations that mutate must use interior
/// mutability (a lock or a concurrent map). The lookup helpers call
/// [`get`](Self::get) before querying and [`insert`](Self::insert) after a
/// query that returned records or a cacheable negative answer; they do not
/// check expiry themselves. See the [module documentation](self) for an
/// example.
pub trait ResolverCache<K, V>: Sized {
    /// Returns a copy of the cached value for `name`, or `None` if there is
    /// none. Implementations should return `None` for expired entries.
    fn get<Q>(&self, name: &Q) -> Option<V>
    where
        K: Borrow<Q>,
        Q: Hash + Eq + ?Sized;
    /// Removes the entry for `name` and returns its value. Not called by this
    /// crate; available to applications that invalidate entries.
    fn remove<Q>(&self, name: &Q) -> Option<V>
    where
        K: Borrow<Q>,
        Q: Hash + Eq + ?Sized;
    /// Stores `value` under `key`. `valid_until` is the expiry time derived
    /// from the TTLs of the DNS answer, or from its negative TTL for a
    /// negative answer.
    fn insert(&self, key: K, value: V, valid_until: Instant);
}

/// A set of DNS caches, one per record type, passed to verifiers through
/// [`Parameters::with_cache`].
///
/// An accessor that returns `None` disables caching for that record type.
/// See the [module documentation](self) for an example.
pub trait DnsCache {
    /// Cache for parsed TXT records (SPF, DKIM, DMARC, ATPS, MTA-STS,
    /// TLSRPT), keyed by fully qualified domain name.
    type Txt: ResolverCache<Box<str>, TxtRecord>;
    /// Cache for MX records and negative MX answers, keyed by fully
    /// qualified domain name.
    type Mx: ResolverCache<Box<str>, Result<RecordSet<Mx>, Negative>>;
    /// Cache for A records and negative A answers, keyed by fully qualified
    /// domain name.
    type Ipv4: ResolverCache<Box<str>, Result<RecordSet<Ipv4Addr>, Negative>>;
    /// Cache for AAAA records and negative AAAA answers, keyed by fully
    /// qualified domain name.
    type Ipv6: ResolverCache<Box<str>, Result<RecordSet<Ipv6Addr>, Negative>>;
    /// Cache for PTR records and negative PTR answers, keyed by IP address.
    type Ptr: ResolverCache<IpAddr, Result<RecordSet<Box<str>>, Negative>>;

    /// Returns the TXT record cache, or `None` to disable it.
    fn txt(&self) -> Option<&Self::Txt>;
    /// Returns the MX record cache, or `None` to disable it.
    fn mx(&self) -> Option<&Self::Mx>;
    /// Returns the A record cache, or `None` to disable it.
    fn ipv4(&self) -> Option<&Self::Ipv4>;
    /// Returns the AAAA record cache, or `None` to disable it.
    fn ipv6(&self) -> Option<&Self::Ipv6>;
    /// Returns the PTR record cache, or `None` to disable it.
    fn ptr(&self) -> Option<&Self::Ptr>;
}

/// A cache that stores nothing.
///
/// Implements both [`ResolverCache`] (every lookup misses) and [`DnsCache`]
/// (every accessor returns `None`). It is the default cache type of
/// [`Parameters`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct NoCache;

impl<K, V> ResolverCache<K, V> for NoCache {
    fn get<Q>(&self, _: &Q) -> Option<V>
    where
        K: Borrow<Q>,
        Q: Hash + Eq + ?Sized,
    {
        None
    }

    fn remove<Q>(&self, _: &Q) -> Option<V>
    where
        K: Borrow<Q>,
        Q: Hash + Eq + ?Sized,
    {
        None
    }

    fn insert(&self, _: K, _: V, _: Instant) {}
}

impl DnsCache for NoCache {
    type Txt = NoCache;
    type Mx = NoCache;
    type Ipv4 = NoCache;
    type Ipv6 = NoCache;
    type Ptr = NoCache;

    fn txt(&self) -> Option<&Self::Txt> {
        None
    }

    fn mx(&self) -> Option<&Self::Mx> {
        None
    }

    fn ipv4(&self) -> Option<&Self::Ipv4> {
        None
    }

    fn ipv6(&self) -> Option<&Self::Ipv6> {
        None
    }

    fn ptr(&self) -> Option<&Self::Ptr> {
        None
    }
}

/// The input of a verifier, optionally paired with a DNS cache.
///
/// Every verifier on [`MessageAuthenticator`](crate::MessageAuthenticator)
/// takes `impl Into<Parameters<..>>`, so the bare input (a message, an IP
/// address, SPF or DMARC parameters) can be passed directly when no cache is
/// needed. Wrap it with [`Parameters::new`] and
/// [`with_cache`](Self::with_cache) to use a cache.
pub struct Parameters<'x, P, C: DnsCache = NoCache> {
    /// The verifier input.
    pub input: P,
    /// The DNS cache, or `None` to query without caching.
    pub cache: Option<&'x C>,
}

impl<P> Parameters<'_, P, NoCache> {
    /// Wraps `input` without a cache.
    pub fn new(input: P) -> Self {
        Parameters { input, cache: None }
    }
}

impl<'x, P, C: DnsCache> Parameters<'x, P, C> {
    /// Sets the DNS cache, replacing any cache set before.
    pub fn with_cache<NewC: DnsCache>(self, cache: &'x NewC) -> Parameters<'x, P, NewC> {
        Parameters {
            input: self.input,
            cache: Some(cache),
        }
    }

    /// Returns parameters with a different input and the same cache. Useful
    /// for running several verifiers against one cache.
    pub fn clone_with<NewP>(&self, input: NewP) -> Parameters<'x, NewP, C> {
        Parameters {
            input,
            cache: self.cache,
        }
    }

    #[inline(always)]
    pub(crate) fn txt_cache(&self) -> Option<&'x C::Txt> {
        self.cache.and_then(DnsCache::txt)
    }

    #[inline(always)]
    pub(crate) fn mx_cache(&self) -> Option<&'x C::Mx> {
        self.cache.and_then(DnsCache::mx)
    }

    #[inline(always)]
    pub(crate) fn ipv4_cache(&self) -> Option<&'x C::Ipv4> {
        self.cache.and_then(DnsCache::ipv4)
    }

    #[inline(always)]
    pub(crate) fn ipv6_cache(&self) -> Option<&'x C::Ipv6> {
        self.cache.and_then(DnsCache::ipv6)
    }

    #[inline(always)]
    pub(crate) fn ptr_cache(&self) -> Option<&'x C::Ptr> {
        self.cache.and_then(DnsCache::ptr)
    }
}

#[cfg(test)]
pub(crate) mod test {
    use crate::dns::{
        DnsCache, DnssecStatus, Mx, Negative, Parameters, RecordSet, ResolverCache, ToFqdn,
        TxtRecord,
    };
    use std::{
        borrow::Borrow,
        hash::Hash,
        net::{IpAddr, Ipv4Addr, Ipv6Addr},
        sync::Arc,
    };

    pub(crate) struct DummyCache<K, V>(std::sync::Mutex<std::collections::HashMap<K, V>>);

    impl<K: Hash + Eq, V: Clone> DummyCache<K, V> {
        pub fn new() -> Self {
            DummyCache(std::sync::Mutex::new(std::collections::HashMap::new()))
        }
    }

    impl<K: Hash + Eq, V: Clone> ResolverCache<K, V> for DummyCache<K, V> {
        fn get<Q>(&self, key: &Q) -> Option<V>
        where
            K: Borrow<Q>,
            Q: Hash + Eq + ?Sized,
        {
            self.0.lock().unwrap().get(key).cloned()
        }

        fn remove<Q>(&self, key: &Q) -> Option<V>
        where
            K: Borrow<Q>,
            Q: Hash + Eq + ?Sized,
        {
            self.0.lock().unwrap().remove(key)
        }

        fn insert(&self, key: K, value: V, _: std::time::Instant) {
            self.0.lock().unwrap().insert(key, value);
        }
    }

    type Answer<T> = Result<RecordSet<T>, Negative>;

    pub(crate) struct DummyCaches {
        pub txt: DummyCache<Box<str>, TxtRecord>,
        pub mx: DummyCache<Box<str>, Answer<Mx>>,
        pub ptr: DummyCache<IpAddr, Answer<Box<str>>>,
        pub ipv4: DummyCache<Box<str>, Answer<Ipv4Addr>>,
        pub ipv6: DummyCache<Box<str>, Answer<Ipv6Addr>>,
    }

    impl DummyCaches {
        pub fn new() -> Self {
            Self {
                txt: DummyCache::new(),
                mx: DummyCache::new(),
                ptr: DummyCache::new(),
                ipv4: DummyCache::new(),
                ipv6: DummyCache::new(),
            }
        }

        pub fn with_txt(
            self,
            name: impl ToFqdn,
            value: impl Into<TxtRecord>,
            valid_until: std::time::Instant,
        ) -> Self {
            self.txt.insert(
                name.to_fqdn().into_owned().into_boxed_str(),
                value.into(),
                valid_until,
            );
            self
        }

        pub fn txt_add(
            &self,
            name: impl ToFqdn,
            value: impl Into<TxtRecord>,
            valid_until: std::time::Instant,
        ) {
            self.txt.insert(
                name.to_fqdn().into_owned().into_boxed_str(),
                value.into(),
                valid_until,
            );
        }

        pub fn ipv4_add(
            &self,
            name: impl ToFqdn,
            value: Vec<Ipv4Addr>,
            valid_until: std::time::Instant,
        ) {
            self.ipv4.insert(
                name.to_fqdn().into_owned().into_boxed_str(),
                Ok(RecordSet {
                    records: Arc::from(value.into_boxed_slice()),
                    dnssec_status: DnssecStatus::Indeterminate,
                }),
                valid_until,
            );
        }

        pub fn ipv6_add(
            &self,
            name: impl ToFqdn,
            value: Vec<Ipv6Addr>,
            valid_until: std::time::Instant,
        ) {
            self.ipv6.insert(
                name.to_fqdn().into_owned().into_boxed_str(),
                Ok(RecordSet {
                    records: Arc::from(value.into_boxed_slice()),
                    dnssec_status: DnssecStatus::Indeterminate,
                }),
                valid_until,
            );
        }

        pub fn ptr_add(&self, name: IpAddr, value: Vec<Box<str>>, valid_until: std::time::Instant) {
            self.ptr.insert(
                name,
                Ok(RecordSet {
                    records: Arc::from(value.into_boxed_slice()),
                    dnssec_status: DnssecStatus::Indeterminate,
                }),
                valid_until,
            );
        }

        pub fn mx_add(&self, name: impl ToFqdn, value: Vec<Mx>, valid_until: std::time::Instant) {
            self.mx.insert(
                name.to_fqdn().into_owned().into_boxed_str(),
                Ok(RecordSet {
                    records: Arc::from(value.into_boxed_slice()),
                    dnssec_status: DnssecStatus::Indeterminate,
                }),
                valid_until,
            );
        }

        pub fn parameters<T>(&self, param: T) -> Parameters<'_, T, DummyCaches> {
            Parameters::new(param).with_cache(self)
        }
    }

    impl DnsCache for DummyCaches {
        type Txt = DummyCache<Box<str>, TxtRecord>;
        type Mx = DummyCache<Box<str>, Answer<Mx>>;
        type Ipv4 = DummyCache<Box<str>, Answer<Ipv4Addr>>;
        type Ipv6 = DummyCache<Box<str>, Answer<Ipv6Addr>>;
        type Ptr = DummyCache<IpAddr, Answer<Box<str>>>;

        fn txt(&self) -> Option<&Self::Txt> {
            Some(&self.txt)
        }

        fn mx(&self) -> Option<&Self::Mx> {
            Some(&self.mx)
        }

        fn ipv4(&self) -> Option<&Self::Ipv4> {
            Some(&self.ipv4)
        }

        fn ipv6(&self) -> Option<&Self::Ipv6> {
            Some(&self.ipv6)
        }

        fn ptr(&self) -> Option<&Self::Ptr> {
            Some(&self.ptr)
        }
    }
}