Skip to main content

hatchet_rest/
webhooks.rs

1//! Incoming webhooks: an HTTP endpoint on the engine that turns a
2//! provider's request into an event (`v1-webhook:*`). A webhook is
3//! addressed by its **name**, not an id.
4
5use std::fmt;
6
7use serde::{Deserialize, Serialize};
8
9use crate::transport::Query;
10use crate::types::{string_enum, to_object};
11use crate::{Error, JsonObject, Operation, Page, ResourceMeta, RestClient, Result};
12
13string_enum! {
14    /// Who sends the webhook (`V1WebhookSourceName`).
15    WebhookSource {
16        /// Anyone.
17        Generic => "GENERIC",
18        /// GitHub.
19        Github => "GITHUB",
20        /// Stripe.
21        Stripe => "STRIPE",
22        /// Slack.
23        Slack => "SLACK",
24        /// Linear.
25        Linear => "LINEAR",
26        /// Svix.
27        Svix => "SVIX",
28    }
29}
30
31string_enum! {
32    /// How a webhook authenticates its sender (`V1WebhookAuthType`).
33    WebhookAuthType {
34        /// HTTP basic auth.
35        Basic => "BASIC",
36        /// A key in a header.
37        ApiKey => "API_KEY",
38        /// An HMAC signature in a header.
39        Hmac => "HMAC",
40    }
41}
42
43string_enum! {
44    /// The HMAC hash (`V1WebhookHMACAlgorithm`).
45    HmacAlgorithm {
46        /// SHA-1.
47        Sha1 => "SHA1",
48        /// SHA-256.
49        Sha256 => "SHA256",
50        /// SHA-512.
51        Sha512 => "SHA512",
52        /// MD5.
53        Md5 => "MD5",
54    }
55}
56
57string_enum! {
58    /// How the HMAC signature is encoded (`V1WebhookHMACEncoding`).
59    HmacEncoding {
60        /// Hexadecimal.
61        Hex => "HEX",
62        /// Base64.
63        Base64 => "BASE64",
64        /// URL-safe base64.
65        Base64Url => "BASE64URL",
66    }
67}
68
69/// How a webhook authenticates its sender: exactly one of the spec's three
70/// shapes. Its `Debug` output never shows the secret.
71#[derive(Clone)]
72#[non_exhaustive]
73pub enum WebhookAuth {
74    /// HTTP basic auth.
75    Basic {
76        /// The user name.
77        username: String,
78        /// The password (secret).
79        password: String,
80    },
81    /// A key in a header.
82    ApiKey {
83        /// The header carrying it.
84        header_name: String,
85        /// The key (secret).
86        api_key: String,
87    },
88    /// An HMAC signature in a header.
89    Hmac {
90        /// The hash.
91        algorithm: HmacAlgorithm,
92        /// The signature's encoding.
93        encoding: HmacEncoding,
94        /// The header carrying it.
95        signature_header_name: String,
96        /// The signing secret (secret).
97        signing_secret: String,
98    },
99}
100
101impl WebhookAuth {
102    /// HTTP basic auth.
103    pub fn basic(username: impl Into<String>, password: impl Into<String>) -> Self {
104        Self::Basic {
105            username: username.into(),
106            password: password.into(),
107        }
108    }
109
110    /// A key in the header `header_name`.
111    pub fn api_key(header_name: impl Into<String>, api_key: impl Into<String>) -> Self {
112        Self::ApiKey {
113            header_name: header_name.into(),
114            api_key: api_key.into(),
115        }
116    }
117
118    /// An HMAC signature in the header `signature_header_name`.
119    pub fn hmac(
120        algorithm: HmacAlgorithm,
121        encoding: HmacEncoding,
122        signature_header_name: impl Into<String>,
123        signing_secret: impl Into<String>,
124    ) -> Self {
125        Self::Hmac {
126            algorithm,
127            encoding,
128            signature_header_name: signature_header_name.into(),
129            signing_secret: signing_secret.into(),
130        }
131    }
132
133    /// Svix's scheme — HMAC-SHA256, base64, in the `svix-signature` header
134    /// — which is what the official Go SDK sends for Svix. Use it with
135    /// [`WebhookSource::Svix`].
136    pub fn svix(signing_secret: impl Into<String>) -> Self {
137        Self::hmac(
138            HmacAlgorithm::Sha256,
139            HmacEncoding::Base64,
140            "svix-signature",
141            signing_secret,
142        )
143    }
144
145    /// The `authType` this shape is sent with.
146    #[must_use]
147    pub fn auth_type(&self) -> WebhookAuthType {
148        match self {
149            Self::Basic { .. } => WebhookAuthType::Basic,
150            Self::ApiKey { .. } => WebhookAuthType::ApiKey,
151            Self::Hmac { .. } => WebhookAuthType::Hmac,
152        }
153    }
154}
155
156const REDACTED: &str = "<redacted>";
157
158impl fmt::Debug for WebhookAuth {
159    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160        match self {
161            Self::Basic { username, .. } => f
162                .debug_struct("Basic")
163                .field("username", username)
164                .field("password", &REDACTED)
165                .finish(),
166            Self::ApiKey { header_name, .. } => f
167                .debug_struct("ApiKey")
168                .field("header_name", header_name)
169                .field("api_key", &REDACTED)
170                .finish(),
171            Self::Hmac {
172                algorithm,
173                encoding,
174                signature_header_name,
175                ..
176            } => f
177                .debug_struct("Hmac")
178                .field("algorithm", algorithm)
179                .field("encoding", encoding)
180                .field("signature_header_name", signature_header_name)
181                .field("signing_secret", &REDACTED)
182                .finish(),
183        }
184    }
185}
186
187/// A webhook (`V1Webhook`). The engine never sends the secret back.
188#[derive(Clone, Debug, Deserialize)]
189#[serde(rename_all = "camelCase")]
190#[non_exhaustive]
191pub struct Webhook {
192    /// Id and timestamps.
193    pub metadata: ResourceMeta,
194    /// The tenant.
195    pub tenant_id: String,
196    /// Its name — what [`WebhooksApi::get`], `update` and `delete` take.
197    pub name: String,
198    /// Who sends it.
199    pub source_name: WebhookSource,
200    /// The CEL expression that makes the event key from the request.
201    pub event_key_expression: String,
202    /// How it authenticates.
203    pub auth_type: WebhookAuthType,
204    /// The CEL expression that makes the event's scope.
205    #[serde(default)]
206    pub scope_expression: Option<String>,
207    /// A payload added to every event.
208    #[serde(default)]
209    pub static_payload: Option<JsonObject>,
210    /// Whether the webhook's HTTP answer is the event it triggered (not
211    /// sent by v0.80.0).
212    #[serde(default)]
213    pub return_event_as_response_payload: Option<bool>,
214    /// Fields this crate does not model, as the engine sent them.
215    #[serde(flatten)]
216    pub other: JsonObject,
217}
218
219/// A webhook to create; for [`WebhooksApi::create`]. Its `Debug` output
220/// never shows the secret.
221#[derive(Clone, Debug)]
222#[must_use]
223pub struct WebhookSpec {
224    name: String,
225    source: WebhookSource,
226    event_key_expression: String,
227    auth: WebhookAuth,
228    scope_expression: Option<String>,
229    static_payload: Option<std::result::Result<JsonObject, String>>,
230    return_event_as_response_payload: Option<bool>,
231}
232
233impl WebhookSpec {
234    /// A webhook called `name` for `source`, making each event's key with
235    /// the CEL `event_key_expression`, and authenticating with `auth`.
236    pub fn new(
237        name: impl Into<String>,
238        source: WebhookSource,
239        event_key_expression: impl Into<String>,
240        auth: WebhookAuth,
241    ) -> Self {
242        Self {
243            name: name.into(),
244            source,
245            event_key_expression: event_key_expression.into(),
246            auth,
247            scope_expression: None,
248            static_payload: None,
249            return_event_as_response_payload: None,
250        }
251    }
252
253    /// A CEL expression for each event's scope.
254    pub fn scope_expression(mut self, expression: impl Into<String>) -> Self {
255        self.scope_expression = Some(expression.into());
256        self
257    }
258
259    /// A payload added to every event; must serialize to a JSON object
260    /// ([`WebhooksApi::create`] refuses anything else).
261    pub fn static_payload(mut self, payload: &impl Serialize) -> Self {
262        self.static_payload = Some(to_object(payload, "the static payload"));
263        self
264    }
265
266    /// Whether to answer the webhook's HTTP request with the event it
267    /// triggered.
268    pub fn return_event_as_response_payload(mut self, enabled: bool) -> Self {
269        self.return_event_as_response_payload = Some(enabled);
270        self
271    }
272}
273
274#[derive(Serialize)]
275#[serde(rename_all = "camelCase")]
276struct CreateBody<'a> {
277    name: &'a str,
278    source_name: &'a WebhookSource,
279    event_key_expression: &'a str,
280    #[serde(skip_serializing_if = "Option::is_none")]
281    scope_expression: Option<&'a str>,
282    #[serde(skip_serializing_if = "Option::is_none")]
283    static_payload: Option<JsonObject>,
284    #[serde(skip_serializing_if = "Option::is_none")]
285    return_event_as_response_payload: Option<bool>,
286    auth_type: WebhookAuthType,
287    auth: AuthBody<'a>,
288}
289
290#[derive(Serialize)]
291#[serde(untagged, rename_all_fields = "camelCase")]
292enum AuthBody<'a> {
293    Basic {
294        username: &'a str,
295        password: &'a str,
296    },
297    ApiKey {
298        header_name: &'a str,
299        api_key: &'a str,
300    },
301    Hmac {
302        algorithm: &'a HmacAlgorithm,
303        encoding: &'a HmacEncoding,
304        signature_header_name: &'a str,
305        signing_secret: &'a str,
306    },
307}
308
309impl<'a> AuthBody<'a> {
310    fn new(auth: &'a WebhookAuth) -> Self {
311        match auth {
312            WebhookAuth::Basic { username, password } => Self::Basic { username, password },
313            WebhookAuth::ApiKey {
314                header_name,
315                api_key,
316            } => Self::ApiKey {
317                header_name,
318                api_key,
319            },
320            WebhookAuth::Hmac {
321                algorithm,
322                encoding,
323                signature_header_name,
324                signing_secret,
325            } => Self::Hmac {
326                algorithm,
327                encoding,
328                signature_header_name,
329                signing_secret,
330            },
331        }
332    }
333}
334
335/// What to change in a webhook; for [`WebhooksApi::update`]. Only the
336/// fields given a value are sent, and at least one is required. Neither the
337/// source nor the authentication can be changed.
338#[derive(Clone, Debug, Default, Serialize)]
339#[serde(rename_all = "camelCase")]
340#[must_use]
341pub struct WebhookUpdate {
342    #[serde(skip_serializing_if = "Option::is_none")]
343    event_key_expression: Option<String>,
344    #[serde(skip_serializing_if = "Option::is_none")]
345    scope_expression: Option<String>,
346    #[serde(skip_serializing_if = "Option::is_none")]
347    static_payload: Option<JsonObject>,
348    #[serde(skip_serializing_if = "Option::is_none")]
349    return_event_as_response_payload: Option<bool>,
350    #[serde(skip)]
351    error: Option<String>,
352}
353
354impl WebhookUpdate {
355    /// No change yet.
356    pub fn new() -> Self {
357        Self::default()
358    }
359
360    /// A new event key expression.
361    pub fn event_key_expression(mut self, expression: impl Into<String>) -> Self {
362        self.event_key_expression = Some(expression.into());
363        self
364    }
365
366    /// A new scope expression.
367    pub fn scope_expression(mut self, expression: impl Into<String>) -> Self {
368        self.scope_expression = Some(expression.into());
369        self
370    }
371
372    /// A new static payload; must serialize to a JSON object.
373    pub fn static_payload(mut self, payload: &impl Serialize) -> Self {
374        match to_object(payload, "the static payload") {
375            Ok(object) => self.static_payload = Some(object),
376            Err(message) => self.error = Some(message),
377        }
378        self
379    }
380
381    /// Whether to answer with the triggered event.
382    pub fn return_event_as_response_payload(mut self, enabled: bool) -> Self {
383        self.return_event_as_response_payload = Some(enabled);
384        self
385    }
386}
387
388/// Which webhooks [`WebhooksApi::list`] returns. Only the settings given a
389/// value are sent.
390#[derive(Clone, Debug, Default)]
391#[must_use]
392pub struct WebhookListQuery {
393    offset: Option<i64>,
394    limit: Option<i64>,
395    source_names: Vec<WebhookSource>,
396    webhook_names: Vec<String>,
397}
398
399impl WebhookListQuery {
400    /// Every webhook.
401    pub fn new() -> Self {
402        Self::default()
403    }
404
405    /// Skip this many.
406    pub fn offset(mut self, offset: i64) -> Self {
407        self.offset = Some(offset);
408        self
409    }
410
411    /// At most this many.
412    pub fn limit(mut self, limit: i64) -> Self {
413        self.limit = Some(limit);
414        self
415    }
416
417    /// Only these sources.
418    pub fn source_names(mut self, sources: impl IntoIterator<Item = WebhookSource>) -> Self {
419        self.source_names.extend(sources);
420        self
421    }
422
423    /// Only these names.
424    pub fn webhook_names(mut self, names: impl IntoIterator<Item = impl Into<String>>) -> Self {
425        self.webhook_names.extend(names.into_iter().map(Into::into));
426        self
427    }
428
429    fn query(&self) -> Query {
430        let mut query = Query::new();
431        query.push_opt("offset", self.offset);
432        query.push_opt("limit", self.limit);
433        query.push_all("sourceNames", &self.source_names);
434        query.push_all("webhookNames", &self.webhook_names);
435        query
436    }
437}
438
439/// Incoming webhooks; from [`RestClient::webhooks`].
440#[derive(Clone, Copy, Debug)]
441pub struct WebhooksApi<'a> {
442    pub(crate) client: &'a RestClient,
443}
444
445impl RestClient {
446    /// Incoming webhooks (`v1-webhook:list`, `:get`, `:create`, `:update`,
447    /// `:delete`).
448    pub fn webhooks(&self) -> WebhooksApi<'_> {
449        WebhooksApi { client: self }
450    }
451}
452
453impl WebhooksApi<'_> {
454    /// Lists webhooks (`v1-webhook:list`). Neither supported engine reports
455    /// pagination for this list, so [`Page::pagination`] is `None`.
456    ///
457    /// # Errors
458    ///
459    /// As for any call; see [`Error`].
460    pub async fn list(&self, query: WebhookListQuery) -> Result<Page<Webhook>> {
461        self.client
462            .inner
463            .call(Operation::V1WebhookList, &[], query.query())
464            .await
465    }
466
467    /// One webhook, by name (`v1-webhook:get`). This is the one operation
468    /// the spec marks as rate limited, and both supported engines were seen
469    /// answering `429` (with no `Retry-After`) to a burst of it; like any
470    /// bodiless `GET` it is retried with backoff.
471    ///
472    /// # Errors
473    ///
474    /// [`Error::NotFound`] for a name the engine does not know (both
475    /// supported engines answer `404` `{"message":"not found"}`);
476    /// [`Error::InvalidArgument`] for an empty name; otherwise as for any
477    /// call.
478    pub async fn get(&self, name: &str) -> Result<Webhook> {
479        self.client
480            .inner
481            .call(Operation::V1WebhookGet, &[name], Query::new())
482            .await
483    }
484
485    /// Creates a webhook (`v1-webhook:create`). The answer does not carry
486    /// the secret.
487    ///
488    /// ```no_run
489    /// # async fn example(rest: hatchet_rest::RestClient) -> hatchet_rest::Result<()> {
490    /// use hatchet_rest::{HmacAlgorithm, HmacEncoding, WebhookAuth, WebhookSource, WebhookSpec};
491    ///
492    /// let auth = WebhookAuth::hmac(
493    ///     HmacAlgorithm::Sha256,
494    ///     HmacEncoding::Hex,
495    ///     "X-Hub-Signature-256",
496    ///     std::env::var("GITHUB_WEBHOOK_SECRET").unwrap_or_default(),
497    /// );
498    /// let webhook = rest
499    ///     .webhooks()
500    ///     .create(
501    ///         WebhookSpec::new("github", WebhookSource::Github, "'github:' + input.action", auth)
502    ///             .scope_expression("input.repository.full_name"),
503    ///     )
504    ///     .await?;
505    /// println!("created {}", webhook.name);
506    /// # Ok(())
507    /// # }
508    /// ```
509    ///
510    /// # Errors
511    ///
512    /// [`Error::InvalidArgument`] for a static payload that is not a JSON
513    /// object, before anything is sent; otherwise as for any call. Sent
514    /// once, never retried.
515    pub async fn create(&self, spec: WebhookSpec) -> Result<Webhook> {
516        let static_payload = spec
517            .static_payload
518            .clone()
519            .transpose()
520            .map_err(Error::InvalidArgument)?;
521        let body = CreateBody {
522            name: &spec.name,
523            source_name: &spec.source,
524            event_key_expression: &spec.event_key_expression,
525            scope_expression: spec.scope_expression.as_deref(),
526            static_payload,
527            return_event_as_response_payload: spec.return_event_as_response_payload,
528            auth_type: spec.auth.auth_type(),
529            auth: AuthBody::new(&spec.auth),
530        };
531        self.client
532            .inner
533            .call_json(Operation::V1WebhookCreate, &[], &body)
534            .await
535    }
536
537    /// Changes a webhook, by name (`v1-webhook:update`), and returns it as
538    /// it now is.
539    ///
540    /// # Errors
541    ///
542    /// [`Error::InvalidArgument`] for an update that changes nothing or a
543    /// static payload that is not a JSON object, before anything is sent;
544    /// otherwise as for [`get`](Self::get). Sent once, never retried.
545    pub async fn update(&self, name: &str, update: WebhookUpdate) -> Result<Webhook> {
546        if let Some(message) = &update.error {
547            return Err(Error::InvalidArgument(message.clone()));
548        }
549        if update.event_key_expression.is_none()
550            && update.scope_expression.is_none()
551            && update.static_payload.is_none()
552            && update.return_event_as_response_payload.is_none()
553        {
554            return Err(Error::InvalidArgument(
555                "a webhook update must change something".into(),
556            ));
557        }
558        self.client
559            .inner
560            .call_json(Operation::V1WebhookUpdate, &[name], &update)
561            .await
562    }
563
564    /// Deletes a webhook, by name, and returns what was deleted
565    /// (`v1-webhook:delete`): both supported engines answer `200` with the
566    /// webhook, not `204`.
567    ///
568    /// # Errors
569    ///
570    /// As for [`get`](Self::get). Sent once, never retried.
571    pub async fn delete(&self, name: &str) -> Result<Webhook> {
572        self.client
573            .inner
574            .call(Operation::V1WebhookDelete, &[name], Query::new())
575            .await
576    }
577}