Skip to main content

fauna_api/
webhooks.rs

1use chrono::{DateTime, Utc};
2use hmac::{Hmac, Mac};
3use serde::{Deserialize, Serialize};
4use serde_json::json;
5use sha2::Sha256;
6
7use crate::authentification::{CredentialsOrApiKey, Profile};
8use crate::error::Result;
9use crate::http::{client, encode, ok};
10
11/// Event types a webhook can listen for: `chat.message` for groups and chats,
12/// payment events for API keys.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
14pub enum EventType {
15    #[serde(rename = "chat.message")]
16    ChatMessage,
17    #[serde(rename = "payment.succeeded")]
18    PaymentSucceeded,
19    #[serde(rename = "payment.expired")]
20    PaymentExpired,
21    #[serde(rename = "payment.refunded")]
22    PaymentRefunded,
23    #[serde(rename = "payment.disputed")]
24    PaymentDisputed,
25}
26
27/// Who a webhook belongs to: a group, one chat, or the API key making the call.
28#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
29#[serde(rename_all = "camelCase")]
30pub enum WebhookOwner {
31    Group(String),
32    Chat(String),
33    Key,
34}
35
36/// An outbound webhook. Its events are signed and POSTed to `url`.
37#[derive(Debug, Clone, Serialize, Deserialize)]
38#[serde(rename_all = "camelCase")]
39pub struct Webhook {
40    pub id: String,
41
42    pub url: String,
43    pub events: Vec<EventType>,
44
45    pub created: DateTime<Utc>,
46}
47
48/// What `create` resolves to. The secret is only ever returned here.
49#[derive(Debug, Clone, Serialize, Deserialize)]
50pub struct Registration {
51    pub webhook: Webhook,
52    pub secret: String,
53}
54
55/// One event as POSTed to a webhook URL, with a `Fauna-Signature` header.
56#[derive(Debug, Clone, Serialize, Deserialize)]
57pub struct Delivery {
58    pub id: String,
59    pub r#type: EventType,
60    /// Milliseconds since the epoch.
61    pub created: i64,
62    pub data: serde_json::Value,
63}
64
65/// A reaction carried by a `chat.message` event.
66#[derive(Debug, Clone, Serialize, Deserialize)]
67pub struct Reaction {
68    pub emoji: String,
69    /// Position of the message reacted to.
70    pub position: u32,
71    pub on: bool,
72}
73
74/// `data` of a `chat.message` event: a message sent in a chat. `group` is set
75/// when a group owns the chat.
76#[derive(Debug, Clone, Serialize, Deserialize)]
77#[serde(rename_all = "camelCase")]
78pub struct ChatMessage {
79    pub chat_id: String,
80    pub chat_name: String,
81    #[serde(default, skip_serializing_if = "Option::is_none")]
82    pub group: Option<String>,
83    pub position: u32,
84
85    pub author: Profile,
86    pub text: String,
87    /// Chat members tagged with `@`, never the author.
88    #[serde(default)]
89    pub mentions: Vec<Profile>,
90    /// Set when the message is a reaction, so apps can skip it.
91    #[serde(default, skip_serializing_if = "Option::is_none")]
92    pub reaction: Option<Reaction>,
93
94    /// Milliseconds since the epoch.
95    pub created: i64,
96}
97
98/// Register a webhook for a group or a chat you can read, or, signed in with an
99/// API key, for that key. In production `url` must be https on a public address.
100/// Pass `secret` to choose the signing secret; otherwise one is made.
101pub async fn create(
102    authorization: &CredentialsOrApiKey,
103    owner: &WebhookOwner,
104    url: &str,
105    events: &[EventType],
106    secret: Option<&str>,
107) -> Result<Registration> {
108    let response = client()
109        .post(format!("{}/webhooks", crate::get_url()))
110        .header(
111            "Authorization",
112            match authorization {
113                CredentialsOrApiKey::Credentials(credentials) => {
114                    format!("Token {}", credentials.token)
115                }
116                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
117            },
118        )
119        .json(&json!({ "owner": owner, "url": url, "events": events, "secret": secret }))
120        .send()
121        .await?;
122    Ok(ok(response).await?.json().await?)
123}
124
125/// An owner's webhooks. Secrets are never listed.
126pub async fn list(
127    authorization: &CredentialsOrApiKey,
128    owner: &WebhookOwner,
129) -> Result<Vec<Webhook>> {
130    let response = client()
131        .post(format!("{}/webhooks/list", crate::get_url()))
132        .header(
133            "Authorization",
134            match authorization {
135                CredentialsOrApiKey::Credentials(credentials) => {
136                    format!("Token {}", credentials.token)
137                }
138                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
139            },
140        )
141        .json(&json!({ "owner": owner }))
142        .send()
143        .await?;
144    Ok(ok(response).await?.json().await?)
145}
146
147pub async fn remove(authorization: &CredentialsOrApiKey, id: &str) -> Result<()> {
148    let response = client()
149        .delete(format!("{}/webhooks/{}", crate::get_url(), encode(id)))
150        .header(
151            "Authorization",
152            match authorization {
153                CredentialsOrApiKey::Credentials(credentials) => {
154                    format!("Token {}", credentials.token)
155                }
156                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
157            },
158        )
159        .send()
160        .await?;
161    ok(response).await?;
162    Ok(())
163}
164
165/// True when `signature` (the `Fauna-Signature` header, `t=<seconds>,v1=<hex>`)
166/// is the HMAC SHA-256 of `t.body` under `secret`, signed within `tolerance`
167/// seconds of now (300 when `None`). Pass the raw request body, before any JSON
168/// parsing.
169pub async fn verify(
170    secret: &str,
171    body: &str,
172    signature: &str,
173    tolerance: Option<i64>,
174) -> Result<bool> {
175    let mut timestamp = None;
176    let mut expected = None;
177    for piece in signature.split(',') {
178        if let Some((key, value)) = piece.split_once('=') {
179            match key.trim() {
180                "t" => timestamp = value.trim().parse::<i64>().ok(),
181                "v1" => expected = hex(value.trim()),
182                _ => {}
183            }
184        }
185    }
186    let (Some(timestamp), Some(expected)) = (timestamp, expected) else {
187        return Ok(false);
188    };
189    if (Utc::now().timestamp() - timestamp).abs() > tolerance.unwrap_or(300) {
190        return Ok(false);
191    }
192    let Ok(mut mac) = Hmac::<Sha256>::new_from_slice(secret.as_bytes()) else {
193        return Ok(false);
194    };
195    mac.update(format!("{timestamp}.{body}").as_bytes());
196    Ok(mac.verify_slice(&expected).is_ok())
197}
198
199fn hex(text: &str) -> Option<Vec<u8>> {
200    if !text.len().is_multiple_of(2) {
201        return None;
202    }
203    (0..text.len())
204        .step_by(2)
205        .map(|at| u8::from_str_radix(text.get(at..at + 2)?, 16).ok())
206        .collect()
207}