fauna-api 1.0.815

The Fauna SDK for Rust: accounts, Drive, groups, calendar, chats, payments, Parrot and live rooms.
Documentation
use chrono::{DateTime, Utc};
use hmac::{Hmac, Mac};
use serde::{Deserialize, Serialize};
use serde_json::json;
use sha2::Sha256;

use crate::authentification::{CredentialsOrApiKey, Profile};
use crate::error::Result;
use crate::groups::GroupRef;
use crate::http::{client, encode, ok};

/// Event types a webhook can listen for: `chat.message` for groups and chats,
/// `group.joined` and `group.left` for groups, payment events for API keys.
/// `calendar.event.started` goes to a calendar event's own `webhook`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum EventType {
    #[serde(rename = "chat.message")]
    ChatMessage,
    #[serde(rename = "group.joined")]
    GroupJoined,
    #[serde(rename = "group.left")]
    GroupLeft,
    #[serde(rename = "payment.succeeded")]
    PaymentSucceeded,
    #[serde(rename = "payment.expired")]
    PaymentExpired,
    #[serde(rename = "payment.refunded")]
    PaymentRefunded,
    #[serde(rename = "payment.disputed")]
    PaymentDisputed,
    #[serde(rename = "calendar.event.started")]
    CalendarEventStarted,
}

/// Who a webhook belongs to: a group, one chat, or the API key making the call.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum WebhookOwner {
    Group(String),
    Chat(String),
    Key,
}

/// An outbound webhook. Its events are signed and POSTed to `url`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Webhook {
    pub id: String,

    pub url: String,
    pub events: Vec<EventType>,

    /// Who made it. A webhook goes when its maker can no longer read what it
    /// listens to.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub creator: Option<Profile>,
    pub created: DateTime<Utc>,
}

/// What `create` resolves to. The secret is only ever returned here.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Registration {
    pub webhook: Webhook,
    pub secret: String,
}

/// One event as POSTed to a webhook URL, with a `Fauna-Signature` header.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Delivery {
    pub id: String,
    pub r#type: EventType,
    /// Milliseconds since the epoch.
    pub created: i64,
    pub data: serde_json::Value,
}

/// A reaction carried by a `chat.message` event.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Reaction {
    pub emoji: String,
    /// Position of the message reacted to.
    pub position: u32,
    pub on: bool,
}

/// `data` of a `chat.message` event: a message sent in a chat. `group` is set
/// when a group owns the chat.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatMessage {
    pub chat_id: String,
    pub chat_name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub group: Option<String>,
    pub position: u32,

    pub author: Profile,
    pub text: String,
    /// Chat members tagged with `@`, never the author.
    #[serde(default)]
    pub mentions: Vec<Profile>,
    /// Set when the message is a reaction, so apps can skip it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reaction: Option<Reaction>,

    /// Milliseconds since the epoch.
    pub created: i64,
}

/// Who came into a group or went out of it: a person, or a group nested directly
/// inside it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GroupChangeMember {
    Person { email: String },
    Group { group: GroupRef },
}

/// Why: `Joined` for `group.joined`; for `group.left`, the person `Left` or was
/// `Removed` by an admin, or the nested group was `Unnested` or `Deleted`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum GroupChangeReason {
    Joined,
    Left,
    Removed,
    Unnested,
    Deleted,
}

/// `data` of `group.joined` and `group.left`: a person or a nested group came
/// directly into `group` or went directly out of it. Changes further down
/// (someone leaving a nested group) are told only to that group's own webhooks.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GroupChange {
    pub group: GroupRef,
    pub member: GroupChangeMember,
    pub reason: GroupChangeReason,
}

/// Register a webhook for a group or a chat you can read, or, signed in with an
/// API key, for that key. In production `url` must be https on a public address.
/// Pass `secret` to choose the signing secret; otherwise one is made.
pub async fn create(
    authorization: &CredentialsOrApiKey,
    owner: &WebhookOwner,
    url: &str,
    events: &[EventType],
    secret: Option<&str>,
) -> Result<Registration> {
    let response = client()
        .post(format!("{}/webhooks", crate::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .json(&json!({ "owner": owner, "url": url, "events": events, "secret": secret }))
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

/// An owner's webhooks. Secrets are never listed.
pub async fn list(
    authorization: &CredentialsOrApiKey,
    owner: &WebhookOwner,
) -> Result<Vec<Webhook>> {
    let response = client()
        .post(format!("{}/webhooks/list", crate::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .json(&json!({ "owner": owner }))
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

pub async fn remove(authorization: &CredentialsOrApiKey, id: &str) -> Result<()> {
    let response = client()
        .delete(format!("{}/webhooks/{}", crate::get_url(), encode(id)))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .send()
        .await?;
    ok(response).await?;
    Ok(())
}

/// True when `signature` (the `Fauna-Signature` header, `t=<seconds>,v1=<hex>`)
/// is the HMAC SHA-256 of `t.body` under `secret`, signed within `tolerance`
/// seconds of now (300 when `None`). Pass the raw request body, before any JSON
/// parsing.
pub async fn verify(
    secret: &str,
    body: &str,
    signature: &str,
    tolerance: Option<i64>,
) -> Result<bool> {
    let mut timestamp = None;
    let mut expected = None;
    for piece in signature.split(',') {
        if let Some((key, value)) = piece.split_once('=') {
            match key.trim() {
                "t" => timestamp = value.trim().parse::<i64>().ok(),
                "v1" => expected = hex(value.trim()),
                _ => {}
            }
        }
    }
    let (Some(timestamp), Some(expected)) = (timestamp, expected) else {
        return Ok(false);
    };
    if (Utc::now().timestamp() - timestamp).abs() > tolerance.unwrap_or(300) {
        return Ok(false);
    }
    let Ok(mut mac) = Hmac::<Sha256>::new_from_slice(secret.as_bytes()) else {
        return Ok(false);
    };
    mac.update(format!("{timestamp}.{body}").as_bytes());
    Ok(mac.verify_slice(&expected).is_ok())
}

fn hex(text: &str) -> Option<Vec<u8>> {
    if !text.len().is_multiple_of(2) {
        return None;
    }
    (0..text.len())
        .step_by(2)
        .map(|at| u8::from_str_radix(text.get(at..at + 2)?, 16).ok())
        .collect()
}