codoseo-web 0.1.0-rc.1

The CodoSEO web app: axum routes, askama templates and htmx partials.
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
//! Dodo Payments: webhook signatures (Standard Webhooks), the subscription envelope, and the
//! two API calls the app makes (checkout and customer portal).
//!
//! Field names in the webhook payload follow Dodo's documentation. They are read leniently
//! (everything optional, unknown fields ignored) and should be confirmed against payloads from
//! Dodo's live webhook deliveries before launch.

use axum::http::HeaderMap;
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD as B64;
use hmac::{Hmac, KeyInit, Mac};
use serde::Deserialize;
use serde_json::Value;
use sha2::Sha256;
use time::OffsetDateTime;
use time::format_description::well_known::Rfc3339;
use url::Url;

use crate::config::DodoConfig;

/// How far a webhook's timestamp may be from now, either way.
pub const TOLERANCE_SECS: i64 = 5 * 60;

#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum SigError {
    #[error("missing {0} header")]
    MissingHeader(&'static str),
    #[error("webhook-timestamp is not a unix timestamp")]
    BadTimestamp,
    #[error("webhook-timestamp is outside the 5 minute window")]
    Stale,
    #[error("the webhook secret is not a whsec_ key")]
    BadSecret,
    #[error("no valid signature")]
    NoValidSignature,
}

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

/// The shortest webhook key accepted. HMAC takes a key of any length, an empty one included,
/// so without a floor a `whsec_` secret with nothing after it would "verify" forgeries.
pub const MIN_KEY_BYTES: usize = 16;

/// The HMAC key behind a `whsec_<base64>` secret.
pub fn key(secret: &str) -> Result<Vec<u8>, SigError> {
    let encoded = secret
        .trim()
        .strip_prefix("whsec_")
        .ok_or(SigError::BadSecret)?;
    let key = B64.decode(encoded).map_err(|_| SigError::BadSecret)?;
    if key.len() < MIN_KEY_BYTES {
        return Err(SigError::BadSecret);
    }
    Ok(key)
}

fn mac(key: &[u8], id: &str, timestamp: &str, body: &[u8]) -> Hmac<Sha256> {
    let mut mac = Hmac::<Sha256>::new_from_slice(key).expect("HMAC accepts keys of any length");
    mac.update(id.as_bytes());
    mac.update(b".");
    mac.update(timestamp.as_bytes());
    mac.update(b".");
    mac.update(body);
    mac
}

/// Checks a webhook the Standard Webhooks way: `webhook-id`, `webhook-timestamp` (unix seconds,
/// within five minutes of `now`) and `webhook-signature` (`v1,<base64 HMAC-SHA256 of
/// "{id}.{timestamp}.{body}">`, several separated by spaces; one valid is enough). Signatures
/// are compared in constant time.
pub fn verify(
    secret: &str,
    headers: &HeaderMap,
    body: &[u8],
    now: OffsetDateTime,
) -> Result<(), SigError> {
    let id = header(headers, "webhook-id")?;
    let timestamp = header(headers, "webhook-timestamp")?;
    let signatures = header(headers, "webhook-signature")?;
    let sent: i64 = timestamp.parse().map_err(|_| SigError::BadTimestamp)?;
    // `abs_diff` can't overflow, whatever the sender put in the header.
    if now.unix_timestamp().abs_diff(sent) > TOLERANCE_SECS as u64 {
        return Err(SigError::Stale);
    }
    let key = key(secret)?;
    let valid = signatures
        .split_ascii_whitespace()
        .filter_map(|s| s.strip_prefix("v1,"))
        .filter_map(|s| B64.decode(s).ok())
        .any(|sig| mac(&key, id, timestamp, body).verify_slice(&sig).is_ok());
    if valid {
        Ok(())
    } else {
        Err(SigError::NoValidSignature)
    }
}

/// The `webhook-signature` value for a body: what Dodo sends, and what tests send.
pub fn sign(secret: &str, id: &str, timestamp: i64, body: &[u8]) -> Result<String, SigError> {
    let key = key(secret)?;
    let sig = mac(&key, id, &timestamp.to_string(), body)
        .finalize()
        .into_bytes();
    Ok(format!("v1,{}", B64.encode(sig)))
}

// ---- the envelope -------------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Subscription {
    pub subscription_id: Option<String>,
    pub product_id: Option<String>,
    pub customer_id: Option<String>,
    pub customer_email: Option<String>,
    pub status: Option<String>,
    pub next_billing_date: Option<OffsetDateTime>,
    /// `metadata.account_id`, set when the checkout was created.
    pub metadata_account_id: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DodoEvent {
    /// The `webhook-id` header; the body has no id of its own.
    pub id: String,
    /// `subscription.active`, ...
    pub kind: String,
    /// When it happened, from the body; `None` if missing or unreadable.
    pub timestamp: Option<OffsetDateTime>,
    /// Present on subscription events.
    pub subscription: Option<Subscription>,
}

/// ISO 8601 with an offset, or without one (taken as UTC).
fn parse_time(text: &str) -> Option<OffsetDateTime> {
    let text = text.trim();
    OffsetDateTime::parse(text, &Rfc3339)
        .or_else(|_| OffsetDateTime::parse(&format!("{text}Z"), &Rfc3339))
        .ok()
}

/// A string field, or `None` when it is missing, null, empty, or not a string (logged: the
/// signature was valid, so a surprise in the payload is worth a line, not a rejection).
fn text(object: &serde_json::Map<String, Value>, field: &str) -> Option<String> {
    match object.get(field) {
        None | Some(Value::Null) => None,
        Some(Value::String(s)) if !s.trim().is_empty() => Some(s.clone()),
        Some(Value::String(_)) => None,
        Some(_) => {
            tracing::warn!(field, "billing webhook field is not a string, ignoring it");
            None
        }
    }
}

/// An object field, or `None` (logged) when it is something else.
fn object<'a>(
    parent: &'a serde_json::Map<String, Value>,
    field: &str,
) -> Option<&'a serde_json::Map<String, Value>> {
    match parent.get(field) {
        None | Some(Value::Null) => None,
        Some(Value::Object(o)) => Some(o),
        Some(_) => {
            tracing::warn!(field, "billing webhook field is not an object, ignoring it");
            None
        }
    }
}

/// The body wasn't a JSON object.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("the webhook body is not a JSON object")]
pub struct NotAnObject;

/// Reads a verified webhook body. Fails only when it isn't a JSON object; every field inside
/// is optional, and one of the wrong type counts as absent.
pub fn parse_event(id: &str, body: &[u8]) -> Result<DodoEvent, NotAnObject> {
    let Ok(Value::Object(root)) = serde_json::from_slice::<Value>(body) else {
        return Err(NotAnObject);
    };
    let kind = text(&root, "type").unwrap_or_default();
    let timestamp = text(&root, "timestamp").as_deref().and_then(parse_time);
    let subscription = object(&root, "data")
        .filter(|d| kind.starts_with("subscription.") || d.contains_key("subscription_id"))
        .map(|d| {
            let customer = object(d, "customer");
            Subscription {
                subscription_id: text(d, "subscription_id"),
                product_id: text(d, "product_id"),
                customer_id: customer.and_then(|c| text(c, "customer_id")),
                customer_email: customer.and_then(|c| text(c, "email")),
                status: text(d, "status"),
                next_billing_date: text(d, "next_billing_date").as_deref().and_then(parse_time),
                metadata_account_id: object(d, "metadata").and_then(|m| text(m, "account_id")),
            }
        });
    Ok(DodoEvent {
        id: id.to_owned(),
        kind,
        timestamp,
        subscription,
    })
}

// ---- API calls ----------------------------------------------------------------------------------

#[derive(Debug, thiserror::Error)]
pub enum DodoError {
    #[error("could not reach Dodo: {0}")]
    Unreachable(String),
    #[error("Dodo answered {status}: {body}")]
    Rejected { status: u16, body: String },
    #[error("Dodo's answer had no usable {0}")]
    BadResponse(&'static str),
}

#[derive(Deserialize)]
struct CheckoutResponse {
    checkout_url: Option<String>,
}

#[derive(Deserialize)]
struct PortalResponse {
    link: Option<String>,
}

async fn post(
    http: &reqwest::Client,
    cfg: &DodoConfig,
    url: Url,
    body: Option<serde_json::Value>,
) -> Result<String, DodoError> {
    let mut req = http.post(url).bearer_auth(&cfg.api_key);
    if let Some(body) = body {
        req = req.json(&body);
    }
    let res = req
        .send()
        .await
        .map_err(|e| DodoError::Unreachable(e.to_string()))?;
    let status = res.status();
    let text = res
        .text()
        .await
        .map_err(|e| DodoError::Unreachable(e.to_string()))?;
    if !status.is_success() {
        return Err(DodoError::Rejected {
            status: status.as_u16(),
            body: text.chars().take(300).collect(),
        });
    }
    Ok(text)
}

/// A link Dodo gave us must at least be a web address before we redirect to it.
fn web_url(link: Option<String>, field: &'static str) -> Result<String, DodoError> {
    link.filter(|l| {
        Url::parse(l).is_ok_and(|u| matches!(u.scheme(), "http" | "https") && u.host().is_some())
    })
    .ok_or(DodoError::BadResponse(field))
}

/// Starts a hosted checkout for `product_id`; returns the page to send the customer to.
pub async fn create_checkout(
    http: &reqwest::Client,
    cfg: &DodoConfig,
    product_id: &str,
    email: &str,
    account_id: uuid::Uuid,
    return_url: &str,
) -> Result<String, DodoError> {
    let url = cfg
        .api_url
        .join("checkouts")
        .map_err(|_| DodoError::BadResponse("api url"))?;
    let text = post(
        http,
        cfg,
        url,
        Some(serde_json::json!({
            "product_cart": [{ "product_id": product_id, "quantity": 1 }],
            "customer": { "email": email },
            "return_url": return_url,
            "metadata": { "account_id": account_id.to_string() },
        })),
    )
    .await?;
    let parsed: CheckoutResponse =
        serde_json::from_str(&text).map_err(|_| DodoError::BadResponse("checkout_url"))?;
    web_url(parsed.checkout_url, "checkout_url")
}

/// Opens a customer-portal session; returns the link to send the customer to.
pub async fn create_portal_session(
    http: &reqwest::Client,
    cfg: &DodoConfig,
    customer_id: &str,
    return_url: &str,
) -> Result<String, DodoError> {
    let mut url = cfg
        .api_url
        .join(&format!(
            "customers/{}/customer-portal/session",
            urlencode(customer_id)
        ))
        .map_err(|_| DodoError::BadResponse("api url"))?;
    url.query_pairs_mut().append_pair("return_url", return_url);
    let text = post(http, cfg, url, None).await?;
    let parsed: PortalResponse =
        serde_json::from_str(&text).map_err(|_| DodoError::BadResponse("link"))?;
    web_url(parsed.link, "link")
}

/// Escapes a path segment.
fn urlencode(s: &str) -> String {
    url::form_urlencoded::byte_serialize(s.as_bytes())
        .collect::<String>()
        .replace('+', "%20")
}

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

    const SECRET: &str = "whsec_dGVzdC1zZWNyZXQtMDEyMzQ1Njc4OQ==";
    const BODY: &[u8] = br#"{"type":"subscription.active"}"#;

    fn now() -> OffsetDateTime {
        OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap()
    }

    fn headers(id: &str, ts: i64, sig: &str) -> HeaderMap {
        let mut h = HeaderMap::new();
        h.insert("webhook-id", HeaderValue::from_str(id).unwrap());
        h.insert(
            "webhook-timestamp",
            HeaderValue::from_str(&ts.to_string()).unwrap(),
        );
        h.insert("webhook-signature", HeaderValue::from_str(sig).unwrap());
        h
    }

    fn signed(ts: i64) -> HeaderMap {
        headers("msg_1", ts, &sign(SECRET, "msg_1", ts, BODY).unwrap())
    }

    #[test]
    fn a_valid_signature_verifies() {
        let ts = now().unix_timestamp();
        assert_eq!(verify(SECRET, &signed(ts), BODY, now()), Ok(()));
    }

    #[test]
    fn the_signature_matches_the_standard_webhooks_reference_vector() {
        // From the Standard Webhooks test suite: secret MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw,
        // id msg_p5jXN8AQM9LWM0D4loKWxJek, timestamp 1614265330.
        let secret = "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw";
        let body = br#"{"test": 2432232314}"#;
        assert_eq!(
            sign(secret, "msg_p5jXN8AQM9LWM0D4loKWxJek", 1_614_265_330, body).unwrap(),
            "v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE="
        );
    }

    #[test]
    fn a_wrong_secret_is_refused() {
        let ts = now().unix_timestamp();
        let other = "whsec_b3RoZXItc2VjcmV0LTAxMjM0NTY3ODk=";
        assert_eq!(
            verify(other, &signed(ts), BODY, now()),
            Err(SigError::NoValidSignature)
        );
    }

    #[test]
    fn a_modified_body_is_refused() {
        let ts = now().unix_timestamp();
        assert_eq!(
            verify(
                SECRET,
                &signed(ts),
                br#"{"type":"subscription.expired"}"#,
                now()
            ),
            Err(SigError::NoValidSignature)
        );
    }

    #[test]
    fn a_modified_id_is_refused() {
        let ts = now().unix_timestamp();
        let h = headers("msg_2", ts, &sign(SECRET, "msg_1", ts, BODY).unwrap());
        assert_eq!(
            verify(SECRET, &h, BODY, now()),
            Err(SigError::NoValidSignature)
        );
    }

    #[test]
    fn a_stale_or_future_timestamp_is_refused() {
        let ts = now().unix_timestamp() - TOLERANCE_SECS - 1;
        assert_eq!(
            verify(SECRET, &signed(ts), BODY, now()),
            Err(SigError::Stale)
        );
        let ts = now().unix_timestamp() + TOLERANCE_SECS + 1;
        assert_eq!(
            verify(SECRET, &signed(ts), BODY, now()),
            Err(SigError::Stale)
        );
        // Right at the edge is still fine.
        let ts = now().unix_timestamp() - TOLERANCE_SECS;
        assert_eq!(verify(SECRET, &signed(ts), BODY, now()), Ok(()));
    }

    #[test]
    fn a_missing_header_is_refused() {
        let ts = now().unix_timestamp();
        for name in ["webhook-id", "webhook-timestamp", "webhook-signature"] {
            let mut h = signed(ts);
            h.remove(name);
            assert!(
                matches!(verify(SECRET, &h, BODY, now()), Err(SigError::MissingHeader(n)) if n == name),
                "{name}"
            );
        }
    }

    #[test]
    fn a_garbled_timestamp_or_signature_is_refused() {
        let mut h = signed(now().unix_timestamp());
        h.insert("webhook-timestamp", HeaderValue::from_static("yesterday"));
        assert_eq!(verify(SECRET, &h, BODY, now()), Err(SigError::BadTimestamp));
        let h = headers(
            "msg_1",
            now().unix_timestamp(),
            "v1,%%%not-base64 v2,AAAA nonsense",
        );
        assert_eq!(
            verify(SECRET, &h, BODY, now()),
            Err(SigError::NoValidSignature)
        );
    }

    #[test]
    fn one_valid_signature_among_several_passes() {
        let ts = now().unix_timestamp();
        let good = sign(SECRET, "msg_1", ts, BODY).unwrap();
        let bad = sign("whsec_b3RoZXItc2VjcmV0LTAxMjM0NTY3ODk=", "msg_1", ts, BODY).unwrap();
        for list in [
            format!("{bad} {good}"),
            format!("{good} {bad}"),
            format!("v2,AAAA {bad} {good}"),
        ] {
            let h = headers("msg_1", ts, &list);
            assert_eq!(verify(SECRET, &h, BODY, now()), Ok(()), "{list}");
        }
        let h = headers("msg_1", ts, &format!("{bad} {bad}"));
        assert_eq!(
            verify(SECRET, &h, BODY, now()),
            Err(SigError::NoValidSignature)
        );
    }

    #[test]
    fn an_empty_or_short_key_is_refused_even_with_a_matching_signature() {
        let ts = now().unix_timestamp();
        for short in ["whsec_", "whsec_YQ==", "whsec_c2VjcmV0LTAxMjM0NQ=="] {
            // 0, 1 and 15 bytes: the HMAC would accept them, so `key` must not.
            assert_eq!(
                sign(short, "msg_1", ts, BODY),
                Err(SigError::BadSecret),
                "{short}"
            );
            let h = headers("msg_1", ts, "v1,AAAA");
            assert_eq!(
                verify(short, &h, BODY, now()),
                Err(SigError::BadSecret),
                "{short}"
            );
        }
        // 16 bytes is the smallest accepted.
        assert!(sign("whsec_MDEyMzQ1Njc4OWFiY2RlZg==", "msg_1", ts, BODY).is_ok());
    }

    #[test]
    fn extreme_timestamps_are_refused_without_panicking() {
        for extreme in [i64::MIN, i64::MAX, i64::MIN + 1, 0] {
            let h = headers("msg_1", extreme, "v1,AAAA");
            assert_eq!(
                verify(SECRET, &h, BODY, now()),
                Err(SigError::Stale),
                "{extreme}"
            );
        }
    }

    #[test]
    fn a_field_of_the_wrong_type_is_treated_as_absent() {
        let body = br#"{
            "type": "subscription.active",
            "timestamp": 1760000000,
            "data": {
                "subscription_id": "sub_1",
                "product_id": ["pdt_pro"],
                "status": 7,
                "next_billing_date": {"at": "soon"},
                "customer": "cus_1",
                "metadata": "account"
            }
        }"#;
        let ev = parse_event("m", body).unwrap();
        assert_eq!(ev.kind, "subscription.active");
        assert_eq!(ev.timestamp, None);
        let sub = ev.subscription.unwrap();
        assert_eq!(sub.subscription_id.as_deref(), Some("sub_1"));
        assert_eq!(sub.product_id, None);
        assert_eq!(sub.status, None);
        assert_eq!(sub.next_billing_date, None);
        assert_eq!(sub.customer_id, None);
        assert_eq!(sub.metadata_account_id, None);

        // Only something that isn't a JSON object at all is refused.
        for bad in ["[]", "7", "\"text\"", "null", "not json"] {
            assert!(parse_event("m", bad.as_bytes()).is_err(), "{bad}");
        }
        let ev = parse_event("m", br#"{"type": 5, "data": 5}"#).unwrap();
        assert_eq!(ev.kind, "");
        assert!(ev.subscription.is_none());
    }

    #[test]
    fn the_config_does_not_print_its_secrets() {
        let cfg = DodoConfig {
            api_key: "dodo_key_SUPERSECRET".to_owned(),
            webhook_secret: "whsec_WEBHOOKSECRET".to_owned(),
            product_pro: "pdt_pro".to_owned(),
            product_agency: "pdt_agency".to_owned(),
            api_url: Url::parse("https://test.dodopayments.com").unwrap(),
        };
        let shown = format!("{cfg:?}");
        assert!(
            !shown.contains("SUPERSECRET") && !shown.contains("WEBHOOKSECRET"),
            "{shown}"
        );
        assert!(shown.contains("pdt_pro") && shown.contains("test.dodopayments.com"));
    }

    #[test]
    fn a_secret_that_is_not_whsec_is_a_configuration_error() {
        let ts = now().unix_timestamp();
        assert_eq!(
            verify("plain", &signed(ts), BODY, now()),
            Err(SigError::BadSecret)
        );
    }

    #[test]
    fn a_subscription_event_is_read() {
        let body = br#"{
            "business_id": "bus_1",
            "type": "subscription.active",
            "timestamp": "2026-10-05T10:00:00.123456Z",
            "data": {
                "payload_type": "Subscription",
                "subscription_id": "sub_1",
                "product_id": "pdt_pro",
                "status": "active",
                "next_billing_date": "2026-11-05T10:00:00Z",
                "customer": {"customer_id": "cus_1", "email": "ana@example.com", "name": "Ana"},
                "metadata": {"account_id": "6f1d9a54-6b0e-4a39-9f43-0c2a8b6d8e11"},
                "something_new": {"nested": [1, 2, 3]}
            },
            "also_new": true
        }"#;
        let ev = parse_event("msg_1", body).unwrap();
        assert_eq!(ev.id, "msg_1");
        assert_eq!(ev.kind, "subscription.active");
        assert_eq!(
            ev.timestamp,
            Some(OffsetDateTime::parse("2026-10-05T10:00:00.123456Z", &Rfc3339).unwrap())
        );
        let sub = ev.subscription.unwrap();
        assert_eq!(sub.subscription_id.as_deref(), Some("sub_1"));
        assert_eq!(sub.product_id.as_deref(), Some("pdt_pro"));
        assert_eq!(sub.customer_id.as_deref(), Some("cus_1"));
        assert_eq!(sub.customer_email.as_deref(), Some("ana@example.com"));
        assert_eq!(sub.status.as_deref(), Some("active"));
        assert_eq!(
            sub.next_billing_date,
            Some(OffsetDateTime::parse("2026-11-05T10:00:00Z", &Rfc3339).unwrap())
        );
        assert_eq!(
            sub.metadata_account_id.as_deref(),
            Some("6f1d9a54-6b0e-4a39-9f43-0c2a8b6d8e11")
        );
    }

    #[test]
    fn missing_fields_and_other_events_are_tolerated() {
        let ev = parse_event("m", br#"{"type":"subscription.on_hold","data":{}}"#).unwrap();
        let sub = ev.subscription.unwrap();
        assert_eq!(sub.subscription_id, None);
        assert_eq!(ev.timestamp, None);

        let ev = parse_event(
            "m",
            br#"{"type":"payment.succeeded","data":{"payment_id":"p"}}"#,
        )
        .unwrap();
        assert_eq!(ev.kind, "payment.succeeded");
        assert!(ev.subscription.is_none());

        // A timestamp without an offset is read as UTC; garbage is "unknown".
        let ev = parse_event("m", br#"{"type":"x","timestamp":"2026-10-05T10:00:00"}"#).unwrap();
        assert!(ev.timestamp.is_some());
        let ev = parse_event("m", br#"{"type":"x","timestamp":"soon"}"#).unwrap();
        assert!(ev.timestamp.is_none());

        assert!(parse_event("m", b"not json").is_err());
    }
}