//! The little of Stripe's API we use: Checkout Sessions (a hosted payment //! page for one package) and webhook signature checking. The package catalog //! stays in `packages.rs`; each session carries its name and price, so no //! products have to be kept in the Stripe dashboard. use std::time::Duration; use hmac::{Hmac, Mac}; use serde::Deserialize; use sha2::Sha256; use crate::config::StripeConfig; use crate::error::ApiError; /// How old a webhook signature may be (Stripe's own libraries use 5 minutes). const SIGNATURE_TOLERANCE: i64 = 300; #[derive(Debug, Deserialize)] pub struct Session { pub id: String, /// The payment page (only while the session is open). pub url: Option, /// `paid`, `unpaid` or `no_payment_required`. pub payment_status: String, /// `open`, `complete` or `expired`. pub status: Option, } impl Session { pub fn paid(&self) -> bool { self.payment_status == "paid" } } pub struct Client { http: reqwest::Client, } impl Default for Client { fn default() -> Self { let http = reqwest::Client::builder().timeout(Duration::from_secs(20)).build().expect("static configuration"); Self { http } } } /// What the user sees when Stripe cannot be reached. fn unavailable(detail: String) -> ApiError { tracing::error!(error = %detail, "stripe request failed"); ApiError::Limited { code: "payment_unavailable", message: "A fizetési oldal most nem érhető el. Próbáld újra pár perc múlva.".into(), } } impl Client { /// Creates a Checkout Session from form fields (Stripe's API takes /// `application/x-www-form-urlencoded` with `a[b][c]` keys). pub async fn create_session(&self, config: &StripeConfig, form: &[(String, String)]) -> Result { let res = self .http .post(format!("{}/v1/checkout/sessions", config.api_url)) .bearer_auth(&config.secret_key) .form(form) .send() .await .map_err(|e| unavailable(e.to_string()))?; Self::session(res).await } pub async fn get_session(&self, config: &StripeConfig, id: &str) -> Result { let res = self .http .get(format!("{}/v1/checkout/sessions/{id}", config.api_url)) .bearer_auth(&config.secret_key) .send() .await .map_err(|e| unavailable(e.to_string()))?; Self::session(res).await } async fn session(res: reqwest::Response) -> Result { let status = res.status(); if !status.is_success() { let body = res.text().await.unwrap_or_default(); return Err(unavailable(format!("HTTP {status}: {}", body.chars().take(500).collect::()))); } res.json().await.map_err(|e| unavailable(format!("unexpected response: {e}"))) } } /// Checks a `Stripe-Signature` header (`t=…,v1=…[,v1=…]`): an HMAC-SHA256 of /// `"{t}.{body}"` with the endpoint's signing secret, at most five minutes old. pub fn verify_signature(secret: &str, header: &str, body: &[u8], now: i64) -> bool { let mut timestamp = None; let mut signatures = Vec::new(); for part in header.split(',') { match part.trim().split_once('=') { Some(("t", v)) => timestamp = v.parse::().ok(), Some(("v1", v)) => signatures.push(v), _ => {} } } let Some(timestamp) = timestamp else { return false }; if (now - timestamp).abs() > SIGNATURE_TOLERANCE { return false; } let mut mac = Hmac::::new_from_slice(secret.as_bytes()).expect("HMAC takes any key length"); mac.update(timestamp.to_string().as_bytes()); mac.update(b"."); mac.update(body); let expected = mac.finalize().into_bytes(); signatures.iter().any(|s| decode_hex(s).is_some_and(|sig| constant_time_eq(&sig, &expected))) } /// The signature header for a body, as Stripe would send it (tests). #[cfg(test)] pub fn sign(secret: &str, body: &[u8], timestamp: i64) -> String { let mut mac = Hmac::::new_from_slice(secret.as_bytes()).unwrap(); mac.update(format!("{timestamp}.").as_bytes()); mac.update(body); let hex: String = mac.finalize().into_bytes().iter().map(|b| format!("{b:02x}")).collect(); format!("t={timestamp},v1={hex}") } fn decode_hex(s: &str) -> Option> { if !s.len().is_multiple_of(2) { return None; } (0..s.len()).step_by(2).map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok()).collect() } fn constant_time_eq(a: &[u8], b: &[u8]) -> bool { a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 } #[cfg(test)] mod tests { use super::*; #[test] fn signatures_are_checked() { let body = br#"{"id":"evt_1"}"#; let now = 1_800_000_000; let header = sign("whsec_test", body, now); assert!(verify_signature("whsec_test", &header, body, now)); assert!(verify_signature("whsec_test", &header, body, now + 299)); // Another secret, a changed body, an old or missing timestamp. assert!(!verify_signature("whsec_other", &header, body, now)); assert!(!verify_signature("whsec_test", &header, br#"{"id":"evt_2"}"#, now)); assert!(!verify_signature("whsec_test", &header, body, now + 301)); assert!(!verify_signature("whsec_test", header.split_once(',').unwrap().1, body, now)); // One good signature among others (during a secret rotation) is enough. let rotated = format!("{header},v1=00ff"); assert!(verify_signature("whsec_test", &rotated, body, now)); assert!(!verify_signature("whsec_test", "t=1800000000,v1=zz", body, now)); } }