hatang 0.3.0

Official Rust client for the Ha Tang (Hạ Tầng) API: transactional email, live chat and support CRM, VietQR payments, AI chatbot knowledge and webhook verification. Async (Tokio) and blocking.
Documentation
//! Checking what Ha Tang sends to your endpoints: webhook deliveries and payment IPN calls.
//!
//! Always pass the raw request body exactly as received, before any JSON parsing.

use std::collections::{BTreeMap, HashMap};
use std::time::{SystemTime, UNIX_EPOCH};

use base64::engine::general_purpose::STANDARD as B64;
use base64::Engine as _;
use hmac::{Hmac, Mac};
use serde_json::Value;
use sha2::Sha256;
use subtle::ConstantTimeEq;

use crate::error::{Error, Result};

type HmacSha256 = Hmac<Sha256>;

/// How old a webhook delivery may be, in seconds, unless you say otherwise (against replays).
pub const DEFAULT_TOLERANCE_SECS: u64 = 300;

/// Request headers, looked up case-insensitively. Implemented for `http::HeaderMap` (axum, actix-web 4 via its
/// `HeaderMap`, reqwest, hyper), `HashMap`/`BTreeMap` of strings and slices of `(name, value)` pairs.
pub trait Headers {
    /// The first value of a header, by lowercase name.
    fn header(&self, name: &str) -> Option<String>;
}

impl Headers for reqwest::header::HeaderMap {
    fn header(&self, name: &str) -> Option<String> {
        self.get(name)
            .and_then(|v| v.to_str().ok())
            .map(str::to_string)
    }
}

fn find<'a, K: AsRef<str> + 'a, V: AsRef<str> + 'a>(
    mut pairs: impl Iterator<Item = (&'a K, &'a V)>,
    name: &str,
) -> Option<String> {
    pairs
        .find(|(k, _)| k.as_ref().eq_ignore_ascii_case(name))
        .map(|(_, v)| v.as_ref().to_string())
}

impl<K: AsRef<str>, V: AsRef<str>> Headers for HashMap<K, V> {
    fn header(&self, name: &str) -> Option<String> {
        find(self.iter(), name)
    }
}

impl<K: AsRef<str>, V: AsRef<str>> Headers for BTreeMap<K, V> {
    fn header(&self, name: &str) -> Option<String> {
        find(self.iter(), name)
    }
}

impl<K: AsRef<str>, V: AsRef<str>> Headers for [(K, V)] {
    fn header(&self, name: &str) -> Option<String> {
        find(self.iter().map(|(k, v)| (k, v)), name)
    }
}

impl<K: AsRef<str>, V: AsRef<str>, const N: usize> Headers for [(K, V); N] {
    fn header(&self, name: &str) -> Option<String> {
        self.as_slice().header(name)
    }
}

impl<K: AsRef<str>, V: AsRef<str>> Headers for Vec<(K, V)> {
    fn header(&self, name: &str) -> Option<String> {
        self.as_slice().header(name)
    }
}

impl<T: Headers + ?Sized> Headers for &T {
    fn header(&self, name: &str) -> Option<String> {
        (**self).header(name)
    }
}

fn now_secs() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

fn either(headers: &(impl Headers + ?Sized), svix: &str, standard: &str) -> Option<String> {
    headers
        .header(svix)
        .filter(|v| !v.is_empty())
        .or_else(|| headers.header(standard).filter(|v| !v.is_empty()))
}

/// True when a webhook delivery is signed with your endpoint's `whsec_…` secret (Standard Webhooks / Svix headers)
/// and is no older than five minutes.
///
/// ```
/// # let (raw_body, headers) = (b"{}".as_slice(), [("svix-id", "msg_1")]);
/// if !hatang::verify_webhook(raw_body, &headers, "whsec_…") {
///     // answer 400
/// }
/// ```
pub fn verify_webhook(
    raw_body: impl AsRef<[u8]>,
    headers: &(impl Headers + ?Sized),
    secret: &str,
) -> bool {
    verify_webhook_at(
        raw_body,
        headers,
        secret,
        DEFAULT_TOLERANCE_SECS,
        now_secs(),
    )
}

/// [`verify_webhook`] with your own tolerance and clock (Unix seconds), for tests and unusual setups.
pub fn verify_webhook_at(
    raw_body: impl AsRef<[u8]>,
    headers: &(impl Headers + ?Sized),
    secret: &str,
    tolerance_secs: u64,
    now_secs: u64,
) -> bool {
    let (Some(id), Some(ts), Some(sigs)) = (
        either(headers, "svix-id", "webhook-id"),
        either(headers, "svix-timestamp", "webhook-timestamp"),
        either(headers, "svix-signature", "webhook-signature"),
    ) else {
        return false;
    };
    let Ok(sent) = ts.trim().parse::<u64>() else {
        return false;
    };
    if now_secs.abs_diff(sent) > tolerance_secs {
        return false;
    }
    let Ok(key) = B64.decode(secret.strip_prefix("whsec_").unwrap_or(secret)) else {
        return false;
    };
    let Ok(mut mac) = HmacSha256::new_from_slice(&key) else {
        return false;
    };
    mac.update(id.as_bytes());
    mac.update(b".");
    mac.update(ts.as_bytes());
    mac.update(b".");
    mac.update(raw_body.as_ref());
    let expected = B64.encode(mac.finalize().into_bytes());
    sigs.split(' ').any(|part| match part.split_once(',') {
        Some(("v1", sig)) if !sig.is_empty() => sig.as_bytes().ct_eq(expected.as_bytes()).into(),
        _ => false,
    })
}

/// The verified event (`type`, `created_at`, `data`), or [`Error::Signature`].
pub fn construct_webhook_event(
    raw_body: impl AsRef<[u8]>,
    headers: &(impl Headers + ?Sized),
    secret: &str,
) -> Result<Value> {
    let body = raw_body.as_ref();
    if !verify_webhook(body, headers, secret) {
        return Err(Error::Signature(
            "Webhook signature or timestamp is not valid".into(),
        ));
    }
    Ok(serde_json::from_slice(body)?)
}

/// True when a payment IPN call matches its `Hatang-Signature` header: hex HMAC-SHA256 of the body with your
/// secret key (Payments settings → Integration keys, of the call's environment).
pub fn verify_ipn(raw_body: impl AsRef<[u8]>, signature: Option<&str>, secret_key: &str) -> bool {
    let Some(sig) = signature
        .map(|s| s.trim().to_ascii_lowercase())
        .filter(|s| !s.is_empty())
    else {
        return false;
    };
    let Ok(mut mac) = HmacSha256::new_from_slice(secret_key.as_bytes()) else {
        return false;
    };
    mac.update(raw_body.as_ref());
    let expected = hex(&mac.finalize().into_bytes());
    sig.as_bytes().ct_eq(expected.as_bytes()).into()
}

/// The verified IPN call (`data.status`, `data.metadata`…), or [`Error::Signature`].
pub fn construct_ipn_event(
    raw_body: impl AsRef<[u8]>,
    headers: &(impl Headers + ?Sized),
    secret_key: &str,
) -> Result<Value> {
    let body = raw_body.as_ref();
    if !verify_ipn(
        body,
        headers.header("hatang-signature").as_deref(),
        secret_key,
    ) {
        return Err(Error::Signature(
            "Hatang-Signature does not match the body and secret key".into(),
        ));
    }
    Ok(serde_json::from_slice(body)?)
}

pub(crate) fn hex(bytes: &[u8]) -> String {
    const DIGITS: &[u8; 16] = b"0123456789abcdef";
    let mut out = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        out.push(DIGITS[(b >> 4) as usize] as char);
        out.push(DIGITS[(b & 0xf) as usize] as char);
    }
    out
}