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