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/app/Cargo.lock b/app/Cargo.lock index 352842da..6591b927 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,18 +4925,21 @@ 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", "serde_json", "sha2 0.10.9", "snapshot-diff", + "sqlx", "tokio", "tower", "tracing", diff --git a/app/Cargo.toml b/app/Cargo.toml index dcabfa90..55389479 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" @@ -39,10 +41,10 @@ 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"] } -base64 = "0.22" tower = { version = "0.5", features = ["util"] } url = "2" regex = "1" @@ -51,9 +53,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/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/src/auth/mod.rs b/app/src/auth/mod.rs index 1f7ffc81..592a33d6 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); @@ -278,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/auth/staff.rs b/app/src/auth/staff.rs new file mode 100644 index 00000000..18b56f6a --- /dev/null +++ b/app/src/auth/staff.rs @@ -0,0 +1,130 @@ +//! Staff pages on the auth and emails side (sc-8900), ported from today's server: the latest sign-ups, every email +//! VisualCI sends rendered with sample data, and failed emails to retry or dismiss. Anyone who isn't staff gets a 404. + +use laravel::auth::Authenticated; +use laravel::db; +use laravel::prelude::*; +use serde_json::{Value, json}; + +use super::me::summary; +use crate::models::User; +use crate::notify::outbox::AppUrl; +use crate::notify::{About, DeliverEmails, render, render::samples}; + +pub fn routes(route: &mut Router) { + route.get("/api/ui/staff/signups", signups); + route.get("/api/ui/staff/emails", emails); + route.post("/api/ui/staff/emails/{id}/resolve", resolve); +} + +fn staff_only(user: &User) -> laravel::Result<()> { + if user.staff { Ok(()) } else { Err(laravel::abort(404)) } +} + +const TIME: &str = "YYYY-MM-DD\"T\"HH24:MI:SS\"Z\""; + +/// `GET /api/ui/staff/signups`: the latest 100 people, newest first, with how they heard about VisualCI. +pub async fn signups(Authenticated(user): Authenticated) -> laravel::Result> { + staff_only(&user)?; + let rows = db::query!( + "SELECT name, email, heard_about_source, heard_about_detail, \ + to_char(created_at AT TIME ZONE 'UTC', {TIME}) AS created_at, \ + (SELECT login FROM identities WHERE user_id = users.id ORDER BY id LIMIT 1) AS login \ + FROM users ORDER BY id DESC LIMIT 100" + ) + .select() + .await?; + let mut list = Vec::new(); + for r in rows { + let (source, detail): (Option, Option) = + (r.try_get("heard_about_source")?, r.try_get("heard_about_detail")?); + list.push(json!({ + "name": r.try_get::("name")?, "email": r.try_get::("email")?, + "login": r.try_get::>("login")?, "created_at": r.try_get::("created_at")?, + "heard_about": summary(source.as_deref(), detail.as_deref()), + })); + } + Ok(Json(json!({ "signups": list }))) +} + +/// `GET /api/ui/staff/emails`: every email rendered with sample data (for Acme), and the failed ones nobody has +/// retried or dismissed yet, newest first. +pub async fn emails( + Authenticated(user): Authenticated, + app: laravel::config::Section, +) -> laravel::Result> { + staff_only(&user)?; + let about = About { org_name: "Acme", org_slug: "acme", app_url: app.url.trim_end_matches('/') }; + let list: Vec = samples() + .into_iter() + .map(|(label, kind)| { + let r = render(&kind, &about); + json!({ + "label": label, "kind": kind.name(), "subject": r.subject, "text": r.text, "html": r.html, + "can_turn_off": kind.preference().is_some(), + }) + }) + .collect(); + let rows = db::query!( + "SELECT e.id, e.kind, e.recipient, e.attempts, e.last_error, o.slug AS org, \ + to_char(e.created_at AT TIME ZONE 'UTC', {TIME}) AS created_at, \ + to_char(e.updated_at AT TIME ZONE 'UTC', {TIME}) AS failed_at \ + FROM emails e LEFT JOIN organizations o ON o.id = e.organization_id \ + WHERE e.state = 'failed' AND e.dismissed_at IS NULL ORDER BY e.id DESC LIMIT 100" + ) + .select() + .await?; + let mut failed = Vec::new(); + for r in rows { + failed.push(json!({ + "id": r.try_get::("id")?, "kind": r.try_get::("kind")?, + "recipient": r.try_get::("recipient")?, "org": r.try_get::>("org")?, + "attempts": r.try_get::("attempts")?, "last_error": r.try_get::>("last_error")?, + "created_at": r.try_get::("created_at")?, "failed_at": r.try_get::("failed_at")?, + })); + } + Ok(Json(json!({ "emails": list, "failed": failed }))) +} + +#[laravel::input] +#[validate(authenticated)] +pub struct ResolveInput { + /// `retry` or `dismiss`. + #[validate(required)] + action: String, +} + +/// `POST /api/ui/staff/emails/{id}/resolve`: retry a failed email (sent again from scratch) or dismiss it. Either way +/// it stops counting in `/status`'s `emails_failed_unresolved`. 404 when there's no such failed, undismissed email. +pub async fn resolve( + Authenticated(user): Authenticated, + Params(id): Params, + Valid(p): Valid, +) -> laravel::Result> { + staff_only(&user)?; + let done: Option = match p.action.as_str() { + "retry" => { + db::query!( + "UPDATE emails SET state = 'pending', attempts = 0, claimed_at = NULL, updated_at = now() \ + WHERE id = {id} AND state = 'failed' AND dismissed_at IS NULL RETURNING id" + ) + .scalar() + .await? + } + "dismiss" => { + db::query!( + "UPDATE emails SET dismissed_at = now(), updated_at = now() \ + WHERE id = {id} AND state = 'failed' AND dismissed_at IS NULL RETURNING id" + ) + .scalar() + .await? + } + _ => return Err(laravel::abort_with(422, "action is retry or dismiss")), + }; + done.ok_or_else(|| laravel::abort(404))?; + tracing::info!(email_id = id, action = %p.action, staff = user.id, "staff resolved a failed email"); + if p.action == "retry" { + DeliverEmails.dispatch().await?; + } + Ok(Json(json!({ "id": id }))) +} diff --git a/app/src/forge/github_app.rs b/app/src/forge/github_app.rs new file mode 100644 index 00000000..301edf03 --- /dev/null +++ b/app/src/forge/github_app.rs @@ -0,0 +1,252 @@ +//! The VisualCI GitHub App acting as itself (sc-8900, the forge side), ported from today's server: a JWT signed with +//! the App's private key, installation tokens, and a person's permission on a repository through an installation. +//! Its webhook is in `forge::webhooks`. + +use laravel::http::client; +use serde_json::Value; + +use super::Permission; + +const API: &str = "https://api.github.com"; + +/// The App (`GITHUB_APP_ID`, `GITHUB_APP_PRIVATE_KEY_BASE64`: its PEM key, base64-encoded to fit one line) and its +/// webhook's secret (`GITHUB_WEBHOOK_SECRET`). Without the secret, the webhook answers 404. +#[derive(Clone, laravel::config::Section)] +pub struct GithubApp { + #[env("GITHUB_APP_ID")] + pub app_id: Option, + #[env("GITHUB_APP_PRIVATE_KEY_BASE64")] + pub private_key_base64: Option, + #[env("GITHUB_WEBHOOK_SECRET")] + pub webhook_secret: Option, +} + +fn err(e: impl std::fmt::Display) -> laravel::Error { + laravel::Error::msg(format!("GitHub: {e}")) +} + +#[derive(serde::Serialize)] +struct AppClaims { + iat: i64, + exp: i64, + iss: String, +} + +/// A JWT that authenticates as the App itself, for nine minutes. +fn app_jwt(app: &GithubApp) -> laravel::Result { + use base64::Engine; + let (Some(id), Some(key)) = (app.app_id.as_deref(), app.private_key_base64.as_deref()) else { + return Err(err("the GitHub App isn't configured (GITHUB_APP_ID, GITHUB_APP_PRIVATE_KEY_BASE64)")); + }; + let now = laravel::now().timestamp().as_second(); + let claims = AppClaims { iat: now - 60, exp: now + 540, iss: id.to_string() }; + let pem = base64::engine::general_purpose::STANDARD + .decode(key.trim()) + .map_err(|e| err(format!("the App's private key isn't base64: {e}")))?; + let key = jsonwebtoken::EncodingKey::from_rsa_pem(&pem).map_err(err)?; + jsonwebtoken::encode(&jsonwebtoken::Header::new(jsonwebtoken::Algorithm::RS256), &claims, &key).map_err(err) +} + +/// GET a GitHub API path as JSON; `None` on 404. +async fn get(token: &str, path: &str) -> laravel::Result> { + let response = client::get(format!("{API}{path}")) + .token(token) + .header("accept", "application/vnd.github+json") + .header("user-agent", "visualci") + .await?; + if response.status() == 404 { + return Ok(None); + } + if !response.successful() { + return Err(err(format!("GET {path}: HTTP {}", response.status()))); + } + Ok(Some(response.json()?)) +} + +/// A token for one of the App's installations. +/// +/// # Errors +/// When the App isn't configured, or GitHub refuses its credentials. +pub async fn installation_token(app: &GithubApp, installation: &str) -> laravel::Result { + let response = client::post(format!("{API}/app/installations/{installation}/access_tokens")) + .token(app_jwt(app)?) + .header("accept", "application/vnd.github+json") + .header("user-agent", "visualci") + .await?; + if !response.successful() { + return Err(err(format!("installation token: HTTP {}", response.status()))); + } + let body: Value = response.json()?; + body["token"].as_str().map(str::to_string).ok_or_else(|| err("an installation token response without a token")) +} + +/// Whether the App's installation `id` exists (a delivery can be stale, or redelivered after the installation went). +/// +/// # Errors +/// When the App isn't configured, or GitHub can't be reached or refuses. +pub async fn installation_exists(app: &GithubApp, id: &str) -> laravel::Result { + if !id.bytes().all(|b| b.is_ascii_digit()) { + return Ok(false); + } + Ok(get(&app_jwt(app)?, &format!("/app/installations/{id}")).await?.is_some()) +} + +/// Below this many API calls left in the hour, a recheck stops instead of using up what webhooks and checks need. +pub const RATE_LIMIT_RESERVE: i64 = 500; + +/// Every collaborator on a repository (`owner/name`) with their permission, keyed by GitHub user ID: direct +/// collaborators, team members and organization members with access, as `affiliation=all` lists them. Public +/// visibility gives nobody a place on it. `Err` when it can't be read completely (a partial list would drop people); +/// also when GitHub's rate limit is down to [`RATE_LIMIT_RESERVE`]. +/// +/// # Errors +/// Those. +pub async fn collaborators(token: &str, repo: &str) -> laravel::Result> { + let mut out = Vec::new(); + for page in 1..=50 { + let response = client::get(format!("{API}/repos/{repo}/collaborators")) + .token(token) + .header("accept", "application/vnd.github+json") + .header("user-agent", "visualci") + .query([("affiliation", "all".to_string()), ("per_page", "100".to_string()), ("page", page.to_string())]) + .await?; + if !response.successful() { + return Err(err(format!("GET /repos/{repo}/collaborators: HTTP {}", response.status()))); + } + let remaining = response.header("x-ratelimit-remaining").and_then(|v| v.parse::().ok()); + let list: Vec = response.json()?; + let done = list.len() < 100; + for c in &list { + let (Some(id), Some(permission)) = ( + c["id"].as_i64(), + c["role_name"].as_str().and_then(permission_from).or_else(|| permission_from_flags(&c["permissions"])), + ) else { + continue; + }; + out.push((id.to_string(), permission)); + } + if remaining.is_some_and(|r| r < RATE_LIMIT_RESERVE) { + return Err(err(format!("the rate limit is down to {} calls", remaining.unwrap_or(0)))); + } + if done { + return Ok(out); + } + } + Err(err(format!("{repo} has more than 5,000 collaborators"))) +} + +/// The highest permission in a `permissions` object (`{admin, maintain, push, triage, pull}`). +fn permission_from_flags(flags: &Value) -> Option { + [ + ("admin", Permission::Admin), + ("maintain", Permission::Maintain), + ("push", Permission::Write), + ("triage", Permission::Triage), + ("pull", Permission::Read), + ] + .into_iter() + .find(|(flag, _)| flags[*flag] == true) + .map(|(_, p)| p) +} + +/// A repository's `owner/name` now, by its permanent ID (`None` when the installation can't see it). +/// +/// # Errors +/// When GitHub can't be reached or refuses. +pub async fn repository_path(token: &str, id: &str) -> laravel::Result> { + if !id.bytes().all(|b| b.is_ascii_digit()) { + return Ok(None); + } + Ok(get(token, &format!("/repositories/{id}")).await?.and_then(|v| v["full_name"].as_str().map(str::to_string))) +} + +/// A repository as GitHub describes it (`GET /repos/{path}`: visibility, licence, ID); `None` when the installation +/// can't see it. +/// +/// # Errors +/// When GitHub can't be reached or refuses. +pub async fn repository(token: &str, repo: &str) -> laravel::Result> { + get(token, &format!("/repos/{repo}")).await +} + +/// Whether a branch exists in a repository (`None` when the installation can't see the repository). +/// +/// # Errors +/// When GitHub can't be reached or refuses. +pub async fn branch_exists(token: &str, repo: &str, branch: &str) -> 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 +/// When GitHub can't be reached or refuses. +pub async fn repository_id(token: &str, repo: &str) -> 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 { + "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..0d8113fd 100644 --- a/app/src/forge/mod.rs +++ b/app/src/forge/mod.rs @@ -4,7 +4,11 @@ pub mod events; pub mod github; +pub mod github_app; pub mod gitlab; +pub mod open_source; +pub mod sync; +pub mod webhooks; use crate::auth::Role; 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 new file mode 100644 index 00000000..cc211a16 --- /dev/null +++ b/app/src/forge/sync.rs @@ -0,0 +1,236 @@ +//! 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. Each linked repository's visibility and licence are checked once a day per project +//! (`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}; +use laravel::schedule::{self, Schedule}; + +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 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, +} + +/// Run the sync for GitHub. +/// +/// # Errors +/// When GitHub can't answer for some repository (other than a low rate limit), or on a database error. +pub async fn sync_github(app: &GithubApp) -> laravel::Result { + 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 changed = webhooks::apply_reach(&reach, &people).await?; + let unlinked = recheck_links(&reach, &unseen).await?; + // Each linked repository's visibility and licence, once a day per project, in an hour of its own + let open_source = match super::open_source::recheck_due(app).await { + Ok(n) => n, + Err(e) if github_app::rate_limited(&e) => 0, + Err(e) => return Err(e), + }; + 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. +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); + } + } + 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()) +} + +/// 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; + +#[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) { + 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) => { + tracing::info!( + people = s.people, + changed = s.changed, + unlinked = s.unlinked, + open_source = s.open_source, + branches_closed = s.branches_closed, + deferred = s.deferred, + "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/src/forge/webhooks.rs b/app/src/forge/webhooks.rs new file mode 100644 index 00000000..930e2229 --- /dev/null +++ b/app/src/forge/webhooks.rs @@ -0,0 +1,492 @@ +//! The GitHub App's webhook, `POST /webhooks/github` on the API host (sc-8900, the forge side), ported from today's +//! server. A delivery is checked against `X-Hub-Signature-256` and read into a [`ForgeEvent`]: +//! +//! - merges, closed or reopened pull requests, deleted branches and repository visibility changes are dispatched to +//! the domain as `forge::events`, once per linked project; +//! - installation changes attach or detach the App's installation on linked projects, so checks stop without errors, +//! and recheck the access of the people whose memberships those organizations' repositories decide; +//! - membership changes (collaborators, teams, organization members) recheck the people they name ([`RecheckAccess`]). +//! +//! Every event is safe to receive twice. GitLab's project hooks come with the self-managed instances' port. + +use std::collections::{HashMap, HashSet}; + +use hmac::{Hmac, Mac}; +use laravel::db; +use laravel::prelude::*; +use laravel::queue::{Queueable, job}; +use serde_json::{Value, json}; +use sha2::Sha256; + +use super::events::{BranchClosed, BranchReopened, PullRequestMerged, RepositoryVisibilityChanged}; +use super::github_app::{self, GithubApp}; +use super::{ForgeKind, Permission, Repository}; + +/// One delivery, as VisualCI acts on it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ForgeEvent { + Merged { + repository: Repository, + head: String, + base: String, + merge_commit: String, + }, + Closed { + repository: Repository, + branch: String, + why: &'static str, + }, + Reopened { + repository: Repository, + branch: String, + }, + /// The App was installed on these repositories (`installation` set) or removed from them (`None`). + Installation { + installation: Option, + previous: Option, + repositories: Vec, + }, + /// These people's access may have changed (GitHub user IDs). + Access { + people: Vec, + }, + /// Anyone's access through this installation may have changed (a team's repositories changed). + AccessAll { + installation: String, + }, + RepositoryChanged { + repository: Repository, + private: bool, + }, + /// Renamed or transferred: the same repository (by ID) at a new URL. + Moved { + repository: Repository, + }, + Ignored, +} + +/// `X-Hub-Signature-256`: `sha256=` and the body's HMAC-SHA256 under the webhook's secret, compared in constant time. +#[must_use] +pub fn signed(secret: &str, header: &str, body: &[u8]) -> bool { + let Some(hex_sig) = header.strip_prefix("sha256=") else { return false }; + let Ok(sig) = hex::decode(hex_sig) else { return false }; + let Ok(mut mac) = Hmac::::new_from_slice(secret.as_bytes()) else { return false }; + mac.update(body); + mac.verify_slice(&sig).is_ok() +} + +fn repositories(list: &Value) -> Vec { + list.as_array() + .map(|l| { + l.iter() + .filter_map(|r| { + let id = r["id"].as_i64().map(|i| i.to_string()); + r["full_name"].as_str().and_then(Repository::parse).map(|repo| repo.with_id(id)) + }) + .collect() + }) + .unwrap_or_default() +} + +/// The repository an event names, with GitHub's ID for it (which survives a rename). +fn repository(event: &Value) -> Option { + event["repository"]["full_name"] + .as_str() + .and_then(Repository::parse) + .map(|r| r.with_id(event["repository"]["id"].as_i64().map(|i| i.to_string()))) +} + +/// A pull request's branch: a fork's goes by its head label (`octocat:main`), as the CLI names it, so a fork's `main` +/// isn't taken for the base repository's. +fn pr_branch(event: &Value) -> Option<&str> { + let pr = &event["pull_request"]; + let head_repo = pr["head"]["repo"]["full_name"].as_str(); + let from_fork = head_repo.is_some() && head_repo != event["repository"]["full_name"].as_str(); + if from_fork { pr["head"]["label"].as_str() } else { pr["head"]["ref"].as_str() } +} + +fn deleted_branch(event: &Value, branch: Option<&str>) -> ForgeEvent { + match (repository(event), branch) { + (Some(repository), Some(branch)) => { + ForgeEvent::Closed { repository, branch: branch.to_string(), why: "branch_deleted" } + } + _ => ForgeEvent::Ignored, + } +} + +/// One delivery (`X-GitHub-Event` and its body) as a [`ForgeEvent`]. +/// +/// # Errors +/// A message for a merged pull request without its branches or merge commit. +pub fn read_event(kind: &str, event: &Value) -> Result { + let action = event["action"].as_str().unwrap_or_default(); + let installation = event["installation"]["id"].as_i64().map(|i| i.to_string()); + let person = |v: &Value| v["id"].as_i64().map(|i| vec![i.to_string()]).unwrap_or_default(); + Ok(match (kind, action) { + ("pull_request", "closed") if event["pull_request"]["merged"] == true => { + let pr = &event["pull_request"]; + let (Some(repository), Some(head), Some(base), Some(merge)) = + (repository(event), pr_branch(event), pr["base"]["ref"].as_str(), pr["merge_commit_sha"].as_str()) + else { + return Err("a merged pull request without its branches or merge commit".into()); + }; + ForgeEvent::Merged { + repository, + head: head.to_string(), + base: base.to_string(), + merge_commit: merge.to_string(), + } + } + ("pull_request", "closed" | "reopened") => match (repository(event), pr_branch(event)) { + (Some(repository), Some(branch)) if action == "closed" => { + ForgeEvent::Closed { repository, branch: branch.to_string(), why: "pull_request" } + } + (Some(repository), Some(branch)) => ForgeEvent::Reopened { repository, branch: branch.to_string() }, + _ => ForgeEvent::Ignored, + }, + // A branch deleted: GitHub sends `delete` (ref_type branch) and a `push` with `deleted: true` + ("delete", _) if event["ref_type"] == "branch" => deleted_branch(event, event["ref"].as_str()), + ("push", _) if event["deleted"] == true => { + deleted_branch(event, event["ref"].as_str().and_then(|r| r.strip_prefix("refs/heads/"))) + } + ("installation", "created" | "unsuspend") => ForgeEvent::Installation { + installation, + previous: None, + repositories: repositories(&event["repositories"]), + }, + ("installation", "deleted" | "suspend") => ForgeEvent::Installation { + installation: None, + previous: installation, + repositories: repositories(&event["repositories"]), + }, + ("installation_repositories", "added") => ForgeEvent::Installation { + installation, + previous: None, + repositories: repositories(&event["repositories_added"]), + }, + ("installation_repositories", "removed") => ForgeEvent::Installation { + installation: None, + previous: installation, + repositories: repositories(&event["repositories_removed"]), + }, + // Made public or private, or edited: projects linked to it follow at once + ("repository", "publicized" | "privatized" | "edited") => match repository(event) { + Some(repository) => { + let private = event["repository"]["private"].as_bool().unwrap_or(action == "privatized"); + ForgeEvent::RepositoryChanged { repository, private } + } + None => ForgeEvent::Ignored, + }, + // The same repository at a new URL; links follow by its ID + ("repository", "renamed" | "transferred") => match repository(event) { + Some(repository) if repository.id.is_some() => ForgeEvent::Moved { repository }, + _ => ForgeEvent::Ignored, + }, + // A collaborator added, removed or changed; someone joined or left a team + ("member" | "membership", _) => ForgeEvent::Access { people: person(&event["member"]) }, + // Someone joined or left the organization + ("organization", "member_added" | "member_removed") => { + ForgeEvent::Access { people: person(&event["membership"]["user"]) } + } + // A team's repositories or permission changed, or it was deleted + ("team", "added_to_repository" | "removed_from_repository" | "edited" | "deleted") => match installation { + Some(installation) => ForgeEvent::AccessAll { installation }, + None => ForgeEvent::Ignored, + }, + _ => ForgeEvent::Ignored, + }) +} + +/// A project linked to a repository. +struct Linked { + id: i64, + organization_id: i64, + installation: Option, +} + +/// The GitHub projects linked to a repository: by GitHub's permanent ID when the delivery has it (a renamed repository +/// is still the same one, and a new repository that took the old name isn't), and links whose ID isn't known yet by +/// URL, which get the ID now. +async fn linked(repository: &Repository) -> laravel::Result> { + let (id, url) = (repository.id.clone(), repository.url.to_lowercase()); + if id.is_some() { + db::query!( + "UPDATE projects SET repository_id = {id}, updated_at = now() \ + WHERE forge = 'github' AND repository_id IS NULL AND lower(repository_url) = {url}" + ) + .update() + .await?; + } + let rows = db::query!( + "SELECT id, organization_id, forge_installation FROM projects WHERE forge = 'github' AND ( \ + ({id}::text IS NOT NULL AND repository_id = {id}) \ + OR (({id}::text IS NULL OR repository_id IS NULL) AND lower(repository_url) = {url}))" + ) + .select() + .await?; + rows.iter() + .map(|r| { + Ok(Linked { + id: r.try_get("id")?, + organization_id: r.try_get("organization_id")?, + installation: r.try_get("forge_installation")?, + }) + }) + .collect() +} + +/// `POST /webhooks/github`. +pub async fn github( + app: laravel::config::Section, + headers: axum::http::HeaderMap, + body: axum::body::Bytes, +) -> laravel::Result> { + let Some(secret) = app.webhook_secret.as_deref().filter(|s| !s.is_empty()) else { + return Err(laravel::abort(404)); + }; + let header = |name: &str| headers.get(name).and_then(|v| v.to_str().ok()).unwrap_or_default().to_string(); + if !signed(secret, &header("x-hub-signature-256"), &body) { + return Err(laravel::abort_with(401, "bad signature")); + } + let event: Value = serde_json::from_slice(&body).map_err(|e| laravel::abort_with(400, e.to_string()))?; + let (kind, delivery) = (header("x-github-event"), header("x-github-delivery")); + let read = read_event(&kind, &event).map_err(|e| laravel::abort_with(400, e))?; + let outcome = handle(&app, read).await?; + tracing::info!(forge = "github", kind, delivery, outcome = %outcome, "webhook"); + Ok(Json(outcome)) +} + +/// Act on one event; returns what happened, for the delivery's log on GitHub. +/// +/// # Errors +/// On a database error. +pub async fn handle(app: &GithubApp, event: ForgeEvent) -> laravel::Result { + Ok(match event { + ForgeEvent::Merged { repository, head, base, merge_commit } => { + let projects = linked(&repository).await?; + for p in &projects { + PullRequestMerged { + project_id: p.id, + head: head.clone(), + base: base.clone(), + merge_commit: merge_commit.clone(), + } + .dispatch() + .await?; + } + json!({ "dispatched": projects.len() }) + } + ForgeEvent::Closed { repository, branch, why } => { + let projects = linked(&repository).await?; + for p in &projects { + BranchClosed { project_id: p.id, branch: branch.clone(), why: why.to_string() }.dispatch().await?; + } + json!({ "dispatched": projects.len() }) + } + ForgeEvent::Reopened { repository, branch } => { + let projects = linked(&repository).await?; + for p in &projects { + BranchReopened { project_id: p.id, branch: branch.clone() }.dispatch().await?; + } + json!({ "dispatched": projects.len() }) + } + ForgeEvent::RepositoryChanged { repository, private } => { + let projects = linked(&repository).await?; + for p in &projects { + RepositoryVisibilityChanged { project_id: p.id, private }.dispatch().await?; + } + json!({ "dispatched": projects.len() }) + } + ForgeEvent::Moved { repository } => { + let (id, url) = (repository.id.clone(), repository.url.clone()); + let moved = db::query!( + "UPDATE projects SET repository_url = {url}, updated_at = now() \ + WHERE forge = 'github' AND repository_id = {id} AND repository_url IS DISTINCT FROM {url}" + ) + .update() + .await?; + json!({ "moved": moved }) + } + ForgeEvent::Installation { installation, previous, repositories } => { + // A stale or redelivered "created" mustn't attach an installation that's gone + if let Some(id) = &installation + && !github_app::installation_exists(app, id).await? + { + return Ok(json!({ "ignored": "no such installation" })); + } + let mut changed = 0; + let mut affected = HashSet::new(); + for repository in &repositories { + for p in linked(repository).await? { + // Removal only from the installation being removed; a project already on another keeps it + if previous.is_some() && p.installation != previous { + continue; + } + if p.installation == installation { + continue; + } + let (id, to) = (p.id, installation.clone()); + db::query!("UPDATE projects SET forge_installation = {to}, updated_at = now() WHERE id = {id}") + .update() + .await?; + affected.insert(p.organization_id); + changed += 1; + } + } + recheck_organizations(affected.into_iter().collect()).await?; + if installation.is_some() { json!({ "linked": changed }) } else { json!({ "unlinked": changed }) } + } + ForgeEvent::Access { people } => { + let mut users = Vec::new(); + for person in people { + let found: Option = db::query!( + "SELECT user_id FROM identities WHERE forge = 'github' AND site = '' AND forge_user_id = {person}" + ) + .scalar() + .await?; + users.extend(found); + } + let n = users.len(); + if n > 0 { + RecheckAccess { user_ids: users }.dispatch().await?; + } + json!({ "rechecking": n }) + } + ForgeEvent::AccessAll { installation } => { + let orgs: Vec = db::query!( + "SELECT DISTINCT organization_id FROM projects WHERE forge = 'github' AND forge_installation = {installation}" + ) + .select() + .await? + .iter() + .map(|r| r.try_get("organization_id")) + .collect::>()?; + recheck_organizations(orgs).await?; + json!({ "rechecking": "installation" }) + } + ForgeEvent::Ignored => json!({ "ignored": true }), + }) +} + +/// Recheck everyone whose membership in these organizations GitHub decides. +async fn recheck_organizations(orgs: Vec) -> laravel::Result<()> { + let mut users = HashSet::new(); + for org in orgs { + let rows = db::query!("SELECT user_id FROM memberships WHERE organization_id = {org} AND source = 'github'") + .select() + .await?; + for r in rows { + users.insert(r.try_get::("user_id")?); + } + } + if !users.is_empty() { + RecheckAccess { user_ids: users.into_iter().collect() }.dispatch().await?; + } + Ok(()) +} + +/// Recheck people's memberships from GitHub through the App ([`recheck`]). +#[derive(Queueable, Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct RecheckAccess { + pub user_ids: Vec, +} + +#[job] +impl RecheckAccess { + async fn handle(self, app: laravel::config::Section) -> laravel::Result<()> { + recheck(&app, &self.user_ids).await?; + Ok(()) + } +} + +/// 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 (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" + ) + .select() + .await?; + let mut tokens: 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")?); + 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 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.clone())); + let people = reach.repositories.entry(repository_id).or_default(); + for (person, permission) in github_app::collaborators(&token, &path).await? { + people.insert(person.clone(), permission); + reach.people.entry(person).or_default().push((repository.clone(), permission)); + } + } + Ok(reach) +} + +/// GitHub user IDs of these people, where they have one. +async fn github_ids(user_ids: &[i64]) -> 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(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/src/http/app_shell.rs b/app/src/http/app_shell.rs new file mode 100644 index 00000000..423aec88 --- /dev/null +++ b/app/src/http/app_shell.rs @@ -0,0 +1,60 @@ +//! 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}; + +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 { + 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. 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 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")) +} + +#[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 02b9ee67..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; @@ -15,3 +16,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..e23a5285 --- /dev/null +++ b/app/src/http/security.rs @@ -0,0 +1,204 @@ +//! 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 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; + +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(); +/// 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 `") 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 storage's public endpoint, for the policy's images. +#[derive(Clone, laravel::config::Section)] +pub struct Frontend { + #[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())) +} + +/// 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 page = config.app.public_path("index.html"); + if let Ok(html) = std::fs::read_to_string(&page) { + let _ = INDEX.set(html); + } + let value = match policy_for(&page, 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(request: Request, next: Next) -> Response { + let gallery = request.path().starts_with("/g/"); + let assets = request.path().starts_with("/assets/"); + 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")); + // A page is always checked again (a stale one after a deploy would load assets that are gone); the built assets, + // named by their content's hash, never change + let html = h.get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).is_some_and(|v| v.starts_with("text/html")); + if html { + h.entry(header::CACHE_CONTROL).or_insert(HeaderValue::from_static("no-cache")); + } else if assets && response.status().is_success() { + response + .headers_mut() + .insert(header::CACHE_CONTROL, HeaderValue::from_static("public, max-age=31536000, immutable")); + } + let h = response.headers_mut(); + let policy = POLICY.get().cloned().unwrap_or(HeaderValue::from_static("default-src 'self'")); + h.entry(header::CONTENT_SECURITY_POLICY).or_insert(policy); + 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")); + } + + #[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 95033310..d175eb15 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -11,6 +11,7 @@ pub mod heartbeat; pub mod http; pub mod jobs; pub mod listeners; +pub mod live; pub mod mcp; pub mod models; pub mod notify; @@ -46,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, _| { @@ -59,6 +61,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 @@ -70,6 +74,10 @@ 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); + // 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/src/live.rs b/app/src/live.rs new file mode 100644 index 00000000..e12b3d12 --- /dev/null +++ b/app/src/live.rs @@ -0,0 +1,226 @@ +//! 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. +//! - 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. +//! +//! 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 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)] +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, 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(()) +} + +struct Hub { + tx: broadcast::Sender, + ready: watch::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); + let (ready_tx, ready) = watch::channel(false); + tokio::spawn(supervise(database_url.to_string(), tx.clone(), ready_tx)); + Hub { tx, ready } + }) +} + +/// 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 { + 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.try_recv().await { + // No subscribers right now is fine: `send` only fails then + 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 failed"); + break; + } + } + } + true + } + Err(e) => { + tracing::warn!(error = %e, "live updates: LISTEN failed"); + false + } + }, + 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 { + 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 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; + +#[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 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) + } +} + +#[schedule::tasks] +fn schedule(schedule: &mut Schedule) { + schedule.job(CheckLive).every_minute().without_overlapping(); +} 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/app_shell.rs b/app/tests/app_shell.rs new file mode 100644 index 00000000..8288455f --- /dev/null +++ b/app/tests/app_shell.rs @@ -0,0 +1,39 @@ +//! 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) { + 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") + .header("accept", "application/json") + .await + .assert_status(404) + .assert_header_contains("content-type", "application/json"); + app.post("/docspring/billing").header("sec-fetch-site", "same-origin").await.assert_status(404); +} + +fn hosts() -> Application { + app::testing::configure() + .with_envs([ + ("VISUALCI_SITE_URL", "https://visualci.test"), + ("VISUALCI_APP_URL", "https://app.visualci.test"), + ("VISUALCI_API_URL", "https://api.visualci.test"), + ("VISUALCI_MCP_URL", "https://mcp.visualci.test"), + ]) + .create() +} + +/// 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) { + 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); +} diff --git a/app/tests/forge_sync.rs b/app/tests/forge_sync.rs new file mode 100644 index 00000000..29a4aada --- /dev/null +++ b/app/tests/forge_sync.rs @@ -0,0 +1,200 @@ +//! 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, 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() + .await? + .iter() + .map(|r| r.try_get("organization_id")) + .collect::>()?; + 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(()) +} + +/// 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(()) +} + +/// 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(()) +} diff --git a/app/tests/hosts.rs b/app/tests/hosts.rs index 20311864..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"), @@ -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"); +} diff --git a/app/tests/live.rs b/app/tests/live.rs new file mode 100644 index 00000000..11c6d7a9 --- /dev/null +++ b/app/tests/live.rs @@ -0,0 +1,31 @@ +//! 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 = app::testing::database_url(); + 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); + 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"); + + // 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"); +} diff --git a/app/tests/staff.rs b/app/tests/staff.rs new file mode 100644 index 00000000..11ee277b --- /dev/null +++ b/app/tests/staff.rs @@ -0,0 +1,49 @@ +//! Staff pages: the latest sign-ups, every email rendered, failed emails retried or dismissed; a 404 for anyone else. + +use app::models::User; +use laravel::db; +use laravel::model::create; +use laravel::testing::prelude::*; + +#[laravel::test] +async fn staff_see_sign_ups_and_emails_and_resolve_failures(app: Application) -> laravel::Result<()> { + let grace = + create!(User { pid: laravel::str::uuid7(), name: "Grace", email: "grace@example.com", staff: true }).await?; + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let ada_id = ada.id; + db::query!( + "UPDATE users SET heard_about_source = 'ai_assistant', heard_about_detail = 'Claude' WHERE id = {ada_id}" + ) + .update() + .await?; + for path in ["/api/ui/staff/signups", "/api/ui/staff/emails"] { + app.get(path).acting_as(&ada).await.assert_status(404); + } + app.get("/api/ui/staff/signups") + .acting_as(&grace) + .await + .assert_ok() + .assert_json_path("signups.0.name", "Ada") + .assert_json_path("signups.0.heard_about", "AI assistant: Claude"); + + let failed: i64 = db::query!( + "INSERT INTO emails (kind, dedupe_key, recipient, data, state, attempts, last_error) \ + VALUES ('welcome', 'w:1', 'ada@example.com', '[]', 'failed', 5, 'Postmark: HTTP 422') RETURNING id" + ) + .scalar() + .await? + .unwrap(); + let page = app.get("/api/ui/staff/emails").acting_as(&grace).await; + page.assert_ok().assert_json_path("failed.0.id", failed).assert_json_path("emails.0.kind", "credits_low"); + let resolve = |who: &User, action: &str| { + app.post(format!("/api/ui/staff/emails/{failed}/resolve")) + .acting_as(who) + .header("sec-fetch-site", "same-origin") + .json(json!({ "action": action })) + }; + resolve(&ada, "dismiss").await.assert_status(404); + resolve(&grace, "dismiss").await.assert_ok(); + resolve(&grace, "dismiss").await.assert_status(404); + app.get("/api/ui/staff/emails").acting_as(&grace).await.assert_json_path("failed", json!([])); + Ok(()) +} diff --git a/app/tests/webhooks.rs b/app/tests/webhooks.rs new file mode 100644 index 00000000..27974837 --- /dev/null +++ b/app/tests/webhooks.rs @@ -0,0 +1,258 @@ +//! GitHub's webhook: signed deliveries only; merges and closed branches go to the domain once per linked project (by +//! GitHub's repository ID, else URL); installations attach to and detach from linked projects; membership changes +//! queue a recheck of the people they name. + +use app::forge::events::{BranchClosed, PullRequestMerged}; +use app::forge::webhooks::RecheckAccess; +use app::models::User; +use hmac::{Hmac, Mac}; +use laravel::db; +use laravel::model::create; +use laravel::testing::TestResponse; +use laravel::testing::prelude::*; +use sha2::Sha256; + +const SECRET: &str = "github-webhook-test"; + +/// A GitHub App key made once per run (base64 of its PEM, as GITHUB_APP_PRIVATE_KEY_BASE64 holds it). +fn app_key() -> &'static str { + static KEY: std::sync::OnceLock = std::sync::OnceLock::new(); + KEY.get_or_init(|| { + use base64::Engine; + use rsa::pkcs1::EncodeRsaPrivateKey; + let key = rsa::RsaPrivateKey::new(&mut rsa::rand_core::OsRng, 2048).expect("a key"); + let pem = key.to_pkcs1_pem(rsa::pkcs1::LineEnding::LF).expect("its PEM"); + base64::engine::general_purpose::STANDARD.encode(pem.as_bytes()) + }) +} + +fn github() -> Application { + app::testing::configure() + .with_envs([ + ("GITHUB_WEBHOOK_SECRET", SECRET), + ("GITHUB_APP_ID", "1"), + ("GITHUB_APP_PRIVATE_KEY_BASE64", app_key()), + ]) + .create() +} + +fn github_app() -> app::forge::github_app::GithubApp { + app::forge::github_app::GithubApp { + app_id: Some("1".into()), + private_key_base64: Some(app_key().into()), + webhook_secret: None, + } +} + +async fn deliver(app: &Application, kind: &str, event: serde_json::Value) -> TestResponse { + let body = event.to_string(); + let mut mac = Hmac::::new_from_slice(SECRET.as_bytes()).unwrap(); + mac.update(body.as_bytes()); + let signature = format!("sha256={}", hex::encode(mac.finalize().into_bytes())); + app.post("/webhooks/github") + .header("x-github-event", kind) + .header("x-github-delivery", "d-1") + .header("x-hub-signature-256", signature) + .header("content-type", "application/json") + .body(body) + .await +} + +/// Two organizations' projects linking acme/web: one by GitHub's repository ID, one by URL only. +async fn linked() -> laravel::Result<(i64, i64, i64)> { + let mut ids = Vec::new(); + for (slug, repository_id) in [("acme", Some("42")), ("other", None)] { + let org: i64 = db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) \ + VALUES (gen_random_uuid(), {slug}, {slug}, now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + let project: i64 = db::query!( + "INSERT INTO projects (pid, organization_id, slug, name, forge, repository_url, repository_id, \ + forge_installation, created_at, updated_at) \ + VALUES (gen_random_uuid(), {org}, 'web', 'Web', 'github', 'https://github.com/acme/web', {repository_id}, \ + '7', now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + ids.push((org, project)); + } + Ok((ids[0].0, ids[0].1, ids[1].1)) +} + +fn repository() -> serde_json::Value { + json!({ "id": 42, "full_name": "acme/web" }) +} + +#[laravel::test(app = github)] +async fn an_unsigned_delivery_is_refused(app: Application) { + app.post("/webhooks/github") + .header("x-github-event", "ping") + .header("x-hub-signature-256", "sha256=00") + .json(json!({})) + .await + .assert_status(401); +} + +#[laravel::test(app = github)] +async fn a_merge_and_a_deleted_branch_reach_each_linked_project(app: Application) -> laravel::Result<()> { + let (_, by_id, by_url) = linked().await?; + let events = laravel::event::fake(); + let merged = json!({ + "action": "closed", "repository": repository(), + "pull_request": { "merged": true, "merge_commit_sha": "abc123", "base": { "ref": "main" }, + "head": { "ref": "feature", "repo": { "full_name": "acme/web" } } }, + }); + deliver(&app, "pull_request", merged).await.assert_ok().assert_json_path("dispatched", 2); + events.assert_dispatched_times::(2); + events.assert_dispatched_where::(|e| { + e.project_id == by_id && e.head == "feature" && e.base == "main" && e.merge_commit == "abc123" + }); + events.assert_dispatched_where::(|e| e.project_id == by_url); + + // A fork's branch goes by its label + let fork = json!({ + "action": "closed", "repository": repository(), + "pull_request": { "merged": false, "head": { "ref": "main", "label": "octocat:main", + "repo": { "full_name": "octocat/web" } } }, + }); + deliver(&app, "pull_request", fork).await.assert_ok(); + events.assert_dispatched_where::(|e| e.branch == "octocat:main" && e.why == "pull_request"); + let deleted = json!({ "ref": "old", "ref_type": "branch", "repository": repository() }); + deliver(&app, "delete", deleted).await.assert_ok(); + events.assert_dispatched_where::(|e| e.branch == "old" && e.why == "branch_deleted"); + Ok(()) +} + +#[laravel::test(app = github)] +async fn installations_attach_and_detach_and_membership_changes_recheck(app: Application) -> laravel::Result<()> { + let (org, by_id, _) = linked().await?; + let jobs = laravel::queue::fake(); + let _github = laravel::http::client::fake() + .with("api.github.com/app/installations/8", json!({ "id": 8 })) + .with("api.github.com/app/installations/*", laravel::http::client::response().status(404).json(json!({}))); + // A stale "created" for an installation that's gone attaches nothing + let stale = json!({ "action": "created", "installation": { "id": 5 }, "repositories": [repository()] }); + deliver(&app, "installation", stale).await.assert_ok().assert_json_path("ignored", "no such installation"); + let installation = |id: i64| async move { + db::query!("SELECT forge_installation FROM projects WHERE id = {id}").scalar::>().await + }; + // Removing another installation leaves the project's own alone + let other = json!({ "action": "deleted", "installation": { "id": 9 }, "repositories": [repository()] }); + deliver(&app, "installation", other).await.assert_ok().assert_json_path("unlinked", 0); + assert_eq!(installation(by_id).await?.flatten().as_deref(), Some("7")); + let removed = json!({ "action": "removed", "installation": { "id": 7 }, "repositories_removed": [repository()] }); + deliver(&app, "installation_repositories", removed).await.assert_ok().assert_json_path("unlinked", 2); + assert_eq!(installation(by_id).await?.flatten(), None); + let added = json!({ "action": "added", "installation": { "id": 8 }, "repositories_added": [repository()] }); + deliver(&app, "installation_repositories", added).await.assert_ok().assert_json_path("linked", 2); + assert_eq!(installation(by_id).await?.flatten().as_deref(), Some("8")); + + // A collaborator changed: the person with that GitHub ID is rechecked + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let ada_id = ada.id; + db::query!( + "INSERT INTO identities (user_id, forge, site, forge_user_id, login, created_at, updated_at) \ + VALUES ({ada_id}, 'github', '', '1001', 'ada', now(), now())" + ) + .insert() + .await?; + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org}, {ada_id}, 'member', 'github', now(), now())" + ) + .insert() + .await?; + let member = json!({ "action": "removed", "member": { "id": 1001 }, "repository": repository() }); + deliver(&app, "member", member).await.assert_ok().assert_json_path("rechecking", 1); + assert!(jobs.pushed::().iter().any(|j| j.job().user_ids == vec![ada_id])); + Ok(()) +} + +#[laravel::test(app = github)] +async fn a_recheck_reads_each_repositorys_collaborators_once(_app: Application) -> laravel::Result<()> { + let (org, _, _) = linked().await?; + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let ada_id = ada.id; + db::query!( + "INSERT INTO identities (user_id, forge, site, forge_user_id, login, created_at, updated_at) \ + VALUES ({ada_id}, 'github', '', '1001', 'ada', now(), now())" + ) + .insert() + .await?; + let github = laravel::http::client::fake() + .with("api.github.com/app/installations/7/access_tokens", json!({ "token": "t" })) + .with("api.github.com/repositories/42", json!({ "full_name": "acme/web" })) + .with( + "api.github.com/repos/acme/web/collaborators*", + json!([{ "id": 1001, "role_name": "maintain" }, { "id": 2002, "role_name": "read" }]), + ); + assert_eq!(app::forge::webhooks::recheck(&github_app(), &[ada_id]).await?, 1); + let role: Option = + db::query!("SELECT role FROM memberships WHERE organization_id = {org} AND user_id = {ada_id}") + .scalar() + .await?; + assert_eq!(role.as_deref(), Some("admin"), "maintain is admin"); + github.assert_sent_count(3); + Ok(()) +} + +#[laravel::test(app = github)] +async fn a_listing_that_fails_changes_nobody(_app: Application) -> laravel::Result<()> { + let (org, _, _) = linked().await?; + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let ada_id = ada.id; + db::query!( + "INSERT INTO identities (user_id, forge, site, forge_user_id, login, created_at, updated_at) \ + VALUES ({ada_id}, 'github', '', '1001', 'ada', now(), now())" + ) + .insert() + .await?; + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org}, {ada_id}, 'member', 'github', now(), now())" + ) + .insert() + .await?; + let _github = laravel::http::client::fake() + .with("api.github.com/app/installations/7/access_tokens", json!({ "token": "t" })) + .with("api.github.com/repositories/42", json!({ "full_name": "acme/web" })) + .with( + "api.github.com/repos/acme/web/collaborators*", + laravel::http::client::response().status(502).json(json!({})), + ); + assert!(app::forge::webhooks::recheck(&github_app(), &[ada_id]).await.is_err()); + let role: Option = + db::query!("SELECT role FROM memberships WHERE organization_id = {org} AND user_id = {ada_id}") + .scalar() + .await?; + assert_eq!(role.as_deref(), Some("member"), "a partial answer drops nobody"); + Ok(()) +} + +#[laravel::test(app = github)] +async fn a_renamed_repository_moves_its_links_and_edits_say_whether_it_is_private( + app: Application, +) -> laravel::Result<()> { + let (_, by_id, by_url) = linked().await?; + let events = laravel::event::fake(); + let renamed = json!({ "action": "renamed", "repository": { "id": 42, "full_name": "acme/website" } }); + deliver(&app, "repository", renamed).await.assert_ok().assert_json_path("moved", 1); + let url: Option = db::query!("SELECT repository_url FROM projects WHERE id = {by_id}").scalar().await?; + assert_eq!(url.as_deref(), Some("https://github.com/acme/website")); + // A delivery naming the ID backfills a link that only had the URL + let edited = json!({ "action": "edited", "repository": { "id": 77, "full_name": "acme/web", "private": true } }); + deliver(&app, "repository", edited).await.assert_ok(); + events.assert_dispatched_where::(|e| { + e.project_id == by_url && e.private + }); + let id: Option = db::query!("SELECT repository_id FROM projects WHERE id = {by_url}") + .scalar::>() + .await? + .flatten(); + assert_eq!(id.as_deref(), Some("77")); + Ok(()) +} 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"]