Packages paid through Stripe Checkout
The catalog stays in packages.rs: every checkout session carries the package's name and gross price, nothing has to be kept in Stripe. The package is granted once, when Stripe confirms the payment: by the signed webhook, or by the return page asking Stripe when the webhook is late. With a test key only admins can buy, so Stripe's test cards give nobody free packages. Without the keys nothing changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -10,6 +10,7 @@ publish.workspace = true
|
||||
db.workspace = true
|
||||
analysis-prompt.workspace = true
|
||||
email-templates.workspace = true
|
||||
hmac.workspace = true
|
||||
horoscope-client.workspace = true
|
||||
service-kit.workspace = true
|
||||
anyhow.workspace = true
|
||||
|
||||
@@ -45,6 +45,9 @@ pub struct Config {
|
||||
/// `MOCK_PAYMENTS` (default `false`): a stand-in payment that adds an
|
||||
/// analysis unit at once, until Stripe is connected.
|
||||
pub mock_payments: bool,
|
||||
/// Stripe Checkout, when `STRIPE_SECRET_KEY` is set (it wins over
|
||||
/// `MOCK_PAYMENTS`). With a test key only admins can buy.
|
||||
pub stripe: Option<StripeConfig>,
|
||||
/// `USER_INVITES` (default `false`): users may invite others ("how
|
||||
/// compatible are we?" links, which also let the invitee sign up). Off
|
||||
/// until the launch; admins may always.
|
||||
@@ -85,6 +88,34 @@ pub struct Config {
|
||||
pub signup_mode: SignupMode,
|
||||
}
|
||||
|
||||
/// `STRIPE_SECRET_KEY` (`sk_test_…` or `sk_live_…`), `STRIPE_WEBHOOK_SECRET`
|
||||
/// (`whsec_…`, from the webhook endpoint in the Stripe dashboard) and
|
||||
/// `STRIPE_API_URL` (default `https://api.stripe.com`, tests change it).
|
||||
#[derive(Clone)]
|
||||
pub struct StripeConfig {
|
||||
pub secret_key: String,
|
||||
pub webhook_secret: Option<String>,
|
||||
pub api_url: String,
|
||||
}
|
||||
|
||||
impl StripeConfig {
|
||||
/// A test-mode key: no real money moves.
|
||||
pub fn test_mode(&self) -> bool {
|
||||
self.secret_key.starts_with("sk_test_") || self.secret_key.starts_with("rk_test_")
|
||||
}
|
||||
}
|
||||
|
||||
// The keys stay out of logs.
|
||||
impl std::fmt::Debug for StripeConfig {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("StripeConfig")
|
||||
.field("test_mode", &self.test_mode())
|
||||
.field("webhook_secret", &self.webhook_secret.is_some())
|
||||
.field("api_url", &self.api_url)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
fn var(name: &str) -> Option<String> {
|
||||
std::env::var(name).ok().map(|v| v.trim().to_string()).filter(|v| !v.is_empty())
|
||||
}
|
||||
@@ -127,6 +158,14 @@ impl Config {
|
||||
session_ttl_days: parsed("SESSION_TTL_DAYS", 30)?,
|
||||
password_login: parsed("PASSWORD_LOGIN", false)?,
|
||||
mock_payments: parsed("MOCK_PAYMENTS", false)?,
|
||||
stripe: var("STRIPE_SECRET_KEY").map(|secret_key| StripeConfig {
|
||||
secret_key,
|
||||
webhook_secret: var("STRIPE_WEBHOOK_SECRET"),
|
||||
api_url: var("STRIPE_API_URL")
|
||||
.unwrap_or_else(|| "https://api.stripe.com".into())
|
||||
.trim_end_matches('/')
|
||||
.to_string(),
|
||||
}),
|
||||
user_invites: parsed("USER_INVITES", false)?,
|
||||
referral_rewards: parsed("REFERRAL_REWARDS", false)?,
|
||||
google_client_ids: list("GOOGLE_CLIENT_IDS"),
|
||||
@@ -166,6 +205,7 @@ impl Config {
|
||||
session_ttl_days: 30,
|
||||
password_login: true,
|
||||
mock_payments: true,
|
||||
stripe: None,
|
||||
user_invites: true,
|
||||
referral_rewards: true,
|
||||
google_client_ids: vec!["test-client.apps.googleusercontent.com".into()],
|
||||
|
||||
@@ -17,6 +17,7 @@ mod models;
|
||||
mod packages;
|
||||
mod persons;
|
||||
mod routes;
|
||||
mod stripe;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod views;
|
||||
@@ -41,6 +42,7 @@ pub struct AppState {
|
||||
pub google: GoogleVerifier,
|
||||
pub login_limiter: LoginLimiter,
|
||||
pub models: models::Catalog,
|
||||
pub stripe: stripe::Client,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
@@ -50,6 +52,7 @@ impl AppState {
|
||||
google: GoogleVerifier::new(config.google_client_ids.clone(), config.google_jwks_url.clone()),
|
||||
login_limiter: LoginLimiter::new(10, Duration::from_secs(15 * 60)),
|
||||
models: models::Catalog::new(&config.openrouter_models_url),
|
||||
stripe: stripe::Client::default(),
|
||||
db,
|
||||
config,
|
||||
}
|
||||
|
||||
@@ -186,6 +186,8 @@ pub enum Source {
|
||||
Mock,
|
||||
/// A redeemed promo code.
|
||||
Promo,
|
||||
/// Paid through Stripe Checkout.
|
||||
Stripe,
|
||||
}
|
||||
|
||||
impl Source {
|
||||
@@ -194,6 +196,7 @@ impl Source {
|
||||
Source::Admin => "admin",
|
||||
Source::Mock => "mock",
|
||||
Source::Promo => "promo",
|
||||
Source::Stripe => "stripe",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -268,7 +271,7 @@ async fn record(
|
||||
let order = Uuid::now_v7();
|
||||
let price = match source {
|
||||
Source::Admin | Source::Promo => 0,
|
||||
Source::Mock => package.price_huf,
|
||||
Source::Mock | Source::Stripe => package.price_huf,
|
||||
};
|
||||
sqlx::query(
|
||||
"INSERT INTO package_orders (id, user_id, package, source, price_huf, note, created_by) \
|
||||
|
||||
@@ -77,6 +77,9 @@ pub fn router(state: Arc<AppState>) -> Router {
|
||||
.route("/v1/me/export", get(account::export))
|
||||
.route("/v1/credits", get(account::credits))
|
||||
.route("/v1/payments/mock", post(payments::mock))
|
||||
.route("/v1/payments/checkout", post(payments::checkout))
|
||||
.route("/v1/payments/checkout/{id}", get(payments::checkout_status))
|
||||
.route("/v1/payments/stripe/webhook", post(payments::stripe_webhook))
|
||||
// charts
|
||||
.route("/v1/charts", get(charts::list).post(charts::create))
|
||||
.route("/v1/charts/{id}", get(charts::get_one).patch(charts::update).delete(charts::remove))
|
||||
@@ -161,7 +164,10 @@ async fn public_config(State(state): St) -> Json<Value> {
|
||||
"google_login": { "enabled": state.google.enabled(), "client_id": c.google_client_ids.first() },
|
||||
"locales": c.supported_locales,
|
||||
"password_login": c.password_login,
|
||||
"mock_payments": c.mock_payments,
|
||||
"mock_payments": payments::method(c) == Some("mock"),
|
||||
// "stripe", "mock" or null; with a Stripe test key only admins can buy.
|
||||
"payments": payments::method(c),
|
||||
"payments_test": c.stripe.as_ref().is_some_and(|s| s.test_mode()),
|
||||
"user_invites": c.user_invites,
|
||||
"referral_rewards": c.referral_rewards,
|
||||
"signup_mode": c.signup_mode.as_str(),
|
||||
|
||||
@@ -1,19 +1,27 @@
|
||||
//! Packages and payments. Until Stripe is connected, `MOCK_PAYMENTS=true`
|
||||
//! turns on a stand-in: "paying" grants the package right away, so the paid
|
||||
//! flow can be used end to end.
|
||||
//! Packages and payments. With `STRIPE_SECRET_KEY` a package is paid on
|
||||
//! Stripe's hosted Checkout page and granted when Stripe confirms the payment
|
||||
//! (webhook, or the return page asking). Without it `MOCK_PAYMENTS=true`
|
||||
//! turns on a stand-in: "paying" grants the package right away.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::State;
|
||||
use axum::body::Bytes;
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::HeaderMap;
|
||||
use axum_extra::extract::WithRejection;
|
||||
use db::Role;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{Body, St};
|
||||
use crate::AppState;
|
||||
use crate::auth::AuthUser;
|
||||
use crate::config::StripeConfig;
|
||||
use crate::credits::{self, Unit};
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::packages::{self, CATALOG, Source};
|
||||
use crate::persons;
|
||||
use crate::{persons, stripe};
|
||||
|
||||
/// The package catalog (public).
|
||||
pub async fn catalog() -> Json<Value> {
|
||||
@@ -46,7 +54,7 @@ pub async fn mock(
|
||||
auth: AuthUser,
|
||||
WithRejection(Json(req), _): Body<MockPayment>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
if !state.config.mock_payments {
|
||||
if !state.config.mock_payments || state.config.stripe.is_some() {
|
||||
return Err(ApiError::NotFound("payment method"));
|
||||
}
|
||||
let id = match (req.package.as_deref(), req.unit) {
|
||||
@@ -65,3 +73,172 @@ pub async fn mock(
|
||||
tracing::info!(user = %auth.id(), package = package.id, "mock payment");
|
||||
Ok(Json(holdings(&state, &auth).await?))
|
||||
}
|
||||
|
||||
/// How the frontend should offer purchases: `"stripe"`, `"mock"` or `None`
|
||||
/// (no purchases).
|
||||
pub fn method(config: &crate::config::Config) -> Option<&'static str> {
|
||||
match (&config.stripe, config.mock_payments) {
|
||||
(Some(_), _) => Some("stripe"),
|
||||
(None, true) => Some("mock"),
|
||||
(None, false) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Stripe, if this user may pay through it (with a test key: admins only, so
|
||||
/// nobody gets packages with Stripe's test cards).
|
||||
fn stripe_for<'a>(state: &'a AppState, auth: &AuthUser) -> Result<&'a StripeConfig, ApiError> {
|
||||
let config = state.config.stripe.as_ref().ok_or(ApiError::NotFound("payment method"))?;
|
||||
if config.test_mode() && !auth.user.has_role(Role::Admin) {
|
||||
return Err(ApiError::Forbidden("purchases are being tested; they open soon".into()));
|
||||
}
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
/// The page to come back to after paying: a plain path of this site, without
|
||||
/// its query (anything else: the packages page).
|
||||
fn return_path(path: Option<&str>) -> String {
|
||||
let path = path.unwrap_or("").split(['?', '#']).next().unwrap_or("");
|
||||
let plain = path.starts_with('/')
|
||||
&& !path.starts_with("//")
|
||||
&& path.len() <= 200
|
||||
&& path.chars().all(|c| c.is_ascii_alphanumeric() || "/-_.".contains(c));
|
||||
if plain { path.to_string() } else { "/csomagok".to_string() }
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CheckoutRequest {
|
||||
package: String,
|
||||
/// The page the purchase started on (default: the packages page).
|
||||
return_path: Option<String>,
|
||||
}
|
||||
|
||||
/// Starts paying for a package: returns the address of Stripe's payment page.
|
||||
pub async fn checkout(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
WithRejection(Json(req), _): Body<CheckoutRequest>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let config = stripe_for(&state, &auth)?;
|
||||
let package = packages::find(&req.package).ok_or(ApiError::NotFound("package"))?;
|
||||
let back = format!("{}{}", state.config.public_base_url, return_path(req.return_path.as_deref()));
|
||||
let field = |k: &str, v: &str| (k.to_string(), v.to_string());
|
||||
let form = vec![
|
||||
field("mode", "payment"),
|
||||
field("locale", "hu"),
|
||||
field("client_reference_id", &auth.id().to_string()),
|
||||
field("customer_email", &auth.user.email),
|
||||
// Name and address go on the invoice.
|
||||
field("billing_address_collection", "required"),
|
||||
field("line_items[0][quantity]", "1"),
|
||||
field("line_items[0][price_data][currency]", "huf"),
|
||||
// Stripe counts forints in fillér.
|
||||
field("line_items[0][price_data][unit_amount]", &(package.price_huf * 100).to_string()),
|
||||
field("line_items[0][price_data][product_data][name]", &format!("Sorsfonalak – {}", package.name)),
|
||||
field("line_items[0][price_data][product_data][description]", package.tagline),
|
||||
field("metadata[package]", package.id),
|
||||
field("metadata[user_id]", &auth.id().to_string()),
|
||||
field("payment_intent_data[description]", &format!("Sorsfonalak – {}", package.name)),
|
||||
field("payment_intent_data[metadata][package]", package.id),
|
||||
field("success_url", &format!("{back}?fizetes={{CHECKOUT_SESSION_ID}}")),
|
||||
field("cancel_url", &format!("{back}?fizetes=megszakitva")),
|
||||
];
|
||||
let session = state.stripe.create_session(config, &form).await?;
|
||||
let url = session.url.ok_or_else(|| ApiError::Internal(format!("checkout session {} has no url", session.id)))?;
|
||||
sqlx::query("INSERT INTO stripe_checkouts (id, user_id, package, price_huf, live) VALUES ($1, $2, $3, $4, $5)")
|
||||
.bind(&session.id)
|
||||
.bind(auth.id())
|
||||
.bind(package.id)
|
||||
.bind(package.price_huf as i32)
|
||||
.bind(!config.test_mode())
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
tracing::info!(user = %auth.id(), package = package.id, session = %session.id, "checkout started");
|
||||
Ok(Json(json!({ "url": url })))
|
||||
}
|
||||
|
||||
/// Grants the package of a paid session, once. `false`: not our session.
|
||||
async fn complete(state: &AppState, session_id: &str) -> Result<bool, ApiError> {
|
||||
let mut tx = state.db.begin().await?;
|
||||
let row: Option<(Uuid, String, Option<OffsetDateTime>)> =
|
||||
sqlx::query_as("SELECT user_id, package, completed_at FROM stripe_checkouts WHERE id = $1 FOR UPDATE")
|
||||
.bind(session_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
let Some((user_id, package_id, completed_at)) = row else { return Ok(false) };
|
||||
if completed_at.is_some() {
|
||||
return Ok(true);
|
||||
}
|
||||
let package =
|
||||
packages::find(&package_id).ok_or_else(|| ApiError::Internal(format!("unknown package {package_id}")))?;
|
||||
let note = format!("Stripe {session_id}");
|
||||
let order = packages::grant(&mut tx, user_id, package, Source::Stripe, Some(user_id), Some(¬e)).await?;
|
||||
sqlx::query("UPDATE stripe_checkouts SET completed_at = now(), order_id = $2 WHERE id = $1")
|
||||
.bind(session_id)
|
||||
.bind(order)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
tracing::info!(user = %user_id, package = package.id, session = session_id, "package paid");
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Where a payment stands (the return page asks until it is paid). If the
|
||||
/// webhook has not arrived yet, Stripe is asked directly.
|
||||
pub async fn checkout_status(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
WithRejection(Path(id), _): WithRejection<Path<String>, ApiError>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let row: Option<(String, Option<OffsetDateTime>)> =
|
||||
sqlx::query_as("SELECT package, completed_at FROM stripe_checkouts WHERE id = $1 AND user_id = $2")
|
||||
.bind(&id)
|
||||
.bind(auth.id())
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
let (package_id, completed_at) = row.ok_or(ApiError::NotFound("payment"))?;
|
||||
let mut status = if completed_at.is_some() { "paid" } else { "pending" };
|
||||
if let (None, Some(config)) = (completed_at, &state.config.stripe) {
|
||||
let session = state.stripe.get_session(config, &id).await?;
|
||||
if session.paid() {
|
||||
complete(&state, &id).await?;
|
||||
status = "paid";
|
||||
} else if session.status.as_deref() == Some("expired") {
|
||||
status = "expired";
|
||||
}
|
||||
}
|
||||
Ok(Json(json!({
|
||||
"status": status,
|
||||
"package": package_id,
|
||||
"name": packages::find(&package_id).map(|p| p.name),
|
||||
})))
|
||||
}
|
||||
|
||||
/// Stripe's webhook (Developers → Webhooks; event `checkout.session.completed`,
|
||||
/// for delayed methods also `checkout.session.async_payment_succeeded`).
|
||||
pub async fn stripe_webhook(State(state): St, headers: HeaderMap, body: Bytes) -> ApiResult<Json<Value>> {
|
||||
let secret = state
|
||||
.config
|
||||
.stripe
|
||||
.as_ref()
|
||||
.and_then(|c| c.webhook_secret.as_deref())
|
||||
.ok_or(ApiError::NotFound("payment method"))?;
|
||||
let signature = headers.get("stripe-signature").and_then(|v| v.to_str().ok()).unwrap_or("");
|
||||
let now = OffsetDateTime::now_utc().unix_timestamp();
|
||||
if !stripe::verify_signature(secret, signature, &body, now) {
|
||||
tracing::warn!("stripe webhook with a bad signature");
|
||||
return Err(ApiError::BadRequest("invalid signature".into()));
|
||||
}
|
||||
let event: Value = serde_json::from_slice(&body).map_err(|e| ApiError::BadRequest(e.to_string()))?;
|
||||
let kind = event["type"].as_str().unwrap_or_default();
|
||||
let session = &event["data"]["object"];
|
||||
if matches!(kind, "checkout.session.completed" | "checkout.session.async_payment_succeeded")
|
||||
&& session["payment_status"] == "paid"
|
||||
{
|
||||
let id = session["id"].as_str().unwrap_or_default();
|
||||
if !complete(&state, id).await? {
|
||||
tracing::warn!(session = id, "stripe webhook for a session we did not start");
|
||||
}
|
||||
}
|
||||
Ok(Json(json!({ "received": true })))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
//! 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<String>,
|
||||
/// `paid`, `unpaid` or `no_payment_required`.
|
||||
pub payment_status: String,
|
||||
/// `open`, `complete` or `expired`.
|
||||
pub status: Option<String>,
|
||||
}
|
||||
|
||||
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<Session, ApiError> {
|
||||
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<Session, ApiError> {
|
||||
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<Session, ApiError> {
|
||||
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::<String>())));
|
||||
}
|
||||
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::<i64>().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::<Sha256>::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::<Sha256>::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<Vec<u8>> {
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -111,9 +111,54 @@ async fn fake_openrouter_models() -> Json<Value> {
|
||||
]}))
|
||||
}
|
||||
|
||||
/// Checkout sessions the fake Stripe created: form fields and whether paid.
|
||||
type FakeSessions = std::sync::Mutex<std::collections::HashMap<String, (Vec<(String, String)>, bool)>>;
|
||||
static STRIPE_SESSIONS: std::sync::LazyLock<FakeSessions> = std::sync::LazyLock::new(Default::default);
|
||||
static STRIPE_IDS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||||
|
||||
fn stripe_form(id: &str, key: &str) -> Option<String> {
|
||||
let sessions = STRIPE_SESSIONS.lock().unwrap();
|
||||
sessions.get(id)?.0.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone())
|
||||
}
|
||||
|
||||
fn stripe_pay(id: &str) {
|
||||
STRIPE_SESSIONS.lock().unwrap().get_mut(id).unwrap().1 = true;
|
||||
}
|
||||
|
||||
async fn fake_stripe_create(
|
||||
headers: HeaderMap,
|
||||
axum::Form(form): axum::Form<Vec<(String, String)>>,
|
||||
) -> (StatusCode, Json<Value>) {
|
||||
if headers.get("authorization").and_then(|v| v.to_str().ok()) != Some("Bearer sk_live_fake") {
|
||||
return (StatusCode::UNAUTHORIZED, Json(json!({"error": {"message": "bad key"}})));
|
||||
}
|
||||
let id = format!("cs_fake_{}", STRIPE_IDS.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
|
||||
STRIPE_SESSIONS.lock().unwrap().insert(id.clone(), (form, false));
|
||||
(
|
||||
StatusCode::OK,
|
||||
Json(
|
||||
json!({"id": id, "url": format!("https://checkout.stripe.test/{id}"), "payment_status": "unpaid", "status": "open"}),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
async fn fake_stripe_get(axum::extract::Path(id): axum::extract::Path<String>) -> (StatusCode, Json<Value>) {
|
||||
match STRIPE_SESSIONS.lock().unwrap().get(&id) {
|
||||
Some((_, paid)) => (
|
||||
StatusCode::OK,
|
||||
Json(json!({"id": id, "url": null,
|
||||
"payment_status": if *paid { "paid" } else { "unpaid" },
|
||||
"status": if *paid { "complete" } else { "open" }})),
|
||||
),
|
||||
None => (StatusCode::NOT_FOUND, Json(json!({"error": {"message": "no such session"}}))),
|
||||
}
|
||||
}
|
||||
|
||||
async fn fake_services() -> String {
|
||||
let app = Router::new()
|
||||
.route("/openrouter/models", get(fake_openrouter_models))
|
||||
.route("/v1/checkout/sessions", post(fake_stripe_create))
|
||||
.route("/v1/checkout/sessions/{id}", get(fake_stripe_get))
|
||||
.route("/v1/natal", post(fake_natal))
|
||||
.route("/v1/synastry", post(fake_synastry))
|
||||
.route("/v1/forecast", post(fake_forecast))
|
||||
@@ -782,8 +827,10 @@ async fn export_and_delete_account(pool: PgPool) {
|
||||
/// config and catalog, shared links, invitation pages, the waitlist and
|
||||
/// unsubscribing. Every other route (charts, calculations, analyses) needs a
|
||||
/// logged-in user, so other apps cannot use them.
|
||||
const PUBLIC_ROUTES: [&str; 15] = [
|
||||
const PUBLIC_ROUTES: [&str; 16] = [
|
||||
"/healthz",
|
||||
// Stripe calls it; the signature proves it.
|
||||
"/v1/payments/stripe/webhook",
|
||||
"/v1/config",
|
||||
"/v1/packages",
|
||||
"/v1/auth/register",
|
||||
@@ -2207,3 +2254,132 @@ async fn a_new_user_from_a_shared_link_earns_an_analysis(pool: PgPool) {
|
||||
.unwrap();
|
||||
assert_eq!(count, 0);
|
||||
}
|
||||
|
||||
fn with_stripe(config: &mut Config, key: &str) {
|
||||
config.stripe = Some(crate::config::StripeConfig {
|
||||
secret_key: key.into(),
|
||||
webhook_secret: Some("whsec_fake".into()),
|
||||
api_url: config.horoscope_api_url.clone(),
|
||||
});
|
||||
}
|
||||
|
||||
async fn stripe_orders(pool: &PgPool, email: &str) -> Vec<(String, i32)> {
|
||||
sqlx::query_as(
|
||||
"SELECT o.package, o.price_huf FROM package_orders o JOIN users u ON u.id = o.user_id \
|
||||
WHERE u.email = $1 AND o.source = 'stripe' ORDER BY o.created_at",
|
||||
)
|
||||
.bind(email)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn stripe_checkout_grants_the_paid_package_once(pool: PgPool) {
|
||||
let app = TestApp::with_config(pool, |c| with_stripe(c, "sk_live_fake")).await;
|
||||
let r = app.get("/v1/config", None).await;
|
||||
assert_eq!(r.body["payments"], "stripe");
|
||||
assert_eq!(r.body["payments_test"], false);
|
||||
// Stripe replaces the stand-in payment.
|
||||
assert_eq!(r.body["mock_payments"], false);
|
||||
let anna = app.register("anna@example.com", "Anna").await;
|
||||
let r = app.post("/v1/payments/mock", Some(&anna), json!({"package": "couple"})).await;
|
||||
assert_eq!(r.status, StatusCode::NOT_FOUND);
|
||||
|
||||
let r = app.post("/v1/payments/checkout", Some(&anna), json!({"package": "nincs"})).await;
|
||||
assert_eq!(r.status, StatusCode::NOT_FOUND);
|
||||
let r = app
|
||||
.post("/v1/payments/checkout", Some(&anna), json!({"package": "couple", "return_path": "/kepletek/abc?x=1"}))
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
let url = r.body["url"].as_str().unwrap();
|
||||
let id = url.rsplit('/').next().unwrap().to_string();
|
||||
assert_eq!(stripe_form(&id, "line_items[0][price_data][currency]").as_deref(), Some("huf"));
|
||||
assert_eq!(stripe_form(&id, "line_items[0][price_data][unit_amount]").as_deref(), Some("600000"));
|
||||
assert_eq!(
|
||||
stripe_form(&id, "line_items[0][price_data][product_data][name]").as_deref(),
|
||||
Some("Sorsfonalak – Páros")
|
||||
);
|
||||
assert_eq!(stripe_form(&id, "customer_email").as_deref(), Some("anna@example.com"));
|
||||
assert_eq!(
|
||||
stripe_form(&id, "success_url").as_deref(),
|
||||
Some("https://sorsfonalak.test/kepletek/abc?fizetes={CHECKOUT_SESSION_ID}")
|
||||
);
|
||||
// Only paths of this site to come back to.
|
||||
let r = app
|
||||
.post("/v1/payments/checkout", Some(&anna), json!({"package": "single", "return_path": "//evil.example/x"}))
|
||||
.await;
|
||||
let other = r.body["url"].as_str().unwrap().rsplit('/').next().unwrap().to_string();
|
||||
assert_eq!(
|
||||
stripe_form(&other, "cancel_url").as_deref(),
|
||||
Some("https://sorsfonalak.test/csomagok?fizetes=megszakitva")
|
||||
);
|
||||
|
||||
// Not paid yet: nothing granted.
|
||||
let r = app.get(&format!("/v1/payments/checkout/{id}"), Some(&anna)).await;
|
||||
assert_eq!(r.body["status"], "pending", "{}", r.body);
|
||||
assert!(stripe_orders(&app.pool, "anna@example.com").await.is_empty());
|
||||
// Someone else's payment is not found.
|
||||
let bela = app.register("bela@example.com", "Béla").await;
|
||||
let r = app.get(&format!("/v1/payments/checkout/{id}"), Some(&bela)).await;
|
||||
assert_eq!(r.status, StatusCode::NOT_FOUND);
|
||||
|
||||
// The webhook: a bad signature is refused, a good one grants the package,
|
||||
// and Stripe's retries do not grant it again.
|
||||
let event = json!({"id": "evt_1", "type": "checkout.session.completed",
|
||||
"data": {"object": {"id": id, "payment_status": "paid"}}});
|
||||
let body = event.to_string();
|
||||
let now = time::OffsetDateTime::now_utc().unix_timestamp();
|
||||
let bad = crate::stripe::sign("whsec_other", body.as_bytes(), now);
|
||||
let r = app
|
||||
.call_with("POST", "/v1/payments/stripe/webhook", None, Some(event.clone()), &[("stripe-signature", &bad)])
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::BAD_REQUEST);
|
||||
assert!(stripe_orders(&app.pool, "anna@example.com").await.is_empty());
|
||||
let good = crate::stripe::sign("whsec_fake", body.as_bytes(), now);
|
||||
for _ in 0..2 {
|
||||
let r = app
|
||||
.call_with("POST", "/v1/payments/stripe/webhook", None, Some(event.clone()), &[("stripe-signature", &good)])
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
}
|
||||
assert_eq!(stripe_orders(&app.pool, "anna@example.com").await, vec![("couple".to_string(), 6000)]);
|
||||
let r = app.get(&format!("/v1/payments/checkout/{id}"), Some(&anna)).await;
|
||||
assert_eq!(r.body["status"], "paid");
|
||||
assert_eq!(r.body["name"], "Páros");
|
||||
let r = app.get("/v1/me", Some(&anna)).await;
|
||||
assert_eq!(r.status, StatusCode::OK);
|
||||
|
||||
// A session we did not start is ignored.
|
||||
let stray = json!({"type": "checkout.session.completed", "data": {"object": {"id": "cs_unknown", "payment_status": "paid"}}});
|
||||
let sig = crate::stripe::sign("whsec_fake", stray.to_string().as_bytes(), now);
|
||||
let r =
|
||||
app.call_with("POST", "/v1/payments/stripe/webhook", None, Some(stray), &[("stripe-signature", &sig)]).await;
|
||||
assert_eq!(r.status, StatusCode::OK);
|
||||
|
||||
// Without the webhook (late or not set up) the return page asks Stripe.
|
||||
stripe_pay(&other);
|
||||
let r = app.get(&format!("/v1/payments/checkout/{other}"), Some(&anna)).await;
|
||||
assert_eq!(r.body["status"], "paid", "{}", r.body);
|
||||
let r = app.get(&format!("/v1/payments/checkout/{other}"), Some(&anna)).await;
|
||||
assert_eq!(r.body["status"], "paid");
|
||||
assert_eq!(
|
||||
stripe_orders(&app.pool, "anna@example.com").await,
|
||||
vec![("couple".to_string(), 6000), ("single".to_string(), 2000)]
|
||||
);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn stripe_test_mode_is_for_admins_only(pool: PgPool) {
|
||||
let app = TestApp::with_config(pool, |c| with_stripe(c, "sk_test_fake")).await;
|
||||
let r = app.get("/v1/config", None).await;
|
||||
assert_eq!(r.body["payments"], "stripe");
|
||||
assert_eq!(r.body["payments_test"], true);
|
||||
let anna = app.register("anna@example.com", "Anna").await;
|
||||
let r = app.post("/v1/payments/checkout", Some(&anna), json!({"package": "single"})).await;
|
||||
assert_eq!(r.status, StatusCode::FORBIDDEN);
|
||||
// The admin gets as far as Stripe (the fake one only knows the live key).
|
||||
let admin = app.register("admin@example.com", "Admin").await;
|
||||
let r = app.post("/v1/payments/checkout", Some(&admin), json!({"package": "single"})).await;
|
||||
assert_eq!(r.body["error"]["code"], "payment_unavailable", "{}", r.body);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user