meteroid-rs 0.31.4

Official Rust SDK for Meteroid, the open-source billing platform: subscriptions, invoicing, usage-based billing and webhooks.
Documentation
// this file is @generated by Perseid; edit the shared runtime template.
//! Standard Webhooks signature verification, also accepting the legacy `svix-*` headers.
//!
//! ```no_run
//! use meteroid_rs::webhooks::{Webhook, WebhookError};
//!
//! fn verify(body: &[u8], headers: &http::HeaderMap) -> Result<(), WebhookError> {
//!     Webhook::new("whsec_your_webhook_secret")?.verify(body, headers)
//! }
//! ```
use base64::{engine::general_purpose::STANDARD, Engine as _};
use hmac::{Hmac, Mac};
use sha2::Sha256;
use std::{
    fmt,
    time::{SystemTime, UNIX_EPOCH},
};

const TOLERANCE_SECONDS: i64 = 5 * 60;
const SECRET_PREFIX: &str = "whsec_";
const HEADERS: [[&str; 2]; 3] = [
    ["webhook-id", "svix-id"],
    ["webhook-timestamp", "svix-timestamp"],
    ["webhook-signature", "svix-signature"],
];

/// Why a webhook payload is rejected.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WebhookError {
    /// The secret is empty or not valid base64.
    InvalidSecret,
    /// A `webhook-id`, `webhook-timestamp` or `webhook-signature` header is missing.
    MissingHeaders,
    /// The timestamp header is not a number of seconds.
    InvalidTimestamp,
    /// The payload was signed more than five minutes ago.
    TimestampTooOld,
    /// The payload claims to be signed more than five minutes from now.
    TimestampTooNew,
    /// No signature matches the payload.
    NoMatchingSignature,
}

impl fmt::Display for WebhookError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::InvalidSecret => "webhook secret is empty or not valid base64",
            Self::MissingHeaders => "missing webhook signature headers",
            Self::InvalidTimestamp => "invalid webhook timestamp header",
            Self::TimestampTooOld => "webhook timestamp is too old",
            Self::TimestampTooNew => "webhook timestamp is too far in the future",
            Self::NoMatchingSignature => "no matching webhook signature",
        })
    }
}

impl std::error::Error for WebhookError {}

/// Verifies and signs webhook payloads. `webhook-*` headers win over `svix-*` ones.
pub struct Webhook {
    key: Vec<u8>,
}

impl Webhook {
    /// The secret as shown in your dashboard: base64, with or without the `whsec_` prefix.
    ///
    /// # Errors
    ///
    /// [`WebhookError::InvalidSecret`] when the secret is empty or not base64.
    pub fn new(secret: &str) -> Result<Self, WebhookError> {
        let encoded = secret.strip_prefix(SECRET_PREFIX).unwrap_or(secret);
        let key = STANDARD
            .decode(encoded)
            .map_err(|_| WebhookError::InvalidSecret)?;
        Self::from_bytes(key)
    }

    /// The raw, already decoded signing key.
    ///
    /// # Errors
    ///
    /// [`WebhookError::InvalidSecret`] when the key is empty.
    pub fn from_bytes(key: Vec<u8>) -> Result<Self, WebhookError> {
        if key.is_empty() {
            return Err(WebhookError::InvalidSecret);
        }
        Ok(Self { key })
    }

    /// Checks the signature and that the timestamp is within five minutes of now.
    /// `payload` must be the exact request body, before any parsing.
    ///
    /// # Errors
    ///
    /// The reason the payload is not to be trusted: missing headers, a timestamp too old or
    /// too new, or no matching signature.
    pub fn verify(&self, payload: &[u8], headers: &http::HeaderMap) -> Result<(), WebhookError> {
        let [id, timestamp, signatures] = HEADERS.map(|names| header(headers, names));
        if id.is_empty() || timestamp.is_empty() || signatures.is_empty() {
            return Err(WebhookError::MissingHeaders);
        }
        let seconds: i64 = timestamp
            .parse()
            .map_err(|_| WebhookError::InvalidTimestamp)?;
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX));
        if seconds < now - TOLERANCE_SECONDS {
            return Err(WebhookError::TimestampTooOld);
        }
        if seconds > now + TOLERANCE_SECONDS {
            return Err(WebhookError::TimestampTooNew);
        }
        let matches = signatures
            .split_whitespace()
            .filter_map(|part| part.strip_prefix("v1,"))
            .filter_map(|signature| STANDARD.decode(signature).ok())
            .any(|signature| {
                self.mac(&id, seconds, payload)
                    .verify_slice(&signature)
                    .is_ok()
            });
        matches
            .then_some(())
            .ok_or(WebhookError::NoMatchingSignature)
    }

    /// Returns the `v1,<base64>` value of the `webhook-signature` header.
    #[must_use]
    pub fn sign(&self, msg_id: &str, timestamp: i64, payload: &[u8]) -> String {
        let signature = self.mac(msg_id, timestamp, payload).finalize().into_bytes();
        format!("v1,{}", STANDARD.encode(signature))
    }

    fn mac(&self, msg_id: &str, timestamp: i64, payload: &[u8]) -> Hmac<Sha256> {
        let mut mac = Hmac::<Sha256>::new_from_slice(&self.key).expect("HMAC accepts any key size");
        mac.update(format!("{msg_id}.{timestamp}.").as_bytes());
        mac.update(payload);
        mac
    }
}

fn header(headers: &http::HeaderMap, names: [&str; 2]) -> String {
    names
        .iter()
        .map(|name| {
            headers
                .get_all(*name)
                .iter()
                .filter_map(|value| value.to_str().ok())
                .collect::<Vec<_>>()
                .join(" ")
        })
        .find(|value| !value.is_empty())
        .unwrap_or_default()
}