From bc50ec509fbbe7d151a7720fca112af63b09e21c Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 02:59:30 +1300 Subject: [PATCH 01/20] app/: staff pages for sign-ups and emails (sc-8900): the latest 100 sign-ups with how they heard about VisualCI, every email rendered with sample data, failed emails retried or dismissed; a 404 for anyone who isn't staff --- app/src/auth/mod.rs | 2 + app/src/auth/staff.rs | 130 ++++++++++++++++++++++++++++++++++++++++++ app/tests/staff.rs | 49 ++++++++++++++++ 3 files changed, 181 insertions(+) create mode 100644 app/src/auth/staff.rs create mode 100644 app/tests/staff.rs diff --git a/app/src/auth/mod.rs b/app/src/auth/mod.rs index 1f7ffc81..843d2983 100644 --- a/app/src/auth/mod.rs +++ b/app/src/auth/mod.rs @@ -16,6 +16,7 @@ pub mod oauth; pub mod orgs; pub mod setup; pub mod sign_in; +pub mod staff; pub mod tokens; use axum::extract::FromRequestParts; @@ -271,6 +272,7 @@ pub fn routes(route: &mut laravel::prelude::Router) { orgs::routes(route); me::routes(route); device::routes(route); + staff::routes(route); route.get("/auth/{forge}", sign_in::start); route.post("/auth/{forge}/link", sign_in::link); route.get("/auth/{forge}/callback", sign_in::callback); diff --git a/app/src/auth/staff.rs b/app/src/auth/staff.rs new file mode 100644 index 00000000..18b56f6a --- /dev/null +++ b/app/src/auth/staff.rs @@ -0,0 +1,130 @@ +//! Staff pages on the auth and emails side (sc-8900), ported from today's server: the latest sign-ups, every email +//! VisualCI sends rendered with sample data, and failed emails to retry or dismiss. Anyone who isn't staff gets a 404. + +use laravel::auth::Authenticated; +use laravel::db; +use laravel::prelude::*; +use serde_json::{Value, json}; + +use super::me::summary; +use crate::models::User; +use crate::notify::outbox::AppUrl; +use crate::notify::{About, DeliverEmails, render, render::samples}; + +pub fn routes(route: &mut Router) { + route.get("/api/ui/staff/signups", signups); + route.get("/api/ui/staff/emails", emails); + route.post("/api/ui/staff/emails/{id}/resolve", resolve); +} + +fn staff_only(user: &User) -> laravel::Result<()> { + if user.staff { Ok(()) } else { Err(laravel::abort(404)) } +} + +const TIME: &str = "YYYY-MM-DD\"T\"HH24:MI:SS\"Z\""; + +/// `GET /api/ui/staff/signups`: the latest 100 people, newest first, with how they heard about VisualCI. +pub async fn signups(Authenticated(user): Authenticated) -> laravel::Result> { + staff_only(&user)?; + let rows = db::query!( + "SELECT name, email, heard_about_source, heard_about_detail, \ + to_char(created_at AT TIME ZONE 'UTC', {TIME}) AS created_at, \ + (SELECT login FROM identities WHERE user_id = users.id ORDER BY id LIMIT 1) AS login \ + FROM users ORDER BY id DESC LIMIT 100" + ) + .select() + .await?; + let mut list = Vec::new(); + for r in rows { + let (source, detail): (Option, Option) = + (r.try_get("heard_about_source")?, r.try_get("heard_about_detail")?); + list.push(json!({ + "name": r.try_get::("name")?, "email": r.try_get::("email")?, + "login": r.try_get::>("login")?, "created_at": r.try_get::("created_at")?, + "heard_about": summary(source.as_deref(), detail.as_deref()), + })); + } + Ok(Json(json!({ "signups": list }))) +} + +/// `GET /api/ui/staff/emails`: every email rendered with sample data (for Acme), and the failed ones nobody has +/// retried or dismissed yet, newest first. +pub async fn emails( + Authenticated(user): Authenticated, + app: laravel::config::Section, +) -> laravel::Result> { + staff_only(&user)?; + let about = About { org_name: "Acme", org_slug: "acme", app_url: app.url.trim_end_matches('/') }; + let list: Vec = samples() + .into_iter() + .map(|(label, kind)| { + let r = render(&kind, &about); + json!({ + "label": label, "kind": kind.name(), "subject": r.subject, "text": r.text, "html": r.html, + "can_turn_off": kind.preference().is_some(), + }) + }) + .collect(); + let rows = db::query!( + "SELECT e.id, e.kind, e.recipient, e.attempts, e.last_error, o.slug AS org, \ + to_char(e.created_at AT TIME ZONE 'UTC', {TIME}) AS created_at, \ + to_char(e.updated_at AT TIME ZONE 'UTC', {TIME}) AS failed_at \ + FROM emails e LEFT JOIN organizations o ON o.id = e.organization_id \ + WHERE e.state = 'failed' AND e.dismissed_at IS NULL ORDER BY e.id DESC LIMIT 100" + ) + .select() + .await?; + let mut failed = Vec::new(); + for r in rows { + failed.push(json!({ + "id": r.try_get::("id")?, "kind": r.try_get::("kind")?, + "recipient": r.try_get::("recipient")?, "org": r.try_get::>("org")?, + "attempts": r.try_get::("attempts")?, "last_error": r.try_get::>("last_error")?, + "created_at": r.try_get::("created_at")?, "failed_at": r.try_get::("failed_at")?, + })); + } + Ok(Json(json!({ "emails": list, "failed": failed }))) +} + +#[laravel::input] +#[validate(authenticated)] +pub struct ResolveInput { + /// `retry` or `dismiss`. + #[validate(required)] + action: String, +} + +/// `POST /api/ui/staff/emails/{id}/resolve`: retry a failed email (sent again from scratch) or dismiss it. Either way +/// it stops counting in `/status`'s `emails_failed_unresolved`. 404 when there's no such failed, undismissed email. +pub async fn resolve( + Authenticated(user): Authenticated, + Params(id): Params, + Valid(p): Valid, +) -> laravel::Result> { + staff_only(&user)?; + let done: Option = match p.action.as_str() { + "retry" => { + db::query!( + "UPDATE emails SET state = 'pending', attempts = 0, claimed_at = NULL, updated_at = now() \ + WHERE id = {id} AND state = 'failed' AND dismissed_at IS NULL RETURNING id" + ) + .scalar() + .await? + } + "dismiss" => { + db::query!( + "UPDATE emails SET dismissed_at = now(), updated_at = now() \ + WHERE id = {id} AND state = 'failed' AND dismissed_at IS NULL RETURNING id" + ) + .scalar() + .await? + } + _ => return Err(laravel::abort_with(422, "action is retry or dismiss")), + }; + done.ok_or_else(|| laravel::abort(404))?; + tracing::info!(email_id = id, action = %p.action, staff = user.id, "staff resolved a failed email"); + if p.action == "retry" { + DeliverEmails.dispatch().await?; + } + Ok(Json(json!({ "id": id }))) +} diff --git a/app/tests/staff.rs b/app/tests/staff.rs new file mode 100644 index 00000000..11ee277b --- /dev/null +++ b/app/tests/staff.rs @@ -0,0 +1,49 @@ +//! Staff pages: the latest sign-ups, every email rendered, failed emails retried or dismissed; a 404 for anyone else. + +use app::models::User; +use laravel::db; +use laravel::model::create; +use laravel::testing::prelude::*; + +#[laravel::test] +async fn staff_see_sign_ups_and_emails_and_resolve_failures(app: Application) -> laravel::Result<()> { + let grace = + create!(User { pid: laravel::str::uuid7(), name: "Grace", email: "grace@example.com", staff: true }).await?; + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let ada_id = ada.id; + db::query!( + "UPDATE users SET heard_about_source = 'ai_assistant', heard_about_detail = 'Claude' WHERE id = {ada_id}" + ) + .update() + .await?; + for path in ["/api/ui/staff/signups", "/api/ui/staff/emails"] { + app.get(path).acting_as(&ada).await.assert_status(404); + } + app.get("/api/ui/staff/signups") + .acting_as(&grace) + .await + .assert_ok() + .assert_json_path("signups.0.name", "Ada") + .assert_json_path("signups.0.heard_about", "AI assistant: Claude"); + + let failed: i64 = db::query!( + "INSERT INTO emails (kind, dedupe_key, recipient, data, state, attempts, last_error) \ + VALUES ('welcome', 'w:1', 'ada@example.com', '[]', 'failed', 5, 'Postmark: HTTP 422') RETURNING id" + ) + .scalar() + .await? + .unwrap(); + let page = app.get("/api/ui/staff/emails").acting_as(&grace).await; + page.assert_ok().assert_json_path("failed.0.id", failed).assert_json_path("emails.0.kind", "credits_low"); + let resolve = |who: &User, action: &str| { + app.post(format!("/api/ui/staff/emails/{failed}/resolve")) + .acting_as(who) + .header("sec-fetch-site", "same-origin") + .json(json!({ "action": action })) + }; + resolve(&ada, "dismiss").await.assert_status(404); + resolve(&grace, "dismiss").await.assert_ok(); + resolve(&grace, "dismiss").await.assert_status(404); + app.get("/api/ui/staff/emails").acting_as(&grace).await.assert_json_path("failed", json!([])); + Ok(()) +} From 634349dbfb9dd2593b14f95f36a0cc2b12ffe689 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 03:43:31 +1300 Subject: [PATCH 02/20] app/: GitHub's webhook (sc-8900, forge): signed deliveries only (X-Hub-Signature-256, constant time); merges, closed and reopened pull requests (a fork's branch by its label), deleted branches and visibility changes dispatched to the domain once per linked project (by GitHub's repository ID, else URL) as forge::events; installations attach to and detach from linked projects (only from the installation being removed) and recheck their organizations' GitHub members; membership and team changes queue RecheckAccess, which asks the App for each person's permission on every linked repository and applies it as a sign-in does; the GitHub App client (JWT, installation tokens, collaborator permission) --- app/Cargo.toml | 2 + app/src/forge/github_app.rs | 128 ++++++++++++ app/src/forge/mod.rs | 2 + app/src/forge/webhooks.rs | 402 ++++++++++++++++++++++++++++++++++++ app/src/lib.rs | 1 + app/tests/webhooks.rs | 141 +++++++++++++ 6 files changed, 676 insertions(+) create mode 100644 app/src/forge/github_app.rs create mode 100644 app/src/forge/webhooks.rs create mode 100644 app/tests/webhooks.rs diff --git a/app/Cargo.toml b/app/Cargo.toml index dcabfa90..90e50911 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -26,10 +26,12 @@ path = "src/main.rs" laravel-rust = { version = "=0.1.4", features = ["database-postgres", "minijinja"] } # The same axum Laravel Rust runs on, for extractors (auth::Principal) axum = "0.8" +base64 = "0.22" hex = "0.4" oauth-provider = "0.1.3" oauth-provider-laravel = { version = "=0.1.1", features = ["postgres"] } hmac = "0.12" +jsonwebtoken = "9" serde = { version = "1", features = ["derive"] } serde_json = "1" sha2 = "0.10" diff --git a/app/src/forge/github_app.rs b/app/src/forge/github_app.rs new file mode 100644 index 00000000..e482103c --- /dev/null +++ b/app/src/forge/github_app.rs @@ -0,0 +1,128 @@ +//! The VisualCI GitHub App acting as itself (sc-8900, the forge side), ported from today's server: a JWT signed with +//! the App's private key, installation tokens, and a person's permission on a repository through an installation. +//! Its webhook is in `forge::webhooks`. + +use laravel::http::client; +use serde_json::Value; + +use super::Permission; + +const API: &str = "https://api.github.com"; + +/// The App (`GITHUB_APP_ID`, `GITHUB_APP_PRIVATE_KEY_BASE64`: its PEM key, base64-encoded to fit one line) and its +/// webhook's secret (`GITHUB_WEBHOOK_SECRET`). Without the secret, the webhook answers 404. +#[derive(Clone, laravel::config::Section)] +pub struct GithubApp { + #[env("GITHUB_APP_ID")] + pub app_id: Option, + #[env("GITHUB_APP_PRIVATE_KEY_BASE64")] + pub private_key_base64: Option, + #[env("GITHUB_WEBHOOK_SECRET")] + pub webhook_secret: Option, +} + +fn err(e: impl std::fmt::Display) -> laravel::Error { + laravel::Error::msg(format!("GitHub: {e}")) +} + +#[derive(serde::Serialize)] +struct AppClaims { + iat: i64, + exp: i64, + iss: String, +} + +/// A JWT that authenticates as the App itself, for nine minutes. +fn app_jwt(app: &GithubApp) -> laravel::Result { + use base64::Engine; + let (Some(id), Some(key)) = (app.app_id.as_deref(), app.private_key_base64.as_deref()) else { + return Err(err("the GitHub App isn't configured (GITHUB_APP_ID, GITHUB_APP_PRIVATE_KEY_BASE64)")); + }; + let now = laravel::now().timestamp().as_second(); + let claims = AppClaims { iat: now - 60, exp: now + 540, iss: id.to_string() }; + let pem = base64::engine::general_purpose::STANDARD + .decode(key.trim()) + .map_err(|e| err(format!("the App's private key isn't base64: {e}")))?; + let key = jsonwebtoken::EncodingKey::from_rsa_pem(&pem).map_err(err)?; + jsonwebtoken::encode(&jsonwebtoken::Header::new(jsonwebtoken::Algorithm::RS256), &claims, &key).map_err(err) +} + +/// GET a GitHub API path as JSON; `None` on 404. +async fn get(token: &str, path: &str) -> laravel::Result> { + let response = client::get(format!("{API}{path}")) + .token(token) + .header("accept", "application/vnd.github+json") + .header("user-agent", "visualci") + .await?; + if response.status() == 404 { + return Ok(None); + } + if !response.successful() { + return Err(err(format!("GET {path}: HTTP {}", response.status()))); + } + Ok(Some(response.json()?)) +} + +/// A token for one of the App's installations. +/// +/// # Errors +/// When the App isn't configured, or GitHub refuses its credentials. +pub async fn installation_token(app: &GithubApp, installation: &str) -> laravel::Result { + let response = client::post(format!("{API}/app/installations/{installation}/access_tokens")) + .token(app_jwt(app)?) + .header("accept", "application/vnd.github+json") + .header("user-agent", "visualci") + .await?; + if !response.successful() { + return Err(err(format!("installation token: HTTP {}", response.status()))); + } + let body: Value = response.json()?; + body["token"].as_str().map(str::to_string).ok_or_else(|| err("an installation token response without a token")) +} + +/// GitHub's role name for a collaborator (`admin`, `maintain`, `write`, `triage`, `read`). +fn permission_from(role: &str) -> Option { + match role { + "admin" => Some(Permission::Admin), + "maintain" => Some(Permission::Maintain), + "write" | "push" => Some(Permission::Write), + "triage" => Some(Permission::Triage), + "read" | "pull" => Some(Permission::Read), + _ => None, + } +} + +/// A person's permission on a repository (`owner/name`) through an installation (organization base permission, +/// teams and direct access all count), from their permanent GitHub ID. Only for collaborators: on a public repository +/// GitHub answers `read` for anyone, which would make every GitHub user a member of every organization linking one. +/// +/// # Errors +/// When GitHub can't be reached or refuses. +pub async fn permission( + app: &GithubApp, + repo: &str, + installation: &str, + user_id: &str, +) -> laravel::Result> { + let token = installation_token(app, installation).await?; + // The account's login now, from its permanent ID: a stored login may have been renamed and taken. + let Ok(id) = user_id.parse::() else { return Ok(None) }; + let Some(user) = get(&token, &format!("/user/{id}")).await? else { return Ok(None) }; + let Some(login) = user["login"].as_str() else { return Ok(None) }; + // 204 when they're a collaborator (directly, through a team, or by the organization's base permission), 404 not + let collaborator = client::get(format!("{API}/repos/{repo}/collaborators/{login}")) + .token(&token) + .header("accept", "application/vnd.github+json") + .header("user-agent", "visualci") + .await?; + match collaborator.status().as_u16() { + 204 | 200 => {} + 404 => return Ok(None), + s => return Err(err(format!("GET /repos/{repo}/collaborators/{login}: HTTP {s}"))), + } + let Some(v) = get(&token, &format!("/repos/{repo}/collaborators/{login}/permission")).await? else { + return Ok(None); + }; + // `role_name` says maintain and triage, which `permission` folds into write and read + Ok(v["role_name"].as_str().and_then(permission_from).or_else(|| v["permission"].as_str().and_then(permission_from))) +} diff --git a/app/src/forge/mod.rs b/app/src/forge/mod.rs index 2ac56e35..445cc127 100644 --- a/app/src/forge/mod.rs +++ b/app/src/forge/mod.rs @@ -5,6 +5,8 @@ pub mod events; pub mod github; pub mod gitlab; +pub mod github_app; +pub mod webhooks; use crate::auth::Role; diff --git a/app/src/forge/webhooks.rs b/app/src/forge/webhooks.rs new file mode 100644 index 00000000..1637fc87 --- /dev/null +++ b/app/src/forge/webhooks.rs @@ -0,0 +1,402 @@ +//! The GitHub App's webhook, `POST /webhooks/github` on the API host (sc-8900, the forge side), ported from today's +//! server. A delivery is checked against `X-Hub-Signature-256` and read into a [`ForgeEvent`]: +//! +//! - merges, closed or reopened pull requests, deleted branches and repository visibility changes are dispatched to +//! the domain as `forge::events`, once per linked project; +//! - installation changes attach or detach the App's installation on linked projects, so checks stop without errors, +//! and recheck the access of the people whose memberships those organizations' repositories decide; +//! - membership changes (collaborators, teams, organization members) recheck the people they name ([`RecheckAccess`]). +//! +//! Every event is safe to receive twice. GitLab's project hooks come with the self-managed instances' port. + +use std::collections::{HashMap, HashSet}; + +use hmac::{Hmac, Mac}; +use laravel::db; +use laravel::prelude::*; +use laravel::queue::{Queueable, job}; +use serde_json::{Value, json}; +use sha2::Sha256; + +use super::events::{BranchClosed, BranchReopened, PullRequestMerged, RepositoryVisibilityChanged}; +use super::github_app::{self, GithubApp}; +use super::{ForgeKind, Permission, Repository}; + +/// One delivery, as VisualCI acts on it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ForgeEvent { + Merged { + repository: Repository, + head: String, + base: String, + merge_commit: String, + }, + Closed { + repository: Repository, + branch: String, + why: &'static str, + }, + Reopened { + repository: Repository, + branch: String, + }, + /// The App was installed on these repositories (`installation` set) or removed from them (`None`). + Installation { + installation: Option, + previous: Option, + repositories: Vec, + }, + /// These people's access may have changed (GitHub user IDs). + Access { + people: Vec, + }, + /// Anyone's access through this installation may have changed (a team's repositories changed). + AccessAll { + installation: String, + }, + RepositoryChanged { + repository: Repository, + private: bool, + }, + Ignored, +} + +/// `X-Hub-Signature-256`: `sha256=` and the body's HMAC-SHA256 under the webhook's secret, compared in constant time. +#[must_use] +pub fn signed(secret: &str, header: &str, body: &[u8]) -> bool { + let Some(hex_sig) = header.strip_prefix("sha256=") else { return false }; + let Ok(sig) = hex::decode(hex_sig) else { return false }; + let Ok(mut mac) = Hmac::::new_from_slice(secret.as_bytes()) else { return false }; + mac.update(body); + mac.verify_slice(&sig).is_ok() +} + +fn repositories(list: &Value) -> Vec { + list.as_array() + .map(|l| { + l.iter() + .filter_map(|r| { + let id = r["id"].as_i64().map(|i| i.to_string()); + r["full_name"].as_str().and_then(Repository::parse).map(|repo| repo.with_id(id)) + }) + .collect() + }) + .unwrap_or_default() +} + +/// The repository an event names, with GitHub's ID for it (which survives a rename). +fn repository(event: &Value) -> Option { + event["repository"]["full_name"] + .as_str() + .and_then(Repository::parse) + .map(|r| r.with_id(event["repository"]["id"].as_i64().map(|i| i.to_string()))) +} + +/// A pull request's branch: a fork's goes by its head label (`octocat:main`), as the CLI names it, so a fork's `main` +/// isn't taken for the base repository's. +fn pr_branch(event: &Value) -> Option<&str> { + let pr = &event["pull_request"]; + let head_repo = pr["head"]["repo"]["full_name"].as_str(); + let from_fork = head_repo.is_some() && head_repo != event["repository"]["full_name"].as_str(); + if from_fork { pr["head"]["label"].as_str() } else { pr["head"]["ref"].as_str() } +} + +fn deleted_branch(event: &Value, branch: Option<&str>) -> ForgeEvent { + match (repository(event), branch) { + (Some(repository), Some(branch)) => { + ForgeEvent::Closed { repository, branch: branch.to_string(), why: "branch_deleted" } + } + _ => ForgeEvent::Ignored, + } +} + +/// One delivery (`X-GitHub-Event` and its body) as a [`ForgeEvent`]. +/// +/// # Errors +/// A message for a merged pull request without its branches or merge commit. +pub fn read_event(kind: &str, event: &Value) -> Result { + let action = event["action"].as_str().unwrap_or_default(); + let installation = event["installation"]["id"].as_i64().map(|i| i.to_string()); + let person = |v: &Value| v["id"].as_i64().map(|i| vec![i.to_string()]).unwrap_or_default(); + Ok(match (kind, action) { + ("pull_request", "closed") if event["pull_request"]["merged"] == true => { + let pr = &event["pull_request"]; + let (Some(repository), Some(head), Some(base), Some(merge)) = + (repository(event), pr_branch(event), pr["base"]["ref"].as_str(), pr["merge_commit_sha"].as_str()) + else { + return Err("a merged pull request without its branches or merge commit".into()); + }; + ForgeEvent::Merged { + repository, + head: head.to_string(), + base: base.to_string(), + merge_commit: merge.to_string(), + } + } + ("pull_request", "closed" | "reopened") => match (repository(event), pr_branch(event)) { + (Some(repository), Some(branch)) if action == "closed" => { + ForgeEvent::Closed { repository, branch: branch.to_string(), why: "pull_request" } + } + (Some(repository), Some(branch)) => ForgeEvent::Reopened { repository, branch: branch.to_string() }, + _ => ForgeEvent::Ignored, + }, + // A branch deleted: GitHub sends `delete` (ref_type branch) and a `push` with `deleted: true` + ("delete", _) if event["ref_type"] == "branch" => deleted_branch(event, event["ref"].as_str()), + ("push", _) if event["deleted"] == true => { + deleted_branch(event, event["ref"].as_str().and_then(|r| r.strip_prefix("refs/heads/"))) + } + ("installation", "created" | "unsuspend") => ForgeEvent::Installation { + installation, + previous: None, + repositories: repositories(&event["repositories"]), + }, + ("installation", "deleted" | "suspend") => ForgeEvent::Installation { + installation: None, + previous: installation, + repositories: repositories(&event["repositories"]), + }, + ("installation_repositories", "added") => ForgeEvent::Installation { + installation, + previous: None, + repositories: repositories(&event["repositories_added"]), + }, + ("installation_repositories", "removed") => ForgeEvent::Installation { + installation: None, + previous: installation, + repositories: repositories(&event["repositories_removed"]), + }, + // Made public or private, or edited: projects linked to it follow at once + ("repository", "publicized" | "privatized" | "edited") => match repository(event) { + Some(repository) => ForgeEvent::RepositoryChanged { repository, private: action == "privatized" }, + None => ForgeEvent::Ignored, + }, + // A collaborator added, removed or changed; someone joined or left a team + ("member" | "membership", _) => ForgeEvent::Access { people: person(&event["member"]) }, + // Someone joined or left the organization + ("organization", "member_added" | "member_removed") => { + ForgeEvent::Access { people: person(&event["membership"]["user"]) } + } + // A team's repositories or permission changed, or it was deleted + ("team", "added_to_repository" | "removed_from_repository" | "edited" | "deleted") => match installation { + Some(installation) => ForgeEvent::AccessAll { installation }, + None => ForgeEvent::Ignored, + }, + _ => ForgeEvent::Ignored, + }) +} + +/// A project linked to a repository. +struct Linked { + id: i64, + organization_id: i64, + installation: Option, +} + +/// The GitHub projects linked to a repository: by GitHub's permanent ID when the delivery has it (a renamed repository +/// is still the same one, and a new repository that took the old name isn't), and links whose ID isn't known yet by +/// URL. +async fn linked(repository: &Repository) -> laravel::Result> { + let (id, url) = (repository.id.clone(), repository.url.to_lowercase()); + let rows = db::query!( + "SELECT id, organization_id, forge_installation FROM projects WHERE forge = 'github' AND ( \ + ({id}::text IS NOT NULL AND repository_id = {id}) \ + OR (({id}::text IS NULL OR repository_id IS NULL) AND lower(repository_url) = {url}))" + ) + .select() + .await?; + rows.iter() + .map(|r| { + Ok(Linked { + id: r.try_get("id")?, + organization_id: r.try_get("organization_id")?, + installation: r.try_get("forge_installation")?, + }) + }) + .collect() +} + +/// `POST /webhooks/github`. +pub async fn github( + app: laravel::config::Section, + headers: axum::http::HeaderMap, + body: axum::body::Bytes, +) -> laravel::Result> { + let Some(secret) = app.webhook_secret.as_deref().filter(|s| !s.is_empty()) else { + return Err(laravel::abort(404)); + }; + let header = |name: &str| headers.get(name).and_then(|v| v.to_str().ok()).unwrap_or_default().to_string(); + if !signed(secret, &header("x-hub-signature-256"), &body) { + return Err(laravel::abort_with(401, "bad signature")); + } + let event: Value = serde_json::from_slice(&body).map_err(|e| laravel::abort_with(400, e.to_string()))?; + let (kind, delivery) = (header("x-github-event"), header("x-github-delivery")); + let read = read_event(&kind, &event).map_err(|e| laravel::abort_with(400, e))?; + let outcome = handle(read).await?; + tracing::info!(forge = "github", kind, delivery, outcome = %outcome, "webhook"); + Ok(Json(outcome)) +} + +/// Act on one event; returns what happened, for the delivery's log on GitHub. +/// +/// # Errors +/// On a database error. +pub async fn handle(event: ForgeEvent) -> laravel::Result { + Ok(match event { + ForgeEvent::Merged { repository, head, base, merge_commit } => { + let projects = linked(&repository).await?; + for p in &projects { + PullRequestMerged { + project_id: p.id, + head: head.clone(), + base: base.clone(), + merge_commit: merge_commit.clone(), + } + .dispatch() + .await?; + } + json!({ "dispatched": projects.len() }) + } + ForgeEvent::Closed { repository, branch, why } => { + let projects = linked(&repository).await?; + for p in &projects { + BranchClosed { project_id: p.id, branch: branch.clone(), why: why.to_string() }.dispatch().await?; + } + json!({ "dispatched": projects.len() }) + } + ForgeEvent::Reopened { repository, branch } => { + let projects = linked(&repository).await?; + for p in &projects { + BranchReopened { project_id: p.id, branch: branch.clone() }.dispatch().await?; + } + json!({ "dispatched": projects.len() }) + } + ForgeEvent::RepositoryChanged { repository, private } => { + let projects = linked(&repository).await?; + for p in &projects { + RepositoryVisibilityChanged { project_id: p.id, private }.dispatch().await?; + } + json!({ "dispatched": projects.len() }) + } + ForgeEvent::Installation { installation, previous, repositories } => { + let mut changed = 0; + let mut affected = HashSet::new(); + for repository in &repositories { + for p in linked(repository).await? { + // Removal only from the installation being removed; a project already on another keeps it + if previous.is_some() && p.installation != previous { + continue; + } + if p.installation == installation { + continue; + } + let (id, to) = (p.id, installation.clone()); + db::query!("UPDATE projects SET forge_installation = {to}, updated_at = now() WHERE id = {id}") + .update() + .await?; + affected.insert(p.organization_id); + changed += 1; + } + } + recheck_organizations(affected.into_iter().collect()).await?; + if installation.is_some() { json!({ "linked": changed }) } else { json!({ "unlinked": changed }) } + } + ForgeEvent::Access { people } => { + let mut users = Vec::new(); + for person in people { + let found: Option = db::query!( + "SELECT user_id FROM identities WHERE forge = 'github' AND site = '' AND forge_user_id = {person}" + ) + .scalar() + .await?; + users.extend(found); + } + let n = users.len(); + if n > 0 { + RecheckAccess { user_ids: users }.dispatch().await?; + } + json!({ "rechecking": n }) + } + ForgeEvent::AccessAll { installation } => { + let orgs: Vec = db::query!( + "SELECT DISTINCT organization_id FROM projects WHERE forge = 'github' AND forge_installation = {installation}" + ) + .select() + .await? + .iter() + .map(|r| r.try_get("organization_id")) + .collect::>()?; + recheck_organizations(orgs).await?; + json!({ "rechecking": "installation" }) + } + ForgeEvent::Ignored => json!({ "ignored": true }), + }) +} + +/// Recheck everyone whose membership in these organizations GitHub decides. +async fn recheck_organizations(orgs: Vec) -> laravel::Result<()> { + let mut users = HashSet::new(); + for org in orgs { + let rows = db::query!("SELECT user_id FROM memberships WHERE organization_id = {org} AND source = 'github'") + .select() + .await?; + for r in rows { + users.insert(r.try_get::("user_id")?); + } + } + if !users.is_empty() { + RecheckAccess { user_ids: users.into_iter().collect() }.dispatch().await?; + } + Ok(()) +} + +/// Recheck people's memberships from GitHub through the App: their permission on every repository a project links +/// through an installation decides their role in its organization, as a sign-in does (`auth::memberships::apply`). +/// One person GitHub can't answer for is logged and skipped, so the others still update. +#[derive(Queueable, Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct RecheckAccess { + pub user_ids: Vec, +} + +#[job] +impl RecheckAccess { + async fn handle(self, app: laravel::config::Section) -> laravel::Result<()> { + for user_id in self.user_ids { + if let Err(e) = recheck(&app, user_id).await { + tracing::warn!(user_id, error = %e, "GitHub access recheck failed"); + } + } + Ok(()) + } +} + +/// Recheck one person. Returns how many memberships changed. +/// +/// # Errors +/// When GitHub can't answer, or on a database error. +pub async fn recheck(app: &GithubApp, user_id: i64) -> laravel::Result { + let Some(github_id) = db::query!( + "SELECT forge_user_id FROM identities WHERE user_id = {user_id} AND forge = 'github' AND site = '' \ + ORDER BY id LIMIT 1" + ) + .scalar::() + .await? + else { + return Ok(0); + }; + let rows = db::query!( + "SELECT DISTINCT ON (lower(repository_url)) repository_url, forge_installation FROM projects \ + WHERE forge = 'github' AND repository_url IS NOT NULL AND forge_installation IS NOT NULL" + ) + .select() + .await?; + let mut permissions: HashMap = HashMap::new(); + for r in rows { + let (url, installation): (String, String) = (r.try_get("repository_url")?, r.try_get("forge_installation")?); + let Some(repository) = Repository::parse(&url) else { continue }; + if let Some(permission) = github_app::permission(app, &repository.path, &installation, &github_id).await? { + permissions.insert(repository.url.to_lowercase(), (repository, permission)); + } + } + let list: Vec<(Repository, Permission)> = permissions.into_values().collect(); + crate::auth::memberships::apply(user_id, ForgeKind::Github, "", &list).await +} diff --git a/app/src/lib.rs b/app/src/lib.rs index 95033310..c35f47c6 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -70,6 +70,7 @@ pub fn configure() -> ApplicationBuilder { // MCP clients: a person's OAuth token (the guard joins with the OAuth server, #57) or a personal // or project token. route.any("/mcp", mcp::handle); + route.post("/webhooks/github", forge::webhooks::github); }) .routes(http::renderer::routes) .routes(http::gallery::routes) diff --git a/app/tests/webhooks.rs b/app/tests/webhooks.rs new file mode 100644 index 00000000..58fafbb5 --- /dev/null +++ b/app/tests/webhooks.rs @@ -0,0 +1,141 @@ +//! GitHub's webhook: signed deliveries only; merges and closed branches go to the domain once per linked project (by +//! GitHub's repository ID, else URL); installations attach to and detach from linked projects; membership changes +//! queue a recheck of the people they name. + +use app::forge::events::{BranchClosed, PullRequestMerged}; +use app::forge::webhooks::RecheckAccess; +use app::models::User; +use hmac::{Hmac, Mac}; +use laravel::db; +use laravel::model::create; +use laravel::testing::TestResponse; +use laravel::testing::prelude::*; +use sha2::Sha256; + +const SECRET: &str = "github-webhook-test"; + +fn github() -> Application { + app::testing::configure().with_env("GITHUB_WEBHOOK_SECRET", SECRET).create() +} + +async fn deliver(app: &Application, kind: &str, event: serde_json::Value) -> TestResponse { + let body = event.to_string(); + let mut mac = Hmac::::new_from_slice(SECRET.as_bytes()).unwrap(); + mac.update(body.as_bytes()); + let signature = format!("sha256={}", hex::encode(mac.finalize().into_bytes())); + app.post("/webhooks/github") + .header("x-github-event", kind) + .header("x-github-delivery", "d-1") + .header("x-hub-signature-256", signature) + .header("content-type", "application/json") + .body(body) + .await +} + +/// Two organizations' projects linking acme/web: one by GitHub's repository ID, one by URL only. +async fn linked() -> laravel::Result<(i64, i64, i64)> { + let mut ids = Vec::new(); + for (slug, repository_id) in [("acme", Some("42")), ("other", None)] { + let org: i64 = db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) \ + VALUES (gen_random_uuid(), {slug}, {slug}, now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + let project: i64 = db::query!( + "INSERT INTO projects (pid, organization_id, slug, name, forge, repository_url, repository_id, \ + forge_installation, created_at, updated_at) \ + VALUES (gen_random_uuid(), {org}, 'web', 'Web', 'github', 'https://github.com/acme/web', {repository_id}, \ + '7', now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + ids.push((org, project)); + } + Ok((ids[0].0, ids[0].1, ids[1].1)) +} + +fn repository() -> serde_json::Value { + json!({ "id": 42, "full_name": "acme/web" }) +} + +#[laravel::test(app = github)] +async fn an_unsigned_delivery_is_refused(app: Application) { + app.post("/webhooks/github") + .header("x-github-event", "ping") + .header("x-hub-signature-256", "sha256=00") + .json(json!({})) + .await + .assert_status(401); +} + +#[laravel::test(app = github)] +async fn a_merge_and_a_deleted_branch_reach_each_linked_project(app: Application) -> laravel::Result<()> { + let (_, by_id, by_url) = linked().await?; + let events = laravel::event::fake(); + let merged = json!({ + "action": "closed", "repository": repository(), + "pull_request": { "merged": true, "merge_commit_sha": "abc123", "base": { "ref": "main" }, + "head": { "ref": "feature", "repo": { "full_name": "acme/web" } } }, + }); + deliver(&app, "pull_request", merged).await.assert_ok().assert_json_path("dispatched", 2); + events.assert_dispatched_times::(2); + events.assert_dispatched_where::(|e| { + e.project_id == by_id && e.head == "feature" && e.base == "main" && e.merge_commit == "abc123" + }); + events.assert_dispatched_where::(|e| e.project_id == by_url); + + // A fork's branch goes by its label + let fork = json!({ + "action": "closed", "repository": repository(), + "pull_request": { "merged": false, "head": { "ref": "main", "label": "octocat:main", + "repo": { "full_name": "octocat/web" } } }, + }); + deliver(&app, "pull_request", fork).await.assert_ok(); + events.assert_dispatched_where::(|e| e.branch == "octocat:main" && e.why == "pull_request"); + let deleted = json!({ "ref": "old", "ref_type": "branch", "repository": repository() }); + deliver(&app, "delete", deleted).await.assert_ok(); + events.assert_dispatched_where::(|e| e.branch == "old" && e.why == "branch_deleted"); + Ok(()) +} + +#[laravel::test(app = github)] +async fn installations_attach_and_detach_and_membership_changes_recheck(app: Application) -> laravel::Result<()> { + let (org, by_id, _) = linked().await?; + let jobs = laravel::queue::fake(); + let installation = |id: i64| async move { + db::query!("SELECT forge_installation FROM projects WHERE id = {id}").scalar::>().await + }; + // Removing another installation leaves the project's own alone + let other = json!({ "action": "deleted", "installation": { "id": 9 }, "repositories": [repository()] }); + deliver(&app, "installation", other).await.assert_ok().assert_json_path("unlinked", 0); + assert_eq!(installation(by_id).await?.flatten().as_deref(), Some("7")); + let removed = json!({ "action": "removed", "installation": { "id": 7 }, "repositories_removed": [repository()] }); + deliver(&app, "installation_repositories", removed).await.assert_ok().assert_json_path("unlinked", 2); + assert_eq!(installation(by_id).await?.flatten(), None); + let added = json!({ "action": "added", "installation": { "id": 8 }, "repositories_added": [repository()] }); + deliver(&app, "installation_repositories", added).await.assert_ok().assert_json_path("linked", 2); + assert_eq!(installation(by_id).await?.flatten().as_deref(), Some("8")); + + // A collaborator changed: the person with that GitHub ID is rechecked + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let ada_id = ada.id; + db::query!( + "INSERT INTO identities (user_id, forge, site, forge_user_id, login, created_at, updated_at) \ + VALUES ({ada_id}, 'github', '', '1001', 'ada', now(), now())" + ) + .insert() + .await?; + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org}, {ada_id}, 'member', 'github', now(), now())" + ) + .insert() + .await?; + let member = json!({ "action": "removed", "member": { "id": 1001 }, "repository": repository() }); + deliver(&app, "member", member).await.assert_ok().assert_json_path("rechecking", 1); + assert!(jobs.pushed::().iter().any(|j| j.job().user_ids == vec![ada_id])); + Ok(()) +} From 07930e2fe4fb4e146fd59fbaf285aced5453f5bb Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 04:17:57 +1300 Subject: [PATCH 03/20] GitHub webhook, review fixes: a recheck lists each linked repository's collaborators once (affiliation=all; one installation token per installation for the run; the path looked up by GitHub's ID) and derives everyone's permission from that, keyed by repository ID; nothing changes unless every repository was read, and it stops when the rate limit is low; an installation is attached only after GitHub confirms it exists (a stale or redelivered 'created'); renamed and transferred repositories move their links by ID; a delivery naming a repository's ID backfills links that only had its URL; 'edited' takes the repository's own private flag; deliveries up to GitHub's 25 MB --- app/Cargo.toml | 10 ++- app/src/forge/github_app.rs | 80 ++++++++++++++++++++++++ app/src/forge/webhooks.rs | 121 ++++++++++++++++++++++++++---------- app/src/lib.rs | 4 ++ app/tests/webhooks.rs | 119 ++++++++++++++++++++++++++++++++++- 5 files changed, 300 insertions(+), 34 deletions(-) diff --git a/app/Cargo.toml b/app/Cargo.toml index 90e50911..c1bfe12a 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -44,7 +44,6 @@ schemars = "1" tracing = "0.1" include_dir = "0.7" rmcp = { version = "3.12", features = ["server", "transport-streamable-http-server", "macros"] } -base64 = "0.22" tower = { version = "0.5", features = ["util"] } url = "2" regex = "1" @@ -53,9 +52,18 @@ visualci-core = { path = "../crates/visualci-core", features = ["bundle"] } snapshot-diff = { path = "../crates/snapshot-diff" } [dev-dependencies] +regex = "1" +# A GitHub App key made at test time, so no private key is committed +rsa = { version = "0.9", features = ["pem"] } [profile.dev] debug = "line-tables-only" [profile.dev.package."*"] debug = false + +# Generating the tests' RSA key is slow unoptimised +[profile.dev.package.num-bigint-dig] +opt-level = 3 +[profile.dev.package.rsa] +opt-level = 3 diff --git a/app/src/forge/github_app.rs b/app/src/forge/github_app.rs index e482103c..9da5047a 100644 --- a/app/src/forge/github_app.rs +++ b/app/src/forge/github_app.rs @@ -80,6 +80,86 @@ pub async fn installation_token(app: &GithubApp, installation: &str) -> laravel: body["token"].as_str().map(str::to_string).ok_or_else(|| err("an installation token response without a token")) } +/// Whether the App's installation `id` exists (a delivery can be stale, or redelivered after the installation went). +/// +/// # Errors +/// When the App isn't configured, or GitHub can't be reached or refuses. +pub async fn installation_exists(app: &GithubApp, id: &str) -> laravel::Result { + if !id.bytes().all(|b| b.is_ascii_digit()) { + return Ok(false); + } + Ok(get(&app_jwt(app)?, &format!("/app/installations/{id}")).await?.is_some()) +} + +/// Below this many API calls left in the hour, a recheck stops instead of using up what webhooks and checks need. +pub const RATE_LIMIT_RESERVE: i64 = 500; + +/// Every collaborator on a repository (`owner/name`) with their permission, keyed by GitHub user ID: direct +/// collaborators, team members and organization members with access, as `affiliation=all` lists them. Public +/// visibility gives nobody a place on it. `Err` when it can't be read completely (a partial list would drop people); +/// also when GitHub's rate limit is down to [`RATE_LIMIT_RESERVE`]. +/// +/// # Errors +/// Those. +pub async fn collaborators(token: &str, repo: &str) -> laravel::Result> { + let mut out = Vec::new(); + for page in 1..=50 { + let response = client::get(format!("{API}/repos/{repo}/collaborators")) + .token(token) + .header("accept", "application/vnd.github+json") + .header("user-agent", "visualci") + .query([("affiliation", "all".to_string()), ("per_page", "100".to_string()), ("page", page.to_string())]) + .await?; + if !response.successful() { + return Err(err(format!("GET /repos/{repo}/collaborators: HTTP {}", response.status()))); + } + let remaining = response.header("x-ratelimit-remaining").and_then(|v| v.parse::().ok()); + let list: Vec = response.json()?; + let done = list.len() < 100; + for c in &list { + let (Some(id), Some(permission)) = ( + c["id"].as_i64(), + c["role_name"].as_str().and_then(permission_from).or_else(|| permission_from_flags(&c["permissions"])), + ) else { + continue; + }; + out.push((id.to_string(), permission)); + } + if remaining.is_some_and(|r| r < RATE_LIMIT_RESERVE) { + return Err(err(format!("the rate limit is down to {} calls", remaining.unwrap_or(0)))); + } + if done { + return Ok(out); + } + } + Err(err(format!("{repo} has more than 5,000 collaborators"))) +} + +/// The highest permission in a `permissions` object (`{admin, maintain, push, triage, pull}`). +fn permission_from_flags(flags: &Value) -> Option { + [ + ("admin", Permission::Admin), + ("maintain", Permission::Maintain), + ("push", Permission::Write), + ("triage", Permission::Triage), + ("pull", Permission::Read), + ] + .into_iter() + .find(|(flag, _)| flags[*flag] == true) + .map(|(_, p)| p) +} + +/// A repository's `owner/name` now, by its permanent ID (`None` when the installation can't see it). +/// +/// # Errors +/// When GitHub can't be reached or refuses. +pub async fn repository_path(token: &str, id: &str) -> laravel::Result> { + if !id.bytes().all(|b| b.is_ascii_digit()) { + return Ok(None); + } + Ok(get(token, &format!("/repositories/{id}")).await?.and_then(|v| v["full_name"].as_str().map(str::to_string))) +} + /// GitHub's role name for a collaborator (`admin`, `maintain`, `write`, `triage`, `read`). fn permission_from(role: &str) -> Option { match role { diff --git a/app/src/forge/webhooks.rs b/app/src/forge/webhooks.rs index 1637fc87..35d0d3a2 100644 --- a/app/src/forge/webhooks.rs +++ b/app/src/forge/webhooks.rs @@ -58,6 +58,10 @@ pub enum ForgeEvent { repository: Repository, private: bool, }, + /// Renamed or transferred: the same repository (by ID) at a new URL. + Moved { + repository: Repository, + }, Ignored, } @@ -167,9 +171,17 @@ pub fn read_event(kind: &str, event: &Value) -> Result { }, // Made public or private, or edited: projects linked to it follow at once ("repository", "publicized" | "privatized" | "edited") => match repository(event) { - Some(repository) => ForgeEvent::RepositoryChanged { repository, private: action == "privatized" }, + Some(repository) => { + let private = event["repository"]["private"].as_bool().unwrap_or(action == "privatized"); + ForgeEvent::RepositoryChanged { repository, private } + } None => ForgeEvent::Ignored, }, + // The same repository at a new URL; links follow by its ID + ("repository", "renamed" | "transferred") => match repository(event) { + Some(repository) if repository.id.is_some() => ForgeEvent::Moved { repository }, + _ => ForgeEvent::Ignored, + }, // A collaborator added, removed or changed; someone joined or left a team ("member" | "membership", _) => ForgeEvent::Access { people: person(&event["member"]) }, // Someone joined or left the organization @@ -194,9 +206,17 @@ struct Linked { /// The GitHub projects linked to a repository: by GitHub's permanent ID when the delivery has it (a renamed repository /// is still the same one, and a new repository that took the old name isn't), and links whose ID isn't known yet by -/// URL. +/// URL, which get the ID now. async fn linked(repository: &Repository) -> laravel::Result> { let (id, url) = (repository.id.clone(), repository.url.to_lowercase()); + if id.is_some() { + db::query!( + "UPDATE projects SET repository_id = {id}, updated_at = now() \ + WHERE forge = 'github' AND repository_id IS NULL AND lower(repository_url) = {url}" + ) + .update() + .await?; + } let rows = db::query!( "SELECT id, organization_id, forge_installation FROM projects WHERE forge = 'github' AND ( \ ({id}::text IS NOT NULL AND repository_id = {id}) \ @@ -231,7 +251,7 @@ pub async fn github( let event: Value = serde_json::from_slice(&body).map_err(|e| laravel::abort_with(400, e.to_string()))?; let (kind, delivery) = (header("x-github-event"), header("x-github-delivery")); let read = read_event(&kind, &event).map_err(|e| laravel::abort_with(400, e))?; - let outcome = handle(read).await?; + let outcome = handle(&app, read).await?; tracing::info!(forge = "github", kind, delivery, outcome = %outcome, "webhook"); Ok(Json(outcome)) } @@ -240,7 +260,7 @@ pub async fn github( /// /// # Errors /// On a database error. -pub async fn handle(event: ForgeEvent) -> laravel::Result { +pub async fn handle(app: &GithubApp, event: ForgeEvent) -> laravel::Result { Ok(match event { ForgeEvent::Merged { repository, head, base, merge_commit } => { let projects = linked(&repository).await?; @@ -277,7 +297,23 @@ pub async fn handle(event: ForgeEvent) -> laravel::Result { } json!({ "dispatched": projects.len() }) } + ForgeEvent::Moved { repository } => { + let (id, url) = (repository.id.clone(), repository.url.clone()); + let moved = db::query!( + "UPDATE projects SET repository_url = {url}, updated_at = now() \ + WHERE forge = 'github' AND repository_id = {id} AND repository_url IS DISTINCT FROM {url}" + ) + .update() + .await?; + json!({ "moved": moved }) + } ForgeEvent::Installation { installation, previous, repositories } => { + // A stale or redelivered "created" mustn't attach an installation that's gone + if let Some(id) = &installation + && !github_app::installation_exists(app, id).await? + { + return Ok(json!({ "ignored": "no such installation" })); + } let mut changed = 0; let mut affected = HashSet::new(); for repository in &repositories { @@ -349,9 +385,7 @@ async fn recheck_organizations(orgs: Vec) -> laravel::Result<()> { Ok(()) } -/// Recheck people's memberships from GitHub through the App: their permission on every repository a project links -/// through an installation decides their role in its organization, as a sign-in does (`auth::memberships::apply`). -/// One person GitHub can't answer for is logged and skipped, so the others still update. +/// Recheck people's memberships from GitHub through the App ([`recheck`]). #[derive(Queueable, Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct RecheckAccess { pub user_ids: Vec, @@ -360,43 +394,66 @@ pub struct RecheckAccess { #[job] impl RecheckAccess { async fn handle(self, app: laravel::config::Section) -> laravel::Result<()> { - for user_id in self.user_ids { - if let Err(e) = recheck(&app, user_id).await { - tracing::warn!(user_id, error = %e, "GitHub access recheck failed"); - } - } + recheck(&app, &self.user_ids).await?; Ok(()) } } -/// Recheck one person. Returns how many memberships changed. +/// Recheck people's memberships: each linked repository's collaborators are listed once (one installation token per +/// installation, its path looked up by GitHub's ID so a rename can't mislead it), and each person's permission on each +/// decides their role in its organization, as a sign-in does (`auth::memberships::apply`). Nobody's memberships change +/// unless every repository was read: a list that failed part-way would drop people. Returns how many changed. /// /// # Errors -/// When GitHub can't answer, or on a database error. -pub async fn recheck(app: &GithubApp, user_id: i64) -> laravel::Result { - let Some(github_id) = db::query!( - "SELECT forge_user_id FROM identities WHERE user_id = {user_id} AND forge = 'github' AND site = '' \ - ORDER BY id LIMIT 1" - ) - .scalar::() - .await? - else { +/// When GitHub can't answer for some repository (or its rate limit is low), or on a database error. +pub async fn recheck(app: &GithubApp, user_ids: &[i64]) -> laravel::Result { + let mut github_ids: HashMap = HashMap::new(); + for &user_id in user_ids { + if let Some(id) = db::query!( + "SELECT forge_user_id FROM identities WHERE user_id = {user_id} AND forge = 'github' AND site = '' \ + ORDER BY id LIMIT 1" + ) + .scalar::() + .await? + { + github_ids.insert(user_id, id); + } + } + if github_ids.is_empty() { return Ok(0); - }; + } let rows = db::query!( - "SELECT DISTINCT ON (lower(repository_url)) repository_url, forge_installation FROM projects \ - WHERE forge = 'github' AND repository_url IS NOT NULL AND forge_installation IS NOT NULL" + "SELECT DISTINCT repository_id, forge_installation FROM projects \ + WHERE forge = 'github' AND repository_id IS NOT NULL AND forge_installation IS NOT NULL" ) .select() .await?; - let mut permissions: HashMap = HashMap::new(); + let mut tokens: HashMap = HashMap::new(); + // GitHub user ID -> [(repository, permission)] + let mut reach: HashMap> = HashMap::new(); for r in rows { - let (url, installation): (String, String) = (r.try_get("repository_url")?, r.try_get("forge_installation")?); - let Some(repository) = Repository::parse(&url) else { continue }; - if let Some(permission) = github_app::permission(app, &repository.path, &installation, &github_id).await? { - permissions.insert(repository.url.to_lowercase(), (repository, permission)); + let (repository_id, installation): (String, String) = + (r.try_get("repository_id")?, r.try_get("forge_installation")?); + let token = match tokens.get(&installation) { + Some(t) => t.clone(), + None => { + let t = github_app::installation_token(app, &installation).await?; + tokens.insert(installation.clone(), t.clone()); + t + } + }; + // The installation can't see it any more: it grants nobody anything + let Some(path) = github_app::repository_path(&token, &repository_id).await? else { continue }; + let Some(repository) = Repository::parse(&path) else { continue }; + let repository = repository.with_id(Some(repository_id)); + for (person, permission) in github_app::collaborators(&token, &path).await? { + reach.entry(person).or_default().push((repository.clone(), permission)); } } - let list: Vec<(Repository, Permission)> = permissions.into_values().collect(); - crate::auth::memberships::apply(user_id, ForgeKind::Github, "", &list).await + let mut changed = 0; + for (user_id, github_id) in github_ids { + let list = reach.remove(&github_id).unwrap_or_default(); + changed += crate::auth::memberships::apply(user_id, ForgeKind::Github, "", &list).await?; + } + Ok(changed) } diff --git a/app/src/lib.rs b/app/src/lib.rs index c35f47c6..0c90496c 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -71,6 +71,10 @@ pub fn configure() -> ApplicationBuilder { // or project token. route.any("/mcp", mcp::handle); route.post("/webhooks/github", forge::webhooks::github); + // GitHub sends deliveries of up to 25 MB + route + .post("/webhooks/github", forge::webhooks::github) + .middleware(laravel::http::middleware::LimitBody::megabytes(25)); }) .routes(http::renderer::routes) .routes(http::gallery::routes) diff --git a/app/tests/webhooks.rs b/app/tests/webhooks.rs index 58fafbb5..27974837 100644 --- a/app/tests/webhooks.rs +++ b/app/tests/webhooks.rs @@ -14,8 +14,34 @@ use sha2::Sha256; const SECRET: &str = "github-webhook-test"; +/// A GitHub App key made once per run (base64 of its PEM, as GITHUB_APP_PRIVATE_KEY_BASE64 holds it). +fn app_key() -> &'static str { + static KEY: std::sync::OnceLock = std::sync::OnceLock::new(); + KEY.get_or_init(|| { + use base64::Engine; + use rsa::pkcs1::EncodeRsaPrivateKey; + let key = rsa::RsaPrivateKey::new(&mut rsa::rand_core::OsRng, 2048).expect("a key"); + let pem = key.to_pkcs1_pem(rsa::pkcs1::LineEnding::LF).expect("its PEM"); + base64::engine::general_purpose::STANDARD.encode(pem.as_bytes()) + }) +} + fn github() -> Application { - app::testing::configure().with_env("GITHUB_WEBHOOK_SECRET", SECRET).create() + app::testing::configure() + .with_envs([ + ("GITHUB_WEBHOOK_SECRET", SECRET), + ("GITHUB_APP_ID", "1"), + ("GITHUB_APP_PRIVATE_KEY_BASE64", app_key()), + ]) + .create() +} + +fn github_app() -> app::forge::github_app::GithubApp { + app::forge::github_app::GithubApp { + app_id: Some("1".into()), + private_key_base64: Some(app_key().into()), + webhook_secret: None, + } } async fn deliver(app: &Application, kind: &str, event: serde_json::Value) -> TestResponse { @@ -105,6 +131,12 @@ async fn a_merge_and_a_deleted_branch_reach_each_linked_project(app: Application async fn installations_attach_and_detach_and_membership_changes_recheck(app: Application) -> laravel::Result<()> { let (org, by_id, _) = linked().await?; let jobs = laravel::queue::fake(); + let _github = laravel::http::client::fake() + .with("api.github.com/app/installations/8", json!({ "id": 8 })) + .with("api.github.com/app/installations/*", laravel::http::client::response().status(404).json(json!({}))); + // A stale "created" for an installation that's gone attaches nothing + let stale = json!({ "action": "created", "installation": { "id": 5 }, "repositories": [repository()] }); + deliver(&app, "installation", stale).await.assert_ok().assert_json_path("ignored", "no such installation"); let installation = |id: i64| async move { db::query!("SELECT forge_installation FROM projects WHERE id = {id}").scalar::>().await }; @@ -139,3 +171,88 @@ async fn installations_attach_and_detach_and_membership_changes_recheck(app: App assert!(jobs.pushed::().iter().any(|j| j.job().user_ids == vec![ada_id])); Ok(()) } + +#[laravel::test(app = github)] +async fn a_recheck_reads_each_repositorys_collaborators_once(_app: Application) -> laravel::Result<()> { + let (org, _, _) = linked().await?; + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let ada_id = ada.id; + db::query!( + "INSERT INTO identities (user_id, forge, site, forge_user_id, login, created_at, updated_at) \ + VALUES ({ada_id}, 'github', '', '1001', 'ada', now(), now())" + ) + .insert() + .await?; + let github = laravel::http::client::fake() + .with("api.github.com/app/installations/7/access_tokens", json!({ "token": "t" })) + .with("api.github.com/repositories/42", json!({ "full_name": "acme/web" })) + .with( + "api.github.com/repos/acme/web/collaborators*", + json!([{ "id": 1001, "role_name": "maintain" }, { "id": 2002, "role_name": "read" }]), + ); + assert_eq!(app::forge::webhooks::recheck(&github_app(), &[ada_id]).await?, 1); + let role: Option = + db::query!("SELECT role FROM memberships WHERE organization_id = {org} AND user_id = {ada_id}") + .scalar() + .await?; + assert_eq!(role.as_deref(), Some("admin"), "maintain is admin"); + github.assert_sent_count(3); + Ok(()) +} + +#[laravel::test(app = github)] +async fn a_listing_that_fails_changes_nobody(_app: Application) -> laravel::Result<()> { + let (org, _, _) = linked().await?; + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let ada_id = ada.id; + db::query!( + "INSERT INTO identities (user_id, forge, site, forge_user_id, login, created_at, updated_at) \ + VALUES ({ada_id}, 'github', '', '1001', 'ada', now(), now())" + ) + .insert() + .await?; + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org}, {ada_id}, 'member', 'github', now(), now())" + ) + .insert() + .await?; + let _github = laravel::http::client::fake() + .with("api.github.com/app/installations/7/access_tokens", json!({ "token": "t" })) + .with("api.github.com/repositories/42", json!({ "full_name": "acme/web" })) + .with( + "api.github.com/repos/acme/web/collaborators*", + laravel::http::client::response().status(502).json(json!({})), + ); + assert!(app::forge::webhooks::recheck(&github_app(), &[ada_id]).await.is_err()); + let role: Option = + db::query!("SELECT role FROM memberships WHERE organization_id = {org} AND user_id = {ada_id}") + .scalar() + .await?; + assert_eq!(role.as_deref(), Some("member"), "a partial answer drops nobody"); + Ok(()) +} + +#[laravel::test(app = github)] +async fn a_renamed_repository_moves_its_links_and_edits_say_whether_it_is_private( + app: Application, +) -> laravel::Result<()> { + let (_, by_id, by_url) = linked().await?; + let events = laravel::event::fake(); + let renamed = json!({ "action": "renamed", "repository": { "id": 42, "full_name": "acme/website" } }); + deliver(&app, "repository", renamed).await.assert_ok().assert_json_path("moved", 1); + let url: Option = db::query!("SELECT repository_url FROM projects WHERE id = {by_id}").scalar().await?; + assert_eq!(url.as_deref(), Some("https://github.com/acme/website")); + // A delivery naming the ID backfills a link that only had the URL + let edited = json!({ "action": "edited", "repository": { "id": 77, "full_name": "acme/web", "private": true } }); + deliver(&app, "repository", edited).await.assert_ok(); + events.assert_dispatched_where::(|e| { + e.project_id == by_url && e.private + }); + let id: Option = db::query!("SELECT repository_id FROM projects WHERE id = {by_url}") + .scalar::>() + .await? + .flatten(); + assert_eq!(id.as_deref(), Some("77")); + Ok(()) +} From 8e6de5823a50cc6c1e6351660869d9c0a2cb9700 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 05:00:09 +1300 Subject: [PATCH 04/20] Rebased on main: Cargo.lock resolved from main's, and the boot checks and dependencies merged --- app/src/forge/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/forge/mod.rs b/app/src/forge/mod.rs index 445cc127..d0f62216 100644 --- a/app/src/forge/mod.rs +++ b/app/src/forge/mod.rs @@ -4,8 +4,8 @@ pub mod events; pub mod github; -pub mod gitlab; pub mod github_app; +pub mod gitlab; pub mod webhooks; use crate::auth::Role; From 0602d4bf66fae03effde270be41b6a12ed0bd75f Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 10:16:14 +1300 Subject: [PATCH 05/20] Rebased on main: Cargo.lock resolved from main's, and the boot checks and dependencies merged --- app/src/lib.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/app/src/lib.rs b/app/src/lib.rs index 0c90496c..fbc672a8 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -70,7 +70,6 @@ pub fn configure() -> ApplicationBuilder { // MCP clients: a person's OAuth token (the guard joins with the OAuth server, #57) or a personal // or project token. route.any("/mcp", mcp::handle); - route.post("/webhooks/github", forge::webhooks::github); // GitHub sends deliveries of up to 25 MB route .post("/webhooks/github", forge::webhooks::github) From 1c1902cc1c56f9599da10104f7e329745ef289ff Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 10:48:44 +1300 Subject: [PATCH 06/20] Rebased on main: Cargo.lock resolved from main's, and the boot checks and dependencies merged --- app/Cargo.lock | 196 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 194 insertions(+), 2 deletions(-) diff --git a/app/Cargo.lock b/app/Cargo.lock index 352842da..9c6367a1 100644 --- a/app/Cargo.lock +++ b/app/Cargo.lock @@ -286,6 +286,12 @@ version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + [[package]] name = "bcrypt" version = "0.19.3" @@ -617,6 +623,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + [[package]] name = "const-oid" version = "0.10.3" @@ -833,6 +845,17 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid 0.9.6", + "pem-rfc7468", + "zeroize", +] + [[package]] name = "deranged" version = "0.5.9" @@ -852,6 +875,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer 0.10.4", + "const-oid 0.9.6", "crypto-common 0.1.6", "subtle", ] @@ -863,7 +887,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ "block-buffer 0.12.1", - "const-oid", + "const-oid 0.10.3", "crypto-common 0.2.2", "ctutils", ] @@ -1993,6 +2017,21 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "jsonwebtoken" +version = "9.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde" +dependencies = [ + "base64 0.22.1", + "js-sys", + "pem", + "ring", + "serde", + "serde_json", + "simple_asn1", +] + [[package]] name = "laravel-rust" version = "0.1.4" @@ -2586,6 +2625,9 @@ name = "lazy_static" version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +dependencies = [ + "spin", +] [[package]] name = "libc" @@ -2868,6 +2910,22 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-bigint-dig" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" +dependencies = [ + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand 0.8.8", + "smallvec", + "zeroize", +] + [[package]] name = "num-conv" version = "0.2.2" @@ -2883,6 +2941,16 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -2890,6 +2958,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", + "libm", ] [[package]] @@ -3043,6 +3112,25 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" +[[package]] +name = "pem" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" +dependencies = [ + "base64 0.22.1", + "serde_core", +] + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -3055,6 +3143,27 @@ version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" +[[package]] +name = "pkcs1" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der", + "pkcs8", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + [[package]] name = "pkg-config" version = "0.3.34" @@ -3234,13 +3343,23 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + [[package]] name = "rand" version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" dependencies = [ - "rand_chacha", + "rand_chacha 0.9.0", "rand_core 0.9.5", ] @@ -3255,6 +3374,16 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + [[package]] name = "rand_chacha" version = "0.9.0" @@ -3265,6 +3394,15 @@ dependencies = [ "rand_core 0.9.5", ] +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + [[package]] name = "rand_core" version = "0.9.5" @@ -3496,6 +3634,26 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "rsa" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +dependencies = [ + "const-oid 0.9.6", + "digest 0.10.7", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core 0.6.4", + "signature", + "spki", + "subtle", + "zeroize", +] + [[package]] name = "rustc-demangle" version = "0.1.28" @@ -3871,6 +4029,16 @@ dependencies = [ "libc", ] +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest 0.10.7", + "rand_core 0.6.4", +] + [[package]] name = "simd-adler32" version = "0.3.10" @@ -3899,6 +4067,18 @@ version = "2.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" +[[package]] +name = "simple_asn1" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d" +dependencies = [ + "num-bigint 0.4.8", + "num-traits", + "thiserror", + "time", +] + [[package]] name = "slab" version = "0.4.12" @@ -3950,6 +4130,16 @@ dependencies = [ "lock_api", ] +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "sqlx" version = "0.9.1" @@ -4735,12 +4925,14 @@ dependencies = [ "hmac 0.12.1", "image", "include_dir", + "jsonwebtoken", "laravel-rust", "oauth-provider", "oauth-provider-laravel", "regex", "reqwest 0.12.28", "rmcp", + "rsa", "rusty-s3", "schemars", "serde", From 023e802d3ab92cbe2e8ec90d97dd9d113cf4d07e Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 03:48:47 +1300 Subject: [PATCH 07/20] app/: live updates' transport (sc-8897, sc-8900): Postgres LISTEN/NOTIFY on one channel, one listener per process (started by the first subscriber, reconnecting with backoff) fanning topics out to subscribers; notify() is delivered on commit; topics only say 'look again', so a missed one costs a moment and payloads carry no data; CheckLive notifies itself every minute and pushes VISUALCI_LIVE_HEARTBEAT only when it arrives --- app/Cargo.lock | 1 + app/Cargo.toml | 1 + app/src/lib.rs | 1 + app/src/live.rs | 121 ++++++++++++++++++++++++++++++++++++++++++++++ app/tests/live.rs | 39 +++++++++++++++ 5 files changed, 163 insertions(+) create mode 100644 app/src/live.rs create mode 100644 app/tests/live.rs diff --git a/app/Cargo.lock b/app/Cargo.lock index 9c6367a1..6591b927 100644 --- a/app/Cargo.lock +++ b/app/Cargo.lock @@ -4939,6 +4939,7 @@ dependencies = [ "serde_json", "sha2 0.10.9", "snapshot-diff", + "sqlx", "tokio", "tower", "tracing", diff --git a/app/Cargo.toml b/app/Cargo.toml index c1bfe12a..55389479 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -41,6 +41,7 @@ reqwest = { version = "0.12", default-features = false, features = ["json", "rus rusty-s3 = "0.12" globset = "0.4" schemars = "1" +sqlx = { version = "0.9", default-features = false, features = ["runtime-tokio", "tls-rustls-ring", "postgres"] } tracing = "0.1" include_dir = "0.7" rmcp = { version = "3.12", features = ["server", "transport-streamable-http-server", "macros"] } diff --git a/app/src/lib.rs b/app/src/lib.rs index fbc672a8..08147654 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -12,6 +12,7 @@ pub mod http; pub mod jobs; pub mod listeners; pub mod mcp; +pub mod live; pub mod models; pub mod notify; #[path = "../database/seeders/mod.rs"] diff --git a/app/src/live.rs b/app/src/live.rs new file mode 100644 index 00000000..0f597056 --- /dev/null +++ b/app/src/live.rs @@ -0,0 +1,121 @@ +//! Live updates between replicas (sc-8897, sc-8900): Postgres LISTEN/NOTIFY, fanned out in each process to whoever is +//! streaming server-sent events (`EventStream`) to a browser or the CLI's `--wait`. No WebSockets and no broadcaster +//! service: the database every replica already shares carries the signal. +//! +//! - [`notify`] sends a topic, such as `build:42`. Inside a transaction, Postgres delivers it on commit, so nobody is +//! told about a change they can't read yet. +//! - [`subscribe`] gets every topic sent from now on, from any replica. One connection per process LISTENs; it starts +//! with the first subscriber and reconnects by itself after an error. +//! - A notification only says "look again": the stream's handler reads the current state, so a missed one costs a +//! moment, never a wrong answer, and payloads never carry data a subscriber mightn't be allowed to see. +//! +//! [`CheckLive`] sends itself a notification every minute and pushes `VISUALCI_LIVE_HEARTBEAT` only when it arrives, +//! so a listener that's connected but deaf fails the heartbeat. + +use std::sync::OnceLock; +use std::time::Duration; + +use laravel::db; +use laravel::queue::{Queueable, job}; +use laravel::schedule::{self, Schedule}; +use tokio::sync::broadcast; + +/// The one Postgres channel; topics travel as its payloads. +pub const CHANNEL: &str = "visualci_live"; + +/// Where the listener connects: the application's database. +#[derive(Clone, laravel::config::Section)] +pub struct LiveDatabase { + #[env("DATABASE_URL")] + pub url: Option, +} + +/// Tell every replica's subscribers that `topic` changed (`build:42`, `project:7`). On commit, inside a transaction. +/// +/// # Errors +/// On a database error. +pub async fn notify(topic: &str) -> laravel::Result<()> { + db::query!("SELECT pg_notify({CHANNEL}, {topic})").statement().await?; + Ok(()) +} + +static HUB: OnceLock> = OnceLock::new(); + +/// Every topic sent from now on. The first call starts this process's listener on `database_url`. +pub fn subscribe(database_url: &str) -> broadcast::Receiver { + HUB.get_or_init(|| { + let (tx, _) = broadcast::channel(1024); + tokio::spawn(listen(database_url.to_string(), tx.clone())); + tx + }) + .subscribe() +} + +/// LISTEN, forwarding each payload; on any error wait a moment and connect again, for as long as the process runs. +async fn listen(url: String, tx: broadcast::Sender) { + let mut wait = Duration::from_millis(500); + loop { + match sqlx::postgres::PgListener::connect(&url).await { + Ok(mut listener) => match listener.listen(CHANNEL).await { + Ok(()) => { + wait = Duration::from_millis(500); + loop { + match listener.recv().await { + // No subscribers right now is fine: `send` only fails then + Ok(n) => drop(tx.send(n.payload().to_string())), + Err(e) => { + tracing::warn!(error = %e, "live updates: the listener lost its connection"); + break; + } + } + } + } + Err(e) => tracing::warn!(error = %e, "live updates: LISTEN failed"), + }, + Err(e) => tracing::warn!(error = %e, "live updates: can't connect"), + } + tokio::time::sleep(wait).await; + wait = (wait * 2).min(Duration::from_secs(30)); + } +} + +/// Wait up to `within` for `topic` on `rx`, skipping others. `false` when it doesn't come (or the hub closed). +pub async fn arrives(rx: &mut broadcast::Receiver, topic: &str, within: Duration) -> bool { + tokio::time::timeout(within, async { + loop { + match rx.recv().await { + Ok(t) if t == topic => return true, + Ok(_) | Err(broadcast::error::RecvError::Lagged(_)) => {} + Err(broadcast::error::RecvError::Closed) => return false, + } + } + }) + .await + .unwrap_or(false) +} + +/// Every minute: notify a probe topic and check this process's listener hears it, then push the heartbeat. +#[derive(Queueable, Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct CheckLive; + +#[job] +impl CheckLive { + async fn handle(self, database: laravel::config::Section) -> laravel::Result<()> { + let Some(url) = database.url.as_deref().filter(|u| !u.is_empty()) else { return Ok(()) }; + let mut rx = subscribe(url); + let probe = format!("probe:{}", laravel::str::random(12)); + let sent = notify(&probe).await; + let health = match sent { + Err(e) => Err(e.to_string()), + Ok(()) if arrives(&mut rx, &probe, Duration::from_secs(10)).await => Ok(()), + Ok(()) => Err("a notification didn't arrive within 10 seconds".to_string()), + }; + crate::heartbeat::push("VISUALCI_LIVE_HEARTBEAT", health.clone()).await; + health.map_err(laravel::Error::msg) + } +} + +#[schedule::tasks] +fn schedule(schedule: &mut Schedule) { + schedule.job(CheckLive).every_minute().without_overlapping(); +} diff --git a/app/tests/live.rs b/app/tests/live.rs new file mode 100644 index 00000000..b96a544f --- /dev/null +++ b/app/tests/live.rs @@ -0,0 +1,39 @@ +//! Live updates: a topic notified from any connection reaches every subscriber in this process, and only once it's +//! committed. Run against the database itself, outside a test's rolled-back transaction, where NOTIFY never arrives. + +use std::time::Duration; + +use sqlx::Connection; + +/// The test server's `postgres` database: LISTEN and NOTIFY only need both sides on one database, and the tests' own +/// databases are per-test copies. +fn database() -> String { + let url = std::env::var("VISUALCI_APP_TEST_DATABASE_URL") + .unwrap_or_else(|_| "postgres://loco:loco@127.0.0.1:55433/visualci_app_test".to_string()); + let server = url.rsplit_once('/').map_or(url.as_str(), |(server, _)| server); + format!("{server}/postgres") +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_committed_notification_reaches_subscribers() { + let url = database(); + let mut rx = app::live::subscribe(&url); + let mut other = sqlx::PgConnection::connect(&url).await.expect("the test database"); + // Give the listener a moment to LISTEN before anything is sent + let mut tries = 0; + loop { + sqlx::query("SELECT pg_notify($1, 'probe:ready')").bind(app::live::CHANNEL).execute(&mut other).await.unwrap(); + if app::live::arrives(&mut rx, "probe:ready", Duration::from_millis(500)).await { + break; + } + tries += 1; + assert!(tries < 20, "the listener never started"); + } + + // Inside a transaction: nothing until it commits + let mut tx = other.begin().await.unwrap(); + sqlx::query("SELECT pg_notify($1, 'build:42')").bind(app::live::CHANNEL).execute(&mut *tx).await.unwrap(); + assert!(!app::live::arrives(&mut rx, "build:42", Duration::from_millis(300)).await, "not before the commit"); + tx.commit().await.unwrap(); + assert!(app::live::arrives(&mut rx, "build:42", Duration::from_secs(5)).await, "after the commit"); +} From 9be528424fbfeae41e1c7cd4cf0485ff33dac265 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 04:25:42 +1300 Subject: [PATCH 08/20] Live updates, review fixes: the listener uses try_recv, and after each fresh LISTEN and each silent reconnect tells subscribers to re-read everything (*), as they must on Lagged too; every process probes its own listener each minute over a separate connection and restarts it when the probe doesn't come back in ten seconds (a half-open connection), with live::healthy() for its health check; the queue worker's heartbeat waits for the listener to be ready before probing; topics are capped well under Postgres's 8000 bytes; documented: LISTEN needs a direct or session-mode connection, not a transaction-mode PgBouncer --- app/src/live.rs | 161 ++++++++++++++++++++++++++++++++++++++-------- app/tests/live.rs | 13 +--- 2 files changed, 136 insertions(+), 38 deletions(-) diff --git a/app/src/live.rs b/app/src/live.rs index 0f597056..e12b3d12 100644 --- a/app/src/live.rs +++ b/app/src/live.rs @@ -5,23 +5,38 @@ //! - [`notify`] sends a topic, such as `build:42`. Inside a transaction, Postgres delivers it on commit, so nobody is //! told about a change they can't read yet. //! - [`subscribe`] gets every topic sent from now on, from any replica. One connection per process LISTENs; it starts -//! with the first subscriber and reconnects by itself after an error. -//! - A notification only says "look again": the stream's handler reads the current state, so a missed one costs a -//! moment, never a wrong answer, and payloads never carry data a subscriber mightn't be allowed to see. +//! with the first subscriber. +//! - A notification only says "look again": the stream's handler reads the current state, so payloads never carry data +//! a subscriber mightn't be allowed to see. Whenever notifications may have been missed, subscribers get +//! [`EVERYTHING`] and must re-read everything they show: after the listener (re)connects, and when a subscriber falls +//! behind (`RecvError::Lagged`). +//! - Each process checks its own listener every minute: it notifies a probe topic over a separate connection and, when +//! the probe doesn't come back within ten seconds (a half-open connection that hears nothing), restarts the listener. +//! [`healthy`] says whether the last probe came back, for the process's health check; [`CheckLive`] pushes +//! `VISUALCI_LIVE_HEARTBEAT` from the queue worker the same way. //! -//! [`CheckLive`] sends itself a notification every minute and pushes `VISUALCI_LIVE_HEARTBEAT` only when it arrives, -//! so a listener that's connected but deaf fails the heartbeat. +//! The connection must reach Postgres directly or through a session-mode pooler: LISTEN doesn't work through a +//! transaction-mode PgBouncer. use std::sync::OnceLock; +use std::sync::atomic::{AtomicI64, Ordering}; use std::time::Duration; use laravel::db; use laravel::queue::{Queueable, job}; use laravel::schedule::{self, Schedule}; -use tokio::sync::broadcast; +use sqlx::Connection; +use tokio::sync::{broadcast, watch}; /// The one Postgres channel; topics travel as its payloads. pub const CHANNEL: &str = "visualci_live"; +/// What subscribers get when they may have missed something: re-read everything. +pub const EVERYTHING: &str = "*"; +/// Postgres refuses payloads of 8000 bytes or more; topics are far shorter. +pub const MAX_TOPIC: usize = 1000; +/// How often each process probes its listener, and how long a probe may take. +const PROBE_EVERY: Duration = Duration::from_secs(60); +const PROBE_WITHIN: Duration = Duration::from_secs(10); /// Where the listener connects: the application's database. #[derive(Clone, laravel::config::Section)] @@ -33,52 +48,138 @@ pub struct LiveDatabase { /// Tell every replica's subscribers that `topic` changed (`build:42`, `project:7`). On commit, inside a transaction. /// /// # Errors -/// On a database error. +/// On a database error, or a topic longer than [`MAX_TOPIC`]. pub async fn notify(topic: &str) -> laravel::Result<()> { + if topic.len() > MAX_TOPIC { + return Err(laravel::Error::msg(format!("a live topic of {} bytes; topics name what changed", topic.len()))); + } db::query!("SELECT pg_notify({CHANNEL}, {topic})").statement().await?; Ok(()) } -static HUB: OnceLock> = OnceLock::new(); +struct Hub { + tx: broadcast::Sender, + ready: watch::Receiver, +} -/// Every topic sent from now on. The first call starts this process's listener on `database_url`. -pub fn subscribe(database_url: &str) -> broadcast::Receiver { +static HUB: OnceLock = OnceLock::new(); +/// When this process's last probe came back (Unix seconds); 0 before the first. +static LAST_PROBE_OK: AtomicI64 = AtomicI64::new(0); + +fn hub(database_url: &str) -> &'static Hub { HUB.get_or_init(|| { let (tx, _) = broadcast::channel(1024); - tokio::spawn(listen(database_url.to_string(), tx.clone())); - tx + let (ready_tx, ready) = watch::channel(false); + tokio::spawn(supervise(database_url.to_string(), tx.clone(), ready_tx)); + Hub { tx, ready } }) - .subscribe() } -/// LISTEN, forwarding each payload; on any error wait a moment and connect again, for as long as the process runs. -async fn listen(url: String, tx: broadcast::Sender) { +/// Every topic sent from now on. The first call starts this process's listener on `database_url`. +pub fn subscribe(database_url: &str) -> broadcast::Receiver { + hub(database_url).tx.subscribe() +} + +/// Wait up to `within` for this process's listener to be LISTENing. `false` when it isn't by then. +pub async fn ready(database_url: &str, within: Duration) -> bool { + let mut ready = hub(database_url).ready.clone(); + tokio::time::timeout(within, ready.wait_for(|r| *r)).await.is_ok_and(|r| r.is_ok()) +} + +/// Whether this process's listener answered its last probe within the last three minutes. +#[must_use] +pub fn healthy() -> bool { + let last = LAST_PROBE_OK.load(Ordering::Relaxed); + last > 0 && laravel::now().timestamp().as_second() - last < 180 +} + +/// Keep a listener running, restarting it when it stops or when a probe doesn't come back. +async fn supervise(url: String, tx: broadcast::Sender, ready: watch::Sender) { + loop { + let listener = tokio::spawn(listen(url.clone(), tx.clone(), ready.clone())); + let mut probes = tokio::time::interval(PROBE_EVERY); + probes.tick().await; + loop { + probes.tick().await; + if listener.is_finished() { + break; + } + if probe(&url, &tx).await { + LAST_PROBE_OK.store(laravel::now().timestamp().as_second(), Ordering::Relaxed); + } else { + tracing::warn!("live updates: a probe didn't come back; restarting the listener"); + break; + } + } + listener.abort(); + let _ = ready.send(false); + tokio::time::sleep(Duration::from_secs(1)).await; + } +} + +/// LISTEN, forwarding each payload. Tells subscribers to re-read everything after each (re)connection, since +/// notifications sent meanwhile are gone. Returns when the connection can't be used; `supervise` starts it again. +async fn listen(url: String, tx: broadcast::Sender, ready: watch::Sender) { let mut wait = Duration::from_millis(500); loop { - match sqlx::postgres::PgListener::connect(&url).await { + let connected = match sqlx::postgres::PgListener::connect(&url).await { Ok(mut listener) => match listener.listen(CHANNEL).await { Ok(()) => { wait = Duration::from_millis(500); + let _ = ready.send(true); + let _ = tx.send(EVERYTHING.to_string()); loop { - match listener.recv().await { + match listener.try_recv().await { // No subscribers right now is fine: `send` only fails then - Ok(n) => drop(tx.send(n.payload().to_string())), + Ok(Some(n)) => drop(tx.send(n.payload().to_string())), + // The connection dropped and sqlx reconnected and LISTENs again: anything sent in between + // is lost + Ok(None) => drop(tx.send(EVERYTHING.to_string())), Err(e) => { - tracing::warn!(error = %e, "live updates: the listener lost its connection"); + tracing::warn!(error = %e, "live updates: the listener failed"); break; } } } + true + } + Err(e) => { + tracing::warn!(error = %e, "live updates: LISTEN failed"); + false } - Err(e) => tracing::warn!(error = %e, "live updates: LISTEN failed"), }, - Err(e) => tracing::warn!(error = %e, "live updates: can't connect"), + Err(e) => { + tracing::warn!(error = %e, "live updates: can't connect"); + false + } + }; + let _ = ready.send(false); + if connected { + return; } tokio::time::sleep(wait).await; wait = (wait * 2).min(Duration::from_secs(30)); } } +/// Notify a fresh probe topic over a connection of its own and wait for this process's listener to hear it. +async fn probe(url: &str, tx: &broadcast::Sender) -> bool { + let mut rx = tx.subscribe(); + let topic = format!("probe:{}", laravel::str::random(12)); + let sent = async { + let mut connection = sqlx::PgConnection::connect(url).await?; + sqlx::query("SELECT pg_notify($1, $2)").bind(CHANNEL).bind(&topic).execute(&mut connection).await?; + connection.close().await + }; + match sent.await { + Ok(()) => arrives(&mut rx, &topic, PROBE_WITHIN).await, + Err(e) => { + tracing::warn!(error = %e, "live updates: the probe couldn't be sent"); + false + } + } +} + /// Wait up to `within` for `topic` on `rx`, skipping others. `false` when it doesn't come (or the hub closed). pub async fn arrives(rx: &mut broadcast::Receiver, topic: &str, within: Duration) -> bool { tokio::time::timeout(within, async { @@ -94,7 +195,8 @@ pub async fn arrives(rx: &mut broadcast::Receiver, topic: &str, within: .unwrap_or(false) } -/// Every minute: notify a probe topic and check this process's listener hears it, then push the heartbeat. +/// Every minute in the queue worker: wait for its listener to be ready, notify a probe topic through the application's +/// database, check the listener hears it, and push the heartbeat. #[derive(Queueable, Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct CheckLive; @@ -103,12 +205,15 @@ impl CheckLive { async fn handle(self, database: laravel::config::Section) -> laravel::Result<()> { let Some(url) = database.url.as_deref().filter(|u| !u.is_empty()) else { return Ok(()) }; let mut rx = subscribe(url); - let probe = format!("probe:{}", laravel::str::random(12)); - let sent = notify(&probe).await; - let health = match sent { - Err(e) => Err(e.to_string()), - Ok(()) if arrives(&mut rx, &probe, Duration::from_secs(10)).await => Ok(()), - Ok(()) => Err("a notification didn't arrive within 10 seconds".to_string()), + let health = if ready(url, PROBE_WITHIN).await { + let probe = format!("probe:{}", laravel::str::random(12)); + match notify(&probe).await { + Err(e) => Err(e.to_string()), + Ok(()) if arrives(&mut rx, &probe, PROBE_WITHIN).await => Ok(()), + Ok(()) => Err("a notification didn't arrive within 10 seconds".to_string()), + } + } else { + Err("the listener isn't LISTENing".to_string()) }; crate::heartbeat::push("VISUALCI_LIVE_HEARTBEAT", health.clone()).await; health.map_err(laravel::Error::msg) diff --git a/app/tests/live.rs b/app/tests/live.rs index b96a544f..594e5e06 100644 --- a/app/tests/live.rs +++ b/app/tests/live.rs @@ -18,17 +18,10 @@ fn database() -> String { async fn a_committed_notification_reaches_subscribers() { let url = database(); let mut rx = app::live::subscribe(&url); + assert!(app::live::ready(&url, Duration::from_secs(10)).await, "the listener LISTENs"); + // Connecting tells subscribers to re-read everything, since anything sent before is gone + assert!(app::live::arrives(&mut rx, app::live::EVERYTHING, Duration::from_secs(5)).await); let mut other = sqlx::PgConnection::connect(&url).await.expect("the test database"); - // Give the listener a moment to LISTEN before anything is sent - let mut tries = 0; - loop { - sqlx::query("SELECT pg_notify($1, 'probe:ready')").bind(app::live::CHANNEL).execute(&mut other).await.unwrap(); - if app::live::arrives(&mut rx, "probe:ready", Duration::from_millis(500)).await { - break; - } - tries += 1; - assert!(tries < 20, "the listener never started"); - } // Inside a transaction: nothing until it commits let mut tx = other.begin().await.unwrap(); From 5daabb6d61ff6ef355e9e21758cf168795caaa49 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 10:23:07 +1300 Subject: [PATCH 09/20] Rebased on main: Cargo.lock resolved from main's, and the boot checks and dependencies merged --- app/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/lib.rs b/app/src/lib.rs index 08147654..77b131e4 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -11,8 +11,8 @@ pub mod heartbeat; pub mod http; pub mod jobs; pub mod listeners; -pub mod mcp; pub mod live; +pub mod mcp; pub mod models; pub mod notify; #[path = "../database/seeders/mod.rs"] From 43de774a7a7cea1174e7937cca9b3211477f32a7 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 03:50:30 +1300 Subject: [PATCH 10/20] app/: the hourly forge sync for GitHub (sc-8900): everyone with a GitHub identity is rechecked through the App, so access lost without a webhook goes within the hour; people GitHub can't answer for keep their memberships (synced_at ages) and fail VISUALCI_FORGE_SYNC_HEARTBEAT, as does a run that can't read the database --- app/src/forge/mod.rs | 1 + app/src/forge/sync.rs | 76 +++++++++++++++++++++++++++++++++++++++++ app/tests/forge_sync.rs | 48 ++++++++++++++++++++++++++ 3 files changed, 125 insertions(+) create mode 100644 app/src/forge/sync.rs create mode 100644 app/tests/forge_sync.rs diff --git a/app/src/forge/mod.rs b/app/src/forge/mod.rs index d0f62216..f4472364 100644 --- a/app/src/forge/mod.rs +++ b/app/src/forge/mod.rs @@ -6,6 +6,7 @@ pub mod events; pub mod github; pub mod github_app; pub mod gitlab; +pub mod sync; pub mod webhooks; use crate::auth::Role; diff --git a/app/src/forge/sync.rs b/app/src/forge/sync.rs new file mode 100644 index 00000000..f0f3850a --- /dev/null +++ b/app/src/forge/sync.rs @@ -0,0 +1,76 @@ +//! The hourly forge sync (sc-8900, the forge side), ported from today's `forge:sync` for GitHub: everyone with a +//! GitHub identity is rechecked through the App, so access lost without a webhook goes within the hour. People GitHub +//! can't answer for are left as they were (their memberships' `synced_at` ages) and fail the run's heartbeat, +//! `VISUALCI_FORGE_SYNC_HEARTBEAT`, as does a run that can't read the database. Self-managed GitLab instances, their +//! webhooks and the bot token's expiry come with sc-8634; rechecking repositories' visibility and closing deleted +//! branches' builds are the domain's. + +use laravel::db; +use laravel::queue::{Queueable, job}; +use laravel::schedule::{self, Schedule}; + +use super::github_app::GithubApp; +use super::webhooks::recheck; + +/// What a run did. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct Synced { + pub people: usize, + pub changed: usize, + pub failed: usize, +} + +/// Recheck everyone with a GitHub identity. +/// +/// # Errors +/// When the database can't be read; one person GitHub can't answer for is counted in `failed` instead. +pub async fn sync_github(app: &GithubApp) -> laravel::Result { + let people: Vec = db::query!("SELECT DISTINCT user_id FROM identities WHERE forge = 'github' AND site = ''") + .select() + .await? + .iter() + .map(|r| r.try_get("user_id")) + .collect::>()?; + let mut synced = Synced { people: people.len(), ..Synced::default() }; + for user_id in people { + match recheck(app, user_id).await { + Ok(n) => synced.changed += n, + Err(e) => { + synced.failed += 1; + tracing::warn!(user_id, error = %e, "forge sync failed for one person"); + } + } + } + Ok(synced) +} + +/// The hourly run. Without the GitHub App configured there's nothing to check, and the heartbeat says so plainly. +#[derive(Queueable, Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct SyncForges; + +#[job] +impl SyncForges { + async fn handle(self, app: laravel::config::Section) -> laravel::Result<()> { + if app.app_id.as_deref().is_none_or(str::is_empty) { + return Ok(()); + } + let result = sync_github(&app).await; + let health = match &result { + Err(e) => Err(e.to_string()), + Ok(s) if s.failed > 0 => { + Err(format!("{} of {} people couldn't be checked; see the log", s.failed, s.people)) + } + Ok(s) => { + tracing::info!(people = s.people, changed = s.changed, "forge sync"); + Ok(()) + } + }; + crate::heartbeat::push("VISUALCI_FORGE_SYNC_HEARTBEAT", health).await; + result.map(|_| ()) + } +} + +#[schedule::tasks] +fn schedule(schedule: &mut Schedule) { + schedule.job(SyncForges).hourly().without_overlapping(); +} diff --git a/app/tests/forge_sync.rs b/app/tests/forge_sync.rs new file mode 100644 index 00000000..2bc30cac --- /dev/null +++ b/app/tests/forge_sync.rs @@ -0,0 +1,48 @@ +//! The hourly sync rechecks everyone with a GitHub identity: a membership GitHub no longer grants (here, its +//! organization's repository was unlinked) goes, one made by an invitation stays. + +use app::forge::github_app::GithubApp; +use app::forge::sync::{Synced, sync_github}; +use app::models::User; +use laravel::db; +use laravel::model::create; +use laravel::testing::prelude::*; + +#[laravel::test] +async fn access_github_no_longer_grants_goes_within_the_hour(_app: Application) -> laravel::Result<()> { + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let ada_id = ada.id; + db::query!( + "INSERT INTO identities (user_id, forge, site, forge_user_id, login, created_at, updated_at) \ + VALUES ({ada_id}, 'github', '', '1001', 'ada', now(), now())" + ) + .insert() + .await?; + let mut orgs = Vec::new(); + for (slug, source) in [("acme", "github"), ("invited", "invite")] { + let org: i64 = db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) \ + VALUES (gen_random_uuid(), {slug}, {slug}, now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org}, {ada_id}, 'member', {source}, now(), now())" + ) + .insert() + .await?; + orgs.push(org); + } + let app = GithubApp { app_id: Some("1".into()), private_key_base64: None, webhook_secret: None }; + assert_eq!(sync_github(&app).await?, Synced { people: 1, changed: 1, failed: 0 }); + let left: Vec = db::query!("SELECT organization_id FROM memberships WHERE user_id = {ada_id}") + .select() + .await? + .iter() + .map(|r| r.try_get("organization_id")) + .collect::>()?; + assert_eq!(left, vec![orgs[1]], "the invited membership stays"); + Ok(()) +} From 9c63eb9c342c27e88bb8438affb60549de376847 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 04:28:25 +1300 Subject: [PATCH 11/20] Forge sync, review fixes: one listing of each linked repository's collaborators (webhooks::reach) rechecks everyone, and recheck_links unlinks projects whose linker no longer maintains the repository or whose repository the App can't see (no more checks and comments from someone who lost access); links without GitHub's repository ID get it first; nothing changes unless GitHub answered for every repository, and a low rate limit defers the run without failing the heartbeat; an unconfigured App fails the heartbeat plainly --- app/src/forge/github_app.rs | 14 ++++ app/src/forge/sync.rs | 127 +++++++++++++++++++++++++++++------- app/src/forge/webhooks.rs | 89 +++++++++++++++++-------- app/tests/forge_sync.rs | 62 +++++++++++++++++- 4 files changed, 239 insertions(+), 53 deletions(-) diff --git a/app/src/forge/github_app.rs b/app/src/forge/github_app.rs index 9da5047a..5606a429 100644 --- a/app/src/forge/github_app.rs +++ b/app/src/forge/github_app.rs @@ -160,6 +160,20 @@ pub async fn repository_path(token: &str, id: &str) -> laravel::Result laravel::Result> { + Ok(get(token, &format!("/repos/{repo}")).await?.and_then(|v| v["id"].as_i64().map(|i| i.to_string()))) +} + +/// Whether an error is GitHub's rate limit running low ([`collaborators`]): the work waits for the next run. +#[must_use] +pub fn rate_limited(e: &laravel::Error) -> bool { + e.to_string().contains("the rate limit is down") +} + /// GitHub's role name for a collaborator (`admin`, `maintain`, `write`, `triage`, `read`). fn permission_from(role: &str) -> Option { match role { diff --git a/app/src/forge/sync.rs b/app/src/forge/sync.rs index f0f3850a..640decf9 100644 --- a/app/src/forge/sync.rs +++ b/app/src/forge/sync.rs @@ -1,50 +1,124 @@ -//! The hourly forge sync (sc-8900, the forge side), ported from today's `forge:sync` for GitHub: everyone with a -//! GitHub identity is rechecked through the App, so access lost without a webhook goes within the hour. People GitHub -//! can't answer for are left as they were (their memberships' `synced_at` ages) and fail the run's heartbeat, -//! `VISUALCI_FORGE_SYNC_HEARTBEAT`, as does a run that can't read the database. Self-managed GitLab instances, their -//! webhooks and the bot token's expiry come with sc-8634; rechecking repositories' visibility and closing deleted -//! branches' builds are the domain's. +//! The hourly forge sync (sc-8900, the forge side), ported from today's `forge:sync` for GitHub: +//! +//! - links made before VisualCI stored GitHub's repository ID get it; +//! - every linked repository's collaborators are listed once ([`webhooks::reach`]) and everyone with a GitHub identity +//! is rechecked from that, so access lost without a webhook goes within the hour; +//! - a project whose linker no longer maintains its repository (or whose repository the App can't see) is unlinked, so +//! someone who lost access doesn't keep posting checks and comments through the App. +//! +//! Nothing changes unless GitHub answered for every repository. When its rate limit runs low the run stops and the +//! next one picks up; that isn't a failure. `VISUALCI_FORGE_SYNC_HEARTBEAT` fails when GitHub or the database can't +//! answer, and when the App isn't configured. Self-managed GitLab (sc-8634), the daily open-source recheck and closing +//! deleted branches' builds follow in their own PRs. use laravel::db; use laravel::queue::{Queueable, job}; use laravel::schedule::{self, Schedule}; -use super::github_app::GithubApp; -use super::webhooks::recheck; +use super::Permission; +use super::github_app::{self, GithubApp}; +use super::webhooks::{self, Reach}; /// What a run did. #[derive(Debug, Default, PartialEq, Eq)] pub struct Synced { pub people: usize, pub changed: usize, - pub failed: usize, + pub unlinked: usize, + /// GitHub's rate limit ran low: nothing changed, the next run tries again. + pub deferred: bool, } -/// Recheck everyone with a GitHub identity. +/// Run the sync for GitHub. /// /// # Errors -/// When the database can't be read; one person GitHub can't answer for is counted in `failed` instead. +/// 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 { + 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() }), + Err(e) => return Err(e), + }; + let reach = match webhooks::reach(app).await { + Ok(reach) => reach, + Err(e) if github_app::rate_limited(&e) => return Ok(Synced { deferred: true, ..Synced::default() }), + Err(e) => return Err(e), + }; let people: Vec = db::query!("SELECT DISTINCT user_id FROM identities WHERE forge = 'github' AND site = ''") .select() .await? .iter() .map(|r| r.try_get("user_id")) .collect::>()?; - let mut synced = Synced { people: people.len(), ..Synced::default() }; - for user_id in people { - match recheck(app, user_id).await { - Ok(n) => synced.changed += n, - Err(e) => { - synced.failed += 1; - tracing::warn!(user_id, error = %e, "forge sync failed for one person"); + let changed = webhooks::apply_reach(&reach, &people).await?; + let unlinked = recheck_links(&reach, &unseen).await?; + Ok(Synced { people: people.len(), changed, unlinked, deferred: false }) +} + +/// Give links without GitHub's repository ID their ID. Returns the projects whose repository the App can't see. +async fn backfill_ids(app: &GithubApp) -> laravel::Result> { + let rows = db::query!( + "SELECT id, repository_url, forge_installation FROM projects \ + WHERE forge = 'github' AND repository_id IS NULL AND repository_url IS NOT NULL \ + AND forge_installation IS NOT NULL" + ) + .select() + .await?; + let mut unseen = Vec::new(); + for r in rows { + let (id, url, installation): (i64, String, String) = + (r.try_get("id")?, r.try_get("repository_url")?, r.try_get("forge_installation")?); + let Some(repository) = super::Repository::parse(&url) else { continue }; + let token = github_app::installation_token(app, &installation).await?; + match github_app::repository_id(&token, &repository.path).await? { + Some(repository_id) => { + db::query!("UPDATE projects SET repository_id = {repository_id}, updated_at = now() WHERE id = {id}") + .update() + .await?; } + None => unseen.push(id), + } + } + Ok(unseen) +} + +/// Unlink projects whose linker no longer has Maintain or Admin on the repository, or whose repository the App can't +/// see. Returns how many. +async fn recheck_links(reach: &Reach, unseen: &[i64]) -> laravel::Result { + let rows = db::query!( + "SELECT p.id, p.repository_id, i.forge_user_id FROM projects p \ + LEFT JOIN identities i ON i.user_id = p.linked_by AND i.forge = 'github' AND i.site = '' \ + WHERE p.forge = 'github' AND p.forge_installation IS NOT NULL AND p.linked_by IS NOT NULL" + ) + .select() + .await?; + let mut lost: Vec = unseen.to_vec(); + for r in rows { + let (id, repository_id, linker): (i64, Option, Option) = + (r.try_get("id")?, r.try_get("repository_id")?, r.try_get("forge_user_id")?); + let Some(repository_id) = repository_id else { continue }; + let permission = linker + .as_ref() + .and_then(|linker| reach.repositories.get(&repository_id).and_then(|people| people.get(linker))); + if !permission.is_some_and(|p| *p >= Permission::Maintain) { + lost.push(id); } } - Ok(synced) + lost.sort_unstable(); + lost.dedup(); + for &id in &lost { + tracing::info!(project_id = id, "unlinked: its linker lost access, or the App can't see the repository"); + db::query!( + "UPDATE projects SET forge_installation = NULL, forge_token_enc = NULL, forge_webhook_at = NULL, \ + linked_by = NULL, updated_at = now() WHERE id = {id}" + ) + .update() + .await?; + } + Ok(lost.len()) } -/// The hourly run. Without the GitHub App configured there's nothing to check, and the heartbeat says so plainly. +/// The hourly run. #[derive(Queueable, Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct SyncForges; @@ -52,16 +126,21 @@ pub struct SyncForges; impl SyncForges { async fn handle(self, app: laravel::config::Section) -> laravel::Result<()> { if app.app_id.as_deref().is_none_or(str::is_empty) { + let health = Err("the GitHub App isn't configured (GITHUB_APP_ID), so nobody's access is rechecked".into()); + crate::heartbeat::push("VISUALCI_FORGE_SYNC_HEARTBEAT", health).await; return Ok(()); } let result = sync_github(&app).await; let health = match &result { Err(e) => Err(e.to_string()), - Ok(s) if s.failed > 0 => { - Err(format!("{} of {} people couldn't be checked; see the log", s.failed, s.people)) - } Ok(s) => { - tracing::info!(people = s.people, changed = s.changed, "forge sync"); + tracing::info!( + people = s.people, + changed = s.changed, + unlinked = s.unlinked, + deferred = s.deferred, + "forge sync" + ); Ok(()) } }; diff --git a/app/src/forge/webhooks.rs b/app/src/forge/webhooks.rs index 35d0d3a2..930e2229 100644 --- a/app/src/forge/webhooks.rs +++ b/app/src/forge/webhooks.rs @@ -399,29 +399,23 @@ impl RecheckAccess { } } -/// Recheck people's memberships: each linked repository's collaborators are listed once (one installation token per -/// installation, its path looked up by GitHub's ID so a rename can't mislead it), and each person's permission on each -/// decides their role in its organization, as a sign-in does (`auth::memberships::apply`). Nobody's memberships change -/// unless every repository was read: a list that failed part-way would drop people. Returns how many changed. +/// Who can reach each linked GitHub repository, from one listing of its collaborators. +#[derive(Debug, Default)] +pub struct Reach { + /// GitHub user ID -> the repositories they're a collaborator on, with their permission. + pub people: HashMap>, + /// GitHub repository ID -> GitHub user ID -> permission. A repository the App can't see any more has no entry. + pub repositories: HashMap>, +} + +/// List every linked repository's collaborators once: one installation token per installation, each repository's +/// path looked up by GitHub's ID so a rename can't mislead it. A repository the installation can't see any more +/// gives nobody anything. /// /// # Errors -/// When GitHub can't answer for some repository (or its rate limit is low), or on a database error. -pub async fn recheck(app: &GithubApp, user_ids: &[i64]) -> laravel::Result { - let mut github_ids: HashMap = HashMap::new(); - for &user_id in user_ids { - if let Some(id) = db::query!( - "SELECT forge_user_id FROM identities WHERE user_id = {user_id} AND forge = 'github' AND site = '' \ - ORDER BY id LIMIT 1" - ) - .scalar::() - .await? - { - github_ids.insert(user_id, id); - } - } - if github_ids.is_empty() { - return Ok(0); - } +/// When GitHub can't answer for some repository (a partial answer would drop people), when its rate limit is low, or +/// on a database error. +pub async fn reach(app: &GithubApp) -> laravel::Result { let rows = db::query!( "SELECT DISTINCT repository_id, forge_installation FROM projects \ WHERE forge = 'github' AND repository_id IS NOT NULL AND forge_installation IS NOT NULL" @@ -429,8 +423,7 @@ pub async fn recheck(app: &GithubApp, user_ids: &[i64]) -> laravel::Result = HashMap::new(); - // GitHub user ID -> [(repository, permission)] - let mut reach: HashMap> = HashMap::new(); + let mut reach = Reach::default(); for r in rows { let (repository_id, installation): (String, String) = (r.try_get("repository_id")?, r.try_get("forge_installation")?); @@ -442,18 +435,58 @@ pub async fn recheck(app: &GithubApp, user_ids: &[i64]) -> laravel::Result laravel::Result> { + let mut ids = HashMap::new(); + for &user_id in user_ids { + if let Some(id) = db::query!( + "SELECT forge_user_id FROM identities WHERE user_id = {user_id} AND forge = 'github' AND site = '' \ + ORDER BY id LIMIT 1" + ) + .scalar::() + .await? + { + ids.insert(user_id, id); + } + } + Ok(ids) +} + +/// Apply what `reach` found to these people's memberships, as a sign-in does (`auth::memberships::apply`). Returns +/// how many changed. +/// +/// # Errors +/// On a database error. +pub async fn apply_reach(reach: &Reach, user_ids: &[i64]) -> laravel::Result { let mut changed = 0; - for (user_id, github_id) in github_ids { - let list = reach.remove(&github_id).unwrap_or_default(); + for (user_id, github_id) in github_ids(user_ids).await? { + let list = reach.people.get(&github_id).cloned().unwrap_or_default(); changed += crate::auth::memberships::apply(user_id, ForgeKind::Github, "", &list).await?; } Ok(changed) } + +/// Recheck people's memberships from GitHub through the App: [`reach`], then [`apply_reach`]. Nobody's memberships +/// change unless every repository was read. Returns how many changed. +/// +/// # Errors +/// When GitHub can't answer for some repository (or its rate limit is low), or on a database error. +pub async fn recheck(app: &GithubApp, user_ids: &[i64]) -> laravel::Result { + if github_ids(user_ids).await?.is_empty() { + return Ok(0); + } + let reach = reach(app).await?; + apply_reach(&reach, user_ids).await +} diff --git a/app/tests/forge_sync.rs b/app/tests/forge_sync.rs index 2bc30cac..2108fefe 100644 --- a/app/tests/forge_sync.rs +++ b/app/tests/forge_sync.rs @@ -36,7 +36,7 @@ async fn access_github_no_longer_grants_goes_within_the_hour(_app: Application) orgs.push(org); } let app = GithubApp { app_id: Some("1".into()), private_key_base64: None, webhook_secret: None }; - assert_eq!(sync_github(&app).await?, Synced { people: 1, changed: 1, failed: 0 }); + assert_eq!(sync_github(&app).await?, Synced { people: 1, changed: 1, unlinked: 0, deferred: false }); let left: Vec = db::query!("SELECT organization_id FROM memberships WHERE user_id = {ada_id}") .select() .await? @@ -46,3 +46,63 @@ async fn access_github_no_longer_grants_goes_within_the_hour(_app: Application) assert_eq!(left, vec![orgs[1]], "the invited membership stays"); Ok(()) } + +/// A GitHub App key made once per run (base64 of its PEM). +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()) + }) +} + +/// Someone who linked a repository and is now only a writer on it: the link goes, so checks and comments stop. +#[laravel::test] +async fn a_link_whose_linker_lost_maintain_is_removed(_app: Application) -> laravel::Result<()> { + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let ada_id = ada.id; + db::query!( + "INSERT INTO identities (user_id, forge, site, forge_user_id, login, created_at, updated_at) \ + VALUES ({ada_id}, 'github', '', '1001', 'ada', now(), now())" + ) + .insert() + .await?; + let org: i64 = db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) \ + VALUES (gen_random_uuid(), 'acme', 'Acme', now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + let project: i64 = db::query!( + "INSERT INTO projects (pid, organization_id, slug, name, forge, repository_url, repository_id, \ + forge_installation, linked_by, created_at, updated_at) \ + VALUES (gen_random_uuid(), {org}, 'web', 'Web', 'github', 'https://github.com/acme/web', '42', '7', \ + {ada_id}, now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + let _github = laravel::http::client::fake() + .with("api.github.com/app/installations/7/access_tokens", json!({ "token": "t" })) + .with("api.github.com/repositories/42", json!({ "full_name": "acme/web" })) + .with("api.github.com/repos/acme/web/collaborators*", json!([{ "id": 1001, "role_name": "write" }])); + let app = GithubApp { app_id: Some("1".into()), private_key_base64: Some(app_key().into()), webhook_secret: None }; + let synced = sync_github(&app).await?; + assert_eq!(synced.unlinked, 1); + let installation: Option = db::query!("SELECT forge_installation FROM projects WHERE id = {project}") + .scalar::>() + .await? + .flatten(); + assert_eq!(installation, None); + // Her write access still makes her a member + let role: Option = + db::query!("SELECT role FROM memberships WHERE organization_id = {org} AND user_id = {ada_id}") + .scalar() + .await?; + assert_eq!(role.as_deref(), Some("member")); + Ok(()) +} From 43b0b80b9b3e78520997c2e5058701993b9a4ad4 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 04:32:18 +1300 Subject: [PATCH 12/20] app/: open source checks (sc-8619, sc-8900, forge side, ported from today's open_source.rs): GitHub's word on a repository's visibility and licence decides whether a project may be public and draws from the open source pool; a repository gone private makes its public project private (a notice, the admins emailed), a project that stops qualifying leaves a billing notice and emails the billing contact; the repository webhook applies changes at once (RepositoryVisibilityChanged), and the hourly sync checks each linked project once a day in an hour of its own --- app/src/forge/github_app.rs | 9 ++ app/src/forge/mod.rs | 1 + app/src/forge/open_source.rs | 289 +++++++++++++++++++++++++++++++++++ app/src/forge/sync.rs | 15 +- app/tests/forge_sync.rs | 48 +++++- 5 files changed, 358 insertions(+), 4 deletions(-) create mode 100644 app/src/forge/open_source.rs diff --git a/app/src/forge/github_app.rs b/app/src/forge/github_app.rs index 5606a429..5ea74ac1 100644 --- a/app/src/forge/github_app.rs +++ b/app/src/forge/github_app.rs @@ -160,6 +160,15 @@ pub async fn repository_path(token: &str, id: &str) -> laravel::Result laravel::Result> { + get(token, &format!("/repos/{repo}")).await +} + /// A repository's permanent ID, by its path (`None` when the installation can't see it). /// /// # Errors diff --git a/app/src/forge/mod.rs b/app/src/forge/mod.rs index f4472364..0d8113fd 100644 --- a/app/src/forge/mod.rs +++ b/app/src/forge/mod.rs @@ -6,6 +6,7 @@ pub mod events; pub mod github; pub mod github_app; pub mod gitlab; +pub mod open_source; pub mod sync; pub mod webhooks; diff --git a/app/src/forge/open_source.rs b/app/src/forge/open_source.rs new file mode 100644 index 00000000..9ac5ae12 --- /dev/null +++ b/app/src/forge/open_source.rs @@ -0,0 +1,289 @@ +//! What GitHub says about a project's repository (sc-8619; sc-8900, the forge side, ported from today's server), and +//! what follows from it: +//! +//! - Only a project whose repository is public can be public here: a private repository's screenshots stay private. +//! When a public project's repository goes private (or VisualCI can't see it), the project is made private, with a +//! notice for its members and an email to its admins. +//! - A public repository with an OSI-approved licence is open source; while the project is also public here, its +//! builds draw from the organization's open source pool (the domain's credits read `projects.open_source`). One +//! that stops qualifying uses the plan's credits from then on, with a notice on the billing page and an email. +//! +//! GitHub's `repository` webhook applies a change at once ([`visibility_changed`]), and every linked project is +//! checked again once a day, in an hour of its own so the checks spread over the day ([`recheck_due`], from the +//! hourly sync). When GitHub doesn't answer, nothing changes. Self-managed GitLab instances follow with sc-8634. + +use laravel::db; +use laravel::event::{Event, listener}; +use serde_json::Value; + +use super::Repository; +use super::events::RepositoryVisibilityChanged; +use super::github_app::{self, GithubApp}; +use crate::notify::{self, Kind, To}; + +/// OSI-approved licences, by the SPDX ids GitHub reports (the common ones; GitHub names only licences it recognises). +pub const OSI_LICENCES: &[&str] = &[ + "0BSD", + "AFL-3.0", + "AGPL-3.0", + "AGPL-3.0-only", + "AGPL-3.0-or-later", + "Apache-2.0", + "Artistic-2.0", + "BSD-2-Clause", + "BSD-3-Clause", + "BSD-3-Clause-Clear", + "BSD-4-Clause", + "BSL-1.0", + "CECILL-2.1", + "ECL-2.0", + "EPL-1.0", + "EPL-2.0", + "EUPL-1.1", + "EUPL-1.2", + "GPL-2.0", + "GPL-2.0-only", + "GPL-2.0-or-later", + "GPL-3.0", + "GPL-3.0-only", + "GPL-3.0-or-later", + "ISC", + "LGPL-2.1", + "LGPL-2.1-only", + "LGPL-2.1-or-later", + "LGPL-3.0", + "LGPL-3.0-only", + "LGPL-3.0-or-later", + "LPPL-1.3c", + "MIT", + "MIT-0", + "MPL-2.0", + "MS-PL", + "MS-RL", + "MulanPSL-2.0", + "NCSA", + "OFL-1.1", + "OSL-3.0", + "PostgreSQL", + "UPL-1.0", + "Unlicense", + "Zlib", +]; + +/// What a check found: whether the repository is public, whether the project is open source, and why not (or its +/// licence when it is). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Status { + pub repository_public: bool, + pub open_source: bool, + pub note: String, +} + +impl Status { + fn no(repository_public: bool, note: impl Into) -> Self { + Self { repository_public, open_source: false, note: note.into() } + } + + /// What GitHub's answer about a repository (`GET /repos/{path}`) means for a project. + #[must_use] + pub fn of(repo: &Value) -> Self { + let public = repo["private"] == false && repo["visibility"].as_str().is_none_or(|s| s == "public"); + if !public { + return Self::no(false, "Its repository is private."); + } + match repo["license"]["spdx_id"].as_str() { + Some(l) if OSI_LICENCES.contains(&l) => { + Self { repository_public: true, open_source: true, note: format!("Public, {l}.") } + } + Some("NOASSERTION") => Self::no(true, "Its forge can't tell which licence its repository has."), + Some(l) => Self::no(true, format!("Its licence ({l}) isn't OSI-approved.")), + None => Self::no(true, "Its repository has no licence its forge recognises."), + } + } +} + +/// A project as a check needs it. +struct Project { + id: i64, + organization_id: i64, + slug: String, + public: bool, + counts: bool, + repository_url: Option, + repository_id: Option, + installation: Option, +} + +async fn project(id: i64) -> laravel::Result> { + let Some(r) = db::query!( + "SELECT id, organization_id, slug, public, repository_url, repository_id, forge_installation, \ + (open_source AND public AND NOT open_source_withdrawn) AS counts \ + FROM projects WHERE id = {id} AND (forge = 'github' OR forge IS NULL)" + ) + .select_one() + .await? + else { + return Ok(None); + }; + Ok(Some(Project { + id: r.try_get("id")?, + organization_id: r.try_get("organization_id")?, + slug: r.try_get("slug")?, + public: r.try_get("public")?, + counts: r.try_get("counts")?, + repository_url: r.try_get("repository_url")?, + repository_id: r.try_get("repository_id")?, + installation: r.try_get("forge_installation")?, + })) +} + +/// Ask GitHub about a project's repository. `None` when GitHub couldn't answer: the project keeps what it had. +async fn check(app: &GithubApp, p: &Project) -> Option { + let Some(url) = p.repository_url.as_deref() else { + return Some(Status::no(false, "It isn't linked to a repository.")); + }; + let Some(installation) = p.installation.as_deref() else { + return Some(Status::no(false, "VisualCI's app or bot doesn't have access to its repository.")); + }; + let answer = async { + let token = github_app::installation_token(app, installation).await?; + // By GitHub's ID when known, so a rename can't mislead it + let path = match p.repository_id.as_deref() { + Some(id) => github_app::repository_path(&token, id).await?, + None => Repository::parse(url).map(|r| r.path), + }; + match path { + Some(path) => github_app::repository(&token, &path).await, + None => Ok(None), + } + }; + match answer.await { + Ok(Some(repo)) => Some(Status::of(&repo)), + Ok(None) => Some(Status::no(false, "VisualCI can't see its repository.")), + Err(e) => { + tracing::warn!(project_id = p.id, error = %e, "couldn't check a project's repository"); + None + } + } +} + +/// Record a check, and tell the organization what changed: a public project whose repository isn't public any more +/// is made private (a notice on the project, an email to its admins); one that was drawing from the pool and stops +/// qualifying leaves a notice on the billing page and emails the billing contact. Returns whether it changed either. +/// +/// # Errors +/// On a database error. +async fn record(p: &Project, status: &Status) -> laravel::Result { + let made_private = p.public && !status.repository_public; + let lost_pool = p.counts && !status.open_source && !made_private; + let (id, public, open_source, note) = (p.id, status.repository_public, status.open_source, status.note.clone()); + let notice = made_private.then(|| match p.repository_url { + Some(_) => format!("The repository for {} is private now, so its builds are no longer public.", p.slug), + None => format!("{} isn't linked to a repository now, so its builds are no longer public.", p.slug), + }); + db::query!( + "UPDATE projects SET repository_public = {public}, repository_checked_at = now(), open_source = {open_source}, \ + open_source_note = {note}, public = public AND NOT {made_private}, notice = COALESCE({notice}, notice), \ + updated_at = now() WHERE id = {id}" + ) + .update() + .await?; + let org = p.organization_id; + let now = laravel::now().timestamp().as_second(); + if made_private { + tracing::info!(project_id = id, note = status.note, "project made private: its repository isn't public"); + let kind = Kind::MadePrivate { project: p.slug.clone() }; + notify::queue(&kind, To::Admins(org), None, &format!("made_private:{id}:{now}")).await?; + } else if lost_pool { + let problem = format!( + "{} is no longer an open source project: {} Its builds use the plan's credits from now on.", + p.slug, status.note + ); + db::query!("UPDATE organizations SET billing_problem = {problem}, updated_at = now() WHERE id = {org}") + .update() + .await?; + tracing::info!(project_id = id, note = status.note, "project no longer open source"); + let kind = Kind::OpenSourceLost { project: p.slug.clone(), reason: status.note.clone() }; + notify::queue(&kind, To::Billing(org), None, &format!("open_source_lost:{id}:{now}")).await?; + } + Ok(made_private || lost_pool) +} + +/// Check one project and record the result. Returns whether it was made private or stopped being open source. +/// +/// # Errors +/// On a database error. +pub async fn refresh(app: &GithubApp, project_id: i64) -> laravel::Result { + let Some(p) = project(project_id).await? else { return Ok(false) }; + match check(app, &p).await { + Some(status) => record(&p, &status).await, + None => Ok(false), + } +} + +/// GitHub's `repository` webhook: made private (GitHub's word is enough), or made public or edited (asked again). +#[listener] +pub async fn visibility_changed( + event: Event, + app: laravel::config::Section, +) -> laravel::Result<()> { + if event.private { + if let Some(p) = project(event.project_id).await? { + record(&p, &Status::no(false, "Its repository is private.")).await?; + } + } else { + refresh(&app, event.project_id).await?; + } + Ok(()) +} + +/// Projects checked once a day: the hour (UTC) a project is due in, from its id, so the checks spread over the day. +const HOURS: i64 = 24; + +/// The hourly sync's part: check the projects due now (linked to a repository, or still marked open source or +/// public, in this hour's share and not checked in the last hour, or not checked for over a day). Returns how many +/// were made private or stopped being open source. +/// +/// # Errors +/// On a database error. +pub async fn recheck_due(app: &GithubApp) -> laravel::Result { + let hour = laravel::now().timestamp().as_second().div_euclid(3600).rem_euclid(HOURS); + let (day, share) = (HOURS + 1, HOURS); + let due: Vec = db::query!( + "SELECT id FROM projects WHERE (forge = 'github' OR forge IS NULL) \ + AND (repository_url IS NOT NULL OR open_source OR repository_public) \ + AND (repository_checked_at IS NULL \ + OR repository_checked_at < now() - make_interval(hours => {day}::int) \ + OR (id % {share} = {hour} AND repository_checked_at < now() - interval '1 hour'))" + ) + .select() + .await? + .iter() + .map(|r| r.try_get("id")) + .collect::>()?; + let mut changed = 0; + for id in due { + changed += usize::from(refresh(app, id).await?); + } + Ok(changed) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn a_public_repository_with_an_osi_licence_is_open_source() { + let s = Status::of(&json!({ "private": false, "visibility": "public", "license": { "spdx_id": "MIT" } })); + assert!(s.repository_public && s.open_source); + let s = Status::of(&json!({ "private": false, "license": { "spdx_id": "BUSL-1.1" } })); + assert!(s.repository_public && !s.open_source && s.note.contains("BUSL-1.1")); + let s = Status::of(&json!({ "private": false, "license": null })); + assert!(!s.open_source); + let s = Status::of(&json!({ "private": true, "license": { "spdx_id": "MIT" } })); + assert!(!s.repository_public && !s.open_source); + let s = Status::of(&json!({ "private": false, "visibility": "internal" })); + assert!(!s.repository_public); + } +} diff --git a/app/src/forge/sync.rs b/app/src/forge/sync.rs index 640decf9..129a22b6 100644 --- a/app/src/forge/sync.rs +++ b/app/src/forge/sync.rs @@ -8,8 +8,8 @@ //! //! Nothing changes unless GitHub answered for every repository. When its rate limit runs low the run stops and the //! next one picks up; that isn't a failure. `VISUALCI_FORGE_SYNC_HEARTBEAT` fails when GitHub or the database can't -//! answer, and when the App isn't configured. Self-managed GitLab (sc-8634), the daily open-source recheck and closing -//! deleted branches' builds follow in their own PRs. +//! answer, and when the App isn't configured. Each linked repository's visibility and licence are checked once a day per project +//! (`open_source::recheck_due`). Self-managed GitLab (sc-8634) and closing deleted branches' builds follow. use laravel::db; use laravel::queue::{Queueable, job}; @@ -25,6 +25,8 @@ pub struct Synced { pub people: usize, pub changed: usize, pub unlinked: usize, + /// Projects made private, or no longer open source, by the daily recheck. + pub open_source: usize, /// GitHub's rate limit ran low: nothing changed, the next run tries again. pub deferred: bool, } @@ -52,7 +54,13 @@ pub async fn sync_github(app: &GithubApp) -> laravel::Result { .collect::>()?; let changed = webhooks::apply_reach(&reach, &people).await?; let unlinked = recheck_links(&reach, &unseen).await?; - Ok(Synced { people: people.len(), changed, unlinked, deferred: false }) + // 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 { + Ok(n) => n, + Err(e) if github_app::rate_limited(&e) => 0, + Err(e) => return Err(e), + }; + Ok(Synced { people: people.len(), changed, unlinked, open_source, deferred: false }) } /// Give links without GitHub's repository ID their ID. Returns the projects whose repository the App can't see. @@ -138,6 +146,7 @@ impl SyncForges { people = s.people, changed = s.changed, unlinked = s.unlinked, + open_source = s.open_source, deferred = s.deferred, "forge sync" ); diff --git a/app/tests/forge_sync.rs b/app/tests/forge_sync.rs index 2108fefe..63f9c55e 100644 --- a/app/tests/forge_sync.rs +++ b/app/tests/forge_sync.rs @@ -36,7 +36,10 @@ async fn access_github_no_longer_grants_goes_within_the_hour(_app: Application) orgs.push(org); } let app = GithubApp { app_id: Some("1".into()), private_key_base64: None, webhook_secret: None }; - assert_eq!(sync_github(&app).await?, Synced { people: 1, changed: 1, unlinked: 0, deferred: false }); + assert_eq!( + sync_github(&app).await?, + Synced { people: 1, changed: 1, unlinked: 0, open_source: 0, deferred: false } + ); let left: Vec = db::query!("SELECT organization_id FROM memberships WHERE user_id = {ada_id}") .select() .await? @@ -106,3 +109,46 @@ async fn a_link_whose_linker_lost_maintain_is_removed(_app: Application) -> lara assert_eq!(role.as_deref(), Some("member")); Ok(()) } + +/// GitHub says a public project's repository went private: the project is made private at once, with a notice on it +/// and an email to its admins. +#[laravel::test] +async fn a_repository_gone_private_makes_its_project_private(_app: Application) -> laravel::Result<()> { + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let ada_id = ada.id; + let org: i64 = db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) \ + VALUES (gen_random_uuid(), 'acme', 'Acme', now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org}, {ada_id}, 'admin', 'created', now(), now())" + ) + .insert() + .await?; + let project: i64 = db::query!( + "INSERT INTO projects (pid, organization_id, slug, name, forge, repository_url, repository_id, \ + forge_installation, public, repository_public, open_source, created_at, updated_at) \ + VALUES (gen_random_uuid(), {org}, 'web', 'Web', 'github', 'https://github.com/acme/web', '42', '7', \ + true, true, true, now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + app::forge::events::RepositoryVisibilityChanged { project_id: project, private: true }.dispatch().await?; + let row = db::query!("SELECT public, open_source, notice FROM projects WHERE id = {project}") + .select_one() + .await? + .unwrap(); + assert!(!row.try_get::("public")? && !row.try_get::("open_source")?); + assert!(row.try_get::>("notice")?.unwrap_or_default().contains("private now")); + let emails: Option = + db::query!("SELECT count(*) FROM emails WHERE kind = 'made_private' AND recipient = 'ada@example.com'") + .scalar() + .await?; + assert_eq!(emails, Some(1)); + Ok(()) +} From 9259ce584e97661d51293613c082d46abb7f5fa9 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 04:33:28 +1300 Subject: [PATCH 13/20] app/: the hourly sync closes deleted branches' waiting builds (sc-8797, ported): GitHub doesn't send a branch deletion without a pull request (the App has no Contents permission), so each branch with CI builds waiting for review is asked about once a day (500 a run), and a gone one gets BranchClosed { why: branch_deleted }, which the domain handles --- app/src/forge/github_app.rs | 21 ++++++++++ app/src/forge/sync.rs | 76 ++++++++++++++++++++++++++++++++++++- app/tests/forge_sync.rs | 48 ++++++++++++++++++++++- 3 files changed, 142 insertions(+), 3 deletions(-) diff --git a/app/src/forge/github_app.rs b/app/src/forge/github_app.rs index 5ea74ac1..301edf03 100644 --- a/app/src/forge/github_app.rs +++ b/app/src/forge/github_app.rs @@ -169,6 +169,27 @@ pub async fn repository(token: &str, repo: &str) -> laravel::Result laravel::Result> { + if get(token, &format!("/repos/{repo}")).await?.is_none() { + return Ok(None); + } + let branch: String = branch + .bytes() + .map(|b| { + if b.is_ascii_alphanumeric() || b"-._~".contains(&b) { + (b as char).to_string() + } else { + format!("%{b:02X}") + } + }) + .collect(); + Ok(Some(get(token, &format!("/repos/{repo}/branches/{branch}")).await?.is_some())) +} + /// A repository's permanent ID, by its path (`None` when the installation can't see it). /// /// # Errors diff --git a/app/src/forge/sync.rs b/app/src/forge/sync.rs index 129a22b6..cc211a16 100644 --- a/app/src/forge/sync.rs +++ b/app/src/forge/sync.rs @@ -9,7 +9,9 @@ //! Nothing changes unless GitHub answered for every repository. When its rate limit runs low the run stops and the //! next one picks up; that isn't a failure. `VISUALCI_FORGE_SYNC_HEARTBEAT` fails when GitHub or the database can't //! answer, and when the App isn't configured. Each linked repository's visibility and licence are checked once a day per project -//! (`open_source::recheck_due`). Self-managed GitLab (sc-8634) and closing deleted branches' builds follow. +//! (`open_source::recheck_due`). Branches deleted without a pull request (GitHub doesn't send that event: +//! the App has no Contents permission) are found by asking about each branch with builds waiting for review, once a +//! day, and closed through `BranchClosed` ([`close_deleted_branches`], sc-8797). Self-managed GitLab follows (sc-8634). use laravel::db; use laravel::queue::{Queueable, job}; @@ -27,6 +29,8 @@ pub struct Synced { pub unlinked: usize, /// Projects made private, or no longer open source, by the daily recheck. pub open_source: usize, + /// Branches found deleted, whose builds waiting for review were closed. + pub branches_closed: usize, /// GitHub's rate limit ran low: nothing changed, the next run tries again. pub deferred: bool, } @@ -60,7 +64,12 @@ pub async fn sync_github(app: &GithubApp) -> laravel::Result { Err(e) if github_app::rate_limited(&e) => 0, Err(e) => return Err(e), }; - Ok(Synced { people: people.len(), changed, unlinked, open_source, deferred: false }) + let branches_closed = match close_deleted_branches(app, 500).await { + Ok(n) => n, + Err(e) if github_app::rate_limited(&e) => 0, + Err(e) => return Err(e), + }; + Ok(Synced { people: people.len(), changed, unlinked, open_source, branches_closed, deferred: false }) } /// Give links without GitHub's repository ID their ID. Returns the projects whose repository the App can't see. @@ -126,6 +135,68 @@ async fn recheck_links(reach: &Reach, unseen: &[i64]) -> laravel::Result Ok(lost.len()) } +/// Ask GitHub about up to `limit` branches with CI builds waiting for review (not a fork's, not asked in the last +/// day), and close the ones that are gone through `BranchClosed { why: "branch_deleted" }`, which the domain handles. +/// Returns how many were gone. +/// +/// # Errors +/// When GitHub's rate limit is low, or on a database error; one branch GitHub can't answer for is skipped. +pub async fn close_deleted_branches(app: &GithubApp, limit: i64) -> laravel::Result { + let rows = db::query!( + "SELECT DISTINCT b.project_id, b.branch, p.repository_id, p.repository_url, p.forge_installation \ + FROM builds b JOIN projects p ON p.id = b.project_id \ + LEFT JOIN branch_checks c ON c.project_id = b.project_id AND c.branch = b.branch \ + WHERE b.review_state = 'pending' AND b.mode = 'ci' AND b.branch <> '' AND position(':' in b.branch) = 0 \ + AND p.forge = 'github' AND p.forge_installation IS NOT NULL \ + AND (c.checked_at IS NULL OR c.checked_at < now() - interval '1 day') \ + ORDER BY b.project_id, b.branch LIMIT {limit}" + ) + .select() + .await?; + let mut closed = 0; + let mut tokens: std::collections::HashMap = std::collections::HashMap::new(); + for r in rows { + let (project_id, branch, installation): (i64, String, String) = + (r.try_get("project_id")?, r.try_get("branch")?, r.try_get("forge_installation")?); + let (repository_id, url): (Option, Option) = + (r.try_get("repository_id")?, r.try_get("repository_url")?); + let token = match tokens.get(&installation) { + Some(t) => t.clone(), + None => { + let t = github_app::installation_token(app, &installation).await?; + tokens.insert(installation.clone(), t.clone()); + t + } + }; + let path = match repository_id.as_deref() { + Some(id) => github_app::repository_path(&token, id).await?, + None => url.as_deref().and_then(super::Repository::parse).map(|r| r.path), + }; + let Some(path) = path else { continue }; + match github_app::branch_exists(&token, &path, &branch).await { + Ok(Some(false)) => { + super::events::BranchClosed { project_id, branch: branch.clone(), why: "branch_deleted".into() } + .dispatch() + .await?; + closed += 1; + } + Ok(_) => {} + Err(e) if github_app::rate_limited(&e) => return Err(e), + Err(e) => { + tracing::warn!(error = %e, repo = path, branch, "asking whether a branch exists"); + continue; + } + } + db::query!( + "INSERT INTO branch_checks (project_id, branch, checked_at) VALUES ({project_id}, {branch}, now()) \ + ON CONFLICT (project_id, branch) DO UPDATE SET checked_at = now()" + ) + .statement() + .await?; + } + Ok(closed) +} + /// The hourly run. #[derive(Queueable, Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct SyncForges; @@ -147,6 +218,7 @@ impl SyncForges { changed = s.changed, unlinked = s.unlinked, open_source = s.open_source, + branches_closed = s.branches_closed, deferred = s.deferred, "forge sync" ); diff --git a/app/tests/forge_sync.rs b/app/tests/forge_sync.rs index 63f9c55e..29a4aada 100644 --- a/app/tests/forge_sync.rs +++ b/app/tests/forge_sync.rs @@ -38,7 +38,7 @@ async fn access_github_no_longer_grants_goes_within_the_hour(_app: Application) let app = GithubApp { app_id: Some("1".into()), private_key_base64: None, webhook_secret: None }; assert_eq!( sync_github(&app).await?, - Synced { people: 1, changed: 1, unlinked: 0, open_source: 0, deferred: false } + Synced { people: 1, changed: 1, unlinked: 0, open_source: 0, branches_closed: 0, deferred: false } ); let left: Vec = db::query!("SELECT organization_id FROM memberships WHERE user_id = {ada_id}") .select() @@ -152,3 +152,49 @@ async fn a_repository_gone_private_makes_its_project_private(_app: Application) assert_eq!(emails, Some(1)); Ok(()) } + +/// A branch deleted without a pull request (GitHub doesn't send that event): its builds waiting for review are closed +/// through BranchClosed, and it isn't asked about again for a day. +#[laravel::test] +async fn a_deleted_branchs_waiting_builds_are_closed(_app: Application) -> laravel::Result<()> { + let org: i64 = db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) \ + VALUES (gen_random_uuid(), 'acme', 'Acme', now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + let project: i64 = db::query!( + "INSERT INTO projects (pid, organization_id, slug, name, forge, repository_url, repository_id, \ + forge_installation, created_at, updated_at) \ + VALUES (gen_random_uuid(), {org}, 'web', 'Web', 'github', 'https://github.com/acme/web', '42', '7', \ + now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + for (number, branch) in [(1, "gone"), (2, "still-here")] { + db::query!( + "INSERT INTO builds (pid, project_id, number, commit_sha, branch, mode, review_state, created_at, updated_at) \ + VALUES (gen_random_uuid(), {project}, {number}, 'abc', {branch}, 'ci', 'pending', now(), now())" + ) + .insert() + .await?; + } + let events = laravel::event::fake(); + let _github = laravel::http::client::fake() + .with("api.github.com/app/installations/7/access_tokens", json!({ "token": "t" })) + .with("api.github.com/repositories/42", json!({ "full_name": "acme/web" })) + .with("api.github.com/repos/acme/web/branches/still-here", json!({ "name": "still-here" })) + .with("api.github.com/repos/acme/web/branches/*", laravel::http::client::response().status(404).json(json!({}))) + .with("api.github.com/repos/acme/web", json!({ "id": 42 })); + let app = GithubApp { app_id: Some("1".into()), private_key_base64: Some(app_key().into()), webhook_secret: None }; + assert_eq!(app::forge::sync::close_deleted_branches(&app, 500).await?, 1); + events.assert_dispatched_where::(|e| { + e.project_id == project && e.branch == "gone" && e.why == "branch_deleted" + }); + events.assert_dispatched_times::(1); + // Both were asked about today: neither again until tomorrow + assert_eq!(app::forge::sync::close_deleted_branches(&app, 500).await?, 0); + Ok(()) +} From e37e4d334c135f0c0a4e65c491d8c5fd2cc96ccd Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 03:57:22 +1300 Subject: [PATCH 14/20] app/: security headers on every response (sc-8900), as today's: nosniff, the referrer policy, no framing (DENY, over Laravel's SAMEORIGIN) and the Content-Security-Policy allowing only VisualCI's scripts, the built page's inline script hashes (VISUALCI_FRONTEND_DIR) and the analytics; x-powered-by dropped; the gallery's /g/ paths CORS and CORP cross-origin; outermost, so the host check's 404s carry them too --- app/src/http/mod.rs | 1 + app/src/http/security.rs | 143 +++++++++++++++++++++++++++++++++++++++ app/src/lib.rs | 2 + app/tests/hosts.rs | 17 +++++ 4 files changed, 163 insertions(+) create mode 100644 app/src/http/security.rs diff --git a/app/src/http/mod.rs b/app/src/http/mod.rs index 02b9ee67..0f6612f3 100644 --- a/app/src/http/mod.rs +++ b/app/src/http/mod.rs @@ -15,3 +15,4 @@ pub fn busy(e: &laravel::Error) -> bool { /// How long a client should wait before retrying a 503, in seconds. pub const RETRY_AFTER_SECONDS: u32 = 5; +pub mod security; diff --git a/app/src/http/security.rs b/app/src/http/security.rs new file mode 100644 index 00000000..78611456 --- /dev/null +++ b/app/src/http/security.rs @@ -0,0 +1,143 @@ +//! Security headers on every response (sc-8900, ported from today's server): `nosniff`, a referrer policy, no framing, +//! and a Content-Security-Policy that lets the app's pages run only VisualCI's own scripts (and Plausible's and +//! Cloudflare's analytics), so script injected into a page or served from the app's origin by mistake doesn't run. A +//! route that sets its own headers (the gallery's sandbox) keeps them, and the gallery's images may be embedded +//! anywhere (`/g/`: CORS and CORP cross-origin). +//! +//! The app's `index.html` has inline scripts (the theme, before the page draws; Plausible's queue in production). +//! Their SHA-256 hashes are read from the built page (`VISUALCI_FRONTEND_DIR`, default `frontend/dist`) the first +//! time a response goes out, so the policy always matches the page it's served with. There's no `form-action`: +//! Chrome applies it to every redirect after a form posts, which would block an MCP client's OAuth callback. + +use std::sync::OnceLock; + +use axum::http::{HeaderValue, header}; +use base64::Engine; +use laravel::http::{Next, Request, Response, middleware}; +use sha2::{Digest, Sha256}; + +/// Plausible, DocSpring's self-hosted analytics. +const ANALYTICS: &str = "https://pa.docspring.com"; +/// Cloudflare's Web Analytics beacon, which Cloudflare adds to pages it serves, and where it reports. +const CLOUDFLARE_SCRIPT: &str = "https://static.cloudflareinsights.com"; +const CLOUDFLARE_REPORT: &str = "https://cloudflareinsights.com"; + +static POLICY: OnceLock = OnceLock::new(); + +/// `'sha256-…'` for each inline `") else { break }; + if !tag.contains("src=") { + let body = &after[body_start..body_start + close]; + let digest = Sha256::digest(body.as_bytes()); + hashes.push(format!("'sha256-{}'", base64::engine::general_purpose::STANDARD.encode(digest))); + } + rest = &after[body_start + close + "".len()..]; + } + hashes +} + +/// The policy for a page whose inline scripts hash to `hashes`, with images also from `storage` (the bucket's public +/// origin, for a development server; production's is HTTPS, which `https:` covers). +#[must_use] +pub fn policy(hashes: &[String], storage: Option<&str>) -> String { + let scripts = std::iter::once("'self'".to_string()) + .chain([ANALYTICS.to_string(), CLOUDFLARE_SCRIPT.to_string()]) + .chain(hashes.iter().cloned()) + .collect::>() + .join(" "); + let images = ["'self'", "data:", "blob:", "https:"] + .into_iter() + .map(str::to_string) + .chain(storage.map(str::to_string)) + .collect::>() + .join(" "); + format!( + "default-src 'self'; script-src {scripts}; style-src 'self' 'unsafe-inline'; img-src {images}; \ + font-src 'self' data:; connect-src 'self' {ANALYTICS} {CLOUDFLARE_REPORT}; frame-src 'self'; object-src 'none'; \ + base-uri 'self'; frame-ancestors 'none'" + ) +} + +/// The built app and the storage's public endpoint, for the policy. +#[derive(Clone, laravel::config::Section)] +pub struct Frontend { + #[env("VISUALCI_FRONTEND_DIR", default = "frontend/dist")] + pub dir: String, + #[env("S3_PUBLIC_ENDPOINT")] + pub storage_endpoint: Option, +} + +/// An origin (`scheme://host[:port]`) from a URL. +fn origin(url: &str) -> Option { + let (scheme, rest) = url.trim().split_once("://")?; + let authority = rest.split('/').next().filter(|a| !a.is_empty())?; + Some(format!("{}://{}", scheme.to_ascii_lowercase(), authority.to_ascii_lowercase())) +} + +fn built_policy(frontend: &Frontend) -> HeaderValue { + let html = std::fs::read_to_string(std::path::Path::new(&frontend.dir).join("index.html")).unwrap_or_default(); + let storage = frontend.storage_endpoint.as_deref().and_then(origin); + HeaderValue::from_str(&policy(&inline_script_hashes(&html), storage.as_deref())) + .unwrap_or(HeaderValue::from_static("default-src 'self'")) +} + +/// Global middleware: adds the headers a response doesn't already have, and drops `x-powered-by`. +#[middleware] +pub async fn security_headers(frontend: laravel::config::Section, request: Request, next: Next) -> Response { + let gallery = request.path().starts_with("/g/"); + let mut response = next.run(request).await; + let h = response.headers_mut(); + h.remove("x-powered-by"); + if gallery { + h.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, HeaderValue::from_static("*")); + h.insert("cross-origin-resource-policy", HeaderValue::from_static("cross-origin")); + } + h.entry(header::X_CONTENT_TYPE_OPTIONS).or_insert(HeaderValue::from_static("nosniff")); + h.entry(header::REFERRER_POLICY).or_insert(HeaderValue::from_static("strict-origin-when-cross-origin")); + // Laravel's own default is SAMEORIGIN; VisualCI's pages are never framed (the policy's `frame-ancestors 'none'`) + h.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY")); + let policy = POLICY.get_or_init(|| built_policy(&frontend)); + h.entry(header::CONTENT_SECURITY_POLICY).or_insert(policy.clone()); + response +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hashes_only_inline_scripts() { + let html = r#" + "#; + let hashes = inline_script_hashes(html); + assert_eq!(hashes.len(), 2); + let expected = base64::engine::general_purpose::STANDARD.encode(Sha256::digest(b"var a = 1")); + assert_eq!(hashes[0], format!("'sha256-{expected}'")); + } + + #[test] + fn the_policy_allows_the_app_and_nothing_else() { + let p = policy(&["'sha256-abc'".into()], Some("http://docspring-dev.hs:5190")); + assert!( + p.contains( + "script-src 'self' https://pa.docspring.com https://static.cloudflareinsights.com 'sha256-abc';" + ), + "{p}" + ); + assert!(p.contains("img-src 'self' data: blob: https: http://docspring-dev.hs:5190;"), "{p}"); + assert!(p.contains("frame-ancestors 'none'")); + assert!(!p.contains("unsafe-eval") && !p.contains("form-action")); + assert_eq!(origin("http://Docspring-Dev.hs:5190/bucket").as_deref(), Some("http://docspring-dev.hs:5190")); + } +} diff --git a/app/src/lib.rs b/app/src/lib.rs index 77b131e4..99e18623 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -60,6 +60,8 @@ pub fn configure() -> ApplicationBuilder { // addresses (probes). `route_by_host` is the host check instead: each configured host reaches only its // own paths, and in production any other host only `/up` and the renderers' paths. middleware.trust_hosts(["*"]); + // Outermost, so every response gets the security headers, the host check's 404s included + middleware.prepend(http::security::security_headers); }) .with_routing(|routing, _| { routing diff --git a/app/tests/hosts.rs b/app/tests/hosts.rs index 20311864..2f49ab3c 100644 --- a/app/tests/hosts.rs +++ b/app/tests/hosts.rs @@ -140,3 +140,20 @@ async fn production_doesnt_boot_with_only_some_host_urls() { .create(); assert!(app.boot().await.is_err(), "the site's and MCP's paths would be on every host"); } + +#[laravel::test(app = hosts)] +async fn every_response_carries_the_security_headers(app: Application) { + let response = app.get("/api/v1/version").header("host", "api.visualci.test").await; + response + .assert_ok() + .assert_header("x-content-type-options", "nosniff") + .assert_header("x-frame-options", "DENY") + .assert_header("referrer-policy", "strict-origin-when-cross-origin") + .assert_header_contains("content-security-policy", "frame-ancestors 'none'"); + // A 404 from the host check too + app.get("/mcp") + .header("host", "app.visualci.test") + .await + .assert_status(404) + .assert_header("x-frame-options", "DENY"); +} From 7ee8a73f3b44fe544c1e9d6aaaea49cf3a526beb Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 04:10:03 +1300 Subject: [PATCH 15/20] Security headers, review fixes: the policy's hashes come from the page the server serves (public/index.html under the application's base path, the frontend in the same image), read once at boot; in production a missing page or one with no inline scripts stops the boot (the theme script would be blocked), elsewhere it's logged --- app/src/http/security.rs | 63 +++++++++++++++++++++++++++++++--------- app/src/lib.rs | 1 + 2 files changed, 51 insertions(+), 13 deletions(-) diff --git a/app/src/http/security.rs b/app/src/http/security.rs index 78611456..fc2d11c6 100644 --- a/app/src/http/security.rs +++ b/app/src/http/security.rs @@ -5,8 +5,10 @@ //! anywhere (`/g/`: CORS and CORP cross-origin). //! //! The app's `index.html` has inline scripts (the theme, before the page draws; Plausible's queue in production). -//! Their SHA-256 hashes are read from the built page (`VISUALCI_FRONTEND_DIR`, default `frontend/dist`) the first -//! time a response goes out, so the policy always matches the page it's served with. There's no `form-action`: +//! Their SHA-256 hashes are read at boot from the built page the server serves, `public/index.html` under the +//! application's base path (the frontend in the same image), so the policy always matches the page it's served with. +//! In production a page with no inline scripts (or none at all) stops the boot ([`check`]): the theme script would be +//! blocked. There's no `form-action`: //! Chrome applies it to every redirect after a form posts, which would block an MCP client's OAuth callback. use std::sync::OnceLock; @@ -67,11 +69,9 @@ pub fn policy(hashes: &[String], storage: Option<&str>) -> String { ) } -/// The built app and the storage's public endpoint, for the policy. +/// The storage's public endpoint, for the policy's images. #[derive(Clone, laravel::config::Section)] pub struct Frontend { - #[env("VISUALCI_FRONTEND_DIR", default = "frontend/dist")] - pub dir: String, #[env("S3_PUBLIC_ENDPOINT")] pub storage_endpoint: Option, } @@ -83,16 +83,40 @@ fn origin(url: &str) -> Option { Some(format!("{}://{}", scheme.to_ascii_lowercase(), authority.to_ascii_lowercase())) } -fn built_policy(frontend: &Frontend) -> HeaderValue { - let html = std::fs::read_to_string(std::path::Path::new(&frontend.dir).join("index.html")).unwrap_or_default(); - let storage = frontend.storage_endpoint.as_deref().and_then(origin); - HeaderValue::from_str(&policy(&inline_script_hashes(&html), storage.as_deref())) - .unwrap_or(HeaderValue::from_static("default-src 'self'")) +/// The policy for the page at `page`, or a message when it's missing or has no inline scripts to allow. +/// +/// # Errors +/// That message. +pub fn policy_for(page: &std::path::Path, storage: Option<&str>) -> Result { + let html = std::fs::read_to_string(page).unwrap_or_default(); + let hashes = inline_script_hashes(&html); + if hashes.is_empty() { + return Err(format!("{} has no inline scripts: the policy would block the theme script", page.display())); + } + Ok(policy(&hashes, storage)) +} + +/// Build the policy from the served page (`public/index.html` under the base path), once, at boot. +/// +/// # Errors +/// In production, when the page is missing or has no inline scripts to allow; elsewhere that's only logged. +pub fn check(config: &laravel::config::Config, production: bool) -> laravel::Result<()> { + let storage = config.section::().storage_endpoint.as_deref().and_then(origin); + let value = match policy_for(&config.app.public_path("index.html"), storage.as_deref()) { + Ok(p) => p, + Err(message) if production => return Err(laravel::Error::msg(message)), + Err(message) => { + tracing::warn!("{message}"); + policy(&[], storage.as_deref()) + } + }; + let _ = POLICY.set(HeaderValue::from_str(&value).unwrap_or(HeaderValue::from_static("default-src 'self'"))); + Ok(()) } /// Global middleware: adds the headers a response doesn't already have, and drops `x-powered-by`. #[middleware] -pub async fn security_headers(frontend: laravel::config::Section, request: Request, next: Next) -> Response { +pub async fn security_headers(request: Request, next: Next) -> Response { let gallery = request.path().starts_with("/g/"); let mut response = next.run(request).await; let h = response.headers_mut(); @@ -105,8 +129,8 @@ pub async fn security_headers(frontend: laravel::config::Section, requ h.entry(header::REFERRER_POLICY).or_insert(HeaderValue::from_static("strict-origin-when-cross-origin")); // Laravel's own default is SAMEORIGIN; VisualCI's pages are never framed (the policy's `frame-ancestors 'none'`) h.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY")); - let policy = POLICY.get_or_init(|| built_policy(&frontend)); - h.entry(header::CONTENT_SECURITY_POLICY).or_insert(policy.clone()); + let policy = POLICY.get().cloned().unwrap_or(HeaderValue::from_static("default-src 'self'")); + h.entry(header::CONTENT_SECURITY_POLICY).or_insert(policy); response } @@ -140,4 +164,17 @@ mod tests { assert!(!p.contains("unsafe-eval") && !p.contains("form-action")); assert_eq!(origin("http://Docspring-Dev.hs:5190/bucket").as_deref(), Some("http://docspring-dev.hs:5190")); } + + #[test] + fn a_page_without_inline_scripts_has_no_policy() { + assert!(policy_for(std::path::Path::new("/nonexistent/index.html"), None).is_err()); + let dir = std::env::temp_dir().join(format!("visualci-csp-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let page = dir.join("index.html"); + std::fs::write(&page, "").unwrap(); + assert!(policy_for(&page, None).is_err(), "only external scripts"); + std::fs::write(&page, "").unwrap(); + assert!(policy_for(&page, None).unwrap().contains("'sha256-")); + std::fs::remove_dir_all(&dir).unwrap(); + } } diff --git a/app/src/lib.rs b/app/src/lib.rs index 99e18623..d175eb15 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -47,6 +47,7 @@ pub fn configure() -> ApplicationBuilder { )?; http::hosts::check(config.section::(), config.app.env.is_production())?; billing::check(config.section::(), config.app.env.is_production())?; + http::security::check(config, config.app.env.is_production())?; Ok(()) }) .with_middleware(|middleware, _| { From 8c5718b3d75f0d2ef246f86c83be6d0dd316250e Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 04:38:32 +1300 Subject: [PATCH 16/20] app/: the React app's pages (sc-8900): Laravel serves public/'s files as they are, and any other page path on the web group gets public/index.html (no-cache), so client-side routes load; a path naming a missing file, anything under /api/, and anything but GET or HEAD get a 404, as today --- app/src/auth/mod.rs | 2 ++ app/src/http/app_shell.rs | 41 +++++++++++++++++++++++++++++++++++++++ app/src/http/mod.rs | 1 + app/tests/app_shell.rs | 24 +++++++++++++++++++++++ 4 files changed, 68 insertions(+) create mode 100644 app/src/http/app_shell.rs create mode 100644 app/tests/app_shell.rs diff --git a/app/src/auth/mod.rs b/app/src/auth/mod.rs index 843d2983..592a33d6 100644 --- a/app/src/auth/mod.rs +++ b/app/src/auth/mod.rs @@ -280,4 +280,6 @@ pub fn routes(route: &mut laravel::prelude::Router) { route.get("/auth/providers", sign_in::providers); route.post("/auth/logout", sign_in::logout); setup::routes(route); + // Anything else on the web group is a page of the React app + route.fallback(crate::http::app_shell::app_shell); } diff --git a/app/src/http/app_shell.rs b/app/src/http/app_shell.rs new file mode 100644 index 00000000..f9577046 --- /dev/null +++ b/app/src/http/app_shell.rs @@ -0,0 +1,41 @@ +//! The React app (sc-8900): Laravel serves the built frontend's files from `public/` as they are, and any other page +//! path gets the app's `index.html`, so client-side routes such as `/docspring/billing` load. A path that names a file +//! (`/favicon.ico`, `/logo.png`) and isn't there gets a 404 instead of the page: crawlers would take the HTML for the +//! file, and Cloudflare caches by extension for hours. So does anything under `/api/`, and anything but GET or HEAD. + +use axum::http::{Method, Uri}; + +/// Whether the path's last segment names a file (`logo.png`), other than an HTML page. +#[must_use] +pub fn names_a_file(path: &str) -> bool { + path.rsplit('/') + .next() + .and_then(|last| last.rsplit_once('.')) + .is_some_and(|(stem, ext)| !stem.is_empty() && !ext.is_empty() && !ext.eq_ignore_ascii_case("html")) +} + +/// The web group's fallback. +pub async fn app_shell(method: Method, uri: Uri) -> laravel::Result { + let path = uri.path(); + if !(method == Method::GET || method == Method::HEAD) || names_a_file(path) || path.starts_with("/api/") { + return Err(laravel::abort(404)); + } + let page = laravel::config().app.public_path("index.html"); + let html = tokio::fs::read_to_string(&page).await.map_err(|_| laravel::abort(404))?; + Ok(laravel::http::Response::new(laravel::view::Html::raw(html)).with_header("cache-control", "no-cache")) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn file_paths_are_told_apart_from_pages() { + for page in ["/", "/docspring/billing", "/account", "/docs.html", "/a.b/c"] { + assert!(!names_a_file(page), "{page}"); + } + for file in ["/favicon.ico", "/logo.png", "/assets/app-1234.js", "/robots.txt"] { + assert!(names_a_file(file), "{file}"); + } + } +} diff --git a/app/src/http/mod.rs b/app/src/http/mod.rs index 0f6612f3..9f3c07ab 100644 --- a/app/src/http/mod.rs +++ b/app/src/http/mod.rs @@ -1,6 +1,7 @@ //! HTTP handlers. pub mod api; +pub mod app_shell; pub mod gallery; pub mod hosts; pub mod renderer; diff --git a/app/tests/app_shell.rs b/app/tests/app_shell.rs new file mode 100644 index 00000000..46a2b53a --- /dev/null +++ b/app/tests/app_shell.rs @@ -0,0 +1,24 @@ +//! The React app's pages: any page path gets public/index.html; a missing file, an API path, or a POST doesn't. + +use laravel::testing::prelude::*; + +#[laravel::test] +async fn client_side_routes_get_the_app(app: Application) { + let index = laravel::config().app.public_path("index.html"); + std::fs::create_dir_all(index.parent().unwrap()).unwrap(); + let had = std::fs::read_to_string(&index).ok(); + if had.is_none() { + std::fs::write(&index, "VisualCI").unwrap(); + } + app.get("/docspring/billing") + .await + .assert_ok() + .assert_see("VisualCI") + .assert_header("cache-control", "no-cache"); + app.get("/logo.png").await.assert_status(404); + app.get("/api/ui/nothing-here").await.assert_status(404); + app.post("/docspring/billing").header("sec-fetch-site", "same-origin").await.assert_status(404); + if had.is_none() { + std::fs::remove_file(&index).unwrap(); + } +} From 2712a2abd601d861eff3f81fa921037662bf72e0 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 05:13:53 +1300 Subject: [PATCH 17/20] App pages, review fixes: every HTML response gets no-cache (/ and /index.html come from the static file server), and /assets/ public, max-age=31536000, immutable; the fallback serves the page read at boot with the policy's hashes; only the app host serves the app's pages (any host when none are configured), so other hosts' unknown paths are a 404; the /api/ui 404 is tested as JSON --- app/src/http/app_shell.rs | 27 +++++++++++++++++++++++---- app/src/http/security.rs | 26 +++++++++++++++++++++++++- app/tests/app_shell.rs | 34 +++++++++++++++++++++++++++++++++- 3 files changed, 81 insertions(+), 6 deletions(-) diff --git a/app/src/http/app_shell.rs b/app/src/http/app_shell.rs index f9577046..423aec88 100644 --- a/app/src/http/app_shell.rs +++ b/app/src/http/app_shell.rs @@ -5,6 +5,8 @@ use axum::http::{Method, Uri}; +use super::hosts::{Host, HostUrls}; + /// Whether the path's last segment names a file (`logo.png`), other than an HTML page. #[must_use] pub fn names_a_file(path: &str) -> bool { @@ -14,14 +16,31 @@ pub fn names_a_file(path: &str) -> bool { .is_some_and(|(stem, ext)| !stem.is_empty() && !ext.is_empty() && !ext.eq_ignore_ascii_case("html")) } -/// The web group's fallback. -pub async fn app_shell(method: Method, uri: Uri) -> laravel::Result { +/// The web group's fallback. Only the app host serves the app's pages (or every host, when the hosts aren't +/// configured): another host's unknown paths, such as an MCP or API path that doesn't exist, are a 404, never the app. +pub async fn app_shell( + method: Method, + uri: Uri, + headers: axum::http::HeaderMap, + hosts: laravel::config::Section, +) -> laravel::Result { let path = uri.path(); if !(method == Method::GET || method == Method::HEAD) || names_a_file(path) || path.starts_with("/api/") { return Err(laravel::abort(404)); } - let page = laravel::config().app.public_path("index.html"); - let html = tokio::fs::read_to_string(&page).await.map_err(|_| laravel::abort(404))?; + let configured = [&hosts.site, &hosts.app, &hosts.api, &hosts.mcp].iter().all(|u| u.is_some()); + let host = headers.get(axum::http::header::HOST).and_then(|h| h.to_str().ok()).unwrap_or_default(); + let host = host.rsplit_once(':').filter(|(_, p)| p.bytes().all(|b| b.is_ascii_digit())).map_or(host, |(h, _)| h); + if configured && hosts.classify(&host.to_ascii_lowercase()) != Some(Host::App) { + return Err(laravel::abort(404)); + } + // The page the security policy was built from at boot; read now only when there was none then (a dev server) + let html = match super::security::index_html() { + Some(html) => html.to_string(), + None => tokio::fs::read_to_string(laravel::config().app.public_path("index.html")) + .await + .map_err(|_| laravel::abort(404))?, + }; Ok(laravel::http::Response::new(laravel::view::Html::raw(html)).with_header("cache-control", "no-cache")) } diff --git a/app/src/http/security.rs b/app/src/http/security.rs index fc2d11c6..e23a5285 100644 --- a/app/src/http/security.rs +++ b/app/src/http/security.rs @@ -25,6 +25,14 @@ const CLOUDFLARE_SCRIPT: &str = "https://static.cloudflareinsights.com"; const CLOUDFLARE_REPORT: &str = "https://cloudflareinsights.com"; static POLICY: OnceLock = OnceLock::new(); +/// The page the policy was built from, served as it was read (`app_shell`), so the hashes always match it. +static INDEX: OnceLock = OnceLock::new(); + +/// The app's `index.html` as it was at boot, when there was one. +#[must_use] +pub fn index_html() -> Option<&'static str> { + INDEX.get().map(String::as_str) +} /// `'sha256-…'` for each inline `").unwrap(); + } + app.get("/acme").header("host", "app.visualci.test").await.assert_ok().assert_header("cache-control", "no-cache"); + app.get("/mcp/unknown").header("host", "mcp.visualci.test").await.assert_status(404); + app.get("/webhooks/unknown").header("host", "api.visualci.test").await.assert_status(404); + if had.is_none() { + std::fs::remove_file(&index).unwrap(); + } +} From 52f46779e6655cf140443739bffb2f1beb510055 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 05:35:28 +1300 Subject: [PATCH 18/20] app/'s image (sc-8900): docker/app.Dockerfile builds visualci-app with cargo-chef (the dependencies in a layer of their own; the CLI's crates by path with the repository's workspace manifest), the React frontend in public/ next to the base path (the CSP hashes the page it serves), a non-root user and an emptyDir-ready storage/; one image for serve, queue:work, schedule:work and migrate --force; CI's images job pushes it on main (not deployed until cutover); .dockerignore leaves out every target/ --- .dockerignore | 2 +- .github/workflows/ci.yml | 16 ++++++++++++ docker/app.Dockerfile | 56 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 docker/app.Dockerfile diff --git a/.dockerignore b/.dockerignore index da0a3465..c6c6d6de 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,4 +1,4 @@ -target +**/target **/node_modules server/frontend/dist .git diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 750b8aa2..a049f76d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -337,6 +337,7 @@ jobs: packages: write outputs: server: ${{ steps.server.outputs.digest }} + app: ${{ steps.app.outputs.digest }} renderer: ${{ steps.renderer.outputs.digest }} steps: - uses: actions/checkout@v4 @@ -361,6 +362,21 @@ jobs: tags: ghcr.io/docspring/visualci-server:${{ github.sha }} cache-from: type=gha,scope=server cache-to: type=gha,mode=max,scope=server + # VisualCI on Laravel Rust (app/, sc-8900): built on main so the cutover has an image ready, deployed only at + # cutover (talira-ai/infra k3s/resources/visualci/laravel) + - id: app + uses: docker/build-push-action@v6 + with: + context: . + file: docker/app.Dockerfile + push: true + build-args: | + BUILD_SHA=${{ github.sha }} + RENDERER_VERSION=${{ steps.version.outputs.renderer }} + VISUALCI_ANALYTICS=1 + tags: ghcr.io/docspring/visualci-app:${{ github.sha }} + cache-from: type=gha,scope=app + cache-to: type=gha,mode=max,scope=app # The renderer is rebuilt only when its inputs change, so its digest (and the running renderers) stay put # through deploys that only touch the server. Rebuilding an unchanged renderer would give a new digest and roll # the renderers mid-build for nothing. diff --git a/docker/app.Dockerfile b/docker/app.Dockerfile new file mode 100644 index 00000000..ef8d5828 --- /dev/null +++ b/docker/app.Dockerfile @@ -0,0 +1,56 @@ +# VisualCI on Laravel Rust (app/, sc-8900): one image for every process. `serve` is the web server (port 5150), +# `queue:work` a worker, `schedule:work` the scheduler, `migrate --force` the migrations (the deploy's hook). The +# React frontend's build is the image's public/, next to the binary's base path, so the web server serves it and its +# Content-Security-Policy hashes the very page it serves (app/src/http/security.rs refuses to boot without it). + +FROM node:24-trixie-slim AS frontend +WORKDIR /src/server/frontend +COPY server/frontend/package.json server/frontend/package-lock.json* server/frontend/pnpm-lock.yaml* ./ +RUN corepack enable && (if [ -f pnpm-lock.yaml ]; then pnpm install --frozen-lockfile; else npm ci; fi) +COPY server/frontend/ ./ +# 1 in CI's production image: the app's Plausible snippet (server/frontend/analytics.ts). +ARG VISUALCI_ANALYTICS=0 +ENV VISUALCI_ANALYTICS=${VISUALCI_ANALYTICS} +RUN if [ -f pnpm-lock.yaml ]; then pnpm build; else npm run build; fi + +# cargo-chef: the dependencies build in a layer of their own, rebuilt only when app/Cargo.toml or Cargo.lock change. +FROM rust:1.99.1-trixie AS chef +RUN cargo install cargo-chef --locked +WORKDIR /src + +# The CLI's crates the app uses by path (visualci-core, snapshot-diff) inherit fields from the repository's workspace: +# its manifest comes too, with only crates/* as members (the image doesn't need server/) +FROM chef AS workspace +COPY Cargo.toml ./ +RUN sed -i 's|^members = .*|members = ["crates/*"]|' Cargo.toml +COPY crates/ crates/ + +FROM workspace AS planner +COPY app/ app/ +RUN cd app && cargo chef prepare --recipe-path /recipe.json + +FROM workspace AS build +COPY --from=planner /recipe.json /recipe.json +RUN mkdir app && cd app && cargo chef cook --release --locked --recipe-path /recipe.json +COPY app/ app/ +ARG BUILD_SHA=dev +ENV BUILD_SHA=${BUILD_SHA} +RUN cd app && cargo build --release --locked --bin visualci-app + +FROM debian:trixie-slim +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/* \ + && useradd --uid 10001 --create-home visualci +WORKDIR /app +COPY --from=build /src/app/target/release/visualci-app /usr/local/bin/visualci-app +COPY --from=frontend /src/server/frontend/dist ./public +# Laravel's storage directory (framework files). The pods' root filesystem is read-only, so the deployment mounts an +# emptyDir here; caches, sessions and the queue are in Postgres (CACHE_STORE, SESSION_DRIVER, QUEUE_CONNECTION). +RUN mkdir -p storage/app storage/framework storage/logs && chown -R visualci:visualci storage +ARG RENDERER_VERSION +RUN test -n "$RENDERER_VERSION" +USER visualci +ENV APP_ENV=production APP_BASE_PATH=/app SERVER_HOST=0.0.0.0 SERVER_PORT=5150 LOG_CHANNEL=stderr \ + RENDERER_VERSION=${RENDERER_VERSION} +EXPOSE 5150 +ENTRYPOINT ["/usr/local/bin/visualci-app"] +CMD ["serve"] From 23817f6b4d54e8a0399b4cbdca3603d9c901dea1 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 13:12:46 +1300 Subject: [PATCH 19/20] Tests read a committed stand-in public/index.html (the image's frontend build replaces it) instead of writing and removing one, which raced between tests; production-boot tests find the page the security headers' check needs --- app/public/index.html | 11 +++++++++++ app/tests/app_shell.rs | 21 ++------------------- 2 files changed, 13 insertions(+), 19 deletions(-) create mode 100644 app/public/index.html diff --git a/app/public/index.html b/app/public/index.html new file mode 100644 index 00000000..3a0d4ea6 --- /dev/null +++ b/app/public/index.html @@ -0,0 +1,11 @@ + + + + +VisualCI + + + + + diff --git a/app/tests/app_shell.rs b/app/tests/app_shell.rs index 40acb6fa..8288455f 100644 --- a/app/tests/app_shell.rs +++ b/app/tests/app_shell.rs @@ -1,15 +1,10 @@ -//! The React app's pages: any page path gets public/index.html; a missing file, an API path, or a POST doesn't. +//! The React app's pages: any page path gets public/index.html (in tests, the committed stand-in); a missing file, an +//! API path, or a POST doesn't. use laravel::testing::prelude::*; #[laravel::test] async fn client_side_routes_get_the_app(app: Application) { - let index = laravel::config().app.public_path("index.html"); - std::fs::create_dir_all(index.parent().unwrap()).unwrap(); - let had = std::fs::read_to_string(&index).ok(); - if had.is_none() { - std::fs::write(&index, "VisualCI").unwrap(); - } app.get("/docspring/billing") .await .assert_ok() @@ -22,9 +17,6 @@ async fn client_side_routes_get_the_app(app: Application) { .assert_status(404) .assert_header_contains("content-type", "application/json"); app.post("/docspring/billing").header("sec-fetch-site", "same-origin").await.assert_status(404); - if had.is_none() { - std::fs::remove_file(&index).unwrap(); - } } fn hosts() -> Application { @@ -41,16 +33,7 @@ fn hosts() -> Application { /// Only the app host serves the app; another host's unknown paths are a 404, and every page is checked again. #[laravel::test(app = hosts)] async fn only_the_app_host_serves_the_app(app: Application) { - let index = laravel::config().app.public_path("index.html"); - std::fs::create_dir_all(index.parent().unwrap()).unwrap(); - let had = std::fs::read_to_string(&index).ok(); - if had.is_none() { - std::fs::write(&index, "VisualCI").unwrap(); - } app.get("/acme").header("host", "app.visualci.test").await.assert_ok().assert_header("cache-control", "no-cache"); app.get("/mcp/unknown").header("host", "mcp.visualci.test").await.assert_status(404); app.get("/webhooks/unknown").header("host", "api.visualci.test").await.assert_status(404); - if had.is_none() { - std::fs::remove_file(&index).unwrap(); - } } From 3dd93bcf2841743650bb176a809ea28f5ae293ec Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 13:40:55 +1300 Subject: [PATCH 20/20] Tests: one test database URL (app::testing::database_url, VISUALCI_APP_TEST_DATABASE_URL else CI's), so the live transport's test reaches CI's Postgres instead of the dev box's user --- app/src/testing.rs | 8 +++++++- app/tests/hosts.rs | 2 +- app/tests/live.rs | 3 +-- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/app/src/testing.rs b/app/src/testing.rs index 4370da6f..9cd99b39 100644 --- a/app/src/testing.rs +++ b/app/src/testing.rs @@ -13,8 +13,14 @@ pub fn create() -> Application { configure().create() } +/// The test database: `VISUALCI_APP_TEST_DATABASE_URL`, else CI's. +#[must_use] +pub fn database_url() -> String { + std::env::var("VISUALCI_APP_TEST_DATABASE_URL").unwrap_or_else(|_| CI_DATABASE.to_string()) +} + pub fn configure() -> ApplicationBuilder { - let url = std::env::var("VISUALCI_APP_TEST_DATABASE_URL").unwrap_or_else(|_| CI_DATABASE.to_string()); + let url = database_url(); crate::configure() .for_testing(env!("CARGO_MANIFEST_DIR")) .with_envs([ diff --git a/app/tests/hosts.rs b/app/tests/hosts.rs index 2f49ab3c..a09a626a 100644 --- a/app/tests/hosts.rs +++ b/app/tests/hosts.rs @@ -38,7 +38,7 @@ fn in_production() -> laravel::foundation::ApplicationBuilder { ("CACHE_STORE", "memory"), ("QUEUE_CONNECTION", "sync"), ("DB_CONNECTION", "pgsql"), - ("DATABASE_URL", "postgres://loco:loco@127.0.0.1:55433/visualci_app_test"), + ("DATABASE_URL", app::testing::database_url().as_str()), ("S3_ENDPOINT", "http://127.0.0.1:59000"), ("S3_BUCKET", "visualci-test"), ("S3_ACCESS_KEY_ID", "visualci"), diff --git a/app/tests/live.rs b/app/tests/live.rs index 594e5e06..11c6d7a9 100644 --- a/app/tests/live.rs +++ b/app/tests/live.rs @@ -8,8 +8,7 @@ use sqlx::Connection; /// The test server's `postgres` database: LISTEN and NOTIFY only need both sides on one database, and the tests' own /// databases are per-test copies. fn database() -> String { - let url = std::env::var("VISUALCI_APP_TEST_DATABASE_URL") - .unwrap_or_else(|_| "postgres://loco:loco@127.0.0.1:55433/visualci_app_test".to_string()); + let url = app::testing::database_url(); let server = url.rsplit_once('/').map_or(url.as_str(), |(server, _)| server); format!("{server}/postgres") }