diff --git a/Cargo.lock b/Cargo.lock index 1bd45293..e119dbd2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5000,6 +5000,7 @@ dependencies = [ "include_dir", "jsonwebtoken", "laravel-rust", + "laravel-rust-cache", "oauth-provider", "oauth-provider-laravel", "regex", diff --git a/app/.env.example b/app/.env.example index 8749382f..9c1315ef 100644 --- a/app/.env.example +++ b/app/.env.example @@ -191,6 +191,75 @@ VISUALCI_STRIPE_WEBHOOK_SECRET= # again. # VISUALCI_LIVE_STREAM_SECONDS=1800 +###################################################################################################################### +# Abuse limits +###################################################################################################################### + +# GitHub App deliveries a minute acted on at once for one installation set up for an organization on a paid plan (or +# linked to a project of one). Past it a delivery is kept and acted on later at this rate (GitHub never redelivers on +# its own). A paid installation's deliveries count against nothing shared. +# VISUALCI_GITHUB_WEBHOOKS_PER_INSTALLATION=600 + +# The same for an installation set up for an organization on the free plan, which anyone can make. Its deliveries also +# count against VISUALCI_GITHUB_WEBHOOKS_TOTAL. +# VISUALCI_GITHUB_WEBHOOKS_PER_FREE_INSTALLATION=120 + +# GitHub App deliveries a minute for one installation nobody has set up. Past it a delivery is dropped (a 202, and a +# warning in the log): nothing of a customer's depends on it. Its installation deliveries (installed, suspended, +# removed), which setting it up needs, count only in VISUALCI_GITHUB_WEBHOOKS_TOTAL. +# VISUALCI_GITHUB_WEBHOOKS_PER_UNCLAIMED_INSTALLATION=60 + +# GitHub App deliveries a minute for all the installations nobody has set up, together, so many strangers' +# installations can't crowd out customers' deliveries. Dropped as above past it. +# VISUALCI_GITHUB_WEBHOOKS_UNCLAIMED_TOTAL=600 + +# GitHub App deliveries a minute for unclaimed and free installations together (paid installations' don't count). A +# free installation's delivery past it is kept for later; an unclaimed one's dropped. +# VISUALCI_GITHUB_WEBHOOKS_TOTAL=6000 + +# The most megabytes of deliveries kept for later for one paid installation. Past a cap, a delivery is answered 503 +# (GitHub logs it as failed, and the redelivery check sends it again later) with an error in the log. +# VISUALCI_GITHUB_WEBHOOKS_DEFERRED_PER_INSTALLATION_MB=50 + +# The most megabytes kept for later for one free installation. +# VISUALCI_GITHUB_WEBHOOKS_DEFERRED_PER_FREE_INSTALLATION_MB=5 + +# The most megabytes kept for later for every free installation together, so free installations, which anyone can +# make, can't fill the store paid ones need. +# VISUALCI_GITHUB_WEBHOOKS_DEFERRED_FREE_TOTAL_MB=50 + +# The most megabytes kept for later for every installation together. +# VISUALCI_GITHUB_WEBHOOKS_DEFERRED_TOTAL_MB=500 + +# OAuth client registrations (/oauth/register) a day from one address (an IPv6 address's /64, since one host gets a +# whole /64) for one redirect URI host. Hosted platforms (such as claude.ai's connectors) register their users' +# clients from shared addresses with their own callback host, so each gets a count of its own. +# VISUALCI_OAUTH_REGISTRATIONS_PER_REDIRECT_HOST=50 + +# OAuth client registrations a day from one address (or IPv6 /64) across every redirect host that isn't a known +# platform's, and three times that from an IPv6 /48. +# VISUALCI_OAUTH_REGISTRATIONS_PER_ADDRESS=60 + +# How many different redirect hosts (other than known platforms') one address registers clients for in a day. +# VISUALCI_OAUTH_REDIRECT_HOSTS_PER_ADDRESS=3 + +# Known platforms' callback hosts (a host or any subdomain of it): their users' MCP clients register from the +# platform's shared addresses, so each gets VISUALCI_OAUTH_REGISTRATIONS_PER_PLATFORM_HOST a day per address, outside +# the per-address limit. +# VISUALCI_OAUTH_PLATFORM_REDIRECT_HOSTS=claude.ai,claude.com,chatgpt.com + +# OAuth client registrations a day from one address for one known platform's callback host. +# VISUALCI_OAUTH_REGISTRATIONS_PER_PLATFORM_HOST=2000 + +# The most registered OAuth clients that have never connected. A registration past it first deletes the oldest of them +# registered over a day ago with no sign-in under way (a warning in the log), and is refused with a 429 while none is +# that old; oauth:prune deletes the rest after a week. +# VISUALCI_OAUTH_UNUSED_CLIENTS=100000 + +# Past this many clients that have never connected, the oldest are deleted whatever their age, so young registrations +# can't keep new ones out. +# VISUALCI_OAUTH_UNUSED_CLIENTS_CEILING=150000 + ###################################################################################################################### # Heartbeats ###################################################################################################################### @@ -255,6 +324,12 @@ VISUALCI_STRIPE_WEBHOOK_SECRET= # Secret. The credit override reminder's token. # VISUALCI_CREDIT_OVERRIDES_HEARTBEAT_TOKEN= +# The check for GitHub App deliveries that failed (every ten minutes), which asks GitHub to redeliver them. +# VISUALCI_WEBHOOK_REDELIVERY_HEARTBEAT_URL= + +# Secret. The redelivery check's token. +# VISUALCI_WEBHOOK_REDELIVERY_HEARTBEAT_TOKEN= + ###################################################################################################################### # Laravel Rust ###################################################################################################################### diff --git a/app/Cargo.toml b/app/Cargo.toml index 8afa4694..bbd512ca 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -21,6 +21,8 @@ path = "src/main.rs" [dependencies] # Pinned exactly: each 0.x minor of Laravel Rust may break, and upgrades are deliberate. laravel-rust = { version = "=0.1.4", features = ["database-postgres", "minijinja"] } +# The framework's rate-limit buckets, for giving a count back (`laravel::rate_limit` doesn't export `Bucket` in 0.1.4) +laravel_cache = { package = "laravel-rust-cache", version = "=0.1.4", default-features = false } # The same axum Laravel Rust runs on, for extractors (auth::Principal) axum = "0.8" base64 = "0.22" diff --git a/app/database/migrations/2026_12_06_000000_bounded_forge_work.rs b/app/database/migrations/2026_12_06_000000_bounded_forge_work.rs new file mode 100644 index 00000000..427aac0d --- /dev/null +++ b/app/database/migrations/2026_12_06_000000_bounded_forge_work.rs @@ -0,0 +1,112 @@ +//! Bounded forge work now that the GitHub App is public (sc-9144, sc-9124). +//! +//! - `access_rechecks`: the people a webhook asked to recheck, waiting for the next `RecheckAccess` run: deliveries +//! add to it, and one debounced run reads every linked repository's collaborators once for all of them. `/status` +//! says how long the oldest has waited. +//! - `deferred_webhooks`: verified deliveries for a claimed installation that arrived over its rate limit, kept to be +//! acted on at the allowed rate (`DrainDeferredWebhooks`) instead of refused, since GitHub never redelivers on its +//! own. Capped in bytes per installation and in total. `/status` says how long the oldest has waited. +//! - `webhook_redeliveries`: failed deliveries the ten-minute check found in GitHub's delivery log, drained across runs; +//! `webhook_redelivery_marks` how far it has read the log (and where to go on after a run that stopped at its cap). +//! - `deferred_webhook_bytes`: the bytes kept for later per installation, for free installations and in total. +//! - `webhook_deliveries_seen`: claimed installations' deliveries acted on, by GUID, so one GitHub sends twice is acted +//! on once. +//! - `user_installations.repositories_listed`/`repositories_total`/`repositories_complete`: how many of an +//! installation's repositories the person's last sign-in listed for the picker, of how many GitHub has (`NULL` when +//! it read none), and whether that's all of them. The picker's search goes to GitHub for an installation it didn't +//! list completely. +//! - `projects_forge_installation` finds an installation's projects, which every delivery asks (whether anyone has +//! claimed the installation) and a team change rechecks. + +use laravel::db::AnyTransaction; + +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.query(SCHEMA).unprepared().await?; + Ok(()) +} + +const SCHEMA: &str = r#" +CREATE TABLE access_rechecks ( + user_id BIGINT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, + queued_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE TABLE deferred_webhooks ( + id BIGSERIAL PRIMARY KEY, + installation_id TEXT NOT NULL, + -- GitHub's delivery GUID (X-GitHub-Delivery), so a redelivered one is kept once. + delivery TEXT NOT NULL, + kind TEXT NOT NULL, + -- The delivery's body, whose signature was checked before it was kept. + payload TEXT NOT NULL, + bytes BIGINT NOT NULL, + -- Whether its installation was a paid organization's when it was kept (free ones share a smaller cap). + paid BOOLEAN NOT NULL DEFAULT false, + attempts INT NOT NULL DEFAULT 0, + -- A drain acting on it until then: another run leaves it (and the rest of its installation's) alone. + claimed_until TIMESTAMPTZ, + received_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE UNIQUE INDEX deferred_webhooks_delivery ON deferred_webhooks (delivery) WHERE delivery <> ''; +CREATE INDEX deferred_webhooks_installation ON deferred_webhooks (installation_id, id); + +-- Failed deliveries the redelivery check found in the App's delivery log, by GUID, drained across runs: `pending` +-- (to ask GitHub for, from `next_at`), `redelivered` (asked; a newer attempt that fails makes it pending again), +-- `succeeded` (an attempt got a 2xx), `given_up` (after `tries` asks, or older than GitHub keeps), or `skipped` (an +-- unclaimed installation's). +CREATE TABLE webhook_redeliveries ( + guid TEXT PRIMARY KEY, + installation_id TEXT, + -- Whether its installation was a paid organization's when it was recorded: paid ones are asked for first. + paid BOOLEAN NOT NULL DEFAULT false, + -- The oldest and the newest attempt seen, and the attempt last asked to be redelivered. + first_attempt_id BIGINT NOT NULL, + last_attempt_id BIGINT NOT NULL, + requested_attempt_id BIGINT, + state TEXT NOT NULL DEFAULT 'pending', + tries INT NOT NULL DEFAULT 0, + next_at TIMESTAMPTZ NOT NULL DEFAULT now(), + error TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE INDEX webhook_redeliveries_pending ON webhook_redeliveries (paid DESC, first_attempt_id) WHERE state = 'pending'; + +-- How far the redelivery check has read GitHub's delivery log: everything at or below `delivery_id` is read. A run +-- that stopped at its page cap keeps where to go on (`resume_cursor`) and the newest ID that scan started from +-- (`resume_newest`), which becomes the mark once the scan reaches the old one. +CREATE TABLE webhook_redelivery_marks ( + name TEXT PRIMARY KEY, + delivery_id BIGINT, + resume_cursor TEXT, + resume_newest BIGINT, + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +-- Bytes of deliveries kept for later, per installation (`installation:`), for free installations (`free`) and in +-- total (`total`), kept in step with `deferred_webhooks` so keeping one locks only its installation's row. +CREATE TABLE deferred_webhook_bytes ( + scope TEXT PRIMARY KEY, + bytes BIGINT NOT NULL DEFAULT 0 +); + +-- Claimed installations' deliveries, by GUID, so one sent twice is acted on once: `processing` from `started_at` (a +-- claim older than two minutes was abandoned, a request cut off or a worker gone, and the next delivery takes it +-- over), then `done`. Kept three days. +CREATE TABLE webhook_deliveries_seen ( + delivery TEXT PRIMARY KEY, + state TEXT NOT NULL DEFAULT 'processing', + -- A random token naming the claim: only its holder finishes or lets it go, so a late release can't undo a + -- takeover's claim. + owner TEXT NOT NULL DEFAULT '', + started_at TIMESTAMPTZ NOT NULL DEFAULT now(), + seen_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE INDEX webhook_deliveries_seen_at ON webhook_deliveries_seen (seen_at); + +ALTER TABLE user_installations ADD COLUMN repositories_listed INT NOT NULL DEFAULT 0; +ALTER TABLE user_installations ADD COLUMN repositories_total INT; +ALTER TABLE user_installations ADD COLUMN repositories_complete BOOLEAN NOT NULL DEFAULT true; + +CREATE INDEX projects_forge_installation ON projects (forge_installation) WHERE forge_installation IS NOT NULL; +"#; diff --git a/app/src/auth/mod.rs b/app/src/auth/mod.rs index 5be61e1f..4bb41952 100644 --- a/app/src/auth/mod.rs +++ b/app/src/auth/mod.rs @@ -309,9 +309,12 @@ pub fn routes(route: &mut laravel::prelude::Router) { oauth::routes(route); device::routes(route); staff::routes(route); - route.get("/auth/{forge}", sign_in::start); + // Anyone can start a sign-in, and each callback exchanges its code with the forge: 60 a minute per address keeps a + // flood from becoming a flood of calls to GitHub on VisualCI's OAuth client (sc-9144) + let sign_ins = || laravel::http::middleware::Throttle::per_minute(60).bucket("sign-in"); + route.get("/auth/{forge}", sign_in::start).middleware(sign_ins()); route.post("/auth/{forge}/link", sign_in::link); - route.get("/auth/{forge}/callback", sign_in::callback); + route.get("/auth/{forge}/callback", sign_in::callback).middleware(sign_ins()); route.get("/auth/session", sign_in::session); route.get("/auth/providers", sign_in::providers); route.post("/auth/logout", sign_in::logout); diff --git a/app/src/auth/oauth.rs b/app/src/auth/oauth.rs index 5b224353..cc462734 100644 --- a/app/src/auth/oauth.rs +++ b/app/src/auth/oauth.rs @@ -24,6 +24,7 @@ use laravel::auth::{Auth, Authenticated}; use laravel::container::Inject; use laravel::http::{Next, Request, Response, middleware}; use laravel::prelude::*; +use laravel::rate_limit::Limit; use oauth_provider_laravel::{OAuth, OAuthConfig, OAuthServiceProvider, OAuthTokens}; use serde_json::{Value, json}; @@ -156,6 +157,242 @@ pub async fn consent_scopes(auth: Auth, oauth: Inject, request: Req if get && admin { admin_warning(response, &redirect_uri).await } else { response } } +/// The addresses a registration counts against: an IPv4 address; or for IPv6, its /64 (one host gets a whole /64, so +/// counting each /128 would give it billions of counts) and its /48 (a site's allocation), each with a limit. +#[must_use] +pub fn registration_addresses(ip: std::net::IpAddr) -> Vec { + match ip { + std::net::IpAddr::V4(v4) => vec![v4.to_string()], + std::net::IpAddr::V6(v6) => match v6.to_ipv4_mapped() { + Some(v4) => vec![v4.to_string()], + None => { + let s = v6.segments(); + vec![ + format!("{:x}:{:x}:{:x}:{:x}::/64", s[0], s[1], s[2], s[3]), + format!("{:x}:{:x}:{:x}::/48", s[0], s[1], s[2]), + ] + } + }, + } +} + +/// The host of a registration's first redirect URI (lowercased), or `-` when it has none a URL parser can read: hosted +/// platforms register many clients from shared addresses, each with the platform's own callback host, so the per-day +/// count is per address and redirect host. +#[must_use] +pub fn redirect_host(body: &[u8]) -> String { + serde_json::from_slice::(body) + .ok() + .and_then(|v| v["redirect_uris"][0].as_str().and_then(|u| url::Url::parse(u).ok())) + .and_then(|u| u.host_str().map(str::to_ascii_lowercase)) + .unwrap_or_else(|| "-".to_string()) +} + +/// Whether `address` may register a client for redirect host `host` today: one it has registered for already, or a new +/// one while it has used fewer than `most` different hosts today (remembered in the cache store for a day from the +/// first). Concurrent registrations may slip one host past the limit. +async fn another_host_allowed(address: &str, host: &str, most: u32) -> bool { + use laravel::time::ToSpan; + let key = format!("oauth:register-hosts:{address}"); + let mut hosts: Vec = laravel::cache::get(&key).await.ok().flatten().unwrap_or_default(); + if hosts.iter().any(|h| h == host) { + return true; + } + if hosts.len() >= most as usize { + return false; + } + hosts.push(host.to_string()); + if let Err(e) = laravel::cache::put(&key, hosts, 1.days()).await { + tracing::warn!(error = %e, "couldn't remember an address's redirect hosts"); + } + true +} + +/// How many registrations a /48 may make in a day, as a multiple of a single address's overall limit. +const SITE_MULTIPLE: u32 = 3; + +/// How old a never-connected client must be before a registration past the cap may delete it: a person may take a +/// while between registering a client and signing in (signing up, installing the GitHub App). +const UNUSED_CLIENT_MIN_AGE_SECONDS: i64 = 24 * 3600; + +/// Anonymous client registrations (RFC 7591, `POST /oauth/register`, with or without a trailing slash): at most +/// `VISUALCI_OAUTH_REGISTRATIONS_PER_REDIRECT_HOST` a day from one address (or IPv6 /64) for one redirect URI host, `VISUALCI_OAUTH_REGISTRATIONS_PER_ADDRESS` across them (three times that from an IPv6 /48) and `VISUALCI_OAUTH_REDIRECT_HOSTS_PER_ADDRESS` different hosts; a known platform's callback host (`VISUALCI_OAUTH_PLATFORM_REDIRECT_HOSTS`, whose users register from its shared addresses) gets `VISUALCI_OAUTH_REGISTRATIONS_PER_PLATFORM_HOST` a day per address, outside those ([`registration_addresses`]), and at most +/// `VISUALCI_OAUTH_UNUSED_CLIENTS` clients that have never connected: a registration past that first deletes the oldest +/// of them (registered more than a day ago, with no sign-in under way), so a flood can't stop new MCP clients +/// registering, and the table stays bounded (sc-9144). Past the per-address limit, or when nothing old enough can make +/// room, a `429` with `Retry-After`. +#[middleware] +pub async fn limit_registrations( + oauth: Inject, + limits: laravel::config::Section, + request: Request, + next: Next, +) -> Response { + if request.method() != laravel::http::Method::POST { + return next.run(request).await; + } + let endpoint = oauth + .config() + .registration_endpoint + .as_deref() + .map(|e| url::Url::parse(e).map_or_else(|_| e.to_string(), |u| u.path().to_string())); + let path = crate::http::hosts::normalized(request.path()); + if !endpoint.is_some_and(|e| path.trim_end_matches('/') == e.to_ascii_lowercase().trim_end_matches('/')) { + return next.run(request).await; + } + let too_many = |wait: String| { + Response::new(axum::Json(json!({ + "error": "too_many_requests", + "error_description": "Too many client registrations: try again later, or reuse the client you registered.", + }))) + .with_status(429) + .with_header("retry-after", wait) + }; + let addresses = registration_addresses(request.ip()); + let address = addresses.join(" "); + // The redirect URI's host, from the registration's body (read once, then handed on) + let (parts, body) = request.into_http().into_parts(); + let Ok(bytes) = axum::body::to_bytes(body, 64 * 1024).await else { + return Response::new(axum::Json( + json!({ "error": "invalid_client_metadata", "error_description": "too large" }), + )) + .with_status(413); + }; + let host = redirect_host(&bytes); + let request = Request::from_http(axum::http::Request::from_parts(parts, axum::body::Body::from(bytes))); + let first = &addresses[0]; + let platform = limits + .oauth_platform_redirect_hosts + .iter() + .map(|p| p.trim().to_ascii_lowercase()) + .any(|p| !p.is_empty() && (host == p || host.ends_with(&format!(".{p}")))); + let per_address = limits.oauth_registrations_per_address.max(1); + let counts = if platform { + // A known platform's callback host: its own large count, outside the per-address limits + vec![( + format!("oauth:register:{first}:{host}"), + Limit::per_day(limits.oauth_registrations_per_platform_host.max(1)), + )] + } else { + if !another_host_allowed(first, &host, limits.oauth_redirect_hosts_per_address.max(1)).await { + warn_refused(&address, "too many different redirect hosts from one address"); + return too_many("3600".into()); + } + let mut counts = vec![ + ( + format!("oauth:register:{first}:{host}"), + Limit::per_day(limits.oauth_registrations_per_redirect_host.max(1)), + ), + (format!("oauth:register:{first}"), Limit::per_day(per_address)), + ]; + for site in addresses.iter().skip(1) { + counts.push((format!("oauth:register:{site}"), Limit::per_day(per_address.saturating_mul(SITE_MULTIPLE)))); + } + counts + }; + let mut taken = Vec::new(); + for (key, limit) in counts { + match laravel_cache::rate_limit::Bucket::new(&key, limit).attempt().await { + Ok(Ok((_, bucket))) => taken.push(bucket), + Ok(Err(over)) => { + for bucket in &taken { + let _ = bucket.give_back().await; + } + let wait = over + .headers() + .get(axum::http::header::RETRY_AFTER) + .and_then(|v| v.to_str().ok()) + .unwrap_or("60") + .to_string(); + warn_refused(&address, "over a per-address limit"); + return too_many(wait); + } + Err(e) => { + for bucket in &taken { + let _ = bucket.give_back().await; + } + tracing::error!(error = %e, "OAuth registration limit: the cache store didn't answer"); + return Response::new(axum::Json(json!({ "error": "temporarily_unavailable" }))) + .with_status(503) + .with_header("retry-after", "30"); + } + } + } + match make_room_for_a_client(limits.oauth_unused_clients.max(1), limits.oauth_unused_clients_ceiling.max(1)).await { + Ok(true) => next.run(request).await, + Ok(false) => { + warn_refused(&address, "too many clients that never connected"); + too_many("600".into()) + } + Err(e) => { + tracing::error!(error = %e, "OAuth registration: couldn't count the clients that never connected"); + Response::new(axum::Json(json!({ "error": "temporarily_unavailable" }))) + .with_status(503) + .with_header("retry-after", "30") + } + } +} + +/// Warn that registrations are being refused, at most once a minute per process (a flood doesn't flood the log), with +/// how many were refused since the last warning. +fn warn_refused(address: &str, why: &'static str) { + use std::sync::{Mutex, OnceLock}; + use std::time::{Duration, Instant}; + static LAST: OnceLock, u64)>> = OnceLock::new(); + let mut last = LAST.get_or_init(|| Mutex::new((None, 0))).lock().unwrap_or_else(std::sync::PoisonError::into_inner); + last.1 += 1; + if last.0.is_none_or(|at| at.elapsed() >= Duration::from_secs(60)) { + let refused = std::mem::take(&mut last.1); + last.0 = Some(Instant::now()); + tracing::warn!(address, why, refused, "OAuth client registrations refused (429)"); + } +} + +/// Keep the clients that have never connected under `cap`: past `ceiling`, the oldest are deleted whatever their age +/// (a flood of young registrations can't fill the table); between the two, the oldest registered over a day ago, with +/// no authorization code (no sign-in under way), make room for one more. Returns whether there's room. Concurrent +/// registrations may overshoot by how many arrive at once, which the next one corrects. +async fn make_room_for_a_client(cap: i64, ceiling: i64) -> laravel::Result { + let unused: Option = + laravel::db::query!("SELECT COUNT(*) FROM oauth_clients WHERE last_connected_at IS NULL").scalar().await?; + let mut unused = unused.unwrap_or(0); + let over_ceiling = unused - ceiling.max(cap) + 1; + if over_ceiling > 0 { + let deleted = laravel::db::query!( + "DELETE FROM oauth_clients WHERE client_key IN (SELECT c.client_key FROM oauth_clients c \ + WHERE c.last_connected_at IS NULL \ + AND NOT EXISTS (SELECT 1 FROM oauth_codes k WHERE k.client_key = c.client_key) \ + ORDER BY c.created_at LIMIT {over_ceiling})" + ) + .delete() + .await?; + tracing::warn!( + deleted, + ceiling, + "OAuth clients that never connected deleted, whatever their age: past the ceiling" + ); + unused -= i64::try_from(deleted).unwrap_or(0); + } + let excess = unused - cap + 1; + if excess <= 0 { + return Ok(true); + } + // `created_at` is in microseconds + let before = (laravel::now().timestamp().as_second() - UNUSED_CLIENT_MIN_AGE_SECONDS) * 1_000_000; + let deleted = laravel::db::query!( + "DELETE FROM oauth_clients WHERE client_key IN (SELECT c.client_key FROM oauth_clients c \ + WHERE c.last_connected_at IS NULL AND c.created_at < {before} \ + AND NOT EXISTS (SELECT 1 FROM oauth_codes k WHERE k.client_key = c.client_key) \ + ORDER BY c.created_at LIMIT {excess})" + ) + .delete() + .await?; + if deleted > 0 { + tracing::warn!(deleted, cap, "OAuth clients that never connected deleted to make room: the cap is reached"); + } + Ok(i64::try_from(deleted).unwrap_or(0) >= excess) +} + /// The admin consent page's warning, under its heading: what admin access lets the app do, and the host the person is /// sent back to, so a staff member can see a client that isn't theirs before allowing it. It uses the consent page's /// own `warning` and `muted` styles. diff --git a/app/src/auth/sign_in.rs b/app/src/auth/sign_in.rs index 52d263c9..a71a7396 100644 --- a/app/src/auth/sign_in.rs +++ b/app/src/auth/sign_in.rs @@ -188,6 +188,8 @@ pub async fn callback( // The GitHub App's installations they can reach, for the setup page and the checklist's offers if sign_in.identity.forge == ForgeKind::Github { forge::installations::remember(user.id, &sign_in.installations, &sign_in.reachable).await?; + forge::installations::remember_listings(user.id, &sign_in.listings).await?; + forge::github::remember_user_token(user.id, &profile.token).await; } SignedIn { user_id: user.id, @@ -366,6 +368,10 @@ pub async fn logout( auth: Auth, hosts: laravel::config::Section, ) -> laravel::Result { + // The GitHub token kept from their sign-in for the picker's search goes with the session + if let Some(user) = auth.user().await? { + forge::github::forget_user_token(user.id).await; + } auth.logout().await?; Ok(laravel::http::Response::new(Json(serde_json::json!({ "ok": true }))).with_cookie(signed_in_hint(&hosts, false))) } diff --git a/app/src/config.rs b/app/src/config.rs index 95f43085..846312c6 100644 --- a/app/src/config.rs +++ b/app/src/config.rs @@ -47,6 +47,8 @@ pub struct Config { #[settings(nested)] pub live: Live, #[settings(nested)] + pub limits: Limits, + #[settings(nested)] pub heartbeats: Heartbeats, } @@ -275,6 +277,80 @@ pub struct Live { pub stream_seconds: u64, } +/// Limits on the work anyone on the internet can start: the GitHub App is public, so anyone can install it and send +/// its webhook deliveries, and MCP clients register themselves with the OAuth server. Each count is shared by every +/// web process (the cache store). A count fills at once and empties evenly: 60 a minute allows a burst of 60, then one +/// a second. +#[derive(Clone, Settings)] +#[settings(title = "Abuse limits")] +pub struct Limits { + /// GitHub App deliveries a minute acted on at once for one installation set up for an organization on a paid plan + /// (or linked to a project of one). Past it a delivery is kept and acted on later at this rate (GitHub never + /// redelivers on its own). A paid installation's deliveries count against nothing shared. + #[env("VISUALCI_GITHUB_WEBHOOKS_PER_INSTALLATION", default = 600)] + pub webhooks_per_installation: u32, + /// The same for an installation set up for an organization on the free plan, which anyone can make. Its deliveries + /// also count against `VISUALCI_GITHUB_WEBHOOKS_TOTAL`. + #[env("VISUALCI_GITHUB_WEBHOOKS_PER_FREE_INSTALLATION", default = 120)] + pub webhooks_per_free_installation: u32, + /// GitHub App deliveries a minute for one installation nobody has set up. Past it a delivery is dropped (a 202, and + /// a warning in the log): nothing of a customer's depends on it. Its `installation` deliveries (installed, + /// suspended, removed), which setting it up needs, count only in `VISUALCI_GITHUB_WEBHOOKS_TOTAL`. + #[env("VISUALCI_GITHUB_WEBHOOKS_PER_UNCLAIMED_INSTALLATION", default = 60)] + pub webhooks_per_unclaimed_installation: u32, + /// GitHub App deliveries a minute for all the installations nobody has set up, together, so many strangers' + /// installations can't crowd out customers' deliveries. Dropped as above past it. + #[env("VISUALCI_GITHUB_WEBHOOKS_UNCLAIMED_TOTAL", default = 600)] + pub webhooks_unclaimed_total: u32, + /// GitHub App deliveries a minute for unclaimed and free installations together (paid installations' don't count). + /// A free installation's delivery past it is kept for later; an unclaimed one's dropped. + #[env("VISUALCI_GITHUB_WEBHOOKS_TOTAL", default = 6000)] + pub webhooks_total: u32, + /// The most megabytes of deliveries kept for later for one paid installation. Past a cap, a delivery is answered 503 + /// (GitHub logs it as failed, and the redelivery check sends it again later) with an error in the log. + #[env("VISUALCI_GITHUB_WEBHOOKS_DEFERRED_PER_INSTALLATION_MB", default = 50)] + pub webhooks_deferred_per_installation_mb: u64, + /// The most megabytes kept for later for one free installation. + #[env("VISUALCI_GITHUB_WEBHOOKS_DEFERRED_PER_FREE_INSTALLATION_MB", default = 5)] + pub webhooks_deferred_per_free_installation_mb: u64, + /// The most megabytes kept for later for every free installation together, so free installations, which anyone can + /// make, can't fill the store paid ones need. + #[env("VISUALCI_GITHUB_WEBHOOKS_DEFERRED_FREE_TOTAL_MB", default = 50)] + pub webhooks_deferred_free_total_mb: u64, + /// The most megabytes kept for later for every installation together. + #[env("VISUALCI_GITHUB_WEBHOOKS_DEFERRED_TOTAL_MB", default = 500)] + pub webhooks_deferred_total_mb: u64, + /// OAuth client registrations (`/oauth/register`) a day from one address (an IPv6 address's /64, since one host + /// gets a whole /64) for one redirect URI host. Hosted platforms (such as claude.ai's connectors) register their + /// users' clients from shared addresses with their own callback host, so each gets a count of its own. + #[env("VISUALCI_OAUTH_REGISTRATIONS_PER_REDIRECT_HOST", default = 50)] + pub oauth_registrations_per_redirect_host: u32, + /// OAuth client registrations a day from one address (or IPv6 /64) across every redirect host that isn't a known + /// platform's, and three times that from an IPv6 /48. + #[env("VISUALCI_OAUTH_REGISTRATIONS_PER_ADDRESS", default = 60)] + pub oauth_registrations_per_address: u32, + /// How many different redirect hosts (other than known platforms') one address registers clients for in a day. + #[env("VISUALCI_OAUTH_REDIRECT_HOSTS_PER_ADDRESS", default = 3)] + pub oauth_redirect_hosts_per_address: u32, + /// Known platforms' callback hosts (a host or any subdomain of it): their users' MCP clients register from the + /// platform's shared addresses, so each gets `VISUALCI_OAUTH_REGISTRATIONS_PER_PLATFORM_HOST` a day per address, + /// outside the per-address limit. + #[env("VISUALCI_OAUTH_PLATFORM_REDIRECT_HOSTS", default = "claude.ai,claude.com,chatgpt.com")] + pub oauth_platform_redirect_hosts: Vec, + /// OAuth client registrations a day from one address for one known platform's callback host. + #[env("VISUALCI_OAUTH_REGISTRATIONS_PER_PLATFORM_HOST", default = 2000)] + pub oauth_registrations_per_platform_host: u32, + /// The most registered OAuth clients that have never connected. A registration past it first deletes the oldest of + /// them registered over a day ago with no sign-in under way (a warning in the log), and is refused with a 429 while + /// none is that old; `oauth:prune` deletes the rest after a week. + #[env("VISUALCI_OAUTH_UNUSED_CLIENTS", default = 100_000)] + pub oauth_unused_clients: i64, + /// Past this many clients that have never connected, the oldest are deleted whatever their age, so young + /// registrations can't keep new ones out. + #[env("VISUALCI_OAUTH_UNUSED_CLIENTS_CEILING", default = 150_000)] + pub oauth_unused_clients_ceiling: i64, +} + /// Each scheduled job pushes its result to a [Gatus](https://gatus.io) external endpoint, so a run that failed, or no /// run at all, alerts. Each pair is the endpoint's URL and its token; a job without a URL pushes nothing. #[derive(Clone, Settings)] @@ -340,6 +416,12 @@ pub struct Heartbeats { /// The credit override reminder's token. #[env("VISUALCI_CREDIT_OVERRIDES_HEARTBEAT_TOKEN", secret)] pub credit_overrides_token: Option, + /// The check for GitHub App deliveries that failed (every ten minutes), which asks GitHub to redeliver them. + #[env("VISUALCI_WEBHOOK_REDELIVERY_HEARTBEAT_URL")] + pub webhook_redelivery_url: Option, + /// The redelivery check's token. + #[env("VISUALCI_WEBHOOK_REDELIVERY_HEARTBEAT_TOKEN", secret)] + pub webhook_redelivery_token: Option, } /// The variables Laravel Rust reads itself. VisualCI keeps the framework's names for them. @@ -489,6 +571,7 @@ pub fn install(config: &mut laravel::config::Config, env: &laravel::config::Env) .set(settings.cloudflare.clone()) .set(settings.gallery.clone()) .set(settings.live.clone()) + .set(settings.limits.clone()) .set(settings.heartbeats.clone()) .set(settings); } diff --git a/app/src/forge/calls.rs b/app/src/forge/calls.rs new file mode 100644 index 00000000..77bb4fa1 --- /dev/null +++ b/app/src/forge/calls.rs @@ -0,0 +1,170 @@ +//! Counting the GitHub API calls each request and each job makes (sc-9124). +//! +//! A request handler must never make an unbounded number of GitHub calls: on 4 Dec 2026 `/github/setup` made projects +//! one after another, at about 4 s of GitHub calls each, until it hit the 30 s request limit and answered 503. Every +//! request runs inside [`count_github_calls`], and the application's HTTP client ([`client`]) counts each request it +//! sends to GitHub's API against the request (or job) it's sent for: +//! +//! - a request may make [`DEFAULT_BUDGET`] calls, or what [`BUDGETS`] allows it, with why. Past that the log gets an +//! error naming the route, and under `APP_ENV=testing` the response becomes a 500 saying so, so any test that +//! reaches a handler looping over a GitHub list fails CI; +//! - every request that made a call logs how many (`github_calls`), so one that starts paging through a long list +//! shows up before it times out; +//! - a queued job counts its own calls ([`in_job`]), logged when it ends; a job's loops over pages stop at a page cap +//! with an error saying which list was too long (`github_app`, `github`). +//! +//! The framework's social login exchanges a sign-in's code and reads `/user` with a client of its own, so those two +//! calls aren't counted. Tests run queued jobs inline, inside the request that dispatched them: [`in_job`] keeps a +//! job's calls off that request's count, as production does. + +use std::future::Future; +use std::sync::Arc; +use std::sync::atomic::{AtomicU32, Ordering}; + +use laravel::config::app::Environment; +use laravel::http::client::Client; +use laravel::http::{Next, Request, Response, middleware}; + +tokio::task_local! { + static CALLS: Arc; +} + +/// The most GitHub calls a request may make unless [`BUDGETS`] names it. +pub const DEFAULT_BUDGET: u32 = 5; + +/// A sign-in: the person's verified addresses, one page of their installations ([`super::github::SIGN_IN_INSTALLATIONS`]) +/// and at most [`super::github::SIGN_IN_REPOSITORY_PAGES`] pages of repositories across them. +pub const SIGN_IN_BUDGET: u32 = 2 + super::github::SIGN_IN_REPOSITORY_PAGES; + +/// Linking a repository checks it live (`link::link_repository`): the installation that reaches it, the person's +/// permission (a token, their login, collaborator and permission), its ID, then its visibility and licence +/// (`open_source::refresh`: a token, its path by ID, the repository). +pub const LINK_BUDGET: u32 = 10; + +/// Requests allowed more than [`DEFAULT_BUDGET`]: method, path (`*` is one segment), the most calls, and why. Each is +/// still a fixed number, whatever the size of the organization. +pub const BUDGETS: &[(&str, &str, u32, &str)] = &[ + ( + "GET", + "/auth/github/callback", + SIGN_IN_BUDGET, + "a sign-in lists the person's installations and repositories, a page at a time, up to fixed caps", + ), + ("PATCH", "/api/ui/orgs/*/projects/*", LINK_BUDGET, "updating a project may link its repository, checked live"), + ("POST", "/mcp", LINK_BUDGET, "the update_project tool may link a repository, checked live"), +]; + +/// The most GitHub calls `method path` may make, and why when it's more than [`DEFAULT_BUDGET`]. +#[must_use] +pub fn budget(method: &str, path: &str) -> (u32, Option<&'static str>) { + BUDGETS + .iter() + .find(|(m, pattern, _, _)| m.eq_ignore_ascii_case(method) && matches(pattern, path)) + .map_or((DEFAULT_BUDGET, None), |(_, _, n, why)| (*n, Some(*why))) +} + +fn matches(pattern: &str, path: &str) -> bool { + let path = path.trim_end_matches('/'); + let (mut p, mut s) = (pattern.split('/'), path.split('/')); + loop { + match (p.next(), s.next()) { + (None, None) => return true, + (Some("*"), Some(seg)) if !seg.is_empty() => {} + (Some(a), Some(b)) if a == b => {} + _ => return false, + } + } +} + +/// Whether a URL is GitHub's API (api.github.com, or a GitHub Enterprise server's `/api/v3`). +fn is_github(url: &str) -> bool { + let api = super::github_api(); + url.len() > api.len() && url[..api.len()].eq_ignore_ascii_case(&api) && url.as_bytes()[api.len()] == b'/' +} + +/// Count one call against the current request or job, if there is one. +fn count(url: &str) { + let _ = CALLS.try_with(|calls| { + if is_github(url) { + calls.fetch_add(1, Ordering::Relaxed); + } + }); +} + +/// GitHub calls counted so far for the current request or job (0 outside one). +#[must_use] +pub fn so_far() -> u32 { + CALLS.try_with(|calls| calls.load(Ordering::Relaxed)).unwrap_or(0) +} + +/// The application's HTTP client: the framework's defaults, counting each request to GitHub's API. +#[must_use] +pub fn client() -> Client { + Client::new().before_sending(|request| { + if let Ok(url) = request.url() { + count(url.as_str()); + } + request + }) +} + +/// Run a queued job's work with a count of its own, logged when it made any calls. +pub async fn in_job(job: &'static str, work: F) -> F::Output { + let calls = Arc::new(AtomicU32::new(0)); + let out = CALLS.scope(calls.clone(), work).await; + let n = calls.load(Ordering::Relaxed); + if n > 0 { + tracing::info!(job, github_calls = n, "GitHub calls"); + } + out +} + +/// Every request: count its GitHub calls and hold it to its budget ([`budget`]). +#[middleware] +pub async fn count_github_calls(request: Request, next: Next) -> Response { + let (method, path) = (request.method().as_str().to_string(), request.path().to_string()); + let calls = Arc::new(AtomicU32::new(0)); + let response = CALLS.scope(calls.clone(), next.run(request)).await; + let n = calls.load(Ordering::Relaxed); + if n == 0 { + return response; + } + let (allowed, _) = budget(&method, &path); + if n <= allowed { + tracing::info!(method, path, github_calls = n, "GitHub calls"); + return response; + } + tracing::error!( + method, + path, + github_calls = n, + budget = allowed, + "a request made more GitHub calls than its budget: move the work to a queued job or cap it" + ); + if matches!(laravel::config().app.env, Environment::Testing) { + return Response::new(format!( + "{method} {path} made {n} GitHub calls, over its budget of {allowed} (forge::calls): a request handler \ + must make a fixed number, whatever the organization's size. Move the work to a queued job, or name the \ + route in BUDGETS with why." + )) + .with_status(500); + } + response +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn routes_get_their_budgets() { + assert_eq!(budget("GET", "/auth/github/callback").0, SIGN_IN_BUDGET); + assert_eq!(budget("PATCH", "/api/ui/orgs/acme/projects/web").0, LINK_BUDGET); + assert_eq!(budget("PATCH", "/api/ui/orgs/acme/projects/web/").0, LINK_BUDGET); + assert_eq!(budget("GET", "/api/ui/orgs/acme/projects/web").0, DEFAULT_BUDGET); + assert_eq!(budget("PATCH", "/api/ui/orgs/acme/projects/web/builds").0, DEFAULT_BUDGET); + assert_eq!(budget("POST", "/github/setup").0, DEFAULT_BUDGET); + assert_eq!(budget("POST", "/mcp").0, LINK_BUDGET); + assert_eq!(budget("POST", "/mcp/admin").0, DEFAULT_BUDGET); + } +} diff --git a/app/src/forge/checks.rs b/app/src/forge/checks.rs index 72f0d4a3..a32f7263 100644 --- a/app/src/forge/checks.rs +++ b/app/src/forge/checks.rs @@ -137,7 +137,7 @@ impl ReportCheck { // transaction and holds no database connection or lock while it waits for GitHub. let posted = laravel::cache::lock(&format!("forge.check:{build_id}"), HOLD_SECONDS.seconds())? .block(10.seconds()) - .get(|| post(build_id)) + .get(|| super::calls::in_job("forge.check", post(build_id))) .await; match posted { // Another post of this build is still going: try again once it's done diff --git a/app/src/forge/deliveries.rs b/app/src/forge/deliveries.rs new file mode 100644 index 00000000..b98066f8 --- /dev/null +++ b/app/src/forge/deliveries.rs @@ -0,0 +1,776 @@ +//! GitHub App deliveries that can't be acted on at once (sc-9144). GitHub never redelivers a delivery on its own, so +//! nothing a claimed installation sends is lost to a limit: +//! +//! - over its rate limit, a verified delivery is kept in `deferred_webhooks` ([`defer`]) and acted on later at the +//! allowed rate, in the order it came ([`DrainDeferredWebhooks`]: queued when one is kept, and every minute while any +//! wait); while an installation has deliveries kept, its new ones join them, so none overtakes another. What's kept +//! is capped in bytes per installation, for free installations together and in total +//! (`VISUALCI_GITHUB_WEBHOOKS_DEFERRED_*`): past a cap the delivery is answered 503, which GitHub logs as failed, so +//! the redelivery check sends it again later. `/status` reports `oldest_deferred_webhook_seconds`. +//! - a delivery that never reached the app, or was answered with an error (a deploy, an outage, a cap), is found every +//! ten minutes in the App's delivery log and redelivered ([`RedeliverFailedWebhooks`]), for claimed installations +//! only, once each, with `VISUALCI_WEBHOOK_REDELIVERY_HEARTBEAT_URL` saying each run read the whole log back to the +//! last one's mark. +//! +//! An unclaimed installation's deliveries over its limit are dropped instead (`webhooks::admit`). + +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::time::{Duration, Instant}; + +use laravel::db; +use laravel::queue::{Queueable, job}; +use laravel::schedule::{self, Schedule}; +use serde_json::{Value, json}; + +use super::github_app; +use super::webhooks::{self, Claim}; +use crate::config::{GithubApp, Limits}; + +const MB: i64 = 1024 * 1024; + +fn megabytes(mb: u64) -> i64 { + i64::try_from(mb).unwrap_or(i64::MAX / MB).saturating_mul(MB) +} + +/// Whether an installation has deliveries kept for later: its new ones join them, so they're acted on in order. +/// +/// # Errors +/// On a database error. +pub async fn has_deferred(installation: &str) -> laravel::Result { + let id = installation.to_string(); + let found: Option = + db::query!("SELECT EXISTS (SELECT 1 FROM deferred_webhooks WHERE installation_id = {id})").scalar().await?; + Ok(found.unwrap_or(false)) +} + +/// Keep a claimed installation's verified delivery to act on later. Returns the status to answer (202 kept; past a cap, +/// 503 for a paid installation, which GitHub logs as failed and the redelivery check sends again, or 507 for a free one, +/// which it doesn't) and what happened, for the delivery's log on GitHub. +/// +/// The bytes kept are counted in `deferred_webhook_bytes`, in the same transaction: the installation's own row is +/// locked while it's checked and added to, so its cap holds exactly; the `free` and `total` rows are read without a +/// lock and added to in one statement each, so deliveries for different installations never wait on each other, and +/// those two caps may be overshot by the deliveries being kept at that moment (bounded by the bodies in flight: about +/// 100 MB per web process, `webhooks::IN_FLIGHT_BODY_MB`). +/// +/// # Errors +/// On a database or queue error. +pub async fn defer( + limits: &Limits, + claim: Claim, + installation: &str, + delivery: &str, + kind: &str, + body: &[u8], +) -> laravel::Result<(u16, Value)> { + let payload = String::from_utf8_lossy(body).into_owned(); + let bytes = i64::try_from(payload.len()).unwrap_or(i64::MAX); + let paid = claim == Claim::Paid; + let own_cap = megabytes(if paid { + limits.webhooks_deferred_per_installation_mb + } else { + limits.webhooks_deferred_per_free_installation_mb + }); + let free_cap = megabytes(limits.webhooks_deferred_free_total_mb); + let total_cap = megabytes(limits.webhooks_deferred_total_mb); + let (id, delivery_id, kind_s) = (installation.to_string(), delivery.to_string(), kind.to_string()); + let own = format!("installation:{installation}"); + let kept = db::transaction(async |_| { + db::query!("INSERT INTO deferred_webhook_bytes (scope) VALUES ({own}) ON CONFLICT (scope) DO NOTHING") + .insert() + .await?; + let mine: Option = + db::query!("SELECT bytes FROM deferred_webhook_bytes WHERE scope = {own} FOR UPDATE").scalar().await?; + let shared = db::query!( + "SELECT COALESCE((SELECT bytes FROM deferred_webhook_bytes WHERE scope = 'free'), 0)::BIGINT AS free, \ + COALESCE((SELECT bytes FROM deferred_webhook_bytes WHERE scope = 'total'), 0)::BIGINT AS all_kept" + ) + .select_one() + .await? + .ok_or_else(|| laravel::Error::msg("no sums"))?; + let (mine, free, all): (i64, i64, i64) = + (mine.unwrap_or(0), shared.try_get("free")?, shared.try_get("all_kept")?); + if mine + bytes > own_cap || all + bytes > total_cap || (!paid && free + bytes > free_cap) { + return Ok(Err((mine, free, all))); + } + let inserted = db::query!( + "INSERT INTO deferred_webhooks (installation_id, delivery, kind, payload, bytes, paid) \ + VALUES ({id}, {delivery_id}, {kind_s}, {payload}, {bytes}, {paid}) ON CONFLICT DO NOTHING" + ) + .insert() + .await?; + if inserted.rows_affected() > 0 { + add_bytes(&id, paid, bytes).await?; + } + Ok(Ok(())) + }) + .await?; + if let Err((mine, free, all)) = kept { + // A free installation through which a paid organization's projects are linked is redelivered like a paid one + let redeliver = paid || webhooks::paid_project_linked(installation).await?; + tracing::error!( + forge = "github", + installation, + delivery, + kind, + ?claim, + kept_for_installation = mine, + kept_for_free = free, + kept_in_total = all, + "a claimed installation's delivery was refused (503, for redelivery): over its rate limit, and the \ + deliveries kept for later are at their cap" + ); + // A paid installation's: 503, which the redelivery check sends again. A free one's: 507, which it doesn't, so + // a free installation filling its own share on purpose can't fill the redelivery queue too + return Ok(if redeliver { + ( + 503, + json!({ "refused": "over the limit, and the deliveries kept for later are at their cap: GitHub will redeliver it" }), + ) + } else { + ( + 507, + json!({ "refused": "over the limit, and this installation's deliveries kept for later are at their cap" }), + ) + }); + } + tracing::warn!(forge = "github", installation, delivery, kind, "webhook delivery kept for later"); + DrainDeferredWebhooks.dispatch().await?; + Ok((202, json!({ "deferred": "kept, and acted on shortly in the order it came" }))) +} + +/// Add (or, negative, take away) a kept delivery's bytes in the counters: its installation's, `free` for a free one, +/// and `total`. +async fn add_bytes(installation: &str, paid: bool, bytes: i64) -> laravel::Result<()> { + let own = format!("installation:{installation}"); + for scope in [Some(own), (!paid).then(|| "free".to_string()), Some("total".to_string())].into_iter().flatten() { + db::query!( + "INSERT INTO deferred_webhook_bytes (scope, bytes) VALUES ({scope}, GREATEST({bytes}, 0)) \ + ON CONFLICT (scope) DO UPDATE SET bytes = GREATEST(deferred_webhook_bytes.bytes + {bytes}, 0)" + ) + .insert() + .await?; + } + Ok(()) +} + +/// Delete a kept delivery and take its bytes out of the counters, in one transaction. +async fn forget(id: i64) -> laravel::Result<()> { + db::transaction(async |_| { + let row = db::query!("DELETE FROM deferred_webhooks WHERE id = {id} RETURNING installation_id, paid, bytes") + .select_one() + .await?; + if let Some(r) = row { + let (installation, paid, bytes): (String, bool, i64) = + (r.try_get("installation_id")?, r.try_get("paid")?, r.try_get("bytes")?); + add_bytes(&installation, paid, -bytes).await?; + } + Ok(()) + }) + .await +} + +/// How many kept deliveries one drain looks at a time, how often one is tried before it's dropped, how long one drain +/// runs at most (well under its lock's ten minutes), and how long a delivery it's acting on is held for it. +const DRAIN_BATCH: i64 = 100; +const MAX_ATTEMPTS: i32 = 5; +pub const DRAIN_RUN_SECONDS: u64 = 240; +/// The most one kept delivery is acted on for, under `webhooks::CLAIM_TAKEOVER_SECONDS`: past it, it's a failure that +/// lets its claim go. +pub const PROCESS_SECONDS: u64 = 90; +const CLAIM_SECONDS: i64 = 300; + +/// What a drain did. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct Drained { + pub processed: usize, + pub failed: usize, + /// Installations left for a later run: still over their limit, or another run is acting on one of theirs. + pub blocked: usize, +} + +/// Act on kept deliveries, oldest first, each counted against its installation's limit (by its claim now) as a new +/// delivery is. An installation still over its limit, or with a delivery another run holds, is left out (in SQL, so its +/// payloads aren't read) until the next run, so its deliveries stay in order. Each delivery is held for this run +/// (`claimed_until`) while it's acted on, so two runs never act on the same one; a run stops after +/// [`DRAIN_RUN_SECONDS`]. Each hold counts as an attempt (so one that kills the worker counts too); a delivery is +/// dropped with an error after [`MAX_ATTEMPTS`]. +/// +/// # Errors +/// On a database error. +pub async fn drain(app: &GithubApp, limits: &Limits) -> laravel::Result { + let started = Instant::now(); + let mut drained = Drained::default(); + let mut blocked: Vec = Vec::new(); + let mut claims: HashMap = HashMap::new(); + let mut after = 0i64; + 'runs: while started.elapsed() < Duration::from_secs(DRAIN_RUN_SECONDS) { + let left_out = Value::Array(blocked.iter().map(|b| Value::String(b.clone())).collect()).to_string(); + let rows = db::query!( + "SELECT id, installation_id, kind, (claimed_until IS NOT NULL AND claimed_until > now()) AS held \ + FROM deferred_webhooks WHERE id > {after} \ + AND NOT (installation_id = ANY (SELECT jsonb_array_elements_text({left_out}::jsonb))) \ + ORDER BY id LIMIT {DRAIN_BATCH}" + ) + .select() + .await?; + if rows.is_empty() { + break; + } + for r in &rows { + let (id, installation, kind): (i64, String, String) = + (r.try_get("id")?, r.try_get("installation_id")?, r.try_get("kind")?); + after = id; + if blocked.contains(&installation) { + continue; + } + if started.elapsed() >= Duration::from_secs(DRAIN_RUN_SECONDS) { + break 'runs; + } + let claim = match claims.get(&installation) { + Some(c) => *c, + None => { + let c = if installation.is_empty() { Claim::Free } else { webhooks::claim(&installation).await? }; + claims.insert(installation.clone(), c); + c + } + }; + let scope = (!installation.is_empty()).then_some(installation.as_str()); + if r.try_get::("held")? + || webhooks::admit(limits, &kind, scope, claim).await == webhooks::Admission::Over + { + blocked.push(installation); + drained.blocked += 1; + continue; + } + // Held for this run, and counted as an attempt now, so one that kills the worker is still counted; another + // run that got here first holds it, and its installation waits + let Some(held) = db::query!( + "UPDATE deferred_webhooks SET claimed_until = now() + {CLAIM_SECONDS} * interval '1 second', \ + attempts = attempts + 1 \ + WHERE id = {id} AND (claimed_until IS NULL OR claimed_until < now()) \ + RETURNING delivery, payload, attempts" + ) + .select_one() + .await? + else { + blocked.push(installation); + drained.blocked += 1; + continue; + }; + let (delivery, payload, attempts): (String, String, i32) = + (held.try_get("delivery")?, held.try_get("payload")?, held.try_get("attempts")?); + if attempts > MAX_ATTEMPTS { + forget(id).await?; + tracing::error!( + forge = "github", + kind, + delivery, + attempts, + "kept webhook delivery dropped: tried too often" + ); + drained.failed += 1; + continue; + } + // Claimed before it's acted on: one acted on already (GitHub sent it twice) is let go; one another request + // is acting on right now waits, with its installation, for the next run + let delivery_claim = if claim.claimed() { + webhooks::claim_delivery(&delivery).await? + } else { + webhooks::DeliveryClaim::Claimed(String::new()) + }; + if delivery_claim == webhooks::DeliveryClaim::InProgress { + db::query!( + "UPDATE deferred_webhooks SET claimed_until = NULL, attempts = attempts - 1 WHERE id = {id}" + ) + .update() + .await?; + blocked.push(installation); + drained.blocked += 1; + continue; + } + let owner = match &delivery_claim { + webhooks::DeliveryClaim::Claimed(owner) => Some(owner.clone()), + _ => None, + }; + let outcome = if owner.is_some() { + match serde_json::from_str::(&payload) { + // Under the claim's takeover time, so a live copy can't take it over while it's still running + Ok(event) => match tokio::time::timeout( + Duration::from_secs(PROCESS_SECONDS), + webhooks::process(app, &kind, &event, claim.claimed()), + ) + .await + { + Ok(outcome) => outcome, + Err(_) => Err(laravel::Error::msg(format!("acting on it took over {PROCESS_SECONDS} seconds"))), + }, + Err(e) => Err(laravel::abort_with(400, e.to_string())), + } + } else { + Ok(json!({ "duplicate": "acted on already" })) + }; + match outcome { + Ok(outcome) => { + if let (true, Some(owner)) = (claim.claimed(), &owner) { + webhooks::finish_delivery(&delivery, owner).await?; + } + forget(id).await?; + tracing::info!(forge = "github", kind, delivery, outcome = %outcome, "kept webhook delivery acted on"); + drained.processed += 1; + } + Err(e) => { + if let (true, Some(owner)) = (claim.claimed(), &owner) { + webhooks::release_delivery(&delivery, owner).await?; + } + if attempts >= MAX_ATTEMPTS || e.status().is_client_error() { + forget(id).await?; + tracing::error!(forge = "github", kind, delivery, error = %e, "kept webhook delivery dropped: it failed"); + } else { + db::query!("UPDATE deferred_webhooks SET claimed_until = NULL WHERE id = {id}") + .update() + .await?; + tracing::warn!(forge = "github", kind, delivery, error = %e, "kept webhook delivery failed: trying again later"); + // Its installation's later deliveries wait for it, in order + blocked.push(installation); + } + drained.failed += 1; + } + } + } + } + Ok(drained) +} + +/// Act on the deliveries kept over the limit ([`drain`]). Queued when one is kept (debounced: a burst makes one run), +/// and every minute; one run at a time (a lock longer than [`DRAIN_RUN_SECONDS`]). +#[derive(Queueable, Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct DrainDeferredWebhooks; + +#[job(debounce_for = 5.seconds(), max_wait = 30.seconds())] +impl DrainDeferredWebhooks { + async fn handle( + self, + app: laravel::config::Section, + limits: laravel::config::Section, + ) -> laravel::Result<()> { + use laravel::time::ToSpan; + let ran = laravel::cache::lock("webhooks:drain", 10.minutes())? + .get(|| super::calls::in_job("DrainDeferredWebhooks", drain(&app, &limits))) + .await?; + if let Some(d) = ran + && d != Drained::default() + { + tracing::info!(processed = d.processed, failed = d.failed, blocked = d.blocked, "kept webhook deliveries"); + } + Ok(()) + } +} + +/// How far back the redelivery check reads on its first run, how many pages of the delivery log (100 each) one run reads +/// at most, how many deliveries it asks for in one run and for one installation, how often one is asked for before it's +/// given up, and how long GitHub keeps a delivery to redeliver. +pub const REDELIVERY_WINDOW_HOURS: i64 = 24; +pub const REDELIVERY_PAGES: usize = 100; +pub const REDELIVERIES_PER_RUN: usize = 50; +pub const REDELIVERIES_PER_INSTALLATION: usize = 10; +pub const REDELIVERY_TRIES: i32 = 5; +pub const PENDING_PER_FREE_INSTALLATION: i64 = 100; +const REDELIVERY_KEPT_HOURS: i64 = 72; + +/// What a redelivery run did. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct Redelivered { + /// Entries of the delivery log read. + pub read: usize, + pub redelivered: usize, + /// Asks GitHub refused (tried again later, with a backoff). + pub refused: usize, + /// Deliveries given up this run (asked for too often, or older than GitHub keeps). + pub given_up: usize, + /// Failed deliveries of unclaimed installations, left alone. + pub skipped: usize, + /// Failed deliveries still waiting to be asked for after this run (past its share, or backing off). + pub waiting: usize, + /// The log wasn't read back to the last run's mark within the page cap: the next run goes on from where this one + /// stopped. + pub partial: bool, +} + +/// A redelivery run's heartbeat: a failure when it stopped at its page cap before reading the log back to the last +/// run's mark (the next run goes on from there, but the log is filling faster than it's read). +/// +/// # Errors +/// That. +pub fn health(r: &Redelivered) -> Result<(), String> { + if r.partial { + return Err(format!( + "the delivery log wasn't read back to the last run's mark within {REDELIVERY_PAGES} pages: the next run goes \ + on from where this one stopped" + )); + } + Ok(()) +} + +/// Record a page of the delivery log: each failed attempt makes its delivery pending (or, after it was redelivered, a +/// newer failed attempt makes it pending again, with a backoff), and an attempt that got a 2xx marks it succeeded. +/// +/// Only claimed installations' deliveries are recorded (paid ones, and those a paid organization's projects are linked +/// through, marked `paid`: asked for first, and not held to a free installation's queue cap), and not a free +/// installation's 507 (its own store at its cap, `defer`). +/// +/// The log is read newest first, so `succeeded` carries the GUIDs that got a 2xx on this scan's earlier pages: an older +/// failed attempt of one of them isn't recorded. (One whose success was read on an earlier run may be recorded and +/// redelivered; the webhook acts on a claimed installation's delivery once, by its GUID.) +async fn record_page( + items: &[Value], + succeeded: &mut HashSet, + claims: &mut HashMap, +) -> laravel::Result<()> { + let mut failed = Vec::new(); + let mut ok = Vec::new(); + for item in items { + if let (Some(guid), true) = + (item["guid"].as_str(), item["status_code"].as_i64().is_some_and(|c| (200..300).contains(&c))) + { + succeeded.insert(guid.to_string()); + } + } + for item in items { + let (Some(guid), Some(id)) = (item["guid"].as_str(), item["id"].as_i64()) else { continue }; + let installation = item["installation_id"].as_i64().map(|i| i.to_string()); + if succeeded.contains(guid) { + ok.push(json!({ "guid": guid, "id": id, "installation": installation, "paid": false })); + continue; + } + // A free installation's own store at its cap (507): not sent again + let Some(installation) = installation else { continue }; + if item["status_code"].as_i64() == Some(507) { + continue; + } + let (claim, first) = match claims.get(&installation) { + Some(c) => *c, + None => { + let c = webhooks::claim(&installation).await?; + // Asked for first, and not held to a free installation's queue cap: a paid installation's, or one a + // paid organization's projects are linked through + let first = c == Claim::Paid || webhooks::paid_project_linked(&installation).await?; + claims.insert(installation.clone(), (c, first)); + (c, first) + } + }; + if claim.claimed() { + failed.push(json!({ "guid": guid, "id": id, "installation": installation, "paid": first })); + } + } + let (failed, ok) = (Value::Array(failed).to_string(), Value::Array(ok).to_string()); + db::query!( + "INSERT INTO webhook_redeliveries (guid, installation_id, paid, first_attempt_id, last_attempt_id) \ + SELECT DISTINCT ON (guid) guid, installation, paid, id, id \ + FROM jsonb_to_recordset({failed}::jsonb) AS x(guid text, id bigint, installation text, paid boolean) \ + ORDER BY guid, id DESC \ + ON CONFLICT (guid) DO UPDATE SET \ + first_attempt_id = LEAST(webhook_redeliveries.first_attempt_id, EXCLUDED.first_attempt_id), \ + last_attempt_id = GREATEST(webhook_redeliveries.last_attempt_id, EXCLUDED.last_attempt_id), \ + state = CASE WHEN webhook_redeliveries.state = 'redelivered' \ + AND EXCLUDED.last_attempt_id > COALESCE(webhook_redeliveries.requested_attempt_id, 0) \ + THEN 'pending' ELSE webhook_redeliveries.state END, \ + next_at = CASE WHEN webhook_redeliveries.state = 'redelivered' \ + AND EXCLUDED.last_attempt_id > COALESCE(webhook_redeliveries.requested_attempt_id, 0) \ + THEN now() + interval '10 minutes' * power(2, LEAST(webhook_redeliveries.tries, 8)) \ + ELSE webhook_redeliveries.next_at END, \ + updated_at = now()" + ) + .insert() + .await?; + db::query!( + "UPDATE webhook_redeliveries r SET state = 'succeeded', updated_at = now() \ + FROM jsonb_to_recordset({ok}::jsonb) AS x(guid text, id bigint, installation text, paid boolean) \ + WHERE r.guid = x.guid AND r.state IN ('pending', 'redelivered')" + ) + .update() + .await?; + // At most PENDING_PER_FREE_INSTALLATION waiting for one free installation: the rest are given up at once, so free + // installations (which anyone can make) can't keep a queue ahead of anyone + let given_up = db::query!( + "UPDATE webhook_redeliveries SET state = 'given_up', \ + error = 'more failed deliveries waiting than a free installation may have', updated_at = now() \ + WHERE guid IN (SELECT guid FROM (SELECT guid, row_number() OVER (PARTITION BY installation_id \ + ORDER BY first_attempt_id DESC) AS n FROM webhook_redeliveries WHERE state = 'pending' AND NOT paid) x \ + WHERE n > {PENDING_PER_FREE_INSTALLATION})" + ) + .update() + .await?; + if given_up > 0 { + tracing::error!( + forge = "github", + given_up, + "failed webhook deliveries of free installations given up: more waiting than one may have" + ); + } + Ok(()) +} + +/// Read the App's delivery log, newest first, back to the last run's mark (on a first run, [`REDELIVERY_WINDOW_HOURS`] +/// back), at most `max_pages` pages, recording every failed delivery ([`record_page`]). A run that stops at the cap +/// keeps where to go on and goes on from there next time; the mark moves only once a scan has read everything back to +/// the old one. Returns entries read and whether it stopped at the cap. +async fn read_log(app: &GithubApp, max_pages: usize) -> laravel::Result<(usize, bool)> { + let state = db::query!( + "SELECT delivery_id, resume_cursor, resume_newest FROM webhook_redelivery_marks WHERE name = 'github'" + ) + .select_one() + .await?; + let (mark, mut cursor, mut newest): (Option, Option, Option) = match &state { + Some(r) => (r.try_get("delivery_id")?, r.try_get("resume_cursor")?, r.try_get("resume_newest")?), + None => (None, None, None), + }; + let since = laravel::now().timestamp().as_second() - REDELIVERY_WINDOW_HOURS * 3600; + let mut read = 0; + let mut pages = 0; + let mut reached = false; + let mut succeeded = HashSet::new(); + let mut claims = HashMap::new(); + while pages < max_pages { + let (items, next) = match github_app::hook_deliveries(app, cursor.as_deref()).await { + Ok(page) => page, + // A saved cursor GitHub no longer takes (expired): start again from the newest, back to the mark + Err(e) if cursor.is_some() && e.to_string().contains("HTTP 4") => { + tracing::warn!(error = %e, "GitHub refused the delivery log's saved cursor: reading again from the newest"); + (cursor, newest) = (None, None); + pages += 1; + continue; + } + Err(e) => return Err(e), + }; + pages += 1; + let mut page = Vec::new(); + for item in items { + let Some(id) = item["id"].as_i64() else { continue }; + let delivered = item["delivered_at"] + .as_str() + .and_then(|t| t.parse::().ok()) + .map_or(0, |t| t.as_second()); + if mark.is_some_and(|m| id <= m) || (mark.is_none() && delivered < since) { + reached = true; + break; + } + newest = Some(newest.map_or(id, |n| n.max(id))); + page.push(item); + } + read += page.len(); + record_page(&page, &mut succeeded, &mut claims).await?; + if reached { + break; + } + match next { + Some(c) => cursor = Some(c), + None => { + reached = true; + break; + } + } + } + if reached { + let mark = newest.or(mark); + db::query!( + "INSERT INTO webhook_redelivery_marks (name, delivery_id) VALUES ('github', {mark}) \ + ON CONFLICT (name) DO UPDATE SET delivery_id = EXCLUDED.delivery_id, resume_cursor = NULL, \ + resume_newest = NULL, updated_at = now()" + ) + .insert() + .await?; + } else { + db::query!( + "INSERT INTO webhook_redelivery_marks (name, delivery_id, resume_cursor, resume_newest) \ + VALUES ('github', {mark}, {cursor}, {newest}) \ + ON CONFLICT (name) DO UPDATE SET resume_cursor = EXCLUDED.resume_cursor, \ + resume_newest = EXCLUDED.resume_newest, updated_at = now()" + ) + .insert() + .await?; + } + Ok((read, !reached)) +} + +/// The redelivery check: read the delivery log ([`read_log`]), then ask GitHub to redeliver pending failed deliveries +/// of claimed installations: paid installations first, then oldest first, at most [`REDELIVERIES_PER_INSTALLATION`] +/// for one installation and [`REDELIVERIES_PER_RUN`] in all; the rest wait for later runs. A delivery whose +/// redelivery fails again is asked for again with a backoff (10 minutes, doubling), and given up with an error after +/// [`REDELIVERY_TRIES`] asks, or once GitHub no longer keeps it. An ask GitHub refuses is recorded with its error, and +/// the run goes on. +/// +/// # Errors +/// When GitHub's log can't be read, or on a database error. +pub async fn redeliver_failed(app: &GithubApp, max_pages: usize) -> laravel::Result { + let mut done = Redelivered::default(); + let (read, partial) = read_log(app, max_pages).await?; + (done.read, done.partial) = (read, partial); + + let too_old = db::query!( + "UPDATE webhook_redeliveries SET state = 'given_up', error = COALESCE(error, 'older than GitHub keeps'), \ + updated_at = now() \ + WHERE state IN ('pending', 'redelivered') AND created_at < now() - {REDELIVERY_KEPT_HOURS} * interval '1 hour' \ + RETURNING guid" + ) + .select() + .await?; + for r in &too_old { + tracing::error!( + forge = "github", + guid = r.try_get::("guid")?, + "a failed webhook delivery was given up: older than GitHub keeps" + ); + } + done.given_up += too_old.len(); + + let rows = db::query!( + "SELECT guid, installation_id, last_attempt_id, tries FROM webhook_redeliveries \ + WHERE state = 'pending' AND next_at <= now() ORDER BY paid DESC, first_attempt_id LIMIT 2000" + ) + .select() + .await?; + let mut claims: HashMap = HashMap::new(); + // Paid installations first (best claim first), each one's oldest first + type ByInstallation = BTreeMap<(std::cmp::Reverse, String), Vec<(String, i64, i32)>>; + let mut by_installation: ByInstallation = BTreeMap::new(); + for r in &rows { + let (guid, installation, attempt, tries): (String, Option, i64, i32) = + (r.try_get("guid")?, r.try_get("installation_id")?, r.try_get("last_attempt_id")?, r.try_get("tries")?); + let installation = installation.unwrap_or_default(); + let claim = match claims.get(&installation) { + Some(c) => *c, + None => { + let c = if installation.is_empty() { Claim::Unclaimed } else { webhooks::claim(&installation).await? }; + claims.insert(installation.clone(), c); + c + } + }; + if !claim.claimed() { + db::query!("UPDATE webhook_redeliveries SET state = 'skipped', updated_at = now() WHERE guid = {guid}") + .update() + .await?; + done.skipped += 1; + continue; + } + by_installation.entry((std::cmp::Reverse(claim), installation)).or_default().push((guid, attempt, tries)); + } + let mut chosen = Vec::new(); + for list in by_installation.values_mut() { + let room = REDELIVERIES_PER_RUN.saturating_sub(chosen.len()); + let take = list.len().min(REDELIVERIES_PER_INSTALLATION).min(room); + done.waiting += list.len() - take; + chosen.extend(list.drain(..take)); + } + for (guid, attempt, tries) in chosen { + let tries = tries + 1; + match github_app::redeliver(app, attempt).await { + Ok(()) => { + db::query!( + "UPDATE webhook_redeliveries SET state = 'redelivered', tries = {tries}, \ + requested_attempt_id = {attempt}, error = NULL, updated_at = now() WHERE guid = {guid}" + ) + .update() + .await?; + done.redelivered += 1; + tracing::info!( + forge = "github", + guid, + delivery_id = attempt, + tries, + "failed webhook delivery redelivered" + ); + } + Err(e) => { + let error = e.to_string(); + let state = if tries >= REDELIVERY_TRIES { "given_up" } else { "pending" }; + db::query!( + "UPDATE webhook_redeliveries SET state = {state}, tries = {tries}, error = {error}, \ + next_at = now() + interval '10 minutes' * power(2, LEAST({tries}, 8)), updated_at = now() \ + WHERE guid = {guid}" + ) + .update() + .await?; + done.refused += 1; + if state == "given_up" { + done.given_up += 1; + tracing::error!( + forge = "github", + guid, + delivery_id = attempt, + error, + "a failed webhook delivery was given up" + ); + } else { + tracing::warn!( + forge = "github", + guid, + delivery_id = attempt, + error, + "redelivering a failed webhook delivery was refused" + ); + } + } + } + } + // Redelivered and failed again, asked for too often + let exhausted = db::query!( + "UPDATE webhook_redeliveries SET state = 'given_up', \ + error = COALESCE(error, 'redelivered and failed again too often'), updated_at = now() \ + WHERE state = 'pending' AND tries >= {REDELIVERY_TRIES} RETURNING guid" + ) + .select() + .await?; + for r in &exhausted { + tracing::error!( + forge = "github", + guid = r.try_get::("guid")?, + "a failed webhook delivery was given up: redelivered and failed again too often" + ); + } + done.given_up += exhausted.len(); + db::query!("DELETE FROM webhook_redeliveries WHERE updated_at < now() - interval '7 days'").delete().await?; + db::query!("DELETE FROM webhook_deliveries_seen WHERE seen_at < now() - interval '3 days'").delete().await?; + Ok(done) +} + +/// Every ten minutes: [`redeliver_failed`], with its heartbeat ([`health`]). +#[derive(Queueable, Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct RedeliverFailedWebhooks; + +#[job] +impl RedeliverFailedWebhooks { + async fn handle(self, app: laravel::config::Section) -> laravel::Result<()> { + use crate::heartbeat::{Heartbeat, push}; + if !github_app::configured(&app) { + let health = Err("the GitHub App isn't configured, so failed deliveries aren't redelivered".into()); + push(Heartbeat::WebhookRedelivery, health).await; + return Ok(()); + } + let result = super::calls::in_job("RedeliverFailedWebhooks", redeliver_failed(&app, REDELIVERY_PAGES)).await; + let health = match &result { + Ok(r) => { + tracing::info!( + read = r.read, + redelivered = r.redelivered, + refused = r.refused, + given_up = r.given_up, + skipped = r.skipped, + waiting = r.waiting, + partial = r.partial, + "webhook redelivery check" + ); + health(r) + } + Err(e) => Err(e.to_string()), + }; + push(Heartbeat::WebhookRedelivery, health).await; + result.map(|_| ()) + } +} + +#[schedule::tasks] +fn schedule(schedule: &mut Schedule) { + schedule.job(DrainDeferredWebhooks).every_minute().without_overlapping(); + schedule.job(RedeliverFailedWebhooks).every_ten_minutes().without_overlapping(); +} diff --git a/app/src/forge/github.rs b/app/src/forge/github.rs index 7deea7c8..c2333b40 100644 --- a/app/src/forge/github.rs +++ b/app/src/forge/github.rs @@ -6,7 +6,7 @@ use laravel::http::client; use serde::Deserialize; use serde_json::Value; -use super::{ForgeKind, Identity, Installation, Permission, Repository, SignIn}; +use super::{ForgeKind, Identity, Installation, Listing, Permission, Repository, SignIn}; fn api() -> String { super::github_api() @@ -21,7 +21,7 @@ pub async fn sign_in(profile: &laravel::auth::social::User) -> laravel::Result laravel::Result laravel::Result> { Ok(emails.into_iter().map(|e| e.email.to_lowercase()).collect()) } +/// The most installations a sign-in lists: one page. Someone who can reach more (a member of over a hundred +/// organizations with the App) sees the first hundred GitHub lists. +pub const SIGN_IN_INSTALLATIONS: u32 = 100; + +/// The most pages of repositories (100 each) a sign-in reads across all the installations, so it takes a fixed number +/// of GitHub calls however many repositories the person can reach (sc-9124, `calls::SIGN_IN_BUDGET`). +pub const SIGN_IN_REPOSITORY_PAGES: u32 = 20; + +/// The most pages of repositories a sign-in reads for one installation: 1,000 repositories, so one installation with +/// many (anyone's, the App being public) can't use up the pages the others need. +pub const SIGN_IN_PAGES_PER_INSTALLATION: u32 = 10; + /// The App's installations the person can reach, every repository the App can see through them that the person has a -/// permission on, and the same repositories by installation (with whether each is private or archived). +/// permission on, and the same repositories by installation (with whether each is private or archived), up to the caps +/// above. What's past a cap isn't listed, and the log says so. +#[allow(clippy::type_complexity)] async fn installations( token: &str, -) -> laravel::Result<(Vec, Vec<(Repository, Permission)>, Vec)> { +) -> laravel::Result<(Vec, Vec<(Repository, Permission)>, Vec, Vec)> { + let mut listings = Vec::new(); let mut found = Vec::new(); let mut out = Vec::new(); let mut reachable = Vec::new(); - for item in all_pages(token, "/user/installations", "installations").await? { + let listed = pages(token, "/user/installations", "installations", 1).await?; + if listed.more { + tracing::warn!(shown = SIGN_IN_INSTALLATIONS, "a sign-in can reach more installations than it lists"); + } + let mut pages_left = SIGN_IN_REPOSITORY_PAGES; + let mut skipped = 0; + for item in listed.items { let Some(installation) = item["id"].as_i64() else { continue }; if let Some(account) = installation_account(installation.to_string(), &item["account"]) { found.push(account); } + if pages_left == 0 { + skipped += 1; + listings.push(Listing { installation_id: installation.to_string(), listed: 0, total: None }); + continue; + } let path = format!("/user/installations/{installation}/repositories"); - for repo in all_pages(token, &path, "repositories").await? { + let repos = pages(token, &path, "repositories", pages_left.min(SIGN_IN_PAGES_PER_INSTALLATION)).await?; + pages_left -= repos.read; + listings.push(Listing { + installation_id: installation.to_string(), + listed: i32::try_from(repos.items.len()).unwrap_or(i32::MAX), + total: repos.total.map(|t| i32::try_from(t).unwrap_or(i32::MAX)), + }); + if repos.more { + tracing::warn!( + installation, + listed = repos.items.len(), + "a sign-in listed only some of an installation's repositories" + ); + } + for repo in repos.items { let (Some(repository), Some(permission)) = (repo["full_name"].as_str().and_then(Repository::parse), permission_from_flags(&repo["permissions"])) else { @@ -90,7 +131,13 @@ async fn installations( out.push((repository, permission)); } } - Ok((found, out, reachable)) + if skipped > 0 { + tracing::warn!( + installations = skipped, + "a sign-in listed no repositories of some installations: past its page cap" + ); + } + Ok((found, out, reachable, listings)) } /// An installation from GitHub's `account` object (on `/user/installations` and the `installation` webhook). @@ -104,27 +151,42 @@ pub fn installation_account(id: String, account: &Value) -> Option }) } -/// Every item of a paged list (`key` in each page's object), 100 a page, up to 50 pages. -async fn all_pages(token: &str, path: &str, key: &str) -> laravel::Result> { - let mut items = Vec::new(); - for page in 1..=50 { +/// Items of a paged list, and whether GitHub has more past the pages read. +struct Paged { + items: Vec, + /// GitHub's `total_count` on the first page, when it says. + total: Option, + /// Pages read (GitHub calls made). + read: u32, + more: bool, +} + +/// The items of a paged list (`key` in each page's object), 100 a page, up to `max_pages` pages. +async fn pages(token: &str, path: &str, key: &str, max_pages: u32) -> laravel::Result { + let mut paged = Paged { items: Vec::new(), total: None, read: 0, more: false }; + for page in 1..=max_pages { let response = client::get(format!("{}{path}", api())) .token(token) .accept_json() .query([("per_page", 100), ("page", page)]) .await?; + paged.read += 1; if !response.successful() { return Err(laravel::Error::msg(format!("GitHub {path}: HTTP {}", response.status()))); } let body: Value = response.json()?; + if page == 1 { + paged.total = body["total_count"].as_i64(); + } let list = body[key].as_array().cloned().unwrap_or_default(); - let done = list.len() < 100; - items.extend(list); - if done { - break; + let full = list.len() >= 100; + paged.items.extend(list); + if !full { + return Ok(paged); } + paged.more = page == max_pages; } - Ok(items) + Ok(paged) } /// The highest permission GitHub's flags give (`{"admin": false, "push": true, …}`). @@ -140,3 +202,90 @@ fn permission_from_flags(flags: &Value) -> Option { .find(|(flag, _)| flags[*flag] == true) .map(|(_, p)| p) } + +/// The cache key of a person's GitHub token, for the picker's search. +fn user_token_key(user_id: i64) -> String { + format!("github:user-token:{user_id}") +} + +/// Keep a person's GitHub token from their sign-in, encrypted with `APP_KEY` in the cache store, until five minutes +/// before it expires (8 hours when GitHub didn't say): the repository picker's search uses it for installations whose +/// repositories the sign-in didn't list completely. A GitHub App's user token reaches only what both the person and +/// the App's installations can. +pub async fn remember_user_token(user_id: i64, token: &laravel::auth::social::Token) { + use laravel::time::ToSpan; + let now = laravel::now().timestamp().as_second(); + let seconds = token.expires_at.map_or(8 * 3600, |t| t.as_second() - now - 300); + if seconds < 60 { + return; + } + let stored = async { + let sealed = laravel::crypt::encrypt_string(&token.access).map_err(|e| laravel::Error::msg(e.to_string()))?; + laravel::cache::put(&user_token_key(user_id), sealed, seconds.seconds()).await + }; + if let Err(e) = stored.await { + tracing::warn!(user_id, error = %e, "couldn't keep a GitHub token for the picker's search"); + } +} + +/// Forget the person's kept GitHub token (they signed out). +pub async fn forget_user_token(user_id: i64) { + if let Err(e) = laravel::cache::forget(&user_token_key(user_id)).await { + tracing::warn!(user_id, error = %e, "couldn't forget a kept GitHub token"); + } +} + +/// The person's GitHub token from their last sign-in, while it lasts. +pub async fn user_token(user_id: i64) -> Option { + let sealed = laravel::cache::get::(&user_token_key(user_id)).await.ok().flatten()?; + laravel::crypt::decrypt_string(&sealed).ok() +} + +/// A repository GitHub's search found. +pub struct Found { + pub repository: Repository, + pub owner: String, + pub permission: Permission, + pub private: bool, + pub archived: bool, +} + +/// Search the repositories of these accounts (logins, with whether each is an organization) whose names match +/// `query`, as the person (`token`): one call. Only repositories they have a permission on come back. +/// +/// # Errors +/// When GitHub can't be reached or refuses. +pub async fn search_repositories(token: &str, query: &str, accounts: &[(String, bool)]) -> laravel::Result> { + let scope: Vec = accounts + .iter() + .map(|(login, organization)| format!("{}:{login}", if *organization { "org" } else { "user" })) + .collect(); + let words: String = query.chars().filter(|c| !matches!(c, ':' | '"')).take(100).collect(); + let q = format!("{} in:name {}", words.trim(), scope.join(" ")); + let response = client::get(format!("{}/search/repositories", api())) + .token(token) + .accept_json() + .query([("q", q), ("per_page", "50".to_string())]) + .await?; + if !response.successful() { + return Err(laravel::Error::msg(format!("GitHub repository search: HTTP {}", response.status()))); + } + let body: Value = response.json()?; + Ok(body["items"] + .as_array() + .cloned() + .unwrap_or_default() + .iter() + .filter_map(|r| { + let repository = r["full_name"].as_str().and_then(Repository::parse)?; + let repository = repository.with_id(Some(r["id"].as_i64()?.to_string())); + Some(Found { + owner: r["owner"]["login"].as_str()?.to_string(), + permission: permission_from_flags(&r["permissions"])?, + private: r["private"].as_bool().unwrap_or(false), + archived: r["archived"].as_bool().unwrap_or(false), + repository, + }) + }) + .collect()) +} diff --git a/app/src/forge/github_app.rs b/app/src/forge/github_app.rs index f795c97e..53a95efa 100644 --- a/app/src/forge/github_app.rs +++ b/app/src/forge/github_app.rs @@ -40,7 +40,8 @@ fn app_jwt(app: &GithubApp) -> laravel::Result { jsonwebtoken::encode(&jsonwebtoken::Header::new(jsonwebtoken::Algorithm::RS256), &claims, &key).map_err(err) } -/// GET a GitHub API path as JSON; `None` on 404. +/// GET a GitHub API path as JSON; `None` on 404. A 401 forgets the installation token it was sent with, if it was one +/// ([`token_refused`]). async fn get(token: &str, path: &str) -> laravel::Result> { let response = client::get(format!("{}{path}", api())) .token(token) @@ -50,17 +51,45 @@ async fn get(token: &str, path: &str) -> laravel::Result> { if response.status() == 404 { return Ok(None); } + if response.status() == 401 { + token_refused(token).await; + } 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. +/// How long before GitHub's expiry a cached installation token stops being used. +const TOKEN_MARGIN_SECONDS: i64 = 300; + +fn token_key(installation: &str) -> String { + format!("github:installation-token:{installation}") +} + +/// The cache key naming the installation a token belongs to, by the token's SHA-256 (the token itself is never a key). +fn token_owner_key(token: &str) -> String { + use sha2::Digest; + format!("github:installation-token-owner:{}", hex::encode(sha2::Sha256::digest(token.as_bytes()))) +} + +/// A token for one of the App's installations: the cached one (encrypted with `APP_KEY` in the cache store) until five +/// minutes before GitHub's expiry, else a new one, so linking repositories, rechecks and checks don't each mint one with +/// the App's own credentials, whose rate limit every customer shares. A token GitHub didn't say the expiry of isn't +/// cached. /// /// # Errors /// When the App isn't configured, or GitHub refuses its credentials. pub async fn installation_token(app: &GithubApp, installation: &str) -> laravel::Result { + let key = token_key(installation); + match laravel::cache::get::(&key).await { + Ok(Some(sealed)) => match laravel::crypt::decrypt_string(&sealed) { + Ok(token) => return Ok(token), + Err(e) => tracing::warn!(installation, error = %e, "a cached installation token didn't decrypt"), + }, + Ok(None) => {} + Err(e) => tracing::warn!(installation, error = %e, "the cache store didn't answer for an installation token"), + } let response = client::post(format!("{}/app/installations/{installation}/access_tokens", api())) .token(app_jwt(app)?) .header("accept", "application/vnd.github+json") @@ -70,7 +99,47 @@ pub async fn installation_token(app: &GithubApp, installation: &str) -> laravel: 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")) + let token = body["token"] + .as_str() + .map(str::to_string) + .ok_or_else(|| err("an installation token response without a token"))?; + let expires = body["expires_at"].as_str().and_then(|t| t.parse::().ok()); + if let Some(expires) = expires { + let seconds = expires.as_second() - laravel::now().timestamp().as_second() - TOKEN_MARGIN_SECONDS; + if seconds > 60 { + remember_token(installation, &token, seconds).await; + } + } + Ok(token) +} + +async fn remember_token(installation: &str, token: &str, seconds: i64) { + use laravel::time::ToSpan; + let sealed = match laravel::crypt::encrypt_string(token) { + Ok(s) => s, + Err(e) => { + tracing::warn!(error = %e, "couldn't encrypt an installation token to cache it"); + return; + } + }; + let stored = async { + laravel::cache::put(&token_key(installation), sealed, seconds.seconds()).await?; + laravel::cache::put(&token_owner_key(token), installation.to_string(), seconds.seconds()).await + }; + if let Err(e) = stored.await { + tracing::warn!(installation, error = %e, "couldn't cache an installation token"); + } +} + +/// GitHub answered 401 to a request with this token: if it's a cached installation token, forget it, so the next call +/// mints a new one. +pub async fn token_refused(token: &str) { + let owner = token_owner_key(token); + if let Ok(Some(installation)) = laravel::cache::get::(&owner).await { + let _ = laravel::cache::forget(&token_key(&installation)).await; + let _ = laravel::cache::forget(&owner).await; + tracing::info!(installation, "GitHub refused a cached installation token: forgotten"); + } } /// Whether the App's installation `id` exists (a delivery can be stale, or redelivered after the installation went). @@ -95,43 +164,6 @@ pub async fn installation(app: &GithubApp, id: &str) -> laravel::Result, - pub archived: bool, -} - -/// Every repository an installation was granted (with its token), up to `limit`. -/// -/// # Errors -/// When GitHub can't be reached or refuses. -pub async fn installation_repositories(token: &str, limit: usize) -> laravel::Result> { - let mut out = Vec::new(); - for page in 1..=50 { - let Some(body) = get(token, &format!("/installation/repositories?per_page=100&page={page}")).await? else { - break; - }; - let items = body["repositories"].as_array().cloned().unwrap_or_default(); - let n = items.len(); - for r in items { - let Some(full_name) = r["full_name"].as_str() else { continue }; - out.push(Granted { - full_name: full_name.to_string(), - id: r["id"].as_i64().map(|i| i.to_string()), - archived: r["archived"].as_bool().unwrap_or(false), - }); - if out.len() >= limit { - return Ok(out); - } - } - if n < 100 { - break; - } - } - Ok(out) -} - /// An account's display name on GitHub (an organization's or a person's `name`), else its login. /// /// # Errors @@ -164,6 +196,55 @@ pub async fn organization_role(token: &str, org: &str, user_id: &str) -> laravel } } +/// A page of the App's webhook deliveries, newest first (`GET /app/hook/deliveries`, as the App), and the cursor of the +/// next page from the `Link` header, if there is one. +/// +/// # Errors +/// When the App isn't configured, or GitHub refuses. +pub async fn hook_deliveries(app: &GithubApp, cursor: Option<&str>) -> laravel::Result<(Vec, Option)> { + let mut query = vec![("per_page", "100".to_string())]; + if let Some(cursor) = cursor { + query.push(("cursor", cursor.to_string())); + } + let response = client::get(format!("{}/app/hook/deliveries", api())) + .token(app_jwt(app)?) + .header("accept", "application/vnd.github+json") + .header("user-agent", "visualci") + .query(query) + .await?; + if !response.successful() { + return Err(err(format!("GET /app/hook/deliveries: HTTP {}", response.status()))); + } + let next = response.header("link").and_then(next_cursor); + Ok((response.json()?, next)) +} + +/// The `cursor` of a `Link` header's `rel="next"` URL. +#[must_use] +pub fn next_cursor(link: &str) -> Option { + link.split(',').find(|part| part.contains("rel=\"next\"")).and_then(|part| { + let url = part.split(';').next()?.trim().trim_start_matches('<').trim_end_matches('>'); + let query = url.split_once('?')?.1; + url::form_urlencoded::parse(query.as_bytes()).find(|(k, _)| k == "cursor").map(|(_, v)| v.into_owned()) + }) +} + +/// Ask GitHub to deliver a webhook delivery again (`POST /app/hook/deliveries/{id}/attempts`, as the App). +/// +/// # Errors +/// When the App isn't configured, or GitHub refuses. +pub async fn redeliver(app: &GithubApp, delivery_id: i64) -> laravel::Result<()> { + let response = client::post(format!("{}/app/hook/deliveries/{delivery_id}/attempts", api())) + .token(app_jwt(app)?) + .header("accept", "application/vnd.github+json") + .header("user-agent", "visualci") + .await?; + if !response.successful() { + return Err(err(format!("redelivering {delivery_id}: HTTP {}", response.status()))); + } + Ok(()) +} + /// Where people install the App on their repositories. #[must_use] pub fn install_url() -> String { @@ -206,6 +287,9 @@ pub async fn collaborators(token: &str, repo: &str) -> laravel::Result {} 404 => return Ok(None), + 401 => { + token_refused(&token).await; + return Err(err(format!("GET /repos/{repo}/collaborators/{login}: HTTP 401"))); + } 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 { diff --git a/app/src/forge/gitlab.rs b/app/src/forge/gitlab.rs index 9ed60992..6ec73e53 100644 --- a/app/src/forge/gitlab.rs +++ b/app/src/forge/gitlab.rs @@ -96,6 +96,7 @@ pub async fn sign_in(base: &str, profile: &social::User) -> laravel::Result String { if base == "https://gitlab.com" { String::new() } else { base } } -/// Every item of a paged API list, 100 a page, up to 50 pages. +/// The most pages (100 items each) a GitLab sign-in reads, so it makes a fixed number of calls however many projects +/// the person can reach. Past it the log says the list was cut short. +pub const SIGN_IN_PAGES: u32 = 20; + +/// The items of a paged API list, 100 a page, up to [`SIGN_IN_PAGES`] pages. async fn all_pages(base: &str, token: &str, path: &str) -> laravel::Result> { let mut items = Vec::new(); - for page in 1..=50 { + for page in 1..=SIGN_IN_PAGES { let sep = if path.contains('?') { '&' } else { '?' }; let response = client::get(format!("{base}/api/v4{path}{sep}per_page=100&page={page}")).token(token).accept_json().await?; @@ -122,9 +127,10 @@ async fn all_pages(base: &str, token: &str, path: &str) -> laravel::Result laravel::Result<()> { + for l in listings { + let (id, listed, total) = (l.installation_id.clone(), l.listed, l.total); + let complete = total.is_some_and(|t| listed >= t); + db::query!( + "UPDATE user_installations SET repositories_listed = {listed}, repositories_total = {total}, \ + repositories_complete = {complete} WHERE user_id = {user_id} AND installation_id = {id}" + ) + .update() + .await?; + } + Ok(()) +} + +/// Searches of GitHub one person's picker makes in a minute. +pub const SEARCHES_PER_MINUTE: u32 = 30; + +/// For a picker search over installations whose repositories the person's sign-in didn't list completely: search +/// GitHub for them as the person (one call, [`super::github::search_repositories`]), and record what it finds in +/// `user_repositories`, so the picker lists them like the rest. Returns how the search went: `local` (every +/// installation in scope was listed completely: no GitHub call), `github`, `rate_limited` (past +/// [`SEARCHES_PER_MINUTE`]), `sign_in_again` (their GitHub token from signing in has expired) or `unavailable`. +async fn search_github( + user_id: i64, + organization_id: i64, + installation: Option<&str>, + q: &str, +) -> laravel::Result<&'static str> { + let only = installation.map(str::to_string); + let capped = db::query!( + "SELECT g.installation_id, g.account_login, g.account_type FROM user_installations ui \ + JOIN github_installations g ON g.installation_id = ui.installation_id \ + WHERE ui.user_id = {user_id} AND g.organization_id = {organization_id} AND g.deleted_at IS NULL \ + AND g.suspended_at IS NULL AND ({only}::text IS NULL OR g.installation_id = {only}) \ + AND NOT ui.repositories_complete \ + ORDER BY g.installation_id LIMIT 5" + ) + .select() + .await?; + if capped.is_empty() || q.chars().count() < 2 { + return Ok("local"); + } + let mut accounts = Vec::new(); + let mut by_login = std::collections::HashMap::new(); + for r in &capped { + let login: String = r.try_get("account_login")?; + accounts.push((login.clone(), r.try_get::("account_type")? == "Organization")); + by_login.insert(login.to_lowercase(), r.try_get::("installation_id")?); + } + let limit = laravel::rate_limit::Limit::per_minute(SEARCHES_PER_MINUTE); + if laravel::rate_limit::attempt(&format!("picker-search:{user_id}"), limit).await?.is_err() { + return Ok("rate_limited"); + } + let Some(token) = super::github::user_token(user_id).await else { return Ok("sign_in_again") }; + let found = match super::github::search_repositories(&token, q, &accounts).await { + Ok(found) => found, + Err(e) => { + tracing::warn!(user_id, error = %e, "the picker's GitHub search failed"); + return Ok("unavailable"); + } + }; + for f in found { + let Some(installation_id) = by_login.get(&f.owner.to_lowercase()).cloned() else { continue }; + let Some(repository_id) = f.repository.id.clone() else { continue }; + let (name, permission, private, archived) = + (f.repository.path.clone(), f.permission.as_str(), f.private, f.archived); + db::query!( + "INSERT INTO user_repositories (user_id, installation_id, repository_id, full_name, permission, private, \ + archived) \ + VALUES ({user_id}, {installation_id}, {repository_id}, {name}, {permission}, {private}, {archived}) \ + ON CONFLICT (user_id, installation_id, repository_id) DO UPDATE SET full_name = EXCLUDED.full_name, \ + permission = EXCLUDED.permission, private = EXCLUDED.private, archived = EXCLUDED.archived, \ + seen_at = now()" + ) + .insert() + .await?; + } + Ok("github") +} + /// An installation GitHub says exists: recorded, or brought up to date (its account may have been renamed), and no /// longer marked removed. async fn upsert(i: &Installation) -> laravel::Result<()> { @@ -475,9 +571,11 @@ async fn create_for_account(user: &User, login: &str, name: &str) -> laravel::Re /// A page of the repository picker: the repositories `user_id` can reach through the organization's installations /// (as of their last GitHub sign-in), matching `query`, with their permission and the organization's project already -/// linked to each (only `installation`'s, when given). Read from the database, with no GitHub call, so it pages hundreds at once. `can_add` is a -/// repository they maintain or administer, not archived and not linked yet. Also the organization's installations -/// they reach, and its newest pick still being made (for its progress). +/// linked to each (only `installation`'s, when given). Read from the database, so it pages hundreds at once; a search +/// over an installation the sign-in didn't list completely first asks GitHub once ([`search_github`], answered as +/// `search`). `can_add` is a repository they maintain or administer, not archived and not linked yet. Also the +/// organization's installations they reach, each with how many of its repositories were `listed` of its `total`, and +/// its newest pick still being made (for its progress). /// /// # Errors /// On a database error. @@ -489,6 +587,11 @@ pub async fn picker( page: i64, ) -> laravel::Result { let q = query.trim().to_lowercase(); + let search = if q.is_empty() || page > 1 { + "local" + } else { + search_github(user_id, organization_id, installation, query.trim()).await? + }; let only = installation.map(str::to_string); let page = page.max(1); let (limit, offset) = (PAGE_SIZE, (page - 1) * PAGE_SIZE); @@ -533,7 +636,8 @@ pub async fn picker( }) .collect::>>()?; let installations = db::query!( - "SELECT g.installation_id, g.account_login FROM github_installations g \ + "SELECT g.installation_id, g.account_login, ui.repositories_listed, ui.repositories_total \ + FROM github_installations g \ JOIN user_installations ui ON ui.installation_id = g.installation_id AND ui.user_id = {user_id} \ WHERE g.organization_id = {organization_id} AND g.deleted_at IS NULL ORDER BY lower(g.account_login)" ) @@ -544,6 +648,8 @@ pub async fn picker( Ok(json!({ "installation_id": r.try_get::("installation_id")?, "account_login": r.try_get::("account_login")?, + "listed": r.try_get::("repositories_listed")?, + "total": r.try_get::>("repositories_total")?, })) }) .collect::>>()?; @@ -565,16 +671,18 @@ pub async fn picker( "query": query, "installations": installations, "running": running, + "search": search, })) } /// Make the chosen repositories (GitHub's IDs) into projects of the organization: checked against what the person -/// can reach through its installations and maintain, then made by a queued job ([`ImportRepositories`]), a few -/// GitHub calls each. Repositories already linked are left out. Returns the pick's ID, for its progress -/// ([`import_state`]). +/// can reach through its installations and maintain (in one query), then made by a queued job +/// ([`ImportRepositories`]) [`IMPORT_BATCH`] at a time. Repositories already linked are left out. Returns the pick's ID, +/// for its progress ([`import_state`]). /// /// # Errors -/// 422 for none, more than [`IMPORT_LIMIT`], or one they can't add; database and queue errors. +/// 422 for none, more than [`IMPORT_LIMIT`], or one they can't add; 429 past [`PICKS_PER_PERSON_PER_HOUR`] or +/// [`PICKS_PER_ORGANIZATION_PER_DAY`], saying when to try again; database and queue errors. pub async fn import(user: &User, organization_id: i64, repository_ids: &[String]) -> laravel::Result { if repository_ids.is_empty() { return Err(refused(422, "pick at least one repository")); @@ -583,21 +691,32 @@ pub async fn import(user: &User, organization_id: i64, repository_ids: &[String] return Err(refused(422, format!("pick at most {IMPORT_LIMIT} repositories at a time"))); } let user_id = user.id; + let ids = Value::Array(repository_ids.iter().map(|i| Value::String(i.clone())).collect()).to_string(); + let rows = db::query!( + "SELECT DISTINCT ON (ur.repository_id) ur.repository_id, ur.installation_id, ur.full_name, ur.permission, \ + ur.archived, EXISTS (SELECT 1 FROM projects p WHERE p.organization_id = {organization_id} \ + AND p.forge = 'github' AND (p.repository_id = ur.repository_id \ + OR lower(p.repository_url) LIKE '%/' || lower(ur.full_name))) AS linked \ + FROM user_repositories ur JOIN github_installations g ON g.installation_id = ur.installation_id \ + WHERE ur.user_id = {user_id} AND ur.repository_id IN (SELECT jsonb_array_elements_text({ids}::jsonb)) \ + AND g.organization_id = {organization_id} AND g.deleted_at IS NULL AND g.suspended_at IS NULL \ + ORDER BY ur.repository_id, ur.installation_id" + ) + .select() + .await?; + let mut found = std::collections::HashMap::new(); + for r in &rows { + found.insert(r.try_get::("repository_id")?, r); + } let mut requested = Vec::new(); + let mut seen = std::collections::HashSet::new(); for repository_id in repository_ids { - let rid = repository_id.clone(); - let row = db::query!( - "SELECT ur.installation_id, ur.full_name, ur.permission, ur.archived, \ - EXISTS (SELECT 1 FROM projects p WHERE p.organization_id = {organization_id} AND p.forge = 'github' \ - AND (p.repository_id = ur.repository_id OR lower(p.repository_url) LIKE '%/' || lower(ur.full_name))) \ - AS linked \ - FROM user_repositories ur JOIN github_installations g ON g.installation_id = ur.installation_id \ - WHERE ur.user_id = {user_id} AND ur.repository_id = {rid} AND g.organization_id = {organization_id} \ - AND g.deleted_at IS NULL AND g.suspended_at IS NULL LIMIT 1" - ) - .select_one() - .await? - .ok_or_else(|| refused(422, format!("repository {repository_id} isn't one you can add here")))?; + if !seen.insert(repository_id.clone()) { + continue; + } + let row = found + .get(repository_id) + .ok_or_else(|| refused(422, format!("repository {repository_id} isn't one you can add here")))?; let name: String = row.try_get("full_name")?; if row.try_get::("linked")? { continue; @@ -620,18 +739,111 @@ pub async fn import(user: &User, organization_id: i64, repository_ids: &[String] if requested.is_empty() { return Err(refused(422, "those repositories are already projects here")); } + let wanted = requested.len(); let requested = Value::Array(requested).to_string(); - let id: Option = db::query!( - "INSERT INTO repository_imports (organization_id, user_id, requested) \ - VALUES ({organization_id}, {user_id}, {requested}::jsonb) RETURNING id" - ) - .scalar() + // The limits checked and the pick recorded under the organization's and the person's locks, so picks made at once + // can't each fit under a limit the sum passes + let id = db::transaction(async |_| { + let (org_lock, user_lock) = + (format!("repository-imports:org:{organization_id}"), format!("repository-imports:user:{user_id}")); + db::query!("SELECT pg_advisory_xact_lock(hashtext({org_lock}))").statement().await?; + db::query!("SELECT pg_advisory_xact_lock(hashtext({user_lock}))").statement().await?; + within_pick_limits(user_id, organization_id, wanted).await?; + let id: Option = db::query!( + "INSERT INTO repository_imports (organization_id, user_id, requested) \ + VALUES ({organization_id}, {user_id}, {requested}::jsonb) RETURNING id" + ) + .scalar() + .await?; + id.ok_or_else(|| laravel::Error::msg("no import row")) + }) .await?; - let id = id.ok_or_else(|| laravel::Error::msg("no import row"))?; ImportRepositories { import_id: id }.dispatch().await?; Ok(id) } +/// Picks (repositories, and the time each pick leaves the window) within a window, oldest first. +async fn picks_in_window(user_id: Option, organization_id: Option) -> laravel::Result> { + let rows = match (user_id, organization_id) { + (Some(user_id), _) => { + db::query!( + "SELECT jsonb_array_length(requested)::BIGINT AS n, \ + to_char((created_at + interval '1 hour') AT TIME ZONE 'UTC', 'HH24:MI') || ' UTC' || \ + CASE WHEN ((created_at + interval '1 hour') AT TIME ZONE 'UTC')::date \ + <> (now() AT TIME ZONE 'UTC')::date \ + THEN to_char((created_at + interval '1 hour') AT TIME ZONE 'UTC', ' \"on\" FMDD Mon') ELSE '' END \ + AS free_at \ + FROM repository_imports WHERE user_id = {user_id} AND created_at > now() - interval '1 hour' \ + ORDER BY created_at" + ) + .select() + .await? + } + (None, Some(organization_id)) => { + db::query!( + "SELECT jsonb_array_length(requested)::BIGINT AS n, \ + to_char((created_at + interval '1 day') AT TIME ZONE 'UTC', 'HH24:MI') || ' UTC' || \ + CASE WHEN ((created_at + interval '1 day') AT TIME ZONE 'UTC')::date \ + <> (now() AT TIME ZONE 'UTC')::date \ + THEN to_char((created_at + interval '1 day') AT TIME ZONE 'UTC', ' \"on\" FMDD Mon') ELSE '' END \ + AS free_at \ + FROM repository_imports WHERE organization_id = {organization_id} \ + AND created_at > now() - interval '1 day' ORDER BY created_at" + ) + .select() + .await? + } + (None, None) => Vec::new(), + }; + rows.iter().map(|r| Ok((r.try_get::("n")?, r.try_get::("free_at")?))).collect() +} + +/// When a pick of `wanted` fits under `limit`, given the picks in the window: `None` now, else the time enough of them +/// have left it (`14:20 UTC`, with the day when it isn't today: `09:05 UTC on 5 Dec`). +#[must_use] +pub fn fits_at(picks: &[(i64, String)], wanted: i64, limit: i64) -> Option { + let used: i64 = picks.iter().map(|(n, _)| n).sum(); + let mut over = used + wanted - limit; + if over <= 0 { + return None; + } + for (n, free_at) in picks { + over -= n; + if over <= 0 { + return Some(free_at.clone()); + } + } + picks.last().map(|(_, at)| at.clone()) +} + +/// Refuse a pick of `wanted` repositories past either limit, saying when to try again. +async fn within_pick_limits(user_id: i64, organization_id: i64, wanted: usize) -> laravel::Result<()> { + let wanted = i64::try_from(wanted).unwrap_or(i64::MAX); + let mine = picks_in_window(Some(user_id), None).await?; + if let Some(at) = fits_at(&mine, wanted, PICKS_PER_PERSON_PER_HOUR) { + let used: i64 = mine.iter().map(|(n, _)| n).sum(); + return Err(refused( + 429, + format!( + "You've added {used} repositories in the last hour, and the most is {PICKS_PER_PERSON_PER_HOUR} an hour: \ + try again at {at}." + ), + )); + } + let theirs = picks_in_window(None, Some(organization_id)).await?; + if let Some(at) = fits_at(&theirs, wanted, PICKS_PER_ORGANIZATION_PER_DAY) { + let used: i64 = theirs.iter().map(|(n, _)| n).sum(); + return Err(refused( + 429, + format!( + "This organization has added {used} repositories in the last day, and the most is \ + {PICKS_PER_ORGANIZATION_PER_DAY} a day: try again at {at}." + ), + )); + } + Ok(()) +} + /// A pick's progress: how many repositories it asked for, the projects made and the repositories not made (with /// why) so far, and whether it's finished (or stopped on an error). `Value::Null` for another organization's. /// @@ -666,50 +878,82 @@ pub struct ImportRepositories { #[job] impl ImportRepositories { async fn handle(self) -> laravel::Result<()> { - let id = self.import_id; - let Some(row) = db::query!( - "SELECT organization_id, user_id, requested::text AS requested, finished_at IS NOT NULL AS finished \ - FROM repository_imports WHERE id = {id}" - ) - .select_one() - .await? - else { - return Ok(()); - }; - if row.try_get::("finished")? { - return Ok(()); + use laravel::time::ToSpan; + let more = super::calls::in_job("ImportRepositories", import_batch(self.import_id)).await?; + if more { + ImportRepositories { import_id: self.import_id }.dispatch().delay(IMPORT_PAUSE_SECONDS.seconds()).await?; } - let organization_id: i64 = row.try_get("organization_id")?; - let requested: Vec = serde_json::from_str(&row.try_get::("requested")?) - .map_err(|e| laravel::Error::msg(e.to_string()))?; - let user = match row.try_get::>("user_id")? { - Some(u) => User::find(u).await?, - None => None, - }; - let Some(user) = user else { - return finish(id, Some("the person who picked these repositories is gone")).await; + Ok(()) + } +} + +/// Make the next [`IMPORT_BATCH`] of a pick's repositories into projects, saving progress after each. Returns whether +/// any are left for the next run. +/// +/// # Errors +/// On a database error. +pub async fn import_batch(id: i64) -> laravel::Result { + let Some(row) = db::query!( + "SELECT organization_id, user_id, requested::text AS requested, linked::text AS linked, \ + skipped::text AS skipped, finished_at IS NOT NULL AS finished \ + FROM repository_imports WHERE id = {id}" + ) + .select_one() + .await? + else { + return Ok(false); + }; + if row.try_get::("finished")? { + return Ok(false); + } + fn parse(t: &str) -> laravel::Result { + serde_json::from_str(t).map_err(|e| laravel::Error::msg(e.to_string())) + } + let organization_id: i64 = row.try_get("organization_id")?; + let requested: Vec = parse(&row.try_get::("requested")?)?; + let mut linked: Vec = parse(&row.try_get::("linked")?)?; + let mut skipped: Vec = parse(&row.try_get::("skipped")?)?; + let user = match row.try_get::>("user_id")? { + Some(u) => User::find(u).await?, + None => None, + }; + let Some(user) = user else { + finish(id, Some("the person who picked these repositories is gone")).await?; + return Ok(false); + }; + // Each batch only while they're still an admin of the organization + if role_in(organization_id, user.id).await? != Some(Role::Admin) { + finish(id, Some("the person who picked these repositories isn't an admin of this organization any more")) + .await?; + return Ok(false); + } + let start = linked.len() + skipped.len(); + for r in requested.iter().skip(start).take(IMPORT_BATCH) { + let name = r["full_name"].as_str().unwrap_or_default().to_string(); + let Some(repository) = + Repository::parse(&name).map(|repo| repo.with_id(r["repository_id"].as_str().map(str::to_string))) + else { + skipped.push(Skipped { repository: name, reason: "not a repository name".into() }); + save_progress(id, &linked, &skipped).await?; + continue; }; - let (mut linked, mut skipped) = (Vec::::new(), Vec::::new()); - for r in &requested { - let Some(name) = r["full_name"].as_str() else { continue }; - let Some(repository) = - Repository::parse(name).map(|repo| repo.with_id(r["repository_id"].as_str().map(str::to_string))) - else { - continue; - }; - match add_one(organization_id, &user, &repository).await { - Ok(Ok(l)) => linked.push(l), - Ok(Err(s)) => skipped.push(s), - Err(e) => { - save_progress(id, &linked, &skipped).await?; - tracing::warn!(import = id, error = %e, "repository import stopped"); - return finish(id, Some(&format!("{name}: {e}"))).await; - } + match add_one(organization_id, &user, &repository).await { + Ok(Ok(l)) => linked.push(l), + Ok(Err(s)) => skipped.push(s), + Err(e) => { + save_progress(id, &linked, &skipped).await?; + tracing::warn!(import = id, error = %e, "repository import stopped"); + finish(id, Some(&format!("{name}: {e}"))).await?; + return Ok(false); } - save_progress(id, &linked, &skipped).await?; } - finish(id, None).await + save_progress(id, &linked, &skipped).await?; + } + if linked.len() + skipped.len() < requested.len() { + return Ok(true); } + finish(id, None).await?; + Ok(false) } async fn save_progress(id: i64, linked: &[Linked], skipped: &[Skipped]) -> laravel::Result<()> { diff --git a/app/src/forge/mod.rs b/app/src/forge/mod.rs index 03034716..d2721c61 100644 --- a/app/src/forge/mod.rs +++ b/app/src/forge/mod.rs @@ -2,7 +2,9 @@ //! 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 calls; pub mod checks; +pub mod deliveries; pub mod events; pub mod github; pub mod github_app; @@ -307,6 +309,17 @@ pub struct SignIn { pub installations: Vec, /// Each repository they can reach through each of those installations, for the repository picker. pub reachable: Vec, + /// How many of each installation's repositories the sign-in listed, of how many GitHub has. + pub listings: Vec, +} + +/// How many of an installation's repositories a sign-in listed (`reachable`), of how many GitHub has: `total` is +/// `None` when it read none (past its page cap). Past the cap, the picker's search goes to GitHub. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Listing { + pub installation_id: String, + pub listed: i32, + pub total: Option, } /// A repository someone can reach through an installation of the GitHub App, and their permission on it. diff --git a/app/src/forge/pr_comment.rs b/app/src/forge/pr_comment.rs index 426c3668..d1429937 100644 --- a/app/src/forge/pr_comment.rs +++ b/app/src/forge/pr_comment.rs @@ -309,7 +309,7 @@ impl PostPrComment { let posted = laravel::cache::lock(&format!("forge.pr_comment:{project_id}:{pr_number}"), HOLD_SECONDS.seconds())? .block(10.seconds()) - .get(|| post(project_id, pr_number, build_id)) + .get(|| super::calls::in_job("forge.pr_comment", post(project_id, pr_number, build_id))) .await; match posted { // Another post to this pull request is still going: try again once it's done diff --git a/app/src/forge/report.rs b/app/src/forge/report.rs index 5a6bde54..78bfcca1 100644 --- a/app/src/forge/report.rs +++ b/app/src/forge/report.rs @@ -175,9 +175,12 @@ pub async fn report_check( None => client::post(format!("{}/repos/{path}/check-runs", github())), }; let request = - request.token(token).header("accept", "application/vnd.github+json").header("user-agent", "visualci"); + request.token(&token).header("accept", "application/vnd.github+json").header("user-agent", "visualci"); let request = request.json(github_check_run(check)); let reply = outbound::exchange(request, &github()).await?; + if reply.status == 401 { + github_app::token_refused(&token).await; + } if !reply.successful() { return Err(refused("GitHub check run", &reply)); } @@ -250,7 +253,11 @@ pub async fn upsert_comment( } else { request }; - outbound::exchange(request, &base).await + let reply = outbound::exchange(request, &base).await?; + if github && reply.status == 401 { + github_app::token_refused(&token).await; + } + Ok::<_, laravel::Error>(reply) }; // No comment remembered (the first post, or one whose row wasn't saved after the forge took it): look for // VisualCI's own on the pull request before posting, so a retry edits it instead of posting a second diff --git a/app/src/forge/sync.rs b/app/src/forge/sync.rs index 11e0e93a..cefd32ab 100644 --- a/app/src/forge/sync.rs +++ b/app/src/forge/sync.rs @@ -41,6 +41,8 @@ pub struct Synced { /// # Errors /// When GitHub can't answer for some repository (other than a low rate limit), or on a database error. pub async fn sync_github(app: &GithubApp) -> laravel::Result { + // Everyone is rechecked below: whoever a webhook queued before now needn't wait for their own run + let started: Option = db::query!("SELECT now()::text").scalar().await?; let unseen = match backfill_ids(app).await { Ok(unseen) => unseen, Err(e) if github_app::rate_limited(&e) => return Ok(Synced { deferred: true, ..Synced::default() }), @@ -58,6 +60,7 @@ pub async fn sync_github(app: &GithubApp) -> laravel::Result { .map(|r| r.try_get("user_id")) .collect::>()?; let changed = webhooks::apply_reach(&reach, &people).await?; + db::query!("DELETE FROM access_rechecks WHERE queued_at <= {started}::timestamptz").delete().await?; let unlinked = recheck_links(&reach, &unseen).await?; // Each linked repository's visibility and licence, once a day per project, in an hour of its own let open_source = match super::open_source::recheck_due(app).await { @@ -211,7 +214,7 @@ impl SyncForges { crate::heartbeat::push(crate::heartbeat::Heartbeat::ForgeSync, health).await; return Ok(()); } - let result = sync_github(&app).await; + let result = super::calls::in_job("SyncForges", sync_github(&app)).await; let health = match &result { Err(e) => Err(e.to_string()), Ok(s) => { diff --git a/app/src/forge/webhooks.rs b/app/src/forge/webhooks.rs index e0b0771b..48558ef8 100644 --- a/app/src/forge/webhooks.rs +++ b/app/src/forge/webhooks.rs @@ -16,13 +16,14 @@ use hmac::{Hmac, Mac}; use laravel::db; use laravel::prelude::*; use laravel::queue::{Queueable, job}; +use laravel::schedule::{self, Schedule}; use serde_json::{Value, json}; use sha2::Sha256; use super::events::{BranchClosed, BranchReopened, PullRequestMerged, RepositoryVisibilityChanged}; use super::github_app; use super::{ForgeKind, Permission, Repository}; -use crate::config::GithubApp; +use crate::config::{GithubApp, Limits}; /// One delivery, as VisualCI acts on it. #[derive(Debug, Clone, PartialEq, Eq)] @@ -260,39 +261,608 @@ async fn linked(repository: &Repository) -> laravel::Result> { .collect() } -/// `POST /webhooks/github`. +/// The GitHub projects linked to any of these repositories, as [`linked`] finds them, in two queries however many +/// there are (an installation's delivery lists every repository it was granted). +async fn linked_any(repositories: &[Repository]) -> laravel::Result> { + if repositories.is_empty() { + return Ok(Vec::new()); + } + let list = Value::Array(repositories.iter().map(|r| json!({ "id": r.id, "url": r.url.to_lowercase() })).collect()) + .to_string(); + db::query!( + "WITH r AS (SELECT * FROM jsonb_to_recordset({list}::jsonb) AS x(id text, url text) WHERE id IS NOT NULL) \ + UPDATE projects p SET repository_id = r.id, updated_at = now() FROM r \ + WHERE p.forge = 'github' AND p.repository_id IS NULL AND lower(p.repository_url) = r.url" + ) + .update() + .await?; + let rows = db::query!( + "WITH r AS (SELECT * FROM jsonb_to_recordset({list}::jsonb) AS x(id text, url text)) \ + SELECT DISTINCT p.id, p.organization_id, p.forge_installation FROM projects p JOIN r ON p.forge = 'github' \ + AND ((r.id IS NOT NULL AND p.repository_id = r.id) \ + OR ((r.id IS NULL OR p.repository_id IS NULL) AND lower(p.repository_url) = r.url)) \ + ORDER BY p.id" + ) + .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() +} + +/// GitHub sends deliveries of up to 25 MB. +pub const MAX_BODY: usize = 25 * 1024 * 1024; + +/// The most delivery bytes one process holds before checking their signatures, in megabytes: a request takes a +/// megabyte of it for each megabyte of body as it arrives, not for what it declares, so a request that sends slowly +/// holds only what it has sent. Requests from outside GitHub's hook addresses ([`from_github`]) share a small budget of +/// their own, so they can't use up GitHub's. A request that waits more than [`BODY_WAIT_SECONDS`] for room gets a 503. +pub const IN_FLIGHT_BODY_MB: u32 = 100; +pub const OUTSIDE_GITHUB_BODY_MB: u32 = 8; +const BODY_WAIT_SECONDS: u64 = 5; + +/// Bodies must arrive at least this fast (bytes a second) once started, after a few seconds' grace: a request that +/// dribbles its body is cut off with a 408 instead of holding its share for the 30-second request limit. +pub const MIN_BODY_RATE: usize = 1024 * 1024; +const BODY_GRACE_SECONDS: u64 = 5; + +fn body_budget(outside: bool) -> &'static tokio::sync::Semaphore { + static GITHUB: std::sync::OnceLock = std::sync::OnceLock::new(); + static OUTSIDE: std::sync::OnceLock = std::sync::OnceLock::new(); + if outside { + OUTSIDE.get_or_init(|| tokio::sync::Semaphore::new(OUTSIDE_GITHUB_BODY_MB as usize)) + } else { + GITHUB.get_or_init(|| tokio::sync::Semaphore::new(IN_FLIGHT_BODY_MB as usize)) + } +} + +/// Why a body couldn't be read. +enum BodyError { + TooLarge, + TooSlow, + Busy, +} + +/// Read a delivery's body, taking a megabyte of the budget for each megabyte as it arrives, within a deadline from its +/// declared size at [`MIN_BODY_RATE`]. The budget is given back when the returned permits are dropped. +async fn read_body( + body: axum::body::Body, + declared: Option, + outside: bool, +) -> Result<(Vec, Vec>), BodyError> { + use laravel::stream::StreamExt; + use std::time::{Duration, Instant}; + const MB_BYTES: usize = 1024 * 1024; + let budget = body_budget(outside); + let size = declared.unwrap_or(MAX_BODY); + let deadline = + Instant::now() + Duration::from_secs(BODY_GRACE_SECONDS) + Duration::from_secs((size / MIN_BODY_RATE) as u64); + let mut buf: Vec = Vec::with_capacity(size.min(MB_BYTES)); + let mut held: Vec> = Vec::new(); + let mut stream = body.into_data_stream(); + loop { + let left = deadline.saturating_duration_since(Instant::now()); + let chunk = match tokio::time::timeout(left, stream.next()).await { + Err(_) => return Err(BodyError::TooSlow), + Ok(None) => break, + Ok(Some(Err(_))) => return Err(BodyError::TooLarge), + Ok(Some(Ok(chunk))) => chunk, + }; + if buf.len() + chunk.len() > MAX_BODY { + return Err(BodyError::TooLarge); + } + buf.extend_from_slice(&chunk); + while held.len() < buf.len().div_ceil(MB_BYTES) { + let wait = Duration::from_secs(BODY_WAIT_SECONDS).min(deadline.saturating_duration_since(Instant::now())); + match tokio::time::timeout(wait, budget.acquire()).await { + Ok(Ok(permit)) => held.push(permit), + _ => return Err(BodyError::Busy), + } + } + } + Ok((buf, held)) +} + +/// [`read_body`] for tests: the body's length, or why it couldn't be read (`too large`, `too slow`, `busy`). +/// +/// # Errors +/// That. +pub async fn read_delivery_body( + body: axum::body::Body, + declared: Option, + outside: bool, +) -> Result { + match read_body(body, declared, outside).await { + Ok((body, _)) => Ok(body.len()), + Err(BodyError::TooLarge) => Err("too large"), + Err(BodyError::TooSlow) => Err("too slow"), + Err(BodyError::Busy) => Err("busy"), + } +} + +/// The cache key of GitHub's webhook source addresses (`hooks` in `GET /meta`), refreshed hourly +/// ([`RefreshGithubHookAddresses`]). +const HOOK_ADDRESSES: &str = "github:hook-addresses"; + +/// Whether an address is one of GitHub's webhook sources. `true` while the list isn't known yet (a new server, a +/// development one), so nothing is refused for want of it; `false` when the cache store can't be read. The address is the request's as the trusted proxies resolve +/// it (`VISUALCI_TRUSTED_PROXIES`: behind Cloudflare's tunnel and Envoy, the client Cloudflare names), which a client +/// can't choose by sending headers. +pub async fn from_github(ip: std::net::IpAddr) -> bool { + match laravel::cache::get::>(HOOK_ADDRESSES).await { + Ok(Some(ranges)) => ranges.is_empty() || ranges.iter().any(|r| in_range(ip, r)), + Ok(None) => true, + // The cache store failing: the small budget, not GitHub's + Err(e) => { + tracing::warn!(error = %e, "GitHub's hook addresses couldn't be read: treating the request as from outside"); + false + } + } +} + +/// Whether `ip` is in a CIDR range (`192.30.252.0/22`, `2a0a:a440::/29`). +#[must_use] +pub fn in_range(ip: std::net::IpAddr, range: &str) -> bool { + use std::net::IpAddr; + let (base, bits) = range.split_once('/').unwrap_or((range, "")); + let Ok(base) = base.parse::() else { return false }; + match (ip.to_canonical(), base) { + (IpAddr::V4(a), IpAddr::V4(b)) => { + let bits: u32 = bits.parse().unwrap_or(32).min(32); + let mask = if bits == 0 { 0 } else { u32::MAX << (32 - bits) }; + (u32::from(a) & mask) == (u32::from(b) & mask) + } + (IpAddr::V6(a), IpAddr::V6(b)) => { + let bits: u32 = bits.parse().unwrap_or(128).min(128); + let mask = if bits == 0 { 0 } else { u128::MAX << (128 - bits) }; + (u128::from(a) & mask) == (u128::from(b) & mask) + } + _ => false, + } +} + +/// Read GitHub's webhook source addresses (`GET /meta`, `hooks`) into the cache store for [`from_github`], with when +/// they were read (`/status` reports `github_hook_addresses_seconds`, so a refresh that keeps failing alerts). Scheduled +/// every five minutes, it reads them when they're missing (a new server: within five minutes of starting) or an hour +/// old. +#[derive(Queueable, Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct RefreshGithubHookAddresses; + +#[job] +impl RefreshGithubHookAddresses { + async fn handle(self) -> laravel::Result<()> { + use laravel::time::ToSpan; + let read_at: Option = laravel::cache::get("github:hook-addresses-at").await.ok().flatten(); + let fresh = read_at.is_some_and(|at| laravel::now().timestamp().as_second() - at < 3600); + if fresh && laravel::cache::get::>(HOOK_ADDRESSES).await.ok().flatten().is_some() { + return Ok(()); + } + let meta = super::calls::in_job("RefreshGithubHookAddresses", async { + laravel::http::client::get(format!("{}/meta", super::github_api())) + .header("accept", "application/vnd.github+json") + .header("user-agent", "visualci") + .await + }) + .await?; + if !meta.successful() { + return Err(laravel::Error::msg(format!("GitHub /meta: HTTP {}", meta.status()))); + } + let body: Value = meta.json()?; + let hooks: Vec = body["hooks"] + .as_array() + .map(|l| l.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()) + .unwrap_or_default(); + if hooks.is_empty() { + return Err(laravel::Error::msg("GitHub /meta lists no hook addresses")); + } + laravel::cache::put(HOOK_ADDRESSES, hooks, 7.days()).await?; + laravel::cache::put("github:hook-addresses-at", laravel::now().timestamp().as_second(), 7.days()).await?; + Ok(()) + } +} + +#[schedule::tasks] +fn hook_addresses(schedule: &mut Schedule) { + schedule.job(RefreshGithubHookAddresses).every_five_minutes().without_overlapping(); +} + +/// Whether a signature header has the shape GitHub sends (`sha256=` and 64 hex digits): anything else is refused +/// before the body is read. +fn well_formed(header: &str) -> bool { + header.strip_prefix("sha256=").is_some_and(|h| h.len() == 64 && h.bytes().all(|b| b.is_ascii_hexdigit())) +} + +/// Who has claimed an installation, which decides its limits. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum Claim { + /// Nobody: no organization set up for it and no project linked through it. Nothing of a customer's depends on its + /// deliveries. + Unclaimed, + /// An organization on the free plan (anyone with a GitHub account can make one by installing the App on their own + /// account and setting it up). + Free, + /// An organization on a paid plan (team, or staff). + Paid, +} + +impl Claim { + #[must_use] + pub fn claimed(self) -> bool { + self != Self::Unclaimed + } +} + +/// Who has claimed an installation: paid when the organization it's set up for is on a paid plan; free when it's set up +/// for one on the free plan, or only projects link through it. Only the organization it's set up for decides the plan, +/// so linking a project of a paid organization through someone else's installation doesn't lift it. +/// +/// # Errors +/// On a database error. +pub async fn claim(installation: &str) -> laravel::Result { + let id = installation.to_string(); + let best: Option = db::query!( + "SELECT CASE \ + WHEN EXISTS (SELECT 1 FROM github_installations g JOIN organizations o ON o.id = g.organization_id \ + WHERE g.installation_id = {id} AND o.plan IN ('team', 'staff')) THEN 2 \ + WHEN EXISTS (SELECT 1 FROM github_installations WHERE installation_id = {id} AND organization_id IS NOT NULL) \ + OR EXISTS (SELECT 1 FROM projects WHERE forge = 'github' AND forge_installation = {id}) THEN 1 \ + ELSE 0 END" + ) + .scalar() + .await?; + Ok(match best.unwrap_or(0) { + 0 => Claim::Unclaimed, + 1 => Claim::Free, + _ => Claim::Paid, + }) +} + +/// Whether a paid organization has a project linked through an installation. Its limits stay those of the organization +/// it's set up for ([`claim`]), but a paying customer's deliveries through it are never left unredelivered: past its +/// store's cap it answers 503 (redelivered), not 507, and its failures aren't held to a free installation's queue cap. +/// +/// # Errors +/// On a database error. +pub async fn paid_project_linked(installation: &str) -> laravel::Result { + let id = installation.to_string(); + let found: Option = db::query!( + "SELECT EXISTS (SELECT 1 FROM projects p JOIN organizations o ON o.id = p.organization_id \ + WHERE p.forge = 'github' AND p.forge_installation = {id} AND o.plan IN ('team', 'staff'))" + ) + .scalar() + .await?; + Ok(found.unwrap_or(false)) +} + +/// Whether anyone has claimed an installation ([`claim`]). +/// +/// # Errors +/// On a database error. +pub async fn claimed(installation: &str) -> laravel::Result { + Ok(claim(installation).await?.claimed()) +} + +/// What the limits said about a delivery. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Admission { + Accepted, + /// Over a limit: a claimed installation's delivery is kept for later ([`super::deliveries::defer`]), an unclaimed + /// one's dropped with a 202. + Over, +} + +/// The counts a delivery is checked against (`config::Limits`), its installation's first: +/// +/// - a paid installation: `webhooks_per_installation` a minute, and nothing shared, so no amount of others' traffic +/// holds up a paying customer's; +/// - a free one: `webhooks_per_free_installation`, and the shared `webhooks_total`; +/// - an unclaimed one: `webhooks_per_unclaimed_installation`, every unclaimed installation together +/// `webhooks_unclaimed_total`, and `webhooks_total`. Its `installation` deliveries (installed, suspended, removed: +/// only a person in GitHub's pages makes them) count only in `webhooks_total`, so a flood can't drop the one that +/// lets someone set it up; +/// - a delivery naming no installation: `webhooks_total`. +#[must_use] +pub fn counts( + limits: &Limits, + kind: &str, + installation: Option<&str>, + claim: Claim, +) -> Vec<(String, laravel::rate_limit::Limit)> { + use laravel::rate_limit::Limit; + let total = ("webhooks:github".to_string(), Limit::per_minute(limits.webhooks_total.max(1))); + let Some(id) = installation else { return vec![total] }; + let own = |n: u32| (format!("webhooks:github:{id}"), Limit::per_minute(n.max(1))); + match claim { + Claim::Paid => vec![own(limits.webhooks_per_installation)], + Claim::Free => vec![own(limits.webhooks_per_free_installation), total], + Claim::Unclaimed if kind == "installation" => vec![total], + Claim::Unclaimed => vec![ + own(limits.webhooks_per_unclaimed_installation), + ("webhooks:github:unclaimed".into(), Limit::per_minute(limits.webhooks_unclaimed_total.max(1))), + total, + ], + } +} + +/// What a delivery whose counts couldn't be read (the cache store failing, or its buckets contended past the +/// framework's retries, as in a flood) gets: never accepted outright, since that's when the limits matter most. A +/// claimed installation's is kept for later (whose own write fails, with a 5xx GitHub logs as failed, if the database +/// is down); an unclaimed one's is dropped. +#[must_use] +pub const fn when_uncounted(_claim: Claim) -> Admission { + Admission::Over +} + +/// Count a delivery against its limits ([`counts`]), taking one from each in turn; when a later count refuses, the +/// earlier ones get theirs back, so a refused delivery costs its installation nothing (and the drain doesn't pay +/// twice). +/// +/// GitHub never redelivers on its own, so over a limit a claimed installation's delivery is kept and acted on later at +/// the allowed rate; an unclaimed one's is dropped with a 202. +pub async fn admit(limits: &Limits, kind: &str, installation: Option<&str>, claim: Claim) -> Admission { + use laravel_cache::rate_limit::Bucket; + let mut taken: Vec = Vec::new(); + let mut outcome = Admission::Accepted; + for (key, limit) in counts(limits, kind, installation, claim) { + match Bucket::new(&key, limit).attempt().await { + Ok(Ok((_, bucket))) => taken.push(bucket), + Ok(Err(_)) => { + outcome = Admission::Over; + break; + } + Err(e) => { + tracing::error!(error = %e, key, ?claim, "webhook limits: the count couldn't be read; not accepting it now"); + outcome = when_uncounted(claim); + break; + } + } + } + if outcome != Admission::Accepted { + for bucket in &taken { + if let Err(e) = bucket.give_back().await { + tracing::warn!(error = %e, "webhook limits: couldn't give a count back"); + } + } + } + outcome +} + +/// Log a dropped delivery at most once a minute per installation in each process, so a flood doesn't flood the log. +fn log_dropped(installation: Option<&str>, kind: &str, delivery: &str) { + use std::sync::{Mutex, OnceLock}; + use std::time::{Duration, Instant}; + type Dropped = HashMap, u64)>; + static LAST: OnceLock> = OnceLock::new(); + let key = installation.unwrap_or("-").to_string(); + let mut last = LAST.get_or_init(|| Mutex::new(HashMap::new())).lock().unwrap_or_else(|e| e.into_inner()); + if last.len() > 10_000 { + last.clear(); + } + let now = Instant::now(); + let entry = last.entry(key).or_insert((None, 0)); + entry.1 += 1; + if entry.0.is_none_or(|at| now.duration_since(at) >= Duration::from_secs(60)) { + let dropped = std::mem::take(&mut entry.1); + entry.0 = Some(now); + tracing::warn!( + forge = "github", + installation, + kind, + delivery, + dropped, + "webhook deliveries dropped: over the limit" + ); + } +} + +/// Whether a delivery may be acted on now ([`claim_delivery`]). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DeliveryClaim { + /// Claimed for acting on (new, or taking over one abandoned mid-way), with the claim's owner token, which + /// [`finish_delivery`] and [`release_delivery`] need. + Claimed(String), + /// Acted on already: a duplicate. + Done, + /// Being acted on right now by another request or worker. + InProgress, +} + +/// How long a claim stays `processing` before another delivery of the same GUID may take it over: past the 30-second +/// request limit and the drain's own limit on acting on one ([`super::deliveries::PROCESS_SECONDS`]), so a claim older +/// than this was abandoned (a request cut off, a panic, a worker gone). +pub const CLAIM_TAKEOVER_SECONDS: i64 = 120; + +/// Claim a claimed installation's delivery (by `X-GitHub-Delivery`) for acting on, so one GitHub sends twice (such as +/// a redelivery of one that ran past its 10-second wait) is acted on once. Only a delivery acted on to the end +/// ([`finish_delivery`]) counts as a duplicate; one still `processing` after [`CLAIM_TAKEOVER_SECONDS`] is taken over, +/// with a new owner token. A delivery without a GUID is always claimed. Kept three days (the redelivery check prunes +/// them). +/// +/// # Errors +/// On a database error. +pub async fn claim_delivery(delivery: &str) -> laravel::Result { + let owner = laravel::str::random(32); + if delivery.is_empty() { + return Ok(DeliveryClaim::Claimed(owner)); + } + let guid = delivery.to_string(); + let claimed = db::query!( + "INSERT INTO webhook_deliveries_seen (delivery, owner) VALUES ({guid}, {owner}) \ + ON CONFLICT (delivery) DO UPDATE SET owner = EXCLUDED.owner, started_at = now(), seen_at = now() \ + WHERE webhook_deliveries_seen.state = 'processing' \ + AND webhook_deliveries_seen.started_at < now() - {CLAIM_TAKEOVER_SECONDS} * interval '1 second'" + ) + .insert() + .await?; + if claimed.rows_affected() > 0 { + return Ok(DeliveryClaim::Claimed(owner)); + } + let state: Option = + db::query!("SELECT state FROM webhook_deliveries_seen WHERE delivery = {guid}").scalar().await?; + Ok(if state.as_deref() == Some("done") { DeliveryClaim::Done } else { DeliveryClaim::InProgress }) +} + +/// Mark a delivery acted on to the end, if `owner`'s claim still holds it: from now on it's a duplicate. +/// +/// # Errors +/// On a database error. +pub async fn finish_delivery(delivery: &str, owner: &str) -> laravel::Result<()> { + if delivery.is_empty() { + return Ok(()); + } + let (guid, owner) = (delivery.to_string(), owner.to_string()); + db::query!( + "UPDATE webhook_deliveries_seen SET state = 'done', seen_at = now() WHERE delivery = {guid} AND owner = {owner}" + ) + .update() + .await?; + Ok(()) +} + +/// Let `owner`'s claim on a delivery go after acting on it failed, so GitHub's redelivery of it is acted on. A claim +/// taken over meanwhile (another owner) is left alone. (One abandoned without this is taken over after +/// [`CLAIM_TAKEOVER_SECONDS`].) +/// +/// # Errors +/// On a database error. +pub async fn release_delivery(delivery: &str, owner: &str) -> laravel::Result<()> { + if delivery.is_empty() { + return Ok(()); + } + let (guid, owner) = (delivery.to_string(), owner.to_string()); + db::query!( + "DELETE FROM webhook_deliveries_seen WHERE delivery = {guid} AND owner = {owner} AND state = 'processing'" + ) + .delete() + .await?; + Ok(()) +} + +/// `POST /webhooks/github`. The signature is checked before anything else: a missing or malformed one before the body +/// is read (each body read holds a share of [`IN_FLIGHT_BODY_MB`] as it arrives), a wrong one before the body is parsed, and neither +/// touches the database. Then: +/// +/// - a claimed installation's delivery already acted on is answered as a duplicate; +/// - one for a claimed installation with deliveries kept for later is kept too, behind them, so they're acted on in +/// order; +/// - the rest are counted against their limits ([`admit`]) and acted on ([`process`]), or over them kept for later (a +/// claimed installation's: a 202, or a 503 when what's kept is at its cap, so GitHub logs it as failed and the +/// redelivery check sends it again) or dropped (an unclaimed one's, with a 202). 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 { + limits: laravel::config::Section, + request: laravel::http::Request, +) -> laravel::Result { + let Some(secret) = app.webhook_secret.clone().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) { + let header = |name: &str| request.header(name).unwrap_or_default().to_string(); + let signature = header("x-hub-signature-256"); + if !well_formed(&signature) { 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 mut outcome = handle(&app, read).await?; + let declared = header("content-length").parse::().ok(); + if declared.is_some_and(|n| n > MAX_BODY) { + return Err(laravel::abort_with(413, "a delivery is at most 25 MB")); + } + let outside = !from_github(request.ip()).await; + let busy = + || Ok(laravel::http::Response::new("busy: try again shortly").with_status(503).with_header("retry-after", "5")); + let (body, permits) = match read_body(request.into_http().into_body(), declared, outside).await { + Ok(read) => read, + Err(BodyError::TooLarge) => return Err(laravel::abort_with(413, "a delivery is at most 25 MB")), + Err(BodyError::TooSlow) => return Err(laravel::abort_with(408, "the delivery's body arrived too slowly")), + Err(BodyError::Busy) => return busy(), + }; + if !signed(&secret, &signature, &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()))?; + drop(permits); + let installation = event["installation"]["id"].as_i64().map(|i| i.to_string()); + let claim = match &installation { + Some(id) => claim(id).await?, + // GitHub App deliveries name their installation; the few that don't (a ping) count against the total + None => Claim::Free, + }; + let keep = |status: u16, outcome: Value| Ok(laravel::http::Response::new(Json(outcome)).with_status(status)); + if let Some(id) = installation.as_deref().filter(|_| claim.claimed()) + && super::deliveries::has_deferred(id).await? + { + let (status, outcome) = super::deliveries::defer(&limits, claim, id, &delivery, &kind, &body).await?; + return keep(status, outcome); + } + if admit(&limits, &kind, installation.as_deref(), claim).await == Admission::Over { + if let Some(id) = installation.as_deref().filter(|_| claim.claimed()) { + let (status, outcome) = super::deliveries::defer(&limits, claim, id, &delivery, &kind, &body).await?; + return keep(status, outcome); + } + log_dropped(installation.as_deref(), &kind, &delivery); + return keep(202, json!({ "dropped": "over the limit" })); + } + let dedupe = installation.is_some() && claim.claimed(); + let mut owner = None; + if dedupe { + match claim_delivery(&delivery).await? { + DeliveryClaim::Claimed(token) => owner = Some(token), + DeliveryClaim::Done => return keep(200, json!({ "duplicate": "acted on already" })), + // Not a 2xx: if the other one never finishes, GitHub's log shows this attempt failed, and the redelivery + // check sends it again once the claim can be taken over + DeliveryClaim::InProgress => { + return keep(409, json!({ "in_progress": "this delivery is being acted on now" })); + } + } + } + let outcome = match process(&app, &kind, &event, claim.claimed()).await { + Ok(outcome) => outcome, + Err(e) => { + if let Some(owner) = &owner { + release_delivery(&delivery, owner).await?; + } + return Err(e); + } + }; + if let Some(owner) = &owner { + finish_delivery(&delivery, owner).await?; + } + tracing::info!(forge = "github", kind, delivery, ?claim, outcome = %outcome, "webhook"); + Ok(laravel::http::Response::new(Json(outcome))) +} + +/// Act on one verified delivery (its `X-GitHub-Event` and parsed body): now, or later when it was kept over the limit. +/// +/// # Errors +/// 400 for a delivery VisualCI can't read; database and GitHub errors. +pub async fn process(app: &GithubApp, kind: &str, event: &Value, claimed: bool) -> laravel::Result { + let read = read_event(kind, event).map_err(|e| laravel::abort_with(400, e))?; + let mut outcome = handle(app, read, claimed).await?; // Installations recorded (after `handle` has attached the projects already linked) - let installations = super::installations::from_webhook(&kind, &event).await?; + let installations = super::installations::from_webhook(kind, event).await?; if !installations.is_null() && let Some(map) = outcome.as_object_mut() { map.insert("installations".into(), installations); } - tracing::info!(forge = "github", kind, delivery, outcome = %outcome, "webhook"); - Ok(Json(outcome)) + Ok(outcome) } -/// Act on one event; returns what happened, for the delivery's log on GitHub. +/// Act on one event; returns what happened, for the delivery's log on GitHub. `claimed` is whether anyone has claimed +/// the delivery's installation ([`claimed`]): an unclaimed one's membership changes recheck nobody, since no +/// organization's access comes through it. +/// +/// Each event costs a fixed number of queries and GitHub calls, whatever its size: an installation's repositories are +/// looked up in one query, and GitHub is asked whether the installation exists only when a project would change. /// /// # Errors /// On a database error. -pub async fn handle(app: &GithubApp, event: ForgeEvent) -> laravel::Result { +pub async fn handle(app: &GithubApp, event: ForgeEvent, claimed: bool) -> laravel::Result { Ok(match event { ForgeEvent::Merged { repository, head, base, merge_commit } => { let projects = linked(&repository).await?; @@ -340,34 +910,37 @@ pub async fn handle(app: &GithubApp, event: ForgeEvent) -> laravel::Result { + let mut changes = Vec::new(); + for p in linked_any(&repositories).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; + } + changes.push(p); + } // A stale or redelivered "created" mustn't attach an installation that's gone - if let Some(id) = &installation + if !changes.is_empty() + && 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; - } + for p in &changes { + 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); } recheck_organizations(affected.into_iter().collect()).await?; + let changed = changes.len(); if installation.is_some() { json!({ "linked": changed }) } else { json!({ "unlinked": changed }) } } + ForgeEvent::Access { .. } if !claimed => json!({ "ignored": "unclaimed installation" }), ForgeEvent::Access { people } => { let mut users = Vec::new(); for person in people { @@ -379,9 +952,7 @@ pub async fn handle(app: &GithubApp, event: ForgeEvent) -> laravel::Result 0 { - RecheckAccess { user_ids: users }.dispatch().await?; - } + queue_recheck(users).await?; json!({ "rechecking": n }) } ForgeEvent::AccessAll { installation } => { @@ -417,23 +988,63 @@ async fn recheck_organizations(orgs: Vec) -> laravel::Result<()> { users.insert(r.try_get::("user_id")?); } } - if !users.is_empty() { - RecheckAccess { user_ids: users.into_iter().collect() }.dispatch().await?; + queue_recheck(users.into_iter().collect()).await +} + +/// Queue these people for the next [`RecheckAccess`] run: they wait in `access_rechecks`, and the debounced run +/// rechecks everyone waiting at once. +/// +/// # Errors +/// On a database or queue error. +pub async fn queue_recheck(user_ids: Vec) -> laravel::Result<()> { + if user_ids.is_empty() { + return Ok(()); + } + wait_for_recheck(&user_ids).await?; + RecheckAccess { user_ids }.dispatch().await?; + Ok(()) +} + +/// Add people to `access_rechecks` (those whose accounts still exist). +async fn wait_for_recheck(user_ids: &[i64]) -> laravel::Result<()> { + for &user_id in user_ids { + db::query!( + "INSERT INTO access_rechecks (user_id) SELECT id FROM users WHERE id = {user_id} \ + ON CONFLICT (user_id) DO NOTHING" + ) + .insert() + .await?; } Ok(()) } -/// Recheck people's memberships from GitHub through the App ([`recheck`]). +/// Recheck people's memberships from GitHub through the App ([`recheck`]): everyone waiting in `access_rechecks`, and +/// `user_ids`. Debounced: deliveries in a burst (a team's repositories changed, members added one by one) make one run +/// that lists every linked repository's collaborators once, 30 seconds after the last of them and at most 2 minutes +/// after the first. When GitHub can't answer, the people go back to wait for the retry or the hourly sync, which +/// rechecks everyone. #[derive(Queueable, Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct RecheckAccess { pub user_ids: Vec, } -#[job] +#[job(debounce_for = 30.seconds(), max_wait = 2.minutes())] impl RecheckAccess { async fn handle(self, app: laravel::config::Section) -> laravel::Result<()> { - recheck(&app, &self.user_ids).await?; - Ok(()) + super::calls::in_job("RecheckAccess", async move { + let mut users: HashSet = self.user_ids.iter().copied().collect(); + let waiting = db::query!("DELETE FROM access_rechecks RETURNING user_id").select().await?; + for r in waiting { + users.insert(r.try_get::("user_id")?); + } + let users: Vec = users.into_iter().collect(); + if let Err(e) = recheck(&app, &users).await { + wait_for_recheck(&users).await?; + return Err(e); + } + Ok(()) + }) + .await } } diff --git a/app/src/heartbeat.rs b/app/src/heartbeat.rs index b0253639..250ecb16 100644 --- a/app/src/heartbeat.rs +++ b/app/src/heartbeat.rs @@ -19,6 +19,7 @@ pub enum Heartbeat { BuildsExpire, GroupsCheck, CreditOverrides, + WebhookRedelivery, } impl Heartbeats { @@ -36,6 +37,7 @@ impl Heartbeats { Heartbeat::BuildsExpire => (&self.builds_expire_url, &self.builds_expire_token), Heartbeat::GroupsCheck => (&self.groups_check_url, &self.groups_check_token), Heartbeat::CreditOverrides => (&self.credit_overrides_url, &self.credit_overrides_token), + Heartbeat::WebhookRedelivery => (&self.webhook_redelivery_url, &self.webhook_redelivery_token), }; (url.as_deref(), token.as_deref()) } diff --git a/app/src/http/hosts.rs b/app/src/http/hosts.rs index b0ef4807..f7b1adf9 100644 --- a/app/src/http/hosts.rs +++ b/app/src/http/hosts.rs @@ -68,7 +68,10 @@ fn under(path: &str, prefix: &str) -> bool { fn is_oauth_server_path(path: &str) -> bool { under(path, "/.well-known/oauth-authorization-server") || under(path, "/.well-known/oauth-protected-resource") - || matches!(path, "/oauth/register" | "/oauth/token" | "/oauth/revoke" | "/oauth/introspect") + || matches!( + path.trim_end_matches('/'), + "/oauth/register" | "/oauth/token" | "/oauth/revoke" | "/oauth/introspect" + ) } fn is_site_path(path: &str) -> bool { diff --git a/app/src/http/status.rs b/app/src/http/status.rs index 4344614e..6a13b985 100644 --- a/app/src/http/status.rs +++ b/app/src/http/status.rs @@ -12,9 +12,124 @@ pub const COMMIT: &str = match option_env!("BUILD_SHA") { None => "dev", }; +/// How long one process reuses its answer: `/status` is anonymous and its query counts rows across several tables, so +/// a flood of requests runs it at most once per this many seconds per process instead of once each. Gatus polls every +/// minute. Not under `APP_ENV=testing`, whose tests change rows and read the numbers again at once. +const REUSE_SECONDS: u64 = 10; + +/// How long a failed query is remembered: a database that hangs or fails is asked at most this often per process, +/// and requests meanwhile get the 503 at once. +const FAILURE_SECONDS: u64 = 2; +/// How long one request asking the database stops others asking too (they get the last answer meanwhile): past it, +/// the request is taken to have died (a timeout, a client gone), and the next one asks. +const ASKING_SECONDS: u64 = 15; +/// The oldest answer ever given: past it a request asks the database itself, whoever else is asking. +const OLDEST_SECONDS: u64 = 60; + +/// The last answer and when, the last failure's time, and since when a request has been asking the database. The lock +/// is held only to read or write these, never across the query. +#[derive(Default)] +struct Reused { + answer: Option<(std::time::Instant, Value)>, + failed: Option, + asking_since: Option, +} + +fn reused() -> std::sync::MutexGuard<'static, Reused> { + static LAST: std::sync::OnceLock> = std::sync::OnceLock::new(); + LAST.get_or_init(Default::default).lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + +/// Clears `asking_since` however the asking request ends, its future dropped (a timeout, a client gone) included. +struct Asking; + +impl Drop for Asking { + fn drop(&mut self) { + reused().asking_since = None; + } +} + +/// What a `/status` request does: reuse the last answer, give the last failure, or ask the database (then marked as +/// asking since `now`). +#[derive(Debug, PartialEq)] +enum Decision { + Reuse(Value), + Failed, + Ask, +} + +fn decide(r: &mut Reused, now: std::time::Instant) -> Decision { + use std::time::Duration; + let age = |at: std::time::Instant| now.saturating_duration_since(at); + let asking = r.asking_since.is_some_and(|at| age(at) < Duration::from_secs(ASKING_SECONDS)); + match (&r.answer, r.failed) { + (Some((at, body)), _) if age(*at) < Duration::from_secs(REUSE_SECONDS) => Decision::Reuse(body.clone()), + (_, Some(at)) if age(at) < Duration::from_secs(FAILURE_SECONDS) => Decision::Failed, + (Some((at, body)), _) if asking && age(*at) < Duration::from_secs(OLDEST_SECONDS) => { + Decision::Reuse(body.clone()) + } + _ => { + r.asking_since = Some(now); + Decision::Ask + } + } +} + +/// [`numbers`], reused for [`REUSE_SECONDS`]: while one request asks the database (for at most [`ASKING_SECONDS`]), +/// others get the last answer, never one older than [`OLDEST_SECONDS`]. A failure is reused for [`FAILURE_SECONDS`]. +/// The live stream fields are this process's own and always fresh. +async fn cached() -> laravel::Result { + use std::time::Instant; + if matches!(laravel::config().app.env, laravel::config::app::Environment::Testing) { + let mut body = numbers().await.map(|Json(v)| v)?; + body["github_hook_addresses_seconds"] = json!(hook_addresses_age().await); + return Ok(body); + } + let reuse = match decide(&mut reused(), Instant::now()) { + Decision::Reuse(body) => Some(Ok(body)), + Decision::Failed => Some(Err(laravel::Error::msg("the database didn't answer a moment ago"))), + Decision::Ask => None, + }; + let mut body = match reuse { + Some(answer) => answer?, + None => { + let guard = Asking; + let asked = numbers().await; + let mut r = reused(); + match asked { + Ok(Json(body)) => { + r.answer = Some((Instant::now(), body.clone())); + r.failed = None; + drop(r); + drop(guard); + body + } + Err(e) => { + r.failed = Some(Instant::now()); + drop(r); + drop(guard); + return Err(e); + } + } + } + }; + body["live_streams_open"] = json!(super::live::STREAMS.open()); + body["live_listener"] = json!(crate::live::listener_state()); + body["github_hook_addresses_seconds"] = json!(hook_addresses_age().await); + Ok(body) +} + +/// How long ago GitHub's webhook addresses were read (`-1` when never): the hourly refresh keeps it under an hour. +async fn hook_addresses_age() -> i64 { + match laravel::cache::get::("github:hook-addresses-at").await { + Ok(Some(at)) => laravel::now().timestamp().as_second() - at, + _ => -1, + } +} + pub async fn status() -> axum::response::Response { use axum::response::IntoResponse; - match numbers().await { + match cached().await.map(Json) { Ok(body) => body.into_response(), // Every connection busy, or the database down: a fast 503 that Gatus alerts on, never a hang. Err(e) => { @@ -56,7 +171,11 @@ async fn numbers() -> laravel::Result> { COALESCE((SELECT EXTRACT(EPOCH FROM now() - MIN(synced_at)) FROM memberships \ WHERE source = 'github' AND synced_at IS NOT NULL), 0)::BIGINT AS oldest_forge_sync_seconds, \ COALESCE((SELECT EXTRACT(EPOCH FROM now() - MIN(updated_at)) FROM repository_imports \ - WHERE finished_at IS NULL), 0)::BIGINT AS stalled_repository_import_seconds" + WHERE finished_at IS NULL), 0)::BIGINT AS stalled_repository_import_seconds, \ + COALESCE((SELECT EXTRACT(EPOCH FROM now() - MIN(queued_at)) FROM access_rechecks), 0)::BIGINT \ + AS oldest_access_recheck_seconds, \ + COALESCE((SELECT EXTRACT(EPOCH FROM now() - MIN(received_at)) FROM deferred_webhooks), 0)::BIGINT \ + AS oldest_deferred_webhook_seconds" ) .select_one() .await? @@ -95,5 +214,46 @@ async fn numbers() -> laravel::Result> { // The longest an unfinished pick of repositories has gone without progress: its job saves after each repository // (a few seconds), so past a few minutes the queue has stopped or the job died. "stalled_repository_import_seconds": get("stalled_repository_import_seconds")?, + // The longest anyone a webhook queued for an access recheck has waited: the debounced run takes them within + // about 2 minutes, and the hourly forge sync anyway, so past an hour and a bit both have stopped. + "oldest_access_recheck_seconds": get("oldest_access_recheck_seconds")?, + // The longest a GitHub delivery kept over its installation's rate limit has waited: the drain (every minute) + // acts on them at the allowed rate, so past ten minutes it has stopped or the installation is flooding. + "oldest_deferred_webhook_seconds": get("oldest_deferred_webhook_seconds")?, }))) } + +#[cfg(test)] +mod tests { + use std::time::{Duration, Instant}; + + use super::*; + + fn ago(now: Instant, seconds: u64) -> Instant { + now.checked_sub(Duration::from_secs(seconds)).expect("the clock has run long enough") + } + + /// A request asking the database whose future is dropped (a timeout, a client gone) doesn't leave others served a + /// stale answer for good: the guard clears it, an ask past its time no longer counts, and no answer older than a + /// minute is given. + #[test] + fn a_dropped_ask_leaves_no_stale_answer() { + let now = Instant::now() + Duration::from_secs(600); + let answer = Some((ago(now, 30), json!({ "ok": true }))); + // Someone asking now: the 30-second-old answer meanwhile + let mut r = Reused { answer: answer.clone(), failed: None, asking_since: Some(ago(now, 1)) }; + assert_eq!(decide(&mut r, now), Decision::Reuse(json!({ "ok": true }))); + // Their ask died 20 seconds ago: this request asks + let mut r = Reused { answer: answer.clone(), failed: None, asking_since: Some(ago(now, 20)) }; + assert_eq!(decide(&mut r, now), Decision::Ask); + // Someone asking, but the answer is over a minute old: ask anyway + let mut r = Reused { answer: Some((ago(now, 70), json!({}))), failed: None, asking_since: Some(ago(now, 1)) }; + assert_eq!(decide(&mut r, now), Decision::Ask); + // The guard clears the flag however the asking future ends + reused().asking_since = Some(Instant::now()); + { + let _asking = Asking; + } + assert!(reused().asking_since.is_none()); + } +} diff --git a/app/src/lib.rs b/app/src/lib.rs index bec39fa3..3dc53393 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -36,6 +36,8 @@ pub fn configure() -> ApplicationBuilder { // Every VisualCI setting, from the environment (config.rs) .with_config(config::install) .with_services(|app| { + // Counts each request's GitHub calls against its budget (forge::calls) + app.instance(forge::calls::client()); app.social().extend("gitlab", |config| forge::gitlab::Driver { url: config.section::().url.clone(), }); @@ -63,6 +65,10 @@ pub fn configure() -> ApplicationBuilder { tracing::error!(error = %e, "VISUALCI_TRUSTED_PROXIES: trusting no proxies"); } middleware.prepend(http::hosts::route_by_host); + // Every request's GitHub calls, held to a fixed budget (sc-9124) + middleware.prepend(forge::calls::count_github_calls); + // Anonymous OAuth client registrations, limited per address and in total (sc-9144) + middleware.prepend(auth::oauth::limit_registrations); // 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])); // Laravel's TrustHosts would trust APP_URL's host alone, refusing the API and MCP hosts and the pods' own diff --git a/app/tests/abuse.rs b/app/tests/abuse.rs new file mode 100644 index 00000000..14057708 --- /dev/null +++ b/app/tests/abuse.rs @@ -0,0 +1,1263 @@ +//! The GitHub App is public, so anyone can install it and make GitHub send its webhook (sc-9144). A flood from +//! installations nobody has claimed stays cheap and bounded: bad signatures are refused before anything is read or +//! written, each unclaimed installation and all of them together are limited, their deliveries queue no jobs, write +//! nothing but their own installation's row, and make no GitHub calls; and a claimed installation's delivery is still +//! acted on. Anonymous OAuth client registrations are limited too. + +use app::forge::events::PullRequestMerged; +use app::forge::webhooks::RecheckAccess; +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 = "github-webhook-test"; + +/// Per minute: one unclaimed installation, all unclaimed together, one claimed installation, everything. +const PER_UNCLAIMED: u32 = 3; +const UNCLAIMED_TOTAL: u32 = 30; +const PER_INSTALLATION: u32 = 200; +const TOTAL: u32 = 2000; + +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 limited() -> Application { + app::testing::configure() + .with_envs([ + ("VISUALCI_GITHUB_WEBHOOK_SECRET", SECRET.to_string()), + ("VISUALCI_GITHUB_APP_ID", "1".to_string()), + ("VISUALCI_GITHUB_APP_PRIVATE_KEY_BASE64", app_key().to_string()), + ("VISUALCI_GITHUB_WEBHOOKS_PER_UNCLAIMED_INSTALLATION", PER_UNCLAIMED.to_string()), + ("VISUALCI_GITHUB_WEBHOOKS_UNCLAIMED_TOTAL", UNCLAIMED_TOTAL.to_string()), + ("VISUALCI_GITHUB_WEBHOOKS_PER_INSTALLATION", PER_INSTALLATION.to_string()), + ("VISUALCI_GITHUB_WEBHOOKS_TOTAL", TOTAL.to_string()), + ("VISUALCI_OAUTH_REGISTRATIONS_PER_ADDRESS", "3".to_string()), + ]) + .create() +} + +fn signature(body: &str) -> String { + let mut mac = Hmac::::new_from_slice(SECRET.as_bytes()).unwrap(); + mac.update(body.as_bytes()); + format!("sha256={}", hex::encode(mac.finalize().into_bytes())) +} + +async fn send(app: &Application, kind: &str, body: String, signature: Option) -> TestResponse { + let mut request = app + .post("/webhooks/github") + .header("x-github-event", kind) + .header("x-github-delivery", laravel::str::uuid7().to_string()) + .header("content-type", "application/json"); + if let Some(s) = signature { + request = request.header("x-hub-signature-256", s); + } + request.body(body).await +} + +async fn deliver(app: &Application, kind: &str, event: &serde_json::Value) -> TestResponse { + let body = event.to_string(); + let s = signature(&body); + send(app, kind, body, Some(s)).await +} + +async fn count(table: &str) -> laravel::Result { + let n: Option = match table { + "github_installations" => db::query!("SELECT COUNT(*) FROM github_installations").scalar().await?, + "access_rechecks" => db::query!("SELECT COUNT(*) FROM access_rechecks").scalar().await?, + "projects" => db::query!("SELECT COUNT(*) FROM projects").scalar().await?, + "user_repositories" => db::query!("SELECT COUNT(*) FROM user_repositories").scalar().await?, + "oauth_clients" => db::query!("SELECT COUNT(*) FROM oauth_clients").scalar().await?, + other => panic!("no count for {other}"), + }; + Ok(n.unwrap_or(0)) +} + +/// Ada (GitHub 1001), a member through GitHub of `acme`, whose project `web` links acme/web through installation 7. +async fn claimed_installation() -> laravel::Result { + let ada = + create!(app::models::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 org = app::testing::fixtures::organization("acme").await?; + let org_id = org.id; + // A paying customer's installation (set up for its organization): its own limits, and nothing shared + db::query!("UPDATE organizations SET plan = 'team' WHERE id = {org_id}").update().await?; + db::query!( + "INSERT INTO github_installations (installation_id, account_id, account_login, account_type, organization_id) \ + VALUES ('7', '5005', 'acme', 'Organization', {org_id})" + ) + .insert() + .await?; + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org_id}, {ada_id}, 'member', 'github', now(), now())" + ) + .insert() + .await?; + 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_id}, 'web', 'Web', 'github', 'https://github.com/acme/web', '42', '7', \ + now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + Ok(project) +} + +/// An unclaimed installation's account and a few hundred of its repositories, as its deliveries list them. +fn stranger(n: usize) -> (serde_json::Value, serde_json::Value, serde_json::Value) { + let account = json!({ "id": 70_000 + n, "login": format!("stranger-{n}"), "type": "Organization" }); + let repositories: Vec = (0..300) + .map(|r| json!({ "id": 9_000_000 + n * 1000 + r, "full_name": format!("stranger-{n}/repo-{r}") })) + .collect(); + let repo = repositories[0].clone(); + (account, serde_json::Value::Array(repositories), repo) +} + +/// What one unclaimed installation sends: installed with 300 repositories, then repositories added, a branch deleted, +/// a failed run, membership and team changes naming Ada (a VisualCI user), and an organization member added. +fn flood_of(n: usize) -> Vec<(&'static str, serde_json::Value)> { + let id = 1000 + n; + let (account, repositories, repo) = stranger(n); + let installation = json!({ "id": id, "account": account }); + vec![ + ( + "installation", + json!({ "action": "created", "installation": installation, "sender": { "id": 70_000 + n }, + "repositories": repositories }), + ), + ( + "installation_repositories", + json!({ "action": "added", "installation": installation, "repositories_added": repositories }), + ), + ( + "push", + json!({ "ref": "refs/heads/main", "deleted": true, "repository": repo, "installation": { "id": id } }), + ), + ( + "workflow_run", + json!({ "action": "completed", "repository": repo, "installation": { "id": id }, + "workflow_run": { "head_sha": "abc", "conclusion": "failure", + "html_url": format!("https://github.com/stranger-{n}/repo-0/actions/runs/1") } }), + ), + ( + "member", + json!({ "action": "added", "member": { "id": 1001 }, "repository": repo, "installation": { "id": id } }), + ), + ("membership", json!({ "action": "added", "member": { "id": 1001 }, "installation": { "id": id } })), + ( + "organization", + json!({ "action": "member_added", "membership": { "user": { "id": 1001 } }, "installation": { "id": id } }), + ), + ("team", json!({ "action": "added_to_repository", "repository": repo, "installation": { "id": id } })), + ( + "pull_request", + json!({ "action": "closed", "repository": repo, "installation": { "id": id }, + "pull_request": { "merged": false, "head": { "ref": "x", "repo": { "full_name": repo["full_name"] } } } }), + ), + ("repository", json!({ "action": "privatized", "repository": repo, "installation": { "id": id } })), + ] +} + +/// N unclaimed installations with M deliveries each, plus badly signed ones: bounded responses, rows, jobs and GitHub +/// calls, and the claimed installation's deliveries are still acted on. +#[laravel::test(app = limited)] +async fn a_flood_from_unclaimed_installations_stays_bounded(app: Application) -> laravel::Result<()> { + const N: usize = 20; + let project = claimed_installation().await?; + let jobs = laravel::queue::fake(); + let events = laravel::event::fake(); + let github = client::fake() + .with("api.github.com/app/installations/*", json!({ "id": 7 })) + .with("api.github.com/*", client::response().status(404).json(json!({}))); + let (rows_before, rechecks_before) = (count("github_installations").await?, count("access_rechecks").await?); + + let started = std::time::Instant::now(); + let (mut accepted, mut dropped, mut refused, mut sent) = (0u32, 0u32, 0u32, 0u32); + let mut per_installation = std::collections::HashMap::::new(); + for n in 0..N { + let deliveries = flood_of(n); + let m = deliveries.len(); + for (kind, event) in deliveries { + sent += 1; + let r = deliver(&app, kind, &event).await; + match r.status().as_u16() { + 200 => { + accepted += 1; + if kind != "installation" { + *per_installation.entry(n).or_default() += 1; + } + } + 202 => dropped += 1, + s => panic!("{kind} for installation {n}: {s} {}", r.text()), + } + } + assert_eq!(m, 10, "M deliveries each"); + // Badly signed, unsigned and malformed: refused before anything is read, written or counted + let forged = json!({ "action": "created", "installation": { "id": 900 + n, "account": stranger(n).0 }, + "repositories": stranger(n).1 }) + .to_string(); + for s in [Some(signature("something else")), None, Some("sha256=zz".to_string()), Some("sha1=00".to_string())] { + let r = send(&app, "installation", forged.clone(), s).await; + assert_eq!(r.status().as_u16(), 401, "{}", r.text()); + refused += 1; + } + } + let seconds = started.elapsed().as_secs_f64(); + assert_eq!(sent, (N * 10) as u32); + assert_eq!(refused, (N * 4) as u32); + + // Each count fills at once and refills evenly: what the limits allow in the time the flood took. `installation` + // deliveries count only in the total, so every installation is recorded and can be set up. + let allowed = |per_minute: u32| f64::from(per_minute) * (1.0 + seconds / 60.0) + 1.0; + for (n, got) in &per_installation { + assert!(f64::from(*got) <= allowed(PER_UNCLAIMED), "installation {n}: {got} accepted in {seconds:.1}s"); + } + let others: u32 = per_installation.values().sum(); + assert_eq!(accepted - others, N as u32, "every installation's `installation` delivery accepted"); + assert!(f64::from(others) <= allowed(UNCLAIMED_TOTAL), "{others} accepted in {seconds:.1}s"); + assert_eq!(dropped, sent - accepted, "the rest dropped with a 202"); + assert!(dropped > 0, "the limits dropped some"); + + // Nothing queued, no GitHub calls, no events: an unclaimed installation can't reach a customer's data + jobs.assert_nothing_pushed(); + events.assert_not_dispatched::(); + assert_eq!( + github.sent().len(), + 0, + "GitHub calls: {:?}", + github.sent().iter().map(|r| r.url().to_string()).collect::>() + ); + // Rows: at most one per installation that got through, none from forged deliveries, no projects, no rechecks + let rows = count("github_installations").await? - rows_before; + assert_eq!(rows, N as i64, "one row per installation"); + let forged_rows: Option = + db::query!("SELECT COUNT(*) FROM github_installations WHERE installation_id::bigint BETWEEN 900 AND 999") + .scalar() + .await?; + assert_eq!(forged_rows, Some(0)); + assert_eq!(count("projects").await?, 1, "only the claimed project"); + assert_eq!(count("access_rechecks").await?, rechecks_before); + assert_eq!(count("user_repositories").await?, 0); + // The limits' own rows: one per installation and the two shared counts + let buckets: Option = + db::query!("SELECT COUNT(*) FROM cache WHERE key LIKE '%webhooks:github%'").scalar().await?; + assert!(buckets.unwrap_or(0) <= N as i64 + 3, "{buckets:?} rate limit rows"); + + // The claimed installation is acted on as before: a merge reaches its project, a membership change queues a recheck + let merged = json!({ + "action": "closed", "installation": { "id": 7 }, "repository": { "id": 42, "full_name": "acme/web" }, + "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", 1); + events.assert_dispatched_where::(|e| e.project_id == project); + let member = json!({ "action": "removed", "member": { "id": 1001 }, "installation": { "id": 7 }, + "repository": { "id": 42, "full_name": "acme/web" } }); + deliver(&app, "member", &member).await.assert_ok().assert_json_path("rechecking", 1); + jobs.assert_pushed_times::(1); + assert_eq!(count("access_rechecks").await?, rechecks_before + 1); + Ok(()) +} + +/// A build receiving snapshots from run 9 of acme/web on `commit`. +async fn receiving(project_id: i64, commit: &str) -> laravel::Result { + let project = app::models::Project::find_or_fail(project_id).await?; + let params: app::domain::builds::CreateParams = serde_json::from_value(json!({ + "commit": commit, "branch": "feature", "mode": "ci", + "environment_info": { "provider": "github", "job_url": "https://github.com/acme/web/actions/runs/9" }, + }))?; + let build = app::domain::builds::create(&project, ¶ms, None) + .await + .map_err(|e| laravel::Error::msg(format!("{e:?}")))?; + Ok(build.id) +} + +fn limits() -> app::config::Limits { + laravel::config().get::().cloned().expect("the limits") +} + +fn github_app() -> app::config::GithubApp { + app::config::GithubApp { + app_id: Some("1".into()), + private_key_base64: Some(app_key().into()), + webhook_secret: Some(SECRET.into()), + } +} + +/// A claimed installation past its own limit loses nothing: GitHub never redelivers, so each delivery over it is kept +/// (202) and acted on once the limit allows: a failed run still closes the build it was sending. +#[laravel::test(app = limited)] +async fn a_claimed_installation_over_its_limit_has_its_deliveries_kept_and_acted_on( + app: Application, +) -> laravel::Result<()> { + let project = claimed_installation().await?; + let build = receiving(project, "abc123").await?; + let events = laravel::event::fake(); + let push = json!({ "ref": "refs/heads/main", "installation": { "id": 7 }, "repository": { "id": 42, "full_name": "acme/web" } }); + let mut statuses = std::collections::BTreeMap::::new(); + // The count refills while the deliveries go in (a slow machine sends fewer a second), so send until one is kept, + // then a few more + for _ in 0..(PER_INSTALLATION * 3) { + *statuses.entry(deliver(&app, "push", &push).await.status().as_u16()).or_default() += 1; + if statuses.get(&202).copied().unwrap_or(0) >= 3 { + break; + } + } + assert!(statuses.get(&200).copied().unwrap_or(0) >= PER_INSTALLATION, "{statuses:?}"); + assert!(statuses.get(&202).copied().unwrap_or(0) >= 3, "{statuses:?}"); + assert_eq!(statuses.get(&429), None, "never refused: GitHub wouldn't redeliver it"); + let run = json!({ + "action": "completed", "installation": { "id": 7 }, "repository": { "id": 42, "full_name": "acme/web" }, + "workflow_run": { "head_sha": "abc123", "conclusion": "failure", + "html_url": "https://github.com/acme/web/actions/runs/9" }, + }); + let body = run.to_string(); + let s = signature(&body); + let r = app + .post("/webhooks/github") + .header("x-github-event", "workflow_run") + .header("x-github-delivery", "run-9") + .header("x-hub-signature-256", s) + .header("content-type", "application/json") + .body(body) + .await; + r.assert_status(202).assert_json_path("deferred", "kept, and acted on shortly in the order it came"); + assert_eq!(app::models::Build::find_or_fail(build).await?.state, "receiving", "not yet"); + let kept: Option = + db::query!("SELECT COUNT(*) FROM deferred_webhooks WHERE installation_id = '7'").scalar().await?; + assert!(kept.unwrap_or(0) >= 2, "{kept:?}"); + let status = app.get("/status").await.json().clone(); + assert!(status["oldest_deferred_webhook_seconds"].as_i64().is_some(), "{status}"); + + // Still over the limit: the drain keeps them + let drained = app::forge::deliveries::drain(&github_app(), &limits()).await?; + assert_eq!(drained.processed, 0, "{drained:?}"); + // The limit allows more again: they're acted on, the failed run's build closed + laravel::rate_limit::clear("webhooks:github:7").await?; + let drained = app::forge::deliveries::drain(&github_app(), &limits()).await?; + assert!(drained.processed >= 2, "{drained:?}"); + assert_eq!(app::models::Build::find_or_fail(build).await?.state, "failed"); + events.assert_dispatched_where::(|e| e.build_id == build); + let left: Option = db::query!("SELECT COUNT(*) FROM deferred_webhooks").scalar().await?; + assert_eq!(left, Some(0)); + + let huge = format!("{{\"pad\":\"{}\"}}", "x".repeat(26 * 1024 * 1024)); + let s = signature(&huge); + let r = send(&app, "push", huge, Some(s)).await; + assert_eq!(r.status().as_u16(), 413, "{}", r.status()); + Ok(()) +} + +fn tight_store() -> Application { + app::testing::configure() + .with_envs([ + ("VISUALCI_GITHUB_WEBHOOK_SECRET", SECRET.to_string()), + ("VISUALCI_GITHUB_APP_ID", "1".to_string()), + ("VISUALCI_GITHUB_APP_PRIVATE_KEY_BASE64", app_key().to_string()), + ("VISUALCI_GITHUB_WEBHOOKS_PER_INSTALLATION", "1".to_string()), + ("VISUALCI_GITHUB_WEBHOOKS_DEFERRED_PER_INSTALLATION_MB", "1".to_string()), + ("VISUALCI_GITHUB_WEBHOOKS_DEFERRED_TOTAL_MB", "2".to_string()), + ]) + .create() +} + +/// What's kept for later is capped per installation and in total: past a cap a claimed delivery is refused with a 503 +/// (GitHub logs it as failed, so the redelivery check sends it again), never answered 202 and lost, and the store stays +/// within the cap. +#[laravel::test(app = tight_store)] +async fn the_deliveries_kept_for_later_stay_within_their_caps(app: Application) -> laravel::Result<()> { + claimed_installation().await?; + let _events = laravel::event::fake(); + let pad = "x".repeat(300 * 1024); + let mut outcomes = std::collections::BTreeMap::::new(); + for n in 0..8 { + let push = json!({ "ref": "refs/heads/main", "installation": { "id": 7 }, "pad": pad, + "repository": { "id": 42, "full_name": "acme/web" } }); + let body = push.to_string(); + let s = signature(&body); + let r = app + .post("/webhooks/github") + .header("x-github-event", "push") + .header("x-github-delivery", format!("pad-{n}")) + .header("x-hub-signature-256", s) + .header("content-type", "application/json") + .body(body) + .await; + let key = r.json().as_object().and_then(|o| o.keys().next().cloned()).unwrap_or_default(); + *outcomes.entry(format!("{} {key}", r.status().as_u16())).or_default() += 1; + } + assert!(outcomes.contains_key("202 deferred"), "{outcomes:?}"); + assert!(outcomes.contains_key("503 refused"), "{outcomes:?}"); + assert!(!outcomes.keys().any(|k| k.contains("dropped")), "{outcomes:?}"); + let kept: Option = + db::query!("SELECT COALESCE(SUM(bytes), 0)::BIGINT FROM deferred_webhooks").scalar().await?; + assert!(kept.unwrap_or(0) <= 1024 * 1024, "{kept:?} bytes kept for one installation"); + Ok(()) +} + +/// The ten-minute check redelivers a claimed installation's failed delivery once, and leaves alone an unclaimed one's, +/// one that succeeded on a later attempt, and one older than its window. +#[laravel::test(app = limited)] +async fn failed_deliveries_of_claimed_installations_are_redelivered_once(_app: Application) -> laravel::Result<()> { + claimed_installation().await?; + let now = laravel::now().timestamp(); + let at = |minutes: i64| { + laravel::time::Timestamp::from_second(now.as_second() - minutes * 60).expect("a time").to_string() + }; + let page_one = json!([ + { "id": 11, "guid": "claimed-failed", "delivered_at": at(5), "status_code": 503, "installation_id": 7, "event": "workflow_run" }, + { "id": 12, "guid": "unclaimed-failed", "delivered_at": at(6), "status_code": 0, "installation_id": 999, "event": "push" }, + { "id": 13, "guid": "retried-ok", "delivered_at": at(7), "status_code": 200, "installation_id": 7, "event": "push" }, + ]); + let page_two = json!([ + { "id": 9, "guid": "retried-ok", "delivered_at": at(9), "status_code": 502, "installation_id": 7, "event": "push" }, + { "id": 8, "guid": "too-old", "delivered_at": at(60 * 30), "status_code": 500, "installation_id": 7, "event": "push" }, + ]); + let github = client::fake() + .with("api.github.com/app/hook/deliveries/*/attempts", client::response().status(202).json(json!({}))) + .with("api.github.com/app/hook/deliveries*", move |r: &client::Request| { + if r.url().contains("cursor=two") { + client::response().json(page_two.clone()) + } else { + client::response() + .header( + "link", + "; rel=\"next\"", + ) + .json(page_one.clone()) + } + }); + let first = app::forge::deliveries::redeliver_failed(&github_app(), 10).await?; + assert_eq!(first.redelivered, 1, "{first:?}"); + assert!(!first.partial, "read back to the window's start"); + let pages = |g: &client::HttpFake| g.sent().iter().filter(|r| !r.url().ends_with("/attempts")).count(); + assert_eq!(pages(&github), 2); + let posted: Vec = + github.sent().iter().filter(|r| r.url().ends_with("/attempts")).map(|r| r.url().to_string()).collect(); + assert_eq!(posted, vec!["https://api.github.com/app/hook/deliveries/11/attempts".to_string()]); + // Again: the newest page reaches the last run's mark at once, so it reads one page and redelivers nothing + let second = app::forge::deliveries::redeliver_failed(&github_app(), 10).await?; + assert_eq!(second.redelivered, 0, "{second:?}"); + assert_eq!((second.read, second.partial), (0, false), "{second:?}"); + assert_eq!(pages(&github), 3, "one page, back to the mark"); + assert_eq!(github.sent().iter().filter(|r| r.url().ends_with("/attempts")).count(), 1); + Ok(()) +} + +/// The same delivery twice from an unclaimed installation that lists a repository a project already links (installed +/// again on a new account) still attaches it: the onboarding path is unchanged. +#[laravel::test(app = limited)] +async fn an_unclaimed_installation_still_attaches_projects_that_link_its_repositories( + app: Application, +) -> laravel::Result<()> { + let project = claimed_installation().await?; + db::query!("UPDATE projects SET forge_installation = NULL WHERE id = {project}").update().await?; + let jobs = laravel::queue::fake(); + let _github = client::fake().with("api.github.com/app/installations/8", json!({ "id": 8 })); + let account = json!({ "id": 5005, "login": "acme", "type": "Organization" }); + let created = json!({ "action": "created", "installation": { "id": 8, "account": account }, + "repositories": [{ "id": 42, "full_name": "acme/web" }] }); + deliver(&app, "installation", &created).await.assert_ok().assert_json_path("linked", 1); + let installation: Option> = + db::query!("SELECT forge_installation FROM projects WHERE id = {project}").scalar().await?; + assert_eq!(installation.flatten().as_deref(), Some("8")); + jobs.assert_pushed_times::(1); + Ok(()) +} + +fn register(app: &Application, path: &str) -> laravel::testing::TestRequest { + app.post(path).json(json!({ + "client_name": "Flood", "redirect_uris": ["http://127.0.0.1:3000/callback"], + "token_endpoint_auth_method": "none", "grant_types": ["authorization_code"], "response_types": ["code"], + })) +} + +/// Anonymous OAuth client registrations: a few an hour from one address, with or without a trailing slash. +#[laravel::test(app = limited)] +async fn oauth_registrations_are_limited_per_address_with_or_without_a_trailing_slash( + app: Application, +) -> laravel::Result<()> { + let mut statuses = Vec::new(); + for path in ["/oauth/register", "/oauth/register/", "/oauth/register", "/oauth/register/", "/OAUTH/register//"] { + statuses.push(register(&app, path).await.status().as_u16()); + } + let created = statuses.iter().filter(|s| (200..300).contains(*s)).count(); + assert!(created <= 3, "3 a day from one address, whatever the path's spelling: {statuses:?}"); + assert!(statuses.contains(&429), "{statuses:?}"); + let r = register(&app, "/oauth/register/").await; + assert!(!r.status().is_success(), "{}", r.status()); + assert!(app::http::hosts::serves(app::http::hosts::Host::Mcp, "/oauth/register/")); + assert!(!app::http::hosts::serves(app::http::hosts::Host::App, "/oauth/register/")); + // An IPv6 host counts by its /64 + let a: std::net::IpAddr = "2001:db8:1:2:aaaa::1".parse().unwrap(); + let b: std::net::IpAddr = "2001:db8:1:2:bbbb::2".parse().unwrap(); + let (a, b) = (app::auth::oauth::registration_addresses(a), app::auth::oauth::registration_addresses(b)); + assert_eq!(a, b); + assert_eq!(a, vec!["2001:db8:1:2::/64".to_string(), "2001:db8:1::/48".to_string()]); + assert_eq!( + app::auth::oauth::registration_addresses("203.0.113.9".parse().unwrap()), + vec!["203.0.113.9".to_string()] + ); + Ok(()) +} + +fn few_unused_clients() -> Application { + app::testing::configure() + .with_envs([ + ("VISUALCI_OAUTH_REGISTRATIONS_PER_ADDRESS", "100"), + ("VISUALCI_OAUTH_UNUSED_CLIENTS", "3"), + ("VISUALCI_OAUTH_UNUSED_CLIENTS_CEILING", "1000"), + ]) + .create() +} + +/// Clients that never connect are capped: a registration past the cap deletes the oldest unused one older than a day, +/// and is refused while every unused one is newer than that (a 2-hour-old one stays). +#[laravel::test(app = few_unused_clients)] +async fn unused_oauth_clients_are_capped_by_deleting_the_oldest(app: Application) -> laravel::Result<()> { + for _ in 0..3 { + assert!(register(&app, "/oauth/register").await.status().is_success()); + } + register(&app, "/oauth/register").await.assert_status(429); + assert_eq!(count("oauth_clients").await?, 3); + let oldest: Option = + db::query!("SELECT client_key FROM oauth_clients ORDER BY created_at LIMIT 1").scalar().await?; + let oldest = oldest.unwrap(); + // Two hours old: someone may still be signing up or installing the App, so it stays, and the registration waits + db::query!("UPDATE oauth_clients SET created_at = created_at - 7200000000 WHERE client_key = {oldest}") + .update() + .await?; + register(&app, "/oauth/register").await.assert_status(429); + assert_eq!(count("oauth_clients").await?, 3); + // Over a day old: it makes room + db::query!("UPDATE oauth_clients SET created_at = created_at - 86400000000 WHERE client_key = {oldest}") + .update() + .await?; + assert!(register(&app, "/oauth/register").await.status().is_success()); + assert_eq!(count("oauth_clients").await?, 3); + let gone: Option = + db::query!("SELECT NOT EXISTS (SELECT 1 FROM oauth_clients WHERE client_key = {oldest})").scalar().await?; + assert_eq!(gone, Some(true), "the oldest unused client made room"); + Ok(()) +} + +/// Counts that can't be read never let a delivery through: claimed ones are kept for later, unclaimed ones dropped. +#[test] +fn uncounted_deliveries_are_never_accepted() { + use app::forge::webhooks::{Admission, Claim, when_uncounted}; + for claim in [Claim::Unclaimed, Claim::Free, Claim::Paid] { + assert_eq!(when_uncounted(claim), Admission::Over, "{claim:?}"); + } +} + +fn free_with_a_small_total() -> Application { + app::testing::configure() + .with_envs([("VISUALCI_GITHUB_WEBHOOKS_PER_FREE_INSTALLATION", "2"), ("VISUALCI_GITHUB_WEBHOOKS_TOTAL", "1")]) + .create() +} + +/// A free installation's delivery its own count allows but the shared one refuses gets its own count back, so the +/// refusal costs it nothing; a paid installation counts against nothing shared. +#[laravel::test(app = free_with_a_small_total)] +async fn a_refused_delivery_gives_its_counts_back(_app: Application) -> laravel::Result<()> { + use app::forge::webhooks::{Admission, Claim, admit}; + let limits = limits(); + assert_eq!(admit(&limits, "push", Some("7"), Claim::Free).await, Admission::Accepted); + // The shared count is used up: refused, and installation 7's second count given back + assert_eq!(admit(&limits, "push", Some("7"), Claim::Free).await, Admission::Over); + laravel::rate_limit::clear("webhooks:github").await?; + assert_eq!(admit(&limits, "push", Some("7"), Claim::Free).await, Admission::Accepted, "its count was given back"); + // Paid: the shared count doesn't apply + assert_eq!(admit(&limits, "push", Some("8"), Claim::Paid).await, Admission::Accepted); + assert_eq!(admit(&limits, "push", Some("8"), Claim::Paid).await, Admission::Accepted); + Ok(()) +} + +fn one_a_minute() -> Application { + app::testing::configure() + .with_envs([ + ("VISUALCI_GITHUB_WEBHOOK_SECRET", SECRET.to_string()), + ("VISUALCI_GITHUB_APP_ID", "1".to_string()), + ("VISUALCI_GITHUB_APP_PRIVATE_KEY_BASE64", app_key().to_string()), + ("VISUALCI_GITHUB_WEBHOOKS_PER_INSTALLATION", "1".to_string()), + ]) + .create() +} + +fn pull_request(action: &str) -> serde_json::Value { + json!({ "action": action, "installation": { "id": 7 }, "repository": { "id": 42, "full_name": "acme/web" }, + "pull_request": { "merged": false, "head": { "ref": "feature", "repo": { "full_name": "acme/web" } } } }) +} + +/// While an installation has deliveries kept for later, its new ones are kept behind them, even when its limit allows +/// them again: a pull request closed (kept) and then reopened is acted on in that order. Two drains at once act on +/// each delivery once. +#[laravel::test(app = one_a_minute)] +async fn kept_deliveries_are_acted_on_in_order_and_once(app: Application) -> laravel::Result<()> { + use app::forge::events::{BranchClosed, BranchReopened}; + claimed_installation().await?; + let events = laravel::event::fake(); + // The drain runs when the test says, not inline as tests' queue would run it + let _jobs = laravel::queue::fake(); + let push = json!({ "ref": "refs/heads/main", "installation": { "id": 7 }, "repository": { "id": 42, "full_name": "acme/web" } }); + deliver(&app, "push", &push).await.assert_ok(); + deliver(&app, "pull_request", &pull_request("closed")).await.assert_status(202); + laravel::rate_limit::clear("webhooks:github:7").await?; + // Its limit allows one now, but the closed one is waiting: the reopened one waits behind it + deliver(&app, "pull_request", &pull_request("reopened")).await.assert_status(202); + events.assert_not_dispatched::(); + events.assert_not_dispatched::(); + let kinds: Vec = db::query!("SELECT payload::jsonb->>'action' AS a FROM deferred_webhooks ORDER BY id") + .select() + .await? + .iter() + .map(|r| r.try_get("a")) + .collect::>()?; + assert_eq!(kinds, vec!["closed".to_string(), "reopened".to_string()]); + + laravel::rate_limit::clear("webhooks:github:7").await?; + let unlimited = app::config::Limits { webhooks_per_installation: 1000, ..limits() }; + let github = github_app(); + let (a, b) = tokio::join!( + app::forge::deliveries::drain(&github, &unlimited), + app::forge::deliveries::drain(&github, &unlimited) + ); + let (a, b) = (a?, b?); + assert_eq!(a.processed + b.processed, 2, "{a:?} {b:?}"); + events.assert_dispatched_times::(1); + events.assert_dispatched_times::(1); + assert_eq!(count_deferred().await?, 0); + Ok(()) +} + +async fn count_deferred() -> laravel::Result { + Ok(db::query!("SELECT COUNT(*) FROM deferred_webhooks").scalar::().await?.unwrap_or(0)) +} + +/// A claimed installation's delivery sent twice (GitHub redelivering one that ran past its 10-second wait) is acted on +/// once. +#[laravel::test(app = limited)] +async fn a_delivery_sent_twice_is_acted_on_once(app: Application) -> laravel::Result<()> { + use app::forge::events::BranchClosed; + claimed_installation().await?; + let events = laravel::event::fake(); + let body = pull_request("closed").to_string(); + let s = signature(&body); + let send_it = || { + app.post("/webhooks/github") + .header("x-github-event", "pull_request") + .header("x-github-delivery", "same-guid") + .header("x-hub-signature-256", s.clone()) + .header("content-type", "application/json") + .body(body.clone()) + }; + send_it().await.assert_ok().assert_json_path("dispatched", 1); + send_it().await.assert_ok().assert_json_path("duplicate", "acted on already"); + events.assert_dispatched_times::(1); + Ok(()) +} + +/// A redelivery GitHub refuses is recorded and the run goes on to the next; it's asked for again once its backoff has +/// passed. +#[laravel::test(app = limited)] +async fn a_refused_redelivery_is_recorded_and_the_run_goes_on(_app: Application) -> laravel::Result<()> { + use app::forge::deliveries::redeliver_failed; + claimed_installation().await?; + let at = laravel::time::Timestamp::from_second(laravel::now().timestamp().as_second() - 60).unwrap().to_string(); + let log = json!([ + { "id": 22, "guid": "second", "delivered_at": at, "status_code": 500, "installation_id": 7 }, + { "id": 21, "guid": "first", "delivered_at": at, "status_code": 500, "installation_id": 7 }, + ]); + let refuse = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true)); + let refusing = refuse.clone(); + let github = client::fake() + .with("api.github.com/app/hook/deliveries/21/attempts", move |_: &client::Request| { + if refusing.load(std::sync::atomic::Ordering::SeqCst) { 500 } else { 202 } + }) + .with("api.github.com/app/hook/deliveries/*/attempts", 202) + .with("api.github.com/app/hook/deliveries*", client::response().json(log)); + let run = redeliver_failed(&github_app(), 10).await?; + assert_eq!((run.redelivered, run.refused), (1, 1), "{run:?}"); + let error: Option> = + db::query!("SELECT error FROM webhook_redeliveries WHERE guid = 'first'").scalar().await?; + assert!(error.flatten().is_some_and(|e| e.contains("500"))); + // Backing off: not asked again yet + refuse.store(false, std::sync::atomic::Ordering::SeqCst); + let run = redeliver_failed(&github_app(), 10).await?; + assert_eq!((run.redelivered, run.waiting), (0, 0), "{run:?}"); + db::query!("UPDATE webhook_redeliveries SET next_at = now() WHERE guid = 'first'").update().await?; + let run = redeliver_failed(&github_app(), 10).await?; + assert_eq!(run.redelivered, 1, "{run:?}"); + assert_eq!(github.sent().iter().filter(|r| r.url().ends_with("/21/attempts")).count(), 2); + assert_eq!(github.sent().iter().filter(|r| r.url().ends_with("/22/attempts")).count(), 1); + Ok(()) +} + +fn minutes_ago(minutes: i64) -> String { + laravel::time::Timestamp::from_second(laravel::now().timestamp().as_second() - minutes * 60).unwrap().to_string() +} + +/// A 15-minute outage failed 40 of one customer's deliveries: all 40 are redelivered over the next runs (10 a run for +/// one installation), none skipped because the log's mark moved past them. +#[laravel::test(app = limited)] +async fn every_failed_delivery_is_redelivered_over_several_runs(_app: Application) -> laravel::Result<()> { + use app::forge::deliveries::{REDELIVERIES_PER_INSTALLATION, redeliver_failed}; + claimed_installation().await?; + let log: Vec = (1..=40) + .rev() + .map(|n| { + json!({ "id": 100 + n, "guid": format!("outage-{n}"), "delivered_at": minutes_ago(20 - n / 3), + "status_code": 503, "installation_id": 7 }) + }) + .collect(); + let github = client::fake() + .with("api.github.com/app/hook/deliveries/*/attempts", 202) + .with("api.github.com/app/hook/deliveries*", client::response().json(serde_json::Value::Array(log))); + let mut redelivered = 0; + for run in 1..=4 { + let r = redeliver_failed(&github_app(), 10).await?; + assert_eq!(r.redelivered, REDELIVERIES_PER_INSTALLATION, "run {run}: {r:?}"); + redelivered += r.redelivered; + } + assert_eq!(redelivered, 40); + let asked: std::collections::HashSet = + github.sent().iter().filter(|r| r.url().ends_with("/attempts")).map(|r| r.url().to_string()).collect(); + assert_eq!(asked.len(), 40, "each once"); + let fifth = redeliver_failed(&github_app(), 10).await?; + assert_eq!(fifth.redelivered, 0, "{fifth:?}"); + Ok(()) +} + +/// A run that stops at its page cap goes on from where it stopped next time, and the mark moves only once the scan has +/// read everything back to the old one: failures on every page are found. +#[laravel::test(app = limited)] +async fn a_partial_run_goes_on_from_its_cursor(_app: Application) -> laravel::Result<()> { + use app::forge::deliveries::{health, redeliver_failed}; + claimed_installation().await?; + let page = |n: i64| { + json!([{ "id": 300 - n, "guid": format!("page-{n}"), "delivered_at": minutes_ago(n), "status_code": 500, + "installation_id": 7 }]) + }; + let github = client::fake().with("api.github.com/app/hook/deliveries/*/attempts", 202).with( + "api.github.com/app/hook/deliveries*", + move |r: &client::Request| { + let n: i64 = r + .url() + .split("cursor=") + .nth(1) + .and_then(|c| c.split('&').next()) + .and_then(|c| c.parse().ok()) + .unwrap_or(1); + let mut response = client::response().json(page(n)); + if n < 3 { + response = response.header( + "link", + &format!( + "; rel=\"next\"", + n + 1 + ), + ); + } + response + }, + ); + let first = redeliver_failed(&github_app(), 1).await?; + assert!(first.partial && health(&first).is_err(), "{first:?}"); + let second = redeliver_failed(&github_app(), 1).await?; + assert!(second.partial, "{second:?}"); + let third = redeliver_failed(&github_app(), 1).await?; + assert!(!third.partial && health(&third).is_ok(), "{third:?}"); + let listed: Vec = + github.sent().iter().filter(|r| !r.url().ends_with("/attempts")).map(|r| r.url().to_string()).collect(); + assert_eq!(listed.len(), 3, "each page once: {listed:?}"); + assert!(listed[1].contains("cursor=2") && listed[2].contains("cursor=3"), "{listed:?}"); + let found: Option = db::query!("SELECT COUNT(*) FROM webhook_redeliveries").scalar().await?; + assert_eq!(found, Some(3), "a failure from every page"); + let mark: Option> = + db::query!("SELECT delivery_id FROM webhook_redelivery_marks WHERE name = 'github'").scalar().await?; + assert_eq!(mark.flatten(), Some(299), "the newest the scan started from"); + Ok(()) +} + +/// A delivery that was redelivered but whose new attempt failed too is asked for again after a backoff, and given up +/// after `REDELIVERY_TRIES`. +#[laravel::test(app = limited)] +async fn a_redelivery_that_fails_again_is_retried_then_given_up(_app: Application) -> laravel::Result<()> { + use app::forge::deliveries::{REDELIVERY_TRIES, redeliver_failed}; + claimed_installation().await?; + let log = std::sync::Arc::new(std::sync::Mutex::new(vec![ + json!({ "id": 11, "guid": "again", "delivered_at": minutes_ago(5), "status_code": 503, "installation_id": 7 }), + ])); + let served = log.clone(); + let _github = client::fake() + .with("api.github.com/app/hook/deliveries/*/attempts", 202) + .with("api.github.com/app/hook/deliveries*", move |_: &client::Request| { + client::response().json(serde_json::Value::Array(served.lock().unwrap().clone())) + }); + assert_eq!(redeliver_failed(&github_app(), 10).await?.redelivered, 1); + for attempt in 2..=REDELIVERY_TRIES { + // Its redelivery failed too: a newer attempt in the log + log.lock().unwrap().insert( + 0, + json!({ "id": 100 + i64::from(attempt), "guid": "again", "delivered_at": minutes_ago(1), + "status_code": 503, "installation_id": 7, "redelivery": true }), + ); + let r = redeliver_failed(&github_app(), 10).await?; + assert_eq!(r.redelivered, 0, "backing off: {r:?}"); + let state: Option = + db::query!("SELECT state FROM webhook_redeliveries WHERE guid = 'again'").scalar().await?; + assert_eq!(state.as_deref(), Some("pending")); + db::query!("UPDATE webhook_redeliveries SET next_at = now() WHERE guid = 'again'").update().await?; + assert_eq!(redeliver_failed(&github_app(), 10).await?.redelivered, 1, "attempt {attempt}"); + } + log.lock().unwrap().insert( + 0, + json!({ "id": 900, "guid": "again", "delivered_at": minutes_ago(0), "status_code": 503, "installation_id": 7 }), + ); + let r = redeliver_failed(&github_app(), 10).await?; + assert_eq!(r.given_up, 1, "{r:?}"); + let state: Option = + db::query!("SELECT state FROM webhook_redeliveries WHERE guid = 'again'").scalar().await?; + assert_eq!(state.as_deref(), Some("given_up")); + Ok(()) +} + +/// A body that arrives slowly holds only the budget for what it has sent: many of them at once don't stop a normal +/// delivery being read. +#[laravel::test(app = limited)] +async fn slow_bodies_do_not_starve_a_normal_delivery(_app: Application) -> laravel::Result<()> { + use app::forge::webhooks::read_delivery_body; + use std::pin::Pin; + use std::task::{Context, Poll}; + /// A body that sends one small chunk, then nothing. + struct Dribble(bool); + impl laravel::stream::Stream for Dribble { + type Item = Result; + fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { + if self.0 { + Poll::Pending + } else { + self.0 = true; + Poll::Ready(Some(Ok(axum::body::Bytes::from_static(b"{\"a\":")))) + } + } + } + let declared = Some(25 * 1024 * 1024); + let slow: Vec<_> = (0..40) + .map(|_| { + let body = axum::body::Body::from_stream(Dribble(false)); + tokio::spawn(read_delivery_body(body, declared, false)) + }) + .collect(); + tokio::task::yield_now().await; + let normal = vec![b'x'; 2 * 1024 * 1024]; + let started = std::time::Instant::now(); + let read = read_delivery_body(axum::body::Body::from(normal), Some(2 * 1024 * 1024), false).await; + assert_eq!(read, Ok(2 * 1024 * 1024)); + assert!(started.elapsed() < std::time::Duration::from_secs(2), "{:?}", started.elapsed()); + for s in slow { + s.abort(); + } + Ok(()) +} + +/// Deliveries kept for two installations at once both go in, and the byte counters match what's kept. +#[laravel::test(app = limited)] +async fn defers_for_different_installations_count_their_bytes(_app: Application) -> laravel::Result<()> { + use app::forge::deliveries::defer; + use app::forge::webhooks::Claim; + let _jobs = laravel::queue::fake(); + let limits = limits(); + let (a, b) = tokio::join!( + defer(&limits, Claim::Paid, "71", "g-71", "push", b"{\"n\":71}"), + defer(&limits, Claim::Free, "72", "g-72", "push", b"{\"n\":7200}") + ); + assert_eq!((a?.0, b?.0), (202, 202)); + let rows = db::query!("SELECT scope, bytes FROM deferred_webhook_bytes ORDER BY scope").select().await?; + let counted: Vec<(String, i64)> = + rows.iter().map(|r| Ok((r.try_get("scope")?, r.try_get("bytes")?))).collect::>()?; + assert_eq!( + counted, + vec![("free".into(), 10), ("installation:71".into(), 8), ("installation:72".into(), 10), ("total".into(), 18)] + ); + Ok(()) +} + +/// A kept delivery is counted as an attempt when a drain takes it, so one that kills the worker each time is dropped +/// after its attempts instead of holding its installation for good. +#[laravel::test(app = limited)] +async fn a_delivery_that_keeps_killing_the_drain_is_dropped(_app: Application) -> laravel::Result<()> { + claimed_installation().await?; + let events = laravel::event::fake(); + let payload = pull_request("closed").to_string(); + // Taken five times by drains that never came back + db::query!( + "INSERT INTO deferred_webhooks (installation_id, delivery, kind, payload, bytes, paid, attempts) \ + VALUES ('7', 'killer', 'pull_request', {payload}, 10, true, 5)" + ) + .insert() + .await?; + let drained = app::forge::deliveries::drain(&github_app(), &limits()).await?; + assert_eq!((drained.processed, drained.failed), (0, 1), "{drained:?}"); + events.assert_not_dispatched::(); + assert_eq!(count_deferred().await?, 0); + Ok(()) +} + +/// Only the organization an installation is set up for decides its plan: a paid organization's project linked through +/// someone else's free installation doesn't make it paid. +#[laravel::test(app = limited)] +async fn only_the_organization_set_up_decides_the_plan(_app: Application) -> laravel::Result<()> { + use app::forge::webhooks::{Claim, claim}; + let project = claimed_installation().await?; + assert_eq!(claim("7").await?, Claim::Paid); + let free = app::testing::fixtures::organization("someone").await?; + let free_id = free.id; + db::query!( + "INSERT INTO github_installations (installation_id, account_id, account_login, account_type, organization_id) \ + VALUES ('9', '6006', 'someone', 'Organization', {free_id})" + ) + .insert() + .await?; + db::query!("UPDATE projects SET forge_installation = '9' WHERE id = {project}").update().await?; + assert_eq!(claim("9").await?, Claim::Free, "the paid organization's project linked through it doesn't lift it"); + assert_eq!(claim("10").await?, Claim::Unclaimed); + Ok(()) +} + +/// A claim left `processing` (its request cut off mid-way, its worker gone) is taken over by the next delivery of the +/// same GUID after the takeover time, and the delivery is acted on once; one being acted on right now gets a 409 (not a +/// 2xx, so GitHub's log keeps it for the redelivery check), never "duplicate". +#[laravel::test(app = limited)] +async fn an_abandoned_claim_is_taken_over_and_acted_on_once(app: Application) -> laravel::Result<()> { + use app::forge::events::BranchClosed; + claimed_installation().await?; + let events = laravel::event::fake(); + db::query!( + "INSERT INTO webhook_deliveries_seen (delivery, state, started_at) VALUES \ + ('abandoned', 'processing', now() - interval '3 minutes'), ('busy', 'processing', now())" + ) + .insert() + .await?; + let body = pull_request("closed").to_string(); + let s = signature(&body); + let send_it = |guid: &'static str| { + app.post("/webhooks/github") + .header("x-github-event", "pull_request") + .header("x-github-delivery", guid) + .header("x-hub-signature-256", s.clone()) + .header("content-type", "application/json") + .body(body.clone()) + }; + send_it("busy").await.assert_status(409); + events.assert_not_dispatched::(); + send_it("abandoned").await.assert_ok().assert_json_path("dispatched", 1); + send_it("abandoned").await.assert_ok().assert_json_path("duplicate", "acted on already"); + events.assert_dispatched_times::(1); + let state: Option = + db::query!("SELECT state FROM webhook_deliveries_seen WHERE delivery = 'abandoned'").scalar().await?; + assert_eq!(state.as_deref(), Some("done")); + Ok(()) +} + +/// Paid installations' failed deliveries are asked for first: 3,000 older ones of free installations don't hold up a +/// paid customer's. A free installation's 507 (its own store at its cap) isn't recorded at all. +#[laravel::test(app = limited)] +async fn a_paid_failure_is_redelivered_ahead_of_older_free_ones(_app: Application) -> laravel::Result<()> { + use app::forge::deliveries::redeliver_failed; + claimed_installation().await?; + db::query!( + "INSERT INTO webhook_redeliveries (guid, installation_id, paid, first_attempt_id, last_attempt_id) \ + SELECT 'free-' || n, (1000 + n / 100)::text, false, n, n FROM generate_series(1, 3000) n" + ) + .insert() + .await?; + let log = json!([ + { "id": 9001, "guid": "paid-fail", "delivered_at": minutes_ago(1), "status_code": 503, "installation_id": 7 }, + { "id": 9000, "guid": "full-store", "delivered_at": minutes_ago(1), "status_code": 507, "installation_id": 7 }, + ]); + let github = client::fake() + .with("api.github.com/app/hook/deliveries/*/attempts", 202) + .with("api.github.com/app/hook/deliveries*", client::response().json(log)); + redeliver_failed(&github_app(), 10).await?; + assert!( + github.sent().iter().any(|r| r.url().ends_with("/deliveries/9001/attempts")), + "the paid failure was asked for in this run" + ); + let full: Option = + db::query!("SELECT COUNT(*) FROM webhook_redeliveries WHERE guid = 'full-store'").scalar().await?; + assert_eq!(full, Some(0), "a 507 isn't recorded"); + Ok(()) +} + +/// One free installation can have at most 100 failed deliveries waiting; the rest are given up at once. +#[laravel::test(app = limited)] +async fn a_free_installation_has_at_most_a_hundred_waiting(_app: Application) -> laravel::Result<()> { + use app::forge::deliveries::{PENDING_PER_FREE_INSTALLATION, redeliver_failed}; + let org = app::testing::fixtures::organization("freebie").await?; + let org_id = org.id; + db::query!( + "INSERT INTO github_installations (installation_id, account_id, account_login, account_type, organization_id) \ + VALUES ('55', '5555', 'freebie', 'Organization', {org_id})" + ) + .insert() + .await?; + let log: Vec = (1..=150) + .rev() + .map(|n| { + json!({ "id": n, "guid": format!("f-{n}"), "delivered_at": minutes_ago(1), "status_code": 503, + "installation_id": 55 }) + }) + .collect(); + let _github = client::fake() + .with("api.github.com/app/hook/deliveries/*/attempts", 202) + .with("api.github.com/app/hook/deliveries*", client::response().json(serde_json::Value::Array(log))); + redeliver_failed(&github_app(), 10).await?; + let waiting: Option = db::query!( + "SELECT COUNT(*) FROM webhook_redeliveries WHERE installation_id = '55' AND state IN ('pending', 'redelivered')" + ) + .scalar() + .await?; + assert_eq!(waiting, Some(PENDING_PER_FREE_INSTALLATION)); + Ok(()) +} + +/// A saved cursor GitHub no longer takes: the run starts again from the newest page. +#[laravel::test(app = limited)] +async fn a_rejected_resume_cursor_starts_again_from_the_top(_app: Application) -> laravel::Result<()> { + use app::forge::deliveries::redeliver_failed; + claimed_installation().await?; + db::query!( + "INSERT INTO webhook_redelivery_marks (name, delivery_id, resume_cursor, resume_newest) \ + VALUES ('github', 10, 'expired', 50)" + ) + .insert() + .await?; + let github = client::fake() + .with("api.github.com/app/hook/deliveries/*/attempts", 202) + .with("api.github.com/app/hook/deliveries*", |r: &client::Request| { + if r.url().contains("cursor=expired") { + client::response().status(422).json(json!({ "message": "invalid cursor" })) + } else { + client::response().json(json!([ + { "id": 60, "guid": "late", "delivered_at": minutes_ago(1), "status_code": 500, "installation_id": 7 }, + ])) + } + }); + let run = redeliver_failed(&github_app(), 10).await?; + assert!(!run.partial, "{run:?}"); + assert_eq!(run.redelivered, 1, "{run:?}"); + assert!(github.sent().iter().any(|r| r.url().ends_with("/deliveries/60/attempts"))); + let state = + db::query!("SELECT delivery_id, resume_cursor FROM webhook_redelivery_marks").select_one().await?.unwrap(); + assert_eq!(state.try_get::>("delivery_id")?, Some(60)); + assert_eq!(state.try_get::>("resume_cursor")?, None); + Ok(()) +} + +fn register_for(app: &Application, redirect: &str) -> laravel::testing::TestRequest { + app.post("/oauth/register").json(json!({ + "client_name": "Connector", "redirect_uris": [redirect], + "token_endpoint_auth_method": "none", "grant_types": ["authorization_code"], "response_types": ["code"], + })) +} + +/// A known platform's callback host (claude.ai, whose users' connectors register from its shared addresses) gets far +/// more than the per-address limit from one address; made-up callback hosts from one address stop at the per-address +/// limit, and at the number of different hosts. +#[laravel::test] +async fn registrations_are_counted_per_address_and_redirect_host(app: Application) -> laravel::Result<()> { + for n in 1..=80 { + let r = register_for(&app, "https://claude.ai/api/mcp/auth_callback").await; + assert!(r.status().is_success(), "claude.ai registration {n}: {}", r.status()); + } + // Made-up hosts: 50 for one, then the address's 60 in all + for n in 1..=50 { + let r = register_for(&app, "https://made-up-1.example/cb").await; + assert!(r.status().is_success(), "made-up host registration {n}: {}", r.status()); + } + register_for(&app, "https://made-up-1.example/cb").await.assert_status(429); + for n in 1..=10 { + let r = register_for(&app, "https://made-up-2.example/cb").await; + assert!(r.status().is_success(), "second host registration {n}: {}", r.status()); + } + register_for(&app, "https://made-up-2.example/cb").await.assert_status(429); + assert_eq!(app::auth::oauth::redirect_host(br#"{"redirect_uris":["https://Claude.AI/cb"]}"#), "claude.ai"); + assert_eq!(app::auth::oauth::redirect_host(b"not json"), "-"); + Ok(()) +} + +fn many_per_address() -> Application { + app::testing::configure().with_envs([("VISUALCI_OAUTH_REGISTRATIONS_PER_ADDRESS", "1000")]).create() +} + +/// One address registers clients for at most 3 different (non-platform) redirect hosts a day. +#[laravel::test(app = many_per_address)] +async fn an_address_registers_for_at_most_three_redirect_hosts(app: Application) -> laravel::Result<()> { + for host in ["a.example", "b.example", "c.example"] { + assert!(register_for(&app, &format!("https://{host}/cb")).await.status().is_success(), "{host}"); + } + register_for(&app, "https://d.example/cb").await.assert_status(429); + assert!(register_for(&app, "https://a.example/cb").await.status().is_success(), "a host it already uses"); + assert!(register_for(&app, "https://claude.ai/cb").await.status().is_success(), "a platform's host isn't counted"); + Ok(()) +} + +fn tight_ceiling() -> Application { + app::testing::configure() + .with_envs([ + ("VISUALCI_OAUTH_REGISTRATIONS_PER_ADDRESS", "100"), + ("VISUALCI_OAUTH_UNUSED_CLIENTS", "2"), + ("VISUALCI_OAUTH_UNUSED_CLIENTS_CEILING", "3"), + ]) + .create() +} + +/// Past the ceiling, the oldest unused clients are deleted whatever their age, so young registrations can't keep the +/// table full for good. +#[laravel::test(app = tight_ceiling)] +async fn past_the_ceiling_the_oldest_unused_clients_go_whatever_their_age(app: Application) -> laravel::Result<()> { + let now = laravel::now().timestamp().as_second() * 1_000_000; + for n in 0..5i64 { + let (key, id, at) = (format!("young-{n}"), format!("young-{n}"), now - n * 1_000_000); + db::query!( + "INSERT INTO oauth_clients (client_key, client_id, registration, name, redirect_uris, created_at) \ + VALUES ({key}, {id}, 'dynamic', 'Young', '[]', {at})" + ) + .insert() + .await?; + } + // Five young clients, past the ceiling of 3: the three oldest go, then the cap of 2 has nothing old enough to free + register(&app, "/oauth/register").await.assert_status(429); + assert_eq!(count("oauth_clients").await?, 2); + let left: Vec = db::query!("SELECT client_key FROM oauth_clients ORDER BY client_key") + .select() + .await? + .iter() + .map(|r| r.try_get("client_key")) + .collect::>()?; + assert_eq!(left, vec!["young-0".to_string(), "young-1".to_string()], "the newest stay"); + Ok(()) +} + +#[test] +fn addresses_are_matched_against_cidr_ranges() { + use app::forge::webhooks::in_range; + assert!(in_range("192.30.252.10".parse().unwrap(), "192.30.252.0/22")); + assert!(!in_range("192.30.0.1".parse().unwrap(), "192.30.252.0/22")); + assert!(in_range("2a0a:a440::1".parse().unwrap(), "2a0a:a440::/29")); + assert!(!in_range("2a0a:a440::1".parse().unwrap(), "192.30.252.0/22")); + assert!(in_range("::ffff:192.30.252.10".parse().unwrap(), "192.30.252.0/22")); +} + +/// A claim taken over by another delivery isn't undone by the first one's late release: only the claim's owner may +/// let it go or finish it. +#[laravel::test(app = limited)] +async fn a_late_release_does_not_undo_a_takeover(_app: Application) -> laravel::Result<()> { + use app::forge::webhooks::{DeliveryClaim, claim_delivery, finish_delivery, release_delivery}; + db::query!( + "INSERT INTO webhook_deliveries_seen (delivery, owner, started_at) \ + VALUES ('taken', 'first-owner', now() - interval '3 minutes')" + ) + .insert() + .await?; + let DeliveryClaim::Claimed(second) = claim_delivery("taken").await? else { panic!("taken over") }; + assert_ne!(second, "first-owner"); + // The first one, back late, lets go and finishes: neither touches the takeover's claim + release_delivery("taken", "first-owner").await?; + finish_delivery("taken", "first-owner").await?; + let row = + db::query!("SELECT state, owner FROM webhook_deliveries_seen WHERE delivery = 'taken'").select_one().await?; + let row = row.expect("still claimed"); + assert_eq!(row.try_get::("state")?, "processing"); + assert_eq!(row.try_get::("owner")?, second); + assert_eq!(claim_delivery("taken").await?, DeliveryClaim::InProgress); + finish_delivery("taken", &second).await?; + assert_eq!(claim_delivery("taken").await?, DeliveryClaim::Done); + Ok(()) +} + +fn free_tight_store() -> Application { + app::testing::configure() + .with_envs([ + ("VISUALCI_GITHUB_WEBHOOK_SECRET", SECRET.to_string()), + ("VISUALCI_GITHUB_APP_ID", "1".to_string()), + ("VISUALCI_GITHUB_APP_PRIVATE_KEY_BASE64", app_key().to_string()), + ("VISUALCI_GITHUB_WEBHOOKS_PER_FREE_INSTALLATION", "1".to_string()), + ("VISUALCI_GITHUB_WEBHOOKS_DEFERRED_PER_FREE_INSTALLATION_MB", "1".to_string()), + ]) + .create() +} + +/// An installation set up for a free organization keeps its free limits, but when a paid organization has a project +/// linked through it, its deliveries past the store's cap answer 503 (redelivered), not 507, and its failures are asked +/// for first, without the free queue cap. +#[laravel::test(app = free_tight_store)] +async fn a_free_installation_with_a_paid_project_linked_is_still_redelivered(app: Application) -> laravel::Result<()> { + let project = claimed_installation().await?; + let free = app::testing::fixtures::organization("freeorg").await?; + let free_id = free.id; + db::query!( + "INSERT INTO github_installations (installation_id, account_id, account_login, account_type, organization_id) \ + VALUES ('9', '6006', 'freeorg', 'Organization', {free_id})" + ) + .insert() + .await?; + // acme (paid) links its project through installation 9, set up for the free organization + db::query!("UPDATE projects SET forge_installation = '9' WHERE id = {project}").update().await?; + assert_eq!(app::forge::webhooks::claim("9").await?, app::forge::webhooks::Claim::Free); + let _events = laravel::event::fake(); + let pad = "x".repeat(300 * 1024); + let mut statuses = std::collections::BTreeSet::new(); + for _ in 0..8 { + let push = json!({ "ref": "refs/heads/main", "installation": { "id": 9 }, "pad": pad, + "repository": { "id": 42, "full_name": "acme/web" } }); + statuses.insert(deliver(&app, "push", &push).await.status().as_u16()); + } + assert!(statuses.contains(&503), "{statuses:?}"); + assert!(!statuses.contains(&507), "{statuses:?}"); + + // Its failed deliveries are marked to be asked for first, without the free queue cap + let log: Vec = (1..=120) + .rev() + .map(|n| { + json!({ "id": n, "guid": format!("p-{n}"), "delivered_at": minutes_ago(1), "status_code": 503, + "installation_id": 9 }) + }) + .collect(); + let _github = client::fake() + .with("api.github.com/app/hook/deliveries/*/attempts", 202) + .with("api.github.com/app/hook/deliveries*", client::response().json(serde_json::Value::Array(log))); + app::forge::deliveries::redeliver_failed(&github_app(), 10).await?; + let row = db::query!( + "SELECT COUNT(*) FILTER (WHERE paid) AS first, COUNT(*) FILTER (WHERE state = 'given_up') AS given_up \ + FROM webhook_redeliveries WHERE installation_id = '9'" + ) + .select_one() + .await? + .expect("counts"); + assert_eq!(row.try_get::("first")?, 120); + assert_eq!(row.try_get::("given_up")?, 0); + Ok(()) +} diff --git a/app/tests/github_calls.rs b/app/tests/github_calls.rs new file mode 100644 index 00000000..c83c5255 --- /dev/null +++ b/app/tests/github_calls.rs @@ -0,0 +1,232 @@ +//! Every request handler makes a fixed number of GitHub calls, whatever the organization's size (sc-9124). The +//! application's HTTP client counts each request's calls (`forge::calls`): under `APP_ENV=testing` a request over its +//! budget answers 500 saying so, so a handler that loops over a GitHub list fails whichever test reaches it. Here: such +//! a handler fails, one within its budget doesn't, and the routes that read GitHub stay within theirs on fixtures sized +//! like a large organization (hundreds of repositories, paged). + +use app::forge::calls::{DEFAULT_BUDGET, SIGN_IN_BUDGET}; +use app::forge::github::{SIGN_IN_PAGES_PER_INSTALLATION, SIGN_IN_REPOSITORY_PAGES}; +use hmac::{Hmac, Mac}; +use laravel::auth::social::{self, Provider}; +use laravel::db; +use laravel::http::client; +use laravel::testing::prelude::*; +use sha2::Sha256; + +const SECRET: &str = "github-webhook-test"; + +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()) + }) +} + +/// A handler that pages through a GitHub list in the request, as `/github/setup` did before #153. +async fn pages_through_everything() -> laravel::Result { + let mut repositories = 0; + for page in 1..=10 { + let response = client::get(format!("https://api.github.com/installation/repositories?page={page}")).await?; + let body: serde_json::Value = response.json()?; + repositories += body["repositories"].as_array().map_or(0, Vec::len); + } + Ok(format!("{repositories} repositories")) +} + +/// A handler that makes a few calls, within the default budget. +async fn a_few_calls() -> laravel::Result { + for _ in 0..DEFAULT_BUDGET { + client::get("https://api.github.com/app").await?; + } + // Calls elsewhere don't count + client::get("https://example.com/").await?; + Ok("ok".into()) +} + +fn github() -> Application { + app::testing::configure() + .with_envs([ + ("VISUALCI_GITHUB_WEBHOOK_SECRET", SECRET), + ("VISUALCI_GITHUB_APP_ID", "1"), + ("VISUALCI_GITHUB_APP_PRIVATE_KEY_BASE64", app_key()), + ]) + .with_routing(|routing, _| { + routing.routes(|route| { + route.get("/test/pages-through-everything", pages_through_everything); + route.get("/test/a-few-calls", a_few_calls); + }); + }) + .create() +} + +#[laravel::test(app = github)] +async fn a_handler_that_loops_over_a_github_list_fails(app: Application) -> laravel::Result<()> { + let _github = client::fake().with("api.github.com/*", json!({ "repositories": [{ "id": 1 }] })); + let r = app.get("/test/pages-through-everything").await; + r.assert_status(500); + let text = r.text(); + assert!(text.contains("made 10 GitHub calls, over its budget of 5"), "{text}"); + + app.get("/test/a-few-calls").await.assert_ok().assert_see("ok"); + Ok(()) +} + +/// A page of `count` repositories numbered from `first`, for installation `owner`. +fn page_of(owner: &str, first: usize, count: usize) -> serde_json::Value { + let repositories: Vec = (first..first + count) + .map(|n| { + json!({ "id": 10_000_000 + n, "full_name": format!("{owner}/repo-{n}"), "private": true, + "permissions": { "admin": true, "maintain": true, "push": true, "pull": true } }) + }) + .collect(); + json!({ "repositories": repositories }) +} + +/// The `page` a request asked for. +fn page_asked(url: &str) -> usize { + url.split(['?', '&']).find_map(|p| p.strip_prefix("page=")).and_then(|p| p.parse().ok()).unwrap_or(1) +} + +/// A sign-in for someone in four large organizations (250, 5,000, 5,000 and 300 repositories through the App): a +/// fixed number of GitHub calls, the repositories listed up to the caps, and every installation recorded. +#[laravel::test(app = github)] +async fn a_sign_in_reaching_thousands_of_repositories_stays_within_its_budget(app: Application) -> laravel::Result<()> { + let sizes = [("acme", 250usize), ("huge", 5000), ("huger", 5000), ("late", 300)]; + let mut github = client::fake().with( + "api.github.com/user/emails*", + json!([{ "email": "ada@example.com", "primary": true, "verified": true }]), + ); + for (i, (owner, size)) in sizes.iter().enumerate() { + let (owner, size) = (owner.to_string(), *size); + github = github.with( + &format!("api.github.com/user/installations/{}/repositories*", i + 1), + move |r: &client::Request| { + let page = page_asked(r.url()); + let first = (page - 1) * 100; + page_of(&owner, first, size.saturating_sub(first).min(100)) + }, + ); + } + let installations: Vec = sizes + .iter() + .enumerate() + .map(|(i, (owner, _))| { + json!({ "id": i + 1, "account": { "id": 5000 + i, "login": owner, "type": "Organization" } }) + }) + .collect(); + let github = github.with("api.github.com/user/installations*", json!({ "installations": installations })); + let _social = social::fake().with( + Provider::GITHUB, + social::User::fake("gh-1").name("Ada").raw(json!({ "login": "ada" })).verified_email("ada@example.com"), + ); + + app.get("/auth/github/callback").await.assert_redirect(); + let calls = github.sent().len(); + assert!(calls <= SIGN_IN_BUDGET as usize, "{calls} GitHub calls"); + assert_eq!(calls, 2 + SIGN_IN_REPOSITORY_PAGES as usize, "every page of the cap used"); + let listed: Vec<(String, i64)> = db::query!( + "SELECT installation_id, COUNT(*) AS n FROM user_repositories GROUP BY installation_id ORDER BY installation_id" + ) + .select() + .await? + .iter() + .map(|r| Ok((r.try_get("installation_id")?, r.try_get("n")?))) + .collect::>()?; + let per = i64::from(SIGN_IN_PAGES_PER_INSTALLATION) * 100; + // 3 pages for acme, 10 for huge, the 7 left for huger, none for late + let left = (i64::from(SIGN_IN_REPOSITORY_PAGES) - 3 - i64::from(SIGN_IN_PAGES_PER_INSTALLATION)) * 100; + assert_eq!(listed, vec![("1".into(), 250), ("2".into(), per), ("3".into(), left)], "{listed:?}"); + let recorded: Option = db::query!("SELECT COUNT(*) FROM user_installations").scalar().await?; + assert_eq!(recorded, Some(4), "every installation recorded, repositories listed or not"); + Ok(()) +} + +/// An installation's delivery listing 300 repositories, some linked: one query for them all, and one GitHub call +/// (whether the installation exists) only because a project changes. +#[laravel::test(app = github)] +async fn an_installation_delivery_with_hundreds_of_repositories_makes_one_call( + app: Application, +) -> laravel::Result<()> { + let org = app::testing::fixtures::organization("acme").await?; + let org_id = org.id; + for n in 0..3 { + let (slug, url, id) = + (format!("p{n}"), format!("https://github.com/acme/repo-{n}"), (10_000_000 + n).to_string()); + db::query!( + "INSERT INTO projects (pid, organization_id, slug, name, forge, repository_url, repository_id, created_at, \ + updated_at) VALUES (gen_random_uuid(), {org_id}, {slug}, {slug}, 'github', {url}, {id}, now(), now())" + ) + .insert() + .await?; + } + let github = client::fake().with("api.github.com/app/installations/7", json!({ "id": 7 })); + let repositories: Vec = page_of("acme", 0, 300)["repositories"].as_array().unwrap().clone(); + let body = json!({ "action": "created", "installation": { "id": 7, "account": { "id": 5005, "login": "acme", + "type": "Organization" } }, "repositories": repositories }) + .to_string(); + let mut mac = Hmac::::new_from_slice(SECRET.as_bytes()).unwrap(); + mac.update(body.as_bytes()); + app.post("/webhooks/github") + .header("x-github-event", "installation") + .header("x-hub-signature-256", format!("sha256={}", hex::encode(mac.finalize().into_bytes()))) + .header("content-type", "application/json") + .body(body) + .await + .assert_ok() + .assert_json_path("linked", 3); + assert_eq!(github.sent().len(), 1); + Ok(()) +} + +fn github_app() -> app::config::GithubApp { + app::config::GithubApp { + app_id: Some("1".into()), + private_key_base64: Some(app_key().into()), + webhook_secret: None, + } +} + +/// Installation tokens are cached until five minutes before GitHub's expiry, so two calls within the hour mint one; +/// a 401 with the cached token forgets it, and the next call mints a new one. +#[laravel::test(app = github)] +async fn installation_tokens_are_cached_for_their_lifetime(_app: Application) -> laravel::Result<()> { + use app::forge::github_app::{installation_token, repository_path, token_refused}; + let expires = laravel::time::Timestamp::from_second(laravel::now().timestamp().as_second() + 3600) + .expect("a time") + .to_string(); + let minted = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let count = minted.clone(); + let github = client::fake() + .with("api.github.com/app/installations/7/access_tokens", move |_: &client::Request| { + let n = count.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1; + json!({ "token": format!("token-{n}"), "expires_at": expires }) + }) + .with("api.github.com/repositories/42", |r: &client::Request| { + if r.has_header("authorization", "Bearer token-1") { + client::response().status(401).json(json!({ "message": "Bad credentials" })) + } else { + client::response().json(json!({ "full_name": "acme/web" })) + } + }); + let first = installation_token(&github_app(), "7").await?; + let second = installation_token(&github_app(), "7").await?; + assert_eq!((first.as_str(), second.as_str()), ("token-1", "token-1")); + assert_eq!(minted.load(std::sync::atomic::Ordering::SeqCst), 1, "one token minted for two calls"); + let cached: Option = + db::query!("SELECT value FROM cache WHERE key LIKE '%github:installation-token:7'").scalar().await?; + assert!(cached.is_some_and(|v| !v.contains("token-1")), "cached encrypted"); + + // GitHub refuses it: forgotten, and the next call mints another + assert!(repository_path(&first, "42").await.is_err()); + let third = installation_token(&github_app(), "7").await?; + assert_eq!(third, "token-2"); + assert_eq!(repository_path(&third, "42").await?.as_deref(), Some("acme/web")); + token_refused("not-a-cached-token").await; + assert_eq!(installation_token(&github_app(), "7").await?, "token-2"); + assert_eq!(github.sent().iter().filter(|r| r.url().ends_with("/access_tokens")).count(), 2); + Ok(()) +} diff --git a/app/tests/installations.rs b/app/tests/installations.rs index 20d74c43..b6e3177a 100644 --- a/app/tests/installations.rs +++ b/app/tests/installations.rs @@ -51,7 +51,7 @@ async fn deliver(app: &Application, kind: &str, event: serde_json::Value) -> lar 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-github-delivery", laravel::str::uuid7().to_string()) .header("x-hub-signature-256", signature) .header("content-type", "application/json") .body(body) @@ -476,7 +476,7 @@ async fn three_hundred_repositories_set_up_in_a_few_calls_and_two_picked_make_tw assert_eq!(found["total"], 9, "repo-290 to repo-298: {found}"); assert_eq!(github.sent().len(), calls, "the picker made GitHub calls"); - let too_many: Vec = (1..=51).map(|n| (1000 + n).to_string()).collect(); + let too_many: Vec = (1..=501).map(|n| (1000 + n).to_string()).collect(); ui(&app, &ada, "POST", path, Some(json!({ "repository_ids": too_many }))).await.assert_status(422); let pick = ui(&app, &ada, "POST", path, Some(json!({ "repository_ids": ["42", "44"] }))).await; pick.assert_ok().assert_json_path("total", 2); @@ -626,3 +626,263 @@ async fn two_installations_each_get_their_own_picker(app: Application) -> larave assert_eq!(none["total"], 0, "her own installation's repositories aren't Acme's"); Ok(()) } + +/// GitHub for linking any of Acme's 300 repositories (`three_hundred`): the App installed (7), Ada an admin of each. +fn acme_three_hundred() -> client::HttpFake { + let by_id: std::collections::HashMap = three_hundred() + .into_iter() + .map(|r| (r.repository.id.clone().expect("an ID"), r.repository.path.clone())) + .collect(); + let by_name: std::collections::HashMap = + by_id.iter().map(|(k, v)| (v.clone(), k.clone())).collect(); + client::fake().with("api.github.com/*", move |r: &client::Request| -> client::FakeResponse { + let path = r.url().split_once("api.github.com").map_or("", |(_, p)| p).split('?').next().unwrap_or(""); + if path.ends_with("/access_tokens") { + return client::response().json(json!({ "token": "t" })); + } + if path == "/user/1001" { + return client::response().json(json!({ "id": 1001, "login": "ada" })); + } + if path.ends_with("/collaborators/ada/permission") { + return client::response().json(json!({ "role_name": "admin" })); + } + if path.ends_with("/collaborators/ada") { + return client::response().status(204); + } + if path.ends_with("/installation") { + return client::response().json(json!({ "id": 7 })); + } + if let Some(id) = path.strip_prefix("/repositories/") { + return match by_id.get(id) { + Some(name) => client::response().json(json!({ "full_name": name })), + None => client::response().status(404).json(json!({})), + }; + } + if let Some(name) = path.strip_prefix("/repos/") { + return match by_name.get(name) { + Some(id) => client::response() + .json(json!({ "id": id.parse::().unwrap(), "private": true, "license": null })), + None => client::response().status(404).json(json!({})), + }; + } + client::response().status(404).json(json!({})) + }) +} + +/// A large organization picks all 300 repositories at once: accepted, and the queued job makes them projects +/// `IMPORT_BATCH` at a time, each run queueing the next. +#[laravel::test(app = github)] +async fn three_hundred_picked_at_once_are_made_in_batches(app: Application) -> laravel::Result<()> { + use installations::{IMPORT_BATCH, ImportRepositories, import_batch}; + let (ada, _) = ada().await?; + remember(ada.id, &[installation("7", "5005", "acme", "Organization")], &three_hundred()).await?; + { + let _github = acme_all("7"); + installations::set_up(&github_app(), &ada, "7").await?; + } + let jobs = laravel::queue::fake(); + let ids: Vec = three_hundred().iter().map(|r| r.repository.id.clone().expect("an ID")).collect(); + let pick = ui(&app, &ada, "POST", "/api/ui/orgs/acme/repositories", Some(json!({ "repository_ids": ids }))).await; + pick.assert_ok().assert_json_path("total", 300); + jobs.assert_pushed_times::(1); + let id = pick.json()["id"].as_i64().unwrap(); + + let _github = acme_three_hundred(); + let mut runs = 0; + loop { + runs += 1; + let more = import_batch(id).await?; + let state = installations::import_state( + Organization::query().filter(Organization::slug.eq("acme")).first().await?.expect("acme").id, + id, + ) + .await?; + let done = state["linked"].as_array().map_or(0, Vec::len) + state["skipped"].as_array().map_or(0, Vec::len); + assert_eq!(done, (runs * IMPORT_BATCH).min(300), "run {runs}: {state}"); + if !more { + assert_eq!(state["finished"], true); + assert_eq!(state["linked"].as_array().map(Vec::len), Some(300), "{}", state["skipped"]); + break; + } + assert!(runs < 100, "it ends"); + } + assert_eq!(runs, 300 / IMPORT_BATCH); + Ok(()) +} + +/// The pick limits say when to try again: 500 repositories an hour for one person, 2,000 a day for an organization. +#[laravel::test(app = github)] +async fn past_the_pick_limits_the_refusal_says_when_to_try_again(app: Application) -> laravel::Result<()> { + let (ada, _) = ada().await?; + remember(ada.id, &[installation("7", "5005", "acme", "Organization")], &three_hundred()).await?; + { + let _github = acme_all("7"); + installations::set_up(&github_app(), &ada, "7").await?; + } + let org = Organization::query().filter(Organization::slug.eq("acme")).first().await?.expect("acme"); + let (org_id, ada_id) = (org.id, ada.id); + // Earlier picks: 450 of Ada's in the last hour (the oldest 40 minutes ago), and 1,700 of the organization's today + let many = |n: usize| serde_json::Value::Array(vec![json!({ "repository_id": "0" }); n]).to_string(); + for (n, ago, user) in + [(200, "40 minutes", Some(ada_id)), (250, "10 minutes", Some(ada_id)), (1250, "5 hours", None)] + { + let requested = many(n); + db::query!( + "INSERT INTO repository_imports (organization_id, user_id, requested, finished_at, created_at) \ + VALUES ({org_id}, {user}, {requested}::jsonb, now(), now() - {ago}::interval)" + ) + .insert() + .await?; + } + let _jobs = laravel::queue::fake(); + let ids: Vec = three_hundred().iter().take(60).map(|r| r.repository.id.clone().expect("an ID")).collect(); + let r = ui(&app, &ada, "POST", "/api/ui/orgs/acme/repositories", Some(json!({ "repository_ids": ids }))).await; + r.assert_status(429); + let text = r.text(); + let free: Option = + db::query!("SELECT to_char((now() - interval '40 minutes' + interval '1 hour') AT TIME ZONE 'UTC', 'HH24:MI')") + .scalar() + .await?; + assert!(text.contains("You've added 450 repositories in the last hour"), "{text}"); + assert!(text.contains(&format!("try again at {} UTC", free.unwrap())), "{text}"); + + // Within Ada's hour, but past the organization's day + let few: Vec = three_hundred().iter().take(40).map(|r| r.repository.id.clone().expect("an ID")).collect(); + db::query!("UPDATE repository_imports SET user_id = NULL WHERE created_at < now() - interval '30 minutes'") + .update() + .await?; + let older = many(300); + db::query!( + "INSERT INTO repository_imports (organization_id, user_id, requested, created_at) \ + VALUES ({org_id}, NULL, {older}::jsonb, now() - interval '2 hours')" + ) + .insert() + .await?; + let r = ui(&app, &ada, "POST", "/api/ui/orgs/acme/repositories", Some(json!({ "repository_ids": few }))).await; + r.assert_status(429); + let text = r.text(); + assert!(text.contains("This organization has added 2000 repositories in the last day"), "{text}"); + // When the oldest of today's picks leaves the day: tomorrow, unless it's just after midnight, so with its date + let expected: Option = db::query!( + "SELECT to_char(t, 'HH24:MI') || ' UTC' || CASE WHEN t::date <> (now() AT TIME ZONE 'UTC')::date \ + THEN to_char(t, ' \"on\" FMDD Mon') ELSE '' END \ + FROM (SELECT (now() - interval '5 hours' + interval '1 day') AT TIME ZONE 'UTC' AS t) x" + ) + .scalar() + .await?; + let expected = expected.unwrap(); + assert!(text.contains(&format!("try again at {expected}.")), "{text} / {expected}"); + Ok(()) +} + +/// For an installation the sign-in listed only part of (a large organization), the picker's search asks GitHub once +/// and finds a repository past the cap; for one listed completely, search stays in the database. Searches of GitHub +/// are limited per person. +#[laravel::test(app = github)] +async fn a_search_finds_a_repository_past_the_cap_on_github(app: Application) -> laravel::Result<()> { + use app::forge::Listing; + use installations::{SEARCHES_PER_MINUTE, remember_listings}; + let (ada, _) = ada().await?; + remember(ada.id, &[installation("7", "5005", "acme", "Organization")], &three_hundred()).await?; + { + let _github = acme_all("7"); + installations::set_up(&github_app(), &ada, "7").await?; + } + let listing = |total: i32| Listing { installation_id: "7".into(), listed: 300, total: Some(total) }; + let token = laravel::auth::social::Token { + access: "user-token".into(), + refresh: None, + expires_at: None, + scopes: Vec::new(), + }; + app::forge::github::remember_user_token(ada.id, &token).await; + let github = client::fake().with( + "api.github.com/search/repositories*", + json!({ "total_count": 1, "items": [{ "id": 777_001, "full_name": "acme/far-away", "private": true, + "archived": false, "owner": { "login": "acme" }, + "permissions": { "admin": true, "maintain": true, "push": true, "triage": true, "pull": true } }] }), + ); + let path = "/api/ui/orgs/acme/repositories"; + + // Listed completely: searching stays in the database + remember_listings(ada.id, &[listing(300)]).await?; + let r = ui(&app, &ada, "GET", &format!("{path}?q=far-away"), None).await; + r.assert_ok().assert_json_path("total", 0).assert_json_path("search", "local"); + assert_eq!(github.sent().len(), 0); + + // 300 of 1,500 listed: the search asks GitHub once, as Ada, and finds it + remember_listings(ada.id, &[listing(1500)]).await?; + let r = ui(&app, &ada, "GET", &format!("{path}?q=far-away"), None).await; + r.assert_ok().assert_json_path("search", "github").assert_json_path("total", 1); + assert_eq!(r.json()["repositories"][0]["full_name"], "acme/far-away"); + assert_eq!(r.json()["repositories"][0]["can_add"], true); + assert_eq!(r.json()["installations"][0]["listed"], 300); + assert_eq!(r.json()["installations"][0]["total"], 1500); + assert_eq!(github.sent().len(), 1); + let sent = &github.sent()[0]; + assert!(sent.has_header("authorization", "Bearer user-token"), "as Ada"); + let q = sent.url().to_string(); + assert!(q.contains("org%3Aacme") || q.contains("org:acme"), "{q}"); + // Browsing without a search makes no call + ui(&app, &ada, "GET", path, None).await.assert_ok().assert_json_path("search", "local"); + assert_eq!(github.sent().len(), 1); + + // At most SEARCHES_PER_MINUTE GitHub searches a minute for one person + for _ in 1..SEARCHES_PER_MINUTE { + ui(&app, &ada, "GET", &format!("{path}?q=far"), None).await.assert_ok().assert_json_path("search", "github"); + } + let r = ui(&app, &ada, "GET", &format!("{path}?q=far"), None).await; + r.assert_ok().assert_json_path("search", "rate_limited").assert_json_path("total", 1); + assert_eq!(github.sent().len(), SEARCHES_PER_MINUTE as usize); + Ok(()) +} + +/// Two picks at once can't each fit under a limit their sum passes: the limit is checked and the pick recorded under the +/// person's and the organization's locks. +#[laravel::test(app = github)] +async fn picks_made_at_once_share_the_limit(app: Application) -> laravel::Result<()> { + let (ada, _) = ada().await?; + remember(ada.id, &[installation("7", "5005", "acme", "Organization")], &three_hundred()).await?; + { + let _github = acme_all("7"); + installations::set_up(&github_app(), &ada, "7").await?; + } + let _jobs = laravel::queue::fake(); + let ids: Vec = three_hundred().iter().map(|r| r.repository.id.clone().expect("an ID")).collect(); + let path = "/api/ui/orgs/acme/repositories"; + let (a, b) = tokio::join!( + ui(&app, &ada, "POST", path, Some(json!({ "repository_ids": ids[..280].to_vec() }))), + ui(&app, &ada, "POST", path, Some(json!({ "repository_ids": ids[..260].to_vec() }))), + ); + let statuses = [a.status().as_u16(), b.status().as_u16()]; + assert_eq!(statuses.iter().filter(|s| **s == 200).count(), 1, "{statuses:?}: 280 + 260 is past 500 an hour"); + assert_eq!(statuses.iter().filter(|s| **s == 429).count(), 1, "{statuses:?}"); + let recorded: Option = + db::query!("SELECT COALESCE(SUM(jsonb_array_length(requested)), 0)::BIGINT FROM repository_imports") + .scalar() + .await?; + assert!(recorded.unwrap_or(0) <= installations::PICKS_PER_PERSON_PER_HOUR, "{recorded:?}"); + Ok(()) +} + +/// Signing out forgets the GitHub token kept from the sign-in for the picker's search. +#[laravel::test(app = github)] +async fn signing_out_forgets_the_kept_github_token(app: Application) -> laravel::Result<()> { + let (ada, _) = ada().await?; + let token = laravel::auth::social::Token { + access: "user-token".into(), + refresh: None, + expires_at: None, + scopes: Vec::new(), + }; + app::forge::github::remember_user_token(ada.id, &token).await; + assert_eq!(app::forge::github::user_token(ada.id).await.as_deref(), Some("user-token")); + app.post("/auth/logout") + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .header("accept", "application/json") + .await + .assert_ok(); + assert_eq!(app::forge::github::user_token(ada.id).await, None); + Ok(()) +} diff --git a/app/tests/webhooks.rs b/app/tests/webhooks.rs index 450cdda9..b32a12e7 100644 --- a/app/tests/webhooks.rs +++ b/app/tests/webhooks.rs @@ -51,7 +51,7 @@ async fn deliver(app: &Application, kind: &str, event: serde_json::Value) -> Tes 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-github-delivery", laravel::str::uuid7().to_string()) .header("x-hub-signature-256", signature) .header("content-type", "application/json") .body(body) diff --git a/docs/design.md b/docs/design.md index 60c0d840..e634cf3d 100644 --- a/docs/design.md +++ b/docs/design.md @@ -397,12 +397,68 @@ calls at most, so it answers at once even for an organization with hundreds of r project per repository inside the request ran past the 30 s limit on DocSpring's 255). It lands on the repository picker (`/{org}/repositories`), which reads `user_repositories`: every repository each person can reach through each installation, with their permission, as of their last GitHub sign-in (which lists them anyway), so it pages and -searches with no GitHub call. The repositories they pick (Maintain or Admin, not archived, at most 50 at a time) become +searches with no GitHub call. The repositories they pick (Maintain or Admin, not archived, at most 500 at a time) become a `repository_imports` row and a queued job (`ImportRepositories`) links them one by one through the usual link checks, saving progress after each; the picker shows it, and `/status` reports `stalled_repository_import_seconds`. Nothing becomes a project on its own: repositories added to an installation later wait in the picker too. The checklist (`install_github_app`, `add_to_ci`, `connect_agent`, `review_changes`) offers installations the person can reach that aren't set up yet (`POST /api/ui/installations/{id}/setup`). +**A public App: bounded work for strangers (sc-9144, sc-9124).** Anyone can install the GitHub App, so its webhook +must stay cheap when strangers' installations flood it. `/webhooks/github` refuses a missing or malformed +`X-Hub-Signature-256` before reading the body and a wrong one before parsing it, so neither touches the database; a +body holds a megabyte of a 100 MB per-process budget for each megabyte as it arrives, must arrive at 1 MB/s after 5 +seconds' grace, and requests from outside GitHub's hook addresses (`GET /meta`, read within five minutes of starting and hourly after; `/status` reports +`github_hook_addresses_seconds`) share an 8 MB budget of their own. A delivery's installation is +*unclaimed*, *free* (set up for an organization on the free plan, which anyone can make, or only linked to projects) or +*paid* (set up for an organization on a paid plan: only that organization decides). Deliveries are counted in the cache store (`VISUALCI_GITHUB_WEBHOOKS_*`): a paid installation against its own +count only (600 a minute), a free one against its own (120) and the shared total, an unclaimed one against its own (60), +all unclaimed together (600) and the total; a delivery refused by a later count gets the earlier ones back, and one +whose counts can't be read is never accepted outright. GitHub never redelivers on its own, so a claimed installation's +delivery over its limit is never refused: it's kept in `deferred_webhooks` (its signature already checked), and while +an installation has deliveries kept its new ones join them, so they're acted on in order by `DrainDeferredWebhooks` +(queued when one is kept, and every minute), at the allowed rate, each held for the run acting on it so two runs never +act on one twice (each hold counts as an attempt; 5 at most). What's kept is capped per installation (50 MB paid, 5 MB +free), for free installations together (50 MB) and in total (500 MB), counted in `deferred_webhook_bytes` so keeping +one locks only its installation's row; past a cap a paid installation's delivery is answered 503, which GitHub logs as +failed and the redelivery check sends again, and a free one's 507, which it doesn't. `/status` reports +`oldest_deferred_webhook_seconds`. Every ten minutes the App's delivery log (`GET /app/hook/deliveries`) is read back +to the last run's mark (a run stopping at its 100-page cap goes on from its cursor next time; the mark moves only once a +scan has reached the old one), and each failed delivery is recorded in `webhook_redeliveries`, which runs drain for +claimed installations: paid first, oldest first, 10 per installation and 50 a run. A free installation keeps at most +100 failed deliveries waiting (the rest are given up at once, with an error in the log), and its 507s (its own store +at its cap) aren't redelivered at all; an installation set up for a free organization but with a paid organization's +projects linked through it keeps its free limits, but answers 503 past its cap (redelivered), has its failures asked +for first and isn't held to the 100; one whose redelivery fails too is +asked for again with a doubling backoff and given up with an error after 5 tries. Its heartbeat +(`VISUALCI_WEBHOOK_REDELIVERY_HEARTBEAT_URL`) fails while runs stop at the cap. Claimed installations' deliveries are acted on once per `X-GitHub-Delivery` (`webhook_deliveries_seen`, +three days; claimed `processing` with a random owner token before it's acted on, `done` after, let go by its owner when that +fails, and taken over when a claim is still processing two minutes on (the drain acts on one for at most 90 s); another delivery of one being acted on gets a 409). An unclaimed installation's delivery over its limit is dropped with a 202 and logged; its `installation` +deliveries count only in the total, so a flood can't drop the one that lets someone set it up. Unclaimed installations' +membership changes recheck nobody, an installation delivery looks up all its repositories in one query and asks GitHub +whether the installation exists only when a project would change, so a stranger's deliveries queue no job, make no +GitHub call and write nothing but their installation's row. Membership changes queue people in `access_rechecks` for +one debounced `RecheckAccess` run (30 s after the last delivery, at most 2 minutes after the first); `/status` reports +`oldest_access_recheck_seconds`, and the hourly sync clears the queue too. Installation tokens are cached (encrypted) +until five minutes before GitHub's expiry and forgotten on a 401. + +Every request's GitHub calls are counted (`forge::calls`): a fixed budget per route (5, more for a sign-in, which reads +at most 20 pages of repositories and 10 per installation, and for linking a repository), logged per request, and under +`APP_ENV=testing` a request over budget answers 500, so a handler that loops over a GitHub list fails CI; queued jobs +count their own and stop at page caps. The picker answers each installation's `listed` and `total`; for an installation +the sign-in didn't list completely, its search asks GitHub once as the person (`search/repositories` scoped to the +account, with the GitHub token kept encrypted from their sign-in, which reaches only what both they and the App can; 30 +searches a minute per person) and records what it finds in `user_repositories`. Repository picks go up to 500 at once, +500 an hour per person and 2,000 a day per organization (checked and recorded under per-person and per-organization +locks; a refusal says when to try again), and `ImportRepositories` makes 20 projects a run, 15 s apart, while the +person is still an admin. Anonymous OAuth client registrations are limited per address +and redirect URI host (50 a day per IPv4 address or IPv6 /64 for one host, 60 across hosts and 3 different hosts per +address, three times the 60 per IPv6 /48); known platforms' callback hosts (`VISUALCI_OAUTH_PLATFORM_REDIRECT_HOSTS`: +claude.ai, claude.com, chatgpt.com), whose users register from the platform's shared addresses, get 2,000 a day per +address outside those limits and by a cap on clients that never connected +(100,000), past which the oldest over a day old are deleted, and a ceiling (150,000) past which the oldest go whatever +their age (`VISUALCI_OAUTH_UNUSED_CLIENTS*`); sign-ins are limited to 60 a minute per address; and `/status` reuses its +numbers for 10 seconds per process (never more than a minute old), and a failure for 2. + **GitLab.** GitLab is parked in app/ (sign-in and the bot's token are read, the rest of this is the design to finish). GitLab has no app installations, so VisualCI acts through a bot user on gitlab.com (`@visualci`, its personal access token in `VISUALCI_GITLAB_BOT_TOKEN`). A project's `forge_installation` is `bot` once the bot is a diff --git a/frontend/content/docs/self-hosting/environment-variables.md b/frontend/content/docs/self-hosting/environment-variables.md index 156abe06..92ce5acd 100644 --- a/frontend/content/docs/self-hosting/environment-variables.md +++ b/frontend/content/docs/self-hosting/environment-variables.md @@ -148,6 +148,29 @@ The server-sent event streams the build and project pages and the CLI's `--wait` | `VISUALCI_LIVE_MAX_STREAMS_PER_BUILD` | integer | `100` | The most streams following one build in one web process. | | `VISUALCI_LIVE_STREAM_SECONDS` | integer | `1800` | How long one stream lasts, in seconds. It then ends, and the browser or the CLI connects again, so access is checked again. | +## Abuse limits + +Limits on the work anyone on the internet can start: the GitHub App is public, so anyone can install it and send its webhook deliveries, and MCP clients register themselves with the OAuth server. Each count is shared by every web process (the cache store). A count fills at once and empties evenly: 60 a minute allows a burst of 60, then one a second. + +| Variable | Type | Default | Description | +| --- | --- | --- | --- | +| `VISUALCI_GITHUB_WEBHOOKS_PER_INSTALLATION` | integer | `600` | GitHub App deliveries a minute acted on at once for one installation set up for an organization on a paid plan (or linked to a project of one). Past it a delivery is kept and acted on later at this rate (GitHub never redelivers on its own). A paid installation's deliveries count against nothing shared. | +| `VISUALCI_GITHUB_WEBHOOKS_PER_FREE_INSTALLATION` | integer | `120` | The same for an installation set up for an organization on the free plan, which anyone can make. Its deliveries also count against `VISUALCI_GITHUB_WEBHOOKS_TOTAL`. | +| `VISUALCI_GITHUB_WEBHOOKS_PER_UNCLAIMED_INSTALLATION` | integer | `60` | GitHub App deliveries a minute for one installation nobody has set up. Past it a delivery is dropped (a 202, and a warning in the log): nothing of a customer's depends on it. Its `installation` deliveries (installed, suspended, removed), which setting it up needs, count only in `VISUALCI_GITHUB_WEBHOOKS_TOTAL`. | +| `VISUALCI_GITHUB_WEBHOOKS_UNCLAIMED_TOTAL` | integer | `600` | GitHub App deliveries a minute for all the installations nobody has set up, together, so many strangers' installations can't crowd out customers' deliveries. Dropped as above past it. | +| `VISUALCI_GITHUB_WEBHOOKS_TOTAL` | integer | `6000` | GitHub App deliveries a minute for unclaimed and free installations together (paid installations' don't count). A free installation's delivery past it is kept for later; an unclaimed one's dropped. | +| `VISUALCI_GITHUB_WEBHOOKS_DEFERRED_PER_INSTALLATION_MB` | integer | `50` | The most megabytes of deliveries kept for later for one paid installation. Past a cap, a delivery is answered 503 (GitHub logs it as failed, and the redelivery check sends it again later) with an error in the log. | +| `VISUALCI_GITHUB_WEBHOOKS_DEFERRED_PER_FREE_INSTALLATION_MB` | integer | `5` | The most megabytes kept for later for one free installation. | +| `VISUALCI_GITHUB_WEBHOOKS_DEFERRED_FREE_TOTAL_MB` | integer | `50` | The most megabytes kept for later for every free installation together, so free installations, which anyone can make, can't fill the store paid ones need. | +| `VISUALCI_GITHUB_WEBHOOKS_DEFERRED_TOTAL_MB` | integer | `500` | The most megabytes kept for later for every installation together. | +| `VISUALCI_OAUTH_REGISTRATIONS_PER_REDIRECT_HOST` | integer | `50` | OAuth client registrations (`/oauth/register`) a day from one address (an IPv6 address's /64, since one host gets a whole /64) for one redirect URI host. Hosted platforms (such as claude.ai's connectors) register their users' clients from shared addresses with their own callback host, so each gets a count of its own. | +| `VISUALCI_OAUTH_REGISTRATIONS_PER_ADDRESS` | integer | `60` | OAuth client registrations a day from one address (or IPv6 /64) across every redirect host that isn't a known platform's, and three times that from an IPv6 /48. | +| `VISUALCI_OAUTH_REDIRECT_HOSTS_PER_ADDRESS` | integer | `3` | How many different redirect hosts (other than known platforms') one address registers clients for in a day. | +| `VISUALCI_OAUTH_PLATFORM_REDIRECT_HOSTS` | comma-separated list | `claude.ai,claude.com,chatgpt.com` | Known platforms' callback hosts (a host or any subdomain of it): their users' MCP clients register from the platform's shared addresses, so each gets `VISUALCI_OAUTH_REGISTRATIONS_PER_PLATFORM_HOST` a day per address, outside the per-address limit. | +| `VISUALCI_OAUTH_REGISTRATIONS_PER_PLATFORM_HOST` | integer | `2000` | OAuth client registrations a day from one address for one known platform's callback host. | +| `VISUALCI_OAUTH_UNUSED_CLIENTS` | integer | `100000` | The most registered OAuth clients that have never connected. A registration past it first deletes the oldest of them registered over a day ago with no sign-in under way (a warning in the log), and is refused with a 429 while none is that old; `oauth:prune` deletes the rest after a week. | +| `VISUALCI_OAUTH_UNUSED_CLIENTS_CEILING` | integer | `150000` | Past this many clients that have never connected, the oldest are deleted whatever their age, so young registrations can't keep new ones out. | + ## Heartbeats Each scheduled job pushes its result to a [Gatus](https://gatus.io) external endpoint, so a run that failed, or no run at all, alerts. Each pair is the endpoint's URL and its token; a job without a URL pushes nothing. @@ -174,6 +197,8 @@ Each scheduled job pushes its result to a [Gatus](https://gatus.io) external end | `VISUALCI_GROUPS_CHECK_HEARTBEAT_TOKEN` | string | | Secret. The groups check's token. | | `VISUALCI_CREDIT_OVERRIDES_HEARTBEAT_URL` | string | | The daily reminder to organizations whose credit override ends within a week. | | `VISUALCI_CREDIT_OVERRIDES_HEARTBEAT_TOKEN` | string | | Secret. The credit override reminder's token. | +| `VISUALCI_WEBHOOK_REDELIVERY_HEARTBEAT_URL` | string | | The check for GitHub App deliveries that failed (every ten minutes), which asks GitHub to redeliver them. | +| `VISUALCI_WEBHOOK_REDELIVERY_HEARTBEAT_TOKEN` | string | | Secret. The redelivery check's token. | ## Laravel Rust