Packages paid through Stripe Checkout
CI / test (push) Successful in 1m25s
CI / build (push) Successful in 5m24s
CI / deploy (push) Skipped

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:
feco
2026-11-20 06:41:21 +00:00
co-authored by Claude Opus 5.5
parent 55101f8637
commit 42a982010d
31 changed files with 842 additions and 37 deletions
+177 -1
View File
@@ -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);
}