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