diff --git a/app/Cargo.lock b/app/Cargo.lock index c79c4f17..8c808fac 100644 --- a/app/Cargo.lock +++ b/app/Cargo.lock @@ -286,6 +286,12 @@ version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + [[package]] name = "bcrypt" version = "0.19.3" @@ -615,6 +621,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + [[package]] name = "const-oid" version = "0.10.3" @@ -797,6 +809,17 @@ dependencies = [ "cmov", ] +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid 0.9.6", + "pem-rfc7468", + "zeroize", +] + [[package]] name = "deranged" version = "0.5.9" @@ -816,7 +839,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer 0.10.4", + "const-oid 0.9.6", "crypto-common 0.1.6", + "subtle", ] [[package]] @@ -826,7 +851,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ "block-buffer 0.12.1", - "const-oid", + "const-oid 0.10.3", "crypto-common 0.2.2", "ctutils", ] @@ -1243,7 +1268,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]] @@ -1886,6 +1920,21 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "jsonwebtoken" +version = "9.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde" +dependencies = [ + "base64 0.22.1", + "js-sys", + "pem", + "ring", + "serde", + "serde_json", + "simple_asn1", +] + [[package]] name = "laravel-rust" version = "0.1.4" @@ -1905,7 +1954,7 @@ dependencies = [ "futures-util", "getrandom 0.4.3", "hex", - "hmac", + "hmac 0.13.0", "http", "http-body", "http-body-util", @@ -2053,7 +2102,7 @@ dependencies = [ "futures-util", "getrandom 0.4.3", "hex", - "hmac", + "hmac 0.13.0", "http", "http-body", "idna", @@ -2137,7 +2186,7 @@ dependencies = [ "anyhow", "futures-util", "hex", - "hmac", + "hmac 0.13.0", "inertia-laravel-rust", "inventory", "laravel-rust-core", @@ -2190,7 +2239,7 @@ dependencies = [ "futures-util", "getrandom 0.4.3", "hex", - "hmac", + "hmac 0.13.0", "http", "http-body", "http-body-util", @@ -2293,7 +2342,7 @@ dependencies = [ "base64 0.23.1", "bytes", "futures-util", - "hmac", + "hmac 0.13.0", "inventory", "laravel-rust-core", "laravel-rust-http", @@ -2479,6 +2528,9 @@ name = "lazy_static" version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +dependencies = [ + "spin", +] [[package]] name = "libc" @@ -2761,6 +2813,22 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-bigint-dig" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" +dependencies = [ + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand 0.8.8", + "smallvec", + "zeroize", +] + [[package]] name = "num-conv" version = "0.2.2" @@ -2776,6 +2844,16 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -2783,6 +2861,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", + "libm", ] [[package]] @@ -2930,6 +3009,25 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "pem" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" +dependencies = [ + "base64 0.22.1", + "serde_core", +] + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -2942,6 +3040,27 @@ version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" +[[package]] +name = "pkcs1" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der", + "pkcs8", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + [[package]] name = "pkg-config" version = "0.3.34" @@ -3121,13 +3240,23 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + [[package]] name = "rand" version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" dependencies = [ - "rand_chacha", + "rand_chacha 0.9.0", "rand_core 0.9.5", ] @@ -3142,6 +3271,16 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + [[package]] name = "rand_chacha" version = "0.9.0" @@ -3152,6 +3291,15 @@ dependencies = [ "rand_core 0.9.5", ] +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + [[package]] name = "rand_core" version = "0.9.5" @@ -3332,6 +3480,26 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "rsa" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +dependencies = [ + "const-oid 0.9.6", + "digest 0.10.7", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core 0.6.4", + "signature", + "spki", + "subtle", + "zeroize", +] + [[package]] name = "rustc-demangle" version = "0.1.28" @@ -3463,7 +3631,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", @@ -3706,6 +3874,16 @@ dependencies = [ "libc", ] +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest 0.10.7", + "rand_core 0.6.4", +] + [[package]] name = "simd-adler32" version = "0.3.10" @@ -3734,6 +3912,18 @@ version = "2.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" +[[package]] +name = "simple_asn1" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d" +dependencies = [ + "num-bigint 0.4.8", + "num-traits", + "thiserror", + "time", +] + [[package]] name = "slab" version = "0.4.12" @@ -3785,6 +3975,16 @@ dependencies = [ "lock_api", ] +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "sqlx" version = "0.9.1" @@ -3923,7 +4123,7 @@ dependencies = [ "futures-util", "hex", "hkdf", - "hmac", + "hmac 0.13.0", "itoa", "log", "md-5", @@ -4534,14 +4734,18 @@ name = "visualci-app" version = "0.0.0" dependencies = [ "axum", + "base64 0.22.1", "globset", "hex", + "hmac 0.12.1", "image", + "jsonwebtoken", "laravel-rust", "oauth-provider", "oauth-provider-laravel", "regex", "reqwest 0.12.28", + "rsa", "rusty-s3", "serde", "serde_json", diff --git a/app/Cargo.toml b/app/Cargo.toml index 4c410008..a27a2155 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -26,9 +26,12 @@ path = "src/main.rs" laravel-rust = { version = "=0.1.4", features = ["database-postgres", "minijinja"] } # The same axum Laravel Rust runs on, for extractors (auth::Principal) axum = "0.8" +base64 = "0.22" hex = "0.4" oauth-provider = "0.1.3" oauth-provider-laravel = { version = "=0.1.1", features = ["postgres"] } +hmac = "0.12" +jsonwebtoken = "9" serde = { version = "1", features = ["derive"] } serde_json = "1" sha2 = "0.10" @@ -44,9 +47,17 @@ snapshot-diff = { path = "../crates/snapshot-diff" } [dev-dependencies] regex = "1" +# A GitHub App key made at test time, so no private key is committed +rsa = { version = "0.9", features = ["pem"] } [profile.dev] debug = "line-tables-only" [profile.dev.package."*"] debug = false + +# Generating the tests' RSA key is slow unoptimised +[profile.dev.package.num-bigint-dig] +opt-level = 3 +[profile.dev.package.rsa] +opt-level = 3 diff --git a/app/database/migrations/2026_12_03_000300_create_emails_table.rs b/app/database/migrations/2026_12_03_000300_create_emails_table.rs new file mode 100644 index 00000000..240e0138 --- /dev/null +++ b/app/database/migrations/2026_12_03_000300_create_emails_table.rs @@ -0,0 +1,37 @@ +use laravel::db::AnyTransaction; + +/// The emails outbox (ported as today's), and each person's email choices and sign-up notice. +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.query( + "CREATE TABLE emails ( + id BIGSERIAL PRIMARY KEY, + kind TEXT NOT NULL, + dedupe_key TEXT NOT NULL UNIQUE, + organization_id BIGINT REFERENCES organizations(id) ON DELETE CASCADE, + user_id BIGINT REFERENCES users(id) ON DELETE CASCADE, + recipient TEXT NOT NULL, + data JSONB NOT NULL, + subject TEXT, + text_body TEXT, + html_body TEXT, + state TEXT NOT NULL DEFAULT 'pending' CHECK (state IN ('pending', 'sent', 'failed')), + attempts INTEGER NOT NULL DEFAULT 0, + last_error TEXT, + claimed_at TIMESTAMPTZ, + sent_at TIMESTAMPTZ, + dismissed_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() + ); + CREATE INDEX emails_pending ON emails (created_at) WHERE state = 'pending'; + CREATE INDEX emails_organization ON emails (organization_id, created_at); + CREATE INDEX emails_failed ON emails (id) WHERE state = 'failed' AND dismissed_at IS NULL; + ALTER TABLE users + ADD COLUMN email_low_credits BOOLEAN NOT NULL DEFAULT true, + ADD COLUMN email_receipts BOOLEAN NOT NULL DEFAULT true, + ADD COLUMN signup_notified_at TIMESTAMPTZ;", + ) + .unprepared() + .await?; + Ok(()) +} diff --git a/app/database/migrations/2026_12_03_000400_create_invitations_table.rs b/app/database/migrations/2026_12_03_000400_create_invitations_table.rs new file mode 100644 index 00000000..3ca537ef --- /dev/null +++ b/app/database/migrations/2026_12_03_000400_create_invitations_table.rs @@ -0,0 +1,33 @@ +use laravel::db::AnyTransaction; + +/// Invitations to an organization, by email or by a login on a forge (ported as today's). `for_user_id` is the +/// account it's for when one existed when it was sent, so it shows on their side; it waits for them to accept. +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.query( + "CREATE TABLE invitations ( + id BIGSERIAL PRIMARY KEY, + pid UUID NOT NULL UNIQUE, + organization_id BIGINT NOT NULL REFERENCES organizations(id) ON DELETE CASCADE, + email TEXT, + forge TEXT, + login TEXT, + role TEXT NOT NULL CHECK (role IN ('admin', 'member', 'read')), + invited_by BIGINT REFERENCES users(id) ON DELETE SET NULL, + accepted_by BIGINT REFERENCES users(id) ON DELETE SET NULL, + accepted_at TIMESTAMPTZ, + for_user_id BIGINT REFERENCES users(id) ON DELETE CASCADE, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + CHECK ((email IS NOT NULL) <> (login IS NOT NULL)), + CHECK ((login IS NULL) = (forge IS NULL)) + ); + CREATE UNIQUE INDEX invitations_pending_email ON invitations (organization_id, lower(email)) + WHERE accepted_at IS NULL AND email IS NOT NULL; + CREATE UNIQUE INDEX invitations_pending_login ON invitations (organization_id, forge, lower(login)) + WHERE accepted_at IS NULL AND login IS NOT NULL; + CREATE INDEX invitations_for_user ON invitations (for_user_id) WHERE accepted_at IS NULL;", + ) + .unprepared() + .await?; + Ok(()) +} diff --git a/app/database/migrations/2026_12_03_000500_add_heard_about_to_users.rs b/app/database/migrations/2026_12_03_000500_add_heard_about_to_users.rs new file mode 100644 index 00000000..a46492d1 --- /dev/null +++ b/app/database/migrations/2026_12_03_000500_add_heard_about_to_users.rs @@ -0,0 +1,15 @@ +use laravel::db::AnyTransaction; + +/// "How did you hear about VisualCI?" (asked once after sign-up), ported as today's. +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.query( + "ALTER TABLE users + ADD COLUMN heard_about_pending BOOLEAN NOT NULL DEFAULT false, + ADD COLUMN heard_about_source TEXT, + ADD COLUMN heard_about_detail TEXT; + CREATE INDEX users_signup_unnotified ON users (id) WHERE signup_notified_at IS NULL;", + ) + .unprepared() + .await?; + Ok(()) +} diff --git a/app/database/migrations/2026_12_03_000600_create_device_logins_table.rs b/app/database/migrations/2026_12_03_000600_create_device_logins_table.rs new file mode 100644 index 00000000..4bcab92a --- /dev/null +++ b/app/database/migrations/2026_12_03_000600_create_device_logins_table.rs @@ -0,0 +1,30 @@ +use laravel::db::AnyTransaction; + +/// `visualci login`'s device-code sign-in (ported as today's): the device code is stored hashed; a code gives one +/// token, once. +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.query( + "CREATE TABLE device_logins ( + id BIGSERIAL PRIMARY KEY, + device_code_hash TEXT NOT NULL UNIQUE, + user_code TEXT NOT NULL UNIQUE, + -- What's asking, shown on the approval page: \"visualci CLI on ada-laptop\". + client_name TEXT NOT NULL, + -- Who asked for it (behind the trusted proxies, the address they report), shown on the approval page and + -- counted for the per-address limit. + requester_ip TEXT, + last_polled_at TIMESTAMPTZ, + user_id BIGINT REFERENCES users(id) ON DELETE CASCADE, + approved_at TIMESTAMPTZ, + denied_at TIMESTAMPTZ, + -- When the CLI collected its token. + consumed_at TIMESTAMPTZ, + expires_at TIMESTAMPTZ NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() + ); + CREATE INDEX device_logins_requester ON device_logins (requester_ip, created_at);", + ) + .unprepared() + .await?; + Ok(()) +} diff --git a/app/src/auth/device.rs b/app/src/auth/device.rs new file mode 100644 index 00000000..b914b479 --- /dev/null +++ b/app/src/auth/device.rs @@ -0,0 +1,317 @@ +//! `visualci login`'s device-code sign-in (in the style of RFC 8628; sc-8900, the auth side, ported from today's +//! server). The CLI asks for a code pair: a secret device code it polls with, and a short user code the person types +//! or follows on the app's /device page. Once they approve it, the next poll gets a new personal token, once, and the +//! person gets a security notice. Codes last ten minutes. +//! +//! A code pair can be asked for by anyone, so the approval page is built against phishing: it names the request as a +//! VisualCI command-line sign-in, with where and when it was asked for, and says to approve it only right after running +//! `visualci login`; the name the CLI sent is a detail below that. Each address may ask for a few codes in ten minutes, +//! and expired codes are deleted daily. + +use std::net::IpAddr; + +use laravel::auth::Authenticated; +use laravel::db; +use laravel::http::{Next, Request, Response, middleware}; +use laravel::prelude::*; +use laravel::queue::{Queueable, job}; +use laravel::schedule::{self, Schedule}; +use serde_json::{Value, json}; + +use crate::models::{User, token_hash}; +use crate::notify::outbox::AppUrl; +use crate::notify::{self, Kind, To}; + +/// The CLI's side, on the `api` group: no session, no CSRF. +pub fn api_routes(route: &mut Router) { + route.middleware(limit_codes).group(|route| { + route.post("/v1/device/code", code); + }); + route.post("/v1/device/token", token); +} + +/// The person's side, on the `web` group. +pub fn routes(route: &mut Router) { + route.get("/api/ui/device/{code}", show); + route.post("/api/ui/device/{code}", decide); +} + +/// How long a code pair can be approved and collected. +pub const LIFETIME_SECONDS: i64 = 600; +/// How often the CLI may ask. +pub const INTERVAL_SECONDS: i64 = 3; +/// Code pairs one address may ask for in ten minutes. +pub const CODES_PER_ADDRESS: i64 = 10; + +/// The address that asked for a code pair (behind the trusted proxies, the one they report). +#[derive(Clone, Copy, Debug)] +pub struct Requester(pub IpAddr); + +/// Route middleware for `/api/v1/device/code`: at most [`CODES_PER_ADDRESS`] code pairs per address in ten minutes +/// (429 after that), and the address passed on for the approval page. +#[middleware] +pub async fn limit_codes(request: Request, next: Next) -> Response { + let ip = request.ip(); + let address = ip.to_string(); + let recent: laravel::Result> = db::query!( + "SELECT count(*) FROM device_logins WHERE requester_ip = {address} AND created_at > now() - interval '10 minutes'" + ) + .scalar() + .await; + match recent { + Ok(Some(n)) if n >= CODES_PER_ADDRESS => { + return Response::new(Json( + json!({ "error": "too many sign-in codes from this address; try again in ten minutes" }), + )) + .with_status(429) + .with_header("retry-after", "600"); + } + Err(e) => tracing::warn!(error = %e, "device code limit"), + _ => {} + } + let mut http = request.into_http(); + http.extensions_mut().insert(Requester(ip)); + next.run(Request::from_http(http)).await +} + +/// Letters that can't be mistaken for each other or for digits. +const USER_CODE_ALPHABET: &[u8] = b"BCDFGHJKLMNPQRSTVWXZ"; + +/// A user code such as `KQHT-WMRP`. +fn new_user_code() -> String { + let mut letters = Vec::new(); + while letters.len() < 8 { + letters.extend(laravel::str::random(64).bytes().filter(|b| USER_CODE_ALPHABET.contains(b))); + } + let code: String = letters[..8].iter().map(|&b| char::from(b)).collect(); + format!("{}-{}", &code[..4], &code[4..]) +} + +/// A user code as people type it: upper case, with the dash where it belongs. +#[must_use] +pub fn normalize_user_code(code: &str) -> String { + let letters: String = code.chars().filter(char::is_ascii_alphabetic).map(|c| c.to_ascii_uppercase()).collect(); + if letters.len() == 8 { format!("{}-{}", &letters[..4], &letters[4..]) } else { letters } +} + +#[laravel::input] +#[validate(anyone)] +pub struct CodeInput { + /// What's asking, shown when the person approves: "visualci CLI on ada-laptop". + name: Option, +} + +/// `POST /api/v1/device/code`: a code pair. The person opens `verification_uri_complete` (or `verification_uri` and +/// types `user_code`) and approves; the CLI polls `/api/v1/device/token` with `device_code` every `interval` seconds. +pub async fn code( + app: laravel::config::Section, + requester: Option>, + Valid(p): Valid, +) -> laravel::Result> { + let requester = requester.map(|r| r.0.0.to_string()); + let client: String = p.name.unwrap_or_default().chars().filter(|c| !c.is_control()).take(100).collect(); + let client = if client.trim().is_empty() { "visualci CLI".to_string() } else { client }; + let lifetime = LIFETIME_SECONDS; + for _ in 0..5 { + let device = laravel::str::random(40); + let user = new_user_code(); + let hash = token_hash(&device); + let inserted: Option = db::query!( + "INSERT INTO device_logins (device_code_hash, user_code, client_name, requester_ip, expires_at) \ + VALUES ({hash}, {user}, {client}, {requester}, now() + make_interval(secs => {lifetime}::int)) \ + ON CONFLICT DO NOTHING RETURNING id" + ) + .scalar() + .await?; + if inserted.is_some() { + let uri = format!("{}/device", app.url.trim_end_matches('/')); + return Ok(Json(json!({ + "device_code": device, + "user_code": user, + "verification_uri": uri, + "verification_uri_complete": format!("{uri}?code={user}"), + "expires_in": LIFETIME_SECONDS, + "interval": INTERVAL_SECONDS, + }))); + } + } + Err(laravel::abort_with(503, "couldn't make a code; try again")) +} + +#[laravel::input] +#[validate(anyone)] +pub struct TokenInput { + #[validate(required, max_length(200))] + device_code: String, +} + +/// `POST /api/v1/device/token`, polled: `status` is `pending` (ask again), `slow_down` (asked again within the +/// interval: wait longer), `denied`, `expired`, or `approved` with a new personal token (`token`), given once. +pub async fn token(Valid(p): Valid) -> laravel::Result> { + let hash = token_hash(&p.device_code); + // A second's grace for clocks and networks, as RFC 8628 asks clients to keep the interval. + let pace = INTERVAL_SECONDS - 1; + let paced: Option = db::query!( + "UPDATE device_logins SET last_polled_at = now() WHERE device_code_hash = {hash} \ + AND (last_polled_at IS NULL OR last_polled_at <= now() - make_interval(secs => {pace}::int)) RETURNING id" + ) + .scalar() + .await?; + if paced.is_none() { + let known: Option = + db::query!("SELECT id FROM device_logins WHERE device_code_hash = {hash}").scalar().await?; + if known.is_some() { + return Ok(Json(json!({ "status": "slow_down" }))); + } + } + // Claim an approved, uncollected code and make its token in one transaction: two polls never both get a token, + // and a failure leaves the code to collect again. + let claimed = db::transaction(async |tx| { + let Some(row) = db::query!( + tx, + "UPDATE device_logins SET consumed_at = now() WHERE device_code_hash = {hash} AND approved_at IS NOT NULL \ + AND consumed_at IS NULL AND expires_at > now() RETURNING user_id, client_name" + ) + .select_one() + .await? + else { + return Ok(None); + }; + let user_id: i64 = row.try_get("user_id")?; + let client: String = row.try_get("client_name")?; + let (token, token_hash_, shown) = super::tokens::generate("vcu_"); + db::query!( + tx, + "INSERT INTO user_tokens (user_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({user_id}, {client}, {token_hash_}, {shown}, now(), now())" + ) + .insert() + .await?; + Ok(Some((user_id, client, token))) + }) + .await?; + if let Some((user_id, client, token)) = claimed { + let at = laravel::now().timestamp().strftime("%-d %B %Y, %H:%M UTC").to_string(); + let kind = Kind::DeviceSignIn { client, at }; + let key = format!("device_sign_in:{user_id}:{}", laravel::now().timestamp().as_millisecond()); + notify::queue(&kind, To::User(user_id), None, &key).await?; + let name: Option = db::query!("SELECT name FROM users WHERE id = {user_id}").scalar().await?; + return Ok(Json(json!({ "status": "approved", "token": token, "user": name }))); + } + let row = db::query!( + "SELECT (denied_at IS NOT NULL) AS denied, (expires_at > now() AND consumed_at IS NULL) AS live \ + FROM device_logins WHERE device_code_hash = {hash}" + ) + .select_one() + .await?; + let status = match row { + Some(r) if r.try_get::("denied")? => "denied", + Some(r) if r.try_get::("live")? => "pending", + _ => "expired", + }; + Ok(Json(json!({ "status": status }))) +} + +/// What the approval page says, before anything the request itself sent. +pub const LABEL: &str = "VisualCI command-line sign-in"; +pub const WARNING: &str = "Only approve this if you just ran visualci login yourself. Approving gives whoever asked a \ + token that acts as you."; + +/// `GET /api/ui/device/{code}`: the sign-in a user code asks for, to approve or deny: a fixed label and warning, where +/// and when it was asked for, and the name the CLI sent as a detail (`client`), since anyone can choose that. 404 when +/// there's no such pending code. +pub async fn show( + Authenticated(_user): Authenticated, + Params(code): Params, +) -> laravel::Result> { + let code = normalize_user_code(&code); + let row = db::query!( + "SELECT client_name, requester_ip, \ + to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"') AS requested_at \ + FROM device_logins WHERE user_code = {code} AND expires_at > now() \ + AND approved_at IS NULL AND denied_at IS NULL" + ) + .select_one() + .await? + .ok_or_else(|| laravel::abort(404))?; + Ok(Json(json!({ + "label": LABEL, + "warning": WARNING, + "requested_from": row.try_get::>("requester_ip")?, + "requested_at": row.try_get::("requested_at")?, + "client": row.try_get::("client_name")?, + }))) +} + +/// Delete codes that expired more than a day ago, daily; pushes `VISUALCI_DEVICE_PRUNE_HEARTBEAT`. +#[derive(Queueable, Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct PruneDeviceLogins; + +#[job] +impl PruneDeviceLogins { + async fn handle(self) -> laravel::Result<()> { + let pruned = prune().await; + let health = pruned.as_ref().map(|_| ()).map_err(ToString::to_string); + crate::heartbeat::push("VISUALCI_DEVICE_PRUNE_HEARTBEAT", health).await; + pruned.map(|_| ()) + } +} + +/// Delete codes that expired more than a day ago. Returns how many. +/// +/// # Errors +/// On a database error. +pub async fn prune() -> laravel::Result { + db::query!("DELETE FROM device_logins WHERE expires_at < now() - interval '1 day'").delete().await +} + +#[schedule::tasks] +fn schedule(schedule: &mut Schedule) { + schedule.job(PruneDeviceLogins).daily().without_overlapping(); +} + +#[laravel::input] +#[validate(authenticated)] +pub struct DecideInput { + approve: bool, +} + +/// `POST /api/ui/device/{code}`: approve or deny. Approving gives the waiting CLI a personal token for this person. +pub async fn decide( + Authenticated(user): Authenticated, + Params(code): Params, + Valid(p): Valid, +) -> laravel::Result> { + let (code, user_id) = (normalize_user_code(&code), user.id); + let decided: Option = if p.approve { + db::query!( + "UPDATE device_logins SET approved_at = now(), user_id = {user_id} WHERE user_code = {code} \ + AND expires_at > now() AND approved_at IS NULL AND denied_at IS NULL RETURNING id" + ) + .scalar() + .await? + } else { + db::query!( + "UPDATE device_logins SET denied_at = now(), user_id = {user_id} WHERE user_code = {code} \ + AND expires_at > now() AND approved_at IS NULL AND denied_at IS NULL RETURNING id" + ) + .scalar() + .await? + }; + decided.ok_or_else(|| laravel::abort(404))?; + Ok(Json(json!({ "ok": true }))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn user_codes_read_as_typed() { + assert_eq!(normalize_user_code("kqht wmrp"), "KQHT-WMRP"); + assert_eq!(normalize_user_code("KQHT-WMRP"), "KQHT-WMRP"); + let code = new_user_code(); + assert_eq!(code.len(), 9); + assert!(code.chars().all(|c| c == '-' || USER_CODE_ALPHABET.contains(&(c as u8)))); + } +} diff --git a/app/src/auth/invitations.rs b/app/src/auth/invitations.rs new file mode 100644 index 00000000..3ca34dec --- /dev/null +++ b/app/src/auth/invitations.rs @@ -0,0 +1,561 @@ +//! Invitations and members (sc-8900, the auth side), ported from today's server. An admin invites someone by email +//! or GitHub login; the invitation waits for its invitee to accept or decline it in the app, whether or not they +//! already have an account, so nobody joins an organization, or shows among its members, without saying so. Admins +//! change members' roles or remove them, except where the forge decides the membership, and an organization always +//! keeps an admin. + +use laravel::auth::Authenticated; +use laravel::db; +use laravel::prelude::*; +use serde_json::{Value, json}; + +use super::Role; +use super::memberships::MembershipChanged; +use crate::forge::ForgeKind; +use crate::models::User; +use crate::notify::{self, Kind, To}; + +pub fn routes(route: &mut Router) { + route.get("/api/ui/invitations", mine); + route.post("/api/ui/invitations/{id}/accept", accept); + route.post("/api/ui/invitations/{id}/decline", decline); + route.get("/api/ui/orgs/{org}/members", members); + route.post("/api/ui/orgs/{org}/invitations", invite); + route.delete("/api/ui/orgs/{org}/invitations/{id}", withdraw); + route.patch("/api/ui/orgs/{org}/members/{id}", update_member); + route.delete("/api/ui/orgs/{org}/members/{id}", remove_member); +} + +/// Invitation emails an organization may send in a day, and one address may receive from all organizations: inviting, +/// withdrawing and inviting again would otherwise send mail without end, from VisualCI's own domain. +pub const DAILY_PER_ORGANIZATION: i64 = 50; +pub const DAILY_PER_RECIPIENT: i64 = 3; + +/// Who an invitation is for: an email address, or a login on a forge. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Invitee { + Email(String), + Login(ForgeKind, String), +} + +impl Invitee { + /// `someone@example.com`, `@octocat` or `octocat` (a GitHub login). + /// + /// # Errors + /// A message when it's neither. + pub fn parse(input: &str) -> Result { + let s = input.trim(); + if s.contains('@') && !s.starts_with('@') { + let (local, domain) = s.split_once('@').unwrap_or_default(); + if local.is_empty() || !domain.contains('.') || s.contains(char::is_whitespace) { + return Err(format!("{s:?} isn't an email address")); + } + return Ok(Self::Email(s.to_lowercase())); + } + let login = s.trim_start_matches('@'); + let valid = !login.is_empty() + && login.len() <= 39 + && login.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') + && !login.starts_with('-'); + if valid { + Ok(Self::Login(ForgeKind::Github, login.to_string())) + } else { + Err(format!("{s:?} isn't an email address or GitHub login")) + } + } + + /// The account it's for when one exists already: a verified email, or a login on github.com or gitlab.com (a + /// self-managed instance's logins are its own). + /// + /// # Errors + /// On a database error. + pub async fn account(&self) -> laravel::Result> { + match self { + Self::Email(e) => db::query!( + "SELECT id FROM users WHERE lower(email) = {e} AND email_verified_at IS NOT NULL ORDER BY id LIMIT 1" + ) + .scalar() + .await, + Self::Login(f, l) => { + let (forge, login) = (f.as_str(), l.to_lowercase()); + db::query!( + "SELECT user_id FROM identities WHERE forge = {forge} AND site = '' AND lower(login) = {login} \ + ORDER BY id LIMIT 1" + ) + .scalar() + .await + } + } + } +} + +/// Where an invitation's email goes: the account's address when it's for one, else the address it names (an +/// invitation by login to someone without an account gets no email). +async fn address(invitee: &Invitee, account: Option) -> laravel::Result> { + if let Some(id) = account { + return db::query!("SELECT email FROM users WHERE id = {id}").scalar().await; + } + Ok(match invitee { + Invitee::Email(e) => Some(e.clone()), + Invitee::Login(..) => None, + }) +} + +/// `Err(message)` when an invitation to `address` from organization `org_id` would go over a daily limit. +/// +/// # Errors +/// On a database error. +pub async fn may_send(org_id: i64, address: Option<&str>) -> laravel::Result> { + let sent_by_org: i64 = db::query!( + "SELECT count(*) FROM emails WHERE kind = 'invited' AND organization_id = {org_id} \ + AND created_at > now() - interval '24 hours'" + ) + .scalar() + .await? + .unwrap_or(0); + if sent_by_org >= DAILY_PER_ORGANIZATION { + return Ok(Err(format!( + "this organization has sent {DAILY_PER_ORGANIZATION} invitations in the last 24 hours, the limit; try \ + again tomorrow" + ))); + } + if let Some(address) = address { + let received: i64 = db::query!( + "SELECT count(*) FROM emails WHERE kind = 'invited' AND lower(recipient) = lower({address}) \ + AND created_at > now() - interval '24 hours'" + ) + .scalar() + .await? + .unwrap_or(0); + if received >= DAILY_PER_RECIPIENT { + return Ok(Err("that person has been invited too often in the last 24 hours; try again tomorrow".into())); + } + } + Ok(Ok(())) +} + +/// The organization by slug and the person's role there; a 404 when they aren't a member. Staff are no exception: +/// their tools are the admin MCP's, with its audit log, never the customer pages. +async fn org_role(user: &User, slug: &str) -> laravel::Result<(i64, String, Role)> { + let user_id = user.id; + let row = db::query!( + "SELECT o.id, o.name, 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))?; + let role = row.try_get::>("role")?.as_deref().and_then(Role::parse); + let role = match role { + Some(r) => r, + None => return Err(laravel::abort(404)), + }; + Ok((row.try_get("id")?, row.try_get("name")?, role)) +} + +/// The organization, when the person is an admin there: a member gets a 403, anyone else a 404. +async fn admin_org(user: &User, slug: &str, action: &str) -> laravel::Result<(i64, String)> { + let (id, name, role) = org_role(user, slug).await?; + if role < Role::Admin { + return Err(laravel::abort_with(403, format!("only admins can {action}"))); + } + Ok((id, name)) +} + +fn json_of(text: &str) -> laravel::Result { + serde_json::from_str(text).map_err(|e| laravel::Error::msg(e.to_string())) +} + +fn uuid(s: &str) -> laravel::Result { + laravel::str::Uuid::parse_str(s).map(|u| u.to_string()).map_err(|_| laravel::abort(404)) +} + +/// An organization's pending invitations, newest first. +/// +/// # Errors +/// On a database error. +pub async fn pending(org_id: i64) -> laravel::Result> { + let rows = db::query!( + "SELECT json_build_object('id', i.pid, \ + 'invitee', COALESCE(i.email, '@' || i.login || CASE i.forge WHEN 'github' THEN ' (GitHub)' \ + WHEN 'gitlab' THEN ' (GitLab)' ELSE '' END), \ + 'email', i.email, 'forge', i.forge, 'login', i.login, 'role', i.role, \ + 'created_at', to_char(i.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"'))::text AS j \ + FROM invitations i WHERE i.organization_id = {org_id} AND i.accepted_at IS NULL ORDER BY i.id DESC" + ) + .select() + .await?; + rows.iter().map(|r| json_of(&r.try_get::("j")?)).collect() +} + +/// An organization's members, admins first then by name, with their forge logins; emails only for its admins. +/// +/// # Errors +/// On a database error. +pub async fn members_json(org_id: i64, with_emails: bool) -> laravel::Result> { + let rows = db::query!( + "SELECT json_build_object('id', u.pid, 'name', u.name, \ + 'email', CASE WHEN {with_emails} THEN u.email END, 'avatar_url', u.avatar_url, \ + 'login', (SELECT login FROM identities WHERE user_id = u.id ORDER BY id LIMIT 1), \ + 'identities', COALESCE((SELECT json_agg(json_build_object('forge', forge, 'login', login) ORDER BY id) \ + FROM identities WHERE user_id = u.id), '[]'::json), \ + 'role', m.role, 'source', m.source, \ + 'synced_at', to_char(m.synced_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"'), \ + 'since', to_char(m.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"'))::text AS j \ + FROM memberships m JOIN users u ON u.id = m.user_id WHERE m.organization_id = {org_id} \ + ORDER BY CASE m.role WHEN 'admin' THEN 0 WHEN 'member' THEN 1 ELSE 2 END, u.name" + ) + .select() + .await?; + rows.iter().map(|r| json_of(&r.try_get::("j")?)).collect() +} + +/// `GET /api/ui/orgs/{org}/members`: its members, and its pending invitations for its admins. +pub async fn members( + Authenticated(user): Authenticated, + Params(org): Params, +) -> laravel::Result> { + let (org_id, _, role) = org_role(&user, &org).await?; + let admin = role == Role::Admin; + let invitations = if admin { pending(org_id).await? } else { Vec::new() }; + Ok(Json(json!({ "members": members_json(org_id, admin).await?, "invitations": invitations }))) +} + +/// The pending invitations for a person: recorded for them, or to their verified email, or to one of their logins on +/// github.com or gitlab.com. Newest first, each with its organization and who invited them. +/// +/// # Errors +/// On a database error. +pub async fn pending_for(user: &User) -> laravel::Result> { + let user_id = user.id; + let email = user.email_verified_at.is_some().then(|| user.email.to_lowercase()); + let rows = db::query!( + "SELECT json_build_object('id', i.pid, 'organization', json_build_object('slug', o.slug, 'name', o.name), \ + 'role', i.role, 'invited_by', inviter.name, \ + 'created_at', to_char(i.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"'))::text AS j \ + FROM invitations i JOIN organizations o ON o.id = i.organization_id \ + LEFT JOIN users inviter ON inviter.id = i.invited_by \ + WHERE i.accepted_at IS NULL AND (i.for_user_id = {user_id} \ + OR (i.email IS NOT NULL AND lower(i.email) = {email}) \ + OR EXISTS (SELECT 1 FROM identities d WHERE d.user_id = {user_id} AND d.site = '' \ + AND d.forge = i.forge AND lower(d.login) = lower(i.login))) \ + ORDER BY i.id DESC" + ) + .select() + .await?; + rows.iter().map(|r| json_of(&r.try_get::("j")?)).collect() +} + +/// The pending invitation `pid` when it's for this person: its ID, organization and role. A 404 otherwise. +async fn theirs(user: &User, pid: &str) -> laravel::Result<(i64, i64, Role)> { + let pid = uuid(pid)?; + let user_id = user.id; + let email = user.email_verified_at.is_some().then(|| user.email.to_lowercase()); + let row = db::query!( + "SELECT i.id, i.organization_id, i.role FROM invitations i \ + WHERE i.pid = {pid}::uuid AND i.accepted_at IS NULL AND (i.for_user_id = {user_id} \ + OR (i.email IS NOT NULL AND lower(i.email) = {email}) \ + OR EXISTS (SELECT 1 FROM identities d WHERE d.user_id = {user_id} AND d.site = '' \ + AND d.forge = i.forge AND lower(d.login) = lower(i.login)))" + ) + .select_one() + .await? + .ok_or_else(|| laravel::abort(404))?; + let role: String = row.try_get("role")?; + Ok((row.try_get("id")?, row.try_get("organization_id")?, Role::parse(&role).unwrap_or(Role::Read))) +} + +/// `GET /api/ui/invitations`: the signed-in person's pending invitations. +pub async fn mine(Authenticated(user): Authenticated) -> laravel::Result> { + Ok(Json(json!({ "invitations": pending_for(&user).await? }))) +} + +#[laravel::input] +#[validate(authenticated)] +pub struct InviteInput { + /// An email address, or a GitHub login (`octocat` or `@octocat`). + #[validate(required, max_length(320))] + invitee: String, + #[validate(required)] + role: String, +} + +/// `POST /api/ui/orgs/{org}/invitations` (admins): invite someone, or change the role of their pending invitation. +/// It waits for them to accept, whether or not they have an account; they get an email either way when there's an +/// address to send it to. +pub async fn invite( + Authenticated(user): Authenticated, + Params(org): Params, + Valid(p): Valid, +) -> laravel::Result> { + let (org_id, _) = admin_org(&user, &org, "invite people").await?; + Ok(Json(invite_to(org_id, &user, &p.invitee, &p.role).await?)) +} + +/// Invite `invitee` (an email address or GitHub login) to organization `org_id` as `role`, sent by `by`, or change +/// the role of their pending invitation; returns the invitation as the members page and the MCP server show it. The +/// caller checks that `by` is an admin there. Errors: 422 for an invitee or role it can't read, 429 over a daily +/// limit (staff aren't limited). +/// +/// # Errors +/// Those, and database errors. +pub async fn invite_to(org_id: i64, by: &User, invitee: &str, role: &str) -> laravel::Result { + let user = by; + let role = Role::parse(role).ok_or_else(|| laravel::abort_with(422, "role is admin, member or read"))?; + let invitee = Invitee::parse(invitee).map_err(|e| laravel::abort_with(422, e))?; + let account = invitee.account().await?; + let to = address(&invitee, account).await?; + if !user.staff + && let Err(e) = may_send(org_id, to.as_deref()).await? + { + return Err(laravel::abort_with(429, e)); + } + let (email, forge, login) = match &invitee { + Invitee::Email(e) => (Some(e.clone()), None, None), + Invitee::Login(f, l) => (None, Some(f.as_str().to_string()), Some(l.clone())), + }; + let (role_name, inviter, pid) = (role.as_str(), user.id, laravel::str::uuid7().to_string()); + let lower_login = login.as_deref().map(str::to_lowercase); + let existing: Option = db::query!( + "SELECT id FROM invitations WHERE organization_id = {org_id} AND accepted_at IS NULL \ + AND ((email IS NOT NULL AND lower(email) = {email}) \ + OR (login IS NOT NULL AND forge = {forge} AND lower(login) = {lower_login}))" + ) + .scalar() + .await?; + let id: i64 = match existing { + Some(id) => { + db::query!( + "UPDATE invitations SET role = {role_name}, for_user_id = COALESCE({account}, for_user_id), \ + updated_at = now() WHERE id = {id}" + ) + .update() + .await?; + id + } + None => db::query!( + "INSERT INTO invitations (pid, organization_id, email, forge, login, role, invited_by, for_user_id) \ + VALUES ({pid}::uuid, {org_id}, {email}, {forge}, {login}, {role_name}, {inviter}, {account}) RETURNING id" + ) + .scalar() + .await? + .ok_or_else(|| laravel::Error::msg("no invitation id"))?, + }; + if let Some(to) = to { + let kind = Kind::Invited { inviter: user.name.clone(), role: role_name.to_string() }; + notify::queue(&kind, To::Address(to), Some(org_id), &format!("invited:{id}")).await?; + } + let row = db::query!("SELECT json_build_object('id', i.pid, \ + 'invitee', COALESCE(i.email, '@' || i.login || CASE i.forge WHEN 'github' THEN ' (GitHub)' \ + WHEN 'gitlab' THEN ' (GitLab)' ELSE '' END), \ + 'email', i.email, 'forge', i.forge, 'login', i.login, 'role', i.role, \ + 'created_at', to_char(i.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"'))::text AS j FROM invitations i WHERE i.id = {id}") + .select_one() + .await? + .ok_or_else(|| laravel::abort(404))?; + json_of(&row.try_get::("j")?) +} + +/// `POST /api/ui/invitations/{id}/accept`: join with its role, or keep a higher one already held (an invitation +/// never lowers a role: otherwise an admin could demote the last admin, or take a forge-derived membership out of the +/// forge's hands by inviting downwards). +pub async fn accept( + Authenticated(user): Authenticated, + Params(id): Params, +) -> laravel::Result> { + let (invitation, org_id, role) = theirs(&user, &id).await?; + let (user_id, role_name) = (user.id, role.as_str()); + let joined = db::transaction(async |tx| { + // Still pending? Withdrawn meanwhile, or accepted by a double click: nothing to do. + let pending: Option = db::query!( + tx, + "SELECT id FROM invitations WHERE id = {invitation} AND accepted_at IS NULL FOR UPDATE" + ) + .scalar() + .await?; + if pending.is_none() { + return Ok(None); + } + let current: Option = db::query!( + tx, + "SELECT role FROM memberships WHERE organization_id = {org_id} AND user_id = {user_id} FOR UPDATE" + ) + .scalar() + .await?; + let joined = match current.as_deref().and_then(Role::parse) { + None => { + db::query!( + tx, + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org_id}, {user_id}, {role_name}, 'invite', now(), now())" + ) + .insert() + .await?; + true + } + Some(r) if r < role => { + db::query!( + tx, + "UPDATE memberships SET role = {role_name}, source = 'invite', synced_at = NULL, updated_at = now() \ + WHERE organization_id = {org_id} AND user_id = {user_id}" + ) + .update() + .await?; + true + } + Some(_) => false, + }; + db::query!( + tx, + "UPDATE invitations SET accepted_by = {user_id}, accepted_at = now(), updated_at = now() \ + WHERE id = {invitation}" + ) + .update() + .await?; + Ok(Some(joined)) + }) + .await?; + let Some(joined) = joined else { return Err(laravel::abort(404)) }; + // They're told, as today's grant does, once the membership is there. + if joined { + MembershipChanged::now(org_id, user_id, Some(role)).dispatch().await?; + } + let slug: Option = db::query!("SELECT slug FROM organizations WHERE id = {org_id}").scalar().await?; + Ok(Json(json!({ "slug": slug }))) +} + +/// `POST /api/ui/invitations/{id}/decline`: it's withdrawn, as if its admin had. +pub async fn decline( + Authenticated(user): Authenticated, + Params(id): Params, +) -> laravel::Result> { + let (invitation, _, _) = theirs(&user, &id).await?; + db::query!("DELETE FROM invitations WHERE id = {invitation}").delete().await?; + Ok(Json(json!({ "ok": true }))) +} + +/// `DELETE /api/ui/orgs/{org}/invitations/{id}` (admins): withdraw a pending invitation. +pub async fn withdraw( + Authenticated(user): Authenticated, + Params((org, id)): Params<(String, String)>, +) -> laravel::Result> { + let (org_id, _) = admin_org(&user, &org, "withdraw invitations").await?; + let pid = uuid(&id)?; + db::query!( + "DELETE FROM invitations WHERE pid = {pid}::uuid AND organization_id = {org_id} AND accepted_at IS NULL" + ) + .delete() + .await?; + Ok(Json(json!({ "ok": true }))) +} + +/// The membership of user `pid` in an organization the person administers: its organization and user IDs. A +/// membership the forge decides can't be changed here. +async fn managed(user: &User, org: &str, pid: &str) -> laravel::Result<(i64, i64)> { + let (org_id, _) = admin_org(user, org, "manage members").await?; + let pid = uuid(pid)?; + let row = db::query!( + "SELECT m.user_id, m.source FROM memberships m JOIN users u ON u.id = m.user_id \ + WHERE m.organization_id = {org_id} AND u.pid = {pid}::uuid" + ) + .select_one() + .await? + .ok_or_else(|| laravel::abort(404))?; + let source: String = row.try_get("source")?; + if let Some(forge) = ForgeKind::parse(&source) { + return Err(laravel::abort_with( + 422, + format!("this access comes from {}: change their permission on the repository there", forge.label()), + )); + } + Ok((org_id, row.try_get("user_id")?)) +} + +/// Change (`Some(role)`) or remove (`None`) a membership, unless that would leave the organization without an admin. +/// The admin memberships are locked first, so two admins demoting or removing each other at once can't both succeed. +/// `false` when it would leave no admin. +async fn change_member(org_id: i64, member: i64, role: Option) -> laravel::Result { + db::transaction(async |tx| { + let admins = db::query!( + tx, + "SELECT user_id FROM memberships WHERE organization_id = {org_id} AND role = 'admin' FOR UPDATE" + ) + .select() + .await?; + let others = admins.iter().filter(|r| r.try_get::("user_id").is_ok_and(|id| id != member)).count(); + if role != Some(Role::Admin) && others == 0 { + return Ok(false); + } + match role { + Some(role) => { + let role_name = role.as_str(); + db::query!( + tx, + "UPDATE memberships SET role = {role_name}, updated_at = now() \ + WHERE organization_id = {org_id} AND user_id = {member}" + ) + .update() + .await?; + } + None => { + db::query!(tx, "DELETE FROM memberships WHERE organization_id = {org_id} AND user_id = {member}") + .delete() + .await?; + } + } + Ok(true) + }) + .await +} + +#[laravel::input] +#[validate(authenticated)] +pub struct MemberInput { + #[validate(required)] + role: String, +} + +/// `PATCH /api/ui/orgs/{org}/members/{id}` (admins): change a member's role. The organization keeps an admin. +pub async fn update_member( + Authenticated(user): Authenticated, + Params((org, id)): Params<(String, String)>, + Valid(p): Valid, +) -> laravel::Result> { + let role = Role::parse(&p.role).ok_or_else(|| laravel::abort_with(422, "role is admin, member or read"))?; + let (org_id, member) = managed(&user, &org, &id).await?; + if !change_member(org_id, member, Some(role)).await? { + return Err(laravel::abort_with(422, "the organization needs another admin first")); + } + Ok(Json(json!({ "members": members_json(org_id, true).await? }))) +} + +/// `DELETE /api/ui/orgs/{org}/members/{id}` (admins): remove a member, who's told unless they removed themselves. +/// The organization keeps an admin. +pub async fn remove_member( + Authenticated(user): Authenticated, + Params((org, id)): Params<(String, String)>, +) -> laravel::Result> { + let (org_id, member) = managed(&user, &org, &id).await?; + if !change_member(org_id, member, None).await? { + return Err(laravel::abort_with(422, "the organization needs another admin first")); + } + if member != user.id { + MembershipChanged::now(org_id, member, None).dispatch().await?; + } + Ok(Json(json!({ "members": members_json(org_id, true).await? }))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_invitees() { + assert_eq!(Invitee::parse(" Ann@Example.com "), Ok(Invitee::Email("ann@example.com".into()))); + assert_eq!(Invitee::parse("@octo-cat"), Ok(Invitee::Login(ForgeKind::Github, "octo-cat".into()))); + assert_eq!(Invitee::parse("octocat"), Ok(Invitee::Login(ForgeKind::Github, "octocat".into()))); + for bad in ["", "@", "a@b", "two words", "-x", "a b@c.com"] { + assert!(Invitee::parse(bad).is_err(), "{bad}"); + } + } +} diff --git a/app/src/auth/me.rs b/app/src/auth/me.rs new file mode 100644 index 00000000..94b5a38f --- /dev/null +++ b/app/src/auth/me.rs @@ -0,0 +1,445 @@ +//! The signed-in person's own page (sc-8900, the auth side), ported from today's server: `GET /api/ui/me` (who they +//! are, their organizations, their pending invitations, their email choices), turning low-credit and receipt emails +//! on or off, an organization's billing email, and "How did you hear about VisualCI?". Also the team's email about +//! each new sign-up, which waits for that answer. + +use laravel::auth::Authenticated; +use laravel::db; +use laravel::prelude::*; +use laravel::queue::{Queueable, job}; +use laravel::schedule::{self, Schedule}; +use serde_json::{Value, json}; + +use super::Role; +use super::invitations::{self, Invitee}; +use crate::models::User; +use crate::notify::outbox::AppUrl; +use crate::notify::{self, Kind, To}; + +pub fn routes(route: &mut Router) { + route.get("/api/ui/me", me); + route.patch("/api/ui/me/notifications", update_notifications); + route.post("/api/ui/me/heard-about", heard_about); + route.put("/api/ui/orgs/{org}/billing-email", update_billing_email); +} + +/// An answer to "How did you hear about VisualCI?". The keys are stored, so a label can change but a key can't. +#[derive(Clone, Copy, Debug, serde::Serialize)] +pub struct Choice { + pub key: &'static str, + /// On the card. + pub label: &'static str, + /// On /staff and in the admin tools: "AI assistant: Claude". + pub short_label: &'static str, + /// The text box's label, for the answers that have one. + pub detail_label: Option<&'static str>, +} + +pub const DETAIL_MAX: usize = 255; + +pub const OPTIONS: &[Choice] = &[ + Choice { + key: "search", + label: "Search engine", + short_label: "Search", + detail_label: Some("What did you search for?"), + }, + Choice { + key: "ai_assistant", + label: "AI Assistant (ChatGPT, Claude, etc.)", + short_label: "AI assistant", + detail_label: Some("Which one?"), + }, + Choice { key: "colleague", label: "Colleague or friend", short_label: "Colleague or friend", detail_label: None }, + Choice { + key: "article", + label: "Blog post or article", + short_label: "Blog post or article", + detail_label: Some("Which one?"), + }, + Choice { + key: "social", + label: "Social media (X, LinkedIn, Reddit, etc.)", + short_label: "Social media", + detail_label: Some("Which one?"), + }, + Choice { + key: "directory", + label: "Directory (MCP, software, etc.)", + short_label: "Directory", + detail_label: Some("Which one?"), + }, + Choice { key: "github", label: "GitHub", short_label: "GitHub", detail_label: None }, + Choice { key: "other", label: "Other", short_label: "Other", detail_label: Some("Where did you hear about us?") }, +]; + +/// What's stored: a key we offer (else nothing) and its detail as one clean line of at most 255 characters. An answer +/// we don't offer is dropped, never refused. +#[must_use] +pub fn clean(source: Option<&str>, detail: Option<&str>) -> (Option, Option) { + let Some(option) = source.and_then(|s| OPTIONS.iter().find(|o| o.key == s)) else { return (None, None) }; + let detail = detail + .map(|d| d.chars().map(|c| if c.is_control() { ' ' } else { c }).collect::()) + .map(|d| d.split_whitespace().collect::>().join(" ")) + .map(|d| d.chars().take(DETAIL_MAX).collect::()) + .filter(|d| !d.is_empty() && option.detail_label.is_some()); + (Some(option.key.to_string()), detail) +} + +/// "AI assistant: Claude", or `None` when there's no answer. +#[must_use] +pub fn summary(source: Option<&str>, detail: Option<&str>) -> Option { + let source = source.filter(|s| !s.is_empty())?; + let label = OPTIONS.iter().find(|o| o.key == source).map_or(source, |o| o.short_label); + Some(match detail.filter(|d| !d.is_empty()) { + Some(d) => format!("{label}: {d}"), + None => label.to_string(), + }) +} + +/// `GET /api/ui/me`. +/// The forges a person can sign in with here: those whose OAuth application has its ID and secret. +#[derive(Clone, laravel::config::Section)] +pub struct SignInApps { + #[env("GITHUB_CLIENT_ID")] + pub github_id: Option, + #[env("GITHUB_CLIENT_SECRET")] + pub github_secret: Option, + #[env("GITLAB_CLIENT_ID")] + pub gitlab_id: Option, + #[env("GITLAB_CLIENT_SECRET")] + pub gitlab_secret: Option, +} + +impl SignInApps { + #[must_use] + pub fn forges(&self) -> Vec<&'static str> { + let set = |v: &Option| v.as_deref().is_some_and(|s| !s.trim().is_empty()); + let mut forges = Vec::new(); + if set(&self.github_id) && set(&self.github_secret) { + forges.push("github"); + } + if set(&self.gitlab_id) && set(&self.gitlab_secret) { + forges.push("gitlab"); + } + forges + } +} + +pub async fn me( + Authenticated(user): Authenticated, + apps: laravel::config::Section, +) -> laravel::Result> { + let user_id = user.id; + let row = db::query!( + "SELECT staff, heard_about_pending, email_low_credits, email_receipts, \ + COALESCE((SELECT json_agg(json_build_object('forge', forge, 'login', login) ORDER BY id) \ + FROM identities WHERE user_id = {user_id}), '[]'::json)::text AS identities, \ + COALESCE((SELECT json_agg(json_build_object('slug', o.slug, 'name', o.name, 'role', m.role, 'usage', NULL) \ + ORDER BY o.name) FROM memberships m JOIN organizations o ON o.id = m.organization_id \ + WHERE m.user_id = {user_id}), '[]'::json)::text AS organizations \ + FROM users WHERE id = {user_id}" + ) + .select_one() + .await? + .ok_or_else(|| laravel::abort(401))?; + let identities: Value = serde_json::from_str(&row.try_get::("identities")?).unwrap_or_default(); + let organizations: Value = serde_json::from_str(&row.try_get::("organizations")?).unwrap_or_default(); + Ok(Json(json!({ + "user": { + "name": user.name, "email": user.email, "avatar_url": user.avatar_url, + "login": identities.get(0).and_then(|i| i.get("login")).cloned(), "identities": identities, + }, + "forges": apps.forges(), + "organizations": organizations, + "invitations": invitations::pending_for(&user).await?, + "staff": row.try_get::("staff")?, + // Ask "How did you hear about VisualCI?" (once, after sign-up), with these choices. + "heard_about_pending": row.try_get::("heard_about_pending")?, + "heard_about_options": OPTIONS, + // Emails people can turn off; security emails, billing problems and running out of credits always go. + "notifications": { + "low_credits": row.try_get::("email_low_credits")?, + "receipts": row.try_get::("email_receipts")?, + }, + }))) +} + +#[laravel::input] +#[validate(authenticated)] +pub struct NotificationsInput { + low_credits: Option, + receipts: Option, +} + +/// `PATCH /api/ui/me/notifications`: turn low-credit warnings or receipt-style emails on or off for yourself. +pub async fn update_notifications( + Authenticated(user): Authenticated, + Valid(p): Valid, +) -> laravel::Result> { + let (user_id, low_credits, receipts) = (user.id, p.low_credits, p.receipts); + let row = db::query!( + "UPDATE users SET email_low_credits = COALESCE({low_credits}, email_low_credits), \ + email_receipts = COALESCE({receipts}, email_receipts), updated_at = now() \ + WHERE id = {user_id} RETURNING email_low_credits, email_receipts" + ) + .select_one() + .await? + .ok_or_else(|| laravel::abort(401))?; + Ok(Json(json!({ + "low_credits": row.try_get::("email_low_credits")?, + "receipts": row.try_get::("email_receipts")?, + }))) +} + +#[laravel::input] +#[validate(authenticated)] +pub struct HeardAboutInput { + skip: Option, + source: Option, + detail: Option, +} + +/// `POST /api/ui/me/heard-about`: an answer, or Skip. Either way it isn't asked again, and the team's email about +/// the sign-up, which waits for it, goes out. +pub async fn heard_about( + Authenticated(user): Authenticated, + Valid(p): Valid, +) -> laravel::Result> { + let (source, detail) = if p.skip.unwrap_or(false) { + (None, None) + } else { + clean(p.source.as_ref().and_then(Value::as_str), p.detail.as_ref().and_then(Value::as_str)) + }; + let user_id = user.id; + db::query!( + "UPDATE users SET heard_about_pending = false, \ + heard_about_source = COALESCE({source}, heard_about_source), \ + heard_about_detail = CASE WHEN {source}::text IS NULL THEN heard_about_detail ELSE {detail} END, \ + updated_at = now() WHERE id = {user_id}" + ) + .update() + .await?; + NotifySignups.dispatch().await?; + Ok(Json(json!({ "ok": true }))) +} + +#[laravel::input] +#[validate(authenticated)] +pub struct BillingEmailInput { + /// Empty sends billing emails to the admins again. + #[validate(max_length(320))] + billing_email: Option, +} + +/// `PUT /api/ui/orgs/{org}/billing-email` (admins): where billing emails go instead of the admins. +pub async fn update_billing_email( + Authenticated(user): Authenticated, + Params(org): Params, + Valid(p): Valid, +) -> laravel::Result> { + let user_id = user.id; + let row = db::query!( + "SELECT o.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 = {org}" + ) + .select_one() + .await? + .ok_or_else(|| laravel::abort(404))?; + let org_id: i64 = row.try_get("id")?; + match row.try_get::>("role")?.as_deref().and_then(Role::parse) { + Some(Role::Admin) => {} + Some(_) => return Err(laravel::abort_with(403, "only admins can change the billing email")), + None => return Err(laravel::abort(404)), + } + let email = p.billing_email.as_deref().unwrap_or("").trim(); + if !email.is_empty() && !matches!(Invitee::parse(email), Ok(Invitee::Email(_))) { + return Err(laravel::abort_with(422, format!("{email:?} isn't an email address"))); + } + let email = (!email.is_empty()).then(|| email.to_lowercase()); + db::query!("UPDATE organizations SET billing_email = {email}, updated_at = now() WHERE id = {org_id}") + .update() + .await?; + Ok(Json(json!({ "billing_email": email }))) +} + +/// The team's address for sign-up emails. +#[derive(Clone, laravel::config::Section)] +pub struct Team { + #[env("VISUALCI_TEAM_EMAIL", default = "support@visualci.com")] + pub email: String, +} + +/// How long after sign-up the team's email waits for "How did you hear". +pub const WAIT_MINUTES: i64 = 10; + +/// The team's email's text: who, how they signed up and heard about VisualCI, their organizations, and anything they +/// asked for. +#[must_use] +pub fn signup_text( + who: &str, + signup_via: Option<&str>, + heard: &str, + orgs: &[String], + requests: &[String], + app_url: &str, +) -> String { + let mut lines = vec![ + format!("New sign-up: {who}"), + format!("Signed up with: {}", signup_via.unwrap_or("unknown")), + format!("Heard about VisualCI from: {heard}"), + ]; + for org in orgs { + lines.push(format!("Organization: {app_url}/{org}")); + } + if requests.is_empty() { + lines.push("They haven't asked for anything yet.".to_string()); + } else { + lines.push(String::new()); + lines.push("What they need from VisualCI:".to_string()); + for r in requests { + lines.push(String::new()); + lines.push(r.clone()); + } + } + lines.push(String::new()); + lines.push(format!("All sign-ups: {app_url}/staff. Replying to this email reaches them.")); + lines.join("\n") +} + +/// Queue the team's email about every sign-up that's ready (answered or skipped, or past the wait), up to 20 a run. +/// The outbox sends it (with retries, and its own heartbeat); the dedupe key makes a second run's copy a no-op. +/// Returns how many were queued. +/// +/// # Errors +/// On a database error. +pub async fn queue_signups(team: &Team, app_url: &str) -> laravel::Result { + let wait = WAIT_MINUTES; + let ready = db::query!( + "SELECT id, name, email, signup_via, heard_about_pending, heard_about_source, heard_about_detail, \ + (SELECT login FROM identities WHERE user_id = users.id ORDER BY id LIMIT 1) AS login \ + FROM users WHERE signup_notified_at IS NULL \ + AND (NOT heard_about_pending OR created_at < now() - make_interval(mins => {wait}::int)) \ + ORDER BY id LIMIT 20" + ) + .select() + .await?; + let app_url = app_url.trim_end_matches('/'); + let mut queued = 0; + for u in ready { + let id: i64 = u.try_get("id")?; + let (name, email): (String, String) = (u.try_get("name")?, u.try_get("email")?); + let login: Option = u.try_get("login")?; + let source: Option = u.try_get("heard_about_source")?; + let detail: Option = u.try_get("heard_about_detail")?; + let heard = match summary(source.as_deref(), detail.as_deref()) { + Some(s) => s, + None if u.try_get::("heard_about_pending")? => "not answered yet".to_string(), + None => "skipped".to_string(), + }; + let orgs: Vec = db::query!( + "SELECT o.slug FROM memberships m JOIN organizations o ON o.id = m.organization_id \ + WHERE m.user_id = {id} ORDER BY o.id" + ) + .select() + .await? + .iter() + .map(|r| r.try_get("slug")) + .collect::>()?; + let requests: Vec = + db::query!("SELECT description FROM feedback WHERE user_id = {id} AND kind = 'request' ORDER BY id") + .select() + .await? + .iter() + .map(|r| r.try_get("description")) + .collect::>()?; + let who = match &login { + Some(l) => format!("{name} (@{l}) <{email}>"), + None => format!("{name} <{email}>"), + }; + let signup_via: Option = u.try_get("signup_via")?; + let text = signup_text(&who, signup_via.as_deref(), &heard, &orgs, &requests, app_url); + let subject = format!("New VisualCI sign-up: {}", login.as_deref().unwrap_or(&name)); + let kind = Kind::NewSignup { subject, text, reply_to: email }; + notify::queue(&kind, To::Address(team.email.clone()), None, &format!("new_signup:{id}")).await?; + db::query!("UPDATE users SET signup_notified_at = now() WHERE id = {id}").update().await?; + queued += 1; + } + Ok(queued) +} + +/// How long a ready sign-up may wait before the heartbeat fails: the schedule runs every minute. +pub const STALE_MINUTES: i64 = 30; + +/// Queue the team's sign-up emails; pushes `VISUALCI_SIGNUPS_HEARTBEAT`, failing when one ready sign-up has waited +/// more than half an hour (the job stopped running, or keeps failing). +#[derive(Queueable, Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct NotifySignups; + +#[job] +impl NotifySignups { + async fn handle( + self, + team: laravel::config::Section, + app: laravel::config::Section, + ) -> laravel::Result<()> { + let result = queue_signups(&team, &app.url).await; + let stale = WAIT_MINUTES + STALE_MINUTES; + let waiting = db::query!( + "SELECT count(*) FROM users WHERE signup_notified_at IS NULL \ + AND created_at < now() - make_interval(mins => {stale}::int)" + ) + .scalar::() + .await; + // A database that can't answer fails the heartbeat too. + let health = match (&result, waiting) { + (Err(e), _) => Err(e.to_string()), + (Ok(_), Err(e)) => Err(e.to_string()), + (Ok(_), Ok(Some(n))) if n > 0 => { + Err(format!("{n} sign-ups waited over {stale} minutes for the team's email")) + } + _ => Ok(()), + }; + crate::heartbeat::push("VISUALCI_SIGNUPS_HEARTBEAT", health).await; + result.map(|_| ()) + } +} + +#[schedule::tasks] +fn schedule(schedule: &mut Schedule) { + schedule.job(NotifySignups).every_minute().without_overlapping(); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn answers_are_cleaned_and_summarised() { + assert_eq!( + clean(Some("ai_assistant"), Some(" Claude\n ")), + (Some("ai_assistant".into()), Some("Claude".into())) + ); + assert_eq!(clean(Some("colleague"), Some("Bob")), (Some("colleague".into()), None)); + assert_eq!(clean(Some("made-up"), Some("x")), (None, None)); + assert_eq!(summary(Some("ai_assistant"), Some("Claude")).as_deref(), Some("AI assistant: Claude")); + assert_eq!(summary(None, None), None); + } + + #[test] + fn the_team_email_says_who_how_and_what_they_asked_for() { + let text = signup_text( + "Ada (@ada) ", + Some("github, from an MCP client's sign-in"), + "AI assistant: Claude", + &["ada".into()], + &["Buildkite with Cypress".into()], + "https://app.visualci.com", + ); + assert!(text.contains("New sign-up: Ada (@ada) "), "{text}"); + assert!(text.contains("Signed up with: github, from an MCP client's sign-in")); + assert!(text.contains("Heard about VisualCI from: AI assistant: Claude")); + assert!(text.contains("Organization: https://app.visualci.com/ada")); + assert!(text.contains("Buildkite with Cypress")); + } +} diff --git a/app/src/auth/memberships.rs b/app/src/auth/memberships.rs index 38ac485e..4ea95108 100644 --- a/app/src/auth/memberships.rs +++ b/app/src/auth/memberships.rs @@ -21,6 +21,16 @@ pub struct MembershipChanged { pub organization_id: i64, pub user_id: i64, pub role: Option, + /// When the membership changed (milliseconds), fixed at dispatch: the notice's dedupe key, so a retried listener + /// doesn't send it twice. + pub changed_at: i64, +} + +impl MembershipChanged { + #[must_use] + pub fn now(organization_id: i64, user_id: i64, role: Option) -> Self { + Self { organization_id, user_id, role, changed_at: laravel::now().timestamp().as_millisecond() } + } } #[derive(Debug)] @@ -151,7 +161,7 @@ pub async fn apply( }) .await?; for (org, role) in ¬ices { - MembershipChanged { organization_id: *org, user_id, role: *role }.dispatch().await?; + MembershipChanged::now(*org, user_id, *role).dispatch().await?; } Ok(notices.len()) } diff --git a/app/src/auth/mod.rs b/app/src/auth/mod.rs index 6e1edfa9..17265aaf 100644 --- a/app/src/auth/mod.rs +++ b/app/src/auth/mod.rs @@ -8,9 +8,15 @@ //! //! Nobody found: `401`. +pub mod device; +pub mod invitations; +pub mod me; pub mod memberships; pub mod oauth; +pub mod orgs; pub mod sign_in; +pub mod staff; +pub mod tokens; use axum::extract::FromRequestParts; use axum::http::request::Parts; @@ -259,6 +265,13 @@ pub async fn whoami(principal: Principal) -> laravel::Result laravel::Result> { + let name = name.trim(); + if name.is_empty() || name.chars().count() > MAX_NAME { + return Ok(Err(format!("an organization's name is 1 to {MAX_NAME} characters"))); + } + if user.staff { + return Ok(Ok(())); + } + let user_id = user.id; + let row = db::query!( + "SELECT (SELECT count(*) FROM memberships WHERE user_id = {user_id} AND source = 'created' \ + AND created_at > now() - interval '24 hours') AS today, \ + (created_at > now() - interval '24 hours') AS new_account \ + FROM users WHERE id = {user_id}" + ) + .select_one() + .await? + .ok_or_else(|| laravel::abort(401))?; + let today: i64 = row.try_get("today")?; + // Their own organization, made at sign-up, doesn't count. + let personal = i64::from(today > 0 && row.try_get::("new_account")?); + if today - personal >= DAILY_CREATE_LIMIT { + return Ok(Err(format!( + "you've created {DAILY_CREATE_LIMIT} organizations in the last 24 hours, the limit; try again tomorrow, or \ + ask support@visualci.com for more" + ))); + } + Ok(Ok(())) +} + +#[laravel::input] +#[validate(authenticated)] +pub struct CreateInput { + #[validate(required, max_length(60))] + slug: String, + #[validate(required)] + name: String, +} + +/// `POST /api/ui/orgs`: a new organization with the person as its admin. +pub async fn create( + Authenticated(user): Authenticated, + Valid(p): Valid, +) -> laravel::Result> { + let slug = create_org(&user, &p.slug, &p.name).await?; + Ok(Json(json!({ "slug": slug }))) +} + +/// A new organization with `user` as its admin; returns its slug. Errors: 422 for a slug or name it refuses or over +/// the daily limit, 409 for a slug that's taken. +/// +/// # Errors +/// Those, and database errors. +pub async fn create_org(user: &User, slug: &str, name: &str) -> laravel::Result { + let p = CreateInput { slug: slug.to_string(), name: name.to_string() }; + if !valid_slug(&p.slug) { + return Err(laravel::abort_with( + 422, + "slugs use lowercase letters, digits and dashes, and can't be a reserved word such as account or api", + )); + } + if let Err(e) = may_create(user, &p.name).await? { + return Err(laravel::abort_with(422, e)); + } + let (slug, name, user_id) = (p.slug, p.name.trim().to_string(), user.id); + let created = db::transaction(async |tx| { + let org: Option = db::query!( + tx, + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) \ + VALUES (gen_random_uuid(), {slug}, {name}, now(), now()) ON CONFLICT (slug) DO NOTHING RETURNING id" + ) + .scalar() + .await?; + if let Some(org) = org { + db::query!( + tx, + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org}, {user_id}, 'admin', 'created', now(), now())" + ) + .insert() + .await?; + } + Ok(org) + }) + .await?; + if created.is_none() { + return Err(laravel::abort_with(409, "that slug is taken")); + } + Ok(slug) +} diff --git a/app/src/auth/sign_in.rs b/app/src/auth/sign_in.rs index 44edbfd1..5eed8d59 100644 --- a/app/src/auth/sign_in.rs +++ b/app/src/auth/sign_in.rs @@ -379,7 +379,7 @@ async fn new_user(id: &Identity) -> laravel::Result { .cloned() .unwrap_or_else(|| format!("{}+{}@users.noreply.{}.visualci.com", id.id, id.login, id.forge.as_str())); let verified = (!id.trusted_emails().is_empty()).then(laravel::now); - create!(User { + let user = create!(User { pid: laravel::str::uuid7(), name: id.name.clone().unwrap_or_else(|| id.login.clone()), email: email, @@ -387,7 +387,11 @@ async fn new_user(id: &Identity) -> laravel::Result { avatar_url: id.avatar_url.clone(), staff: false, }) - .await + .await?; + // "How did you hear about VisualCI?" is asked once, after sign-up; the team's email waits for it + let user_id = user.id; + db::query!("UPDATE users SET heard_about_pending = true WHERE id = {user_id}").update().await?; + Ok(user) } async fn record_waitlist(id: &Identity, source: &str) -> laravel::Result<()> { diff --git a/app/src/auth/staff.rs b/app/src/auth/staff.rs new file mode 100644 index 00000000..18b56f6a --- /dev/null +++ b/app/src/auth/staff.rs @@ -0,0 +1,130 @@ +//! Staff pages on the auth and emails side (sc-8900), ported from today's server: the latest sign-ups, every email +//! VisualCI sends rendered with sample data, and failed emails to retry or dismiss. Anyone who isn't staff gets a 404. + +use laravel::auth::Authenticated; +use laravel::db; +use laravel::prelude::*; +use serde_json::{Value, json}; + +use super::me::summary; +use crate::models::User; +use crate::notify::outbox::AppUrl; +use crate::notify::{About, DeliverEmails, render, render::samples}; + +pub fn routes(route: &mut Router) { + route.get("/api/ui/staff/signups", signups); + route.get("/api/ui/staff/emails", emails); + route.post("/api/ui/staff/emails/{id}/resolve", resolve); +} + +fn staff_only(user: &User) -> laravel::Result<()> { + if user.staff { Ok(()) } else { Err(laravel::abort(404)) } +} + +const TIME: &str = "YYYY-MM-DD\"T\"HH24:MI:SS\"Z\""; + +/// `GET /api/ui/staff/signups`: the latest 100 people, newest first, with how they heard about VisualCI. +pub async fn signups(Authenticated(user): Authenticated) -> laravel::Result> { + staff_only(&user)?; + let rows = db::query!( + "SELECT name, email, heard_about_source, heard_about_detail, \ + to_char(created_at AT TIME ZONE 'UTC', {TIME}) AS created_at, \ + (SELECT login FROM identities WHERE user_id = users.id ORDER BY id LIMIT 1) AS login \ + FROM users ORDER BY id DESC LIMIT 100" + ) + .select() + .await?; + let mut list = Vec::new(); + for r in rows { + let (source, detail): (Option, Option) = + (r.try_get("heard_about_source")?, r.try_get("heard_about_detail")?); + list.push(json!({ + "name": r.try_get::("name")?, "email": r.try_get::("email")?, + "login": r.try_get::>("login")?, "created_at": r.try_get::("created_at")?, + "heard_about": summary(source.as_deref(), detail.as_deref()), + })); + } + Ok(Json(json!({ "signups": list }))) +} + +/// `GET /api/ui/staff/emails`: every email rendered with sample data (for Acme), and the failed ones nobody has +/// retried or dismissed yet, newest first. +pub async fn emails( + Authenticated(user): Authenticated, + app: laravel::config::Section, +) -> laravel::Result> { + staff_only(&user)?; + let about = About { org_name: "Acme", org_slug: "acme", app_url: app.url.trim_end_matches('/') }; + let list: Vec = samples() + .into_iter() + .map(|(label, kind)| { + let r = render(&kind, &about); + json!({ + "label": label, "kind": kind.name(), "subject": r.subject, "text": r.text, "html": r.html, + "can_turn_off": kind.preference().is_some(), + }) + }) + .collect(); + let rows = db::query!( + "SELECT e.id, e.kind, e.recipient, e.attempts, e.last_error, o.slug AS org, \ + to_char(e.created_at AT TIME ZONE 'UTC', {TIME}) AS created_at, \ + to_char(e.updated_at AT TIME ZONE 'UTC', {TIME}) AS failed_at \ + FROM emails e LEFT JOIN organizations o ON o.id = e.organization_id \ + WHERE e.state = 'failed' AND e.dismissed_at IS NULL ORDER BY e.id DESC LIMIT 100" + ) + .select() + .await?; + let mut failed = Vec::new(); + for r in rows { + failed.push(json!({ + "id": r.try_get::("id")?, "kind": r.try_get::("kind")?, + "recipient": r.try_get::("recipient")?, "org": r.try_get::>("org")?, + "attempts": r.try_get::("attempts")?, "last_error": r.try_get::>("last_error")?, + "created_at": r.try_get::("created_at")?, "failed_at": r.try_get::("failed_at")?, + })); + } + Ok(Json(json!({ "emails": list, "failed": failed }))) +} + +#[laravel::input] +#[validate(authenticated)] +pub struct ResolveInput { + /// `retry` or `dismiss`. + #[validate(required)] + action: String, +} + +/// `POST /api/ui/staff/emails/{id}/resolve`: retry a failed email (sent again from scratch) or dismiss it. Either way +/// it stops counting in `/status`'s `emails_failed_unresolved`. 404 when there's no such failed, undismissed email. +pub async fn resolve( + Authenticated(user): Authenticated, + Params(id): Params, + Valid(p): Valid, +) -> laravel::Result> { + staff_only(&user)?; + let done: Option = match p.action.as_str() { + "retry" => { + db::query!( + "UPDATE emails SET state = 'pending', attempts = 0, claimed_at = NULL, updated_at = now() \ + WHERE id = {id} AND state = 'failed' AND dismissed_at IS NULL RETURNING id" + ) + .scalar() + .await? + } + "dismiss" => { + db::query!( + "UPDATE emails SET dismissed_at = now(), updated_at = now() \ + WHERE id = {id} AND state = 'failed' AND dismissed_at IS NULL RETURNING id" + ) + .scalar() + .await? + } + _ => return Err(laravel::abort_with(422, "action is retry or dismiss")), + }; + done.ok_or_else(|| laravel::abort(404))?; + tracing::info!(email_id = id, action = %p.action, staff = user.id, "staff resolved a failed email"); + if p.action == "retry" { + DeliverEmails.dispatch().await?; + } + Ok(Json(json!({ "id": id }))) +} diff --git a/app/src/auth/tokens.rs b/app/src/auth/tokens.rs new file mode 100644 index 00000000..9448fa02 --- /dev/null +++ b/app/src/auth/tokens.rs @@ -0,0 +1,186 @@ +//! Personal and project tokens in the web app (sc-8900, the auth side), ported from today's server: a person's own +//! tokens (`vcu_…`, for the MCP server and scripts) and a project's (`vci_…`, CI's, for its admins). A token is shown +//! once, when it's made; only its SHA-256 and its first characters are kept. Making one emails a security notice. + +use laravel::auth::Authenticated; +use laravel::db; +use laravel::prelude::*; +use serde_json::{Value, json}; + +use super::Role; +use crate::models::{User, token_hash}; +use crate::notify::{self, Kind, To}; + +pub fn routes(route: &mut Router) { + route.get("/api/ui/me/tokens", list_user_tokens); + route.post("/api/ui/me/tokens", create_user_token); + route.delete("/api/ui/me/tokens/{id}", delete_user_token); + route.post("/api/ui/orgs/{org}/projects/{project}/tokens", create_project_token); + route.delete("/api/ui/orgs/{org}/projects/{project}/tokens/{id}", delete_project_token); +} + +/// The security notice for a token just made, once per token. The token exists by now and is about to be shown, its +/// only showing: a notice that can't be queued is logged, never allowed to lose it. +async fn notice(kind: &Kind, user_id: i64, org_id: Option, key: &str) { + if let Err(e) = notify::queue(kind, To::User(user_id), org_id, key).await { + tracing::error!(user_id, key, error = %e, "a token's security notice wasn't queued"); + } +} + +/// A new token: the prefix and 40 letters and digits. Returns it, its hash and what's shown of it. +pub(crate) fn generate(prefix: &str) -> (String, String, String) { + let token = format!("{prefix}{}", laravel::str::random(40)); + let shown = token[..prefix.len() + 6].to_string(); + (token.clone(), token_hash(&token), shown) +} + +#[laravel::input] +#[validate(authenticated)] +pub struct CreateToken { + #[validate(required, max_length(100))] + name: String, +} + +/// The signed-in person's personal tokens. +pub async fn list_user_tokens(Authenticated(user): Authenticated) -> laravel::Result> { + let user_id = user.id; + let rows = db::query!( + "SELECT id, name, token_prefix, to_char(last_used_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"') AS last_used_at, \ + to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"') AS created_at \ + FROM user_tokens WHERE user_id = {user_id} ORDER BY id" + ) + .select() + .await?; + let tokens: Vec = rows + .iter() + .map(|r| { + Ok(json!({ + "id": r.try_get::("id")?, + "name": r.try_get::("name")?, + "prefix": r.try_get::("token_prefix")?, + "last_used_at": r.try_get::>("last_used_at")?, + "created_at": r.try_get::("created_at")?, + })) + }) + .collect::>()?; + Ok(Json(json!({ "tokens": tokens }))) +} + +/// A new personal token for `user_id`, named `name`, and its id. Only its hash is stored, so this is the one time +/// it's seen. +/// +/// # Errors +/// On a database error. +pub async fn make_user_token(user_id: i64, name: &str) -> laravel::Result<(String, i64)> { + let (token, hash, shown) = generate("vcu_"); + let id: i64 = db::query!( + "INSERT INTO user_tokens (user_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({user_id}, {name}, {hash}, {shown}, now(), now()) RETURNING id" + ) + .scalar() + .await? + .ok_or_else(|| laravel::Error::msg("no token id"))?; + Ok((token, id)) +} + +/// Make a personal token. It's shown once. +pub async fn create_user_token( + Authenticated(user): Authenticated, + Valid(p): Valid, +) -> laravel::Result> { + let name = p.name.trim().to_string(); + if name.is_empty() { + return Err(laravel::abort_with(422, "give the token a name")); + } + let user_id = user.id; + let (token, id) = make_user_token(user_id, &name).await?; + let kind = Kind::TokenCreated { name: name.clone(), project: None }; + notice(&kind, user_id, None, &format!("token_created:user:{id}")).await; + Ok(Json(json!({ "token": token }))) +} + +/// Delete one of the signed-in person's tokens (anyone else's is left alone). +pub async fn delete_user_token( + Authenticated(user): Authenticated, + Params(id): Params, +) -> laravel::Result> { + let user_id = user.id; + db::query!("DELETE FROM user_tokens WHERE id = {id} AND user_id = {user_id}").delete().await?; + Ok(Json(json!({ "ok": true }))) +} + +/// The project, with its organization, when the person is an admin there. A member gets a 403, anyone else a 404. +async fn admin_project(user: &User, org: &str, project: &str, action: &str) -> laravel::Result<(i64, i64, String)> { + let user_id = user.id; + let row = db::query!( + "SELECT p.id, p.organization_id, p.slug, m.role FROM projects p JOIN organizations o ON o.id = p.organization_id \ + LEFT JOIN memberships m ON m.organization_id = o.id AND m.user_id = {user_id} \ + WHERE o.slug = {org} AND p.slug = {project}" + ) + .select_one() + .await? + .ok_or_else(|| laravel::abort(404))?; + match row.try_get::>("role")?.as_deref().and_then(Role::parse) { + Some(Role::Admin) => Ok((row.try_get("id")?, row.try_get("organization_id")?, row.try_get("slug")?)), + Some(_) => Err(laravel::abort_with(403, format!("only admins can {action}"))), + None => Err(laravel::abort(404)), + } +} + +/// Make a project token (admins). It's shown once; the person who made it gets a security notice. +pub async fn create_project_token( + Authenticated(user): Authenticated, + Params((org, project)): Params<(String, String)>, + Valid(p): Valid, +) -> laravel::Result> { + let (project_id, _, _) = admin_project(&user, &org, &project, "create project tokens").await?; + let (token, _) = make_project_token(&user, project_id, p.name.trim()).await?; + Ok(Json(json!({ "token": token }))) +} + +/// A new token for project `project_id`, made by `by`, and its id. It's shown once: only its hash is stored. `by` gets +/// a security notice. The caller checks that `by` is an admin of the project's organization. +/// +/// # Errors +/// On a database error, or when there's no such project. +pub async fn make_project_token(by: &User, project_id: i64, name: &str) -> laravel::Result<(String, i64)> { + let row = db::query!("SELECT organization_id, slug FROM projects WHERE id = {project_id}") + .select_one() + .await? + .ok_or_else(|| laravel::abort(404))?; + let (org_id, project_slug): (i64, String) = (row.try_get("organization_id")?, row.try_get("slug")?); + let name = name.trim().to_string(); + let (token, hash, shown) = generate("vci_"); + let id: i64 = db::query!( + "INSERT INTO project_tokens (project_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({project_id}, {name}, {hash}, {shown}, now(), now()) RETURNING id" + ) + .scalar() + .await? + .ok_or_else(|| laravel::Error::msg("no token id"))?; + let kind = Kind::TokenCreated { name, project: Some(project_slug) }; + notice(&kind, by.id, Some(org_id), &format!("token_created:project:{id}")).await; + Ok((token, id)) +} + +/// Delete a project token (admins). +pub async fn delete_project_token( + Authenticated(user): Authenticated, + Params((org, project, id)): Params<(String, String, i64)>, +) -> laravel::Result> { + let (project_id, _, _) = admin_project(&user, &org, &project, "delete project tokens").await?; + remove_project_token(project_id, id).await?; + Ok(Json(json!({ "ok": true }))) +} + +/// Delete project `project_id`'s token `id`; `false` when it has no such token. The caller checks the person may. +/// +/// # Errors +/// On a database error. +pub async fn remove_project_token(project_id: i64, id: i64) -> laravel::Result { + let deleted: Option = + db::query!("DELETE FROM project_tokens WHERE id = {id} AND project_id = {project_id} RETURNING id") + .scalar() + .await?; + Ok(deleted.is_some()) +} diff --git a/app/src/billing/mod.rs b/app/src/billing/mod.rs new file mode 100644 index 00000000..497029ed --- /dev/null +++ b/app/src/billing/mod.rs @@ -0,0 +1,127 @@ +//! Billing (sc-8900, the billing side; ported from today's server as it moves over). For now, the credit pack the +//! emails quote. + +/// A pack of credits bought on top of a plan. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CreditPack { + pub credits: i64, + pub price_cents: i64, + /// Automatic packs buy one when the balance falls below this. + pub reload_below: i64, +} + +/// Most automatic reloads an organization can allow in a month. +pub const MAX_AUTO_RELOAD_PACKS: i32 = 50; + +/// One pack: 500,000 credits for $15, as today. +pub const CREDIT_PACK: CreditPack = CreditPack { credits: 500_000, price_cents: 1_500, reload_below: 100_000 }; + +pub mod routes; +pub mod stripe; +pub mod webhook; + +/// A plan an organization can be on. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Plan { + pub id: &'static str, + pub name: &'static str, + /// US cents per month. + pub price_cents: i64, + /// Credits included each calendar month (UTC). + pub included_credits: i64, + /// Whether the organization can buy credit packs past the allowance. + pub credit_packs: bool, + /// No allowance or limit at all: builds never stop for credits. + pub unlimited: bool, +} + +pub const FREE: Plan = + Plan { id: "free", name: "Free", price_cents: 0, included_credits: 25_000, credit_packs: false, unlimited: false }; +pub const TEAM: Plan = Plan { + id: "team", + name: "Team", + price_cents: 2_900, + included_credits: 1_000_000, + credit_packs: true, + unlimited: false, +}; +/// DocSpring's own organizations: unlimited, free, and never offered. +pub const STAFF: Plan = + Plan { id: "staff", name: "Staff", price_cents: 0, included_credits: 0, credit_packs: false, unlimited: true }; + +/// The plan with this id (an organization's `plan` column). Anything unknown is Free. +#[must_use] +pub fn plan_by_id(id: &str) -> 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/forge/events.rs b/app/src/forge/events.rs new file mode 100644 index 00000000..ae1f4d4d --- /dev/null +++ b/app/src/forge/events.rs @@ -0,0 +1,38 @@ +//! What a forge's webhook tells the domain (sc-8900, the seam with visualci features): one event per linked project, +//! dispatched by `forge::webhooks`, with the domain's listeners doing the work. Every event may arrive twice (a forge +//! retries a delivery), so listeners must be idempotent. + +use serde::{Deserialize, Serialize}; + +/// A pull request merged: its approvals become the base branch's at the merge commit (`baselines::record_merge`). +#[derive(laravel::event::Event, Clone, Debug, Serialize, Deserialize)] +pub struct PullRequestMerged { + pub project_id: i64, + pub head: String, + pub base: String, + pub merge_commit: String, +} + +/// A pull request closed without merging (`why` "pull_request"), or its branch deleted ("branch_deleted"): the +/// branch's builds waiting for review stop waiting. +#[derive(laravel::event::Event, Clone, Debug, Serialize, Deserialize)] +pub struct BranchClosed { + pub project_id: i64, + pub branch: String, + pub why: String, +} + +/// A closed pull request reopened: its branch's newest closed build waits for review again. +#[derive(laravel::event::Event, Clone, Debug, Serialize, Deserialize)] +pub struct BranchReopened { + pub project_id: i64, + pub branch: String, +} + +/// The repository was made private (`private`), or public or edited: the project's open source status is checked +/// again (when private, GitHub's word is enough). +#[derive(laravel::event::Event, Clone, Debug, Serialize, Deserialize)] +pub struct RepositoryVisibilityChanged { + pub project_id: i64, + pub private: bool, +} diff --git a/app/src/forge/github_app.rs b/app/src/forge/github_app.rs new file mode 100644 index 00000000..9da5047a --- /dev/null +++ b/app/src/forge/github_app.rs @@ -0,0 +1,208 @@ +//! The VisualCI GitHub App acting as itself (sc-8900, the forge side), ported from today's server: a JWT signed with +//! the App's private key, installation tokens, and a person's permission on a repository through an installation. +//! Its webhook is in `forge::webhooks`. + +use laravel::http::client; +use serde_json::Value; + +use super::Permission; + +const API: &str = "https://api.github.com"; + +/// The App (`GITHUB_APP_ID`, `GITHUB_APP_PRIVATE_KEY_BASE64`: its PEM key, base64-encoded to fit one line) and its +/// webhook's secret (`GITHUB_WEBHOOK_SECRET`). Without the secret, the webhook answers 404. +#[derive(Clone, laravel::config::Section)] +pub struct GithubApp { + #[env("GITHUB_APP_ID")] + pub app_id: Option, + #[env("GITHUB_APP_PRIVATE_KEY_BASE64")] + pub private_key_base64: Option, + #[env("GITHUB_WEBHOOK_SECRET")] + pub webhook_secret: Option, +} + +fn err(e: impl std::fmt::Display) -> laravel::Error { + laravel::Error::msg(format!("GitHub: {e}")) +} + +#[derive(serde::Serialize)] +struct AppClaims { + iat: i64, + exp: i64, + iss: String, +} + +/// A JWT that authenticates as the App itself, for nine minutes. +fn app_jwt(app: &GithubApp) -> laravel::Result { + use base64::Engine; + let (Some(id), Some(key)) = (app.app_id.as_deref(), app.private_key_base64.as_deref()) else { + return Err(err("the GitHub App isn't configured (GITHUB_APP_ID, GITHUB_APP_PRIVATE_KEY_BASE64)")); + }; + let now = laravel::now().timestamp().as_second(); + let claims = AppClaims { iat: now - 60, exp: now + 540, iss: id.to_string() }; + let pem = base64::engine::general_purpose::STANDARD + .decode(key.trim()) + .map_err(|e| err(format!("the App's private key isn't base64: {e}")))?; + let key = jsonwebtoken::EncodingKey::from_rsa_pem(&pem).map_err(err)?; + jsonwebtoken::encode(&jsonwebtoken::Header::new(jsonwebtoken::Algorithm::RS256), &claims, &key).map_err(err) +} + +/// GET a GitHub API path as JSON; `None` on 404. +async fn get(token: &str, path: &str) -> laravel::Result> { + let response = client::get(format!("{API}{path}")) + .token(token) + .header("accept", "application/vnd.github+json") + .header("user-agent", "visualci") + .await?; + if response.status() == 404 { + return Ok(None); + } + if !response.successful() { + return Err(err(format!("GET {path}: HTTP {}", response.status()))); + } + Ok(Some(response.json()?)) +} + +/// A token for one of the App's installations. +/// +/// # Errors +/// When the App isn't configured, or GitHub refuses its credentials. +pub async fn installation_token(app: &GithubApp, installation: &str) -> laravel::Result { + let response = client::post(format!("{API}/app/installations/{installation}/access_tokens")) + .token(app_jwt(app)?) + .header("accept", "application/vnd.github+json") + .header("user-agent", "visualci") + .await?; + if !response.successful() { + return Err(err(format!("installation token: HTTP {}", response.status()))); + } + let body: Value = response.json()?; + body["token"].as_str().map(str::to_string).ok_or_else(|| err("an installation token response without a token")) +} + +/// Whether the App's installation `id` exists (a delivery can be stale, or redelivered after the installation went). +/// +/// # Errors +/// When the App isn't configured, or GitHub can't be reached or refuses. +pub async fn installation_exists(app: &GithubApp, id: &str) -> laravel::Result { + if !id.bytes().all(|b| b.is_ascii_digit()) { + return Ok(false); + } + Ok(get(&app_jwt(app)?, &format!("/app/installations/{id}")).await?.is_some()) +} + +/// Below this many API calls left in the hour, a recheck stops instead of using up what webhooks and checks need. +pub const RATE_LIMIT_RESERVE: i64 = 500; + +/// Every collaborator on a repository (`owner/name`) with their permission, keyed by GitHub user ID: direct +/// collaborators, team members and organization members with access, as `affiliation=all` lists them. Public +/// visibility gives nobody a place on it. `Err` when it can't be read completely (a partial list would drop people); +/// also when GitHub's rate limit is down to [`RATE_LIMIT_RESERVE`]. +/// +/// # Errors +/// Those. +pub async fn collaborators(token: &str, repo: &str) -> laravel::Result> { + let mut out = Vec::new(); + for page in 1..=50 { + let response = client::get(format!("{API}/repos/{repo}/collaborators")) + .token(token) + .header("accept", "application/vnd.github+json") + .header("user-agent", "visualci") + .query([("affiliation", "all".to_string()), ("per_page", "100".to_string()), ("page", page.to_string())]) + .await?; + if !response.successful() { + return Err(err(format!("GET /repos/{repo}/collaborators: HTTP {}", response.status()))); + } + let remaining = response.header("x-ratelimit-remaining").and_then(|v| v.parse::().ok()); + let list: Vec = response.json()?; + let done = list.len() < 100; + for c in &list { + let (Some(id), Some(permission)) = ( + c["id"].as_i64(), + c["role_name"].as_str().and_then(permission_from).or_else(|| permission_from_flags(&c["permissions"])), + ) else { + continue; + }; + out.push((id.to_string(), permission)); + } + if remaining.is_some_and(|r| r < RATE_LIMIT_RESERVE) { + return Err(err(format!("the rate limit is down to {} calls", remaining.unwrap_or(0)))); + } + if done { + return Ok(out); + } + } + Err(err(format!("{repo} has more than 5,000 collaborators"))) +} + +/// The highest permission in a `permissions` object (`{admin, maintain, push, triage, pull}`). +fn permission_from_flags(flags: &Value) -> Option { + [ + ("admin", Permission::Admin), + ("maintain", Permission::Maintain), + ("push", Permission::Write), + ("triage", Permission::Triage), + ("pull", Permission::Read), + ] + .into_iter() + .find(|(flag, _)| flags[*flag] == true) + .map(|(_, p)| p) +} + +/// A repository's `owner/name` now, by its permanent ID (`None` when the installation can't see it). +/// +/// # Errors +/// When GitHub can't be reached or refuses. +pub async fn repository_path(token: &str, id: &str) -> laravel::Result> { + if !id.bytes().all(|b| b.is_ascii_digit()) { + return Ok(None); + } + Ok(get(token, &format!("/repositories/{id}")).await?.and_then(|v| v["full_name"].as_str().map(str::to_string))) +} + +/// GitHub's role name for a collaborator (`admin`, `maintain`, `write`, `triage`, `read`). +fn permission_from(role: &str) -> Option { + match role { + "admin" => Some(Permission::Admin), + "maintain" => Some(Permission::Maintain), + "write" | "push" => Some(Permission::Write), + "triage" => Some(Permission::Triage), + "read" | "pull" => Some(Permission::Read), + _ => None, + } +} + +/// A person's permission on a repository (`owner/name`) through an installation (organization base permission, +/// teams and direct access all count), from their permanent GitHub ID. Only for collaborators: on a public repository +/// GitHub answers `read` for anyone, which would make every GitHub user a member of every organization linking one. +/// +/// # Errors +/// When GitHub can't be reached or refuses. +pub async fn permission( + app: &GithubApp, + repo: &str, + installation: &str, + user_id: &str, +) -> laravel::Result> { + let token = installation_token(app, installation).await?; + // The account's login now, from its permanent ID: a stored login may have been renamed and taken. + let Ok(id) = user_id.parse::() else { return Ok(None) }; + let Some(user) = get(&token, &format!("/user/{id}")).await? else { return Ok(None) }; + let Some(login) = user["login"].as_str() else { return Ok(None) }; + // 204 when they're a collaborator (directly, through a team, or by the organization's base permission), 404 not + let collaborator = client::get(format!("{API}/repos/{repo}/collaborators/{login}")) + .token(&token) + .header("accept", "application/vnd.github+json") + .header("user-agent", "visualci") + .await?; + match collaborator.status().as_u16() { + 204 | 200 => {} + 404 => return Ok(None), + s => return Err(err(format!("GET /repos/{repo}/collaborators/{login}: HTTP {s}"))), + } + let Some(v) = get(&token, &format!("/repos/{repo}/collaborators/{login}/permission")).await? else { + return Ok(None); + }; + // `role_name` says maintain and triage, which `permission` folds into write and read + Ok(v["role_name"].as_str().and_then(permission_from).or_else(|| v["permission"].as_str().and_then(permission_from))) +} diff --git a/app/src/forge/mod.rs b/app/src/forge/mod.rs index e2937e7e..d0f62216 100644 --- a/app/src/forge/mod.rs +++ b/app/src/forge/mod.rs @@ -2,8 +2,11 @@ //! side). These are the forge-neutral types: kinds, permissions, repository URLs, and what a sign-in learns. Each //! forge's API calls are in its own module. +pub mod events; pub mod github; +pub mod github_app; pub mod gitlab; +pub mod webhooks; use crate::auth::Role; diff --git a/app/src/forge/webhooks.rs b/app/src/forge/webhooks.rs new file mode 100644 index 00000000..35d0d3a2 --- /dev/null +++ b/app/src/forge/webhooks.rs @@ -0,0 +1,459 @@ +//! The GitHub App's webhook, `POST /webhooks/github` on the API host (sc-8900, the forge side), ported from today's +//! server. A delivery is checked against `X-Hub-Signature-256` and read into a [`ForgeEvent`]: +//! +//! - merges, closed or reopened pull requests, deleted branches and repository visibility changes are dispatched to +//! the domain as `forge::events`, once per linked project; +//! - installation changes attach or detach the App's installation on linked projects, so checks stop without errors, +//! and recheck the access of the people whose memberships those organizations' repositories decide; +//! - membership changes (collaborators, teams, organization members) recheck the people they name ([`RecheckAccess`]). +//! +//! Every event is safe to receive twice. GitLab's project hooks come with the self-managed instances' port. + +use std::collections::{HashMap, HashSet}; + +use hmac::{Hmac, Mac}; +use laravel::db; +use laravel::prelude::*; +use laravel::queue::{Queueable, job}; +use serde_json::{Value, json}; +use sha2::Sha256; + +use super::events::{BranchClosed, BranchReopened, PullRequestMerged, RepositoryVisibilityChanged}; +use super::github_app::{self, GithubApp}; +use super::{ForgeKind, Permission, Repository}; + +/// One delivery, as VisualCI acts on it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ForgeEvent { + Merged { + repository: Repository, + head: String, + base: String, + merge_commit: String, + }, + Closed { + repository: Repository, + branch: String, + why: &'static str, + }, + Reopened { + repository: Repository, + branch: String, + }, + /// The App was installed on these repositories (`installation` set) or removed from them (`None`). + Installation { + installation: Option, + previous: Option, + repositories: Vec, + }, + /// These people's access may have changed (GitHub user IDs). + Access { + people: Vec, + }, + /// Anyone's access through this installation may have changed (a team's repositories changed). + AccessAll { + installation: String, + }, + RepositoryChanged { + repository: Repository, + private: bool, + }, + /// Renamed or transferred: the same repository (by ID) at a new URL. + Moved { + repository: Repository, + }, + Ignored, +} + +/// `X-Hub-Signature-256`: `sha256=` and the body's HMAC-SHA256 under the webhook's secret, compared in constant time. +#[must_use] +pub fn signed(secret: &str, header: &str, body: &[u8]) -> bool { + let Some(hex_sig) = header.strip_prefix("sha256=") else { return false }; + let Ok(sig) = hex::decode(hex_sig) else { return false }; + let Ok(mut mac) = Hmac::::new_from_slice(secret.as_bytes()) else { return false }; + mac.update(body); + mac.verify_slice(&sig).is_ok() +} + +fn repositories(list: &Value) -> Vec { + list.as_array() + .map(|l| { + l.iter() + .filter_map(|r| { + let id = r["id"].as_i64().map(|i| i.to_string()); + r["full_name"].as_str().and_then(Repository::parse).map(|repo| repo.with_id(id)) + }) + .collect() + }) + .unwrap_or_default() +} + +/// The repository an event names, with GitHub's ID for it (which survives a rename). +fn repository(event: &Value) -> Option { + event["repository"]["full_name"] + .as_str() + .and_then(Repository::parse) + .map(|r| r.with_id(event["repository"]["id"].as_i64().map(|i| i.to_string()))) +} + +/// A pull request's branch: a fork's goes by its head label (`octocat:main`), as the CLI names it, so a fork's `main` +/// isn't taken for the base repository's. +fn pr_branch(event: &Value) -> Option<&str> { + let pr = &event["pull_request"]; + let head_repo = pr["head"]["repo"]["full_name"].as_str(); + let from_fork = head_repo.is_some() && head_repo != event["repository"]["full_name"].as_str(); + if from_fork { pr["head"]["label"].as_str() } else { pr["head"]["ref"].as_str() } +} + +fn deleted_branch(event: &Value, branch: Option<&str>) -> ForgeEvent { + match (repository(event), branch) { + (Some(repository), Some(branch)) => { + ForgeEvent::Closed { repository, branch: branch.to_string(), why: "branch_deleted" } + } + _ => ForgeEvent::Ignored, + } +} + +/// One delivery (`X-GitHub-Event` and its body) as a [`ForgeEvent`]. +/// +/// # Errors +/// A message for a merged pull request without its branches or merge commit. +pub fn read_event(kind: &str, event: &Value) -> Result { + let action = event["action"].as_str().unwrap_or_default(); + let installation = event["installation"]["id"].as_i64().map(|i| i.to_string()); + let person = |v: &Value| v["id"].as_i64().map(|i| vec![i.to_string()]).unwrap_or_default(); + Ok(match (kind, action) { + ("pull_request", "closed") if event["pull_request"]["merged"] == true => { + let pr = &event["pull_request"]; + let (Some(repository), Some(head), Some(base), Some(merge)) = + (repository(event), pr_branch(event), pr["base"]["ref"].as_str(), pr["merge_commit_sha"].as_str()) + else { + return Err("a merged pull request without its branches or merge commit".into()); + }; + ForgeEvent::Merged { + repository, + head: head.to_string(), + base: base.to_string(), + merge_commit: merge.to_string(), + } + } + ("pull_request", "closed" | "reopened") => match (repository(event), pr_branch(event)) { + (Some(repository), Some(branch)) if action == "closed" => { + ForgeEvent::Closed { repository, branch: branch.to_string(), why: "pull_request" } + } + (Some(repository), Some(branch)) => ForgeEvent::Reopened { repository, branch: branch.to_string() }, + _ => ForgeEvent::Ignored, + }, + // A branch deleted: GitHub sends `delete` (ref_type branch) and a `push` with `deleted: true` + ("delete", _) if event["ref_type"] == "branch" => deleted_branch(event, event["ref"].as_str()), + ("push", _) if event["deleted"] == true => { + deleted_branch(event, event["ref"].as_str().and_then(|r| r.strip_prefix("refs/heads/"))) + } + ("installation", "created" | "unsuspend") => ForgeEvent::Installation { + installation, + previous: None, + repositories: repositories(&event["repositories"]), + }, + ("installation", "deleted" | "suspend") => ForgeEvent::Installation { + installation: None, + previous: installation, + repositories: repositories(&event["repositories"]), + }, + ("installation_repositories", "added") => ForgeEvent::Installation { + installation, + previous: None, + repositories: repositories(&event["repositories_added"]), + }, + ("installation_repositories", "removed") => ForgeEvent::Installation { + installation: None, + previous: installation, + repositories: repositories(&event["repositories_removed"]), + }, + // Made public or private, or edited: projects linked to it follow at once + ("repository", "publicized" | "privatized" | "edited") => match repository(event) { + Some(repository) => { + let private = event["repository"]["private"].as_bool().unwrap_or(action == "privatized"); + ForgeEvent::RepositoryChanged { repository, private } + } + None => ForgeEvent::Ignored, + }, + // The same repository at a new URL; links follow by its ID + ("repository", "renamed" | "transferred") => match repository(event) { + Some(repository) if repository.id.is_some() => ForgeEvent::Moved { repository }, + _ => ForgeEvent::Ignored, + }, + // A collaborator added, removed or changed; someone joined or left a team + ("member" | "membership", _) => ForgeEvent::Access { people: person(&event["member"]) }, + // Someone joined or left the organization + ("organization", "member_added" | "member_removed") => { + ForgeEvent::Access { people: person(&event["membership"]["user"]) } + } + // A team's repositories or permission changed, or it was deleted + ("team", "added_to_repository" | "removed_from_repository" | "edited" | "deleted") => match installation { + Some(installation) => ForgeEvent::AccessAll { installation }, + None => ForgeEvent::Ignored, + }, + _ => ForgeEvent::Ignored, + }) +} + +/// A project linked to a repository. +struct Linked { + id: i64, + organization_id: i64, + installation: Option, +} + +/// The GitHub projects linked to a repository: by GitHub's permanent ID when the delivery has it (a renamed repository +/// is still the same one, and a new repository that took the old name isn't), and links whose ID isn't known yet by +/// URL, which get the ID now. +async fn linked(repository: &Repository) -> laravel::Result> { + let (id, url) = (repository.id.clone(), repository.url.to_lowercase()); + if id.is_some() { + db::query!( + "UPDATE projects SET repository_id = {id}, updated_at = now() \ + WHERE forge = 'github' AND repository_id IS NULL AND lower(repository_url) = {url}" + ) + .update() + .await?; + } + let rows = db::query!( + "SELECT id, organization_id, forge_installation FROM projects WHERE forge = 'github' AND ( \ + ({id}::text IS NOT NULL AND repository_id = {id}) \ + OR (({id}::text IS NULL OR repository_id IS NULL) AND lower(repository_url) = {url}))" + ) + .select() + .await?; + rows.iter() + .map(|r| { + Ok(Linked { + id: r.try_get("id")?, + organization_id: r.try_get("organization_id")?, + installation: r.try_get("forge_installation")?, + }) + }) + .collect() +} + +/// `POST /webhooks/github`. +pub async fn github( + app: laravel::config::Section, + headers: axum::http::HeaderMap, + body: axum::body::Bytes, +) -> laravel::Result> { + let Some(secret) = app.webhook_secret.as_deref().filter(|s| !s.is_empty()) else { + return Err(laravel::abort(404)); + }; + let header = |name: &str| headers.get(name).and_then(|v| v.to_str().ok()).unwrap_or_default().to_string(); + if !signed(secret, &header("x-hub-signature-256"), &body) { + 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()))?; + let (kind, delivery) = (header("x-github-event"), header("x-github-delivery")); + let read = read_event(&kind, &event).map_err(|e| laravel::abort_with(400, e))?; + let outcome = handle(&app, read).await?; + tracing::info!(forge = "github", kind, delivery, outcome = %outcome, "webhook"); + Ok(Json(outcome)) +} + +/// Act on one event; returns what happened, for the delivery's log on GitHub. +/// +/// # Errors +/// On a database error. +pub async fn handle(app: &GithubApp, event: ForgeEvent) -> laravel::Result { + Ok(match event { + ForgeEvent::Merged { repository, head, base, merge_commit } => { + let projects = linked(&repository).await?; + for p in &projects { + PullRequestMerged { + project_id: p.id, + head: head.clone(), + base: base.clone(), + merge_commit: merge_commit.clone(), + } + .dispatch() + .await?; + } + json!({ "dispatched": projects.len() }) + } + ForgeEvent::Closed { repository, branch, why } => { + let projects = linked(&repository).await?; + for p in &projects { + BranchClosed { project_id: p.id, branch: branch.clone(), why: why.to_string() }.dispatch().await?; + } + json!({ "dispatched": projects.len() }) + } + ForgeEvent::Reopened { repository, branch } => { + let projects = linked(&repository).await?; + for p in &projects { + BranchReopened { project_id: p.id, branch: branch.clone() }.dispatch().await?; + } + json!({ "dispatched": projects.len() }) + } + ForgeEvent::RepositoryChanged { repository, private } => { + let projects = linked(&repository).await?; + for p in &projects { + RepositoryVisibilityChanged { project_id: p.id, private }.dispatch().await?; + } + json!({ "dispatched": projects.len() }) + } + ForgeEvent::Moved { repository } => { + let (id, url) = (repository.id.clone(), repository.url.clone()); + let moved = db::query!( + "UPDATE projects SET repository_url = {url}, updated_at = now() \ + WHERE forge = 'github' AND repository_id = {id} AND repository_url IS DISTINCT FROM {url}" + ) + .update() + .await?; + json!({ "moved": moved }) + } + ForgeEvent::Installation { installation, previous, repositories } => { + // A stale or redelivered "created" mustn't attach an installation that's gone + if let Some(id) = &installation + && !github_app::installation_exists(app, id).await? + { + return Ok(json!({ "ignored": "no such installation" })); + } + let mut changed = 0; + let mut affected = HashSet::new(); + for repository in &repositories { + for p in linked(repository).await? { + // Removal only from the installation being removed; a project already on another keeps it + if previous.is_some() && p.installation != previous { + continue; + } + if p.installation == installation { + continue; + } + let (id, to) = (p.id, installation.clone()); + db::query!("UPDATE projects SET forge_installation = {to}, updated_at = now() WHERE id = {id}") + .update() + .await?; + affected.insert(p.organization_id); + changed += 1; + } + } + recheck_organizations(affected.into_iter().collect()).await?; + if installation.is_some() { json!({ "linked": changed }) } else { json!({ "unlinked": changed }) } + } + ForgeEvent::Access { people } => { + let mut users = Vec::new(); + for person in people { + let found: Option = db::query!( + "SELECT user_id FROM identities WHERE forge = 'github' AND site = '' AND forge_user_id = {person}" + ) + .scalar() + .await?; + users.extend(found); + } + let n = users.len(); + if n > 0 { + RecheckAccess { user_ids: users }.dispatch().await?; + } + json!({ "rechecking": n }) + } + ForgeEvent::AccessAll { installation } => { + let orgs: Vec = db::query!( + "SELECT DISTINCT organization_id FROM projects WHERE forge = 'github' AND forge_installation = {installation}" + ) + .select() + .await? + .iter() + .map(|r| r.try_get("organization_id")) + .collect::>()?; + recheck_organizations(orgs).await?; + json!({ "rechecking": "installation" }) + } + ForgeEvent::Ignored => json!({ "ignored": true }), + }) +} + +/// Recheck everyone whose membership in these organizations GitHub decides. +async fn recheck_organizations(orgs: Vec) -> laravel::Result<()> { + let mut users = HashSet::new(); + for org in orgs { + let rows = db::query!("SELECT user_id FROM memberships WHERE organization_id = {org} AND source = 'github'") + .select() + .await?; + for r in rows { + users.insert(r.try_get::("user_id")?); + } + } + if !users.is_empty() { + RecheckAccess { user_ids: users.into_iter().collect() }.dispatch().await?; + } + Ok(()) +} + +/// Recheck people's memberships from GitHub through the App ([`recheck`]). +#[derive(Queueable, Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct RecheckAccess { + pub user_ids: Vec, +} + +#[job] +impl RecheckAccess { + async fn handle(self, app: laravel::config::Section) -> laravel::Result<()> { + recheck(&app, &self.user_ids).await?; + Ok(()) + } +} + +/// Recheck people's memberships: each linked repository's collaborators are listed once (one installation token per +/// installation, its path looked up by GitHub's ID so a rename can't mislead it), and each person's permission on each +/// decides their role in its organization, as a sign-in does (`auth::memberships::apply`). Nobody's memberships change +/// unless every repository was read: a list that failed part-way would drop people. Returns how many changed. +/// +/// # Errors +/// When GitHub can't answer for some repository (or its rate limit is low), or on a database error. +pub async fn recheck(app: &GithubApp, user_ids: &[i64]) -> laravel::Result { + let mut github_ids: HashMap = HashMap::new(); + for &user_id in user_ids { + if let Some(id) = db::query!( + "SELECT forge_user_id FROM identities WHERE user_id = {user_id} AND forge = 'github' AND site = '' \ + ORDER BY id LIMIT 1" + ) + .scalar::() + .await? + { + github_ids.insert(user_id, id); + } + } + if github_ids.is_empty() { + return Ok(0); + } + let rows = db::query!( + "SELECT DISTINCT repository_id, forge_installation FROM projects \ + WHERE forge = 'github' AND repository_id IS NOT NULL AND forge_installation IS NOT NULL" + ) + .select() + .await?; + let mut tokens: HashMap = HashMap::new(); + // GitHub user ID -> [(repository, permission)] + let mut reach: HashMap> = HashMap::new(); + for r in rows { + let (repository_id, installation): (String, String) = + (r.try_get("repository_id")?, r.try_get("forge_installation")?); + let token = match tokens.get(&installation) { + Some(t) => t.clone(), + None => { + let t = github_app::installation_token(app, &installation).await?; + tokens.insert(installation.clone(), t.clone()); + t + } + }; + // The installation can't see it any more: it grants nobody anything + let Some(path) = github_app::repository_path(&token, &repository_id).await? else { continue }; + let Some(repository) = Repository::parse(&path) else { continue }; + let repository = repository.with_id(Some(repository_id)); + for (person, permission) in github_app::collaborators(&token, &path).await? { + reach.entry(person).or_default().push((repository.clone(), permission)); + } + } + let mut changed = 0; + for (user_id, github_id) in github_ids { + let list = reach.remove(&github_id).unwrap_or_default(); + changed += crate::auth::memberships::apply(user_id, ForgeKind::Github, "", &list).await?; + } + Ok(changed) +} diff --git a/app/src/heartbeat.rs b/app/src/heartbeat.rs new file mode 100644 index 00000000..abc91f2a --- /dev/null +++ b/app/src/heartbeat.rs @@ -0,0 +1,24 @@ +//! Scheduled work pushes its result to a Gatus external endpoint when one is configured (`_URL` and +//! `_TOKEN`, such as `VISUALCI_EMAILS_HEARTBEAT_URL`), so a run that failed, or no run at all, alerts. Ported +//! from today's server. + +use laravel::http::client; + +/// Push a run's result. A failed push only logs: Gatus alerts on the missing heartbeat instead. +pub async fn push(prefix: &str, result: Result<(), String>) { + let Ok(url) = std::env::var(format!("{prefix}_URL")) else { return }; + if url.is_empty() { + return; + } + let token = std::env::var(format!("{prefix}_TOKEN")).unwrap_or_default(); + let (success, error) = match result { + Ok(()) => ("true", String::new()), + Err(e) => ("false", e), + }; + let sent = client::post(url).token(token).query([("success", success), ("error", error.as_str())]).await; + match sent { + Ok(response) if response.successful() => {} + Ok(response) => tracing::warn!(prefix, status = %response.status(), "heartbeat refused"), + Err(e) => tracing::warn!(prefix, error = %e, "heartbeat failed"), + } +} diff --git a/app/src/http/api/mod.rs b/app/src/http/api/mod.rs index ec458fd2..44b45c2f 100644 --- a/app/src/http/api/mod.rs +++ b/app/src/http/api/mod.rs @@ -19,6 +19,7 @@ pub fn routes(route: &mut Router) { }); route.get("/v1/whoami", crate::auth::whoami); builds::routes(route); + crate::auth::device::api_routes(route); route.fallback(async || laravel::abort(404)); } diff --git a/app/src/lib.rs b/app/src/lib.rs index 8afdb3a9..1df75144 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -1,12 +1,15 @@ //! VisualCI's server on Laravel Rust. Who owns which module, and the seams between them, are in sc-8900. pub mod auth; +pub mod billing; pub mod config; pub mod domain; pub mod forge; +pub mod heartbeat; pub mod http; pub mod listeners; pub mod models; +pub mod notify; #[path = "../database/seeders/mod.rs"] pub mod seeders; pub mod storage; @@ -37,9 +40,18 @@ 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, _| { + // The load balancers in front (TRUSTED_PROXIES, comma-separated addresses or networks): the client's + // address comes from their X-Forwarded-For, for the device sign-in's page and its per-address limit + if let Ok(proxies) = std::env::var("TRUSTED_PROXIES") + && let Err(e) = + middleware.try_trust_proxies(proxies.split(',').map(str::trim).filter(|p| !p.is_empty())) + { + tracing::warn!("TRUSTED_PROXIES: {e}; trusting no proxies"); + } middleware.prepend(http::hosts::route_by_host); // The site's signed-in hint is read by its script: plain, not encrypted middleware.replace(laravel::cookie::EncryptCookies::except([auth::sign_in::SIGNED_IN_HINT])); @@ -49,6 +61,16 @@ 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); + // GitHub sends deliveries of up to 25 MB + route + .post("/webhooks/github", forge::webhooks::github) + .middleware(laravel::http::middleware::LimitBody::megabytes(25)); + }) + .health("/up"); }) } diff --git a/app/src/notify/mod.rs b/app/src/notify/mod.rs new file mode 100644 index 00000000..2f29169e --- /dev/null +++ b/app/src/notify/mod.rs @@ -0,0 +1,30 @@ +//! Transactional emails (sc-8900, the emails side), ported from today's server. Each email is rendered from a +//! [`Kind`], recorded in the `emails` outbox under a `dedupe_key` that names the event and its period (so a threshold +//! emails once a month, an invoice once), and sent through Postmark by [`DeliverEmails`]: queued right after an email +//! is, and scheduled every five minutes for anything left over. A failed send stays pending and is retried; after five +//! attempts it's marked failed for staff to retry or dismiss. Billing emails go to an organization's billing email, or +//! else its admins; security emails go to the person concerned. People can turn off low-credit warnings and +//! receipt-style emails; security, billing problems and running out can't be. + +pub mod outbox; +pub mod postmark; +pub mod render; + +pub use outbox::{DeliverEmails, To, queue}; +pub use render::{About, Kind, Paused, Preference, Rendered, render}; + +use laravel::event::{Event, listener}; + +use crate::auth::memberships::MembershipChanged; + +/// Someone joined an organization or left it: tell them. +#[listener] +pub async fn membership_changed(event: Event) -> laravel::Result<()> { + let kind = match event.role { + Some(role) => Kind::AddedToOrg { role: role.as_str().to_string() }, + None => Kind::RemovedFromOrg, + }; + let key = format!("{}:{}:{}:{}", kind.name(), event.organization_id, event.user_id, event.changed_at); + queue(&kind, To::User(event.user_id), Some(event.organization_id), &key).await?; + Ok(()) +} diff --git a/app/src/notify/outbox.rs b/app/src/notify/outbox.rs new file mode 100644 index 00000000..a6638095 --- /dev/null +++ b/app/src/notify/outbox.rs @@ -0,0 +1,266 @@ +//! The `emails` outbox: queueing (once per dedupe key and recipient), delivery, and what staff and `/status` read. + +use laravel::db; +use laravel::queue::{Queueable, job}; +use laravel::schedule::{self, Schedule}; + +use super::postmark::{self, Postmark}; +use super::render::{About, Kind, Preference, render}; + +/// Who gets an email. +#[derive(Clone, Debug)] +pub enum To { + /// The organization's billing email, or else its admins (each one's preferences apply). + Billing(i64), + /// One person, by user ID. + User(i64), + /// The organization's admins (each one's preferences apply). + Admins(i64), + /// An address with no account behind it yet (an invitation). + Address(String), +} + +/// The organization's admins who haven't turned this email off, with their user IDs. +async fn admins(org_id: i64, preference: Option) -> laravel::Result)>> { + let rows = match preference { + Some(Preference::LowCredits) => { + db::query!( + "SELECT u.id, u.email FROM memberships m JOIN users u ON u.id = m.user_id \ + WHERE m.organization_id = {org_id} AND m.role = 'admin' AND u.email_low_credits ORDER BY u.id" + ) + .select() + .await? + } + Some(Preference::Receipts) => { + db::query!( + "SELECT u.id, u.email FROM memberships m JOIN users u ON u.id = m.user_id \ + WHERE m.organization_id = {org_id} AND m.role = 'admin' AND u.email_receipts ORDER BY u.id" + ) + .select() + .await? + } + None => { + db::query!( + "SELECT u.id, u.email FROM memberships m JOIN users u ON u.id = m.user_id \ + WHERE m.organization_id = {org_id} AND m.role = 'admin' ORDER BY u.id" + ) + .select() + .await? + } + }; + rows.iter().map(|r| Ok((r.try_get::("email")?, Some(r.try_get::("id")?)))).collect() +} + +/// Record an email in the outbox, once per `dedupe_key` and recipient, and queue its delivery. It's rendered when it's +/// sent. Returns how many were queued: 0 when it was already queued, or everyone it would go to turned it off. +/// +/// # Errors +/// On a database error. +pub async fn queue(kind: &Kind, to: To, org_id: Option, dedupe_key: &str) -> laravel::Result { + let org_id = match to { + To::Billing(o) | To::Admins(o) => Some(o), + To::User(_) | To::Address(_) => org_id, + }; + let recipients: Vec<(String, Option)> = match to { + To::User(id) => db::query!("SELECT email FROM users WHERE id = {id}") + .scalar::() + .await? + .map(|e| vec![(e, Some(id))]) + .unwrap_or_default(), + To::Billing(o) => { + let billing: Option = db::query!("SELECT billing_email FROM organizations WHERE id = {o}") + .scalar::>() + .await? + .flatten() + .filter(|e| !e.trim().is_empty()); + match billing { + Some(e) => vec![(e.trim().to_string(), None)], + None => admins(o, kind.preference()).await?, + } + } + To::Admins(o) => admins(o, kind.preference()).await?, + To::Address(a) => vec![(a, None)], + }; + let data = serde_json::to_value(kind).map_err(|e| laravel::Error::msg(e.to_string()))?; + let name = kind.name(); + let mut queued = 0; + for (address, user_id) in recipients { + let key = format!("{dedupe_key}:{address}"); + let inserted: Option = db::query!( + "INSERT INTO emails (kind, dedupe_key, organization_id, user_id, recipient, data) \ + VALUES ({name}, {key}, {org_id}, {user_id}, {address}, {data}) \ + ON CONFLICT (dedupe_key) DO NOTHING RETURNING id" + ) + .scalar() + .await?; + queued += usize::from(inserted.is_some()); + } + if queued > 0 { + DeliverEmails.dispatch().await?; + } + Ok(queued) +} + +/// Send pending emails, up to 50 a run. Each is claimed just before it's sent, so two runs never send one twice; a +/// failure leaves it pending for the next run, and after five attempts it's marked failed. Without a Postmark token nothing is sent. +#[derive(Queueable, Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct DeliverEmails; + +#[job] +impl DeliverEmails { + async fn handle( + self, + postmark: laravel::config::Section, + app: laravel::config::Section, + ) -> laravel::Result<()> { + let delivered = deliver(&postmark, &app.url).await; + // The heartbeat checks the work, not just the run: an email waiting more than half an hour fails it + let health = match &delivered { + Err(e) => Err(e.to_string()), + Ok(_) => match oldest_unsent_seconds().await { + Ok(waited) if waited > STALE_SECONDS => Err(format!("the oldest unsent email has waited {waited}s")), + Ok(_) => Ok(()), + Err(e) => Err(e.to_string()), + }, + }; + crate::heartbeat::push("VISUALCI_EMAILS_HEARTBEAT", health).await; + delivered?; + Ok(()) + } +} + +/// How long an email may wait unsent before the heartbeat fails. +pub const STALE_SECONDS: i64 = 30 * 60; + +/// The web app's URL, for the links in emails. +#[derive(Clone, laravel::config::Section)] +pub struct AppUrl { + #[env("VISUALCI_APP_URL", default = "http://localhost")] + pub url: String, +} + +/// Anything left over (a failed send, a worker that stopped) goes out within five minutes. +#[schedule::tasks] +fn schedule(schedule: &mut Schedule) { + schedule.job(DeliverEmails).every_five_minutes().without_overlapping(); +} + +/// How long a claimed email waits before another run may take it: far longer than one send can take. +pub const RECLAIM_MINUTES: i64 = 30; +/// How long a failed send waits before it's tried again. +pub const RETRY_MINUTES: i64 = 5; + +/// Send what's pending. Returns how many were sent. +/// +/// # Errors +/// On a database error. +pub async fn deliver(config: &Postmark, app_url: &str) -> laravel::Result { + let Some(token) = config.token.as_deref().filter(|t| !t.is_empty()) else { return Ok(0) }; + // Anything a crashed run left claimed after its fifth attempt has had its tries. + let window = RECLAIM_MINUTES; + db::query!( + "UPDATE emails SET state = 'failed', claimed_at = NULL, \ + last_error = COALESCE(last_error, 'no result after five attempts'), updated_at = now() \ + WHERE state = 'pending' AND attempts >= 5 AND claimed_at < now() - make_interval(mins => {window}::int)" + ) + .update() + .await?; + let mut sent = 0; + // One at a time, each claimed just before it's sent: a claim only lapses after RECLAIM_MINUTES, far longer than one + // send can take, so a slow run's later emails are never taken by the next run while it's still sending. + for _ in 0..50 { + let Some(r) = db::query!( + "UPDATE emails SET claimed_at = now(), attempts = attempts + 1 WHERE id = ( \ + SELECT id FROM emails WHERE state = 'pending' AND attempts < 5 \ + AND (claimed_at IS NULL OR claimed_at < now() - make_interval(mins => {window}::int)) \ + ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED) \ + RETURNING id, recipient, data, organization_id, attempts" + ) + .select_one() + .await? + else { + break; + }; + let id: i64 = r.try_get("id")?; + let to: String = r.try_get("recipient")?; + let attempts: i32 = r.try_get("attempts")?; + let org_id: Option = r.try_get("organization_id")?; + let data: serde_json::Value = r.try_get("data")?; + let Ok(kind) = serde_json::from_value::(data) else { + db::query!( + "UPDATE emails SET state = 'failed', last_error = 'unreadable data', updated_at = now() WHERE id = {id}" + ) + .update() + .await?; + continue; + }; + let (org_name, org_slug) = match org_id { + Some(o) => db::query!("SELECT name, slug FROM organizations WHERE id = {o}") + .select_one() + .await? + .map(|row| { + ( + row.try_get::("name").unwrap_or_default(), + row.try_get::("slug").unwrap_or_default(), + ) + }) + .unwrap_or_default(), + None => (String::new(), String::new()), + }; + let rendered = + render(&kind, &About { org_name: &org_name, org_slug: &org_slug, app_url: app_url.trim_end_matches('/') }); + match postmark::send(config, token, &to, &rendered.subject, &rendered.text, &rendered.html, kind.reply_to()) + .await + { + Ok(()) => { + let (subject, text, html) = (rendered.subject, rendered.text, rendered.html); + db::query!( + "UPDATE emails SET state = 'sent', sent_at = now(), claimed_at = NULL, last_error = NULL, \ + subject = {subject}, text_body = {text}, html_body = {html}, updated_at = now() WHERE id = {id}" + ) + .update() + .await?; + sent += 1; + } + Err(e) => { + let state = if attempts >= 5 { "failed" } else { "pending" }; + let error = e.to_string(); + // Its claim lapses in RETRY_MINUTES, so the next run tries again, never this one. + let hold = RECLAIM_MINUTES - RETRY_MINUTES; + db::query!( + "UPDATE emails SET state = {state}, last_error = {error}, updated_at = now(), \ + claimed_at = CASE WHEN {state} = 'failed' THEN NULL \ + ELSE now() - make_interval(mins => {hold}::int) END WHERE id = {id}" + ) + .update() + .await?; + tracing::warn!(email_id = id, error = %e, "an email wasn't sent"); + } + } + } + Ok(sent) +} + +/// How long the oldest unsent email has waited, for `/status`. +/// +/// # Errors +/// On a database error. +pub async fn oldest_unsent_seconds() -> laravel::Result { + Ok(db::query!( + "SELECT COALESCE(EXTRACT(EPOCH FROM now() - MIN(created_at)), 0)::BIGINT FROM emails WHERE state = 'pending'" + ) + .scalar::() + .await? + .unwrap_or(0)) +} + +/// Failed emails nobody has retried or dismissed yet, for `/status` (`emails_failed_unresolved`). +/// +/// # Errors +/// On a database error. +pub async fn failed_unresolved_count() -> laravel::Result { + Ok(db::query!("SELECT count(*) FROM emails WHERE state = 'failed' AND dismissed_at IS NULL") + .scalar::() + .await? + .unwrap_or(0)) +} diff --git a/app/src/notify/postmark.rs b/app/src/notify/postmark.rs new file mode 100644 index 00000000..3dd43373 --- /dev/null +++ b/app/src/notify/postmark.rs @@ -0,0 +1,50 @@ +//! Sending one email through Postmark's API (`POSTMARK_SERVER_TOKEN`, `MAIL_FROM`, `MAIL_REPLY_TO`). Without a token, +//! nothing is sent and the outbox keeps the emails pending. + +use laravel::http::client; +use serde_json::json; + +#[derive(Clone, laravel::config::Section)] +pub struct Postmark { + #[env("POSTMARK_SERVER_TOKEN")] + pub token: Option, + #[env("MAIL_FROM", default = "VisualCI ")] + pub from: String, + #[env("MAIL_REPLY_TO", default = "support@visualci.com")] + pub reply_to: String, +} + +/// Send one email with its text and HTML bodies. +/// +/// # Errors +/// When Postmark can't be reached or refuses the message. +pub async fn send( + config: &Postmark, + token: &str, + to: &str, + subject: &str, + text: &str, + html: &str, + reply_to: Option<&str>, +) -> laravel::Result<()> { + let body = json!({ + "From": config.from, + "To": to, + "ReplyTo": reply_to.unwrap_or(&config.reply_to), + "Subject": subject, + "TextBody": text, + "HtmlBody": html, + "MessageStream": "outbound", + }); + let response = client::post("https://api.postmarkapp.com/email") + .header("X-Postmark-Server-Token", token) + .accept_json() + .timeout(std::time::Duration::from_secs(10)) + .json(&body) + .await?; + if !response.successful() { + let detail: serde_json::Value = response.json().unwrap_or_default(); + return Err(laravel::Error::msg(format!("Postmark: HTTP {}: {}", response.status(), detail["Message"]))); + } + Ok(()) +} diff --git a/app/src/notify/render.rs b/app/src/notify/render.rs new file mode 100644 index 00000000..b663f634 --- /dev/null +++ b/app/src/notify/render.rs @@ -0,0 +1,464 @@ +//! What each email VisualCI sends says (ported as is from today's server, sc-8900): every [`Kind`], rendered to a +//! subject, plain text and HTML ([`render`]). The outbox and delivery are in `notify::outbox`. + +use crate::billing::CREDIT_PACK; + +/// Why automatic packs stopped. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub enum Paused { + Declined(String), + LimitReached(i32), +} + +/// Every email VisualCI sends to customers, with what it says. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub enum Kind { + /// 80% or 95% of the plan's credits (or of the open source pool) used this month. + CreditsLow { + pool: bool, + percent: u8, + left: i64, + total: i64, + renews: String, + next: String, + }, + /// The plan's credits and packs are used up: builds fail with "out of credits". + OutOfCredits { + plan: String, + renews: String, + packs: bool, + }, + /// Automatic packs bought one. + PackBought { + packs_this_month: i64, + limit: i32, + invoice_url: Option, + }, + AutoBuyPaused(Paused), + PlanChanged { + from: String, + to: String, + }, + OpenSourceLost { + project: String, + reason: String, + }, + /// A public project's repository went private (or it was unlinked), so VisualCI made the project private. + MadePrivate { + project: String, + }, + /// A maintainer of the repository moved its link to their own organization: one organization per repository. + RepositoryMoved { + project: String, + repository: String, + to_org: String, + by: String, + }, + Welcome { + name: String, + }, + Invited { + inviter: String, + role: String, + }, + AddedToOrg { + role: String, + }, + RemovedFromOrg, + /// `client` is how the CLI names itself: `visualci CLI on ada-laptop`. + DeviceSignIn { + client: String, + at: String, + }, + TokenCreated { + name: String, + project: Option, + }, + /// To the team (`VISUALCI_TEAM_EMAIL`): someone signed up. Plain text; replying reaches them. + NewSignup { + subject: String, + text: String, + reply_to: String, + }, +} + +impl Kind { + /// The name the outbox, the admin MCP and the staff page use. + #[must_use] + pub const fn name(&self) -> &'static str { + match self { + Self::CreditsLow { .. } => "credits_low", + Self::OutOfCredits { .. } => "out_of_credits", + Self::PackBought { .. } => "pack_bought", + Self::AutoBuyPaused(_) => "auto_buy_paused", + Self::PlanChanged { .. } => "plan_changed", + Self::OpenSourceLost { .. } => "open_source_lost", + Self::MadePrivate { .. } => "made_private", + Self::RepositoryMoved { .. } => "repository_moved", + Self::Welcome { .. } => "welcome", + Self::Invited { .. } => "invited", + Self::AddedToOrg { .. } => "added_to_org", + Self::RemovedFromOrg => "removed_from_org", + Self::DeviceSignIn { .. } => "device_sign_in", + Self::TokenCreated { .. } => "token_created", + Self::NewSignup { .. } => "new_signup", + } + } + + /// Where a reply goes when it isn't VisualCI's support address. + #[must_use] + pub fn reply_to(&self) -> Option<&str> { + match self { + Self::NewSignup { reply_to, .. } => Some(reply_to), + _ => None, + } + } + + /// Which preference can turn it off, if any. + #[must_use] + pub const fn preference(&self) -> Option { + match self { + Self::CreditsLow { .. } => Some(Preference::LowCredits), + Self::PackBought { .. } | Self::PlanChanged { .. } => Some(Preference::Receipts), + _ => None, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Preference { + LowCredits, + Receipts, +} + +/// An email ready to send. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +pub struct Rendered { + pub subject: String, + pub text: String, + pub html: String, +} + +/// What an email is about: the organization (by name and slug) when it has one. +#[derive(Debug, Clone)] +pub struct About<'a> { + pub org_name: &'a str, + pub org_slug: &'a str, + pub app_url: &'a str, +} + +fn n(v: i64) -> String { + let s = v.abs().to_string(); + let mut out = String::new(); + for (i, c) in s.chars().enumerate() { + if i > 0 && (s.len() - i).is_multiple_of(3) { + out.push(','); + } + out.push(c); + } + if v < 0 { format!("-{out}") } else { out } +} + +fn money(cents: i64) -> String { + if cents % 100 == 0 { format!("${}", cents / 100) } else { format!("${}.{:02}", cents / 100, cents % 100) } +} + +fn escape(s: &str) -> String { + s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) +} + +/// A paragraph that starts with this is a line to copy: monospace in a box in the HTML, on its own line in the text. +const COPY: &str = "copy:"; + +/// The one-line setup prompt for a coding agent, as the app shows it. +pub const AGENT_PROMPT: &str = "Fetch https://visualci.com/install.md and follow it"; + +/// The email's HTML: its paragraphs and one button, in a plain single column. +fn html(paragraphs: &[String], button: (&str, &str)) -> String { + let body: String = paragraphs + .iter() + .map(|p| match p.strip_prefix(COPY) { + Some(line) => format!( + "
{}
", + escape(line) + ), + None => { + format!("

{}

", escape(p)) + } + }) + .collect(); + format!( + "\ +
\ +

VisualCI

{body}\ +

\ + {label}

\ +

\ + Questions? Reply to this email.

", + url = escape(button.1), + label = escape(button.0), + ) +} + +fn text(paragraphs: &[String], button: (&str, &str)) -> String { + let lines: Vec<&str> = paragraphs.iter().map(|p| p.strip_prefix(COPY).unwrap_or(p)).collect(); + let mut out = lines.join("\n\n"); + out.push_str(&format!("\n\n{}: {}\n\nQuestions? Reply to this email.\n", button.0, button.1)); + out +} + +/// Render an email. +#[must_use] +pub fn render(kind: &Kind, about: &About<'_>) -> Rendered { + if let Kind::NewSignup { subject, text, .. } = kind { + let html = format!("
{}
", escape(text)); + return Rendered { subject: subject.clone(), text: text.clone(), html }; + } + let org = about.org_name; + let billing = format!("{}/{}/billing", about.app_url, about.org_slug); + let (subject, paragraphs, button): (String, Vec, (String, String)) = match kind { + Kind::CreditsLow { pool, percent, left, total, renews, next } => { + let what = if *pool { "open source credits" } else { "credits" }; + ( + format!("{org} has used {percent}% of this month's VisualCI {what}"), + vec![ + format!("{org} has {} of its {} {what} left this month. They renew on {renews}.", n(*left), n(*total)), + next.clone(), + ], + ("Open billing".into(), billing), + ) + } + Kind::OutOfCredits { plan, renews, packs } => ( + format!("{org} is out of VisualCI credits"), + vec![ + format!( + "{org} has used this month's credits on the {plan} plan and has no pack credits left. New builds \ + fail with an \"out of credits\" error instead of being compared, until the credits renew on {renews}." + ), + if *packs { + "Buy a credit pack, or turn on automatic packs, on the billing page.".to_string() + } else { + "Team includes 1,000,000 credits a month. Upgrade on the billing page.".to_string() + }, + ], + ("Open billing".into(), billing), + ), + Kind::PackBought { packs_this_month, limit, invoice_url } => ( + format!("VisualCI bought a credit pack for {org}"), + vec![ + format!( + "Credits were running low, so VisualCI bought a pack of {} credits for {} with {org}'s default card.", + n(CREDIT_PACK.credits), + money(CREDIT_PACK.price_cents) + ), + format!("That's {packs_this_month} of the {limit} automatic packs allowed this month."), + ], + match invoice_url { + Some(url) => ("View the invoice".into(), url.clone()), + None => ("Open billing".into(), billing), + }, + ), + Kind::AutoBuyPaused(Paused::Declined(reason)) => ( + format!("A VisualCI credit pack for {org} was declined"), + vec![ + format!("The card was declined ({reason}), so automatic credit packs are paused."), + "Update the card on the Payment methods tab, then save the automatic pack limit on the Plan tab to \ + turn them back on." + .to_string(), + ], + ("Payment methods".into(), format!("{billing}/payment-methods")), + ), + Kind::AutoBuyPaused(Paused::LimitReached(limit)) => ( + format!("{org} reached its limit of automatic credit packs"), + vec![ + format!("VisualCI has bought {limit} credit packs this month, the limit you set, so it won't buy more."), + "When the credits run out, builds stop being compared. Raise the limit or buy a pack on the billing page." + .to_string(), + ], + ("Open billing".into(), billing), + ), + Kind::PlanChanged { from, to } => ( + format!("{org} is now on the {to} plan"), + vec![format!("{org} moved from the {from} plan to the {to} plan. The change applies now.")], + ("Open billing".into(), billing), + ), + Kind::OpenSourceLost { project, reason } => ( + format!("{project} no longer uses VisualCI's open source credits"), + vec![ + format!("{project} isn't an open source project any more: {}.", sentence_part(reason)), + format!( + "Its builds use {org}'s plan credits from now on. If that's a mistake, fix the repository on \ + GitHub: VisualCI checks again when GitHub says it changed, and once a day." + ), + ], + ("Project settings".into(), format!("{}/{}/{project}?tab=settings", about.app_url, about.org_slug)), + ), + Kind::MadePrivate { project } => ( + format!("{project} is private now"), + vec![ + format!( + "The repository for {project} isn't public any more, so VisualCI made the project private too: \ + its builds, diffs and pull requests are no longer public." + ), + "If the repository is public again, an admin can make the project public in its settings.".to_string(), + ], + ("Project settings".into(), format!("{}/{}/{project}?tab=settings", about.app_url, about.org_slug)), + ), + Kind::RepositoryMoved { project, repository, to_org, by } => ( + format!("{repository} moved to another organization"), + vec![ + format!( + "{by}, a maintainer of {repository}, linked it to their organization {to_org} on VisualCI. A \ + repository belongs to one organization, so {project} isn't linked to it any more: its builds \ + no longer post checks or comments there." + ), + format!( + "If that's wrong, a maintainer of {repository} can link it to {project} again from the project's \ + settings, which moves it back." + ), + ], + ("Project settings".into(), format!("{}/{}/{project}?tab=settings", about.app_url, about.org_slug)), + ), + Kind::Welcome { name } => ( + "Welcome to VisualCI".to_string(), + vec![ + format!("Hi {name}, you're signed in to VisualCI."), + "To set it up, paste this into your coding agent:".to_string(), + format!("{COPY}{AGENT_PROMPT}"), + "It connects VisualCI's MCP server and adds a VisualCI step to your CI.".to_string(), + ], + ("Open VisualCI".into(), format!("{}/{}", about.app_url, about.org_slug).trim_end_matches('/').to_string()), + ), + Kind::Invited { inviter, role } => ( + format!("{inviter} invited you to {org} on VisualCI"), + vec![format!( + "{inviter} invited you to join {org} on VisualCI as {}. Sign in with this email address, or with GitHub, \ + and accept it there.", + article(role) + )], + ("See the invitation".into(), about.app_url.to_string()), + ), + Kind::AddedToOrg { role } => ( + format!("You joined {org} on VisualCI"), + vec![format!("You're now {} of {org} on VisualCI.", article(role))], + (format!("Open {org}"), format!("{}/{}", about.app_url, about.org_slug)), + ), + Kind::RemovedFromOrg => ( + format!("You were removed from {org} on VisualCI"), + vec![format!("You're no longer a member of {org} on VisualCI. Its admins can add you again.")], + ("Open VisualCI".into(), about.app_url.to_string()), + ), + Kind::DeviceSignIn { client, at } => ( + "The VisualCI CLI signed in as you".to_string(), + vec![ + format!("{client} signed in to your VisualCI account at {at}."), + "If that wasn't you, revoke it on your account page.".to_string(), + ], + ("Account".into(), format!("{}/account", about.app_url)), + ), + // Rendered as plain text above. + Kind::NewSignup { subject, text, .. } => (subject.clone(), vec![text.clone()], (String::new(), String::new())), + Kind::TokenCreated { name, project } => ( + format!("A new VisualCI token: {name}"), + vec![ + match project { + Some(p) => format!("A project token named \"{name}\" was created for {}/{p}.", about.org_slug), + None => format!("A personal token named \"{name}\" was created for your VisualCI account."), + }, + "If you didn't create it, delete it now.".to_string(), + ], + match project { + Some(p) => ("Project tokens".into(), format!("{}/{}/{p}?tab=tokens", about.app_url, about.org_slug)), + None => ("Account".into(), format!("{}/account", about.app_url)), + }, + ), + }; + let button = (button.0.as_str(), button.1.as_str()); + Rendered { text: text(¶graphs, button), html: html(¶graphs, button), subject } +} + +/// "Its repository is private." as part of a sentence: "its repository is private". +fn sentence_part(s: &str) -> String { + let s = s.trim().trim_end_matches('.'); + let mut c = s.chars(); + c.next().map_or_else(String::new, |f| f.to_lowercase().chain(c).collect()) +} + +fn article(role: &str) -> String { + let role = role.to_lowercase(); + if role.starts_with(['a', 'e', 'i', 'o', 'u']) { format!("an {role}") } else { format!("a {role}") } +} + +/// Every template with sample data, for the staff preview page and the snapshot tests. +#[must_use] +pub fn samples() -> Vec<(&'static str, Kind)> { + let renews = "1 January 2027".to_string(); + vec![ + ("Credits low (80%)", Kind::CreditsLow { + pool: false, + percent: 80, + left: 200_000, + total: 1_000_000, + renews: renews.clone(), + next: "When they run out, VisualCI buys a pack of 500,000 credits for $15 with the default card, up to 4 \ + packs this month." + .into(), + }), + ("Credits low (95%, Free)", Kind::CreditsLow { + pool: false, + percent: 95, + left: 1_250, + total: 25_000, + renews: renews.clone(), + next: "When they run out, builds aren't compared until the credits renew. Team includes 1,000,000 credits a month." + .into(), + }), + ("Open source credits low (80%)", Kind::CreditsLow { + pool: true, + percent: 80, + left: 200_000, + total: 1_000_000, + renews: renews.clone(), + next: "When they run out, open source projects use the plan's credits.".into(), + }), + ("Out of credits (Free)", Kind::OutOfCredits { plan: "Free".into(), renews: renews.clone(), packs: false }), + ("Out of credits (Team)", Kind::OutOfCredits { plan: "Team".into(), renews, packs: true }), + ("Pack bought", Kind::PackBought { + packs_this_month: 1, + limit: 4, + invoice_url: Some("https://invoice.stripe.com/i/acct_test/sample".into()), + }), + ("Automatic packs paused (declined)", Kind::AutoBuyPaused(Paused::Declined("your card has insufficient funds".into()))), + ("Automatic packs paused (limit)", Kind::AutoBuyPaused(Paused::LimitReached(4))), + ("Plan changed", Kind::PlanChanged { from: "Free".into(), to: "Team".into() }), + ("Open source status lost", Kind::OpenSourceLost { + project: "widgets".into(), + reason: "Its licence (BUSL-1.1) isn't OSI-approved.".into(), + }), + ("Project made private", Kind::MadePrivate { project: "widgets".into() }), + ( + "Repository moved", + Kind::RepositoryMoved { + project: "widgets".into(), + repository: "acme/widgets".into(), + to_org: "Acme".into(), + by: "Grace Hopper".into(), + }, + ), + ("Welcome", Kind::Welcome { name: "Ada".into() }), + ("Invitation", Kind::Invited { inviter: "Grace Hopper".into(), role: "member".into() }), + ("Added to an organization", Kind::AddedToOrg { role: "admin".into() }), + ("Removed from an organization", Kind::RemovedFromOrg), + ("CLI signed in", Kind::DeviceSignIn { + client: "visualci CLI on ada-laptop".into(), + at: "1 December 2026, 09:41 UTC".into(), + }), + ("Personal token created", Kind::TokenCreated { name: "Claude Code".into(), project: None }), + ("Project token created", Kind::TokenCreated { name: "GitHub Actions".into(), project: Some("web".into()) }), + ] +} 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(()) +} diff --git a/app/tests/device.rs b/app/tests/device.rs new file mode 100644 index 00000000..97ccf645 --- /dev/null +++ b/app/tests/device.rs @@ -0,0 +1,99 @@ +//! `visualci login`: the CLI gets a code pair, the person approves the user code, and the next poll gets a working +//! personal token, once, with a security notice; a denied code says so. + +use app::models::User; +use laravel::db; +use laravel::model::create; +use laravel::testing::prelude::*; + +#[laravel::test] +async fn an_approved_code_gives_the_cli_one_token(app: Application) -> laravel::Result<()> { + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let pair = app.post("/api/v1/device/code").json(json!({ "name": "visualci CLI on ada-laptop" })).await; + pair.assert_ok().assert_json_path("interval", 3); + let device = pair.json()["device_code"].as_str().unwrap().to_string(); + let user_code = pair.json()["user_code"].as_str().unwrap().to_string(); + assert!(pair.json()["verification_uri_complete"].as_str().unwrap().ends_with(&format!("/device?code={user_code}"))); + + // Each poll as if the interval had passed (a quicker one gets slow_down, tested below) + let poll = || async { + db::query!("UPDATE device_logins SET last_polled_at = NULL").update().await.unwrap(); + app.post("/api/v1/device/token").json(json!({ "device_code": device.clone() })).await + }; + poll().await.assert_ok().assert_json_path("status", "pending"); + + let typed = user_code.to_lowercase().replace('-', ""); + app.get(format!("/api/ui/device/{typed}")) + .acting_as(&ada) + .await + .assert_ok() + .assert_json_path("label", "VisualCI command-line sign-in") + .assert_json_path("client", "visualci CLI on ada-laptop"); + app.post(format!("/api/ui/device/{user_code}")) + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .json(json!({ "approve": true })) + .await + .assert_ok(); + app.get(format!("/api/ui/device/{user_code}")).acting_as(&ada).await.assert_status(404); + + let approved = poll().await; + approved.assert_ok().assert_json_path("status", "approved").assert_json_path("user", "Ada"); + let token = approved.json()["token"].as_str().unwrap().to_string(); + app.get("/api/v1/whoami") + .header("authorization", format!("Bearer {token}")) + .await + .assert_ok() + .assert_json_path("client.token_name", "visualci CLI on ada-laptop"); + poll().await.assert_json_path("status", "expired"); + let notices: Option = db::query!("SELECT count(*) FROM emails WHERE kind = 'device_sign_in'").scalar().await?; + assert_eq!(notices, Some(1)); + Ok(()) +} + +#[laravel::test] +async fn a_denied_code_says_so(app: Application) -> laravel::Result<()> { + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let pair = app.post("/api/v1/device/code").json(json!({})).await; + let device = pair.json()["device_code"].as_str().unwrap().to_string(); + let user_code = pair.json()["user_code"].as_str().unwrap().to_string(); + app.get(format!("/api/ui/device/{user_code}")).header("accept", "application/json").await.assert_status(401); + app.post(format!("/api/ui/device/{user_code}")) + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .json(json!({ "approve": false })) + .await + .assert_ok(); + app.post("/api/v1/device/token").json(json!({ "device_code": device })).await.assert_json_path("status", "denied"); + app.post("/api/v1/device/token") + .json(json!({ "device_code": "nothing-like-it" })) + .await + .assert_json_path("status", "expired"); + Ok(()) +} + +#[laravel::test] +async fn a_quick_poll_is_told_to_slow_down(app: Application) -> laravel::Result<()> { + let pair = app.post("/api/v1/device/code").json(json!({})).await; + let device = pair.json()["device_code"].as_str().unwrap().to_string(); + let poll = || app.post("/api/v1/device/token").json(json!({ "device_code": device.clone() })); + poll().await.assert_json_path("status", "pending"); + poll().await.assert_json_path("status", "slow_down"); + Ok(()) +} + +#[laravel::test] +async fn one_address_gets_a_few_codes_and_old_ones_are_pruned(app: Application) -> laravel::Result<()> { + for _ in 0..app::auth::device::CODES_PER_ADDRESS { + app.post("/api/v1/device/code").json(json!({})).await.assert_ok(); + } + app.post("/api/v1/device/code").json(json!({})).await.assert_status(429); + db::query!( + "UPDATE device_logins SET expires_at = now() - interval '2 days', created_at = now() - interval '2 days'" + ) + .update() + .await?; + assert_eq!(app::auth::device::prune().await?, app::auth::device::CODES_PER_ADDRESS as u64); + app.post("/api/v1/device/code").json(json!({})).await.assert_ok(); + Ok(()) +} diff --git a/app/tests/emails.rs b/app/tests/emails.rs new file mode 100644 index 00000000..e791dc18 --- /dev/null +++ b/app/tests/emails.rs @@ -0,0 +1,117 @@ +//! Emails: every kind renders; the outbox queues once per dedupe key and recipient, respects people's choices, and +//! sends through Postmark (faked), keeping a failed send pending for the next run. + +use app::models::User; +use app::notify::{self, Kind, To, outbox}; +use laravel::db; +use laravel::http::client; +use laravel::model::create; +use laravel::testing::prelude::*; + +#[test] +fn every_email_renders() { + let about = notify::About { org_name: "Acme", org_slug: "acme", app_url: "https://app.visualci.test" }; + for (label, kind) in notify::render::samples() { + let r = notify::render(&kind, &about); + assert!(!r.subject.is_empty() && !r.text.is_empty() && r.html.contains("<"), "{label}"); + } +} + +async fn org_with_admins() -> laravel::Result<(i64, User, User)> { + let org: i64 = 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"); + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let bea = create!(User { pid: laravel::str::uuid7(), name: "Bea", email: "bea@example.com", staff: false }).await?; + for u in [ada.id, bea.id] { + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org}, {u}, 'admin', 'created', now(), now())" + ) + .insert() + .await?; + } + Ok((org, ada, bea)) +} + +fn postmark() -> Application { + app::testing::configure().with_env("POSTMARK_SERVER_TOKEN", "test-token").create() +} + +#[laravel::test(app = postmark)] +async fn the_outbox_queues_once_respects_choices_and_sends(_app: Application) -> laravel::Result<()> { + let (org, _ada, bea) = org_with_admins().await?; + let bea_id = bea.id; + db::query!("UPDATE users SET email_low_credits = false WHERE id = {bea_id}").update().await?; + let low = Kind::CreditsLow { + pool: false, + percent: 80, + left: 200_000, + total: 1_000_000, + renews: "1 January 2027".into(), + next: "1 January 2027".into(), + }; + let postmark = client::fake().with("api.postmarkapp.com/*", json!({ "MessageID": "x" })); + // Only Ada: Bea turned low-credit warnings off. The delivery job runs at once in tests (sync queue). + assert_eq!(notify::queue(&low, To::Billing(org), None, "credits_low:80:2026-12").await?, 1); + assert_eq!(notify::queue(&low, To::Billing(org), None, "credits_low:80:2026-12").await?, 0, "once per period"); + postmark.assert_sent_count(1); + let sent: Option = + db::query!("SELECT state FROM emails WHERE recipient = 'ada@example.com'").scalar().await?; + assert_eq!(sent.as_deref(), Some("sent")); + Ok(()) +} + +#[laravel::test(app = postmark)] +async fn a_failed_send_stays_pending_for_the_next_run(_app: Application) -> laravel::Result<()> { + let (org, _ada, _bea) = org_with_admins().await?; + let _postmark = + client::fake().with("api.postmarkapp.com/*", client::response().status(500).json(json!({ "Message": "down" }))); + notify::queue(&Kind::RemovedFromOrg, To::Admins(org), None, "removed:1").await?; + let rows = db::query!("SELECT state, attempts, last_error FROM emails ORDER BY id").select().await?; + assert_eq!(rows.len(), 2); + for r in rows { + assert_eq!(r.try_get::("state")?, "pending"); + assert_eq!(r.try_get::("attempts")?, 1); + assert!(r.try_get::("last_error")?.contains("down")); + } + assert!(outbox::oldest_unsent_seconds().await? >= 0); + assert_eq!(outbox::failed_unresolved_count().await?, 0, "pending, not failed, after one attempt"); + Ok(()) +} + +#[laravel::test(app = postmark)] +async fn claims_are_per_email_and_attempts_end_at_five(_app: Application) -> laravel::Result<()> { + let postmark = client::fake().with("api.postmarkapp.com/*", json!({ "MessageID": "x" })); + // A run that crashed during its fifth attempt, half an hour ago: failed, not sent a sixth time. + db::query!( + "INSERT INTO emails (kind, dedupe_key, recipient, data, attempts, claimed_at) \ + VALUES ('removed_from_org', 'crashed', 'ada@example.com', '\"RemovedFromOrg\"', 5, now() - interval '31 minutes')" + ) + .insert() + .await?; + // Another run is sending this one right now: left alone. + db::query!( + "INSERT INTO emails (kind, dedupe_key, recipient, data, attempts, claimed_at) \ + VALUES ('removed_from_org', 'in-flight', 'bea@example.com', '\"RemovedFromOrg\"', 1, now() - interval '6 minutes')" + ) + .insert() + .await?; + let config = app::notify::postmark::Postmark { + token: Some("test-token".into()), + from: "VisualCI ".into(), + reply_to: "support@visualci.com".into(), + }; + assert_eq!(outbox::deliver(&config, "https://app.visualci.com").await?, 0); + postmark.assert_nothing_sent(); + let state = |key: &'static str| async move { + db::query!("SELECT state FROM emails WHERE dedupe_key = {key}").scalar::().await + }; + assert_eq!(state("crashed").await?.as_deref(), Some("failed")); + assert_eq!(state("in-flight").await?.as_deref(), Some("pending")); + Ok(()) +} diff --git a/app/tests/invitations.rs b/app/tests/invitations.rs new file mode 100644 index 00000000..8320270d --- /dev/null +++ b/app/tests/invitations.rs @@ -0,0 +1,265 @@ +//! Invitations wait for their invitee to accept; only admins invite and manage members; an organization keeps an +//! admin; the forge's memberships stay the forge's; invitation emails are limited per day. + +use app::models::User; +use laravel::db; +use laravel::model::create; +use laravel::testing::prelude::*; + +async fn person(name: &str, email: &str) -> laravel::Result { + let user = create!(User { pid: laravel::str::uuid7(), name: name, email: email, staff: false }).await?; + let id = user.id; + db::query!("UPDATE users SET email_verified_at = now() WHERE id = {id}").update().await?; + User::find_or_fail(id).await +} + +async fn org(slug: &str) -> laravel::Result { + Ok(db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) \ + VALUES (gen_random_uuid(), {slug}, 'Acme', now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap()) +} + +async fn join(org: i64, user: &User, role: &str, source: &str) -> laravel::Result<()> { + let id = user.id; + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org}, {id}, {role}, {source}, now(), now())" + ) + .insert() + .await?; + Ok(()) +} + +async fn role_of(org: i64, user: &User) -> laravel::Result> { + let id = user.id; + db::query!("SELECT role FROM memberships WHERE organization_id = {org} AND user_id = {id}").scalar().await +} + +#[laravel::test] +async fn an_invitation_waits_for_its_invitee_to_accept(app: Application) -> laravel::Result<()> { + let acme = org("acme").await?; + let admin = person("Grace", "grace@example.com").await?; + let ada = person("Ada", "ada@example.com").await?; + join(acme, &admin, "admin", "created").await?; + + let sent = app + .post("/api/ui/orgs/acme/invitations") + .acting_as(&admin) + .header("sec-fetch-site", "same-origin") + .json(json!({ "invitee": "Ada@Example.com", "role": "member" })) + .await; + sent.assert_ok().assert_json_path("invitee", "ada@example.com").assert_json_path("role", "member"); + let id = sent.json()["id"].as_str().unwrap().to_string(); + assert_eq!(role_of(acme, &ada).await?, None, "nobody joins without saying so"); + let emails: Option = + db::query!("SELECT count(*) FROM emails WHERE kind = 'invited' AND recipient = 'ada@example.com'") + .scalar() + .await?; + assert_eq!(emails, Some(1)); + + app.get("/api/ui/orgs/acme/members") + .acting_as(&admin) + .await + .assert_ok() + .assert_json_path("invitations.0.id", id.as_str()); + app.get("/api/ui/invitations") + .acting_as(&ada) + .await + .assert_ok() + .assert_json_path("invitations.0.organization.slug", "acme") + .assert_json_path("invitations.0.invited_by", "Grace"); + + // Someone else can't take it. + let eve = person("Eve", "eve@example.com").await?; + app.post(format!("/api/ui/invitations/{id}/accept")) + .acting_as(&eve) + .header("sec-fetch-site", "same-origin") + .await + .assert_status(404); + + app.post(format!("/api/ui/invitations/{id}/accept")) + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .await + .assert_ok() + .assert_json_path("slug", "acme"); + assert_eq!(role_of(acme, &ada).await?.as_deref(), Some("member")); + let added: Option = + db::query!("SELECT count(*) FROM emails WHERE kind = 'added_to_org' AND recipient = 'ada@example.com'") + .scalar() + .await?; + assert_eq!(added, Some(1), "she's told she joined"); + // A second click finds nothing to accept. + app.post(format!("/api/ui/invitations/{id}/accept")) + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .await + .assert_status(404); + app.get("/api/ui/invitations").acting_as(&ada).await.assert_json_path("invitations", json!([])); + let members = app.get("/api/ui/orgs/acme/members").acting_as(&ada).await; + members.assert_ok().assert_json_path("members.0.name", "Grace").assert_json_path("members.1.name", "Ada"); + assert!(members.json()["members"][0]["email"].is_null(), "a member doesn't see emails"); + Ok(()) +} + +#[laravel::test] +async fn only_admins_invite_and_an_invitation_never_lowers_a_role(app: Application) -> laravel::Result<()> { + let acme = org("acme").await?; + let admin = person("Grace", "grace@example.com").await?; + let member = person("Ada", "ada@example.com").await?; + let outsider = person("Eve", "eve@example.com").await?; + join(acme, &admin, "admin", "created").await?; + join(acme, &member, "member", "github").await?; + for (who, status) in [(&member, 403), (&outsider, 404)] { + app.post("/api/ui/orgs/acme/invitations") + .acting_as(who) + .header("sec-fetch-site", "same-origin") + .json(json!({ "invitee": "someone@example.com", "role": "admin" })) + .await + .assert_status(status); + } + + // By GitHub login, for someone who has signed in with it: it's recorded for their account. + let ada_id = member.id; + db::query!( + "INSERT INTO identities (user_id, forge, site, forge_user_id, login, created_at, updated_at) \ + VALUES ({ada_id}, 'github', '', '1', 'ada-l', now(), now())" + ) + .insert() + .await?; + let sent = app + .post("/api/ui/orgs/acme/invitations") + .acting_as(&admin) + .header("sec-fetch-site", "same-origin") + .json(json!({ "invitee": "@Ada-L", "role": "read" })) + .await; + sent.assert_ok().assert_json_path("invitee", "@Ada-L (GitHub)"); + let id = sent.json()["id"].as_str().unwrap().to_string(); + app.post(format!("/api/ui/invitations/{id}/accept")) + .acting_as(&member) + .header("sec-fetch-site", "same-origin") + .await + .assert_ok(); + assert_eq!(role_of(acme, &member).await?.as_deref(), Some("member")); + + // Declining withdraws it. + let again = app + .post("/api/ui/orgs/acme/invitations") + .acting_as(&admin) + .header("sec-fetch-site", "same-origin") + .json(json!({ "invitee": "eve@example.com", "role": "member" })) + .await; + let id = again.json()["id"].as_str().unwrap().to_string(); + app.post(format!("/api/ui/invitations/{id}/decline")) + .acting_as(&outsider) + .header("sec-fetch-site", "same-origin") + .await + .assert_ok(); + app.get("/api/ui/orgs/acme/members").acting_as(&admin).await.assert_json_path("invitations", json!([])); + Ok(()) +} + +#[laravel::test] +async fn admins_manage_members_and_the_organization_keeps_an_admin(app: Application) -> laravel::Result<()> { + let acme = org("acme").await?; + let admin = person("Grace", "grace@example.com").await?; + let ada = person("Ada", "ada@example.com").await?; + let forge = person("Linus", "linus@example.com").await?; + join(acme, &admin, "admin", "created").await?; + join(acme, &ada, "member", "invite").await?; + join(acme, &forge, "member", "github").await?; + + app.patch(format!("/api/ui/orgs/acme/members/{}", admin.pid)) + .acting_as(&admin) + .header("sec-fetch-site", "same-origin") + .json(json!({ "role": "member" })) + .await + .assert_status(422); + app.patch(format!("/api/ui/orgs/acme/members/{}", forge.pid)) + .acting_as(&admin) + .header("sec-fetch-site", "same-origin") + .json(json!({ "role": "read" })) + .await + .assert_status(422); + app.patch(format!("/api/ui/orgs/acme/members/{}", ada.pid)) + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .json(json!({ "role": "admin" })) + .await + .assert_status(403); + app.patch(format!("/api/ui/orgs/acme/members/{}", ada.pid)) + .acting_as(&admin) + .header("sec-fetch-site", "same-origin") + .json(json!({ "role": "admin" })) + .await + .assert_ok(); + assert_eq!(role_of(acme, &ada).await?.as_deref(), Some("admin")); + + // With another admin now, Grace can leave; then Ada is the last admin and can't. + app.delete(format!("/api/ui/orgs/acme/members/{}", admin.pid)) + .acting_as(&admin) + .header("sec-fetch-site", "same-origin") + .await + .assert_ok(); + assert_eq!(role_of(acme, &admin).await?, None); + app.delete(format!("/api/ui/orgs/acme/members/{}", ada.pid)) + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .await + .assert_status(422); + let told: Option = + db::query!("SELECT count(*) FROM emails WHERE recipient = 'grace@example.com'").scalar().await?; + assert_eq!(told, Some(0), "someone removing themselves isn't emailed"); + Ok(()) +} + +#[laravel::test] +async fn invitation_emails_are_limited_per_recipient(app: Application) -> laravel::Result<()> { + let acme = org("acme").await?; + let admin = person("Grace", "grace@example.com").await?; + join(acme, &admin, "admin", "created").await?; + for n in 0..3 { + let key = format!("old:{n}"); + db::query!( + "INSERT INTO emails (kind, dedupe_key, recipient, data) VALUES ('invited', {key}, 'ada@example.com', '[]')" + ) + .insert() + .await?; + } + app.post("/api/ui/orgs/acme/invitations") + .acting_as(&admin) + .header("sec-fetch-site", "same-origin") + .json(json!({ "invitee": "ada@example.com", "role": "member" })) + .await + .assert_status(429); + app.post("/api/ui/orgs/acme/invitations") + .acting_as(&admin) + .header("sec-fetch-site", "same-origin") + .json(json!({ "invitee": "not an address", "role": "member" })) + .await + .assert_status(422); + Ok(()) +} + +#[laravel::test] +async fn staff_are_no_admins_of_organizations_they_are_not_in(app: Application) -> laravel::Result<()> { + let acme = org("acme").await?; + let admin = person("Grace", "grace@example.com").await?; + join(acme, &admin, "admin", "created").await?; + let staff = person("Sam", "sam@example.com").await?; + let staff_id = staff.id; + db::query!("UPDATE users SET staff = true WHERE id = {staff_id}").update().await?; + let staff = User::find_or_fail(staff_id).await?; + app.get("/api/ui/orgs/acme/members").acting_as(&staff).await.assert_status(404); + app.post("/api/ui/orgs/acme/invitations") + .acting_as(&staff) + .header("sec-fetch-site", "same-origin") + .json(json!({ "invitee": "eve@example.com", "role": "admin" })) + .await + .assert_status(404); + Ok(()) +} diff --git a/app/tests/me.rs b/app/tests/me.rs new file mode 100644 index 00000000..b86ca640 --- /dev/null +++ b/app/tests/me.rs @@ -0,0 +1,116 @@ +//! The person's own page: who they are, their organizations and invitations, their email choices, the billing email +//! (admins), and "How did you hear", which the team's sign-up email waits for. + +use app::models::User; +use laravel::db; +use laravel::model::create; +use laravel::testing::prelude::*; + +async fn person(name: &str, email: &str) -> laravel::Result { + create!(User { pid: laravel::str::uuid7(), name: name, email: email, staff: false }).await +} + +async fn org_with(user: &User, slug: &str, role: &str) -> laravel::Result { + let org: i64 = db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) \ + VALUES (gen_random_uuid(), {slug}, 'Acme', now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + 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(org) +} + +#[laravel::test] +async fn me_shows_their_organizations_and_email_choices(app: Application) -> laravel::Result<()> { + let ada = person("Ada", "ada@example.com").await?; + org_with(&ada, "acme", "admin").await?; + app.get("/api/ui/me") + .acting_as(&ada) + .await + .assert_ok() + .assert_json_path("user.name", "Ada") + .assert_json_path("organizations.0.slug", "acme") + .assert_json_path("organizations.0.role", "admin") + .assert_json_path("notifications.low_credits", true) + .assert_json_path("heard_about_options.1.key", "ai_assistant") + .assert_json_path("forges", json!([])); + // Signed out, the React app (asking for JSON) gets a 401; a page would go to /login + app.get("/api/ui/me").header("accept", "application/json").await.assert_status(401); + + app.patch("/api/ui/me/notifications") + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .json(json!({ "receipts": false })) + .await + .assert_ok() + .assert_json_path("receipts", false) + .assert_json_path("low_credits", true); + Ok(()) +} + +#[laravel::test] +async fn only_admins_set_the_billing_email(app: Application) -> laravel::Result<()> { + let ada = person("Ada", "ada@example.com").await?; + let bob = person("Bob", "bob@example.com").await?; + let org = org_with(&ada, "acme", "admin").await?; + let bob_id = bob.id; + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org}, {bob_id}, 'member', 'invite', now(), now())" + ) + .insert() + .await?; + let put = |who: &User, email: &str| { + app.put("/api/ui/orgs/acme/billing-email") + .acting_as(who) + .header("sec-fetch-site", "same-origin") + .json(json!({ "billing_email": email })) + }; + put(&bob, "ap@example.com").await.assert_status(403); + // Staff who aren't in it are nobody here. + let sam = create!(User { pid: laravel::str::uuid7(), name: "Sam", email: "sam@example.com", staff: true }).await?; + put(&sam, "ap@example.com").await.assert_status(404); + put(&ada, "not an address").await.assert_status(422); + put(&ada, " AP@Example.com ").await.assert_ok().assert_json_path("billing_email", "ap@example.com"); + put(&ada, "").await.assert_ok().assert_json_path("billing_email", json!(null)); + Ok(()) +} + +#[laravel::test] +async fn the_team_hears_about_a_sign_up_once_it_is_answered(app: Application) -> laravel::Result<()> { + let ada = person("Ada", "ada@example.com").await?; + let id = ada.id; + db::query!("UPDATE users SET heard_about_pending = true WHERE id = {id}").update().await?; + app::auth::me::NotifySignups.dispatch().await?; + let queued = || async { + db::query!("SELECT count(*) FROM emails WHERE kind = 'new_signup' AND recipient = 'support@visualci.com'") + .scalar::() + .await + }; + assert_eq!(queued().await?, Some(0), "it waits for the answer"); + + app.post("/api/ui/me/heard-about") + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .json(json!({ "source": "ai_assistant", "detail": "Claude" })) + .await + .assert_ok(); + assert_eq!(queued().await?, Some(1)); + let data: Option = db::query!("SELECT data::text FROM emails WHERE kind = 'new_signup'").scalar().await?; + let data = data.unwrap(); + assert!(data.contains("AI assistant: Claude") && data.contains("ada@example.com"), "{data}"); + app.get("/api/ui/me").acting_as(&ada).await.assert_json_path("heard_about_pending", false); + + // Once only. + app::auth::me::NotifySignups.dispatch().await?; + assert_eq!(queued().await?, Some(1)); + Ok(()) +} diff --git a/app/tests/orgs.rs b/app/tests/orgs.rs new file mode 100644 index 00000000..cd40bce4 --- /dev/null +++ b/app/tests/orgs.rs @@ -0,0 +1,36 @@ +//! Creating an organization: its creator is its admin; slugs are checked and unique; five a day except for staff. + +use app::models::User; +use laravel::db; +use laravel::model::create; +use laravel::testing::prelude::*; + +#[laravel::test] +async fn the_creator_is_the_admin_and_creations_are_limited(app: Application) -> laravel::Result<()> { + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let make = |slug: &str, name: &str| { + app.post("/api/ui/orgs") + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .json(json!({ "slug": slug, "name": name })) + }; + make("acme", " Acme ").await.assert_ok().assert_json_path("slug", "acme"); + let role: Option = db::query!( + "SELECT m.role FROM memberships m JOIN organizations o ON o.id = m.organization_id \ + WHERE o.slug = 'acme' AND o.name = 'Acme'" + ) + .scalar() + .await?; + assert_eq!(role.as_deref(), Some("admin")); + make("acme", "Another").await.assert_status(409); + make("api", "Reserved").await.assert_status(422); + make("Bad Slug", "x").await.assert_status(422); + make("blank", " ").await.assert_status(422); + // A new account's first organization is its own; four more today, then the limit. + for n in 2..=5 { + make(&format!("acme-{n}"), "Acme").await.assert_ok(); + } + make("acme-6", "Acme").await.assert_ok(); + make("acme-7", "Acme").await.assert_status(422); + Ok(()) +} diff --git a/app/tests/staff.rs b/app/tests/staff.rs new file mode 100644 index 00000000..11ee277b --- /dev/null +++ b/app/tests/staff.rs @@ -0,0 +1,49 @@ +//! Staff pages: the latest sign-ups, every email rendered, failed emails retried or dismissed; a 404 for anyone else. + +use app::models::User; +use laravel::db; +use laravel::model::create; +use laravel::testing::prelude::*; + +#[laravel::test] +async fn staff_see_sign_ups_and_emails_and_resolve_failures(app: Application) -> laravel::Result<()> { + let grace = + create!(User { pid: laravel::str::uuid7(), name: "Grace", email: "grace@example.com", staff: true }).await?; + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let ada_id = ada.id; + db::query!( + "UPDATE users SET heard_about_source = 'ai_assistant', heard_about_detail = 'Claude' WHERE id = {ada_id}" + ) + .update() + .await?; + for path in ["/api/ui/staff/signups", "/api/ui/staff/emails"] { + app.get(path).acting_as(&ada).await.assert_status(404); + } + app.get("/api/ui/staff/signups") + .acting_as(&grace) + .await + .assert_ok() + .assert_json_path("signups.0.name", "Ada") + .assert_json_path("signups.0.heard_about", "AI assistant: Claude"); + + let failed: i64 = db::query!( + "INSERT INTO emails (kind, dedupe_key, recipient, data, state, attempts, last_error) \ + VALUES ('welcome', 'w:1', 'ada@example.com', '[]', 'failed', 5, 'Postmark: HTTP 422') RETURNING id" + ) + .scalar() + .await? + .unwrap(); + let page = app.get("/api/ui/staff/emails").acting_as(&grace).await; + page.assert_ok().assert_json_path("failed.0.id", failed).assert_json_path("emails.0.kind", "credits_low"); + let resolve = |who: &User, action: &str| { + app.post(format!("/api/ui/staff/emails/{failed}/resolve")) + .acting_as(who) + .header("sec-fetch-site", "same-origin") + .json(json!({ "action": action })) + }; + resolve(&ada, "dismiss").await.assert_status(404); + resolve(&grace, "dismiss").await.assert_ok(); + resolve(&grace, "dismiss").await.assert_status(404); + app.get("/api/ui/staff/emails").acting_as(&grace).await.assert_json_path("failed", json!([])); + Ok(()) +} diff --git a/app/tests/tokens.rs b/app/tests/tokens.rs new file mode 100644 index 00000000..bf454a6a --- /dev/null +++ b/app/tests/tokens.rs @@ -0,0 +1,81 @@ +//! Tokens in the web app: a personal token works as its person until deleted; a project's admin makes its tokens, +//! a member can't; making one emails a notice. + +use app::models::User; +use laravel::db; +use laravel::model::create; +use laravel::testing::prelude::*; + +async fn person(email: &str) -> laravel::Result { + create!(User { pid: laravel::str::uuid7(), name: "Ada", email: email, staff: false }).await +} + +#[laravel::test] +async fn a_personal_token_works_until_it_is_deleted(app: Application) -> laravel::Result<()> { + let ada = person("ada@example.com").await?; + let made = app + .post("/api/ui/me/tokens") + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .json(json!({ "name": "laptop" })) + .await; + made.assert_ok(); + let token = made.json()["token"].as_str().unwrap().to_string(); + assert!(token.starts_with("vcu_") && token.len() == 44); + app.get("/api/v1/whoami") + .header("authorization", format!("Bearer {token}")) + .await + .assert_ok() + .assert_json_path("client.token_name", "laptop"); + let list = app.get("/api/ui/me/tokens").acting_as(&ada).await; + list.assert_ok().assert_json_path("tokens.0.name", "laptop").assert_json_path("tokens.0.prefix", &token[..10]); + let id = list.json()["tokens"][0]["id"].as_i64().unwrap(); + app.delete(format!("/api/ui/me/tokens/{id}")) + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .await + .assert_ok(); + app.get("/api/v1/whoami").header("authorization", format!("Bearer {token}")).await.assert_status(401); + let notices: Option = db::query!("SELECT count(*) FROM emails WHERE kind = 'token_created'").scalar().await?; + assert_eq!(notices, Some(1)); + Ok(()) +} + +#[laravel::test] +async fn only_a_projects_admins_make_its_tokens(app: Application) -> laravel::Result<()> { + let org: i64 = db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) VALUES (gen_random_uuid(), 'acme', 'Acme', now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + db::query!( + "INSERT INTO projects (pid, organization_id, slug, name, created_at, updated_at) VALUES (gen_random_uuid(), {org}, 'web', 'Web', now(), now())" + ) + .insert() + .await?; + let admin = person("admin@example.com").await?; + let member = person("member@example.com").await?; + for (u, role) in [(admin.id, "admin"), (member.id, "member")] { + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) VALUES ({org}, {u}, {role}, 'created', now(), now())" + ) + .insert() + .await?; + } + let make = |u: &User| { + app.post("/api/ui/orgs/acme/projects/web/tokens") + .acting_as(u) + .header("sec-fetch-site", "same-origin") + .json(json!({ "name": "CI" })) + }; + make(&member).await.assert_status(403); + let token = make(&admin).await.json()["token"].as_str().unwrap().to_string(); + assert!(token.starts_with("vci_")); + app.get("/api/v1/whoami") + .header("authorization", format!("Bearer {token}")) + .await + .assert_ok() + .assert_json_path("principal.kind", "project"); + Ok(()) +} diff --git a/app/tests/webhooks.rs b/app/tests/webhooks.rs new file mode 100644 index 00000000..27974837 --- /dev/null +++ b/app/tests/webhooks.rs @@ -0,0 +1,258 @@ +//! GitHub's webhook: signed deliveries only; merges and closed branches go to the domain once per linked project (by +//! GitHub's repository ID, else URL); installations attach to and detach from linked projects; membership changes +//! queue a recheck of the people they name. + +use app::forge::events::{BranchClosed, PullRequestMerged}; +use app::forge::webhooks::RecheckAccess; +use app::models::User; +use hmac::{Hmac, Mac}; +use laravel::db; +use laravel::model::create; +use laravel::testing::TestResponse; +use laravel::testing::prelude::*; +use sha2::Sha256; + +const SECRET: &str = "github-webhook-test"; + +/// A GitHub App key made once per run (base64 of its PEM, as GITHUB_APP_PRIVATE_KEY_BASE64 holds it). +fn app_key() -> &'static str { + static KEY: std::sync::OnceLock = std::sync::OnceLock::new(); + KEY.get_or_init(|| { + use base64::Engine; + use rsa::pkcs1::EncodeRsaPrivateKey; + let key = rsa::RsaPrivateKey::new(&mut rsa::rand_core::OsRng, 2048).expect("a key"); + let pem = key.to_pkcs1_pem(rsa::pkcs1::LineEnding::LF).expect("its PEM"); + base64::engine::general_purpose::STANDARD.encode(pem.as_bytes()) + }) +} + +fn github() -> Application { + app::testing::configure() + .with_envs([ + ("GITHUB_WEBHOOK_SECRET", SECRET), + ("GITHUB_APP_ID", "1"), + ("GITHUB_APP_PRIVATE_KEY_BASE64", app_key()), + ]) + .create() +} + +fn github_app() -> app::forge::github_app::GithubApp { + app::forge::github_app::GithubApp { + app_id: Some("1".into()), + private_key_base64: Some(app_key().into()), + webhook_secret: None, + } +} + +async fn deliver(app: &Application, kind: &str, event: serde_json::Value) -> TestResponse { + let body = event.to_string(); + let mut mac = Hmac::::new_from_slice(SECRET.as_bytes()).unwrap(); + mac.update(body.as_bytes()); + let signature = format!("sha256={}", hex::encode(mac.finalize().into_bytes())); + app.post("/webhooks/github") + .header("x-github-event", kind) + .header("x-github-delivery", "d-1") + .header("x-hub-signature-256", signature) + .header("content-type", "application/json") + .body(body) + .await +} + +/// Two organizations' projects linking acme/web: one by GitHub's repository ID, one by URL only. +async fn linked() -> laravel::Result<(i64, i64, i64)> { + let mut ids = Vec::new(); + for (slug, repository_id) in [("acme", Some("42")), ("other", None)] { + let org: i64 = db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) \ + VALUES (gen_random_uuid(), {slug}, {slug}, now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + let project: i64 = db::query!( + "INSERT INTO projects (pid, organization_id, slug, name, forge, repository_url, repository_id, \ + forge_installation, created_at, updated_at) \ + VALUES (gen_random_uuid(), {org}, 'web', 'Web', 'github', 'https://github.com/acme/web', {repository_id}, \ + '7', now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + ids.push((org, project)); + } + Ok((ids[0].0, ids[0].1, ids[1].1)) +} + +fn repository() -> serde_json::Value { + json!({ "id": 42, "full_name": "acme/web" }) +} + +#[laravel::test(app = github)] +async fn an_unsigned_delivery_is_refused(app: Application) { + app.post("/webhooks/github") + .header("x-github-event", "ping") + .header("x-hub-signature-256", "sha256=00") + .json(json!({})) + .await + .assert_status(401); +} + +#[laravel::test(app = github)] +async fn a_merge_and_a_deleted_branch_reach_each_linked_project(app: Application) -> laravel::Result<()> { + let (_, by_id, by_url) = linked().await?; + let events = laravel::event::fake(); + let merged = json!({ + "action": "closed", "repository": repository(), + "pull_request": { "merged": true, "merge_commit_sha": "abc123", "base": { "ref": "main" }, + "head": { "ref": "feature", "repo": { "full_name": "acme/web" } } }, + }); + deliver(&app, "pull_request", merged).await.assert_ok().assert_json_path("dispatched", 2); + events.assert_dispatched_times::(2); + events.assert_dispatched_where::(|e| { + e.project_id == by_id && e.head == "feature" && e.base == "main" && e.merge_commit == "abc123" + }); + events.assert_dispatched_where::(|e| e.project_id == by_url); + + // A fork's branch goes by its label + let fork = json!({ + "action": "closed", "repository": repository(), + "pull_request": { "merged": false, "head": { "ref": "main", "label": "octocat:main", + "repo": { "full_name": "octocat/web" } } }, + }); + deliver(&app, "pull_request", fork).await.assert_ok(); + events.assert_dispatched_where::(|e| e.branch == "octocat:main" && e.why == "pull_request"); + let deleted = json!({ "ref": "old", "ref_type": "branch", "repository": repository() }); + deliver(&app, "delete", deleted).await.assert_ok(); + events.assert_dispatched_where::(|e| e.branch == "old" && e.why == "branch_deleted"); + Ok(()) +} + +#[laravel::test(app = github)] +async fn installations_attach_and_detach_and_membership_changes_recheck(app: Application) -> laravel::Result<()> { + let (org, by_id, _) = linked().await?; + let jobs = laravel::queue::fake(); + let _github = laravel::http::client::fake() + .with("api.github.com/app/installations/8", json!({ "id": 8 })) + .with("api.github.com/app/installations/*", laravel::http::client::response().status(404).json(json!({}))); + // A stale "created" for an installation that's gone attaches nothing + let stale = json!({ "action": "created", "installation": { "id": 5 }, "repositories": [repository()] }); + deliver(&app, "installation", stale).await.assert_ok().assert_json_path("ignored", "no such installation"); + let installation = |id: i64| async move { + db::query!("SELECT forge_installation FROM projects WHERE id = {id}").scalar::>().await + }; + // Removing another installation leaves the project's own alone + let other = json!({ "action": "deleted", "installation": { "id": 9 }, "repositories": [repository()] }); + deliver(&app, "installation", other).await.assert_ok().assert_json_path("unlinked", 0); + assert_eq!(installation(by_id).await?.flatten().as_deref(), Some("7")); + let removed = json!({ "action": "removed", "installation": { "id": 7 }, "repositories_removed": [repository()] }); + deliver(&app, "installation_repositories", removed).await.assert_ok().assert_json_path("unlinked", 2); + assert_eq!(installation(by_id).await?.flatten(), None); + let added = json!({ "action": "added", "installation": { "id": 8 }, "repositories_added": [repository()] }); + deliver(&app, "installation_repositories", added).await.assert_ok().assert_json_path("linked", 2); + assert_eq!(installation(by_id).await?.flatten().as_deref(), Some("8")); + + // A collaborator changed: the person with that GitHub ID is rechecked + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let ada_id = ada.id; + db::query!( + "INSERT INTO identities (user_id, forge, site, forge_user_id, login, created_at, updated_at) \ + VALUES ({ada_id}, 'github', '', '1001', 'ada', now(), now())" + ) + .insert() + .await?; + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org}, {ada_id}, 'member', 'github', now(), now())" + ) + .insert() + .await?; + let member = json!({ "action": "removed", "member": { "id": 1001 }, "repository": repository() }); + deliver(&app, "member", member).await.assert_ok().assert_json_path("rechecking", 1); + assert!(jobs.pushed::().iter().any(|j| j.job().user_ids == vec![ada_id])); + Ok(()) +} + +#[laravel::test(app = github)] +async fn a_recheck_reads_each_repositorys_collaborators_once(_app: Application) -> laravel::Result<()> { + let (org, _, _) = linked().await?; + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let ada_id = ada.id; + db::query!( + "INSERT INTO identities (user_id, forge, site, forge_user_id, login, created_at, updated_at) \ + VALUES ({ada_id}, 'github', '', '1001', 'ada', now(), now())" + ) + .insert() + .await?; + let github = laravel::http::client::fake() + .with("api.github.com/app/installations/7/access_tokens", json!({ "token": "t" })) + .with("api.github.com/repositories/42", json!({ "full_name": "acme/web" })) + .with( + "api.github.com/repos/acme/web/collaborators*", + json!([{ "id": 1001, "role_name": "maintain" }, { "id": 2002, "role_name": "read" }]), + ); + assert_eq!(app::forge::webhooks::recheck(&github_app(), &[ada_id]).await?, 1); + let role: Option = + db::query!("SELECT role FROM memberships WHERE organization_id = {org} AND user_id = {ada_id}") + .scalar() + .await?; + assert_eq!(role.as_deref(), Some("admin"), "maintain is admin"); + github.assert_sent_count(3); + Ok(()) +} + +#[laravel::test(app = github)] +async fn a_listing_that_fails_changes_nobody(_app: Application) -> laravel::Result<()> { + let (org, _, _) = linked().await?; + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let ada_id = ada.id; + db::query!( + "INSERT INTO identities (user_id, forge, site, forge_user_id, login, created_at, updated_at) \ + VALUES ({ada_id}, 'github', '', '1001', 'ada', now(), now())" + ) + .insert() + .await?; + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org}, {ada_id}, 'member', 'github', now(), now())" + ) + .insert() + .await?; + let _github = laravel::http::client::fake() + .with("api.github.com/app/installations/7/access_tokens", json!({ "token": "t" })) + .with("api.github.com/repositories/42", json!({ "full_name": "acme/web" })) + .with( + "api.github.com/repos/acme/web/collaborators*", + laravel::http::client::response().status(502).json(json!({})), + ); + assert!(app::forge::webhooks::recheck(&github_app(), &[ada_id]).await.is_err()); + let role: Option = + db::query!("SELECT role FROM memberships WHERE organization_id = {org} AND user_id = {ada_id}") + .scalar() + .await?; + assert_eq!(role.as_deref(), Some("member"), "a partial answer drops nobody"); + Ok(()) +} + +#[laravel::test(app = github)] +async fn a_renamed_repository_moves_its_links_and_edits_say_whether_it_is_private( + app: Application, +) -> laravel::Result<()> { + let (_, by_id, by_url) = linked().await?; + let events = laravel::event::fake(); + let renamed = json!({ "action": "renamed", "repository": { "id": 42, "full_name": "acme/website" } }); + deliver(&app, "repository", renamed).await.assert_ok().assert_json_path("moved", 1); + let url: Option = db::query!("SELECT repository_url FROM projects WHERE id = {by_id}").scalar().await?; + assert_eq!(url.as_deref(), Some("https://github.com/acme/website")); + // A delivery naming the ID backfills a link that only had the URL + let edited = json!({ "action": "edited", "repository": { "id": 77, "full_name": "acme/web", "private": true } }); + deliver(&app, "repository", edited).await.assert_ok(); + events.assert_dispatched_where::(|e| { + e.project_id == by_url && e.private + }); + let id: Option = db::query!("SELECT repository_id FROM projects WHERE id = {by_url}") + .scalar::>() + .await? + .flatten(); + assert_eq!(id.as_deref(), Some("77")); + Ok(()) +}