diff --git a/app/Cargo.lock b/app/Cargo.lock index c79c4f17..d877b816 100644 --- a/app/Cargo.lock +++ b/app/Cargo.lock @@ -817,6 +817,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer 0.10.4", "crypto-common 0.1.6", + "subtle", ] [[package]] @@ -1243,7 +1244,16 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018" dependencies = [ - "hmac", + "hmac 0.13.0", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.7", ] [[package]] @@ -1905,7 +1915,7 @@ dependencies = [ "futures-util", "getrandom 0.4.3", "hex", - "hmac", + "hmac 0.13.0", "http", "http-body", "http-body-util", @@ -2053,7 +2063,7 @@ dependencies = [ "futures-util", "getrandom 0.4.3", "hex", - "hmac", + "hmac 0.13.0", "http", "http-body", "idna", @@ -2137,7 +2147,7 @@ dependencies = [ "anyhow", "futures-util", "hex", - "hmac", + "hmac 0.13.0", "inertia-laravel-rust", "inventory", "laravel-rust-core", @@ -2190,7 +2200,7 @@ dependencies = [ "futures-util", "getrandom 0.4.3", "hex", - "hmac", + "hmac 0.13.0", "http", "http-body", "http-body-util", @@ -2293,7 +2303,7 @@ dependencies = [ "base64 0.23.1", "bytes", "futures-util", - "hmac", + "hmac 0.13.0", "inventory", "laravel-rust-core", "laravel-rust-http", @@ -3463,7 +3473,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c091b4ca9c4d51c1a959fa746cc74f5a612a2242070a4ae7b14e22b04c71f8c" dependencies = [ "base64 0.23.1", - "hmac", + "hmac 0.13.0", "instant-xml", "jiff 1.1.0", "md-5", @@ -3923,7 +3933,7 @@ dependencies = [ "futures-util", "hex", "hkdf", - "hmac", + "hmac 0.13.0", "itoa", "log", "md-5", @@ -4536,6 +4546,7 @@ dependencies = [ "axum", "globset", "hex", + "hmac 0.12.1", "image", "laravel-rust", "oauth-provider", diff --git a/app/Cargo.toml b/app/Cargo.toml index 4c410008..ed319bfd 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -29,6 +29,7 @@ axum = "0.8" hex = "0.4" oauth-provider = "0.1.3" oauth-provider-laravel = { version = "=0.1.1", features = ["postgres"] } +hmac = "0.12" serde = { version = "1", features = ["derive"] } serde_json = "1" sha2 = "0.10" diff --git a/app/src/auth/mod.rs b/app/src/auth/mod.rs index 6e1edfa9..bc882ca8 100644 --- a/app/src/auth/mod.rs +++ b/app/src/auth/mod.rs @@ -259,6 +259,7 @@ pub async fn whoami(principal: Principal) -> laravel::Result Plan { + [TEAM, STAFF].into_iter().find(|p| p.id == id).unwrap_or(FREE) +} + +/// Stripe (`STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET`). Production's keys come only from the cluster's +/// ExternalSecrets; tests fake Stripe. +#[derive(Clone, laravel::config::Section)] +pub struct Stripe { + #[env("STRIPE_SECRET_KEY")] + pub secret_key: Option, + #[env("STRIPE_WEBHOOK_SECRET")] + pub webhook_secret: Option, +} + +impl Stripe { + /// Whether the secret key is a live one (`sk_live_`, `rk_live_`); `None` without a key. + #[must_use] + pub fn live(&self) -> Option { + let key = self.secret_key.as_deref().map(str::trim).filter(|k| !k.is_empty())?; + Some(key.starts_with("sk_live_") || key.starts_with("rk_live_")) + } +} + +/// At boot: production never runs on a test key (`sk_test_`, `rk_test_`), which would take no real payments while +/// granting real plans and credits. +/// +/// # Errors +/// In production, when the Stripe key isn't a live one. +pub fn check(stripe: &Stripe, production: bool) -> laravel::Result<()> { + if production && stripe.live() == Some(false) { + return Err(laravel::Error::msg( + "STRIPE_SECRET_KEY is a test key; production needs a live one (sk_live_ or rk_live_)", + )); + } + Ok(()) +} + +/// Add purchased credits once per `reference` (a Checkout session or an invoice): `true` when added, `false` when +/// that reference was already credited. Two callers that both get here (an automatic reload and its `invoice.paid` +/// webhook) are kept apart by the `credit_transactions_purchase_once` index. +/// +/// # Errors +/// On a database error. +pub async fn add_purchased_credits(org_id: i64, credits: i64, reference: &str) -> laravel::Result { + let added = laravel::db::transaction(async |tx| { + let balance: Option = laravel::db::query!( + tx, + "UPDATE organizations SET credits_balance = credits_balance + {credits}, updated_at = now() \ + WHERE id = {org_id} RETURNING credits_balance" + ) + .scalar() + .await?; + let Some(balance) = balance else { return Ok(false) }; + let inserted: Option = laravel::db::query!( + tx, + "INSERT INTO credit_transactions (organization_id, amount, balance_after, kind, reference) \ + VALUES ({org_id}, {credits}, {balance}, 'purchase', {reference}) \ + ON CONFLICT (organization_id, reference) WHERE kind = 'purchase' DO NOTHING RETURNING id" + ) + .scalar() + .await?; + if inserted.is_none() { + // Already credited: undo this transaction's balance change + return Err(laravel::Error::msg("already credited")); + } + Ok(true) + }) + .await; + match added { + Ok(added) => Ok(added), + Err(e) if e.to_string().contains("already credited") => Ok(false), + Err(e) => Err(e), + } +} diff --git a/app/src/billing/routes.rs b/app/src/billing/routes.rs new file mode 100644 index 00000000..1120757f --- /dev/null +++ b/app/src/billing/routes.rs @@ -0,0 +1,389 @@ +//! The billing page's routes (`/api/ui/...`, the web app's session), ported from today's server: the plans, Checkout +//! for the Team plan and for credit packs, Stripe's customer portal, automatic reloads, payment methods and invoices. +//! Only an organization's admins choose the plan and pay; anyone else gets a 403 (a member) or a 404. + +use laravel::auth::Authenticated; +use laravel::db; +use laravel::prelude::*; +use serde_json::{Value, json}; + +use super::stripe::{self, Method, catalog, checkout_tax_fields, ensure_customer}; +use super::{CREDIT_PACK, FREE, MAX_AUTO_RELOAD_PACKS, STAFF, Stripe, TEAM, plan_by_id}; +use crate::models::User; +use crate::notify::outbox::AppUrl; + +/// The routes, on the `web` group. +pub fn routes(route: &mut Router) { + route.get("/api/ui/billing/plans", plans); + route.post("/api/ui/orgs/{org}/billing/checkout", checkout); + route.post("/api/ui/orgs/{org}/billing/portal", portal); + route.post("/api/ui/orgs/{org}/billing/packs", buy_packs); + route.put("/api/ui/orgs/{org}/billing/auto-reload", set_auto_reload); + route.get("/api/ui/orgs/{org}/billing/payment-methods", payment_methods); + route.post("/api/ui/orgs/{org}/billing/payment-methods/setup", add_payment_method); + route.post("/api/ui/orgs/{org}/billing/payment-methods/{id}/default", default_payment_method); + route.delete("/api/ui/orgs/{org}/billing/payment-methods/{id}", remove_payment_method); + route.get("/api/ui/orgs/{org}/billing/invoices", invoices); +} + +/// An organization as billing reads it. +struct BillingOrg { + id: i64, + slug: String, + plan: String, + customer: Option, + subscription: Option, +} + +/// The organization, when the user is one of its admins. +async fn billing_org(user: &User, slug: &str) -> laravel::Result { + let user_id = user.id; + let row = db::query!( + "SELECT o.id, o.slug, o.plan, o.stripe_customer_id, o.stripe_subscription_id, m.role \ + FROM organizations o LEFT JOIN memberships m ON m.organization_id = o.id AND m.user_id = {user_id} \ + WHERE o.slug = {slug}" + ) + .select_one() + .await? + .ok_or_else(|| laravel::abort(404))?; + match row.try_get::>("role")?.as_deref() { + Some("admin") => Ok(BillingOrg { + id: row.try_get("id")?, + slug: row.try_get("slug")?, + plan: row.try_get("plan")?, + customer: row.try_get("stripe_customer_id")?, + subscription: row.try_get("stripe_subscription_id")?, + }), + Some(_) => Err(laravel::abort_with(403, "only admins can change the plan")), + None => Err(laravel::abort(404)), + } +} + +/// Stripe's secret key, or a 400 when payments aren't set up. +fn key(stripe: &Stripe) -> laravel::Result<&str> { + stripe + .secret_key + .as_deref() + .filter(|k| !k.is_empty()) + .ok_or_else(|| laravel::abort_with(400, "payments aren't set up yet")) +} + +fn app_url(app: &AppUrl) -> String { + app.url.trim_end_matches('/').to_string() +} + +/// `GET /api/ui/billing/plans`: the plans anyone can choose, the pack, and whether payments are on. +pub async fn plans(stripe: laravel::config::Section) -> Json { + let plan = |p: super::Plan| { + json!({ "id": p.id, "name": p.name, "price_cents": p.price_cents, "included_credits": p.included_credits, + "credit_packs": p.credit_packs, "unlimited": p.unlimited }) + }; + Json(json!({ + "plans": [plan(FREE), plan(TEAM)], + "credit_pack": { "credits": CREDIT_PACK.credits, "price_cents": CREDIT_PACK.price_cents, + "reload_below": CREDIT_PACK.reload_below }, + "max_auto_reload_packs": MAX_AUTO_RELOAD_PACKS, + "stripe_enabled": stripe.secret_key.as_deref().is_some_and(|k| !k.is_empty()), + })) +} + +#[laravel::input] +#[validate(authenticated)] +pub struct CheckoutParams { + #[validate(required)] + plan: String, +} + +/// Stripe Checkout for the Team subscription (flexible billing mode, Stripe Tax). +pub async fn checkout( + Authenticated(user): Authenticated, + Params(org): Params, + stripe: laravel::config::Section, + app: laravel::config::Section, + Valid(p): Valid, +) -> laravel::Result> { + let key = key(&stripe)?; + if p.plan != TEAM.id { + return Err(laravel::abort_with(400, "the only plan to subscribe to is team")); + } + let org = billing_org(&user, &org).await?; + if org.plan == TEAM.id || org.subscription.is_some() { + return Err(laravel::abort_with(400, "this organization already has a Team subscription")); + } + if org.plan == STAFF.id { + return Err(laravel::abort_with(400, "this organization is on the Staff plan, which has no limits")); + } + let catalog = catalog(key).await?; + let customer = ensure_customer(key, org.id, &user.email).await?; + let base = format!("{}/{}/billing", app_url(&app), org.slug); + let mut form = vec![ + ("mode", "subscription".to_string()), + ("customer", customer), + ("success_url", format!("{base}?checkout=success")), + ("cancel_url", format!("{base}?checkout=cancelled")), + ("client_reference_id", org.id.to_string()), + ("line_items[0][price]", catalog.team_price.clone()), + ("line_items[0][quantity]", "1".to_string()), + ("metadata[organization_id]", org.id.to_string()), + ("subscription_data[metadata][organization_id]", org.id.to_string()), + ("subscription_data[billing_mode][type]", "flexible".to_string()), + ]; + form.extend(checkout_tax_fields()); + let body = stripe::post(key, "checkout/sessions", &form).await?; + Ok(Json(json!({ "url": body["url"] }))) +} + +#[laravel::input] +#[validate(authenticated)] +pub struct PackParams { + /// One unless it says otherwise + packs: Option, +} + +/// Stripe Checkout for credit packs (a one-off payment with an invoice and Stripe Tax), on Team. +pub async fn buy_packs( + Authenticated(user): Authenticated, + Params(org): Params, + stripe: laravel::config::Section, + app: laravel::config::Section, + Valid(p): Valid, +) -> laravel::Result> { + let key = key(&stripe)?; + let packs = p.packs.unwrap_or(1); + if !(1..=20).contains(&packs) { + return Err(laravel::abort_with(400, "buy between 1 and 20 packs at a time")); + } + let org = billing_org(&user, &org).await?; + let Some(customer) = org.customer.clone().filter(|_| plan_by_id(&org.plan).credit_packs) else { + return Err(laravel::abort_with(400, "credit packs come with the Team plan")); + }; + let catalog = catalog(key).await?; + let base = format!("{}/{}/billing", app_url(&app), org.slug); + let mut form = vec![ + ("mode", "payment".to_string()), + ("customer", customer), + ("success_url", format!("{base}?packs=success")), + ("cancel_url", format!("{base}?packs=cancelled")), + ("client_reference_id", org.id.to_string()), + ("line_items[0][price]", catalog.pack_price.clone()), + ("line_items[0][quantity]", packs.to_string()), + ("invoice_creation[enabled]", "true".to_string()), + ("metadata[organization_id]", org.id.to_string()), + ("metadata[kind]", "credit_pack".to_string()), + ("metadata[packs]", packs.to_string()), + ]; + form.extend(checkout_tax_fields()); + let body = stripe::post(key, "checkout/sessions", &form).await?; + Ok(Json(json!({ "url": body["url"] }))) +} + +#[laravel::input] +#[validate(authenticated)] +pub struct AutoReloadParams { + #[validate(required)] + packs: i32, +} + +/// How many packs automatic reloads may buy in a month (0 turns them off). Setting it also resumes reloads a failed +/// payment paused: the owner says the card is fixed. +pub async fn set_auto_reload( + Authenticated(user): Authenticated, + Params(org): Params, + Valid(p): Valid, +) -> laravel::Result> { + if !(0..=MAX_AUTO_RELOAD_PACKS).contains(&p.packs) { + return Err(laravel::abort_with( + 400, + format!("automatic reloads can buy 0 to {MAX_AUTO_RELOAD_PACKS} packs a month"), + )); + } + let org = billing_org(&user, &org).await?; + let (id, packs) = (org.id, p.packs); + db::query!( + "UPDATE organizations SET auto_reload_packs = {packs}, reloads_paused_at = NULL, billing_problem = NULL, \ + updated_at = now() WHERE id = {id}" + ) + .update() + .await?; + Ok(Json(json!({ "auto_reload_packs": packs }))) +} + +/// Stripe's customer portal: change the card, name, address and tax ID, see invoices, cancel at the end of the period. +pub async fn portal( + Authenticated(user): Authenticated, + Params(org): Params, + stripe: laravel::config::Section, + app: laravel::config::Section, +) -> laravel::Result> { + let key = key(&stripe)?; + let org = billing_org(&user, &org).await?; + let Some(customer) = org.customer.clone() else { + return Err(laravel::abort_with(400, "this organization has no subscription")); + }; + let catalog = catalog(key).await?; + let form = [ + ("customer", customer), + ("configuration", catalog.portal_configuration.clone()), + ("return_url", format!("{}/{}/billing", app_url(&app), org.slug)), + ]; + let body = stripe::post(key, "billing_portal/sessions", &form).await?; + Ok(Json(json!({ "url": body["url"] }))) +} + +/// The customer's default payment method (its ID), as invoices use it. +async fn default_method(key: &str, customer: &str) -> laravel::Result> { + let c = stripe::get(key, &format!("customers/{customer}"), &[]).await?; + let d = &c["invoice_settings"]["default_payment_method"]; + Ok(d.as_str().map(str::to_string).or_else(|| d["id"].as_str().map(str::to_string))) +} + +/// A payment method, checked to be this customer's before anything is done with it. +async fn own_method(key: &str, customer: &str, id: &str) -> laravel::Result { + let prefixed = id.starts_with("pm_") || id.starts_with("card_") || id.starts_with("src_"); + // It goes into a Stripe API path: letters, digits and underscores only. + if !prefixed || id.len() > 255 || !id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') { + return Err(laravel::abort(404)); + } + let pm = stripe::get(key, &format!("payment_methods/{id}"), &[]).await.map_err(|_| laravel::abort(404))?; + if pm["customer"].as_str() != Some(customer) { + return Err(laravel::abort(404)); + } + Ok(pm) +} + +/// The organization's saved payment methods: cards (brand, last 4, expiry) and others by type, the default marked. +/// A first card (just added in Checkout's setup mode) becomes the default. +pub async fn payment_methods( + Authenticated(user): Authenticated, + Params(org): Params, + stripe: laravel::config::Section, +) -> laravel::Result> { + let key = key(&stripe)?; + let org = billing_org(&user, &org).await?; + let Some(customer) = org.customer else { return Ok(Json(json!({ "methods": [] }))) }; + let mut default = default_method(key, &customer).await?; + let list = stripe::get(key, &format!("customers/{customer}/payment_methods"), &[("limit", "100".into())]).await?; + if default.is_none() + && let Some(newest) = list["data"][0]["id"].as_str() + { + stripe::post( + key, + &format!("customers/{customer}"), + &[("invoice_settings[default_payment_method]", newest.to_string())], + ) + .await?; + default = Some(newest.to_string()); + } + let methods: Vec = list["data"] + .as_array() + .into_iter() + .flatten() + .map(|m| { + let kind = m["type"].as_str().unwrap_or(""); + let card = &m["card"]; + json!({ + "id": m["id"], "type": kind, "brand": card["brand"], + "last4": card["last4"].as_str().or_else(|| m[kind]["last4"].as_str()), + "exp_month": card["exp_month"], "exp_year": card["exp_year"], + "default": m["id"].as_str() == default.as_deref(), + }) + }) + .collect(); + Ok(Json(json!({ "methods": methods }))) +} + +/// "Add payment method": Stripe Checkout in setup mode, back to the Payment methods tab. +pub async fn add_payment_method( + Authenticated(user): Authenticated, + Params(org): Params, + stripe: laravel::config::Section, + app: laravel::config::Section, +) -> laravel::Result> { + let key = key(&stripe)?; + let org = billing_org(&user, &org).await?; + let customer = ensure_customer(key, org.id, &user.email).await?; + let back = format!("{}/{}/billing/payment-methods", app_url(&app), org.slug); + let form = [ + ("mode", "setup".to_string()), + ("customer", customer), + ("currency", "usd".to_string()), + ("success_url", format!("{back}?added=1")), + ("cancel_url", back), + ("metadata[organization_id]", org.id.to_string()), + ]; + let session = stripe::post(key, "checkout/sessions", &form).await?; + Ok(Json(json!({ "url": session["url"] }))) +} + +/// "Make default": invoices and automatic reloads charge it from now on, and the subscription too. +pub async fn default_payment_method( + Authenticated(user): Authenticated, + Params((org, id)): Params<(String, String)>, + stripe: laravel::config::Section, +) -> laravel::Result> { + let key = key(&stripe)?; + let org = billing_org(&user, &org).await?; + let customer = org.customer.ok_or_else(|| laravel::abort(404))?; + own_method(key, &customer, &id).await?; + stripe::post(key, &format!("customers/{customer}"), &[("invoice_settings[default_payment_method]", id.clone())]) + .await?; + if let Some(sub) = &org.subscription { + stripe::post(key, &format!("subscriptions/{sub}"), &[("default_payment_method", id)]).await?; + } + Ok(Json(json!({ "ok": true }))) +} + +/// "Remove": detach a payment method. The default can't go while the Team plan needs it. +pub async fn remove_payment_method( + Authenticated(user): Authenticated, + Params((org, id)): Params<(String, String)>, + stripe: laravel::config::Section, +) -> laravel::Result> { + let key = key(&stripe)?; + let org = billing_org(&user, &org).await?; + let customer = org.customer.ok_or_else(|| laravel::abort(404))?; + own_method(key, &customer, &id).await?; + if org.subscription.is_some() && default_method(key, &customer).await?.as_deref() == Some(id.as_str()) { + return Err(laravel::abort_with(400, "make another card the default first: the Team plan charges this one")); + } + stripe::request(key, Method::Post, &format!("payment_methods/{id}/detach"), &[], None).await?; + Ok(Json(json!({ "ok": true }))) +} + +#[laravel::query] +pub struct InvoicesQuery { + /// Stripe's cursor: the last invoice ID of the previous page. + after: Option, +} + +/// The organization's Stripe invoices, newest first, 20 at a time, with their PDFs and hosted pages. +pub async fn invoices( + Authenticated(user): Authenticated, + Params(org): Params, + stripe: laravel::config::Section, + Query(q): Query, +) -> laravel::Result> { + let key = key(&stripe)?; + let org = billing_org(&user, &org).await?; + let Some(customer) = org.customer else { return Ok(Json(json!({ "invoices": [], "has_more": false }))) }; + let mut query = vec![("customer", customer), ("limit", "20".to_string())]; + if let Some(after) = q.after.filter(|a| a.starts_with("in_")) { + query.push(("starting_after", after)); + } + let list = stripe::get(key, "invoices", &query).await?; + let invoices: Vec = list["data"] + .as_array() + .into_iter() + .flatten() + .filter(|i| i["status"].as_str() != Some("draft")) + .map(|i| { + let description = i["lines"]["data"][0]["description"].as_str().or_else(|| i["description"].as_str()); + json!({ + "id": i["id"], "number": i["number"], "created": i["created"], "description": description, + "total": i["total"], "currency": i["currency"], "status": i["status"], + "pdf": i["invoice_pdf"], "url": i["hosted_invoice_url"], + }) + }) + .collect(); + Ok(Json(json!({ "invoices": invoices, "has_more": list["has_more"] }))) +} diff --git a/app/src/billing/stripe.rs b/app/src/billing/stripe.rs new file mode 100644 index 00000000..e18d2e05 --- /dev/null +++ b/app/src/billing/stripe.rs @@ -0,0 +1,224 @@ +//! Stripe's API, and the catalog billing uses, ported from today's server. Everything is a Stripe Product and Price, +//! created on first use: the products have fixed IDs, prices are found by lookup key (a changed amount gets a new +//! price, which takes the key), and the customer portal configuration is the one marked `metadata[visualci]`. Stripe +//! Tax is on everywhere, with billing addresses and tax IDs collected. + +use laravel::db; +use laravel::http::client; +use serde_json::Value; +use tokio::sync::OnceCell; + +use super::{CREDIT_PACK, TEAM}; + +/// Product tax code: Software as a service (SaaS), business use. +const TAX_CODE: &str = "txcd_10103001"; +const TEAM_PRODUCT: &str = "visualci_team"; +const PACK_PRODUCT: &str = "visualci_credit_pack"; +const TEAM_PRICE: &str = "visualci_team_monthly"; +const PACK_PRICE: &str = "visualci_credit_pack"; +/// Marks the customer portal configuration this code manages. +const PORTAL_MARKER: &str = "visualci"; + +/// A Stripe API call: GET with a query, POST with a form, or DELETE. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Method { + Get, + Post, + Delete, +} + +/// Call Stripe's API. `idempotency_key` makes a retried request return the first result instead of acting again. +/// +/// # Errors +/// When Stripe can't be reached or refuses the request. +pub async fn request( + key: &str, + method: Method, + path: &str, + form: &[(&str, String)], + idempotency_key: Option<&str>, +) -> laravel::Result { + let url = format!("https://api.stripe.com/v1/{path}"); + let pending = match method { + Method::Get => client::get(url).query(form), + Method::Post => client::post(url).form(form), + Method::Delete => client::delete(url), + }; + let mut pending = pending.basic_auth(key, "").accept_json(); + if let Some(k) = idempotency_key { + pending = pending.header("Idempotency-Key", k); + } + let response = pending.await?; + let body: Value = response.json().unwrap_or_default(); + if !response.successful() { + return Err(laravel::Error::msg(format!("Stripe: HTTP {}: {}", response.status(), body["error"]["message"]))); + } + Ok(body) +} + +/// # Errors +/// When Stripe can't be reached or refuses the request. +pub async fn post(key: &str, path: &str, form: &[(&str, String)]) -> laravel::Result { + request(key, Method::Post, path, form, None).await +} + +/// # Errors +/// When Stripe can't be reached or refuses the request. +pub async fn get(key: &str, path: &str, query: &[(&str, String)]) -> laravel::Result { + request(key, Method::Get, path, query, None).await +} + +/// The Stripe objects billing uses, by ID. +#[derive(Clone, Debug)] +pub struct Catalog { + pub team_price: String, + pub pack_price: String, + pub portal_configuration: String, +} + +static CATALOG: OnceCell = OnceCell::const_new(); + +/// The catalog, created in Stripe the first time it's needed in this process. +/// +/// # Errors +/// When Stripe can't be reached or refuses a request. +pub async fn catalog(key: &str) -> laravel::Result<&'static Catalog> { + CATALOG.get_or_try_init(|| ensure_catalog(key)).await +} + +/// Creates or updates the products, prices and portal configuration. Safe to run any number of times. +/// +/// # Errors +/// When Stripe can't be reached or refuses a request. +pub async fn ensure_catalog(key: &str) -> laravel::Result { + ensure_product(key, TEAM_PRODUCT, "VisualCI Team").await?; + ensure_product(key, PACK_PRODUCT, &format!("VisualCI credit pack: {} credits", CREDIT_PACK.credits)).await?; + let team_price = ensure_price(key, TEAM_PRICE, TEAM_PRODUCT, TEAM.price_cents, true).await?; + let pack_price = ensure_price(key, PACK_PRICE, PACK_PRODUCT, CREDIT_PACK.price_cents, false).await?; + let portal_configuration = ensure_portal(key, &team_price).await?; + tracing::info!(team_price, pack_price, portal_configuration, "Stripe catalog ready"); + Ok(Catalog { team_price, pack_price, portal_configuration }) +} + +async fn ensure_product(key: &str, id: &str, name: &str) -> laravel::Result<()> { + let form = [("name", name.to_string()), ("tax_code", TAX_CODE.to_string())]; + if get(key, &format!("products/{id}"), &[]).await.is_ok() { + post(key, &format!("products/{id}"), &form).await?; + } else { + let mut create = vec![("id", id.to_string())]; + create.extend(form); + post(key, "products", &create).await?; + } + Ok(()) +} + +async fn ensure_price( + key: &str, + lookup_key: &str, + product: &str, + cents: i64, + monthly: bool, +) -> laravel::Result { + let found = get(key, "prices", &[("lookup_keys[]", lookup_key.to_string()), ("active", "true".into())]).await?; + if let Some(price) = found["data"].as_array().and_then(|d| d.first()) { + let same = price["unit_amount"].as_i64() == Some(cents) + && price["product"].as_str() == Some(product) + && price["recurring"].is_object() == monthly; + if same && let Some(id) = price["id"].as_str() { + return Ok(id.to_string()); + } + } + let mut form = vec![ + ("product", product.to_string()), + ("currency", "usd".to_string()), + ("unit_amount", cents.to_string()), + ("tax_behavior", "exclusive".to_string()), + ("lookup_key", lookup_key.to_string()), + ("transfer_lookup_key", "true".to_string()), + ]; + if monthly { + form.push(("recurring[interval]", "month".to_string())); + } + let price = post(key, "prices", &form).await?; + price["id"].as_str().map(str::to_string).ok_or_else(|| laravel::Error::msg("Stripe: a price without an id")) +} + +/// The customer portal: update the card, name, address and tax ID, see invoices, and cancel at the end of the period. +async fn ensure_portal(key: &str, team_price: &str) -> laravel::Result { + let form = vec![ + ("business_profile[headline]", "VisualCI billing".to_string()), + ("features[customer_update][enabled]", "true".to_string()), + ("features[customer_update][allowed_updates][]", "email".to_string()), + ("features[customer_update][allowed_updates][]", "name".to_string()), + ("features[customer_update][allowed_updates][]", "address".to_string()), + ("features[customer_update][allowed_updates][]", "tax_id".to_string()), + ("features[invoice_history][enabled]", "true".to_string()), + ("features[payment_method_update][enabled]", "true".to_string()), + ("features[subscription_cancel][enabled]", "true".to_string()), + ("features[subscription_cancel][mode]", "at_period_end".to_string()), + ("features[subscription_update][enabled]", "true".to_string()), + ("features[subscription_update][default_allowed_updates][]", "price".to_string()), + ("features[subscription_update][products][0][product]", TEAM_PRODUCT.to_string()), + ("features[subscription_update][products][0][prices][]", team_price.to_string()), + ("features[subscription_update][proration_behavior]", "create_prorations".to_string()), + ("metadata[visualci]", "billing".to_string()), + ]; + let existing = + get(key, "billing_portal/configurations", &[("active", "true".into()), ("limit", "100".into())]).await?; + let ours = existing["data"] + .as_array() + .and_then(|d| d.iter().find(|c| c["metadata"][PORTAL_MARKER].is_string())) + .and_then(|c| c["id"].as_str().map(str::to_string)); + let config = match ours { + Some(id) => post(key, &format!("billing_portal/configurations/{id}"), &form).await?, + None => post(key, "billing_portal/configurations", &form).await?, + }; + config["id"] + .as_str() + .map(str::to_string) + .ok_or_else(|| laravel::Error::msg("Stripe: a portal configuration without an id")) +} + +/// The organization's Stripe customer, created (named after the organization, billed to `email`) the first time it +/// pays for anything. +/// +/// # Errors +/// On a database error, or when Stripe can't be reached. +pub async fn ensure_customer(key: &str, org_id: i64, email: &str) -> laravel::Result { + let row = db::query!("SELECT name, slug, stripe_customer_id FROM organizations WHERE id = {org_id}") + .select_one() + .await? + .ok_or_else(|| laravel::abort(404))?; + if let Some(id) = row.try_get::>("stripe_customer_id")? { + return Ok(id); + } + let (name, slug): (String, String) = (row.try_get("name")?, row.try_get("slug")?); + let form = [ + ("name", name), + ("email", email.to_string()), + ("metadata[organization_id]", org_id.to_string()), + ("metadata[organization]", slug), + ]; + let idempotency = format!("visualci-customer-{org_id}"); + let customer = request(key, Method::Post, "customers", &form, Some(&idempotency)).await?; + let id = customer["id"] + .as_str() + .map(str::to_string) + .ok_or_else(|| laravel::Error::msg("Stripe: a customer without an id"))?; + db::query!("UPDATE organizations SET stripe_customer_id = {id}, updated_at = now() WHERE id = {org_id}") + .update() + .await?; + Ok(id) +} + +/// What every Checkout session sends for tax: Stripe Tax, the billing address, tax IDs, and both saved on the customer. +#[must_use] +pub fn checkout_tax_fields() -> Vec<(&'static str, String)> { + vec![ + ("automatic_tax[enabled]", "true".to_string()), + ("billing_address_collection", "required".to_string()), + ("tax_id_collection[enabled]", "true".to_string()), + ("customer_update[address]", "auto".to_string()), + ("customer_update[name]", "auto".to_string()), + ] +} diff --git a/app/src/billing/webhook.rs b/app/src/billing/webhook.rs new file mode 100644 index 00000000..93fa2ef5 --- /dev/null +++ b/app/src/billing/webhook.rs @@ -0,0 +1,279 @@ +//! Stripe's webhook (`POST /webhooks/stripe`), ported from today's server. Every event is safe to receive twice. +//! +//! - `checkout.session.completed`: a subscription moves the organization to Team; a paid pack adds its credits. +//! - `customer.subscription.updated`: active keeps it on Team; past due or unpaid shows a billing problem. +//! - `customer.subscription.deleted`: back to Free. +//! - `invoice.paid`: an automatic reload's credits (if the reload itself didn't record them), and any billing problem +//! is over. +//! - `invoice.payment_failed`: shows the problem and pauses automatic reloads. +//! +//! Subscription events apply only to the organization's own subscription, and only when newer than the last one +//! applied: Stripe sends events in any order and retries them for days. + +use hmac::{Hmac, Mac}; +use laravel::db; +use laravel::prelude::*; +use serde_json::{Value, json}; +use sha2::Sha256; + +use super::{CREDIT_PACK, FREE, Stripe, TEAM, add_purchased_credits, plan_by_id}; +use crate::notify::{self, Kind, To}; + +/// `POST /webhooks/stripe`. +pub async fn handle( + stripe: laravel::config::Section, + headers: axum::http::HeaderMap, + body: axum::body::Bytes, +) -> laravel::Result> { + let Some(secret) = stripe.webhook_secret.as_deref().filter(|s| !s.is_empty()) else { + return Err(laravel::abort(404)); + }; + let signature = headers.get("stripe-signature").and_then(|v| v.to_str().ok()).unwrap_or_default(); + if !verify_signature(secret, signature, &body, laravel::now().timestamp().as_second()) { + return Err(laravel::abort_with(401, "bad signature")); + } + let event: Value = serde_json::from_slice(&body).map_err(|e| laravel::abort_with(400, e.to_string()))?; + // A test-mode event never changes a live account's plans or credits, nor a live event a test one's. + if let Some(live) = stripe.live() + && event["livemode"].as_bool() != Some(live) + { + return Err(laravel::abort_with(400, "the event's livemode doesn't match the Stripe key")); + } + let object = &event["data"]["object"]; + let text = |v: &Value| v.as_str().map(str::to_string); + let kind = event["type"].as_str().unwrap_or_default(); + let Some(org_id) = org_for(object).await? else { + return Ok(Json(json!({ "ignored": "not a VisualCI organization's" }))); + }; + let created = event["created"].as_i64().unwrap_or_default(); + match kind { + "checkout.session.completed" if object["mode"] == "subscription" => { + let subscription = text(&object["subscription"]); + match which_subscription(org_id, subscription.as_deref()).await? { + // A second checkout finished while the first is active (two tabs): keep the first, and say so + Which::Other => { + record_payment_problem(org_id, TWO_SUBSCRIPTIONS).await?; + } + Which::Current => { + let change = Change::Plan { plan: TEAM.id, customer: text(&object["customer"]), subscription }; + subscription_event(org_id, created, change).await?; + } + } + } + "checkout.session.completed" if object["mode"] == "payment" && object["metadata"]["kind"] == "credit_pack" => { + let packs: i64 = object["metadata"]["packs"].as_str().and_then(|s| s.parse().ok()).unwrap_or(0); + if packs == 0 { + return Err(laravel::abort_with(400, "session without VisualCI metadata")); + } + if object["payment_status"] != "paid" { + return Ok(Json(json!({ "ignored": "not paid" }))); + } + let reference = format!("packs: {}", object["id"].as_str().unwrap_or_default()); + add_purchased_credits(org_id, packs * CREDIT_PACK.credits, &reference).await?; + } + "customer.subscription.updated" | "customer.subscription.deleted" + if matches!(which_subscription(org_id, object["id"].as_str()).await?, Which::Other) => + { + return Ok(Json(json!({ "ignored": "another subscription" }))); + } + "customer.subscription.updated" => { + let change = match object["status"].as_str().unwrap_or_default() { + "active" | "trialing" => Change::Plan { + plan: TEAM.id, + customer: text(&object["customer"]), + subscription: text(&object["id"]), + }, + "past_due" | "unpaid" => Change::Problem(PAYMENT_FAILED), + _ => Change::Nothing, + }; + if !subscription_event(org_id, created, change).await? { + return Ok(Json(json!({ "ignored": "an older event" }))); + } + } + "customer.subscription.deleted" => { + let change = Change::Plan { plan: FREE.id, customer: None, subscription: None }; + if !subscription_event(org_id, created, change).await? { + return Ok(Json(json!({ "ignored": "an older event" }))); + } + } + "invoice.paid" => { + if object["metadata"]["kind"] == "auto_reload" + && let Some(invoice) = object["id"].as_str() + { + add_purchased_credits(org_id, CREDIT_PACK.credits, &format!("auto-reload: {invoice}")).await?; + } + // A paid invoice settles a payment problem, not a second subscription. + db::query!( + "UPDATE organizations SET billing_problem = NULL, updated_at = now() \ + WHERE id = {org_id} AND billing_problem IS DISTINCT FROM {TWO_SUBSCRIPTIONS}" + ) + .update() + .await?; + } + "invoice.payment_failed" => { + let number = object["number"].as_str().unwrap_or("an invoice"); + // Stripe emails the failed payment itself; a declined automatic pack has its own email (the reload) + record_payment_problem( + org_id, + &format!("Payment for {number} failed. Update the card in Manage billing, then turn reloads back on."), + ) + .await?; + } + _ => return Ok(Json(json!({ "ignored": true }))), + } + Ok(Json(json!({ "ok": true }))) +} + +/// The organization a Stripe object belongs to: its `metadata[organization_id]`, else its customer's organization. +async fn org_for(object: &Value) -> laravel::Result> { + if let Some(id) = object["metadata"]["organization_id"].as_str().and_then(|s| s.parse::().ok()) { + let exists: Option = db::query!("SELECT id FROM organizations WHERE id = {id}").scalar().await?; + return Ok(exists); + } + let customer = object["customer"].as_str().or_else(|| object["customer"]["id"].as_str()); + let Some(customer) = customer else { return Ok(None) }; + db::query!("SELECT id FROM organizations WHERE stripe_customer_id = {customer}").scalar().await +} + +const TWO_SUBSCRIPTIONS: &str = "This organization has two Team subscriptions. Cancel one in Manage billing."; +const PAYMENT_FAILED: &str = "The Team subscription's last payment failed. Update the card in Manage billing."; + +/// What a subscription event does. +enum Change { + /// Move to a plan, with the Stripe customer and subscription. + Plan { + plan: &'static str, + customer: Option, + subscription: Option, + }, + /// Show a billing problem and pause automatic reloads. + Problem(&'static str), + Nothing, +} + +/// Apply a subscription event created at `created` (Unix seconds) when it's newer than the last one applied: an older +/// one would undo a newer state (a late "active" after a cancellation). The check and the change happen in one +/// transaction with the organization's row locked, so two deliveries handled at once can't interleave. `false` when +/// it was older. A plan change emails the billing contact afterwards. +async fn subscription_event(org_id: i64, created: i64, change: Change) -> laravel::Result { + let changed = db::transaction(async |tx| { + let Some(row) = db::query!( + tx, + "SELECT plan, (stripe_event_at IS NULL OR stripe_event_at <= to_timestamp({created})) AS fresh \ + FROM organizations WHERE id = {org_id} FOR UPDATE" + ) + .select_one() + .await? + else { + return Ok(None); + }; + if !row.try_get::("fresh")? { + return Ok(None); + } + let before: String = row.try_get("plan")?; + db::query!(tx, "UPDATE organizations SET stripe_event_at = to_timestamp({created}) WHERE id = {org_id}") + .update() + .await?; + match &change { + Change::Plan { plan, customer, subscription } => { + let plan: &str = plan; + db::query!( + tx, + "UPDATE organizations SET plan = {plan}, \ + stripe_customer_id = COALESCE({customer}, stripe_customer_id), \ + stripe_subscription_id = {subscription}, updated_at = now() WHERE id = {org_id}" + ) + .update() + .await?; + } + Change::Problem(message) => { + let message: &str = message; + db::query!( + tx, + "UPDATE organizations SET billing_problem = {message}, reloads_paused_at = now(), \ + updated_at = now() WHERE id = {org_id}" + ) + .update() + .await?; + } + Change::Nothing => {} + } + Ok(Some(before)) + }) + .await?; + let Some(before) = changed else { return Ok(false) }; + match change { + Change::Plan { plan, .. } => { + tracing::info!(org_id, plan, "plan changed"); + if before != plan { + let kind = Kind::PlanChanged { + from: plan_by_id(&before).name.to_string(), + to: plan_by_id(plan).name.to_string(), + }; + notify::queue(&kind, To::Billing(org_id), None, &format!("plan_changed:{org_id}:{plan}:{created}")) + .await?; + } + } + Change::Problem(message) => tracing::warn!(org_id, message, "billing problem"), + Change::Nothing => {} + } + Ok(true) +} + +/// What an event about subscription `id` may do: `Current` when it's the organization's subscription (or it has +/// none), `Other` when the organization pays through another one. +enum Which { + Current, + Other, +} + +async fn which_subscription(org_id: i64, id: Option<&str>) -> laravel::Result { + let current: Option = db::query!("SELECT stripe_subscription_id FROM organizations WHERE id = {org_id}") + .scalar::>() + .await? + .flatten(); + Ok(match current { + Some(current) if Some(current.as_str()) != id => Which::Other, + _ => Which::Current, + }) +} + +/// Show a billing problem on the organization's pages, and pause automatic reloads. +/// +/// # Errors +/// On a database error. +pub async fn record_payment_problem(org_id: i64, message: &str) -> laravel::Result<()> { + db::query!( + "UPDATE organizations SET billing_problem = {message}, reloads_paused_at = now(), updated_at = now() \ + WHERE id = {org_id}" + ) + .update() + .await?; + tracing::warn!(org_id, message, "billing problem"); + Ok(()) +} + +/// Stripe's `t=,v1=` signature, within five minutes of `now`, compared in constant time. +#[must_use] +pub fn verify_signature(secret: &str, header: &str, payload: &[u8], now: i64) -> bool { + let mut timestamp = None; + let mut signatures = Vec::new(); + for part in header.split(',') { + match part.split_once('=') { + Some(("t", t)) => timestamp = t.parse::().ok(), + Some(("v1", s)) => signatures.push(s.to_string()), + _ => {} + } + } + let Some(t) = timestamp else { return false }; + if (now - t).abs() > 300 { + return false; + } + let Ok(mut mac) = Hmac::::new_from_slice(secret.as_bytes()) else { return false }; + mac.update(format!("{t}.").as_bytes()); + mac.update(payload); + let expected = hex::encode(mac.finalize().into_bytes()); + signatures + .iter() + .any(|s| s.len() == expected.len() && s.bytes().zip(expected.bytes()).fold(0u8, |a, (x, y)| a | (x ^ y)) == 0) +} diff --git a/app/src/lib.rs b/app/src/lib.rs index 698a7a31..6cbdcc4c 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -40,6 +40,7 @@ pub fn configure() -> ApplicationBuilder { config.app.env.is_production(), )?; http::hosts::check(config.section::(), config.app.env.is_production())?; + billing::check(config.section::(), config.app.env.is_production())?; Ok(()) }) .with_middleware(|middleware, _| { @@ -52,6 +53,12 @@ pub fn configure() -> ApplicationBuilder { middleware.trust_hosts(["*"]); }) .with_routing(|routing, _| { - routing.web(auth::routes).api(http::api::routes).health("/up"); + routing + .web(auth::routes) + .api(http::api::routes) + .routes(|route| { + route.post("/webhooks/stripe", billing::webhook::handle); + }) + .health("/up"); }) } diff --git a/app/tests/billing.rs b/app/tests/billing.rs new file mode 100644 index 00000000..634dc799 --- /dev/null +++ b/app/tests/billing.rs @@ -0,0 +1,207 @@ +//! Stripe's webhook: signed events only; a subscription moves the organization to Team and back; a paid pack is +//! credited once; an older subscription event never undoes a newer one. + +use app::billing::webhook::verify_signature; +use app::models::User; +use hmac::{Hmac, Mac}; +use laravel::db; +use laravel::http::client; +use laravel::model::create; +use laravel::testing::TestResponse; +use laravel::testing::prelude::*; +use sha2::Sha256; + +const SECRET: &str = "whsec_test"; + +fn stripe() -> Application { + app::testing::configure().with_env("STRIPE_WEBHOOK_SECRET", SECRET).create() +} + +fn signed(body: &str, t: i64) -> String { + let mut mac = Hmac::::new_from_slice(SECRET.as_bytes()).unwrap(); + mac.update(format!("{t}.{body}").as_bytes()); + format!("t={t},v1={}", hex::encode(mac.finalize().into_bytes())) +} + +async fn org() -> laravel::Result { + Ok(db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) \ + VALUES (gen_random_uuid(), 'acme', 'Acme', now(), now()) RETURNING id" + ) + .scalar() + .await? + .expect("an id")) +} + +async fn post(app: &Application, event: serde_json::Value) -> TestResponse { + let body = event.to_string(); + let now = laravel::now().timestamp().as_second(); + app.post("/webhooks/stripe") + .header("stripe-signature", signed(&body, now)) + .header("content-type", "application/json") + .body(body) + .await +} + +#[test] +fn signatures_are_checked_with_their_time() { + let sig = signed("{}", 1_000); + assert!(verify_signature(SECRET, &sig, b"{}", 1_100)); + assert!(!verify_signature(SECRET, &sig, b"{}", 1_000 + 301), "too old"); + assert!(!verify_signature(SECRET, &sig, b"{ }", 1_100), "another body"); + assert!(!verify_signature("whsec_other", &sig, b"{}", 1_100)); +} + +#[laravel::test(app = stripe)] +async fn an_unsigned_event_is_refused(app: Application) { + app.post("/webhooks/stripe").header("stripe-signature", "t=1,v1=00").body("{}").await.assert_status(401); +} + +#[laravel::test(app = stripe)] +async fn subscriptions_move_the_plan_and_older_events_change_nothing(app: Application) -> laravel::Result<()> { + let org = org().await?; + let meta = json!({ "organization_id": org.to_string() }); + post( + &app, + json!({ "type": "checkout.session.completed", "created": 100, "data": { "object": { + "mode": "subscription", "subscription": "sub_1", "customer": "cus_1", "metadata": meta } } }), + ) + .await + .assert_ok(); + let plan = || async { db::query!("SELECT plan FROM organizations WHERE id = {org}").scalar::().await }; + assert_eq!(plan().await?.as_deref(), Some("team")); + post( + &app, + json!({ "type": "customer.subscription.deleted", "created": 300, "data": { "object": { + "id": "sub_1", "customer": "cus_1" } } }), + ) + .await + .assert_ok(); + assert_eq!(plan().await?.as_deref(), Some("free")); + // A late "active" from before the cancellation changes nothing + post( + &app, + json!({ "type": "customer.subscription.updated", "created": 200, "data": { "object": { + "id": "sub_1", "customer": "cus_1", "status": "active" } } }), + ) + .await + .assert_ok() + .assert_json_path("ignored", "an older event"); + assert_eq!(plan().await?.as_deref(), Some("free")); + Ok(()) +} + +#[laravel::test(app = stripe)] +async fn a_paid_pack_is_credited_once(app: Application) -> laravel::Result<()> { + let org = org().await?; + let event = json!({ "type": "checkout.session.completed", "created": 100, "data": { "object": { + "id": "cs_1", "mode": "payment", "payment_status": "paid", + "metadata": { "organization_id": org.to_string(), "kind": "credit_pack", "packs": "2" } } } }); + post(&app, event.clone()).await.assert_ok(); + post(&app, event).await.assert_ok(); + let balance: Option = + db::query!("SELECT credits_balance FROM organizations WHERE id = {org}").scalar().await?; + assert_eq!(balance, Some(2 * app::billing::CREDIT_PACK.credits), "Stripe's retry adds nothing"); + Ok(()) +} + +fn with_stripe_key() -> Application { + app::testing::configure() + .with_envs([("STRIPE_SECRET_KEY", "sk_test_x"), ("VISUALCI_APP_URL", "https://app.visualci.test")]) + .create() +} + +async fn member(org: i64, email: &str, role: &str) -> laravel::Result { + let user = create!(User { pid: laravel::str::uuid7(), name: "Someone", email: email, staff: false }).await?; + let id = user.id; + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org}, {id}, {role}, 'created', now(), now())" + ) + .insert() + .await?; + Ok(user) +} + +#[laravel::test(app = with_stripe_key)] +async fn only_admins_check_out_and_get_a_stripe_url(app: Application) -> laravel::Result<()> { + let org = org().await?; + let admin = member(org, "admin@example.com", "admin").await?; + let reader = member(org, "reader@example.com", "member").await?; + let outsider = + create!(User { pid: laravel::str::uuid7(), name: "Out", email: "out@example.com", staff: false }).await?; + // Every Stripe call answers with an object that has an ID, a URL and an empty list + let _stripe = client::fake() + .with("api.stripe.com/*", json!({ "id": "cs_1", "url": "https://checkout.stripe.test/cs_1", "data": [] })); + app.get("/api/ui/billing/plans").await.assert_ok().assert_json_path("stripe_enabled", true); + let checkout = |user: &User| { + app.post("/api/ui/orgs/acme/billing/checkout") + .acting_as(user) + .header("sec-fetch-site", "same-origin") + .json(json!({ "plan": "team" })) + }; + checkout(&outsider).await.assert_status(404); + checkout(&reader).await.assert_status(403); + checkout(&admin).await.assert_ok().assert_json_path("url", "https://checkout.stripe.test/cs_1"); + let customer: Option = db::query!("SELECT stripe_customer_id FROM organizations WHERE id = {org}") + .scalar::>() + .await? + .flatten(); + assert_eq!(customer.as_deref(), Some("cs_1"), "the Stripe customer is kept on the organization"); + Ok(()) +} + +#[test] +fn production_never_runs_on_a_test_key() { + let stripe = |key: &str| app::billing::Stripe { secret_key: Some(key.into()), webhook_secret: None }; + assert!(app::billing::check(&stripe("sk_test_x"), true).is_err()); + assert!(app::billing::check(&stripe("rk_test_x"), true).is_err()); + assert!(app::billing::check(&stripe("rk_live_x"), true).is_ok()); + assert!(app::billing::check(&stripe("sk_test_x"), false).is_ok()); +} + +fn stripe_test_key() -> Application { + app::testing::configure() + .with_envs([("STRIPE_WEBHOOK_SECRET", SECRET), ("STRIPE_SECRET_KEY", "sk_test_x")]) + .create() +} + +#[laravel::test(app = stripe_test_key)] +async fn an_event_from_the_other_mode_is_refused(app: Application) -> laravel::Result<()> { + let org = org().await?; + let event = |livemode: bool| { + json!({ + "type": "customer.subscription.deleted", "created": 1_800_000_000, "livemode": livemode, + "data": { "object": { "id": "sub_1", "metadata": { "organization_id": org.to_string() } } }, + }) + }; + post(&app, event(true)).await.assert_status(400); + post(&app, event(false)).await.assert_ok(); + Ok(()) +} + +#[laravel::test(app = stripe)] +async fn a_paid_invoice_keeps_the_two_subscriptions_notice(app: Application) -> laravel::Result<()> { + let org = org().await?; + let notice = "This organization has two Team subscriptions. Cancel one in Manage billing."; + db::query!("UPDATE organizations SET billing_problem = {notice} WHERE id = {org}").update().await?; + let paid = json!({ + "type": "invoice.paid", "created": 1_800_000_000, + "data": { "object": { "id": "in_1", "metadata": { "organization_id": org.to_string() } } }, + }); + post(&app, paid.clone()).await.assert_ok(); + let problem: Option = db::query!("SELECT billing_problem FROM organizations WHERE id = {org}") + .scalar::>() + .await? + .flatten(); + assert_eq!(problem.as_deref(), Some(notice)); + let failed = "Payment for INV-1 failed."; + db::query!("UPDATE organizations SET billing_problem = {failed} WHERE id = {org}").update().await?; + post(&app, paid).await.assert_ok(); + let problem: Option = db::query!("SELECT billing_problem FROM organizations WHERE id = {org}") + .scalar::>() + .await? + .flatten(); + assert_eq!(problem, None); + Ok(()) +}