ankusa 0.6.0

Client SDK for Ankusa, the self-hosted webhook receiver: claim-check redemption, webhook header parsing, and the route-management and operator APIs.
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
//! Decoding the queue message Ankusa publishes to every sink.
//!
//! A consumer receives the message JSON, decodes it with [`decode_message`],
//! and deduplicates on [`Message::idempotency_key`]. The message carries the
//! body inline (`body_base64`) or as a claim-check ref (`claim`), the body's
//! sha256, the provider's `dedupe_key`, the forwarded request `headers`, the
//! `replay_id` when the delivery is a replay, and the `idempotency_key` Ankusa
//! computed for the hook.

use std::collections::BTreeMap;

use base64::Engine as _;
use base64::engine::general_purpose::STANDARD as BASE64;
use serde_json::Value;
use sha2::{Digest, Sha256};

use crate::claim_ref::parse_claim_ref;
use crate::webhook::Verification;

/// The lowest message `v` [`decode_message`] accepts.
///
/// `v` is the wire format's major version: a `v: 2` message is a `v: 1`
/// message plus additive fields, decoded exactly like it (the keys this
/// decoder does not know are ignored) into the one [`Message`] type, with `v`
/// as the wire said it. Raising [`MAX_SUPPORTED_VERSION`] is the whole change
/// an SDK needs for a producer that starts writing the next additive version.
pub const MIN_SUPPORTED_VERSION: u64 = 1;

/// The highest message `v` [`decode_message`] accepts.
pub const MAX_SUPPORTED_VERSION: u64 = 2;

/// A decoded queue message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Message {
    /// The format version the message carried, from [`MIN_SUPPORTED_VERSION`]
    /// to [`MAX_SUPPORTED_VERSION`].
    pub v: u64,
    /// The envelope id, a `UUIDv7`.
    pub id: String,
    /// The source the hook was captured under.
    pub source_id: String,
    /// The tenant, when the source carries one.
    pub tenant_id: Option<String>,
    /// When the edge received the hook, unix milliseconds.
    pub received_at: i64,
    /// The captured content type, when the sender set one.
    pub content_type: Option<String>,
    /// Body size in bytes.
    pub size: u64,
    /// The decoded body bytes for the inline form; `None` for a claim.
    pub body: Option<Vec<u8>>,
    /// The claim-check ref for the claim form; `None` for an inline body.
    pub claim: Option<String>,
    /// Lowercase hex SHA-256 of the body, when the message carries one.
    pub sha256: Option<String>,
    /// The provider event key ingest extracted, when there is one.
    pub dedupe_key: Option<String>,
    /// The replay job id, when this delivery is a replay.
    pub replay_id: Option<String>,
    /// The tenant-scoped key Ankusa computed for the hook, when the message
    /// carries one (a node that predates the field sends none). Read it
    /// through [`Message::idempotency_key`].
    pub idempotency_key: Option<String>,
    /// The forwarded provider request headers, lowercased.
    pub headers: BTreeMap<String, String>,
    /// How Ankusa verified the hook at ingest; `None` from a node older than
    /// the field.
    pub verification: Option<Verification>,
    /// The hook's W3C `traceparent`, verbatim: continue the trace from it.
    /// `None` when the message carries none (or comes from a node older than
    /// the field).
    pub traceparent: Option<String>,
    /// The W3C `tracestate` that goes with `traceparent`, verbatim.
    pub tracestate: Option<String>,
    /// The name of the Ankusa instance that published the message; `None` when
    /// it says `null` or comes from a node older than the field.
    pub instance: Option<String>,
    /// The region that instance is configured with; `None` when it has none or
    /// comes from a node older than the field.
    pub region: Option<String>,
}

impl Message {
    /// The idempotency key for this delivery.
    ///
    /// It is the key Ankusa shipped in the message's `idempotency_key` when
    /// that is a non-empty string. For a message from a node that predates the
    /// field it is computed: `tenant:source_id:dedupe_key` (tenant `default`
    /// when there is none) for a non-empty `dedupe_key`, otherwise `id`.
    ///
    /// With `include_replay`, a non-null `replay_id` appends
    /// `#replay:<replay_id>`, so a consumer that must reprocess replays treats
    /// them as distinct. The default (`false`) drops replays of events it
    /// already processed.
    #[must_use]
    pub fn idempotency_key(&self, include_replay: bool) -> String {
        KeyParts {
            shipped: self.idempotency_key.as_deref(),
            tenant: self.tenant_id.as_deref(),
            source: &self.source_id,
            dedupe_key: self.dedupe_key.as_deref(),
            id: &self.id,
            replay_id: self.replay_id.as_deref(),
        }
        .key(include_replay)
    }

    /// Whether the node verified this message's hook at ingest and nothing
    /// flags it (see [`Verification::is_trusted`]). A message with no
    /// `verification` (a node older than the field) is untrusted.
    #[must_use]
    pub fn is_trusted(&self) -> bool {
        self.verification
            .as_ref()
            .is_some_and(Verification::is_trusted)
    }
}

/// The fields the idempotency key is built from, borrowed from a [`Message`]
/// or from the `HookHeaders` of a delivery. The one place the rule lives.
pub(crate) struct KeyParts<'a> {
    pub(crate) shipped: Option<&'a str>,
    pub(crate) tenant: Option<&'a str>,
    pub(crate) source: &'a str,
    pub(crate) dedupe_key: Option<&'a str>,
    pub(crate) id: &'a str,
    pub(crate) replay_id: Option<&'a str>,
}

impl KeyParts<'_> {
    pub(crate) fn key(&self, include_replay: bool) -> String {
        let mut key = if let Some(shipped) = self.shipped.filter(|key| !key.is_empty()) {
            shipped.to_owned()
        } else if let Some(dedupe_key) = self.dedupe_key.filter(|key| !key.is_empty()) {
            format!(
                "{}:{}:{}",
                self.tenant.unwrap_or("default"),
                self.source,
                dedupe_key
            )
        } else {
            self.id.to_owned()
        };
        if include_replay {
            if let Some(replay_id) = self.replay_id {
                key.push_str("#replay:");
                key.push_str(replay_id);
            }
        }
        key
    }
}

/// A queue message that cannot be decoded.
///
/// Never retryable: the same bytes decode the same way forever, so send the
/// delivery to a dead-letter queue instead of asking for it again.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
#[error("invalid message ({code})")]
pub struct InvalidMessageError {
    /// The machine-readable failure code, e.g. `invalid_json` or
    /// `invalid_field`.
    pub code: &'static str,
    /// The offending key when `code` is `invalid_field`, else `None`.
    pub field: Option<&'static str>,
}

impl InvalidMessageError {
    pub(crate) fn new(code: &'static str, field: Option<&'static str>) -> Self {
        Self { code, field }
    }

    /// Whether calling again later could succeed. Always `false`.
    #[must_use]
    pub fn is_retryable(&self) -> bool {
        false
    }
}

/// Decodes a queue message of any supported `v` ([`MIN_SUPPORTED_VERSION`] to
/// [`MAX_SUPPORTED_VERSION`]).
///
/// Unknown keys are ignored. An absent `dedupe_key`, `replay_id`,
/// `idempotency_key` or `sha256` decodes to `None`; an absent `headers`
/// decodes to an empty map.
///
/// # Errors
///
/// [`InvalidMessageError`], never retryable, with `code` (and `field` for
/// `invalid_field`): `invalid_json`, `not_an_object`, `unsupported_version`,
/// `invalid_field`, `ambiguous_body`, `missing_body`, `invalid_body_base64`,
/// `size_mismatch`, `integrity`, or `tenant_mismatch`. The checks run in that
/// order and the first failure wins.
pub fn decode_message(data: &[u8]) -> Result<Message, InvalidMessageError> {
    let value: Value = serde_json::from_slice(data).map_err(|_| invalid("invalid_json", None))?;
    let Value::Object(map) = value else {
        return Err(invalid("not_an_object", None));
    };

    let version = map
        .get("v")
        .and_then(Value::as_u64)
        .filter(|version| (MIN_SUPPORTED_VERSION..=MAX_SUPPORTED_VERSION).contains(version))
        .ok_or_else(|| invalid("unsupported_version", None))?;

    // Field types, in the contract's order.
    let id = required_string(&map, "id")?;
    if id.is_empty() {
        return Err(invalid("invalid_field", Some("id")));
    }
    let source_id = required_string(&map, "source_id")?;
    let received_at = map
        .get("received_at")
        .and_then(Value::as_i64)
        .ok_or_else(|| invalid("invalid_field", Some("received_at")))?;
    let size = map
        .get("size")
        .and_then(Value::as_u64)
        .ok_or_else(|| invalid("invalid_field", Some("size")))?;
    let tenant_id = optional_string(&map, "tenant_id")?;
    let content_type = optional_string(&map, "content_type")?;
    let dedupe_key = optional_string(&map, "dedupe_key")?;
    let replay_id = optional_string(&map, "replay_id")?;
    let idempotency_key = optional_string(&map, "idempotency_key")?;
    let traceparent = optional_string(&map, "traceparent")?;
    let tracestate = optional_string(&map, "tracestate")?;
    let instance = optional_string(&map, "instance")?;
    let region = optional_string(&map, "region")?;
    let headers = headers_field(&map)?;
    let sha256 = sha256_field(&map)?;
    let verification = verification_field(&map)?;

    // Body form.
    let has_body = map.get("body_base64").is_some_and(|value| !value.is_null());
    let has_claim = map.get("claim").is_some_and(|value| !value.is_null());
    if has_body && has_claim {
        return Err(invalid("ambiguous_body", None));
    }
    if !has_body && !has_claim {
        return Err(invalid("missing_body", None));
    }

    let mut body = None;
    let mut claim = None;
    if has_body {
        let encoded = map
            .get("body_base64")
            .and_then(Value::as_str)
            .ok_or_else(|| invalid("invalid_body_base64", None))?;
        let decoded = BASE64
            .decode(encoded)
            .map_err(|_| invalid("invalid_body_base64", None))?;
        if decoded.len() as u64 != size {
            return Err(invalid("size_mismatch", None));
        }
        if let Some(expected) = &sha256 {
            if &hex::encode(Sha256::digest(&decoded)) != expected {
                return Err(invalid("integrity", None));
            }
        }
        body = Some(decoded);
    } else {
        let claim_ref = map
            .get("claim")
            .and_then(Value::as_str)
            .ok_or_else(|| invalid("invalid_field", Some("claim")))?;
        let parsed =
            parse_claim_ref(claim_ref).map_err(|_| invalid("invalid_field", Some("claim")))?;
        if sha256.is_none() {
            return Err(invalid("invalid_field", Some("sha256")));
        }
        if let Some(tenant) = &tenant_id {
            if tenant != parsed.tenant_id() {
                return Err(invalid("tenant_mismatch", None));
            }
        }
        claim = Some(claim_ref.to_owned());
    }

    Ok(Message {
        v: version,
        id,
        source_id,
        tenant_id,
        received_at,
        content_type,
        size,
        body,
        claim,
        sha256,
        dedupe_key,
        replay_id,
        idempotency_key,
        headers,
        verification,
        traceparent,
        tracestate,
        instance,
        region,
    })
}

fn invalid(code: &'static str, field: Option<&'static str>) -> InvalidMessageError {
    InvalidMessageError::new(code, field)
}

fn required_string(
    map: &serde_json::Map<String, Value>,
    key: &'static str,
) -> Result<String, InvalidMessageError> {
    match map.get(key) {
        Some(Value::String(value)) => Ok(value.clone()),
        _ => Err(invalid("invalid_field", Some(key))),
    }
}

fn optional_string(
    map: &serde_json::Map<String, Value>,
    key: &'static str,
) -> Result<Option<String>, InvalidMessageError> {
    match map.get(key) {
        None | Some(Value::Null) => Ok(None),
        Some(Value::String(value)) => Ok(Some(value.clone())),
        Some(_) => Err(invalid("invalid_field", Some(key))),
    }
}

fn headers_field(
    map: &serde_json::Map<String, Value>,
) -> Result<BTreeMap<String, String>, InvalidMessageError> {
    let Some(value) = map.get("headers") else {
        return Ok(BTreeMap::new());
    };
    let Value::Object(headers) = value else {
        // `null` means "no headers"; any other non-object is a violation.
        return match value {
            Value::Null => Ok(BTreeMap::new()),
            _ => Err(invalid("invalid_field", Some("headers"))),
        };
    };
    let mut out = BTreeMap::new();
    for (name, value) in headers {
        match value.as_str() {
            Some(value) => out.insert(name.clone(), value.to_owned()),
            None => return Err(invalid("invalid_field", Some("headers"))),
        };
    }
    Ok(out)
}

/// `sha256` is absent, or 64 lowercase hex characters; an explicit `null` is
/// not a valid checksum.
fn sha256_field(
    map: &serde_json::Map<String, Value>,
) -> Result<Option<String>, InvalidMessageError> {
    match map.get("sha256") {
        None => Ok(None),
        Some(Value::String(value)) if is_lowercase_hex_64(value) => Ok(Some(value.clone())),
        _ => Err(invalid("invalid_field", Some("sha256"))),
    }
}

fn is_lowercase_hex_64(value: &str) -> bool {
    value.len() == 64
        && value
            .bytes()
            .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))
}

/// `verification` is absent or `null` (predates the field), or an object of
/// a non-empty string `status` and a boolean `flagged`; any other shape is
/// `invalid_field`. The status value itself is never validated: unknown
/// statuses pass through untouched.
fn verification_field(
    map: &serde_json::Map<String, Value>,
) -> Result<Option<Verification>, InvalidMessageError> {
    match map.get("verification") {
        None | Some(Value::Null) => Ok(None),
        Some(Value::Object(fields)) => {
            let status = match fields.get("status") {
                Some(Value::String(status)) if !status.is_empty() => status.clone(),
                _ => return Err(invalid("invalid_field", Some("verification"))),
            };
            let flagged = match fields.get("flagged") {
                Some(Value::Bool(flagged)) => *flagged,
                _ => return Err(invalid("invalid_field", Some("verification"))),
            };
            Ok(Some(Verification { status, flagged }))
        }
        Some(_) => Err(invalid("invalid_field", Some("verification"))),
    }
}

#[cfg(test)]
mod tests {
    use super::{InvalidMessageError, Verification, decode_message};

    fn err(data: &str) -> InvalidMessageError {
        decode_message(data.as_bytes()).expect_err("invalid message")
    }

    #[test]
    fn accepts_every_supported_version_and_reports_the_wire_one() {
        for v in super::MIN_SUPPORTED_VERSION..=super::MAX_SUPPORTED_VERSION {
            let data = format!(
                r#"{{"v":{v},"id":"01a0","source_id":"s","received_at":1,"size":5,
                    "body_base64":"aGVsbG8=","priority":"high"}}"#
            );
            let message = decode_message(data.as_bytes()).expect("valid message");
            assert_eq!(message.v, v);
            assert_eq!(message.body.as_deref(), Some(b"hello".as_slice()));
        }
    }

    #[test]
    fn instance_and_region_are_optional_strings() {
        let message = decode_message(
            br#"{"v":2,"id":"01a0","source_id":"s","received_at":1,"size":5,
                 "body_base64":"aGVsbG8=","instance":"ankusa-eu-1","region":"eu-west-1"}"#,
        )
        .expect("valid message");
        assert_eq!(message.instance.as_deref(), Some("ankusa-eu-1"));
        assert_eq!(message.region.as_deref(), Some("eu-west-1"));

        let bad = err(
            r#"{"v":1,"id":"01a0","source_id":"s","received_at":1,"size":5,
                "body_base64":"aGVsbG8=","instance":7,"region":1}"#,
        );
        assert_eq!((bad.code, bad.field), ("invalid_field", Some("instance")));
    }

    #[test]
    fn decodes_an_inline_body_and_computes_the_key() {
        let message = decode_message(
            br#"{"v":1,"id":"01a0","source_id":"stripe","received_at":1,"size":5,
                 "body_base64":"aGVsbG8=","dedupe_key":"evt_1"}"#,
        )
        .expect("valid message");
        assert_eq!(message.body.as_deref(), Some(b"hello".as_slice()));
        assert_eq!(message.idempotency_key(false), "default:stripe:evt_1");
        assert_eq!(message.idempotency_key(true), "default:stripe:evt_1");
    }

    #[test]
    fn replays_are_distinct_only_when_asked() {
        let message = decode_message(
            br#"{"v":1,"id":"01a0","source_id":"stripe","received_at":1,"size":5,
                 "body_base64":"aGVsbG8=","dedupe_key":"evt_1","replay_id":"rid-1"}"#,
        )
        .expect("valid message");
        assert_eq!(message.idempotency_key(false), "default:stripe:evt_1");
        assert_eq!(
            message.idempotency_key(true),
            "default:stripe:evt_1#replay:rid-1"
        );
    }

    #[test]
    fn the_shipped_key_wins_over_recomputing_it() {
        let message = decode_message(
            br#"{"v":1,"id":"01a0","source_id":"demo","tenant_id":"globex","received_at":1,
                 "size":5,"body_base64":"aGVsbG8=","dedupe_key":"other","replay_id":"rid-1",
                 "idempotency_key":"acme:stripe:evt_1"}"#,
        )
        .expect("valid message");
        assert_eq!(message.idempotency_key(false), "acme:stripe:evt_1");
        assert_eq!(
            message.idempotency_key(true),
            "acme:stripe:evt_1#replay:rid-1"
        );
    }

    #[test]
    fn a_tenant_scopes_the_computed_key() {
        let message = decode_message(
            br#"{"v":1,"id":"01a0","source_id":"stripe","tenant_id":"acme","received_at":1,
                 "size":5,"body_base64":"aGVsbG8=","dedupe_key":"evt_1"}"#,
        )
        .expect("valid message");
        assert_eq!(message.idempotency_key(false), "acme:stripe:evt_1");
    }

    #[test]
    fn a_non_string_idempotency_key_is_invalid() {
        let bad = err(
            r#"{"v":1,"id":"01a0","source_id":"s","received_at":1,"size":5,
                "body_base64":"aGVsbG8=","idempotency_key":7}"#,
        );
        assert_eq!(bad.code, "invalid_field");
        assert_eq!(bad.field, Some("idempotency_key"));
    }

    #[test]
    fn the_first_failure_wins() {
        assert_eq!(err("not json").code, "invalid_json");
        assert_eq!(err("[1,2,3]").code, "not_an_object");
        assert_eq!(err(r#"{"v":3}"#).code, "unsupported_version");
        assert_eq!(err(r#"{"v":0}"#).code, "unsupported_version");
        assert_eq!(err(r#"{"v":"1"}"#).code, "unsupported_version");
        let missing_id = err(r#"{"v":1,"source_id":"s","received_at":1,"size":0}"#);
        assert_eq!(missing_id.code, "invalid_field");
        assert_eq!(missing_id.field, Some("id"));
    }

    #[test]
    fn rejects_a_bad_checksum_and_a_size_mismatch() {
        let size = err(
            r#"{"v":1,"id":"01a0","source_id":"s","received_at":1,"size":6,
                "body_base64":"aGVsbG8="}"#,
        );
        assert_eq!(size.code, "size_mismatch");
        let digest = err(
            r#"{"v":1,"id":"01a0","source_id":"s","received_at":1,"size":5,
                "body_base64":"aGVsbG8=",
                "sha256":"d9298a10d1b0735837dc4bd85dac641b0f3cef27a47e5d53a54f2f3f5b2fcffa"}"#,
        );
        assert_eq!(digest.code, "integrity");
    }

    #[test]
    fn verification_absent_decodes_to_none() {
        let message = decode_message(
            br#"{"v":1,"id":"01a0","source_id":"s","received_at":1,"size":5,
                "body_base64":"aGVsbG8="}"#,
        )
        .expect("valid message");
        assert_eq!(message.verification, None);
    }

    #[test]
    fn verification_flagged_is_true() {
        let message = decode_message(
            br#"{"v":1,"id":"01a0","source_id":"s","received_at":1,"size":5,
                "body_base64":"aGVsbG8=",
                "verification":{"status":"failed","flagged":true}}"#,
        )
        .expect("valid message");
        assert_eq!(
            message.verification,
            Some(Verification {
                status: "failed".to_owned(),
                flagged: true,
            })
        );
    }

    #[test]
    fn verification_malformed_is_an_invalid_field() {
        let bad = err(
            r#"{"v":1,"id":"01a0","source_id":"s","received_at":1,"size":5,
                "body_base64":"aGVsbG8=","verification":"ok"}"#,
        );
        assert_eq!(bad.code, "invalid_field");
        assert_eq!(bad.field, Some("verification"));
    }

    #[test]
    fn is_trusted_is_false_for_a_flagged_or_absent_verification() {
        let decode = |verification: &str| {
            decode_message(
                format!(
                    r#"{{"v":1,"id":"01a0","source_id":"s","received_at":1,"size":5,
                        "body_base64":"aGVsbG8="{verification}}}"#
                )
                .as_bytes(),
            )
            .expect("valid message")
        };
        assert!(decode(r#","verification":{"status":"ok","flagged":false}"#).is_trusted());
        assert!(!decode(r#","verification":{"status":"failed","flagged":true}"#).is_trusted());
        assert!(!decode(r#","verification":{"status":"skipped","flagged":false}"#).is_trusted());
        assert!(!decode("").is_trusted());
    }
}