Skip to main content

adk_auth/web_bot_auth/
verifier.rs

1//! Verifies Web Bot Auth request signatures. Spec 3.5 §7.3, A-I6.
2
3use std::sync::Arc;
4use std::time::Duration;
5
6use adk_core::{Clock, SystemClock};
7use chrono::{DateTime, Utc};
8use serde::{Deserialize, Serialize};
9
10use super::directory::{DirectoryCache, DirectoryCachePolicy, KeyDirectorySource};
11use super::keys::{RFC9421_TEST_KEY_X, verify_ed25519};
12use super::message::{ComponentId, RequestHead, SignatureInput};
13use super::structured::{BareItem, Dictionary, Item, ListEntry};
14use super::{
15    SIGNATURE, SIGNATURE_AGENT, SIGNATURE_INPUT, WEB_BOT_AUTH_TAG, WebBotAuthError, combined_field,
16};
17
18/// At most this many Web Bot Auth signatures are checked per request.
19const MAX_SIGNATURES: usize = 8;
20
21/// A requester whose Web Bot Auth signature verified against the key directory its
22/// `Signature-Agent` names. Spec 3.5 §7.3.
23///
24/// `id` is `wba:{directory origin}#{key thumbprint}`: the directory origin is what the
25/// requester's identity rests on, and the thumbprint is the key that signed. The trust tier it
26/// earns is the edge's decision, not this type's.
27///
28/// # Example
29///
30/// ```rust
31/// use adk_auth::web_bot_auth::VerifiedRequester;
32/// use chrono::{TimeZone, Utc};
33///
34/// let requester = VerifiedRequester::new(
35///     "https://bot.example",
36///     "poqkLGiymh_W0uP6PZFw-dvez3QJT5SolqXBCW38r0U",
37///     Utc.timestamp_opt(1_735_689_600, 0).unwrap(),
38///     Utc.timestamp_opt(1_735_689_900, 0).unwrap(),
39/// );
40/// assert_eq!(requester.id, "wba:https://bot.example#poqkLGiymh_W0uP6PZFw-dvez3QJT5SolqXBCW38r0U");
41/// ```
42#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
43#[serde(rename_all = "camelCase")]
44pub struct VerifiedRequester {
45    /// `wba:{directory origin}#{key thumbprint}`.
46    pub id: String,
47    /// The ASCII-serialised origin of the key directory.
48    pub directory_origin: String,
49    /// The JWK thumbprint of the key that signed (RFC 7638, RFC 8037).
50    pub key_thumbprint: String,
51    /// The signature's `created` time.
52    pub created: DateTime<Utc>,
53    /// The signature's `expires` time.
54    pub expires: DateTime<Utc>,
55}
56
57impl VerifiedRequester {
58    /// Creates a requester, deriving `id` from the origin and thumbprint.
59    pub fn new(
60        directory_origin: impl Into<String>,
61        key_thumbprint: impl Into<String>,
62        created: DateTime<Utc>,
63        expires: DateTime<Utc>,
64    ) -> Self {
65        let directory_origin = directory_origin.into();
66        let key_thumbprint = key_thumbprint.into();
67        Self {
68            id: format!("wba:{directory_origin}#{key_thumbprint}"),
69            directory_origin,
70            key_thumbprint,
71            created,
72            expires,
73        }
74    }
75}
76
77/// Verifies Web Bot Auth signatures ([RFC 9421] with draft-ietf-webbotauth-httpsig-protocol-00)
78/// on incoming requests. Spec 3.5 §7.3.
79///
80/// For each signature tagged `web-bot-auth`, the verifier requires `created`, `expires`,
81/// `keyid` and, when present, `alg="ed25519"`; requires `@authority` or `@target-uri` and the
82/// signature's `Signature-Agent` member to be covered (draft §5.2, §5.2.1), plus any components
83/// added with [`require_component`](HttpSignatureVerifierBuilder::require_component); accepts
84/// `created` and `expires` within the clock skew (60 s by default); resolves the member's origin to
85/// its key directory through the cache; selects the key whose thumbprint is `keyid`, keyed on
86/// the (origin, key) pair (draft §5.4); and verifies the Ed25519 signature over the
87/// recomputed signature base.
88///
89/// A request without a Web Bot Auth signature yields `Ok(None)`: no identity, whatever its
90/// `User-Agent` claims (draft §6.11). When a request carries several, the first in
91/// `Signature-Input` order that verifies is returned.
92///
93/// [RFC 9421]: https://www.rfc-editor.org/rfc/rfc9421
94///
95/// # Example
96///
97/// ```rust
98/// use std::sync::Arc;
99/// use adk_auth::web_bot_auth::{
100///     Ed25519SigningKey, HttpSignatureSigner, HttpSignatureVerifier, InMemoryKeyDirectorySource,
101///     KeyDirectory,
102/// };
103///
104/// # #[tokio::main(flavor = "current_thread")]
105/// # async fn main() {
106/// let key = Arc::new(Ed25519SigningKey::generate().unwrap());
107/// let directories = Arc::new(InMemoryKeyDirectorySource::new());
108/// directories.insert("https://bot.example", KeyDirectory::from_keys([key.as_ref()]), None).await;
109///
110/// let signer = HttpSignatureSigner::builder(Arc::clone(&key), "https://bot.example").build().unwrap();
111/// let mut request = http::Request::get("https://shop.example/catalog").body(()).unwrap();
112/// signer.sign_request(&mut request).unwrap();
113///
114/// let verifier = HttpSignatureVerifier::builder(directories).build();
115/// let requester = verifier.verify_request(&request).await.unwrap().unwrap();
116/// assert_eq!(requester.id, format!("wba:https://bot.example#{}", key.thumbprint()));
117///
118/// let unsigned = http::Request::get("https://shop.example/").header("user-agent", "GPTBot").body(()).unwrap();
119/// assert!(verifier.verify_request(&unsigned).await.unwrap().is_none());
120/// # }
121/// ```
122#[derive(Debug)]
123pub struct HttpSignatureVerifier {
124    cache: DirectoryCache,
125    clock: Arc<dyn Clock>,
126    max_skew: Duration,
127    max_lifetime: Option<Duration>,
128    required: Vec<ComponentId>,
129    default_scheme: String,
130    allow_test_keys: bool,
131}
132
133impl HttpSignatureVerifier {
134    /// Starts a builder resolving directories through `source`.
135    pub fn builder(source: Arc<dyn KeyDirectorySource>) -> HttpSignatureVerifierBuilder {
136        HttpSignatureVerifierBuilder {
137            source,
138            clock: Arc::new(SystemClock),
139            cache_policy: DirectoryCachePolicy::default(),
140            max_skew: Duration::from_secs(60),
141            max_lifetime: Some(Duration::from_secs(24 * 60 * 60)),
142            required: Vec::new(),
143            default_scheme: "https".to_string(),
144            allow_test_keys: false,
145        }
146    }
147
148    /// Verifies an [`http::Request`], reading the scheme of an origin-form URI from the
149    /// builder's [`default_scheme`](HttpSignatureVerifierBuilder::default_scheme).
150    ///
151    /// # Errors
152    ///
153    /// As [`verify`](Self::verify).
154    pub async fn verify_request<B>(
155        &self,
156        request: &http::Request<B>,
157    ) -> Result<Option<VerifiedRequester>, WebBotAuthError> {
158        self.verify(RequestHead::from_request(request).with_default_scheme(&self.default_scheme))
159            .await
160    }
161
162    /// Verifies the Web Bot Auth signatures on a request.
163    ///
164    /// Returns `Ok(None)` when the request carries no signature tagged `web-bot-auth`.
165    ///
166    /// # Errors
167    ///
168    /// Returns the first signature's error when no signature verifies.
169    /// [`WebBotAuthError::is_unverified`] tells a signature whose key material was unavailable
170    /// from one that failed a check.
171    pub async fn verify(
172        &self,
173        head: RequestHead<'_>,
174    ) -> Result<Option<VerifiedRequester>, WebBotAuthError> {
175        let headers = head.headers();
176        let combined = |name: &str| combined_field(headers, name);
177        let inputs = combined(SIGNATURE_INPUT)?;
178        let signatures = combined(SIGNATURE)?;
179        let (inputs, signatures) = match (inputs, signatures) {
180            (None, None) => return Ok(None),
181            (Some(inputs), Some(signatures)) => (inputs, signatures),
182            (Some(_), None) | (None, Some(_)) => {
183                return Err(WebBotAuthError::MalformedField {
184                    field: SIGNATURE.to_string(),
185                    reason: "Signature and Signature-Input must appear together".into(),
186                });
187            }
188        };
189        let inputs = SignatureInput::parse_field(&inputs)?;
190        let signatures = Dictionary::parse_unique(&signatures).map_err(|e| {
191            WebBotAuthError::MalformedField { field: SIGNATURE.to_string(), reason: e.to_string() }
192        })?;
193        let agent_field = combined(SIGNATURE_AGENT)?;
194        let tagged: Vec<_> = inputs
195            .iter()
196            .filter(|(_, input)| input.tag() == Some(WEB_BOT_AUTH_TAG))
197            .take(MAX_SIGNATURES)
198            .collect();
199        if tagged.is_empty() {
200            return Ok(None);
201        }
202        let now = self.clock.now().timestamp();
203        let mut first_error = None;
204        for (label, input) in tagged {
205            let signature = match signatures.get(label) {
206                Some(ListEntry::Item(Item {
207                    bare_item: BareItem::ByteSequence(bytes), ..
208                })) => bytes.as_slice(),
209                Some(_) | None => {
210                    first_error.get_or_insert(WebBotAuthError::MalformedField {
211                        field: SIGNATURE.to_string(),
212                        reason: format!(
213                            "no byte-sequence member `{label}` matches Signature-Input"
214                        ),
215                    });
216                    continue;
217                }
218            };
219            match self.verify_one(&head, label, input, signature, agent_field.as_deref(), now).await
220            {
221                Ok(requester) => {
222                    tracing::debug!(requester.id = %requester.id, signature.label = %label, "web bot auth signature verified");
223                    return Ok(Some(requester));
224                }
225                Err(error) => {
226                    tracing::debug!(signature.label = %label, error = %error, "web bot auth signature rejected");
227                    first_error.get_or_insert(error);
228                }
229            }
230        }
231        Err(first_error.unwrap_or_else(|| WebBotAuthError::MalformedField {
232            field: SIGNATURE.to_string(),
233            reason: "no signature could be checked".into(),
234        }))
235    }
236
237    async fn verify_one(
238        &self,
239        head: &RequestHead<'_>,
240        label: &str,
241        input: &SignatureInput,
242        signature: &[u8],
243        agent_field: Option<&str>,
244        now: i64,
245    ) -> Result<VerifiedRequester, WebBotAuthError> {
246        let invalid = |parameter: &str, reason: &str| WebBotAuthError::InvalidParameter {
247            label: label.to_string(),
248            parameter: parameter.to_string(),
249            reason: reason.to_string(),
250        };
251        if let Some(alg) = input.params.get("alg")
252            && alg.as_str() != Some("ed25519")
253        {
254            return Err(WebBotAuthError::UnsupportedAlgorithm {
255                label: label.to_string(),
256                alg: alg.serialize().unwrap_or_default(),
257            });
258        }
259        let created =
260            input.created().ok_or_else(|| invalid("created", "missing or not an integer"))?;
261        let expires =
262            input.expires().ok_or_else(|| invalid("expires", "missing or not an integer"))?;
263        let keyid = input.keyid().ok_or_else(|| invalid("keyid", "missing or not a string"))?;
264        if expires < created {
265            return Err(invalid("expires", "precedes created"));
266        }
267
268        let covers_target = input.components.iter().any(|c| {
269            (c.name() == "@authority" || c.name() == "@target-uri") && c.params().is_empty()
270        });
271        if !covers_target {
272            return Err(WebBotAuthError::MissingComponent {
273                label: label.to_string(),
274                component: "@authority or @target-uri".into(),
275            });
276        }
277        if let Some(missing) = self.required.iter().find(|c| !input.covers(c)) {
278            return Err(WebBotAuthError::MissingComponent {
279                label: label.to_string(),
280                component: missing.serialize().unwrap_or_else(|_| missing.name().to_string()),
281            });
282        }
283        let agent = agent_component(label, input)?;
284
285        let skew = i64::try_from(self.max_skew.as_secs()).unwrap_or(i64::MAX);
286        if created > now.saturating_add(skew) {
287            return Err(WebBotAuthError::NotYetValid { label: label.to_string(), created, now });
288        }
289        if now > expires.saturating_add(skew) {
290            return Err(WebBotAuthError::Expired { label: label.to_string(), expires, now });
291        }
292        if let Some(max) = self.max_lifetime
293            && (expires - created).unsigned_abs() > max.as_secs()
294        {
295            return Err(WebBotAuthError::LifetimeTooLong {
296                label: label.to_string(),
297                lifetime_secs: expires - created,
298                max_secs: max.as_secs(),
299            });
300        }
301        if signature.len() != 64 {
302            return Err(WebBotAuthError::BadSignature { label: label.to_string() });
303        }
304
305        let origin = agent_origin(label, agent, agent_field)?;
306        // Building the base first rejects a request that cannot verify before any fetch.
307        let base = head.signature_base(input)?;
308        let key = self.cache.key(&origin, keyid).await?;
309        if !self.allow_test_keys && key.x == RFC9421_TEST_KEY_X {
310            return Err(WebBotAuthError::TestKey { keyid: keyid.to_string() });
311        }
312        if !key.is_current(now) {
313            return Err(WebBotAuthError::KeyNotCurrent { origin, keyid: keyid.to_string() });
314        }
315        let public_key = key.public_key()?;
316        if !verify_ed25519(&public_key, base.as_bytes(), signature) {
317            return Err(WebBotAuthError::BadSignature { label: label.to_string() });
318        }
319        let timestamp = |value: i64, parameter: &str| {
320            DateTime::from_timestamp(value, 0).ok_or_else(|| invalid(parameter, "out of range"))
321        };
322        Ok(VerifiedRequester::new(
323            origin,
324            keyid,
325            timestamp(created, "created")?,
326            timestamp(expires, "expires")?,
327        ))
328    }
329}
330
331/// The `Signature-Agent` component a signature covers: its only one, or the one keyed to its
332/// label when it covers several (draft §5.2.1–§5.2.2).
333fn agent_component<'a>(
334    label: &str,
335    input: &'a SignatureInput,
336) -> Result<&'a ComponentId, WebBotAuthError> {
337    let covered: Vec<_> = input.components.iter().filter(|c| c.name() == SIGNATURE_AGENT).collect();
338    let chosen = match covered.as_slice() {
339        [only] => Some(*only),
340        _ => covered
341            .iter()
342            .copied()
343            .find(|c| c.params().get("key").and_then(BareItem::as_str) == Some(label)),
344    };
345    chosen.ok_or_else(|| WebBotAuthError::MissingComponent {
346        label: label.to_string(),
347        component: format!("\"signature-agent\";key=\"{label}\""),
348    })
349}
350
351/// The directory origin a covered `Signature-Agent` member names (draft §5.2.1, §5.5).
352fn agent_origin(
353    label: &str,
354    component: &ComponentId,
355    field: Option<&str>,
356) -> Result<String, WebBotAuthError> {
357    let unusable = |reason: String| WebBotAuthError::InvalidSignatureAgent {
358        label: label.to_string(),
359        reason,
360    };
361    let field = field.ok_or_else(|| unusable("the request has no Signature-Agent field".into()))?;
362    let malformed = |e: super::structured::StructuredFieldError| WebBotAuthError::MalformedField {
363        field: SIGNATURE_AGENT.to_string(),
364        reason: e.to_string(),
365    };
366    let member = match component.params().get("key") {
367        Some(BareItem::String(key)) => {
368            match Dictionary::parse(field).map_err(malformed)?.get(key) {
369                Some(ListEntry::Item(item)) => item.clone(),
370                Some(ListEntry::InnerList(_)) => {
371                    return Err(unusable(format!("member `{key}` is not a string")));
372                }
373                None => return Err(unusable(format!("the field has no member `{key}`"))),
374            }
375        }
376        Some(_) => return Err(unusable("the `key` parameter is not a string".into())),
377        // The draft's legacy form: the whole field is one String (§5.2.1, Appendix E.2.2).
378        None => Item::parse(field).map_err(malformed)?,
379    };
380    let value =
381        member.bare_item.as_str().ok_or_else(|| unusable("the member is not a string".into()))?;
382    match member.params.get("type") {
383        None => {}
384        Some(kind) if kind.as_token() == Some("directory") => {}
385        Some(kind) => {
386            return Err(WebBotAuthError::UnsupportedDiscovery {
387                label: label.to_string(),
388                kind: kind.serialize().unwrap_or_default(),
389            });
390        }
391    }
392    let url = reqwest::Url::parse(value).map_err(|e| unusable(format!("`{value}`: {e}")))?;
393    let is_origin = matches!(url.scheme(), "https" | "http")
394        && url.host_str().is_some()
395        && url.username().is_empty()
396        && url.password().is_none()
397        && url.path() == "/"
398        && url.query().is_none()
399        && url.fragment().is_none();
400    if !is_origin {
401        return Err(unusable(format!("`{value}` is not an http(s) origin")));
402    }
403    Ok(url.origin().ascii_serialization())
404}
405
406/// Builds an [`HttpSignatureVerifier`].
407pub struct HttpSignatureVerifierBuilder {
408    source: Arc<dyn KeyDirectorySource>,
409    clock: Arc<dyn Clock>,
410    cache_policy: DirectoryCachePolicy,
411    max_skew: Duration,
412    max_lifetime: Option<Duration>,
413    required: Vec<ComponentId>,
414    default_scheme: String,
415    allow_test_keys: bool,
416}
417
418impl std::fmt::Debug for HttpSignatureVerifierBuilder {
419    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
420        f.debug_struct("HttpSignatureVerifierBuilder")
421            .field("max_skew", &self.max_skew)
422            .field("max_lifetime", &self.max_lifetime)
423            .finish_non_exhaustive()
424    }
425}
426
427impl HttpSignatureVerifierBuilder {
428    /// Sets the clock that `created`, `expires` and cache lifetimes are checked against.
429    pub fn clock(mut self, clock: Arc<dyn Clock>) -> Self {
430        self.clock = clock;
431        self
432    }
433
434    /// Sets the allowed clock skew for `created` and `expires`. Default 60 s.
435    pub fn max_skew(mut self, skew: Duration) -> Self {
436        self.max_skew = skew;
437        self
438    }
439
440    /// Sets the longest `expires - created` accepted, or `None` for no limit. Default 24 h,
441    /// the longest expiry the draft recommends (§5.2).
442    pub fn max_signature_lifetime(mut self, lifetime: Option<Duration>) -> Self {
443        self.max_lifetime = lifetime;
444        self
445    }
446
447    /// Requires signatures to also cover `component`, such as `@method` or `@path`.
448    pub fn require_component(mut self, component: ComponentId) -> Self {
449        self.required.push(component);
450        self
451    }
452
453    /// Sets the directory cache policy.
454    pub fn cache_policy(mut self, policy: DirectoryCachePolicy) -> Self {
455        self.cache_policy = policy;
456        self
457    }
458
459    /// Sets the scheme of requests whose URI carries none. Default `https`.
460    pub fn default_scheme(mut self, scheme: impl Into<String>) -> Self {
461        self.default_scheme = scheme.into();
462        self
463    }
464
465    /// Accepts the RFC 9421 Appendix B.1.4 test key, which is rejected by default (draft §6.8).
466    /// For test vectors only.
467    pub fn allow_test_keys(mut self, allow: bool) -> Self {
468        self.allow_test_keys = allow;
469        self
470    }
471
472    /// Builds the verifier.
473    pub fn build(self) -> HttpSignatureVerifier {
474        HttpSignatureVerifier {
475            cache: DirectoryCache::new(self.source, self.cache_policy, Arc::clone(&self.clock)),
476            clock: self.clock,
477            max_skew: self.max_skew,
478            max_lifetime: self.max_lifetime,
479            required: self.required,
480            default_scheme: self.default_scheme,
481            allow_test_keys: self.allow_test_keys,
482        }
483    }
484}
485
486#[cfg(test)]
487mod tests {
488    use super::*;
489    use crate::web_bot_auth::InMemoryKeyDirectorySource;
490
491    #[test]
492    fn builder_defaults_match_spec_3_5_section_7_3() {
493        let verifier =
494            HttpSignatureVerifier::builder(Arc::new(InMemoryKeyDirectorySource::new())).build();
495        assert_eq!(verifier.max_skew, Duration::from_secs(60));
496        assert_eq!(verifier.max_lifetime, Some(Duration::from_secs(86_400)));
497        assert_eq!(verifier.default_scheme, "https");
498        assert!(!verifier.allow_test_keys);
499        assert!(verifier.required.is_empty());
500    }
501}