viadkim 0.2.0

Implementation of the DomainKeys Identified Mail (DKIM) specification
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
// viadkim – implementation of the DKIM specification
// Copyright © 2022–2024 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/>.

//! Signer and supporting types.
//!
//! The main API items are [`Signer`] and convenience function
//! [`sign`][`sign()`].

mod format;
mod sign;

use crate::{
    crypto::SigningKey,
    header::{FieldBody, FieldName, HeaderField, HeaderFields},
    message_hash::{BodyHasher, BodyHasherBuilder, BodyHasherStance},
    parse,
    signature::{
        Canonicalization, CanonicalizationAlgorithm, DkimSignature, DomainName, Identity, Selector,
        SigningAlgorithm, DKIM_SIGNATURE_NAME,
    },
    signer::format::LINE_WIDTH,
    tag_list,
};
use std::{
    cmp::Ordering,
    collections::HashSet,
    error::Error,
    fmt::{self, Display, Formatter},
    num::{NonZeroUsize, TryFromIntError},
    time::Duration,
};

/// A generator for the body length limit tag (*l=*).
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub enum BodyLength {
    /// Do not limit the body length: no *l=* tag.
    #[default]
    NoLimit,
    /// Sign the entire canonicalised message body: set *l=* to the actual body
    /// length.
    MessageContent,
    /// Sign exactly the specified number of bytes of canonicalised body
    /// content: set *l=* to the given value.
    Exact(u64),
}

impl BodyLength {
    fn to_usize(self) -> Result<Option<usize>, TryFromIntError> {
        match self {
            Self::NoLimit | Self::MessageContent => Ok(None),
            Self::Exact(n) => n.try_into().map(Some),
        }
    }
}

/// A generator for the timestamp tag (*t=*).
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub enum Timestamp {
    /// No *t=* tag.
    None,
    /// The current timestamp when signing.
    #[default]
    Now,
    /// Exactly the given timestamp in *t=*.
    Exact(u64),
}

/// A generator for the expiration tag (*x=*).
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub enum Expiration {
    /// No *x=* tag.
    #[default]
    Never,
    /// The duration for which the signature will remain valid.
    After(Duration),
    /// Exactly the given timestamp in *x=*.
    Exact(u64),
}

/// Selection of headers to include in the *h=* tag.
#[derive(Clone, Debug, Default, Eq, Hash, PartialEq)]
pub enum HeaderSelection {
    /// Given some `HeaderFields`, select the headers in the default set.
    #[default]
    Auto,
    /// Use exactly the headers given here as contents of the *h=* tag.
    Manual(Vec<FieldName>),
}

/// Selects all headers matching the predicate, in reverse (evaluation order).
pub fn select_headers<'a, 'b: 'a>(
    headers: &'a HeaderFields,
    mut pred: impl FnMut(&FieldName) -> bool + 'b,
) -> impl DoubleEndedIterator<Item = &FieldName> + 'a {
    headers
        .as_ref()
        .iter()
        .rev()
        .filter_map(move |(name, _)| pred(name).then_some(name))
}

/// Returns a collection of headers that should be signed.
///
/// RFC 6376 does not actually recommend a specific set of headers to be signed.
/// Instead, the collection returned here contains the so-called ‘examples’ from
/// section 5.4.1.
pub fn default_signed_headers() -> Vec<FieldName> {
    // This set is the same as in OpenDKIM (minus *Resent-Sender*: *Sender* and
    // *Resent-Sender* were removed between RFC 4871 and 6376, but the latter
    // was left in OpenDKIM possibly by mistake).
    let names = [
        "From",
        "Reply-To",
        "Subject",
        "Date",
        "To",
        "Cc",
        "Resent-Date",
        "Resent-From",
        "Resent-To",
        "Resent-Cc",
        "In-Reply-To",
        "References",
        "List-Id",
        "List-Help",
        "List-Unsubscribe",
        "List-Subscribe",
        "List-Post",
        "List-Owner",
        "List-Archive",
    ];

    names
        .into_iter()
        .map(|n| FieldName::new(n).unwrap())
        .collect()
}

/// Returns a collection of headers that should be excluded from a signature.
///
/// RFC 6376 does not actually recommend a specific set of headers to be
/// excluded. Instead, the collection returned here contains the so-called
/// ‘examples’ from section 5.4.1.
pub fn default_unsigned_headers() -> Vec<FieldName> {
    // This set is the same as in OpenDKIM.
    let names = [
        "Return-Path",
        "Received",
        "Comments",
        "Keywords",
    ];

    names
        .into_iter()
        .map(|n| FieldName::new(n).unwrap())
        .collect()
}

/// An error that occurs when setting up a signer or signing request.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum RequestError {
    /// Conversion from or to a requested integer data type is not supported in
    /// this implementation or on the current platform.
    Overflow,
    /// No *From* header in the message header.
    MissingFromHeader,
    /// More requests for signing than acceptable.
    TooManyRequests,
    /// No signing requests provided to the signing process.
    EmptyRequests,
    /// The requested signing algorithm and the provided signing key are of
    /// incompatible types.
    IncompatibleKeyType,
    /// The *From* header is not included in the selection of headers to sign.
    FromHeaderNotSigned,
    /// A header name included in the selection of headers to sign is
    /// syntactically invalid.
    InvalidSignedFieldName,
    /// The *i=* domain is not equal to or a subdomain of the *d=* domain.
    DomainMismatch,
    /// The expiration (*x=*) duration is zero.
    ZeroExpirationDuration,
    /// The *x=* timestamp is not after the *i=* timestamp.
    ExpirationNotAfterTimestamp,
    /// An extension tag is syntactically invalid.
    InvalidExtTags,
    /// The requested *DKIM-Signature* header name is syntactically invalid.
    InvalidDkimSignatureHeaderName,
    /// The requested indentation whitespace is syntactically invalid.
    InvalidIndentationWhitespace,
}

impl Display for RequestError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Overflow => write!(f, "integer too large"),
            Self::MissingFromHeader => write!(f, "no From header"),
            Self::TooManyRequests => write!(f, "too many sign requests"),
            Self::EmptyRequests => write!(f, "no sign requests"),
            Self::IncompatibleKeyType => write!(f, "incompatible key type"),
            Self::FromHeaderNotSigned => write!(f, "From header not signed"),
            Self::InvalidSignedFieldName => write!(f, "invalid signed header name"),
            Self::DomainMismatch => write!(f, "domain mismatch"),
            Self::ZeroExpirationDuration => write!(f, "zero expiration duration"),
            Self::ExpirationNotAfterTimestamp => write!(f, "expiration not after timestamp"),
            Self::InvalidExtTags => write!(f, "invalid extension tags"),
            Self::InvalidDkimSignatureHeaderName => write!(f, "invalid DKIM-Signature header name"),
            Self::InvalidIndentationWhitespace => write!(f, "invalid indentation whitespace"),
        }
    }
}

impl Error for RequestError {}

/// Formatting options.
pub struct OutputFormat {
    /// The header name, must be equal to `DKIM-Signature` ignoring case.
    pub header_name: String,

    /// The maximum line width in characters to use when breaking lines. The
    /// default is 78.
    pub line_width: NonZeroUsize,

    /// The indentation whitespace to use for continuation lines. Must be a
    /// non-empty sequence of space and tab characters. The default is `"\t"`.
    pub indentation: String,

    /// A comparator applied to tag names that determines the order of the tags
    /// included in the signature.
    pub tag_order: Option<Box<dyn Fn(&str, &str) -> Ordering + Send + Sync>>,

    /// Whether to emit only ASCII, even when internationalised domain name
    /// labels or other items are included in a signature. The default is false.
    ///
    /// Enabling this setting may be necessary for interoperation with legacy
    /// systems. However, according to RFC 8616, section 5 these items *should*
    /// be in U-label (Unicode) form.
    pub ascii_only: bool,
}

impl Default for OutputFormat {
    fn default() -> Self {
        Self {
            header_name: DKIM_SIGNATURE_NAME.into(),
            line_width: LINE_WIDTH.try_into().unwrap(),
            indentation: "\t".into(),
            tag_order: None,
            ascii_only: false,
        }
    }
}

struct ClosureDebug;

impl fmt::Debug for ClosureDebug {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "<closure>")
    }
}

impl fmt::Debug for OutputFormat {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("OutputFormat")
            .field("header_name", &self.header_name)
            .field("line_width", &self.line_width)
            .field("indentation", &self.indentation)
            .field("tag_order", &self.tag_order.as_ref().map(|_| ClosureDebug))
            .field("ascii_only", &self.ascii_only)
            .finish()
    }
}

/// A request for creation of a DKIM signature.
#[derive(Debug)]
pub struct SignRequest<T> {
    /// The key to use for producing the cryptographic signature.
    pub signing_key: T,

    /// The signing algorithm to use in the *a=* tag. Must be compatible with
    /// the signing key.
    pub algorithm: SigningAlgorithm,
    /// The canonicalization to use in the *c=* tag.
    pub canonicalization: Canonicalization,
    /// The signing domain to use in the *d=* tag.
    pub domain: DomainName,
    /// The selection of headers to include in the *h=* tag.
    pub header_selection: HeaderSelection,
    /// The agent or user identifier to use in the *i=* tag.
    pub identity: Option<Identity>,
    /// The length of the message body in the *l=* tag.
    pub body_length: BodyLength,
    /// The selector to use in the *s=* tag.
    pub selector: Selector,
    /// The timestamp value to record in the *t=* tag.
    pub timestamp: Timestamp,
    /// The expiration timestamp to specify in the *x=* tag.
    pub expiration: Expiration,
    /// Whether to record all headers used to create the signature in the *z=*
    /// tag.
    pub copy_headers: bool,
    /// Additional tag/value pairs to include in the signature.
    pub ext_tags: Vec<(String, String)>,

    /// The formatting options to use for producing the formatted
    /// *DKIM-Signature* header.
    pub format: OutputFormat,
}

impl<T> SignRequest<T> {
    /// Creates a request for signing using practical default values.
    ///
    /// The default settings used are not necessarily the `Default` values of
    /// each type, but values that are sensible in practice: *c=* is
    /// *relaxed/simple*, *x=* is five days.
    pub fn new(
        domain: DomainName,
        selector: Selector,
        algorithm: SigningAlgorithm,
        signing_key: T,
    ) -> Self {
        use CanonicalizationAlgorithm::*;

        // Canonicalization relaxed/simple is a good, compatible default.
        let canonicalization = Canonicalization::from((Relaxed, Simple));

        // The default validity period of five days follows the traditionally
        // recommended time for retrying message delivery; see RFC 5321, section
        // 4.5.4.1: ‘Retries continue until the message is transmitted or the
        // sender gives up; the give-up time generally needs to be at least 4-5
        // days.’
        // Five days is also used as duration in the example in RFC 6376, §3.5.
        let five_days = Duration::from_secs(60 * 60 * 24 * 5);

        Self {
            signing_key,

            algorithm,
            canonicalization,
            domain,
            header_selection: Default::default(),
            identity: None,
            body_length: BodyLength::NoLimit,
            selector,
            timestamp: Timestamp::Now,
            expiration: Expiration::After(five_days),
            copy_headers: false,
            ext_tags: vec![],

            format: Default::default(),
        }
    }
}

fn validate_request<T: AsRef<SigningKey>>(request: &SignRequest<T>) -> Result<(), RequestError> {
    if request.signing_key.as_ref().key_type() != request.algorithm.key_type() {
        return Err(RequestError::IncompatibleKeyType);
    }

    if let HeaderSelection::Manual(signed_headers) = &request.header_selection {
        if !signed_headers.iter().any(|name| *name == "From") {
            return Err(RequestError::FromHeaderNotSigned);
        }
        if signed_headers.iter().any(|name| name.as_ref().contains(';')) {
            return Err(RequestError::InvalidSignedFieldName);
        }
    }

    if let Some(identity) = &request.identity {
        if !identity.domain.eq_or_subdomain_of(&request.domain) {
            return Err(RequestError::DomainMismatch);
        }
    }

    validate_timestamps(request.timestamp, request.expiration)?;

    let mut tags_seen = HashSet::new();
    if request.ext_tags.iter().any(|(name, value)| {
        !tags_seen.insert(name)
            || !tag_list::is_tag_name(name)
            || !tag_list::is_tag_value(value)
            || format::is_output_tag(name)
    }) {
        return Err(RequestError::InvalidExtTags);
    }

    if !request.format.header_name.eq_ignore_ascii_case(DKIM_SIGNATURE_NAME) {
        return Err(RequestError::InvalidDkimSignatureHeaderName);
    }

    let indent = &request.format.indentation;
    if indent.is_empty() || indent.chars().any(|c| !parse::is_wsp(c)) {
        return Err(RequestError::InvalidIndentationWhitespace);
    }

    Ok(())
}

fn validate_timestamps(timestamp: Timestamp, expiration: Expiration) -> Result<(), RequestError> {
    if let Expiration::After(duration) = expiration {
        if duration.as_secs() == 0 {
            return Err(RequestError::ZeroExpirationDuration);
        }
    }

    // Any combination making use of the ‘now’ timestamp cannot be checked here,
    // only at signing time. What we can do is make sure any inclusion of
    // `*::Exact` will be respected, and will not produce invalid t=/x=.
    match (timestamp, expiration) {
        (Timestamp::Exact(t), Expiration::Exact(x)) if t >= x => {
            return Err(RequestError::ExpirationNotAfterTimestamp);
        }
        (Timestamp::Now, Expiration::Exact(0))
        | (Timestamp::Exact(u64::MAX), Expiration::After(_)) => {
            return Err(RequestError::ExpirationNotAfterTimestamp);
        }
        _ => {}
    }

    Ok(())
}

/// A result type for the signing outcome.
pub type SigningResult = Result<SigningOutput, SigningError>;

/// An error that occurs when performing signing.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum SigningError {
    /// Conversion from or to a requested integer data type is not supported in
    /// this implementation or on the current platform.
    Overflow,
    /// Less than the number of bytes specified in *l=* were fed to the signing
    /// process.
    InsufficientContent,
    /// Failure to perform the cryptographic signing operation.
    SigningFailure,
}

impl Display for SigningError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Overflow => write!(f, "integer too large"),
            Self::InsufficientContent => write!(f, "not enough message body content"),
            Self::SigningFailure => write!(f, "signing failed"),
        }
    }
}

impl Error for SigningError {}

struct SigningOutputHeaderDisplay<'a> {
    name: &'a str,
    value: &'a str,
}

impl Display for SigningOutputHeaderDisplay<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}:{}", self.name, self.value)
    }
}

/// The output generated after successful signing.
///
/// The header name and value must be concatenated with only a colon character
/// in between, no additional whitespace; use [`SigningOutput::format_header`].
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct SigningOutput {
    /// The generated *DKIM-Signature* header name.
    pub header_name: String,
    /// The generated *DKIM-Signature* header value. Continuation lines use CRLF
    /// line endings.
    pub header_value: String,
    /// DKIM signature data used for producing the formatted header.
    pub signature: DkimSignature,
}

impl SigningOutput {
    /// Produces a formatted header, consisting of name, colon, and value. The
    /// output uses CRLF line endings.
    pub fn format_header(&self) -> impl Display + '_ {
        SigningOutputHeaderDisplay {
            name: &self.header_name,
            value: &self.header_value,
        }
    }

    /// Converts this output result to a header field.
    ///
    /// # Panics
    ///
    /// Panics if the result’s header name and value are not a well-formed
    /// header field. (`SigningOutput` produced by `Signer` is always
    /// well-formed and therefore calling this method on such values does not
    /// panic.)
    pub fn to_header_field(&self) -> HeaderField {
        (
            FieldName::new(self.header_name.as_str()).unwrap(),
            FieldBody::new(self.header_value.as_bytes()).unwrap(),
        )
    }
}

struct SignerTask<T> {
    request: SignRequest<T>,
}

/// A signer for an email message.
///
/// `Signer` is the high-level API for signing a message. It implements a
/// three-phase, staged design that allows processing the message in chunks.
///
/// 1. [`prepare_signing`][Signer::prepare_signing]: first, a number of signing
///    requests together with the message header allow construction of a signer
/// 2. [`process_body_chunk`][Signer::process_body_chunk]: then, any number of
///    chunks of the message body are fed to the signing process
/// 3. **[`sign`][Signer::sign()]** (async): finally, the initial signing
///    requests are answered by performing signing and returning the results;
///    this is where most of the actual work is done
///
/// Compare this with the similar but distinct procedure of
/// [`Verifier`][crate::verifier::Verifier].
///
/// For convenience, the free function [`sign`][`sign()`] can be used to perform
/// all stages in one go.
///
/// # Examples
///
/// The following example shows how to sign a message using the high-level API.
///
/// Don’t forget to prepend the formatted *DKIM-Signature* header(s) to your
/// message when sending it out.
///
/// ```
/// # use tokio::runtime::Builder;
/// #
/// # let rt = Builder::new_current_thread().enable_all().build().unwrap();
/// # rt.block_on(async {
/// use viadkim::*;
///
/// let header = "From: me@example.com\r\n\
///     To: you@example.org\r\n\
///     Subject: Re: Thursday 8pm\r\n\
///     Date: Thu, 22 Jun 2023 14:03:12 +0200\r\n".parse()?;
/// let body = b"Hey,\r\n\
///     \r\n\
///     Ready for tonight? ;)\r\n";
///
/// let domain = DomainName::new("example.com")?;
/// let selector = Selector::new("selector")?;
/// let algorithm = SigningAlgorithm::Ed25519Sha256;
/// let signing_key = SigningKey::from_pkcs8_pem(
///     "-----BEGIN PRIVATE KEY-----\n\
///     MC4CAQAwBQYDK2VwBCIEIH1M+KJ5Nln5QmygpruhNrykdHC9AwB8B7ACiiWMp/tQ\n\
///     -----END PRIVATE KEY-----"
/// )?;
///
/// let request = SignRequest::new(domain, selector, algorithm, signing_key);
/// # let mut request = request;
/// # request.timestamp = viadkim::signer::Timestamp::Exact(1687435395);
///
/// let mut signer = Signer::prepare_signing(header, [request])?;
///
/// let _ = signer.process_body_chunk(body);
///
/// let results = signer.sign().await;
///
/// let signature = results.into_iter().next().unwrap()?;
///
/// assert_eq!(
///     signature.format_header().to_string(),
///     "DKIM-Signature: v=1; d=example.com; s=selector; a=ed25519-sha256; c=relaxed;\r\n\
///     \tt=1687435395; x=1687867395; h=Date:Subject:To:From; bh=1zGfaauQ3vmMhm21CGMC23\r\n\
///     \taJE1JrOoKsgT/wvw9owzE=; b=neMHc/e6jrqSscL1pc/fTxOU/CjuvYzvnGbTABQvYkzlIvazqp3\r\n\
///     \tiR7RXUZi0CbOAq13IEUZPc6S0/63cfAO4CA=="
/// );
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// # }).unwrap();
/// ```
///
/// See [`Verifier`][crate::verifier::Verifier] for how the above example
/// message could be verified.
pub struct Signer<T> {
    tasks: Vec<SignerTask<T>>,  // non-empty
    headers: HeaderFields,
    body_hasher: BodyHasher,
}

impl<T> Signer<T>
where
    T: AsRef<SigningKey>,
{
    /// Prepares a message signing process.
    ///
    /// # Errors
    ///
    /// If the given arguments including any of the requests cannot be used for
    /// signing, an error is returned.
    pub fn prepare_signing<I>(headers: HeaderFields, requests: I) -> Result<Self, RequestError>
    where
        I: IntoIterator<Item = SignRequest<T>>,
    {
        if !headers.as_ref().iter().any(|(name, _)| *name == "From") {
            return Err(RequestError::MissingFromHeader);
        }

        let mut tasks = vec![];
        let mut body_hasher = BodyHasherBuilder::new(false);

        for (i, request) in requests.into_iter().enumerate() {
            if i >= 10 {
                return Err(RequestError::TooManyRequests);
            }

            // Eagerly validate requests and abort entire procedure if any are
            // unusable.
            validate_request(&request)?;

            // Register a body hasher request for each signing request.
            let body_len = request.body_length.to_usize().map_err(|_| RequestError::Overflow)?;
            let hash_alg = request.algorithm.hash_algorithm();
            let canon_alg = request.canonicalization.body;
            body_hasher.register_canonicalization(body_len, hash_alg, canon_alg);

            tasks.push(SignerTask { request });
        }

        if tasks.is_empty() {
            return Err(RequestError::EmptyRequests);
        }

        let body_hasher = body_hasher.build();

        Ok(Self {
            tasks,
            headers,
            body_hasher,
        })
    }

    /// Processes a chunk of the message body.
    ///
    /// Clients should pass the message body either whole or in chunks of
    /// arbitrary size to this method in order to calculate the body hash (the
    /// *bh=* tag). The returned [`BodyHasherStance`] instructs the client how
    /// to proceed if more chunks are outstanding. Note that the given body
    /// chunk is canonicalised and hashed, but not otherwise retained in memory.
    ///
    /// Remember that email message bodies generally use CRLF line endings; this
    /// is important for correct body hash calculation.
    ///
    /// # Examples
    ///
    /// ```
    /// # use viadkim::{crypto::SigningKey, signer::Signer};
    /// # fn f<T: AsRef<SigningKey>>(signer: &mut Signer<T>) {
    /// let _ = signer.process_body_chunk(b"\
    /// Hello friend!\r
    /// \r
    /// How are you?\r
    /// ");
    /// # }
    /// ```
    pub fn process_body_chunk(&mut self, chunk: &[u8]) -> BodyHasherStance {
        self.body_hasher.hash_chunk(chunk)
    }

    // Note: The `sign` method doesn’t actually need to be async. But it’s where
    // the work is done, so we introduce this artificial await point for every
    // signature, so control may be yielded to runtime if many signatures.

    /// Performs the actual signing and returns the resulting signatures.
    ///
    /// The returned result vector is never empty.
    pub async fn sign(self) -> Vec<SigningResult> {
        let bh_results = self.body_hasher.finish();

        let mut result = vec![];

        for task in self.tasks {
            let request = task.request;

            let signing_result = sign::perform_signing(request, &self.headers, &bh_results).await;

            result.push(signing_result);
        }

        result
    }
}

/// Produces the requested DKIM signatures for an email message.
///
/// This is a convenience function around a common usage pattern of [`Signer`],
/// when the whole message body is available as a byte slice. Use `Signer` to
/// process the message body in chunks instead.
///
/// See the example for `Signer` for basic usage.
///
/// # Errors
///
/// If the given arguments including any of the requests cannot be used for
/// signing, an error is returned.
pub async fn sign<I, T>(
    header: HeaderFields,
    body: &[u8],
    requests: I,
) -> Result<Vec<SigningResult>, RequestError>
where
    I: IntoIterator<Item = SignRequest<T>>,
    T: AsRef<SigningKey>,
{
    let mut signer = Signer::prepare_signing(header, requests)?;

    let _ = signer.process_body_chunk(body);

    Ok(signer.sign().await)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::header::FieldBody;
    use std::collections::HashSet;

    #[test]
    fn select_headers_ok() {
        let headers = make_header_fields(["From", "Aa", "Bb", "Aa", "Dd"]);

        let names = make_field_names(["from", "aa", "bb", "cc"]);

        let selection = select_headers(&headers, move |name| names.contains(name));

        assert!(selection.map(|n| n.as_ref()).eq(["Aa", "Bb", "Aa", "From"]));
    }

    fn make_header_fields(names: impl IntoIterator<Item = &'static str>) -> HeaderFields {
        let names: Vec<_> = names
            .into_iter()
            .map(|name| (FieldName::new(name).unwrap(), FieldBody::new(*b"").unwrap()))
            .collect();
        HeaderFields::new(names).unwrap()
    }

    fn make_field_names(names: impl IntoIterator<Item = &'static str>) -> HashSet<FieldName> {
        names
            .into_iter()
            .map(|name| FieldName::new(name).unwrap())
            .collect()
    }

    #[test]
    fn validate_timestamps_ok() {
        use super::{
            Expiration as X,
            RequestError::{ExpirationNotAfterTimestamp as ENAT, ZeroExpirationDuration as ZED},
            Timestamp as T,
        };

        let secs = Duration::from_secs;

        assert_eq!(validate_timestamps(T::None, X::Never), Ok(()));
        assert_eq!(validate_timestamps(T::None, X::After(secs(0))), Err(ZED));
        assert_eq!(validate_timestamps(T::None, X::After(secs(3))), Ok(()));
        assert_eq!(validate_timestamps(T::None, X::Exact(0)), Ok(()));
        assert_eq!(validate_timestamps(T::None, X::Exact(3)), Ok(()));
        assert_eq!(validate_timestamps(T::Now, X::Never), Ok(()));
        assert_eq!(validate_timestamps(T::Now, X::After(secs(0))), Err(ZED));
        assert_eq!(validate_timestamps(T::Now, X::After(secs(3))), Ok(()));
        assert_eq!(validate_timestamps(T::Now, X::Exact(0)), Err(ENAT));
        assert_eq!(validate_timestamps(T::Now, X::Exact(3)), Ok(()));
        assert_eq!(validate_timestamps(T::Exact(3), X::Never), Ok(()));
        assert_eq!(validate_timestamps(T::Exact(3), X::After(secs(0))), Err(ZED));
        assert_eq!(validate_timestamps(T::Exact(3), X::After(secs(3))), Ok(()));
        assert_eq!(validate_timestamps(T::Exact(u64::MAX), X::After(secs(3))), Err(ENAT));
    }
}