mailcycle 0.5.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
//! Checking a webhook came from Mailcycle.
//!
//! `Mailcycle-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256 of "t.body">`,
//! keyed with the webhook's secret. Pass the raw body, before any parsing: a
//! body that has been through a JSON round trip is a different string and will
//! not verify.

use crate::crypto::primitives::{constant_time_equal, hmac_sha256};
use crate::encoding::{from_hex, to_hex};

pub const DEFAULT_TOLERANCE_SECONDS: i64 = 300;

/// The header Mailcycle would send for this body at this second.
///
/// Here so a test suite can build a believable delivery without a live
/// webhook, and so this implementation can be checked against the shared
/// vectors rather than trusted.
pub fn webhook_signature_header(secret: &str, raw_body: &[u8], timestamp: i64) -> String {
    let mut message = timestamp.to_string().into_bytes();
    message.push(b'.');
    message.extend_from_slice(raw_body);
    format!("t={timestamp},v1={}", to_hex(&hmac_sha256(secret.as_bytes(), &message)))
}

/// True if the signature is Mailcycle's, recent, and over this exact body.
///
/// `now` is passed in rather than read from the clock, so this is testable and
/// so a caller with a trusted time source can use it.
pub fn verify_webhook_signature(
    secret: &str,
    raw_body: &[u8],
    header: Option<&str>,
    tolerance_seconds: i64,
    now: i64,
) -> bool {
    let Some(header) = header else { return false };

    let mut timestamp: Option<i64> = None;
    let mut given: Option<&str> = None;
    for part in header.split(',') {
        // Trim the name as well as the value, matching the TS and Go SDKs, so a
        // header written with spaces around the keys still verifies.
        if let Some((name, value)) = part.split_once('=') {
            match name.trim() {
                "t" => timestamp = value.trim().parse().ok(),
                "v1" => given = Some(value.trim()),
                _ => {}
            }
        }
    }

    let (Some(timestamp), Some(given)) = (timestamp, given) else { return false };
    if (now - timestamp).abs() > tolerance_seconds {
        return false;
    }
    if given.len() != 64 {
        return false;
    }
    let Some(signature) = from_hex(given) else { return false };

    let mut message = timestamp.to_string().into_bytes();
    message.push(b'.');
    message.extend_from_slice(raw_body);
    constant_time_equal(&hmac_sha256(secret.as_bytes(), &message), &signature)
}

/// The same, against the system clock.
pub fn verify_webhook_signature_now(secret: &str, raw_body: &[u8], header: Option<&str>) -> bool {
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0);
    verify_webhook_signature(secret, raw_body, header, DEFAULT_TOLERANCE_SECONDS, now)
}