mailcycle 0.3.0

Rust client for the Mailcycle API. Create addresses that receive mail, read and decrypt it on your machine, send, and listen for events.
Documentation
//! API keys, webhooks and sessions.
//!
//! The names on keys and webhooks are sealed here under the vault key, bound
//! to the record's kind and id, exactly as the app seals them, so the server
//! stores none. The id is chosen here for that reason: the name has to be
//! bound to it before the record exists.
//!
//! Minting and revoking keys, and adding, changing and removing webhooks, need
//! a signed-in session. The API answers `session_required` to an API key.

use serde_json::{json, Map, Value};

use crate::client::{is_sealed_box, new_id, open_vault_record, vault_aad, Mailcycle};
use crate::crypto::cipher::{seal_json, SealedBox, SEAL_VERSION};
use crate::error::Result;
use crate::http::path_segment;
use crate::models::{
    ApiKey, CreatedApiKey, CreatedWebhook, DeliveryPage, QueuedDelivery, Session, Webhook, WebhookList,
    WebhookUpdate,
};

const API_KEY_RECORD: &str = "api-key";
const WEBHOOK_RECORD: &str = "webhook";

fn text(value: &Value) -> String {
    value.as_str().unwrap_or_default().to_string()
}

fn maybe_text(value: &Value) -> Option<String> {
    value.as_str().map(str::to_string)
}

/// A record's name, sealed as `{"name": ...}` under the vault key.
fn seal_name(client: &Mailcycle, kind: &str, id: &str, name: &str) -> Result<Value> {
    let keys = client.require_keys("seal a name")?;
    let box_ = seal_json(keys.vault_key(), &json!({ "name": name }), &vault_aad(kind, id), SEAL_VERSION)?;
    Ok(serde_json::to_value(&box_).expect("a sealed box serializes"))
}

/// The name, or `None` if there is no phrase or it will not open.
///
/// A name that will not open is shown as unreadable rather than failing the
/// list, the same as an address label.
fn open_name(client: &Mailcycle, kind: &str, id: &str, meta: Option<&Value>) -> Option<String> {
    let keys = client.keys.as_ref()?;
    if !is_sealed_box(meta) {
        return None;
    }
    let box_: SealedBox = serde_json::from_value(meta?.clone()).ok()?;
    open_vault_record(keys.vault_key(), kind, id, &box_)
        .ok()?
        .get("name")
        .and_then(Value::as_str)
        .map(str::to_string)
}

/// API keys: list, create and revoke. Session only.
pub struct ApiKeys<'a> {
    pub(crate) client: &'a Mailcycle,
}

impl ApiKeys<'_> {
    fn to_api_key(&self, wire: &Value) -> ApiKey {
        let id = text(&wire["id"]);
        ApiKey {
            name: open_name(self.client, API_KEY_RECORD, &id, wire.get("meta")),
            id,
            hint: text(&wire["hint"]),
            created_at: text(&wire["createdAt"]),
            last_used_at: maybe_text(&wire["lastUsedAt"]),
        }
    }

    /// The account's keys, newest first, with their names opened.
    pub fn list(&self) -> Result<Vec<ApiKey>> {
        let result: Value = self.client.http.request("GET", "/api-keys", None, &[])?;
        Ok(result["apiKeys"]
            .as_array()
            .map(|items| items.iter().map(|item| self.to_api_key(item)).collect())
            .unwrap_or_default())
    }

    /// Makes a key. Operator plan and up.
    ///
    /// The token comes back once, here. Keep it somewhere private; the API
    /// holds only its hash and cannot show it again.
    pub fn create(&self, name: &str) -> Result<CreatedApiKey> {
        let id = new_id("key", 16);
        let meta = seal_name(self.client, API_KEY_RECORD, &id, name)?;
        let result: Value =
            self.client.http.request("POST", "/api-keys", Some(&json!({ "id": id, "meta": meta })), &[])?;
        Ok(CreatedApiKey { api_key: self.to_api_key(&result["apiKey"]), token: text(&result["token"]) })
    }

    /// Revokes a key. It stops working at once.
    pub fn revoke(&self, key_id: &str) -> Result<()> {
        let path = format!("/api-keys/{}", path_segment(key_id));
        let _: Value = self.client.http.request("DELETE", &path, None, &[])?;
        Ok(())
    }
}

/// Webhooks, Operator and up.
///
/// A session can do everything. An API key can list, read deliveries, send a
/// test and redeliver.
pub struct Webhooks<'a> {
    pub(crate) client: &'a Mailcycle,
}

fn webhook_path(id: &str) -> String {
    format!("/webhook-endpoints/{}", path_segment(id))
}

impl Webhooks<'_> {
    fn to_webhook(&self, wire: &Value) -> Webhook {
        let id = text(&wire["id"]);
        Webhook {
            name: open_name(self.client, WEBHOOK_RECORD, &id, wire.get("meta")),
            id,
            url: text(&wire["url"]),
            events: wire["events"]
                .as_array()
                .map(|items| items.iter().filter_map(Value::as_str).map(str::to_string).collect())
                .unwrap_or_default(),
            status: text(&wire["status"]),
            disabled_reason: maybe_text(&wire["disabledReason"]),
            failing_since: maybe_text(&wire["failingSince"]),
            last_success_at: maybe_text(&wire["lastSuccessAt"]),
            created_at: text(&wire["createdAt"]),
        }
    }

    /// The account's webhooks, with their names opened, and every event type
    /// one can subscribe to.
    pub fn list(&self) -> Result<WebhookList> {
        let result: Value = self.client.http.request("GET", "/webhook-endpoints", None, &[])?;
        Ok(WebhookList {
            webhooks: result["webhooks"]
                .as_array()
                .map(|items| items.iter().map(|item| self.to_webhook(item)).collect())
                .unwrap_or_default(),
            event_types: result["eventTypes"]
                .as_array()
                .map(|items| items.iter().filter_map(Value::as_str).map(str::to_string).collect())
                .unwrap_or_default(),
        })
    }

    /// Adds a webhook. `events` are event types, or `["*"]` for all of them.
    ///
    /// The signing secret comes back once, here. Keep it to check deliveries
    /// with [`verify_webhook_signature`](crate::verify_webhook_signature).
    pub fn create(&self, url: &str, events: &[&str], name: &str) -> Result<CreatedWebhook> {
        let id = new_id("whk", 16);
        let meta = seal_name(self.client, WEBHOOK_RECORD, &id, name)?;
        let body = json!({ "id": id, "url": url, "events": events, "meta": meta });
        let result: Value = self.client.http.request("POST", "/webhook-endpoints", Some(&body), &[])?;
        Ok(CreatedWebhook { webhook: self.to_webhook(&result["webhook"]), secret: text(&result["secret"]) })
    }

    /// Changes what is set in `changes` and leaves the rest.
    pub fn update(&self, webhook_id: &str, changes: WebhookUpdate) -> Result<Webhook> {
        let mut body = Map::new();
        if let Some(url) = changes.url {
            body.insert("url".into(), json!(url));
        }
        if let Some(events) = changes.events {
            body.insert("events".into(), json!(events));
        }
        if let Some(name) = changes.name {
            body.insert("meta".into(), seal_name(self.client, WEBHOOK_RECORD, webhook_id, &name)?);
        }
        if let Some(enabled) = changes.enabled {
            body.insert("status".into(), json!(if enabled { "active" } else { "disabled" }));
        }
        let result: Value =
            self.client.http.request("PATCH", &webhook_path(webhook_id), Some(&Value::Object(body)), &[])?;
        Ok(self.to_webhook(&result["webhook"]))
    }

    /// Removes the webhook and its delivery log.
    pub fn delete(&self, webhook_id: &str) -> Result<()> {
        let _: Value = self.client.http.request("DELETE", &webhook_path(webhook_id), None, &[])?;
        Ok(())
    }

    /// A new signing secret, returned once. The old one stops at once.
    pub fn rotate_secret(&self, webhook_id: &str) -> Result<String> {
        let path = format!("{}/rotate-secret", webhook_path(webhook_id));
        let result: Value = self.client.http.request("POST", &path, Some(&json!({})), &[])?;
        Ok(text(&result["secret"]))
    }

    /// Sends a `webhook.test` event to it.
    pub fn test(&self, webhook_id: &str) -> Result<QueuedDelivery> {
        let path = format!("{}/test", webhook_path(webhook_id));
        let result: Value = self.client.http.request("POST", &path, Some(&json!({})), &[])?;
        Ok(QueuedDelivery {
            delivery_id: text(&result["deliveryId"]),
            event_id: maybe_text(&result["eventId"]),
        })
    }

    /// The delivery log, newest first.
    ///
    /// `cursor` is the `next_cursor` of the page before, passed back as it is.
    /// `limit` is up to 200, 50 when it is `None`.
    pub fn deliveries(
        &self,
        webhook_id: &str,
        cursor: Option<&str>,
        limit: Option<u32>,
    ) -> Result<DeliveryPage> {
        let mut query: Vec<(&str, String)> = Vec::new();
        if let Some(cursor) = cursor {
            query.push(("cursor", cursor.to_string()));
        }
        if let Some(limit) = limit {
            query.push(("limit", limit.to_string()));
        }
        let path = format!("{}/deliveries", webhook_path(webhook_id));
        let result: Value = self.client.http.request("GET", &path, None, &query)?;
        Ok(DeliveryPage {
            deliveries: serde_json::from_value(result["deliveries"].clone()).unwrap_or_default(),
            next_cursor: maybe_text(&result["nextCursor"]),
        })
    }

    /// Sends a delivery's event again, with the same event id.
    pub fn redeliver(&self, webhook_id: &str, delivery_id: &str) -> Result<QueuedDelivery> {
        let path = format!("{}/deliveries/{}/redeliver", webhook_path(webhook_id), path_segment(delivery_id));
        let result: Value = self.client.http.request("POST", &path, Some(&json!({})), &[])?;
        Ok(QueuedDelivery {
            delivery_id: text(&result["deliveryId"]),
            event_id: maybe_text(&result["eventId"]),
        })
    }
}

/// Signed-in sessions. Session only.
pub struct Sessions<'a> {
    pub(crate) client: &'a Mailcycle,
}

impl Sessions<'_> {
    /// The account's live sessions, newest first. `current` marks this one.
    pub fn list(&self) -> Result<Vec<Session>> {
        let result: Value = self.client.http.request("GET", "/accounts/sessions", None, &[])?;
        Ok(serde_json::from_value(result["sessions"].clone()).unwrap_or_default())
    }

    /// Ends one session.
    pub fn revoke(&self, session_id: &str) -> Result<()> {
        let path = format!("/accounts/sessions/{}", path_segment(session_id));
        let _: Value = self.client.http.request("DELETE", &path, None, &[])?;
        Ok(())
    }

    /// Ends every session but this one. Returns how many ended.
    pub fn revoke_others(&self) -> Result<u64> {
        let result: Value = self.client.http.request("DELETE", "/accounts/sessions", None, &[])?;
        Ok(result["revoked"].as_u64().unwrap_or(0))
    }
}