wellfriend-document-sdk 1.0.0

Official async Rust SDK for the Wellfriend document API: typed document tools, pipelines, streaming uploads and downloads, retries and webhook verification.
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
//! Verifying signed webhook deliveries (Standard Webhooks, HMAC-SHA256).

use std::collections::HashMap;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use base64::Engine;
use hmac::{Hmac, Mac};
use reqwest::header::HeaderMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::Sha256;

use crate::client::{RequestOptions, Wellfriend};
use crate::error::{Error, Result};
use crate::generated::events::WebhookEventData;
use crate::Object;

/// How far a delivery's timestamp may be from now (5 minutes).
pub const DEFAULT_TOLERANCE: Duration = Duration::from_secs(300);

/// A verified webhook event (CloudEvents 1.0).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct WebhookEvent {
    /// The event id (`evt_...`), also sent as `webhook-id`. Deduplicate on it.
    pub id: String,
    /// The event type, for example `com.wellfriend.document-operation.completed.v2`.
    #[serde(rename = "type")]
    pub event_type: String,
    /// The workspace that produced the event (`wellfriend://workspaces/ws_...`).
    #[serde(default)]
    pub source: String,
    /// The id of the resource the event is about.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub subject: Option<String>,
    /// When the event was recorded (RFC 3339).
    #[serde(default)]
    pub time: String,
    /// Always `1.0`.
    #[serde(default)]
    pub specversion: String,
    /// The payload, typed by event type (`Unknown` for types this SDK version does not know).
    #[serde(skip)]
    pub data: WebhookEventData,
    /// The payload as sent.
    #[serde(rename = "data", default)]
    pub raw_data: Value,
    /// Ordering metadata.
    #[serde(default)]
    pub wellfriend: WebhookEventMeta,
    /// Fields this SDK version does not model.
    #[serde(flatten)]
    pub extra: Object,
}

/// The `wellfriend` extension of every event.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct WebhookEventMeta {
    /// When the change happened (the same instant as `time`).
    #[serde(default)]
    pub occurred_at: String,
    /// The resource revision, when it has one.
    #[serde(default)]
    pub resource_revision: Option<i64>,
    /// A decimal sequence for ordering events about one resource.
    #[serde(default)]
    pub sequence: Option<String>,
    /// Fields this SDK version does not model.
    #[serde(flatten)]
    pub extra: Object,
}

impl WebhookEvent {
    /// Parses an event body without verifying it. Use [`verify_webhook`] for deliveries.
    pub fn parse(payload: &[u8]) -> Result<Self> {
        let mut event: WebhookEvent = serde_json::from_slice(payload).map_err(|error| {
            Error::WebhookVerification(format!("the body is not an event: {error}"))
        })?;
        event.data = WebhookEventData::parse(&event.event_type, event.raw_data.clone());
        Ok(event)
    }
}

/// Request headers, from any HTTP framework.
pub trait WebhookHeaders {
    /// The value of a header, by case-insensitive name.
    fn header(&self, name: &str) -> Option<String>;
}

impl WebhookHeaders for HeaderMap {
    fn header(&self, name: &str) -> Option<String> {
        self.get(name)
            .and_then(|value| value.to_str().ok())
            .map(str::to_owned)
    }
}

impl<K: AsRef<str>, V: AsRef<str>> WebhookHeaders for HashMap<K, V> {
    fn header(&self, name: &str) -> Option<String> {
        self.iter()
            .find(|(key, _)| key.as_ref().eq_ignore_ascii_case(name))
            .map(|(_, value)| value.as_ref().to_owned())
    }
}

impl<K: AsRef<str>, V: AsRef<str>> WebhookHeaders for [(K, V)] {
    fn header(&self, name: &str) -> Option<String> {
        self.iter()
            .find(|(key, _)| key.as_ref().eq_ignore_ascii_case(name))
            .map(|(_, value)| value.as_ref().to_owned())
    }
}

impl<K: AsRef<str>, V: AsRef<str>> WebhookHeaders for Vec<(K, V)> {
    fn header(&self, name: &str) -> Option<String> {
        self.as_slice().header(name)
    }
}

impl<T: WebhookHeaders + ?Sized> WebhookHeaders for &T {
    fn header(&self, name: &str) -> Option<String> {
        (**self).header(name)
    }
}

/// Verifies a webhook delivery and returns the typed event.
///
/// `payload` must be the raw request body exactly as received. `secret` is the endpoint's signing
/// secret (`whsec_...`). The signature (`webhook-signature`, `v1,<base64 HMAC-SHA256>` over
/// `{webhook-id}.{webhook-timestamp}.{body}`) and a timestamp within 5 minutes are both required.
/// For several secrets (during rotation) use [`WebhookVerifier`].
///
/// ```no_run
/// # fn handle(body: &[u8], headers: &reqwest::header::HeaderMap) -> wellfriend::Result<()> {
/// let event = wellfriend::verify_webhook(body, headers, "whsec_...")?;
/// if let wellfriend::WebhookEventData::DocumentOperationCompletedV2(data) = &event.data {
///     println!("operation {} finished", data.operation_id);
/// }
/// # Ok(())
/// # }
/// ```
pub fn verify_webhook(
    payload: &[u8],
    headers: impl WebhookHeaders,
    secret: &str,
) -> Result<WebhookEvent> {
    WebhookVerifier::new([secret]).verify(payload, headers)
}

/// A webhook verifier with one or more secrets and a configurable tolerance.
#[derive(Clone)]
pub struct WebhookVerifier {
    secrets: Vec<String>,
    public_keys: Vec<String>,
    tolerance: Duration,
    now: Option<SystemTime>,
}

impl std::fmt::Debug for WebhookVerifier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WebhookVerifier")
            .field("secrets", &self.secrets.len())
            .field("tolerance", &self.tolerance)
            .finish()
    }
}

impl WebhookVerifier {
    /// A verifier accepting a signature made with any of `secrets`.
    pub fn new<I, S>(secrets: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        WebhookVerifier {
            secrets: secrets.into_iter().map(Into::into).collect(),
            public_keys: Vec::new(),
            tolerance: DEFAULT_TOLERANCE,
            now: None,
        }
    }

    /// A verifier for an endpoint created with the `ED25519` signature scheme: `public_keys` are
    /// the endpoint's public keys (standard base64 of the raw 32-byte key). Signatures arrive as
    /// `v1a,<base64 Ed25519 signature>` over the same signed content.
    #[cfg(feature = "ed25519")]
    #[cfg_attr(docsrs, doc(cfg(feature = "ed25519")))]
    pub fn ed25519<I, S>(public_keys: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        WebhookVerifier {
            secrets: Vec::new(),
            public_keys: public_keys.into_iter().map(Into::into).collect(),
            tolerance: DEFAULT_TOLERANCE,
            now: None,
        }
    }

    /// How far the timestamp may be from now (default 5 minutes).
    pub fn tolerance(mut self, tolerance: Duration) -> Self {
        self.tolerance = tolerance;
        self
    }

    /// Verifies as if the current time were `now` (for tests and replays).
    pub fn at(mut self, now: SystemTime) -> Self {
        self.now = Some(now);
        self
    }

    /// Verifies a delivery and returns the typed event.
    pub fn verify(&self, payload: &[u8], headers: impl WebhookHeaders) -> Result<WebhookEvent> {
        let fail = |message: &str| Error::WebhookVerification(message.to_owned());
        let id = headers
            .header("webhook-id")
            .filter(|id| !id.is_empty())
            .ok_or_else(|| fail("the webhook-id header is missing"))?;
        let timestamp = headers
            .header("webhook-timestamp")
            .ok_or_else(|| fail("the webhook-timestamp header is missing"))?;
        let signatures = headers
            .header("webhook-signature")
            .ok_or_else(|| fail("the webhook-signature header is missing"))?;
        let seconds: i64 = timestamp
            .trim()
            .parse()
            .map_err(|_| fail("the webhook-timestamp header is not a Unix time"))?;
        let now = self
            .now
            .unwrap_or_else(SystemTime::now)
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs() as i64)
            .unwrap_or(0);
        if (now - seconds).unsigned_abs() > self.tolerance.as_secs() {
            return Err(fail("the timestamp is outside the allowed tolerance"));
        }
        let keys: Vec<Vec<u8>> = self
            .secrets
            .iter()
            .filter_map(|secret| decode_secret(secret))
            .collect();
        if keys.is_empty() && self.public_keys.is_empty() {
            return Err(fail(
                "no valid signing secret was given (expected whsec_...)",
            ));
        }
        let candidates: Vec<Vec<u8>> = signatures
            .split_whitespace()
            .filter_map(|entry| entry.split_once(','))
            .filter(|(version, _)| *version == "v1")
            .filter_map(|(_, encoded)| {
                base64::engine::general_purpose::STANDARD
                    .decode(encoded)
                    .ok()
            })
            .collect();
        let signed_prefix = format!("{id}.{seconds}.");
        let matched = keys.iter().any(|key| {
            let Ok(mut mac) = Hmac::<Sha256>::new_from_slice(key) else {
                return false;
            };
            mac.update(signed_prefix.as_bytes());
            mac.update(payload);
            let expected = mac.finalize().into_bytes();
            candidates
                .iter()
                .any(|candidate| constant_time_eq(&expected, candidate))
        });
        if !matched && !self.ed25519_matches(&signatures, signed_prefix.as_bytes(), payload) {
            return Err(fail("no signature matches"));
        }
        WebhookEvent::parse(payload)
    }
}

impl WebhookVerifier {
    #[cfg(feature = "ed25519")]
    fn ed25519_matches(&self, signatures: &str, prefix: &[u8], payload: &[u8]) -> bool {
        use ed25519_dalek::{Signature, Verifier as _, VerifyingKey};
        let engine = base64::engine::general_purpose::STANDARD;
        let keys: Vec<VerifyingKey> = self
            .public_keys
            .iter()
            .filter_map(|key| engine.decode(key.trim()).ok())
            .filter_map(|bytes| <[u8; 32]>::try_from(bytes.as_slice()).ok())
            .filter_map(|bytes| VerifyingKey::from_bytes(&bytes).ok())
            .collect();
        let mut message = Vec::with_capacity(prefix.len() + payload.len());
        message.extend_from_slice(prefix);
        message.extend_from_slice(payload);
        signatures
            .split_whitespace()
            .filter_map(|entry| entry.split_once(','))
            .filter(|(version, _)| *version == "v1a")
            .filter_map(|(_, encoded)| engine.decode(encoded).ok())
            .filter_map(|bytes| Signature::from_slice(&bytes).ok())
            .any(|signature| {
                keys.iter()
                    .any(|key| key.verify(&message, &signature).is_ok())
            })
    }

    #[cfg(not(feature = "ed25519"))]
    fn ed25519_matches(&self, _signatures: &str, _prefix: &[u8], _payload: &[u8]) -> bool {
        let _ = &self.public_keys;
        false
    }
}

/// The HMAC key of a `whsec_` secret: standard base64, or the unpadded base64url of older
/// endpoints (both decode to the same bytes).
fn decode_secret(secret: &str) -> Option<Vec<u8>> {
    let trimmed = secret.trim();
    let encoded: String = trimmed
        .strip_prefix("whsec_")
        .unwrap_or(trimmed)
        .trim_end_matches('=')
        .replace('-', "+")
        .replace('_', "/");
    let key = base64::engine::general_purpose::STANDARD_NO_PAD
        .decode(encoded.as_bytes())
        .ok()?;
    (key.len() >= 16).then_some(key)
}

fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
    a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
}

/// Webhook helpers on the client. Get it with [`Wellfriend::webhooks`].
#[derive(Clone, Debug)]
pub struct Webhooks {
    pub(crate) client: Wellfriend,
    pub(crate) options: RequestOptions,
}

impl Webhooks {
    /// The same handle with these options for every call made through it.
    pub fn with_options(mut self, options: RequestOptions) -> Self {
        self.options = options;
        self
    }

    /// Verifies a delivery locally; the same as [`verify_webhook`].
    pub fn verify(
        &self,
        payload: &[u8],
        headers: impl WebhookHeaders,
        secret: &str,
    ) -> Result<WebhookEvent> {
        verify_webhook(payload, headers, secret)
    }
}

impl Wellfriend {
    /// Webhook endpoints, deliveries and local signature verification.
    pub fn webhooks(&self) -> Webhooks {
        Webhooks {
            client: self.clone(),
            options: RequestOptions::default(),
        }
    }
}

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

    const SECRET: &str = "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw";
    const BODY: &str = r#"{"test": 2432232314}"#;

    fn headers(signature: &str) -> Vec<(&'static str, String)> {
        vec![
            ("webhook-id", "msg_p5jXN8AQM9LWM0D4loKWxJek".into()),
            ("webhook-timestamp", "1614265330".into()),
            ("webhook-signature", signature.into()),
        ]
    }

    fn at() -> SystemTime {
        UNIX_EPOCH + Duration::from_secs(1_614_265_330)
    }

    #[test]
    fn checks_the_signature_and_the_secret_list() {
        let good = headers("v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE=");
        // The body is not an event, so a correct signature reaches the parse step.
        let error = WebhookVerifier::new([SECRET])
            .at(at())
            .verify(BODY.as_bytes(), &good)
            .unwrap_err();
        assert!(error.to_string().contains("not an event"), "{error}");
        let wrong = WebhookVerifier::new(["whsec_AAAAAAAAAAAAAAAAAAAAAAAAAAAA"])
            .at(at())
            .verify(BODY.as_bytes(), &good)
            .unwrap_err();
        assert!(wrong.to_string().contains("no signature matches"));
        let rotated = WebhookVerifier::new(["whsec_AAAAAAAAAAAAAAAAAAAAAAAAAAAA", SECRET])
            .at(at())
            .verify(BODY.as_bytes(), &good)
            .unwrap_err();
        assert!(rotated.to_string().contains("not an event"));
    }

    #[cfg(feature = "ed25519")]
    #[test]
    fn verifies_ed25519_signatures() {
        use ed25519_dalek::{Signer, SigningKey};
        let signing = SigningKey::from_bytes(&[9u8; 32]);
        let public =
            base64::engine::general_purpose::STANDARD.encode(signing.verifying_key().to_bytes());
        let signature =
            signing.sign(format!("msg_p5jXN8AQM9LWM0D4loKWxJek.1614265330.{BODY}").as_bytes());
        let header = format!(
            "v1a,{}",
            base64::engine::general_purpose::STANDARD.encode(signature.to_bytes())
        );
        let error = WebhookVerifier::ed25519([public.clone()])
            .at(at())
            .verify(BODY.as_bytes(), headers(&header))
            .unwrap_err();
        assert!(error.to_string().contains("not an event"), "{error}");
        let other = base64::engine::general_purpose::STANDARD.encode(
            SigningKey::from_bytes(&[1u8; 32])
                .verifying_key()
                .to_bytes(),
        );
        let error = WebhookVerifier::ed25519([other])
            .at(at())
            .verify(BODY.as_bytes(), headers(&header))
            .unwrap_err();
        assert!(error.to_string().contains("no signature matches"));
    }

    #[test]
    fn decodes_both_secret_alphabets() {
        assert_eq!(
            decode_secret("whsec_+//+fT4/AAECAwT7/wUGBwgJ+gsMDQ4P+//+EBESExQV"),
            decode_secret("whsec_-__-fT4_AAECAwT7_wUGBwgJ-gsMDQ4P-__-EBESExQV")
        );
        assert!(decode_secret("whsec_short").is_none());
    }
}