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