web-bot-auth 0.7.0

Web Bot Authentication using HTTP Message Signatures
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
#![deny(missing_docs)]
// Copyright (c) 2025 Cloudflare, Inc.
// Licensed under the Apache 2.0 license found in the LICENSE file or at:
//     https://opensource.org/licenses/Apache-2.0

//! # web-bot-auth library
//!
//! `web-bot-auth` is a library provides a Rust implementation of HTTP Message Signatures as defined in
//! [RFC 9421](https://datatracker.ietf.org/doc/html/rfc9421), with additional support
//! for verifying a web bot auth signed message.
//!
//! ## Features
//!
//! - **Message Signing**: Generate HTTP message signatures using Ed25519 cryptography
//! - **Message Verification**: Verify signed HTTP messages against public keys
//! - **Web Bot Auth**: Specialized verification for automated agents with additional security requirements
/// HTTP message components that can be present in a given signed / unsigned message, and all the logic
/// to parse it from an incoming message.
pub mod components;

/// Implementation of a JSON Web Key manager suitable for use with `web-bot-auth`. Can be used for arbitrary
/// HTTP message signatures as well.
pub mod keyring;

/// Implementation of HTTP Message Signatures
pub mod message_signatures;

use components::CoveredComponent;
use message_signatures::{MessageVerifier, ParsedLabel, SignatureTiming, SignedMessage};

use data_url::DataUrl;
use keyring::{Algorithm, JSONWebKeySet, KeyRing};

use crate::components::{HTTPField, HTTPFieldParameters};

/// Errors that may be thrown by this module.
#[derive(Debug)]
pub enum ImplementationError {
    /// Errors that arise from invalid conversions from
    /// parsed structs back into structured field values,
    /// nominally "impossible" because the structs are already
    /// in a valid state.
    ImpossibleSfvError(sfv::Error),
    /// Errors that arise from conversions of structured field
    /// values into parsed structs, with an explanation of what
    /// wrong.
    ParsingError(String),
    /// Errors raised when trying to get the value of a covered
    /// component fails from a `SignedMessage` or `UnsignedMessage`,
    /// likely because the message did not contain the value.
    LookupError(CoveredComponent),
    /// Errors raised when an incoming message references an algorithm
    /// that isn't currently supported by this implementation. The subset
    /// of [registered IANA signature algorithms](https://www.iana.org/assignments/http-message-signature/http-message-signature.xhtml)
    /// implemented here is provided by `Algorithms` struct.
    UnsupportedAlgorithm(Algorithm),
    /// An attempt to resolve key identifier to a valid public key failed.
    /// This prevents message verification.
    NoSuchKey,
    /// The resolved key ID did not have the sufficient length to be parsed as
    /// a valid key for the algorithm chosen.
    InvalidKeyLength,
    /// The signature provided in `Signature` header was not long enough to be
    /// a valid signature for the algorithm chosen.
    InvalidSignatureLength,
    /// Verification of a parsed signature against a resolved key failed, indicating
    /// the signature was invalid.
    FailedToVerify(ed25519_dalek::SignatureError),
    /// A valid signature base must contain only ASCII characters; this error is thrown
    /// if that's not the case. This may be thrown if some of the headers included in
    /// covered components contained non-ASCII characters, for example. This will be thrown
    /// during both signing and verification, as both steps require constructing the signature
    /// base.
    NonAsciiContentFound,
    /// Signature bases are terminated with a line beginning with `@signature-params`. This error
    /// is thrown if the value of that line could not be converted into a structured field value.
    /// This is considered "impossible" as invalid values should not be present in the structure
    /// containing those values.
    SignatureParamsSerialization,
    /// A wrapper around `WebBotAuthError`
    WebBotAuth(WebBotAuthError),
}

impl core::fmt::Display for ImplementationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ImplementationError::ImpossibleSfvError(e) => {
                write!(f, "impossible structured field value error: {e}")
            }
            ImplementationError::ParsingError(s) => write!(f, "parsing error: {s}"),
            ImplementationError::LookupError(component) => {
                write!(f, "lookup error: component not found: {component:?}")
            }
            ImplementationError::UnsupportedAlgorithm(alg) => {
                write!(f, "unsupported algorithm: {alg:?}")
            }
            ImplementationError::NoSuchKey => write!(f, "no such key"),
            ImplementationError::InvalidKeyLength => write!(f, "invalid key length"),
            ImplementationError::InvalidSignatureLength => write!(f, "invalid signature length"),
            ImplementationError::FailedToVerify(e) => {
                write!(f, "signature verification failed: {e}")
            }
            ImplementationError::NonAsciiContentFound => {
                write!(f, "non-ASCII content found in signature base")
            }
            ImplementationError::SignatureParamsSerialization => {
                write!(f, "failed to serialize signature params")
            }
            ImplementationError::WebBotAuth(e) => write!(f, "web bot auth error: {e}"),
        }
    }
}

impl core::error::Error for ImplementationError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            ImplementationError::ImpossibleSfvError(e) => Some(e),
            ImplementationError::FailedToVerify(e) => Some(e),
            ImplementationError::WebBotAuth(e) => Some(e),
            _ => None,
        }
    }
}

/// Errors thrown when verifying a Web Bot Auth-signed message specifically.
#[derive(Debug)]
pub enum WebBotAuthError {
    /// Thrown when the signature is detected to be expired, using the `expires`
    /// and `creates` method.
    SignatureIsExpired,
}

impl core::fmt::Display for WebBotAuthError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            WebBotAuthError::SignatureIsExpired => write!(f, "signature is expired"),
        }
    }
}

impl core::error::Error for WebBotAuthError {}

/// A verifier for Web Bot Auth messages specifically.
#[derive(Clone, Debug)]
pub struct WebBotAuthVerifier {
    message_verifier: MessageVerifier,
    /// List of valid `Signature-Agent` headers to try, if present.
    parsed_directories: Vec<SignatureAgentLink>,
}

/// The different types of URLs a `Signature-Agent` can have.
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum SignatureAgentLink {
    /// A data URL that was parsed into a JSON Web Key Set ahead of time.
    Inline(JSONWebKeySet),
    /// An external https:// or http:// URL that requires resolution into a JSON Web Key Set
    External(String),
}

impl WebBotAuthVerifier {
    /// Parse a message into a structure that is ready for verification against an
    /// external key with a suitable algorithm. If `alg` is not set, a default will
    /// be chosen from the `alg` parameter.
    ///
    /// # Errors
    ///
    /// Returns `ImplementationErrors` relevant to verifying and parsing.
    pub fn parse(message: &impl SignedMessage) -> Result<Self, ImplementationError> {
        let signature_agents = message.lookup_component(&CoveredComponent::HTTP(HTTPField {
            name: "signature-agent".to_string(),
            parameters: components::HTTPFieldParametersSet(vec![]),
        }));

        let message_verifier =
            MessageVerifier::parse(message, |(_, innerlist)| {
                innerlist.params.contains_key("keyid")
                    && innerlist.params.contains_key("tag")
                    && innerlist.params.contains_key("expires")
                    && innerlist.params.contains_key("created")
                    && innerlist
                        .params
                        .get("tag")
                        .and_then(|tag| tag.as_string())
                        .is_some_and(|tag| tag.as_str() == "web-bot-auth")
                    && (innerlist.items.iter().any(|item| {
                        *item == sfv::Item::new(sfv::StringRef::constant("@authority"))
                    }) || innerlist.items.iter().any(|item| {
                        *item == sfv::Item::new(sfv::StringRef::constant("@target-uri"))
                    }))
                    && (if !signature_agents.is_empty() {
                        innerlist.items.iter().any(|item| {
                            item.bare_item
                                .as_string()
                                .is_some_and(|i| i == sfv::StringRef::constant("signature-agent"))
                        })
                    } else {
                        true
                    })
            })?;

        let mut signature_agent_key: Option<String> = None;
        'outer_loop: for (component, _) in message_verifier.parsed.base.components.iter() {
            if let CoveredComponent::HTTP(HTTPField { name, parameters }) = component
                && name == "signature-agent"
            {
                for parameter in parameters.0.iter() {
                    if let HTTPFieldParameters::Key(key) = parameter {
                        signature_agent_key = Some(key.clone());
                        break 'outer_loop;
                    }
                }
            }
        }

        let parse_link = |link: &sfv::StringRef| {
            let link_str = link.as_str();
            if link_str.starts_with("https://") || link_str.starts_with("http://") {
                return Some(SignatureAgentLink::External(String::from(link_str)));
            }

            if let Ok(url) = DataUrl::process(link_str) {
                let mediatype = url.mime_type();
                if mediatype.type_ == "application"
                    && mediatype.subtype == "http-message-signatures-directory"
                    && let Ok((body, _)) = url.decode_to_vec()
                    && let Ok(jwks) = serde_json::from_slice::<JSONWebKeySet>(&body)
                {
                    return Some(SignatureAgentLink::Inline(jwks));
                }
            }

            None
        };

        let parsed_directories = match signature_agent_key {
            Some(key) => signature_agents
                .iter()
                .filter_map(|header| sfv::Parser::new(header).parse_dictionary().ok())
                .reduce(|mut acc, sig_agent| {
                    acc.extend(sig_agent);
                    acc
                })
                .ok_or(ImplementationError::ParsingError(
                    "Failed to parse `Signature-Agent` into valid sfv::Dictionary".to_string(),
                ))?
                .into_iter()
                .filter_map(|(label, listentry)| match listentry {
                    sfv::ListEntry::Item(item) => Some((label, item)),
                    sfv::ListEntry::InnerList(_) => None,
                })
                .filter_map(|(label, item)| {
                    if label.as_str() != key {
                        return None;
                    }
                    let as_string = item.bare_item.as_string();
                    as_string.and_then(parse_link)
                })
                .collect(),
            None => signature_agents
                .iter()
                .map(|header| {
                    sfv::Parser::new(header).parse_item().map_err(|e| {
                        ImplementationError::ParsingError(format!(
                            "Failed to parse `Signature-Agent` into valid sfv::Item: {e}"
                        ))
                    })
                })
                .collect::<Result<Vec<_>, _>>()?
                .iter()
                .flat_map(|item| {
                    let as_string = item.bare_item.as_string();
                    as_string.and_then(parse_link)
                })
                .collect(),
        };

        let web_bot_auth_verifier = Self {
            message_verifier,
            parsed_directories,
        };

        Ok(web_bot_auth_verifier)
    }

    /// Obtain list of Signature-Agents parsed and ready. This method is ideal for populating
    /// a keyring ahead of time at your discretion.
    pub fn get_signature_agents(&self) -> &Vec<SignatureAgentLink> {
        &self.parsed_directories
    }

    /// Verify the messsage, consuming the verifier in the process.
    /// If `key_id` is not supplied, a key ID to fetch the public key
    /// from `keyring` will be sourced from the `keyid` parameter
    /// within the message.
    pub fn verify(
        self,
        keyring: &KeyRing,
        key_id: Option<String>,
    ) -> Result<SignatureTiming, ImplementationError> {
        self.message_verifier.verify(keyring, key_id)
    }

    /// Retrieve the contents of the chosen signature and signature input label for
    /// verification.
    pub fn get_parsed_label(&self) -> &ParsedLabel {
        &self.message_verifier.parsed
    }
}

#[cfg(test)]
mod tests {

    use std::time::Duration;

    use components::DerivedComponent;
    use indexmap::IndexMap;

    use super::*;

    struct StandardTestVector {}

    impl SignedMessage for StandardTestVector {
        fn lookup_component(&self, name: &CoveredComponent) -> Vec<String> {
            match name {
                CoveredComponent::HTTP(HTTPField { name, .. }) => {
                    if name == "signature" {
                        return vec!["sig1=:uz2SAv+VIemw+Oo890bhYh6Xf5qZdLUgv6/PbiQfCFXcX/vt1A8Pf7OcgL2yUDUYXFtffNpkEr5W6dldqFrkDg==:".to_owned()];
                    }

                    if name == "signature-input" {
                        return vec![r#"sig1=("@authority");created=1735689600;keyid="poqkLGiymh_W0uP6PZFw-dvez3QJT5SolqXBCW38r0U";alg="ed25519";expires=1735693200;nonce="gubxywVx7hzbYKatLgzuKDllDAIXAkz41PydU7aOY7vT+Mb3GJNxW0qD4zJ+IOQ1NVtg+BNbTCRUMt1Ojr5BgA==";tag="web-bot-auth""#.to_owned()];
                    }
                    vec![]
                }
                CoveredComponent::Derived(DerivedComponent::Authority { .. }) => {
                    vec!["example.com".to_string()]
                }
                _ => vec![],
            }
        }
    }

    #[test]
    fn test_verifying_as_web_bot_auth() {
        let test = StandardTestVector {};
        let public_key: [u8; ed25519_dalek::PUBLIC_KEY_LENGTH] = [
            0x26, 0xb4, 0x0b, 0x8f, 0x93, 0xff, 0xf3, 0xd8, 0x97, 0x11, 0x2f, 0x7e, 0xbc, 0x58,
            0x2b, 0x23, 0x2d, 0xbd, 0x72, 0x51, 0x7d, 0x08, 0x2f, 0xe8, 0x3c, 0xfb, 0x30, 0xdd,
            0xce, 0x43, 0xd1, 0xbb,
        ];
        let mut keyring = KeyRing::default();
        keyring.import_raw(
            "poqkLGiymh_W0uP6PZFw-dvez3QJT5SolqXBCW38r0U".to_string(),
            Algorithm::Ed25519,
            public_key.to_vec(),
        );
        let verifier = WebBotAuthVerifier::parse(&test).unwrap();
        let advisory = verifier
            .get_parsed_label()
            .base
            .parameters
            .details
            .possibly_insecure(|_| false);
        // Since the expiry date is in the past.
        assert!(advisory.is_expired.unwrap_or(true));
        assert!(!advisory.nonce_is_invalid.unwrap_or(true));
        let timing = verifier.verify(&keyring, None).unwrap();

        assert!(timing.generation.as_nanos() > 0);
        assert!(timing.verification.as_nanos() > 0);
    }

    #[test]
    fn test_signing_then_verifying() {
        struct MyTest {
            signature_input: String,
            signature_header: String,
        }

        impl message_signatures::UnsignedMessage for MyTest {
            fn fetch_components_to_cover(&self) -> IndexMap<CoveredComponent, String> {
                IndexMap::from_iter([(
                    CoveredComponent::Derived(DerivedComponent::Authority { req: false }),
                    "example.com".to_string(),
                )])
            }

            fn register_header_contents(
                &mut self,
                signature_input: String,
                signature_header: String,
            ) {
                self.signature_input = format!("sig1={signature_input}");
                self.signature_header = format!("sig1={signature_header}");
            }
        }

        impl SignedMessage for MyTest {
            fn lookup_component(&self, name: &CoveredComponent) -> Vec<String> {
                match name {
                    CoveredComponent::HTTP(HTTPField { name, .. }) => {
                        if name == "signature" {
                            return vec![self.signature_header.clone()];
                        }

                        if name == "signature-input" {
                            return vec![self.signature_input.clone()];
                        }
                        vec![]
                    }
                    CoveredComponent::Derived(DerivedComponent::Authority { .. }) => {
                        vec!["example.com".to_string()]
                    }
                    _ => vec![],
                }
            }
        }

        let public_key: [u8; ed25519_dalek::PUBLIC_KEY_LENGTH] = [
            0x26, 0xb4, 0x0b, 0x8f, 0x93, 0xff, 0xf3, 0xd8, 0x97, 0x11, 0x2f, 0x7e, 0xbc, 0x58,
            0x2b, 0x23, 0x2d, 0xbd, 0x72, 0x51, 0x7d, 0x08, 0x2f, 0xe8, 0x3c, 0xfb, 0x30, 0xdd,
            0xce, 0x43, 0xd1, 0xbb,
        ];

        let private_key: [u8; ed25519_dalek::SECRET_KEY_LENGTH] = [
            0x9f, 0x83, 0x62, 0xf8, 0x7a, 0x48, 0x4a, 0x95, 0x4e, 0x6e, 0x74, 0x0c, 0x5b, 0x4c,
            0x0e, 0x84, 0x22, 0x91, 0x39, 0xa2, 0x0a, 0xa8, 0xab, 0x56, 0xff, 0x66, 0x58, 0x6f,
            0x6a, 0x7d, 0x29, 0xc5,
        ];

        let mut keyring = KeyRing::default();
        keyring.import_raw(
            "poqkLGiymh_W0uP6PZFw-dvez3QJT5SolqXBCW38r0U".to_string(),
            Algorithm::Ed25519,
            public_key.to_vec(),
        );

        let signer = message_signatures::MessageSigner {
            keyid: "poqkLGiymh_W0uP6PZFw-dvez3QJT5SolqXBCW38r0U".into(),
            nonce: "end-to-end-test".into(),
            tag: "web-bot-auth".into(),
        };

        let mut mytest = MyTest {
            signature_input: String::new(),
            signature_header: String::new(),
        };

        signer
            .generate_signature_headers_content(
                &mut mytest,
                Duration::from_secs(10),
                Algorithm::Ed25519,
                &private_key,
            )
            .unwrap();

        let verifier = WebBotAuthVerifier::parse(&mytest).unwrap();
        let advisory = verifier
            .get_parsed_label()
            .base
            .parameters
            .details
            .possibly_insecure(|_| false);
        assert!(!advisory.is_expired.unwrap_or(true));
        assert!(!advisory.nonce_is_invalid.unwrap_or(true));

        let timing = verifier.verify(&keyring, None).unwrap();
        assert!(timing.generation.as_nanos() > 0);
        assert!(timing.verification.as_nanos() > 0);
    }

    #[test]
    fn test_missing_tags_break_web_bot_auth() {
        struct MissingParametersTestVector {}

        impl SignedMessage for MissingParametersTestVector {
            fn lookup_component(&self, name: &CoveredComponent) -> Vec<String> {
                match name {
                    CoveredComponent::HTTP(HTTPField { name, .. }) => {
                        if name == "signature" {
                            return vec![
                                "sig1=:uz2SAv+VIemw+Oo890bhYh6Xf5qZdLUgv6/PbiQfCFXcX/vt1A8Pf7OcgL2yUDUYXFtffNpkEr5W6dldqFrkDg==:".to_owned()
                            ];
                        }

                        if name == "signature-input" {
                            return vec![r#"sig1=("@authority");created=1735689600;keyid="poqkLGiymh_W0uP6PZFw-dvez3QJT5SolqXBCW38r0U";alg="ed25519";expires=1735693200;nonce="gubxywVx7hzbYKatLgzuKDllDAIXAkz41PydU7aOY7vT+Mb3GJNxW0qD4zJ+IOQ1NVtg+BNbTCRUMt1Ojr5BgA==";tag="not-web-bot-auth""#.to_owned()];
                        }
                        vec![]
                    }
                    CoveredComponent::Derived(DerivedComponent::Authority { .. }) => {
                        vec!["example.com".to_string()]
                    }
                    _ => vec![],
                }
            }
        }

        let test = MissingParametersTestVector {};
        WebBotAuthVerifier::parse(&test).expect_err("This should not have parsed");
    }

    #[test]
    fn test_signature_agents_are_required_in_signature_input() {
        struct MissingParametersTestVector {}

        impl SignedMessage for MissingParametersTestVector {
            fn lookup_component(&self, name: &CoveredComponent) -> Vec<String> {
                match name {
                    CoveredComponent::HTTP(HTTPField { name, .. }) => {
                        if name == "signature" {
                            return vec!["sig1=:uz2SAv+VIemw+Oo890bhYh6Xf5qZdLUgv6/PbiQfCFXcX/vt1A8Pf7OcgL2yUDUYXFtffNpkEr5W6dldqFrkDg==:".to_owned()];
                        }

                        if name == "signature-input" {
                            return vec![r#"sig1=("@authority");created=1735689600;keyid="poqkLGiymh_W0uP6PZFw-dvez3QJT5SolqXBCW38r0U";alg="ed25519";expires=1735693200;nonce="gubxywVx7hzbYKatLgzuKDllDAIXAkz41PydU7aOY7vT+Mb3GJNxW0qD4zJ+IOQ1NVtg+BNbTCRUMt1Ojr5BgA==";tag="web-bot-auth""#.to_owned()];
                        }

                        if name == "signature-agent" {
                            return vec![String::from("\"https://myexample.com\"")];
                        }
                        vec![]
                    }
                    CoveredComponent::Derived(DerivedComponent::Authority { .. }) => {
                        vec!["example.com".to_string()]
                    }
                    _ => vec![],
                }
            }
        }

        let test = MissingParametersTestVector {};
        WebBotAuthVerifier::parse(&test).expect_err("This should not have parsed");
    }

    #[test]
    fn test_signature_agents_are_parsed_with_fallback() {
        struct StandardTestVector {}

        impl SignedMessage for StandardTestVector {
            fn lookup_component(&self, name: &CoveredComponent) -> Vec<String> {
                match name {
                    CoveredComponent::HTTP(HTTPField { name, .. }) => {
                        if name == "signature" {
                            return vec!["sig1=:3q7S1TtbrFhQhpcZ1gZwHPCFHTvdKXNY1xngkp6lyaqqqv3QZupwpu/wQG5a7qybnrj2vZYMeVKuWepm+rNkDw==:".to_owned()];
                        }

                        if name == "signature-input" {
                            return vec![r#"sig1=("@authority" "signature-agent");alg="ed25519";keyid="poqkLGiymh_W0uP6PZFw-dvez3QJT5SolqXBCW38r0U";nonce="ZO3/XMEZjrvSnLtAP9M7jK0WGQf3J+pbmQRUpKDhF9/jsNCWqUh2sq+TH4WTX3/GpNoSZUa8eNWMKqxWp2/c2g==";tag="web-bot-auth";created=1749331474;expires=1749331484"#.to_owned()];
                        }

                        if name == "signature-agent" {
                            return vec![
                                String::from("\"https://myexample.com\""),
                                String::from("\"https://myexample2.com\""),
                            ];
                        }
                        vec![]
                    }
                    CoveredComponent::Derived(DerivedComponent::Authority { .. }) => {
                        vec!["example.com".to_string()]
                    }
                    _ => vec![],
                }
            }
        }

        let public_key: [u8; ed25519_dalek::PUBLIC_KEY_LENGTH] = [
            0x26, 0xb4, 0x0b, 0x8f, 0x93, 0xff, 0xf3, 0xd8, 0x97, 0x11, 0x2f, 0x7e, 0xbc, 0x58,
            0x2b, 0x23, 0x2d, 0xbd, 0x72, 0x51, 0x7d, 0x08, 0x2f, 0xe8, 0x3c, 0xfb, 0x30, 0xdd,
            0xce, 0x43, 0xd1, 0xbb,
        ];
        let mut keyring = KeyRing::default();
        keyring.import_raw(
            "poqkLGiymh_W0uP6PZFw-dvez3QJT5SolqXBCW38r0U".to_string(),
            Algorithm::Ed25519,
            public_key.to_vec(),
        );

        let test = StandardTestVector {};
        let verifier = WebBotAuthVerifier::parse(&test).unwrap();
        assert_eq!(verifier.get_signature_agents().len(), 2);
        assert_eq!(
            verifier.get_signature_agents()[0],
            SignatureAgentLink::External("https://myexample.com".to_string())
        );
    }

    #[test]
    fn test_signature_agents_are_parsed_correctly() {
        struct StandardTestVector {}

        impl SignedMessage for StandardTestVector {
            fn lookup_component(&self, name: &CoveredComponent) -> Vec<String> {
                match name {
                    CoveredComponent::HTTP(HTTPField { name, .. }) => {
                        if name == "signature" {
                            return vec!["sig1=:3q7S1TtbrFhQhpcZ1gZwHPCFHTvdKXNY1xngkp6lyaqqqv3QZupwpu/wQG5a7qybnrj2vZYMeVKuWepm+rNkDw==:".to_owned()];
                        }

                        if name == "signature-input" {
                            return vec![r#"sig1=("@authority" "signature-agent";key="agent1");alg="ed25519";keyid="poqkLGiymh_W0uP6PZFw-dvez3QJT5SolqXBCW38r0U";nonce="ZO3/XMEZjrvSnLtAP9M7jK0WGQf3J+pbmQRUpKDhF9/jsNCWqUh2sq+TH4WTX3/GpNoSZUa8eNWMKqxWp2/c2g==";tag="web-bot-auth";created=1749331474;expires=1749331484"#.to_owned()];
                        }

                        if name == "signature-agent" {
                            return vec![
                                r#"agent1="https://myexample.com", agent2="https://example2.com""#
                                    .to_owned(),
                            ];
                        }
                        vec![]
                    }
                    CoveredComponent::Derived(DerivedComponent::Authority { .. }) => {
                        vec!["example.com".to_string()]
                    }
                    _ => vec![],
                }
            }
        }

        let public_key: [u8; ed25519_dalek::PUBLIC_KEY_LENGTH] = [
            0x26, 0xb4, 0x0b, 0x8f, 0x93, 0xff, 0xf3, 0xd8, 0x97, 0x11, 0x2f, 0x7e, 0xbc, 0x58,
            0x2b, 0x23, 0x2d, 0xbd, 0x72, 0x51, 0x7d, 0x08, 0x2f, 0xe8, 0x3c, 0xfb, 0x30, 0xdd,
            0xce, 0x43, 0xd1, 0xbb,
        ];
        let mut keyring = KeyRing::default();
        keyring.import_raw(
            "poqkLGiymh_W0uP6PZFw-dvez3QJT5SolqXBCW38r0U".to_string(),
            Algorithm::Ed25519,
            public_key.to_vec(),
        );

        let test = StandardTestVector {};
        let verifier = WebBotAuthVerifier::parse(&test).unwrap();

        assert_eq!(verifier.get_signature_agents().len(), 1);
        assert_eq!(
            verifier.get_signature_agents()[0],
            SignatureAgentLink::External("https://myexample.com".to_string())
        );
    }
}