glacier-web 0.4.1

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
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
//! Signature checks for the providers Glacier knows, and a generic HMAC
//! one. Each takes several secrets, so a secret can be rotated without
//! dropping events, and compares signatures in constant time.

// `Stripe::new(secrets)` makes the provider (a `Provider`), ready for `.on`.
#![allow(clippy::new_ret_no_self)]

use base64::Engine as _;
use chrono::TimeDelta;
use hmac::{Hmac as HmacOf, Mac};
use http::HeaderMap;
use sha2::{Digest, Sha256};

use super::{Provider, Verify};
use crate::error::{Error, Result};

type HmacSha256 = HmacOf<Sha256>;

/// How old a signed timestamp may be (Stripe's default tolerance).
const TOLERANCE: TimeDelta = TimeDelta::minutes(5);

fn rejected(why: &str) -> Error {
    Error::bad_request(why.to_owned())
}

fn header<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
    headers.get(name).and_then(|v| v.to_str().ok())
}

/// Whether `signature` is the HMAC-SHA256 of `message` under any secret.
fn signed_by_any(secrets: &[String], message: &[u8], signature: &[u8]) -> bool {
    secrets.iter().any(|secret| {
        let Ok(mut mac) = HmacSha256::new_from_slice(secret.as_bytes()) else {
            return false;
        };
        mac.update(message);
        mac.verify_slice(signature).is_ok()
    })
}

fn hex_decode(text: &str) -> Option<Vec<u8>> {
    if !text.len().is_multiple_of(2) {
        return None;
    }
    (0..text.len())
        .step_by(2)
        .map(|i| u8::from_str_radix(text.get(i..i + 2)?, 16).ok())
        .collect()
}

fn json_field(body: &[u8], path: &[&str]) -> Option<String> {
    let mut value: serde_json::Value = serde_json::from_slice(body).ok()?;
    for key in path {
        value = value.get_mut(*key)?.take();
    }
    match value {
        serde_json::Value::String(text) => Some(text),
        serde_json::Value::Null => None,
        other => Some(other.to_string()),
    }
}

/// An id for providers that don't send one: the body's SHA-256, so an
/// identical redelivery is still stored once.
fn body_hash(body: &[u8]) -> String {
    let digest = Sha256::digest(body);
    let hex: String = digest.iter().map(|b| format!("{b:02x}")).collect();
    format!("sha256:{hex}")
}

fn secrets(secrets: &[&str]) -> Vec<String> {
    secrets
        .iter()
        .filter(|s| !s.is_empty())
        .map(|s| (*s).to_owned())
        .collect()
}

/// Stripe: `Stripe-Signature: t=…,v1=…`, over `"{t}.{body}"`, within five
/// minutes. The event's `id` and `type` come from the body.
pub struct Stripe {
    secrets: Vec<String>,
}

impl Stripe {
    /// The provider `stripe`, checked with any of its signing secrets
    /// (`whsec_…`; more than one while rotating).
    pub fn new(signing_secrets: &[&str]) -> Provider {
        Provider::new(
            "stripe",
            Self {
                secrets: secrets(signing_secrets),
            },
        )
    }
}

impl Verify for Stripe {
    fn verify(&self, headers: &HeaderMap, body: &[u8]) -> Result<()> {
        let header =
            header(headers, "stripe-signature").ok_or_else(|| rejected("no Stripe-Signature"))?;
        let mut timestamp = None;
        let mut signatures = Vec::new();
        for part in header.split(',') {
            match part.trim().split_once('=') {
                Some(("t", t)) => timestamp = t.parse::<i64>().ok(),
                Some(("v1", sig)) => signatures.extend(hex_decode(sig)),
                _ => {}
            }
        }
        let timestamp = timestamp.ok_or_else(|| rejected("no timestamp in Stripe-Signature"))?;
        let age = crate::time::now().timestamp() - timestamp;
        if age.abs() > TOLERANCE.num_seconds() {
            return Err(rejected(
                "Stripe-Signature timestamp is outside the tolerance",
            ));
        }
        let mut message = format!("{timestamp}.").into_bytes();
        message.extend_from_slice(body);
        if signatures
            .iter()
            .any(|sig| signed_by_any(&self.secrets, &message, sig))
        {
            Ok(())
        } else {
            Err(rejected("Stripe signature doesn't match"))
        }
    }

    fn identify(&self, _headers: &HeaderMap, body: &[u8]) -> Result<(String, String)> {
        let id =
            json_field(body, &["id"]).ok_or_else(|| rejected("a Stripe event without an id"))?;
        let kind =
            json_field(body, &["type"]).ok_or_else(|| rejected("a Stripe event without a type"))?;
        Ok((id, kind))
    }
}

/// GitHub: `X-Hub-Signature-256: sha256=…` over the body; the delivery id
/// and event (`push`, `pull_request`) from its headers.
pub struct GitHub {
    secrets: Vec<String>,
}

impl GitHub {
    pub fn new(webhook_secrets: &[&str]) -> Provider {
        Provider::new(
            "github",
            Self {
                secrets: secrets(webhook_secrets),
            },
        )
    }
}

impl Verify for GitHub {
    fn verify(&self, headers: &HeaderMap, body: &[u8]) -> Result<()> {
        let signature = header(headers, "x-hub-signature-256")
            .and_then(|h| h.strip_prefix("sha256="))
            .and_then(hex_decode)
            .ok_or_else(|| rejected("no X-Hub-Signature-256"))?;
        if signed_by_any(&self.secrets, body, &signature) {
            Ok(())
        } else {
            Err(rejected("GitHub signature doesn't match"))
        }
    }

    fn identify(&self, headers: &HeaderMap, _body: &[u8]) -> Result<(String, String)> {
        let id =
            header(headers, "x-github-delivery").ok_or_else(|| rejected("no X-GitHub-Delivery"))?;
        let kind =
            header(headers, "x-github-event").ok_or_else(|| rejected("no X-GitHub-Event"))?;
        Ok((id.to_owned(), kind.to_owned()))
    }
}

/// Shopify: `X-Shopify-Hmac-Sha256` (base64) over the body; the webhook id
/// and topic (`orders/create`) from its headers.
pub struct Shopify {
    secrets: Vec<String>,
}

impl Shopify {
    pub fn new(client_secrets: &[&str]) -> Provider {
        Provider::new(
            "shopify",
            Self {
                secrets: secrets(client_secrets),
            },
        )
    }
}

impl Verify for Shopify {
    fn verify(&self, headers: &HeaderMap, body: &[u8]) -> Result<()> {
        let signature = header(headers, "x-shopify-hmac-sha256")
            .and_then(|h| {
                base64::engine::general_purpose::STANDARD
                    .decode(h.trim())
                    .ok()
            })
            .ok_or_else(|| rejected("no X-Shopify-Hmac-Sha256"))?;
        if signed_by_any(&self.secrets, body, &signature) {
            Ok(())
        } else {
            Err(rejected("Shopify signature doesn't match"))
        }
    }

    fn identify(&self, headers: &HeaderMap, body: &[u8]) -> Result<(String, String)> {
        let id = header(headers, "x-shopify-webhook-id")
            .map(str::to_owned)
            .unwrap_or_else(|| body_hash(body));
        let kind =
            header(headers, "x-shopify-topic").ok_or_else(|| rejected("no X-Shopify-Topic"))?;
        Ok((id, kind.to_owned()))
    }
}

/// Lemon Squeezy: `X-Signature` (hex) over the body; the type from
/// `meta.event_name`. It sends no event id, so identical deliveries are
/// recognised by the body's hash.
pub struct LemonSqueezy {
    secrets: Vec<String>,
}

impl LemonSqueezy {
    pub fn new(signing_secrets: &[&str]) -> Provider {
        Provider::new(
            "lemon_squeezy",
            Self {
                secrets: secrets(signing_secrets),
            },
        )
    }
}

impl Verify for LemonSqueezy {
    fn verify(&self, headers: &HeaderMap, body: &[u8]) -> Result<()> {
        let signature = header(headers, "x-signature")
            .and_then(hex_decode)
            .ok_or_else(|| rejected("no X-Signature"))?;
        if signed_by_any(&self.secrets, body, &signature) {
            Ok(())
        } else {
            Err(rejected("Lemon Squeezy signature doesn't match"))
        }
    }

    fn identify(&self, _headers: &HeaderMap, body: &[u8]) -> Result<(String, String)> {
        let kind = json_field(body, &["meta", "event_name"])
            .ok_or_else(|| rejected("a Lemon Squeezy event without meta.event_name"))?;
        Ok((body_hash(body), kind))
    }
}

/// Paddle Billing: `Paddle-Signature: ts=…;h1=…`, over `"{ts}:{body}"`,
/// within five minutes; `event_id` and `event_type` from the body.
pub struct Paddle {
    secrets: Vec<String>,
}

impl Paddle {
    pub fn new(secret_keys: &[&str]) -> Provider {
        Provider::new(
            "paddle",
            Self {
                secrets: secrets(secret_keys),
            },
        )
    }
}

impl Verify for Paddle {
    fn verify(&self, headers: &HeaderMap, body: &[u8]) -> Result<()> {
        let header =
            header(headers, "paddle-signature").ok_or_else(|| rejected("no Paddle-Signature"))?;
        let mut timestamp = None;
        let mut signatures = Vec::new();
        for part in header.split(';') {
            match part.trim().split_once('=') {
                Some(("ts", ts)) => timestamp = ts.parse::<i64>().ok(),
                Some(("h1", sig)) => signatures.extend(hex_decode(sig)),
                _ => {}
            }
        }
        let timestamp = timestamp.ok_or_else(|| rejected("no timestamp in Paddle-Signature"))?;
        if (crate::time::now().timestamp() - timestamp).abs() > TOLERANCE.num_seconds() {
            return Err(rejected(
                "Paddle-Signature timestamp is outside the tolerance",
            ));
        }
        let mut message = format!("{timestamp}:").into_bytes();
        message.extend_from_slice(body);
        if signatures
            .iter()
            .any(|sig| signed_by_any(&self.secrets, &message, sig))
        {
            Ok(())
        } else {
            Err(rejected("Paddle signature doesn't match"))
        }
    }

    fn identify(&self, _headers: &HeaderMap, body: &[u8]) -> Result<(String, String)> {
        let id = json_field(body, &["event_id"])
            .ok_or_else(|| rejected("a Paddle event without event_id"))?;
        let kind = json_field(body, &["event_type"])
            .ok_or_else(|| rejected("a Paddle event without event_type"))?;
        Ok((id, kind))
    }
}

/// Any service that signs the body with HMAC-SHA256 into a header:
/// `Hmac::new("acme", "X-Acme-Signature", &[secret]).prefix("sha256=")`.
/// The event's id and type come from the body's `id` and `type` unless
/// headers are named for them; without an id, the body's hash.
pub struct Hmac {
    header: String,
    prefix: String,
    base64: bool,
    secrets: Vec<String>,
    id_header: Option<String>,
    type_header: Option<String>,
}

impl Hmac {
    pub fn new(name: &str, header: &str, signing_secrets: &[&str]) -> HmacProvider {
        HmacProvider {
            name: name.to_owned(),
            hmac: Self {
                header: header.to_ascii_lowercase(),
                prefix: String::new(),
                base64: false,
                secrets: secrets(signing_secrets),
                id_header: None,
                type_header: None,
            },
        }
    }
}

/// An [`Hmac`] provider being set up; `.on(…)` finishes it.
pub struct HmacProvider {
    name: String,
    hmac: Hmac,
}

impl HmacProvider {
    /// Text before the signature: `sha256=`.
    #[must_use]
    pub fn prefix(mut self, prefix: &str) -> Self {
        self.hmac.prefix = prefix.to_owned();
        self
    }

    /// The signature is base64 rather than hex.
    #[must_use]
    pub fn base64(mut self) -> Self {
        self.hmac.base64 = true;
        self
    }

    /// Headers naming the event's id and type.
    #[must_use]
    pub fn event_headers(mut self, id: &str, event_type: &str) -> Self {
        self.hmac.id_header = Some(id.to_ascii_lowercase());
        self.hmac.type_header = Some(event_type.to_ascii_lowercase());
        self
    }

    /// The provider, ready for handlers.
    pub fn provider(self) -> Provider {
        Provider::new(&self.name, self.hmac)
    }

    /// Handles events of `event_type`; see [`Provider::on`].
    pub fn on<F, Fut>(self, event_type: &str, handler: F) -> Provider
    where
        F: Fn(super::Event) -> Fut + Send + Sync + 'static,
        Fut: std::future::Future<Output = Result<()>> + Send + 'static,
    {
        self.provider().on(event_type, handler)
    }
}

impl Verify for Hmac {
    fn verify(&self, headers: &HeaderMap, body: &[u8]) -> Result<()> {
        let text = header(headers, &self.header)
            .and_then(|h| h.trim().strip_prefix(self.prefix.as_str()))
            .ok_or_else(|| rejected("no signature header"))?;
        let signature = if self.base64 {
            base64::engine::general_purpose::STANDARD.decode(text).ok()
        } else {
            hex_decode(text)
        }
        .ok_or_else(|| rejected("a signature that isn't hex or base64"))?;
        if signed_by_any(&self.secrets, body, &signature) {
            Ok(())
        } else {
            Err(rejected("signature doesn't match"))
        }
    }

    fn identify(&self, headers: &HeaderMap, body: &[u8]) -> Result<(String, String)> {
        let id = match &self.id_header {
            Some(name) => header(headers, name).map(str::to_owned),
            None => json_field(body, &["id"]),
        }
        .unwrap_or_else(|| body_hash(body));
        let kind = match &self.type_header {
            Some(name) => header(headers, name).map(str::to_owned),
            None => json_field(body, &["type"]),
        }
        .unwrap_or_else(|| "event".to_owned());
        Ok((id, kind))
    }
}

/// Signs `message` as the providers do, for tests: the HMAC-SHA256 in hex.
pub fn sign_hex(secret: &str, message: &[u8]) -> String {
    let mut mac = HmacSha256::new_from_slice(secret.as_bytes()).expect("any key length works");
    mac.update(message);
    mac.finalize()
        .into_bytes()
        .iter()
        .map(|b| format!("{b:02x}"))
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use http::HeaderValue;

    fn headers(pairs: &[(&'static str, String)]) -> HeaderMap {
        let mut map = HeaderMap::new();
        for (name, value) in pairs {
            map.insert(*name, HeaderValue::from_str(value).unwrap());
        }
        map
    }

    #[test]
    fn stripe_checks_signature_secrets_and_age() {
        let body = br#"{"id":"evt_1","type":"charge.succeeded"}"#;
        let t = crate::time::now().timestamp();
        let mut message = format!("{t}.").into_bytes();
        message.extend_from_slice(body);
        let good = headers(&[(
            "stripe-signature",
            format!("t={t},v1={}", sign_hex("whsec_new", &message)),
        )]);
        let verifier = Stripe {
            secrets: secrets(&["whsec_old", "whsec_new"]),
        };
        assert!(
            verifier.verify(&good, body).is_ok(),
            "either secret, while rotating"
        );
        assert!(
            Stripe {
                secrets: secrets(&["whsec_old"])
            }
            .verify(&good, body)
            .is_err()
        );
        assert!(verifier.verify(&good, b"{}").is_err(), "another body");
        let old = t - 600;
        let mut message = format!("{old}.").into_bytes();
        message.extend_from_slice(body);
        let stale = headers(&[(
            "stripe-signature",
            format!("t={old},v1={}", sign_hex("whsec_new", &message)),
        )]);
        assert!(verifier.verify(&stale, body).is_err(), "too old");
        assert_eq!(
            verifier.identify(&good, body).unwrap(),
            ("evt_1".to_owned(), "charge.succeeded".to_owned())
        );
    }

    #[test]
    fn github_shopify_and_lemon_squeezy() {
        let body = b"{\"meta\":{\"event_name\":\"order_created\"}}";
        let github = headers(&[
            (
                "x-hub-signature-256",
                format!("sha256={}", sign_hex("s", body)),
            ),
            ("x-github-delivery", "d-1".into()),
            ("x-github-event", "push".into()),
        ]);
        let verifier = GitHub {
            secrets: secrets(&["s"]),
        };
        assert!(verifier.verify(&github, body).is_ok());
        assert_eq!(
            verifier.identify(&github, body).unwrap(),
            ("d-1".into(), "push".into())
        );

        let digest = hex_decode(&sign_hex("s", body)).unwrap();
        let shopify = headers(&[
            (
                "x-shopify-hmac-sha256",
                base64::engine::general_purpose::STANDARD.encode(digest),
            ),
            ("x-shopify-topic", "orders/create".into()),
        ]);
        assert!(
            Shopify {
                secrets: secrets(&["s"])
            }
            .verify(&shopify, body)
            .is_ok()
        );

        let lemon = headers(&[("x-signature", sign_hex("s", body))]);
        let verifier = LemonSqueezy {
            secrets: secrets(&["s"]),
        };
        assert!(verifier.verify(&lemon, body).is_ok());
        let (id, kind) = verifier.identify(&lemon, body).unwrap();
        assert!(id.starts_with("sha256:"));
        assert_eq!(kind, "order_created");
    }

    #[test]
    fn generic_hmac_with_prefix() {
        let body = br#"{"id":"e9","type":"thing.made"}"#;
        let verifier = Hmac::new("acme", "X-Acme-Signature", &["k"])
            .prefix("sha256=")
            .hmac;
        let good = headers(&[(
            "x-acme-signature",
            format!("sha256={}", sign_hex("k", body)),
        )]);
        assert!(verifier.verify(&good, body).is_ok());
        assert_eq!(
            verifier.identify(&good, body).unwrap(),
            ("e9".into(), "thing.made".into())
        );
        assert!(
            verifier
                .verify(&headers(&[("x-acme-signature", "sha256=00".into())]), body)
                .is_err()
        );
    }
}