keri-http-auth 0.2.0

KERI HTTP message signatures and request authentication
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
//! Signing a request and verifying a response.
//!
//! [`crate::input`] decides what a signature covers and the exact bytes signed, and
//! [`crate::fields`] carries the signature material. This module composes them with a key.
//!
//! ```text
//! Signature-Input: signify=("@method" "@path" "signify-resource" "signify-timestamp");created=…;keyid="…";alg="ed25519"
//! Signature:       indexed="?0";signify="0BCh…"
//! ```
//!
//! [`RequestSigner`] owns the secret and [`ResponseVerifier`] owns the public key, so a value that
//! only checks responses never holds signing capability. [`crate::server`] holds the other direction.
//!
//! Replay policy is the caller's: [`SignatureInput::created`] is returned for it to judge.

use core::fmt;
use std::error::Error;

use keri_cesr::crypto::CryptoError;
use keri_cesr::crypto::signer::Signer;
use keri_cesr::crypto::verifier::VerificationKey;

use crate::fields::{
    FieldText, SIGNATURE_HEADER_NAME, SignageBuilder, SignageMarkers, SignatureFieldError, SignatureHeader,
    UnindexedMarker,
};
use crate::header::{HeaderError, HeaderName, HeaderValue, Headers};
use crate::input::{
    ED25519_ALGORITHM, InputLabel, RequestTarget, SIGNATURE_INPUT_HEADER_NAME, SignatureComponent, SignatureInput,
    SignatureInputBuilder, SignatureInputError, SignatureInputHeader,
};

/// Signs requests with one private key.
///
/// ```
/// use keri_cesr::crypto::salt::{Salt, SecurityTier};
/// use keri_cesr::crypto::verifier::KeyTransferability;
/// use keri_http_auth::header::{HeaderName, HeaderValue, Headers};
/// use keri_http_auth::authentication::RequestSigner;
/// use keri_http_auth::input::{RequestTarget, default_components};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // A fixed example salt; never use a public salt for real keys.
/// let salt = Salt::from_raw(b"0123456789abcdef", SecurityTier::Low)?;
/// let signer = RequestSigner::new(salt.derive_signer("", KeyTransferability::Transferable)?);
///
/// let headers = Headers::from_pairs([
///     (
///         HeaderName::new("signify-resource")?,
///         HeaderValue::new("EWJkQCFvKuyxZi582yJPb0wcwuW3VXmFNuvbQuBpgmIs")?,
///     ),
///     (
///         HeaderName::new("signify-timestamp")?,
///         HeaderValue::new("2022-09-24T00:05:48.196795+00:00")?,
///     ),
/// ])?;
///
/// let input = signer.signature_input(default_components()?, 1_609_459_200)?;
/// let signed = signer.sign(&input, &RequestTarget::new("POST", "/boot")?, &headers)?;
///
/// assert_eq!(
///     signed.signature(),
///     concat!(
///         r#"indexed="?0";signify="0BChvN_BWAf-mgEuTnWfNnktgHdWOuOh9cWc4o0GFWuZ"#,
///         r#"Owra3DyJT5dJ_6BX7AANDOTnIlAKh5Sg_9qGQXHjj5oJ""#,
///     ),
/// );
/// # Ok(())
/// # }
/// ```
pub struct RequestSigner {
    signer: Signer,
    label: InputLabel,
}

impl RequestSigner {
    /// Uses one signer under the `signify` label.
    #[must_use]
    pub fn new(signer: Signer) -> Self {
        Self {
            signer,
            label: InputLabel::signify(),
        }
    }

    /// Uses one signer under an explicit label.
    #[must_use]
    pub const fn with_label(signer: Signer, label: InputLabel) -> Self {
        Self { signer, label }
    }

    /// Returns the label this signer writes.
    #[must_use]
    pub const fn label(&self) -> &InputLabel {
        &self.label
    }

    /// Returns the qualified verification key a peer needs to check these signatures.
    ///
    /// # Errors
    ///
    /// Returns [`AuthenticationError::Crypto`] when the key cannot be encoded and
    /// [`AuthenticationError::Field`] when it is not usable as a parameter value.
    pub fn key_identifier(&self) -> Result<FieldText, AuthenticationError> {
        let key = self.signer.verifier().qb64().map_err(AuthenticationError::crypto)?;
        Ok(FieldText::new(key)?)
    }

    /// Builds the signature input a Signify request carries.
    ///
    /// `keyid` is this signer's verification key and `alg` is [`ED25519_ALGORITHM`]. `created` is a
    /// parameter rather than a clock reading, so the result is reproducible.
    ///
    /// # Errors
    ///
    /// Returns [`AuthenticationError::Input`] when the components are empty, repeated, or too
    /// many, and the errors of [`RequestSigner::key_identifier`].
    pub fn signature_input(
        &self,
        components: Vec<SignatureComponent>,
        created: u64,
    ) -> Result<SignatureInput, AuthenticationError> {
        Ok(SignatureInputBuilder::new(self.label.clone(), components, created)
            .key_identifier(self.key_identifier()?)
            .algorithm(FieldText::new(ED25519_ALGORITHM)?)
            .build()?)
    }

    /// Signs one request, returning the two headers it must carry.
    ///
    /// The signature covers the base [`SignatureInput::signature_base`] derives, and is attached
    /// as one named unindexed marker.
    ///
    /// # Errors
    ///
    /// Returns [`AuthenticationError::Input`] when the base cannot be built, most often because a
    /// covered header is absent; [`AuthenticationError::Crypto`] when signing fails; and
    /// [`AuthenticationError::Field`] when the resulting header cannot be rendered.
    pub fn sign(
        &self,
        input: &SignatureInput,
        target: &RequestTarget,
        headers: &Headers,
    ) -> Result<AuthenticatedHeaders, AuthenticationError> {
        let base = input.signature_base(target, headers)?;
        let signature = self
            .signer
            .sign_unindexed(base.as_bytes())
            .map_err(AuthenticationError::crypto)?;

        let marker = UnindexedMarker::named(FieldText::new(self.label.as_str())?, signature)?;
        let signage = SignageBuilder::new(SignageMarkers::Unindexed(vec![marker])).build()?;
        let signature = SignatureHeader::new(vec![signage])?.to_header_value()?;
        let signature_input = SignatureInputHeader::new(vec![input.clone()])?.to_header_value()?;

        Ok(AuthenticatedHeaders {
            signature_input,
            signature,
        })
    }
}

impl fmt::Debug for RequestSigner {
    /// Redacts the signer.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("RequestSigner")
            .field("label", &self.label)
            .finish_non_exhaustive()
    }
}

/// The two headers a signed request carries.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AuthenticatedHeaders {
    signature_input: String,
    signature: String,
}

impl AuthenticatedHeaders {
    /// Returns the `Signature-Input` value.
    #[must_use]
    pub fn signature_input(&self) -> &str {
        &self.signature_input
    }

    /// Returns the `Signature` value.
    #[must_use]
    pub fn signature(&self) -> &str {
        &self.signature
    }

    /// Returns both headers with their names, `Signature-Input` first.
    pub fn iter(&self) -> impl Iterator<Item = (&'static str, &str)> {
        [
            (SIGNATURE_INPUT_HEADER_NAME, self.signature_input.as_str()),
            (SIGNATURE_HEADER_NAME, self.signature.as_str()),
        ]
        .into_iter()
    }

    /// Adds both headers to a collection.
    ///
    /// # Errors
    ///
    /// Returns [`AuthenticationError::Header`] when either name is already present, which would
    /// mean the message was signed twice.
    pub fn apply(&self, headers: &mut Headers) -> Result<(), AuthenticationError> {
        for (name, value) in self.iter() {
            headers.insert(HeaderName::new(name)?, HeaderValue::new(value)?)?;
        }
        Ok(())
    }
}

impl<'headers> IntoIterator for &'headers AuthenticatedHeaders {
    type Item = (&'static str, &'headers str);
    type IntoIter = std::array::IntoIter<(&'static str, &'headers str), 2>;

    fn into_iter(self) -> Self::IntoIter {
        [
            (SIGNATURE_INPUT_HEADER_NAME, self.signature_input.as_str()),
            (SIGNATURE_HEADER_NAME, self.signature.as_str()),
        ]
        .into_iter()
    }
}

/// Verifies signed responses against one public key.
#[derive(Clone, Debug)]
pub struct ResponseVerifier {
    key: VerificationKey,
    label: InputLabel,
}

impl ResponseVerifier {
    /// Uses one key under the `signify` label.
    #[must_use]
    pub fn new(key: VerificationKey) -> Self {
        Self {
            key,
            label: InputLabel::signify(),
        }
    }

    /// Uses one key under an explicit label.
    #[must_use]
    pub const fn with_label(key: VerificationKey, label: InputLabel) -> Self {
        Self { key, label }
    }

    /// Returns the key responses are checked against.
    #[must_use]
    pub const fn key(&self) -> &VerificationKey {
        &self.key
    }

    /// Returns the label this verifier looks for.
    #[must_use]
    pub const fn label(&self) -> &InputLabel {
        &self.label
    }

    /// Verifies one message, returning the input its signature covered.
    ///
    /// Every signage of the `Signature` header is searched for a marker under this verifier's label,
    /// and exactly one must carry it.
    ///
    /// # Errors
    ///
    /// Returns [`AuthenticationError::MissingSignatureInput`] or
    /// [`AuthenticationError::MissingSignature`] when a header is absent;
    /// [`AuthenticationError::UnknownLabel`] when no input carries this label;
    /// [`AuthenticationError::SignatureNotFound`] or [`AuthenticationError::AmbiguousSignature`]
    /// when the marker is missing or repeated; [`AuthenticationError::Input`] when the base cannot
    /// be rebuilt, including when a covered header is absent; and
    /// [`AuthenticationError::Verification`] when the signature does not authenticate the base.
    pub fn verify(&self, target: &RequestTarget, headers: &Headers) -> Result<SignatureInput, AuthenticationError> {
        let input_value = headers
            .get(SIGNATURE_INPUT_HEADER_NAME)
            .ok_or(AuthenticationError::MissingSignatureInput)?;
        let signature_value = headers
            .get(SIGNATURE_HEADER_NAME)
            .ok_or(AuthenticationError::MissingSignature)?;

        let input_header = SignatureInputHeader::parse(input_value)?;
        let input = input_header
            .find(&self.label)
            .ok_or_else(|| AuthenticationError::UnknownLabel {
                label: self.label.as_str().to_owned(),
            })?;

        let signature_header = SignatureHeader::parse(signature_value)?;
        let signature = find_signature(&signature_header, &self.label)?;

        let base = input.signature_base(target, headers)?;
        self.key
            .verify(signature, base.as_bytes())
            .map_err(|_| AuthenticationError::Verification {
                label: self.label.as_str().to_owned(),
            })?;
        Ok(input.clone())
    }
}

/// Finds the one signature written under a label, searching every signage.
pub(crate) fn find_signature<'header>(
    header: &'header SignatureHeader,
    label: &InputLabel,
) -> Result<&'header [u8], AuthenticationError> {
    let label = label.as_str();
    let mut found: Option<&[u8]> = None;
    for signage in header.signages() {
        let raw = match signage.markers() {
            SignageMarkers::Indexed(markers) => markers
                .iter()
                .find(|marker| marker.tag() == label)
                .map(|marker| marker.signature().raw()),
            SignageMarkers::Unindexed(markers) => {
                let mut matched = None;
                for marker in markers {
                    if marker.tag()? == label {
                        matched = Some(marker.signature().raw().as_slice());
                        break;
                    }
                }
                matched
            }
            // A non-CESR signage carries uninterpreted text, not signature material.
            SignageMarkers::Opaque { .. } => None,
        };
        let Some(raw) = raw else { continue };
        if found.is_some() {
            return Err(AuthenticationError::AmbiguousSignature {
                label: label.to_owned(),
            });
        }
        found = Some(raw);
    }
    found.ok_or_else(|| AuthenticationError::SignatureNotFound {
        label: label.to_owned(),
    })
}

/// Stable request-authentication failures.
#[derive(Debug)]
#[non_exhaustive]
pub enum AuthenticationError {
    /// The message carries no `Signature-Input` header.
    MissingSignatureInput,
    /// The message carries no `Signature` header.
    MissingSignature,
    /// No signature input carries the expected label.
    UnknownLabel {
        /// The label that was looked for.
        label: String,
    },
    /// No signature marker carries the expected label.
    SignatureNotFound {
        /// The label that was looked for.
        label: String,
    },
    /// More than one signature marker carries the expected label.
    AmbiguousSignature {
        /// The repeated label.
        label: String,
    },
    /// The signature does not authenticate the bytes the input describes.
    ///
    /// No further detail is reported, so a prober learns nothing about which step failed.
    Verification {
        /// The label whose signature failed.
        label: String,
    },
    /// The signature input is invalid or its base cannot be built.
    Input {
        /// Underlying failure.
        source: SignatureInputError,
    },
    /// The `Signature` header is invalid.
    Field {
        /// Underlying failure.
        source: SignatureFieldError,
    },
    /// A header name or value is invalid.
    Header {
        /// Underlying failure.
        source: HeaderError,
    },
    /// A cryptographic operation failed.
    Crypto {
        /// Underlying failure.
        source: Box<CryptoError>,
    },
}

impl AuthenticationError {
    fn crypto(source: CryptoError) -> Self {
        Self::Crypto {
            source: Box::new(source),
        }
    }
}

impl From<SignatureInputError> for AuthenticationError {
    fn from(source: SignatureInputError) -> Self {
        Self::Input { source }
    }
}

impl From<SignatureFieldError> for AuthenticationError {
    fn from(source: SignatureFieldError) -> Self {
        Self::Field { source }
    }
}

impl From<HeaderError> for AuthenticationError {
    fn from(source: HeaderError) -> Self {
        Self::Header { source }
    }
}

impl fmt::Display for AuthenticationError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MissingSignatureInput => write!(
                formatter,
                "the message carries no {SIGNATURE_INPUT_HEADER_NAME:?} header"
            ),
            Self::MissingSignature => {
                write!(formatter, "the message carries no {SIGNATURE_HEADER_NAME:?} header")
            }
            Self::UnknownLabel { label } => {
                write!(formatter, "no signature input is labelled {label:?}")
            }
            Self::SignatureNotFound { label } => {
                write!(formatter, "no signature marker is tagged {label:?}")
            }
            Self::AmbiguousSignature { label } => {
                write!(formatter, "more than one signature marker is tagged {label:?}")
            }
            Self::Verification { label } => {
                write!(
                    formatter,
                    "the signature tagged {label:?} does not authenticate the message"
                )
            }
            Self::Input { .. } => formatter.write_str("the signature input is invalid"),
            Self::Field { .. } => formatter.write_str("the signature header is invalid"),
            Self::Header { .. } => formatter.write_str("a header is invalid"),
            Self::Crypto { .. } => formatter.write_str("a cryptographic operation failed"),
        }
    }
}

impl Error for AuthenticationError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Input { source } => Some(source),
            Self::Field { source } => Some(source),
            Self::Header { source } => Some(source),
            Self::Crypto { source } => Some(source.as_ref()),
            _ => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use keri_cesr::crypto::salt::{Salt, SecurityTier};
    use keri_cesr::crypto::verifier::KeyTransferability;
    use std::error::Error;

    use crate::input::default_components;

    const RESOURCE: &str = "EWJkQCFvKuyxZi582yJPb0wcwuW3VXmFNuvbQuBpgmIs";
    const STAMP: &str = "2022-09-24T00:05:48.196795+00:00";
    const CREATED: u64 = 1_609_459_200;

    fn request_signer() -> Result<RequestSigner, Box<dyn Error>> {
        let salt = Salt::from_raw(b"0123456789abcdef", SecurityTier::Low)?;
        Ok(RequestSigner::new(
            salt.derive_signer("", KeyTransferability::Transferable)?,
        ))
    }

    fn request_headers() -> Result<Headers, Box<dyn Error>> {
        Ok(Headers::from_pairs([
            (HeaderName::new("Content-Type")?, HeaderValue::new("application/json")?),
            (HeaderName::new("Signify-Resource")?, HeaderValue::new(RESOURCE)?),
            (HeaderName::new("Signify-Timestamp")?, HeaderValue::new(STAMP)?),
        ])?)
    }

    #[test]
    fn a_signed_request_carries_both_headers() -> Result<(), Box<dyn Error>> {
        let signer = request_signer()?;
        let input = signer.signature_input(default_components()?, CREATED)?;
        let target = RequestTarget::new("POST", "/boot")?;
        let attached = signer.sign(&input, &target, &request_headers()?)?;

        assert_eq!(
            attached.signature_input(),
            concat!(
                "signify=(\"@method\" \"@path\" \"signify-resource\" \"signify-timestamp\");",
                "created=1609459200;keyid=\"DN54yRad_BTqgZYUSi_NthRBQrxSnqQdJXWI5UHcGOQt\";alg=\"ed25519\"",
            )
        );
        assert_eq!(
            attached.signature(),
            concat!(
                "indexed=\"?0\";signify=\"0BChvN_BWAf-mgEuTnWfNnktgHdWOuOh9cWc4o0GFWuZ",
                "Owra3DyJT5dJ_6BX7AANDOTnIlAKh5Sg_9qGQXHjj5oJ\"",
            )
        );

        let names: Vec<&str> = attached.iter().map(|(name, _)| name).collect();
        assert_eq!(names, ["Signature-Input", "Signature"]);
        assert_eq!((&attached).into_iter().count(), 2);
        assert_eq!(signer.label().as_str(), "signify");
        assert_eq!(
            signer.key_identifier()?.as_str(),
            "DN54yRad_BTqgZYUSi_NthRBQrxSnqQdJXWI5UHcGOQt"
        );
        Ok(())
    }

    #[test]
    fn a_signed_request_verifies_against_the_signing_key() -> Result<(), Box<dyn Error>> {
        let signer = request_signer()?;
        let input = signer.signature_input(default_components()?, CREATED)?;
        let target = RequestTarget::new("POST", "/boot")?;
        let mut headers = request_headers()?;
        signer.sign(&input, &target, &headers)?.apply(&mut headers)?;

        let verifier = ResponseVerifier::new(signer.signer.verifier().clone());
        let checked = verifier.verify(&target, &headers)?;
        assert_eq!(checked, input);
        assert_eq!(checked.created(), CREATED);
        assert_eq!(verifier.label().as_str(), "signify");
        assert_eq!(verifier.key().qb64()?, signer.key_identifier()?.as_str());
        Ok(())
    }

    #[test]
    fn a_changed_method_or_path_fails_verification() -> Result<(), Box<dyn Error>> {
        let signer = request_signer()?;
        let input = signer.signature_input(default_components()?, CREATED)?;
        let target = RequestTarget::new("POST", "/boot")?;
        let mut headers = request_headers()?;
        signer.sign(&input, &target, &headers)?.apply(&mut headers)?;
        let verifier = ResponseVerifier::new(signer.signer.verifier().clone());

        for (method, path) in [("GET", "/boot"), ("POST", "/booted")] {
            assert!(matches!(
                verifier.verify(&RequestTarget::new(method, path)?, &headers),
                Err(AuthenticationError::Verification { .. })
            ));
        }
        Ok(())
    }

    #[test]
    fn a_changed_covered_header_fails_verification() -> Result<(), Box<dyn Error>> {
        let signer = request_signer()?;
        let input = signer.signature_input(default_components()?, CREATED)?;
        let target = RequestTarget::new("POST", "/boot")?;
        let attached = signer.sign(&input, &target, &request_headers()?)?;

        let mut tampered = Headers::from_pairs([
            (HeaderName::new("Signify-Resource")?, HeaderValue::new(RESOURCE)?),
            (
                HeaderName::new("Signify-Timestamp")?,
                HeaderValue::new("2022-09-24T00:05:48.196796+00:00")?,
            ),
        ])?;
        attached.apply(&mut tampered)?;
        let verifier = ResponseVerifier::new(signer.signer.verifier().clone());
        assert!(matches!(
            verifier.verify(&target, &tampered),
            Err(AuthenticationError::Verification { .. })
        ));
        Ok(())
    }

    #[test]
    fn a_covered_header_removed_after_signing_is_refused() -> Result<(), Box<dyn Error>> {
        let signer = request_signer()?;
        let input = signer.signature_input(default_components()?, CREATED)?;
        let target = RequestTarget::new("POST", "/boot")?;
        let attached = signer.sign(&input, &target, &request_headers()?)?;

        // The cause is named, not reported as a bad signature.
        let mut stripped = Headers::from_pairs([(HeaderName::new("Signify-Resource")?, HeaderValue::new(RESOURCE)?)])?;
        attached.apply(&mut stripped)?;
        let verifier = ResponseVerifier::new(signer.signer.verifier().clone());
        assert!(matches!(
            verifier.verify(&target, &stripped),
            Err(AuthenticationError::Input {
                source: SignatureInputError::MissingCoveredHeader { .. },
            })
        ));
        Ok(())
    }

    #[test]
    fn missing_headers_are_distinguishable_failures() -> Result<(), Box<dyn Error>> {
        let signer = request_signer()?;
        let verifier = ResponseVerifier::new(signer.signer.verifier().clone());
        let target = RequestTarget::new("POST", "/boot")?;

        // Distinguishable from a bad signature.
        assert!(matches!(
            verifier.verify(&target, &request_headers()?),
            Err(AuthenticationError::MissingSignatureInput)
        ));

        let mut headers = request_headers()?;
        let input = signer.signature_input(default_components()?, CREATED)?;
        let attached = signer.sign(&input, &target, &headers)?;
        headers.insert(
            HeaderName::new("Signature-Input")?,
            HeaderValue::new(attached.signature_input())?,
        )?;
        assert!(matches!(
            verifier.verify(&target, &headers),
            Err(AuthenticationError::MissingSignature)
        ));
        Ok(())
    }

    #[test]
    fn the_expected_label_must_be_present_on_both_headers() -> Result<(), Box<dyn Error>> {
        let signer = RequestSigner::with_label(
            Salt::from_raw(b"0123456789abcdef", SecurityTier::Low)?
                .derive_signer("", KeyTransferability::Transferable)?,
            InputLabel::new("sig0")?,
        );
        let input = signer.signature_input(default_components()?, CREATED)?;
        let target = RequestTarget::new("POST", "/boot")?;
        let mut headers = request_headers()?;
        signer.sign(&input, &target, &headers)?.apply(&mut headers)?;

        // The label is a parameter, so another label verifies too.
        let verifier = ResponseVerifier::with_label(signer.signer.verifier().clone(), InputLabel::new("sig0")?);
        assert_eq!(verifier.verify(&target, &headers)?, input);

        let other = ResponseVerifier::new(signer.signer.verifier().clone());
        assert!(matches!(
            other.verify(&target, &headers),
            Err(AuthenticationError::UnknownLabel { label }) if label == "signify"
        ));
        Ok(())
    }

    #[test]
    fn the_signature_is_found_in_any_signage_and_only_once() -> Result<(), Box<dyn Error>> {
        let signer = request_signer()?;
        let input = signer.signature_input(default_components()?, CREATED)?;
        let target = RequestTarget::new("POST", "/boot")?;
        let attached = signer.sign(&input, &target, &request_headers()?)?;
        let verifier = ResponseVerifier::new(signer.signer.verifier().clone());

        // A later signage is searched as well.
        let decoy = r#"indexed="?0";x="0BCsufRGYI-sRvS2c0rsOueSoSRtrjODaf48DYLJbLvvD8aHe7b2sWGebZ-y9ichhsxMF3Hhn-3LYSKIrnmH3oIN""#;
        let mut headers = request_headers()?;
        headers.insert(
            HeaderName::new("Signature-Input")?,
            HeaderValue::new(attached.signature_input())?,
        )?;
        headers.insert(
            HeaderName::new("Signature")?,
            HeaderValue::new(format!("{decoy},{}", attached.signature()))?,
        )?;
        assert_eq!(verifier.verify(&target, &headers)?, input);

        // Two markers under the same label are ambiguous rather than first-wins.
        let mut ambiguous = request_headers()?;
        ambiguous.insert(
            HeaderName::new("Signature-Input")?,
            HeaderValue::new(attached.signature_input())?,
        )?;
        ambiguous.insert(
            HeaderName::new("Signature")?,
            HeaderValue::new(format!("{},{}", attached.signature(), attached.signature()))?,
        )?;
        assert!(matches!(
            verifier.verify(&target, &ambiguous),
            Err(AuthenticationError::AmbiguousSignature { .. })
        ));

        // A signage carrying no marker under the label is not a signature at all.
        let mut absent = request_headers()?;
        absent.insert(
            HeaderName::new("Signature-Input")?,
            HeaderValue::new(attached.signature_input())?,
        )?;
        absent.insert(HeaderName::new("Signature")?, HeaderValue::new(decoy)?)?;
        assert!(matches!(
            verifier.verify(&target, &absent),
            Err(AuthenticationError::SignatureNotFound { .. })
        ));
        Ok(())
    }

    #[test]
    fn the_signer_never_prints_its_secret() -> Result<(), Box<dyn Error>> {
        let rendered = format!("{:?}", request_signer()?);
        assert!(rendered.contains("RequestSigner"));
        assert!(rendered.contains("signify"));
        assert!(!rendered.contains("0123456789abcdef"));
        Ok(())
    }

    #[test]
    fn applying_the_headers_twice_is_refused() -> Result<(), Box<dyn Error>> {
        let signer = request_signer()?;
        let input = signer.signature_input(default_components()?, CREATED)?;
        let target = RequestTarget::new("POST", "/boot")?;
        let attached = signer.sign(&input, &target, &request_headers()?)?;
        let mut headers = request_headers()?;
        attached.apply(&mut headers)?;
        assert!(matches!(
            attached.apply(&mut headers),
            Err(AuthenticationError::Header {
                source: HeaderError::DuplicateHeader { .. },
            })
        ));
        Ok(())
    }

    #[test]
    fn errors_carry_readable_text_and_sources() {
        for error in [
            AuthenticationError::MissingSignatureInput,
            AuthenticationError::MissingSignature,
            AuthenticationError::UnknownLabel {
                label: "signify".to_owned(),
            },
            AuthenticationError::SignatureNotFound {
                label: "signify".to_owned(),
            },
            AuthenticationError::AmbiguousSignature {
                label: "signify".to_owned(),
            },
            AuthenticationError::Verification {
                label: "signify".to_owned(),
            },
        ] {
            assert_ne!(error.to_string(), "");
            assert!(error.source().is_none());
        }
        for error in [
            AuthenticationError::from(SignatureInputError::NoInputs),
            AuthenticationError::from(SignatureFieldError::NoMarkers),
            AuthenticationError::from(HeaderError::EmptyName),
        ] {
            assert_ne!(error.to_string(), "");
            assert!(error.source().is_some());
        }
    }
}