Skip to main content

webhook_verify/core/
headers.rs

1//! The [`HeaderMap`] abstraction: lets `verify()` work against any framework's
2//! header representation.
3
4use alloc::collections::BTreeMap;
5use alloc::string::String;
6use alloc::vec::Vec;
7#[cfg(feature = "std")]
8use std::collections::HashMap;
9
10/// Case-insensitive, read-only header lookup.
11///
12/// Returns the value of the *first* header matching `name` (ASCII
13/// case-insensitively), or `None` if absent.
14///
15/// # Ambiguity contract
16///
17/// Per `spec.md` §4.4, a request whose signature header appears multiple times
18/// with *different* values is ambiguous and must be rejected — but detection of
19/// duplicates belongs to the caller/adapter layer, since this trait exposes
20/// only first-match lookup. Framework adapters are expected to reject
21/// duplicated signature headers before calling [`crate::verify()`].
22///
23/// # `HashMap` caveat
24///
25/// For [`HashMap`] the inherent exact-case `get` shadows this trait method in
26/// method-call position. Pass the map to `HeaderMap::get(&map, name)` to get
27/// the case-insensitive lookup this crate relies on.
28///
29/// # `BTreeMap` caveat
30///
31/// For [`BTreeMap`] the inherent exact-case `get` shadows this trait method in
32/// method-call position. Pass the map to `HeaderMap::get(&map, name)` to get
33/// the case-insensitive lookup this crate relies on.
34///
35/// # Slice caveat
36///
37/// A [`slice`] also has an inherent `get` (indexing by `usize`) that shadows
38/// this trait method in method-call position. The slices the impls below cover
39/// (`[(&str, &str)]` and `[(String, String)]`) are usually passed as a `&[T]`
40/// to [`crate::verify()`], where unsized coercion selects the trait impl —
41/// there is no ambiguity in that position. Method-call syntax on the slice
42/// itself behaves like the maps above: use `HeaderMap::get(&slice, name)`.
43///
44/// # `http::HeaderMap` support
45///
46/// Behind the `http` feature this trait is implemented for
47/// `http::HeaderMap`, so requests from any framework built on the `http`
48/// crate (axum, tower, hyper) verify without copying headers. Lookup uses
49/// that type's own first-value-wins, case-insensitive semantics; a value
50/// that is not visible ASCII (which `http` permits but this crate cannot
51/// treat as a signature) is reported as absent, failing closed downstream
52/// as a missing header.
53pub trait HeaderMap {
54    /// Case-insensitive lookup of a single header value.
55    fn get(&self, name: &str) -> Option<&str>;
56}
57
58impl HeaderMap for Vec<(String, String)> {
59    fn get(&self, name: &str) -> Option<&str> {
60        self.iter()
61            .find(|(k, _)| k.eq_ignore_ascii_case(name))
62            .map(|(_, v)| v.as_str())
63    }
64}
65
66impl<const N: usize> HeaderMap for [(String, String); N] {
67    fn get(&self, name: &str) -> Option<&str> {
68        self.iter()
69            .find(|(k, _)| k.eq_ignore_ascii_case(name))
70            .map(|(_, v)| v.as_str())
71    }
72}
73
74impl<const N: usize> HeaderMap for [(&str, &str); N] {
75    fn get(&self, name: &str) -> Option<&str> {
76        self.iter()
77            .find(|(k, _)| k.eq_ignore_ascii_case(name))
78            .map(|(_, v)| *v)
79    }
80}
81
82impl HeaderMap for Vec<(&str, &str)> {
83    fn get(&self, name: &str) -> Option<&str> {
84        self.iter()
85            .find(|(k, _)| k.eq_ignore_ascii_case(name))
86            .map(|(_, v)| *v)
87    }
88}
89
90/// Borrowed slice of str tuples — covers subsections of a header table
91/// (`&vec[..]`, `&array[1..]`, a function parameter that hands you `&[..]`)
92/// without an owning allocation alongside the array impl.
93impl HeaderMap for [(&str, &str)] {
94    fn get(&self, name: &str) -> Option<&str> {
95        self.iter()
96            .find(|(k, _)| k.eq_ignore_ascii_case(name))
97            .map(|(_, v)| *v)
98    }
99}
100
101/// Borrowed slice of owned strings, the unsized counterpart of the
102/// `[(String, String); N]` array impl.
103impl HeaderMap for [(String, String)] {
104    fn get(&self, name: &str) -> Option<&str> {
105        self.iter()
106            .find(|(k, _)| k.eq_ignore_ascii_case(name))
107            .map(|(_, v)| v.as_str())
108    }
109}
110
111impl HeaderMap for BTreeMap<String, String> {
112    fn get(&self, name: &str) -> Option<&str> {
113        // Keys may differ in case from the canonical names providers document,
114        // so exact-key lookup is not enough.
115        self.iter()
116            .find(|(k, _)| k.eq_ignore_ascii_case(name))
117            .map(|(_, v)| v.as_str())
118    }
119}
120
121#[cfg(feature = "std")]
122impl HeaderMap for HashMap<String, String> {
123    fn get(&self, name: &str) -> Option<&str> {
124        self.iter()
125            .find(|(k, _)| k.eq_ignore_ascii_case(name))
126            .map(|(_, v)| v.as_str())
127    }
128}
129
130#[cfg(feature = "http")]
131impl HeaderMap for ::http::HeaderMap {
132    fn get(&self, name: &str) -> Option<&str> {
133        // `HeaderName::from_bytes` normalizes to lowercase and rejects names
134        // with invalid bytes, so an unparseable lookup name is simply a miss.
135        // The inherent `get` (reached via UFCS with the typed key) is
136        // case-insensitive per HTTP semantics and returns the first value
137        // when several are present. Duplicate *detection* stays the
138        // adapter's job — see the trait's ambiguity contract.
139        let key = ::http::header::HeaderName::from_bytes(name.as_bytes()).ok()?;
140        let value = ::http::HeaderMap::get(self, &key)?;
141        value.to_str().ok()
142    }
143}
144
145#[cfg(test)]
146mod tests {
147    use std::collections::{BTreeMap, HashMap};
148
149    use super::HeaderMap;
150
151    #[test]
152    fn lookup_is_ascii_case_insensitive() {
153        let headers = vec![("X-Hub-Signature-256".to_string(), "sha256=ab".to_string())];
154        assert_eq!(headers.get("x-hub-signature-256"), Some("sha256=ab"));
155        assert_eq!(headers.get("X-HUB-SIGNATURE-256"), Some("sha256=ab"));
156        assert_eq!(headers.get("x-hub-signature-1"), None);
157    }
158
159    #[test]
160    fn first_match_wins() {
161        let headers = [
162            ("a".to_string(), "first".to_string()),
163            ("A".to_string(), "second".to_string()),
164        ];
165        assert_eq!(headers.get("A"), Some("first"));
166    }
167
168    #[cfg(feature = "std")]
169    #[test]
170    fn hash_map_is_case_insensitive() {
171        let mut headers = HashMap::new();
172        headers.insert("Webhook-Signature".to_string(), "v1,aa".to_string());
173        assert_eq!(HeaderMap::get(&headers, "webhook-signature"), Some("v1,aa"));
174        assert_eq!(HeaderMap::get(&headers, "WEBHOOK-SIGNATURE"), Some("v1,aa"));
175        assert_eq!(HeaderMap::get(&headers, "missing"), None);
176    }
177
178    #[test]
179    fn btree_map_is_case_insensitive() {
180        let mut headers = BTreeMap::new();
181        headers.insert("Webhook-Signature".to_string(), "v1,aa".to_string());
182        // Note: `headers.get(..)` would resolve to BTreeMap's *inherent* exact-key
183        // lookup, which shadows the trait method in method-call position; go
184        // through the trait explicitly.
185        assert_eq!(HeaderMap::get(&headers, "webhook-signature"), Some("v1,aa"));
186    }
187
188    #[test]
189    fn str_tuple_arrays_work() {
190        let headers = [("X-Slack-Signature", "v0=ff")];
191        assert_eq!(headers.get("x-slack-signature"), Some("v0=ff"));
192    }
193
194    #[test]
195    fn str_tuple_vecs_work() {
196        // Dynamically-built header lists of static strings — the `Vec`
197        // counterpart of the fixed array form (spec.md §2).
198        let mut headers: Vec<(&str, &str)> = vec![("X-Slack-Signature", "v0=ff")];
199        headers.push(("Host", "example.com"));
200        assert_eq!(
201            headers.get("x-slack-signature"),
202            Some("v0=ff"),
203            "case-insensitive lookup on the str-tuple Vec"
204        );
205        assert_eq!(headers.get("MISSING"), None);
206    }
207
208    // --- borrowed slices ([(&str, &str)] and [(String, String)]) ------------
209
210    #[test]
211    fn str_tuple_slices_work() {
212        // A bare `&[(&str, &str)]` — the type a read-only header table, a
213        // subslice (`&vec[..]` / `&array[1..]`), or an argument slice yields.
214        // Method-call `get` would hit the slice's inherent usize-index; go
215        // through the trait explicitly (documented caveat).
216        let table: &[(&str, &str)] = &[("Host", "example.com"), ("X-Slack-Signature", "v0=ff")];
217        assert_eq!(HeaderMap::get(table, "x-slack-signature"), Some("v0=ff"));
218        assert_eq!(HeaderMap::get(table, "X-SLACK-SIGNATURE"), Some("v0=ff"));
219        assert_eq!(HeaderMap::get(table, "MISSING"), None);
220    }
221
222    #[test]
223    fn string_tuple_slices_work() {
224        let table: &[(String, String)] = &[
225            ("X-Hub-Signature-256".to_string(), "sha256=ab".to_string()),
226            ("content-type".to_string(), "application/json".to_string()),
227        ];
228        assert_eq!(
229            HeaderMap::get(table, "x-hub-signature-256"),
230            Some("sha256=ab")
231        );
232        assert_eq!(
233            HeaderMap::get(table, "Content-Type"),
234            Some("application/json")
235        );
236        assert_eq!(HeaderMap::get(table, "MISSING"), None);
237    }
238
239    #[test]
240    fn subslices_of_header_tables_work() {
241        // `&vec[..]` coerces to a `[(&str, &str)]` slice; a mid-table window
242        // must look the same as the raw table would.
243        let vec_headers = vec![
244            ("Host", "example.com"),
245            ("X-Slack-Signature", "v0=ff"),
246            ("x-slack-request-timestamp", "1531420618"),
247        ];
248        let whole: &[(&str, &str)] = &vec_headers;
249        assert_eq!(HeaderMap::get(whole, "x-slack-signature"), Some("v0=ff"));
250
251        let window: &[(&str, &str)] = &vec_headers[1..];
252        assert_eq!(HeaderMap::get(window, "x-slack-signature"), Some("v0=ff"));
253        assert_eq!(HeaderMap::get(window, "Host"), None);
254        assert_eq!(
255            HeaderMap::get(window, "x-slack-request-timestamp"),
256            Some("1531420618")
257        );
258    }
259
260    #[cfg(feature = "http")]
261    #[test]
262    fn slices_verify_end_to_end() {
263        // The same GitHub vector passed as a plain slice reaches the same
264        // result as through the Vec/array forms.
265        use crate::{Provider, Secret, verify};
266
267        let result = verify(
268            Provider::GitHub,
269            &[(
270                "X-Hub-Signature-256",
271                "sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17",
272            )],
273            b"Hello, World!",
274            &Secret::new("It's a Secret to Everybody"),
275            Default::default(),
276        );
277        assert_eq!(result, Ok(()));
278    }
279
280    // --- `http::HeaderMap` (feature = "http") ---------------------------------
281
282    #[cfg(feature = "http")]
283    mod http_header_map {
284        use super::HeaderMap;
285        use crate::{Provider, Secret, verify};
286
287        /// GitHub's documented example vector
288        /// (<https://docs.github.com/en/webhooks/using-webhooks/validating-webhook-deliveries>),
289        /// same one used in the crate-level docs.
290        fn github_headers() -> ::http::HeaderMap {
291            let mut headers = ::http::HeaderMap::new();
292            headers.insert(
293                "X-Hub-Signature-256",
294                ::http::HeaderValue::from_static(
295                    "sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17",
296                ),
297            );
298            headers
299        }
300
301        #[test]
302        fn lookup_is_ascii_case_insensitive() {
303            let headers = github_headers();
304            assert_eq!(
305                HeaderMap::get(&headers, "x-hub-signature-256"),
306                Some("sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17")
307            );
308            assert_eq!(
309                HeaderMap::get(&headers, "X-HUB-SIGNATURE-256"),
310                Some("sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17")
311            );
312            assert_eq!(headers.get("x-hub-signature-1"), None);
313        }
314
315        #[test]
316        fn first_value_wins_for_multivalued_headers() {
317            let mut headers = ::http::HeaderMap::new();
318            headers.append(
319                "X-Slack-Signature",
320                ::http::HeaderValue::from_static("v0=first"),
321            );
322            headers.append(
323                "X-Slack-Signature",
324                ::http::HeaderValue::from_static("v0=second"),
325            );
326            assert_eq!(
327                HeaderMap::get(&headers, "X-Slack-Signature"),
328                Some("v0=first")
329            );
330        }
331
332        #[test]
333        fn unparseable_lookup_name_is_a_miss_not_a_panic() {
334            let headers = github_headers();
335            // Invalid header-name bytes must yield `None`, never panic.
336            assert_eq!(HeaderMap::get(&headers, "bad name\n"), None);
337            assert_eq!(HeaderMap::get(&headers, ""), None);
338        }
339
340        #[test]
341        fn non_visible_ascii_value_is_reported_absent() {
342            let mut headers = ::http::HeaderMap::new();
343            // The `http` crate permits opaque bytes >= 0x80 in header values,
344            // so such values are reachable in practice (e.g. hand-built
345            // maps); `to_str` rejects them, and we surface that as absent
346            // rather than panicking or silently matching.
347            let Ok(value) = ::http::HeaderValue::from_bytes(&[0xFF]) else {
348                panic!("0xFF is a permitted header-value byte");
349            };
350            headers.insert("X-Webhook-Sig", value);
351            assert_eq!(HeaderMap::get(&headers, "X-Webhook-Sig"), None);
352        }
353
354        /// End-to-end: a real provider verifies straight against an
355        /// `http::HeaderMap` with no header copying.
356        #[test]
357        fn verifies_github_delivery_end_to_end() {
358            let result = verify(
359                Provider::GitHub,
360                &github_headers(),
361                b"Hello, World!",
362                &Secret::new("It's a Secret to Everybody"),
363                Default::default(),
364            );
365            assert_eq!(result, Ok(()));
366
367            // And a tampered body fails closed through the same path.
368            let result = verify(
369                Provider::GitHub,
370                &github_headers(),
371                b"Hello, World?",
372                &Secret::new("It's a Secret to Everybody"),
373                Default::default(),
374            );
375            assert_eq!(result, Err(crate::VerifyError::SignatureMismatch));
376        }
377
378        #[test]
379        fn missing_header_surfaces_as_missing_header_error() {
380            let result = verify(
381                Provider::GitHub,
382                &::http::HeaderMap::new(),
383                b"Hello, World!",
384                &Secret::new("It's a Secret to Everybody"),
385                Default::default(),
386            );
387            assert_eq!(
388                result,
389                Err(crate::VerifyError::MissingHeader {
390                    header: "X-Hub-Signature-256"
391                })
392            );
393        }
394    }
395}