bachs-sdk 0.1.0

Unofficial Rust SDK for the Bachs API — payments and billing for internet businesses.
Documentation
//! Webhook signature verification.
//!
//! The Bachs Node SDK's `webhooks.constructEvent({ payload, headers, secret: 'whsec_...' })`
//! implies the same `whsec_`-prefixed-secret, HMAC-SHA256, `id.timestamp.payload`
//! convention used by the Standard Webhooks spec (and by Svix, which many
//! payments platforms build their webhook signing on top of). This module
//! implements verification against that convention:
//!
//! - Secret: `whsec_<base64>` — the part after `whsec_` is base64-decoded to
//!   get the raw HMAC key.
//! - Signed content: `{webhook_id}.{webhook_timestamp}.{raw_payload_bytes}`.
//! - Signature header: one or more space-separated `v1,<base64>` tokens (a
//!   payload can be signed with more than one active key during rotation —
//!   a match against any of them is accepted).
//!
//! **Header names aren't pinned down by the public docs**, so instead of
//! guessing exact HTTP header casing, this SDK asks you to pass the three
//! relevant values explicitly via [`SignatureHeaders`] — pull them from
//! whatever your framework calls its webhook-id / webhook-timestamp /
//! webhook-signature (or `X-Bachs-...`) headers. If Bachs' webhook headers
//! turn out to differ from this convention, please open an issue.
//!
//! Always treat webhooks — not client-side checkout redirects — as the
//! source of truth for fulfilment, per the Bachs docs.

use crate::error::{BachsError, BachsResult};
use base64::engine::general_purpose::STANDARD as BASE64;
use base64::Engine;
use hmac::{Hmac, Mac};
use serde::Deserialize;
use sha2::Sha256;
use subtle::ConstantTimeEq;

type HmacSha256 = Hmac<Sha256>;

/// The three header values needed to verify a webhook delivery.
#[derive(Debug, Clone, Copy)]
pub struct SignatureHeaders<'a> {
    /// Unique ID for this delivery attempt (stable across retries of the
    /// same event).
    pub id: &'a str,
    /// Unix timestamp (seconds) of when the webhook was sent.
    pub timestamp: &'a str,
    /// The raw signature header value, e.g. `"v1,g0hM9Ss...="` (may contain
    /// multiple space-separated signatures).
    pub signature: &'a str,
}

/// A parsed webhook event. `data` is left as raw JSON since the shape
/// differs per `event_type` (e.g. `collection.succeeded`) — deserialize it
/// further with `serde_json::from_value` once you've matched on the type.
#[derive(Debug, Clone, Deserialize)]
pub struct Event {
    #[serde(rename = "type")]
    pub event_type: String,
    #[serde(default)]
    pub id: Option<String>,
    #[serde(default)]
    pub created_at: Option<String>,
    pub data: serde_json::Value,
}

/// Verify a webhook's signature without parsing the body.
///
/// `payload` must be the **raw, unparsed** request body bytes — signing is
/// computed over the exact bytes sent, so re-serializing a parsed body will
/// not match.
pub fn verify_signature(
    payload: &[u8],
    headers: SignatureHeaders<'_>,
    secret: &str,
) -> BachsResult<()> {
    let key_b64 = secret.strip_prefix("whsec_").ok_or_else(|| {
        BachsError::WebhookSignature(
            "secret must start with 'whsec_' — pass the signing secret from your webhook \
             endpoint settings, not your API key"
                .to_string(),
        )
    })?;
    let key = BASE64
        .decode(key_b64)
        .map_err(|e| BachsError::WebhookSignature(format!("invalid secret encoding: {e}")))?;

    let signed_content = {
        let mut buf = Vec::with_capacity(headers.id.len() + headers.timestamp.len() + payload.len() + 2);
        buf.extend_from_slice(headers.id.as_bytes());
        buf.push(b'.');
        buf.extend_from_slice(headers.timestamp.as_bytes());
        buf.push(b'.');
        buf.extend_from_slice(payload);
        buf
    };

    let mut mac = HmacSha256::new_from_slice(&key)
        .map_err(|e| BachsError::WebhookSignature(format!("invalid key length: {e}")))?;
    mac.update(&signed_content);
    let expected = mac.finalize().into_bytes();

    for candidate in headers.signature.split_whitespace() {
        let sig_b64 = candidate.split_once(',').map(|(_, s)| s).unwrap_or(candidate);
        if let Ok(sig_bytes) = BASE64.decode(sig_b64) {
            if sig_bytes.len() == expected.len() && bool::from(sig_bytes.ct_eq(&expected)) {
                return Ok(());
            }
        }
    }

    Err(BachsError::WebhookSignature(
        "no signature in the header matched the expected value".to_string(),
    ))
}

/// Verify a webhook's signature and parse its body into an [`Event`].
///
/// ```no_run
/// use bachs_sdk::webhooks::{construct_event, SignatureHeaders};
///
/// # fn handle(raw_body: &[u8], id: &str, timestamp: &str, signature: &str) -> Result<(), bachs_sdk::BachsError> {
/// let event = construct_event(
///     raw_body,
///     SignatureHeaders { id, timestamp, signature },
///     "whsec_your_webhook_secret",
/// )?;
///
/// if event.event_type == "collection.succeeded" {
///     // handle payment success
/// }
/// # Ok(())
/// # }
/// ```
pub fn construct_event(
    payload: &[u8],
    headers: SignatureHeaders<'_>,
    secret: &str,
) -> BachsResult<Event> {
    verify_signature(payload, headers, secret)?;
    serde_json::from_slice(payload).map_err(BachsError::from)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn rejects_a_replay_with_old_timestamp() {
        let (secret, key) = {
            let key = b"0123456789abcdef0123456789abcdef".to_vec();
            let secret = format!("whsec_{}", BASE64.encode(&key));
            (secret, key)
        };
        let payload = br#"{"type":"ping"}"#;
        let headers = SignatureHeaders {
            id: "msg_1",
            timestamp: "1000000",
            signature: "",
        };
        let err = verify_signature(payload, headers, &secret).unwrap_err();
        match err {
            BachsError::WebhookSignature(_) => {}
            other => panic!("expected WebhookSignature, got {other:?}"),
        }
    }

    #[test]
    fn rejects_tampered_signature_header() {
        let (secret, key) = {
            let key = b"0123456789abcdef0123456789abcdef".to_vec();
            let secret = format!("whsec_{}", BASE64.encode(&key));
            (secret, key)
        };
        let payload = br#"{"type":"ping"}"#;
        let headers = SignatureHeaders {
            id: "msg_1",
            timestamp: "1750000000",
            signature: "v1,notavalidbase64signature!!!",
        };
        let err = verify_signature(payload, headers, &secret).unwrap_err();
        match err {
            BachsError::WebhookSignature(_) => {}
            other => panic!("expected WebhookSignature, got {other:?}"),
        }
    }

    #[test]
    fn event_deserialization() {
        let payload = br#"{"type":"collection.succeeded","data":{"charge_id":"chg_1"}}"#;
        let (secret, key) = {
            let key = b"0123456789abcdef0123456789abcdef".to_vec();
            let secret = format!("whsec_{}", BASE64.encode(&key));
            (secret, key)
        };
        let sig = {
            let mut mac = HmacSha256::new_from_slice(&key).unwrap();
            let mut content = Vec::new();
            content.extend_from_slice(b"msg_1");
            content.push(b'.');
            content.extend_from_slice(b"1750000000");
            content.push(b'.');
            content.extend_from_slice(payload);
            mac.update(&content);
            format!("v1,{}", BASE64.encode(mac.finalize().into_bytes()))
        };
        let headers = SignatureHeaders {
            id: "msg_1",
            timestamp: "1750000000",
            signature: &sig,
        };
        let event = construct_event(payload, headers, &secret).unwrap();
        assert_eq!(event.event_type, "collection.succeeded");
        assert_eq!(event.data["charge_id"], "chg_1");
    }
}