1use 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 WebhookSource {
16 Generic => "GENERIC",
18 Github => "GITHUB",
20 Stripe => "STRIPE",
22 Slack => "SLACK",
24 Linear => "LINEAR",
26 Svix => "SVIX",
28 }
29}
30
31string_enum! {
32 WebhookAuthType {
34 Basic => "BASIC",
36 ApiKey => "API_KEY",
38 Hmac => "HMAC",
40 }
41}
42
43string_enum! {
44 HmacAlgorithm {
46 Sha1 => "SHA1",
48 Sha256 => "SHA256",
50 Sha512 => "SHA512",
52 Md5 => "MD5",
54 }
55}
56
57string_enum! {
58 HmacEncoding {
60 Hex => "HEX",
62 Base64 => "BASE64",
64 Base64Url => "BASE64URL",
66 }
67}
68
69#[derive(Clone)]
72#[non_exhaustive]
73pub enum WebhookAuth {
74 Basic {
76 username: String,
78 password: String,
80 },
81 ApiKey {
83 header_name: String,
85 api_key: String,
87 },
88 Hmac {
90 algorithm: HmacAlgorithm,
92 encoding: HmacEncoding,
94 signature_header_name: String,
96 signing_secret: String,
98 },
99}
100
101impl WebhookAuth {
102 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 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 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 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 #[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#[derive(Clone, Debug, Deserialize)]
189#[serde(rename_all = "camelCase")]
190#[non_exhaustive]
191pub struct Webhook {
192 pub metadata: ResourceMeta,
194 pub tenant_id: String,
196 pub name: String,
198 pub source_name: WebhookSource,
200 pub event_key_expression: String,
202 pub auth_type: WebhookAuthType,
204 #[serde(default)]
206 pub scope_expression: Option<String>,
207 #[serde(default)]
209 pub static_payload: Option<JsonObject>,
210 #[serde(default)]
213 pub return_event_as_response_payload: Option<bool>,
214 #[serde(flatten)]
216 pub other: JsonObject,
217}
218
219#[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 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 pub fn scope_expression(mut self, expression: impl Into<String>) -> Self {
255 self.scope_expression = Some(expression.into());
256 self
257 }
258
259 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 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#[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 pub fn new() -> Self {
357 Self::default()
358 }
359
360 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 pub fn scope_expression(mut self, expression: impl Into<String>) -> Self {
368 self.scope_expression = Some(expression.into());
369 self
370 }
371
372 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 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#[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 pub fn new() -> Self {
402 Self::default()
403 }
404
405 pub fn offset(mut self, offset: i64) -> Self {
407 self.offset = Some(offset);
408 self
409 }
410
411 pub fn limit(mut self, limit: i64) -> Self {
413 self.limit = Some(limit);
414 self
415 }
416
417 pub fn source_names(mut self, sources: impl IntoIterator<Item = WebhookSource>) -> Self {
419 self.source_names.extend(sources);
420 self
421 }
422
423 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#[derive(Clone, Copy, Debug)]
441pub struct WebhooksApi<'a> {
442 pub(crate) client: &'a RestClient,
443}
444
445impl RestClient {
446 pub fn webhooks(&self) -> WebhooksApi<'_> {
449 WebhooksApi { client: self }
450 }
451}
452
453impl WebhooksApi<'_> {
454 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 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 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 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 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}