From 761161258c51718af22c03a3f9b80d1744a2345d Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 11:35:29 +1300 Subject: [PATCH 1/5] app/: self-managed GitLab instances (sc-8900, forge, ported): secrets::encrypt/decrypt (AES-256-GCM keyed by VISUALCI_SECRETS_KEY; nothing stored in the clear without it) and secrets::webhook_secret; a gitlab_instances table; forge::instances (normalise_base refuses gitlab.com, paths, IP addresses and http outside development; for_site, for_organization, by_pid, json_for, upsert, enabled) and admins' POST/DELETE /api/ui/orgs/{org}/gitlab-instances, answering with the organization's instances, their sign-in and callback URLs --- app/Cargo.lock | 1 + app/Cargo.toml | 1 + ...03_001000_create_gitlab_instances_table.rs | 25 +++ app/src/auth/invitations.rs | 2 +- app/src/auth/mod.rs | 1 + app/src/forge/instances.rs | 199 ++++++++++++++++++ app/src/forge/mod.rs | 1 + app/src/lib.rs | 1 + app/src/models/gitlab_instances.rs | 19 ++ app/src/models/mod.rs | 2 + app/src/secrets.rs | 106 ++++++++++ app/tests/gitlab_instances.rs | 132 ++++++++++++ 12 files changed, 489 insertions(+), 1 deletion(-) create mode 100644 app/database/migrations/2026_12_03_001000_create_gitlab_instances_table.rs create mode 100644 app/src/forge/instances.rs create mode 100644 app/src/models/gitlab_instances.rs create mode 100644 app/src/secrets.rs create mode 100644 app/tests/gitlab_instances.rs diff --git a/app/Cargo.lock b/app/Cargo.lock index 1a92f968..2a122e9c 100644 --- a/app/Cargo.lock +++ b/app/Cargo.lock @@ -4918,6 +4918,7 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" name = "visualci-app" version = "0.0.0" dependencies = [ + "aes-gcm", "axum", "base64 0.22.1", "globset", diff --git a/app/Cargo.toml b/app/Cargo.toml index c4173843..cb60aae4 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -26,6 +26,7 @@ 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" +aes-gcm = "0.11" base64 = "0.22" hex = "0.4" oauth-provider = "0.1.3" diff --git a/app/database/migrations/2026_12_03_001000_create_gitlab_instances_table.rs b/app/database/migrations/2026_12_03_001000_create_gitlab_instances_table.rs new file mode 100644 index 00000000..ed3328d9 --- /dev/null +++ b/app/database/migrations/2026_12_03_001000_create_gitlab_instances_table.rs @@ -0,0 +1,25 @@ +use laravel::db::AnyTransaction; + +/// Self-managed GitLab instances (ported as today's): an organization registers its instance's base URL and the OAuth +/// application its admin made there, the secret encrypted with `secrets::encrypt`. People sign in there (an identity's +/// `site` is the instance's base URL), and a project on it links with an access token, also encrypted. +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.query( + "CREATE TABLE gitlab_instances ( + id BIGSERIAL PRIMARY KEY, + pid UUID NOT NULL UNIQUE, + organization_id BIGINT NOT NULL REFERENCES organizations(id) ON DELETE CASCADE, + base_url TEXT NOT NULL, + client_id TEXT NOT NULL, + client_secret_enc TEXT NOT NULL, + created_by BIGINT REFERENCES users(id) ON DELETE SET NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + UNIQUE (organization_id, base_url) + ); + CREATE INDEX gitlab_instances_base_url ON gitlab_instances (base_url);", + ) + .unprepared() + .await?; + Ok(()) +} diff --git a/app/src/auth/invitations.rs b/app/src/auth/invitations.rs index 3ca34dec..4fa8bf32 100644 --- a/app/src/auth/invitations.rs +++ b/app/src/auth/invitations.rs @@ -154,7 +154,7 @@ async fn org_role(user: &User, slug: &str) -> laravel::Result<(i64, String, Role } /// The organization, when the person is an admin there: a member gets a 403, anyone else a 404. -async fn admin_org(user: &User, slug: &str, action: &str) -> laravel::Result<(i64, String)> { +pub(crate) async fn admin_org(user: &User, slug: &str, action: &str) -> laravel::Result<(i64, String)> { let (id, name, role) = org_role(user, slug).await?; if role < Role::Admin { return Err(laravel::abort_with(403, format!("only admins can {action}"))); diff --git a/app/src/auth/mod.rs b/app/src/auth/mod.rs index 843d2983..b64e126a 100644 --- a/app/src/auth/mod.rs +++ b/app/src/auth/mod.rs @@ -273,6 +273,7 @@ pub fn routes(route: &mut laravel::prelude::Router) { me::routes(route); device::routes(route); staff::routes(route); + crate::forge::instances::routes(route); route.get("/auth/{forge}", sign_in::start); route.post("/auth/{forge}/link", sign_in::link); route.get("/auth/{forge}/callback", sign_in::callback); diff --git a/app/src/forge/instances.rs b/app/src/forge/instances.rs new file mode 100644 index 00000000..1db72a68 --- /dev/null +++ b/app/src/forge/instances.rs @@ -0,0 +1,199 @@ +//! Self-managed GitLab instances (sc-8900, the forge side), ported from today's `models::gitlab_instances`: an +//! organization's admin registers the instance's base URL and an OAuth application made on it, whose secret is stored +//! encrypted. People then sign in at `/auth/gitlab-`, and the organization's projects there link with an +//! access token its admin pastes. +//! +//! - `POST /api/ui/orgs/{org}/gitlab-instances` adds one, or replaces its OAuth application (admins); +//! - `DELETE /api/ui/orgs/{org}/gitlab-instances/{id}` removes one (admins): its projects stay linked but stop +//! reaching it. +//! +//! Both answer with the organization's instances, as [`json_for`] gives them (the organization's page shows them +//! too). + +use laravel::auth::Authenticated; +use laravel::db; +use laravel::prelude::*; +use serde_json::{Value, json}; + +use crate::models::{GitlabInstance, User}; + +pub fn routes(route: &mut Router) { + route.post("/api/ui/orgs/{org}/gitlab-instances", add); + route.delete("/api/ui/orgs/{org}/gitlab-instances/{id}", remove); +} + +/// A self-managed instance's base URL, normalised: `https://gitlab.example.com` (http, or an IP address, only for a +/// development server's local GitLab). `None` for anything else, gitlab.com included (VisualCI's own). +#[must_use] +pub fn normalise_base(input: &str, allow_http: bool) -> Option { + let s = input.trim().trim_end_matches('/'); + let url = url::Url::parse(s).ok()?; + let ok_scheme = url.scheme() == "https" || (allow_http && url.scheme() == "http"); + let host = url.host_str()?.to_ascii_lowercase(); + // An IP address never goes through the resolver that keeps requests to public addresses (`forge::outbound`), so + // only a name is accepted + let ip_literal = !matches!(url.host(), Some(url::Host::Domain(_))); + if !ok_scheme + || url.path() != "/" && !url.path().is_empty() + || url.query().is_some() + || host.ends_with("gitlab.com") + || ip_literal && !allow_http + { + return None; + } + Some(match url.port() { + Some(p) => format!("{}://{host}:{p}", url.scheme()), + None => format!("{}://{host}", url.scheme()), + }) +} + +/// The organization's instance at a base URL. +/// +/// # Errors +/// On a database error. +pub async fn for_site(organization_id: i64, base_url: &str) -> laravel::Result> { + let base = base_url.trim_end_matches('/').to_ascii_lowercase(); + db::query!("SELECT * FROM gitlab_instances WHERE organization_id = {organization_id} AND base_url = {base}") + .select_one_as() + .await +} + +/// An organization's instances, oldest first. +/// +/// # Errors +/// On a database error. +pub async fn for_organization(organization_id: i64) -> laravel::Result> { + db::query!("SELECT * FROM gitlab_instances WHERE organization_id = {organization_id} ORDER BY id").select_as().await +} + +/// An instance by its pid, for sign-in. +/// +/// # Errors +/// On a database error. +pub async fn by_pid(pid: &laravel::str::Uuid) -> laravel::Result> { + let pid = pid.to_string(); + db::query!("SELECT * FROM gitlab_instances WHERE pid = {pid}::uuid").select_one_as().await +} + +/// The organization's instances as its page shows them: where people sign in, and the callback URL its OAuth +/// application needs. +/// +/// # Errors +/// On a database error. +pub async fn json_for(organization_id: i64) -> laravel::Result> { + let app = laravel::config().app.url.trim_end_matches('/').to_string(); + Ok(for_organization(organization_id) + .await? + .iter() + .map(|i| { + json!({ + "id": i.pid, "base_url": i.base_url, "client_id": i.client_id, + "sign_in_url": format!("/auth/gitlab-{}", i.pid), + "callback_url": format!("{app}/auth/gitlab-{}/callback", i.pid), + "created_at": i.created_at.to_string(), + }) + }) + .collect()) +} + +/// Whether instances can be added here: a server without `VISUALCI_SECRETS_KEY` can't store their secrets. +#[must_use] +pub fn enabled() -> bool { + crate::secrets::encrypt("probe").is_some() +} + +#[laravel::input] +#[validate(authenticated)] +pub struct NewInstance { + /// `https://gitlab.example.com`. + #[validate(required)] + base_url: String, + /// The OAuth application's ID and secret. + #[validate(required)] + client_id: String, + #[validate(required)] + client_secret: String, +} + +/// Register an instance for an organization, or replace its OAuth application. Errors are 422s saying what's wrong. +/// +/// # Errors +/// Those, and database errors. +pub async fn upsert( + organization_id: i64, + base_url: &str, + client_id: &str, + client_secret: &str, + by: i64, +) -> laravel::Result { + let allow_http = !laravel::config().app.env.is_production(); + let base = normalise_base(base_url, allow_http).ok_or_else(|| { + laravel::abort_with( + 422, + "the instance's URL is its https:// address with no path, like https://gitlab.example.com", + ) + })?; + let (client_id, client_secret) = (client_id.trim(), client_secret.trim()); + if client_id.is_empty() || client_secret.is_empty() { + return Err(laravel::abort_with(422, "the OAuth application's ID and secret are both needed")); + } + let secret = crate::secrets::encrypt(client_secret) + .ok_or_else(|| laravel::abort_with(422, "this server can't store secrets (no VISUALCI_SECRETS_KEY)"))?; + let pid = laravel::str::uuid7().to_string(); + db::query!( + "INSERT INTO gitlab_instances (pid, organization_id, base_url, client_id, client_secret_enc, created_by) \ + VALUES ({pid}::uuid, {organization_id}, {base}, {client_id}, {secret}, {by}) \ + ON CONFLICT (organization_id, base_url) DO UPDATE SET client_id = EXCLUDED.client_id, \ + client_secret_enc = EXCLUDED.client_secret_enc, updated_at = now() \ + RETURNING *" + ) + .select_one_as() + .await? + .ok_or_else(|| laravel::Error::msg("no instance row")) +} + +/// `POST /api/ui/orgs/{org}/gitlab-instances`: add an instance (admins). The OAuth application's callback URL is only +/// known afterwards, so its admin registers the instance with any callback, then edits it. +pub async fn add( + Authenticated(user): Authenticated, + Params(org): Params, + Valid(p): Valid, +) -> laravel::Result> { + let (org_id, _) = crate::auth::invitations::admin_org(&user, &org, "add a GitLab instance").await?; + let instance = upsert(org_id, &p.base_url, &p.client_id, &p.client_secret, user.id).await?; + tracing::info!(organization_id = org_id, base_url = instance.base_url, by = user.id, "GitLab instance added"); + Ok(Json(json!({ "gitlab_instances": json_for(org_id).await? }))) +} + +/// `DELETE /api/ui/orgs/{org}/gitlab-instances/{id}`: remove an instance (admins). +pub async fn remove( + Authenticated(user): Authenticated, + Params((org, id)): Params<(String, String)>, +) -> laravel::Result> { + let (org_id, _) = crate::auth::invitations::admin_org(&user, &org, "remove a GitLab instance").await?; + let pid = laravel::str::Uuid::parse_str(&id).map_err(|_| laravel::abort(404))?.to_string(); + db::query!("DELETE FROM gitlab_instances WHERE organization_id = {org_id} AND pid = {pid}::uuid").delete().await?; + Ok(Json(json!({ "gitlab_instances": json_for(org_id).await? }))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn normalises_instance_urls() { + assert_eq!(normalise_base("https://GitLab.Example.com/", false).as_deref(), Some("https://gitlab.example.com")); + assert_eq!( + normalise_base("https://git.example.com:8443", false).as_deref(), + Some("https://git.example.com:8443") + ); + assert_eq!(normalise_base("http://git.example.com", false), None, "https only"); + assert_eq!(normalise_base("http://localhost:5196", true).as_deref(), Some("http://localhost:5196")); + assert_eq!(normalise_base("https://git.example.com/gitlab", false), None, "no relative URL root"); + assert_eq!(normalise_base("https://gitlab.com", false), None, "gitlab.com is VisualCI's own"); + assert_eq!(normalise_base("not a url", false), None); + for ip in ["https://10.0.0.5", "https://127.0.0.1:8443", "https://[::1]", "https://169.254.169.254"] { + assert_eq!(normalise_base(ip, false), None, "{ip}: an address, not a name"); + } + } +} diff --git a/app/src/forge/mod.rs b/app/src/forge/mod.rs index d4c3984c..18e9b5fa 100644 --- a/app/src/forge/mod.rs +++ b/app/src/forge/mod.rs @@ -6,6 +6,7 @@ pub mod events; pub mod github; pub mod github_app; pub mod gitlab; +pub mod instances; pub mod link; pub mod open_source; pub mod sync; diff --git a/app/src/lib.rs b/app/src/lib.rs index 77b131e4..59e607e6 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -15,6 +15,7 @@ pub mod live; pub mod mcp; pub mod models; pub mod notify; +pub mod secrets; #[path = "../database/seeders/mod.rs"] pub mod seeders; pub mod skills; diff --git a/app/src/models/gitlab_instances.rs b/app/src/models/gitlab_instances.rs new file mode 100644 index 00000000..001ae9a4 --- /dev/null +++ b/app/src/models/gitlab_instances.rs @@ -0,0 +1,19 @@ +use laravel::model::model; +use laravel::str::Uuid; +use laravel::time::Timestamp; + +/// A self-managed GitLab instance an organization signs in with: its base URL and the OAuth application its admin made +/// there, whose secret is stored encrypted (`secrets::encrypt`). +#[model(table = "gitlab_instances")] +pub struct GitlabInstance { + pub id: i64, + pub pid: Uuid, + pub organization_id: i64, + pub base_url: String, + pub client_id: String, + #[serde(skip)] + pub client_secret_enc: String, + pub created_by: Option, + pub created_at: Timestamp, + pub updated_at: Timestamp, +} diff --git a/app/src/models/mod.rs b/app/src/models/mod.rs index f4bdcbbe..5109959d 100644 --- a/app/src/models/mod.rs +++ b/app/src/models/mod.rs @@ -12,6 +12,7 @@ mod credit_transactions; mod diffs; mod downloads; mod feedback; +mod gitlab_instances; mod ignored_changes; mod memberships; mod organizations; @@ -38,6 +39,7 @@ pub use credit_transactions::CreditTransaction; pub use diffs::Diff; pub use downloads::Download; pub use feedback::Feedback; +pub use gitlab_instances::GitlabInstance; pub use ignored_changes::IgnoredChange; pub use memberships::Membership; pub use organizations::{Organization, slug_from, valid_slug}; diff --git a/app/src/secrets.rs b/app/src/secrets.rs new file mode 100644 index 00000000..9699af0d --- /dev/null +++ b/app/src/secrets.rs @@ -0,0 +1,106 @@ +//! Secrets derived from the server's own key (`VISUALCI_SECRETS_KEY`, which lives only in 1Password), ported from +//! today's server: each project's GitLab webhook secret, checked later without being stored, and the secrets VisualCI +//! must keep (self-managed GitLab instances' OAuth secrets and projects' access tokens), stored encrypted. + +use hmac::{Hmac, Mac}; +use sha2::Sha256; + +/// The server's key. +#[derive(Clone, laravel::config::Section)] +pub struct SecretsKey { + #[env("VISUALCI_SECRETS_KEY")] + pub key: Option, +} + +fn key() -> Option { + laravel::config().get::()?.key.clone().filter(|k| !k.trim().is_empty()) +} + +/// The secret a project's GitLab webhook sends as `X-Gitlab-Token`: HMAC-SHA256 of the project's ID under the server's +/// key, so each project has its own and nothing is stored. `None` without a key. +#[must_use] +pub fn webhook_secret(project_pid: &laravel::str::Uuid) -> Option { + webhook_secret_with(key().as_deref(), project_pid) +} + +fn webhook_secret_with(key: Option<&str>, project_pid: &laravel::str::Uuid) -> Option { + let key = key.map(str::trim).filter(|k| !k.is_empty())?; + let mut mac = Hmac::::new_from_slice(key.as_bytes()).ok()?; + mac.update(format!("gitlab-webhook:{project_pid}").as_bytes()); + Some(format!("vciwh_{}", hex::encode(mac.finalize().into_bytes()))) +} + +/// The AES-256-GCM key for stored secrets: SHA-256 of the server's key under its own label, so it differs from the +/// webhook secrets' HMAC key. +fn cipher(key: Option<&str>) -> Option { + use aes_gcm::KeyInit; + use sha2::Digest; + let key = key.map(str::trim).filter(|k| !k.is_empty())?; + let digest = Sha256::digest(format!("visualci-stored-secrets-v1:{key}").as_bytes()); + aes_gcm::Aes256Gcm::new_from_slice(&digest).ok() +} + +/// Encrypt a secret for the database: `v1:` and base64 of a random 96-bit nonce followed by the ciphertext. `None` +/// without a key, so nothing is ever stored in the clear. +#[must_use] +pub fn encrypt(plaintext: &str) -> Option { + encrypt_with(key().as_deref(), plaintext) +} + +fn encrypt_with(key: Option<&str>, plaintext: &str) -> Option { + use aes_gcm::aead::{Aead, Generate, Nonce}; + use base64::Engine; + let cipher = cipher(key)?; + let nonce = Nonce::::generate(); + let mut out = nonce.to_vec(); + out.extend(cipher.encrypt(&nonce, plaintext.as_bytes()).ok()?); + Some(format!("v1:{}", base64::engine::general_purpose::STANDARD.encode(out))) +} + +/// Decrypt what [`encrypt`] stored. `None` when the key is missing or different, or the value was tampered with. +#[must_use] +pub fn decrypt(stored: &str) -> Option { + decrypt_with(key().as_deref(), stored) +} + +fn decrypt_with(key: Option<&str>, stored: &str) -> Option { + use aes_gcm::aead::{Aead, Nonce}; + use base64::Engine; + let bytes = base64::engine::general_purpose::STANDARD.decode(stored.strip_prefix("v1:")?).ok()?; + if bytes.len() < 12 { + return None; + } + let (nonce, ciphertext) = bytes.split_at(12); + let plain = cipher(key)?.decrypt(&Nonce::::try_from(nonce).ok()?, ciphertext).ok()?; + String::from_utf8(plain).ok() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn encrypts_and_decrypts_with_the_same_key_only() { + let stored = encrypt_with(Some("key-one"), "glpat-secret").unwrap(); + assert!(stored.starts_with("v1:") && !stored.contains("glpat"), "{stored}"); + assert_ne!(stored, encrypt_with(Some("key-one"), "glpat-secret").unwrap(), "a fresh nonce each time"); + assert_eq!(decrypt_with(Some("key-one"), &stored).as_deref(), Some("glpat-secret")); + assert_eq!(decrypt_with(Some("key-two"), &stored), None, "another key can't read it"); + let mut tampered = stored.clone(); + tampered.pop(); + tampered.push(if stored.ends_with('A') { 'B' } else { 'A' }); + assert_eq!(decrypt_with(Some("key-one"), &tampered), None, "tampering is caught"); + assert_eq!(encrypt_with(None, "x"), None, "never stored in the clear"); + assert_eq!(encrypt_with(Some(" "), "x"), None); + } + + #[test] + fn each_project_has_its_own_webhook_secret() { + let (a, b) = (laravel::str::Uuid::from_u128(1), laravel::str::Uuid::from_u128(2)); + let secret = webhook_secret_with(Some("key"), &a).unwrap(); + assert!(secret.starts_with("vciwh_") && secret.len() == 6 + 64, "{secret}"); + assert_eq!(webhook_secret_with(Some("key"), &a), Some(secret.clone()), "the same each time"); + assert_ne!(webhook_secret_with(Some("key"), &b), Some(secret), "another project's differs"); + assert_eq!(webhook_secret_with(None, &a), None); + } +} diff --git a/app/tests/gitlab_instances.rs b/app/tests/gitlab_instances.rs new file mode 100644 index 00000000..22fea38d --- /dev/null +++ b/app/tests/gitlab_instances.rs @@ -0,0 +1,132 @@ +//! An organization's admins register self-managed GitLab instances: the OAuth application's secret is stored +//! encrypted, a URL that isn't an instance's address is refused, members can't add or remove them, and a server +//! without `VISUALCI_SECRETS_KEY` refuses to store the secret. + +use app::models::User; +use laravel::db; +use laravel::model::create; +use laravel::testing::prelude::*; + +async fn person(name: &str, email: &str) -> laravel::Result { + let user = create!(User { pid: laravel::str::uuid7(), name: name, email: email, staff: false }).await?; + User::find_or_fail(user.id).await +} + +async fn org_with(slug: &str, user: &User, role: &str) -> laravel::Result { + let org: i64 = db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) \ + VALUES (gen_random_uuid(), {slug}, 'Acme', now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + let id = user.id; + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org}, {id}, {role}, 'created', now(), now())" + ) + .insert() + .await?; + Ok(org) +} + +fn with_key() -> Application { + app::testing::configure().with_env("VISUALCI_SECRETS_KEY", "test-secrets-key").create() +} + +fn new_instance(base_url: &str) -> serde_json::Value { + json!({ "base_url": base_url, "client_id": "app-id", "client_secret": "app-secret" }) +} + +#[laravel::test(app = with_key)] +async fn an_admin_adds_and_removes_an_instance(app: Application) -> laravel::Result<()> { + let grace = person("Grace", "grace@example.com").await?; + let acme = org_with("acme", &grace, "admin").await?; + + let added = app + .post("/api/ui/orgs/acme/gitlab-instances") + .acting_as(&grace) + .header("sec-fetch-site", "same-origin") + .json(new_instance("https://GitLab.Example.com/")) + .await; + added.assert_ok(); + let list = added.json()["gitlab_instances"].as_array().unwrap().clone(); + assert_eq!(list.len(), 1); + assert_eq!(list[0]["base_url"], "https://gitlab.example.com"); + assert_eq!(list[0]["client_id"], "app-id"); + let id = list[0]["id"].as_str().unwrap().to_string(); + assert_eq!(list[0]["sign_in_url"], format!("/auth/gitlab-{id}")); + assert!(list[0]["callback_url"].as_str().unwrap().ends_with(&format!("/auth/gitlab-{id}/callback"))); + assert!(list[0].get("client_secret_enc").is_none(), "the secret never leaves the server"); + + let stored: Option = + db::query!("SELECT client_secret_enc FROM gitlab_instances WHERE organization_id = {acme}").scalar().await?; + let stored = stored.unwrap(); + assert!(!stored.contains("app-secret"), "stored encrypted"); + assert_eq!(app::secrets::decrypt(&stored).as_deref(), Some("app-secret")); + + // Adding the same address again replaces its OAuth application + app.post("/api/ui/orgs/acme/gitlab-instances") + .acting_as(&grace) + .header("sec-fetch-site", "same-origin") + .json(json!({ "base_url": "https://gitlab.example.com", "client_id": "new-id", "client_secret": "s2" })) + .await + .assert_ok() + .assert_json_path("gitlab_instances.0.client_id", "new-id") + .assert_json_path("gitlab_instances.0.id", id.as_str()); + + let removed = app + .delete(format!("/api/ui/orgs/acme/gitlab-instances/{id}")) + .acting_as(&grace) + .header("sec-fetch-site", "same-origin") + .await; + removed.assert_ok(); + assert_eq!(removed.json()["gitlab_instances"], json!([])); + Ok(()) +} + +#[laravel::test(app = with_key)] +async fn an_address_that_isnt_an_instance_is_refused(app: Application) -> laravel::Result<()> { + let grace = person("Grace", "grace@example.com").await?; + org_with("acme", &grace, "admin").await?; + for url in ["https://gitlab.com", "https://git.example.com/gitlab", "ftp://git.example.com", "not a url"] { + app.post("/api/ui/orgs/acme/gitlab-instances") + .acting_as(&grace) + .header("sec-fetch-site", "same-origin") + .json(new_instance(url)) + .await + .assert_status(422); + } + let count: Option = db::query!("SELECT count(*) FROM gitlab_instances").scalar().await?; + assert_eq!(count, Some(0)); + Ok(()) +} + +#[laravel::test(app = with_key)] +async fn members_cant_add_instances(app: Application) -> laravel::Result<()> { + let ada = person("Ada", "ada@example.com").await?; + org_with("acme", &ada, "member").await?; + app.post("/api/ui/orgs/acme/gitlab-instances") + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .json(new_instance("https://gitlab.example.com")) + .await + .assert_status(403); + Ok(()) +} + +#[laravel::test] +async fn a_server_without_a_secrets_key_stores_no_secrets(app: Application) -> laravel::Result<()> { + let grace = person("Grace", "grace@example.com").await?; + org_with("acme", &grace, "admin").await?; + assert!(!app::forge::instances::enabled()); + let refused = app + .post("/api/ui/orgs/acme/gitlab-instances") + .acting_as(&grace) + .header("sec-fetch-site", "same-origin") + .json(new_instance("https://gitlab.example.com")) + .await; + refused.assert_status(422); + assert!(refused.text().contains("VISUALCI_SECRETS_KEY"), "{}", refused.text()); + Ok(()) +} From e91e7e2dd8488b74829f32ebc983fdc413feb26d Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 11:47:50 +1300 Subject: [PATCH 2/5] app/: signing in with an organization's GitLab instance (sc-8900, forge, ported): /auth/gitlab- runs the OAuth code flow with PKCE itself (social login's providers are fixed at boot), the state bound to the instance in the session; forge::outbound guards every request to an instance (public addresses only, checked at DNS resolution; no redirects; time and 8 MB limits; VISUALCI_FORGE_PRIVATE_ADDRESSES=1 for development), and gitlab.rs's API reads go through it; an instance's identity names its site, so its addresses never match an existing account; the configured GitLab's URL is recognised at boot --- app/src/auth/sign_in.rs | 74 ++++++++++++-- app/src/forge/gitlab.rs | 23 ++--- app/src/forge/instances.rs | 102 ++++++++++++++++++- app/src/forge/mod.rs | 1 + app/src/forge/outbound.rs | 179 ++++++++++++++++++++++++++++++++++ app/src/lib.rs | 2 + app/tests/gitlab_instances.rs | 101 +++++++++++++++++++ 7 files changed, 454 insertions(+), 28 deletions(-) create mode 100644 app/src/forge/outbound.rs diff --git a/app/src/auth/sign_in.rs b/app/src/auth/sign_in.rs index 5eed8d59..07090b57 100644 --- a/app/src/auth/sign_in.rs +++ b/app/src/auth/sign_in.rs @@ -37,6 +37,35 @@ pub struct SignedIn { const RETURN_TO: &str = "auth.return_to"; const LINKING: &str = "auth.linking"; +/// A sign-in under way at a self-managed GitLab instance: social login's providers are fixed at boot, so these run +/// the OAuth code flow themselves (`forge::instances`). +const INSTANCE_LOGIN: &str = "auth.instance"; + +/// What the session keeps between going to an instance and coming back: the forge name the sign-in started at +/// (`gitlab-`), so a state handed to one instance can't finish a sign-in at another, the state, and the +/// PKCE verifier. +#[derive(serde::Serialize, serde::Deserialize)] +struct InstanceLogin { + forge: String, + state: String, + verifier: String, +} + +/// Off to a self-managed instance: the authorization URL, with the login remembered in the session. +fn instance_redirect(instance: &crate::models::GitlabInstance, forge: &str, session: &Session) -> String { + let login = + InstanceLogin { forge: forge.to_string(), state: laravel::str::random(40), verifier: laravel::str::random(64) }; + let url = forge::instances::authorize_url(instance, &login.state, &login.verifier); + session.put(INSTANCE_LOGIN, login); + url +} + +#[laravel::query] +pub struct CallbackQuery { + code: Option, + state: Option, + error: Option, +} #[laravel::query] pub struct StartQuery { @@ -85,7 +114,8 @@ pub async fn start( Query(q): Query, session: Session, ) -> laravel::Result { - let provider = provider(&forge)?; + let instance = forge::instances::named(&forge).await?; + let provider = if instance.is_some() { None } else { Some(provider(&forge)?) }; match q.return_to.as_deref().and_then(safe_return) { Some(to) => session.put(RETURN_TO, to), None => { @@ -93,7 +123,11 @@ pub async fn start( } } let _: Option = session.pull(LINKING); - social::redirect(provider) + match (instance, provider) { + (Some(instance), _) => Ok(Redirect::to(instance_redirect(&instance, &forge, &session))), + (None, Some(provider)) => social::redirect(provider), + (None, None) => Err(laravel::abort(404)), + } } /// `POST /auth/{forge}/link`: link another forge account to the signed-in user. A JSON POST, which a page on another @@ -103,6 +137,10 @@ pub async fn link( _user: laravel::auth::Authenticated, session: Session, ) -> laravel::Result> { + if let Some(instance) = forge::instances::named(&forge).await? { + session.put(LINKING, true); + return Ok(Json(serde_json::json!({ "url": instance_redirect(&instance, &forge, &session) }))); + } let provider = provider(&forge)?; session.put(LINKING, true); let redirect = laravel::http::Response::new(social::redirect(provider)?).into_http(); @@ -118,19 +156,35 @@ pub async fn callback( gitlab: laravel::config::Section, hosts: laravel::config::Section, session: Session, + Query(q): Query, ) -> laravel::Result { - let provider = provider(&forge)?; + let instance = forge::instances::named(&forge).await?; + let provider = if instance.is_some() { None } else { Some(provider(&forge)?) }; let return_to: Option = session.pull(RETURN_TO); let linking: bool = session.pull(LINKING).unwrap_or(false); - let profile = match social::user(provider).await { - Ok(profile) => profile, - Err(social::Error::Denied) => { - return Ok(laravel::http::Response::new(Redirect::to(return_to.as_deref().unwrap_or("/")))); + let cancelled = || Ok(laravel::http::Response::new(Redirect::to(return_to.as_deref().unwrap_or("/")))); + let profile = match (&instance, provider) { + (Some(instance), _) => { + let login: Option = session.pull(INSTANCE_LOGIN); + if q.error.is_some() { + return cancelled(); + } + let login = login + .filter(|l| l.forge == forge && !l.state.is_empty() && q.state.as_deref() == Some(l.state.as_str())) + .ok_or_else(|| laravel::abort_with(400, "sign-in expired; try again"))?; + let code = q.code.as_deref().ok_or_else(|| laravel::abort_with(400, "sign-in expired; try again"))?; + forge::instances::profile(instance, code, &login.verifier).await? } - Err(e) => return Err(e.into()), + (None, Some(provider)) => match social::user(provider).await { + Ok(profile) => profile, + Err(social::Error::Denied) => return cancelled(), + Err(e) => return Err(e.into()), + }, + (None, None) => return Err(laravel::abort(404)), }; - let sign_in = match ForgeKind::parse(&forge) { - Some(ForgeKind::Gitlab) => forge::gitlab::sign_in(&gitlab.url, &profile).await?, + let sign_in = match (&instance, ForgeKind::parse(&forge)) { + (Some(instance), _) => forge::gitlab::sign_in(&instance.base_url, &profile).await?, + (None, Some(ForgeKind::Gitlab)) => forge::gitlab::sign_in(&gitlab.url, &profile).await?, _ => forge::github::sign_in(&profile).await?, }; let current = auth.user().await?; diff --git a/app/src/forge/gitlab.rs b/app/src/forge/gitlab.rs index f519e5fd..adb035e3 100644 --- a/app/src/forge/gitlab.rs +++ b/app/src/forge/gitlab.rs @@ -119,12 +119,12 @@ async fn all_pages(base: &str, token: &str, path: &str) -> laravel::Result = response.json()?; + let batch: Vec = serde_json::from_value(body).map_err(|e| laravel::Error::msg(e.to_string()))?; let done = batch.len() < 100; items.extend(batch); if done { @@ -179,15 +179,12 @@ fn project_id(path: &str) -> String { /// GET an API path (`/projects/...`) as JSON; `None` on 404. async fn get(base: &str, token: &str, path: &str) -> laravel::Result> { - let base = base.trim_end_matches('/'); - let response = client::get(format!("{base}/api/v4{path}")).token(token).accept_json().await?; - if response.status() == 404 { - return Ok(None); - } - if !response.successful() { - return Err(laravel::Error::msg(format!("GitLab GET {path}: HTTP {}", response.status()))); + let (status, body) = super::outbound::get_json(base, token, &format!("/api/v4{path}")).await?; + match status { + 404 => Ok(None), + 200..300 => Ok(Some(body)), + _ => Err(laravel::Error::msg(format!("GitLab GET {path}: HTTP {status}"))), } - Ok(Some(response.json()?)) } /// The bot's access level on a project (`group/sub/project`), when it's a member. diff --git a/app/src/forge/instances.rs b/app/src/forge/instances.rs index 1db72a68..82d13282 100644 --- a/app/src/forge/instances.rs +++ b/app/src/forge/instances.rs @@ -11,6 +11,7 @@ //! too). use laravel::auth::Authenticated; +use laravel::auth::social; use laravel::db; use laravel::prelude::*; use serde_json::{Value, json}; @@ -53,9 +54,16 @@ pub fn normalise_base(input: &str, allow_http: bool) -> Option { /// On a database error. pub async fn for_site(organization_id: i64, base_url: &str) -> laravel::Result> { let base = base_url.trim_end_matches('/').to_ascii_lowercase(); - db::query!("SELECT * FROM gitlab_instances WHERE organization_id = {organization_id} AND base_url = {base}") - .select_one_as() - .await + let found: Option = + db::query!("SELECT * FROM gitlab_instances WHERE organization_id = {organization_id} AND base_url = {base}") + .select_one_as() + .await?; + Ok(found.inspect(recognise)) +} + +/// An instance's project URLs parse as GitLab repositories from now on, in this process. +fn recognise(instance: &GitlabInstance) { + super::register_gitlab_instance(&instance.base_url); } /// An organization's instances, oldest first. @@ -63,7 +71,12 @@ pub async fn for_site(organization_id: i64, base_url: &str) -> laravel::Result laravel::Result> { - db::query!("SELECT * FROM gitlab_instances WHERE organization_id = {organization_id} ORDER BY id").select_as().await + let all: Vec = + db::query!("SELECT * FROM gitlab_instances WHERE organization_id = {organization_id} ORDER BY id") + .select_as() + .await?; + all.iter().for_each(recognise); + Ok(all) } /// An instance by its pid, for sign-in. @@ -72,7 +85,9 @@ pub async fn for_organization(organization_id: i64) -> laravel::Result laravel::Result> { let pid = pid.to_string(); - db::query!("SELECT * FROM gitlab_instances WHERE pid = {pid}::uuid").select_one_as().await + let found: Option = + db::query!("SELECT * FROM gitlab_instances WHERE pid = {pid}::uuid").select_one_as().await?; + Ok(found.inspect(recognise)) } /// The organization's instances as its page shows them: where people sign in, and the callback URL its OAuth @@ -149,6 +164,7 @@ pub async fn upsert( ) .select_one_as() .await? + .inspect(recognise) .ok_or_else(|| laravel::Error::msg("no instance row")) } @@ -176,6 +192,82 @@ pub async fn remove( Ok(Json(json!({ "gitlab_instances": json_for(org_id).await? }))) } +/// The instance a sign-in path names (`/auth/gitlab-`): `None` for any other forge name, a 404 when no +/// instance has that ID. +/// +/// # Errors +/// That, and database errors. +pub async fn named(forge: &str) -> laravel::Result> { + let Some(pid) = forge.strip_prefix("gitlab-") else { return Ok(None) }; + let pid = laravel::str::Uuid::parse_str(pid).map_err(|_| laravel::abort(404))?; + Ok(Some(by_pid(&pid).await?.ok_or_else(|| laravel::abort_with(404, "that GitLab sign-in isn't set up"))?)) +} + +/// Where the instance sends someone back after they authorise VisualCI's OAuth application there. +#[must_use] +pub fn callback_url(instance: &GitlabInstance) -> String { + format!("{}/auth/gitlab-{}/callback", laravel::config().app.url.trim_end_matches('/'), instance.pid) +} + +/// The instance's authorization URL for a sign-in, with its state and PKCE challenge (S256 of `verifier`). +#[must_use] +pub fn authorize_url(instance: &GitlabInstance, state: &str, verifier: &str) -> String { + use base64::Engine; + use sha2::Digest; + let challenge = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(sha2::Sha256::digest(verifier.as_bytes())); + let mut url = url::Url::parse(&format!("{}/oauth/authorize", instance.base_url)).expect("a normalised base URL"); + url.query_pairs_mut() + .append_pair("client_id", &instance.client_id) + .append_pair("redirect_uri", &callback_url(instance)) + .append_pair("response_type", "code") + .append_pair("scope", "read_user read_api") + .append_pair("state", state) + .append_pair("code_challenge", &challenge) + .append_pair("code_challenge_method", "S256"); + url.into() +} + +/// Finish a sign-in at an instance: exchange the code for a token, and read the person's profile, as social login +/// does for the configured forges. Requests go through [`super::outbound`]. +/// +/// # Errors +/// 400s when the instance's secret can't be read here or the instance refuses the code; connection errors. +pub async fn profile(instance: &GitlabInstance, code: &str, verifier: &str) -> laravel::Result { + let base = instance.base_url.as_str(); + let secret = crate::secrets::decrypt(&instance.client_secret_enc) + .ok_or_else(|| laravel::abort_with(400, format!("sign-in with {base} isn't configured on this server")))?; + let exchange = laravel::http::client::post(format!("{base}/oauth/token")).accept_json().form(json!({ + "client_id": instance.client_id, "client_secret": secret, "code": code, + "grant_type": "authorization_code", "redirect_uri": callback_url(instance), "code_verifier": verifier, + })); + let (status, token) = super::outbound::send_json(exchange, base).await?; + let access = token["access_token"].as_str().filter(|_| (200..300).contains(&status)).ok_or_else(|| { + tracing::warn!(base, status, "a GitLab instance refused a sign-in's code"); + laravel::abort_with(400, format!("{base} refused the sign-in; try again")) + })?; + let (status, user) = super::outbound::get_json(base, access, "/api/v4/user").await?; + if !(200..300).contains(&status) || user["id"].as_i64().is_none() { + return Err(laravel::abort_with(400, format!("{base} didn't say who signed in (HTTP {status})"))); + } + // GitLab lists a person's addresses only once their account is confirmed, so the primary one counts then + let confirmed = !user["confirmed_at"].is_null(); + Ok(social::User { + provider: social::Provider::from(format!("gitlab-{}", instance.pid)), + id: user["id"].as_i64().map(|i| i.to_string()).unwrap_or_default(), + name: user["name"].as_str().map(str::to_owned), + nickname: user["username"].as_str().map(str::to_owned), + email: user["email"].as_str().map(|address| social::Email { address: address.to_owned(), verified: confirmed }), + avatar: user["avatar_url"].as_str().map(str::to_owned), + token: social::Token { + access: access.to_string(), + refresh: token["refresh_token"].as_str().map(str::to_owned), + expires_at: None, + scopes: Vec::new(), + }, + raw: user, + }) +} + #[cfg(test)] mod tests { use super::*; diff --git a/app/src/forge/mod.rs b/app/src/forge/mod.rs index 18e9b5fa..1b9bf218 100644 --- a/app/src/forge/mod.rs +++ b/app/src/forge/mod.rs @@ -9,6 +9,7 @@ pub mod gitlab; pub mod instances; pub mod link; pub mod open_source; +pub mod outbound; pub mod sync; pub mod webhooks; diff --git a/app/src/forge/outbound.rs b/app/src/forge/outbound.rs new file mode 100644 index 00000000..77ea04cc --- /dev/null +++ b/app/src/forge/outbound.rs @@ -0,0 +1,179 @@ +//! Requests to servers an organization chose (a self-managed GitLab instance's base URL), ported from today's server: +//! only public addresses, no redirects, time limits and a size limit. Any organization's admin can add an instance, so +//! without these it could point VisualCI's servers at the cluster's own services or a cloud metadata address, or hang +//! or flood them. +//! +//! The address check is in DNS resolution, at connection time, so a name can't pass a check and then resolve +//! elsewhere. IP literals never reach the resolver: [`super::instances::normalise_base`] refuses them. +//! `VISUALCI_FORGE_PRIVATE_ADDRESSES=1` allows private addresses, for a development server talking to a local GitLab. +//! +//! The GitLab of `VISUALCI_GITLAB_URL` and GitHub are this server's own choice, not an organization's: their requests +//! go out as they are. + +use std::net::{IpAddr, SocketAddr}; +use std::sync::Arc; +use std::time::Duration; + +use laravel::http::client::{self, PendingRequest, reqwest}; +use laravel::prelude::*; +use laravel::stream::StreamExt; + +/// The largest response body read from an organization's server. +pub const MAX_BODY: usize = 8 * 1024 * 1024; + +#[derive(Clone, Debug, laravel::config::Section)] +pub struct Outbound { + /// `1` lets requests reach private addresses: a development server's local GitLab only. + #[env("VISUALCI_FORGE_PRIVATE_ADDRESSES")] + pub private_addresses: Option, +} + +fn private_allowed() -> bool { + laravel::config().get::().is_some_and(|o| o.private_addresses.as_deref() == Some("1")) +} + +/// Whether an address is on the public internet: not private, loopback, link-local (169.254.0.0/16: cloud metadata), +/// shared (100.64.0.0/10), multicast, documentation, reserved or unspecified, in IPv4 or IPv6. +#[must_use] +pub fn is_public(ip: IpAddr) -> bool { + match ip { + IpAddr::V4(v4) => { + let o = v4.octets(); + !(v4.is_private() + || v4.is_loopback() + || v4.is_link_local() + || v4.is_broadcast() + || v4.is_documentation() + || v4.is_unspecified() + || v4.is_multicast() + || o[0] == 0 + || (o[0] == 100 && (o[1] & 0xc0) == 64) + || (o[0] == 192 && o[1] == 0 && o[2] == 0) + || (o[0] == 198 && (o[1] & 0xfe) == 18) + || o[0] >= 240) + } + IpAddr::V6(v6) => { + if let Some(v4) = v6.to_ipv4_mapped() { + return is_public(IpAddr::V4(v4)); + } + let s = v6.segments(); + !(v6.is_loopback() + || v6.is_unspecified() + || v6.is_multicast() + || (s[0] & 0xfe00) == 0xfc00 + || (s[0] & 0xffc0) == 0xfe80 + || (s[0] == 0x2001 && s[1] == 0x0db8) + || (s[0] == 0x64 && s[1] == 0xff9b)) + } + } +} + +/// A resolver that keeps only public addresses. +struct PublicOnly; + +impl reqwest::dns::Resolve for PublicOnly { + fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving { + let host = name.as_str().to_string(); + Box::pin(async move { + let addrs: Vec = + tokio::net::lookup_host((host.as_str(), 0)).await?.filter(|a| is_public(a.ip())).collect(); + if addrs.is_empty() { + return Err(format!("{host} has no public address").into()); + } + Ok(Box::new(addrs.into_iter()) as reqwest::dns::Addrs) + }) + } +} + +/// Whether a base URL is one this server chose (its GitLab, GitHub), not an organization. +fn trusted(base: &str) -> bool { + let base = base.trim_end_matches('/'); + let gitlab = + laravel::config().get::().map(|g| g.url.trim_end_matches('/').to_string()); + base.eq_ignore_ascii_case("https://api.github.com") + || base.eq_ignore_ascii_case("https://github.com") + || gitlab.is_some_and(|g| base.eq_ignore_ascii_case(&g)) +} + +/// A request to an organization's server, guarded: public addresses only (unless allowed for development), no +/// redirects, a 10-second connection and 30-second request limit. +pub fn guard(request: PendingRequest) -> PendingRequest { + let private = private_allowed(); + request.total_timeout(30.seconds()).configure_transport(move |builder| { + let builder = builder.redirect(reqwest::redirect::Policy::none()).connect_timeout(Duration::from_secs(10)); + if private { builder } else { builder.dns_resolver(Arc::new(PublicOnly)) } + }) +} + +/// Send a request to `base` (a forge's base URL) and read its status and body: guarded, and read up to [`MAX_BODY`], +/// unless `base` is a forge this server chose. +/// +/// # Errors +/// When it can't connect (an address that isn't public among them), or the body is larger. +pub async fn send(request: PendingRequest, base: &str) -> laravel::Result<(u16, String)> { + if trusted(base) { + let response = request.await?; + return Ok((response.status().as_u16(), response.text().into_owned())); + } + let response = guard(request).stream().await?; + let status = response.status().as_u16(); + let mut body = Vec::new(); + let mut chunks = response.chunks(); + while let Some(chunk) = chunks.next().await { + let chunk = chunk?; + if body.len() + chunk.len() > MAX_BODY { + return Err(laravel::Error::msg(format!("{base}'s response is larger than {MAX_BODY} bytes"))); + } + body.extend_from_slice(&chunk); + } + Ok((status, String::from_utf8_lossy(&body).into_owned())) +} + +/// [`send`], with the body as JSON (`null` for an error status whose body isn't JSON). +/// +/// # Errors +/// As [`send`], or when a successful response's body isn't JSON. +pub async fn send_json(request: PendingRequest, base: &str) -> laravel::Result<(u16, serde_json::Value)> { + let (status, body) = send(request, base).await?; + match serde_json::from_str(&body) { + Ok(json) => Ok((status, json)), + Err(_) if !(200..300).contains(&status) => Ok((status, serde_json::Value::Null)), + Err(e) => Err(laravel::Error::msg(format!("{base}: not JSON: {e}"))), + } +} + +/// A GET to `{base}{path}` with a token, as JSON. +/// +/// # Errors +/// As [`send_json`]. +pub async fn get_json(base: &str, token: &str, path: &str) -> laravel::Result<(u16, serde_json::Value)> { + let base = base.trim_end_matches('/'); + send_json(client::get(format!("{base}{path}")).token(token).accept_json(), base).await +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_public_addresses_count() { + for private in [ + "127.0.0.1", + "10.1.2.3", + "172.16.0.1", + "192.168.1.1", + "169.254.169.254", + "100.64.0.1", + "0.0.0.0", + "::1", + "fd00::1", + "fe80::1", + "::ffff:10.0.0.1", + ] { + assert!(!is_public(private.parse().unwrap()), "{private}"); + } + for public in ["1.1.1.1", "140.82.112.3", "2606:4700::1111"] { + assert!(is_public(public.parse().unwrap()), "{public}"); + } + } +} diff --git a/app/src/lib.rs b/app/src/lib.rs index 59e607e6..7751c2bb 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -48,6 +48,8 @@ pub fn configure() -> ApplicationBuilder { )?; http::hosts::check(config.section::(), config.app.env.is_production())?; billing::check(config.section::(), config.app.env.is_production())?; + // Repository URLs on the configured GitLab (when it isn't gitlab.com) parse as GitLab projects + forge::register_gitlab_instance(&config.section::().url); Ok(()) }) .with_middleware(|middleware, _| { diff --git a/app/tests/gitlab_instances.rs b/app/tests/gitlab_instances.rs index 22fea38d..07c64e1f 100644 --- a/app/tests/gitlab_instances.rs +++ b/app/tests/gitlab_instances.rs @@ -4,6 +4,7 @@ use app::models::User; use laravel::db; +use laravel::http::client; use laravel::model::create; use laravel::testing::prelude::*; @@ -130,3 +131,103 @@ async fn a_server_without_a_secrets_key_stores_no_secrets(app: Application) -> l assert!(refused.text().contains("VISUALCI_SECRETS_KEY"), "{}", refused.text()); Ok(()) } + +/// Acme's instance at gitlab.example.com, as its admin added it; returns its ID. +async fn acme_instance() -> laravel::Result { + let grace = person("Grace", "grace@example.com").await?; + let acme = org_with("acme", &grace, "admin").await?; + let instance = + app::forge::instances::upsert(acme, "https://gitlab.example.com", "app-id", "app-secret", grace.id).await?; + Ok(instance.pid.to_string()) +} + +/// The instance's OAuth token endpoint and API, as a sign-in reads them. +fn instance_api() -> client::HttpFake { + client::fake() + .with("gitlab.example.com/oauth/token", json!({ "access_token": "tok", "token_type": "Bearer" })) + .with( + "gitlab.example.com/api/v4/user", + json!({ "id": 77, "username": "ada", "name": "Ada Lovelace", "email": "ada@example.com", + "confirmed_at": "2026-01-01T00:00:00Z", "avatar_url": null }), + ) + .with( + "gitlab.example.com/api/v4/projects*", + json!([{ "id": 5, "web_url": "https://gitlab.example.com/acme/web", + "permissions": { "project_access": { "access_level": 40 } } }]), + ) +} + +/// The `state` in a redirect to the instance's authorization page. +fn state_of(location: &str) -> String { + url::Url::parse(location) + .unwrap() + .query_pairs() + .find(|(k, _)| k == "state") + .map(|(_, v)| v.into_owned()) + .expect("a state") +} + +#[laravel::test(app = with_key)] +async fn someone_signs_in_with_an_organizations_instance(app: Application) -> laravel::Result<()> { + let id = acme_instance().await?; + let api = instance_api(); + // Someone already has an account with the address the instance reports + let existing = person("Ada", "ada@example.com").await?; + let existing_id = existing.id; + db::query!("UPDATE users SET email_verified_at = now() WHERE id = {existing_id}").update().await?; + + let start = app.get(format!("/auth/gitlab-{id}?return_to=/acme")).await; + start.assert_redirect(); + let location = start.header("location").unwrap().to_string(); + assert!(location.starts_with("https://gitlab.example.com/oauth/authorize?"), "{location}"); + assert!(location.contains("client_id=app-id") && location.contains("code_challenge_method=S256"), "{location}"); + assert!(location.contains(&format!("%2Fauth%2Fgitlab-{id}%2Fcallback")), "{location}"); + + let state = state_of(&location); + let done = app.get(format!("/auth/gitlab-{id}/callback?code=c0de&state={state}")).with_cookies_from(&start).await; + done.assert_redirect_to("/acme"); + + let exchange = api.sent().into_iter().find(|r| r.url().ends_with("/oauth/token")).expect("the code exchanged"); + let form = String::from_utf8_lossy(exchange.body()).into_owned(); + assert!(form.contains("client_secret=app-secret") && form.contains("code=c0de") && form.contains("code_verifier=")); + + let user = User::first_where(User::name.eq("Ada Lovelace")).await?.expect("an account"); + let user_id = user.id; + // An instance's addresses are its own admins' to set, so they never match an existing account + assert_ne!(user_id, existing_id); + let site: Option = + db::query!("SELECT site FROM identities WHERE user_id = {user_id} AND forge = 'gitlab'").scalar().await?; + assert_eq!(site.as_deref(), Some("https://gitlab.example.com"), "an instance's identity names its site"); + Ok(()) +} + +#[laravel::test(app = with_key)] +async fn a_state_from_another_sign_in_is_refused(app: Application) -> laravel::Result<()> { + let id = acme_instance().await?; + let _api = instance_api(); + let start = app.get(format!("/auth/gitlab-{id}")).await; + app.get(format!("/auth/gitlab-{id}/callback?code=c0de&state=not-the-state")) + .with_cookies_from(&start) + .await + .assert_status(400); + // Nor without the session that started it + let state = state_of(start.header("location").unwrap()); + app.get(format!("/auth/gitlab-{id}/callback?code=c0de&state={state}")).await.assert_status(400); + let users: Option = db::query!("SELECT count(*) FROM users WHERE name = 'Ada Lovelace'").scalar().await?; + assert_eq!(users, Some(0)); + Ok(()) +} + +#[laravel::test(app = with_key)] +async fn an_unknown_instance_has_no_sign_in(app: Application) -> laravel::Result<()> { + app.get(format!("/auth/gitlab-{}", laravel::str::uuid7())).await.assert_status(404); + app.get("/auth/gitlab-not-a-uuid").await.assert_status(404); + Ok(()) +} + +#[laravel::test] +async fn an_instance_that_resolves_to_a_private_address_is_never_reached(_app: Application) -> laravel::Result<()> { + let e = app::forge::outbound::send(client::get("http://localhost:9/"), "http://localhost:9").await.unwrap_err(); + assert!(format!("{e:?}").contains("no public address"), "{e:?}"); + Ok(()) +} From aef228e62546969bddd855613985eeba5c1b7dba Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 11:58:42 +1300 Subject: [PATCH 3/5] app/: GitLab webhooks and instance projects linked with a token (sc-8900, forge, ported): POST /webhooks/gitlab/{project} checks the project's own secret and linked repository and dispatches PullRequestMerged, BranchClosed or BranchReopened for that project alone; forge::gitlab_hooks adds each project's hook (merge request and push events) when the bot or token is a Maintainer, on linking, from POST /api/ui/orgs/{org}/projects/{project}/gitlab-webhook and in the hourly sync; link_repository links a project on one of the organization's instances with an access token (api scope, Developer or more), stored encrypted, after checking the person is a maintainer there --- app/src/auth/mod.rs | 1 + app/src/forge/gitlab_hooks.rs | 331 ++++++++++++++++++++++++++++++++++ app/src/forge/link.rs | 68 ++++++- app/src/forge/mod.rs | 1 + app/src/forge/sync.rs | 6 + app/src/lib.rs | 4 + app/tests/gitlab_hooks.rs | 150 +++++++++++++++ 7 files changed, 553 insertions(+), 8 deletions(-) create mode 100644 app/src/forge/gitlab_hooks.rs create mode 100644 app/tests/gitlab_hooks.rs diff --git a/app/src/auth/mod.rs b/app/src/auth/mod.rs index b64e126a..b1e0ce49 100644 --- a/app/src/auth/mod.rs +++ b/app/src/auth/mod.rs @@ -274,6 +274,7 @@ pub fn routes(route: &mut laravel::prelude::Router) { device::routes(route); staff::routes(route); crate::forge::instances::routes(route); + crate::forge::gitlab_hooks::routes(route); route.get("/auth/{forge}", sign_in::start); route.post("/auth/{forge}/link", sign_in::link); route.get("/auth/{forge}/callback", sign_in::callback); diff --git a/app/src/forge/gitlab_hooks.rs b/app/src/forge/gitlab_hooks.rs new file mode 100644 index 00000000..a9a739b5 --- /dev/null +++ b/app/src/forge/gitlab_hooks.rs @@ -0,0 +1,331 @@ +//! GitLab webhooks (sc-8900, the forge side), ported from today's server: each linked GitLab project has its own hook, +//! at its own URL (`/webhooks/gitlab/`) with its own secret (`secrets::webhook_secret`), which VisualCI adds +//! when its bot or the project's access token is a Maintainer, and otherwise shows on the project's page to add by +//! hand. A delivery acts on that project alone: several organizations' projects may link one repository, and each +//! project's admins see its secret, so a delivery that reached every project linking the repository would let any of +//! them forge merges into the others. +//! +//! - `POST /webhooks/gitlab/{project}`: a delivery (merge requests merged, closed or reopened; branches deleted); +//! - `POST /api/ui/orgs/{org}/projects/{project}/gitlab-webhook`: add the hook now (admins). + +use laravel::auth::Authenticated; +use laravel::db; +use laravel::http::client; +use laravel::prelude::*; +use serde_json::{Value, json}; + +use super::events::{BranchClosed, BranchReopened, PullRequestMerged}; +use super::gitlab::{self, GitlabBot, GitlabConfig}; +use super::webhooks::ForgeEvent; +use super::{ForgeKind, Repository}; +use crate::models::{Project, User}; + +pub fn routes(route: &mut Router) { + route.post("/api/ui/orgs/{org}/projects/{project}/gitlab-webhook", add); +} + +/// The `installation` of a self-managed GitLab project, reached with an access token its admin pasted. +pub const TOKEN: &str = "token"; + +/// How VisualCI reaches a linked GitLab project: the base URL of its GitLab, a token, and the repository. `None` when +/// the project isn't on GitLab, or its GitLab isn't set up here (the bot's token missing, the organization's instance +/// removed, or its stored token unreadable). +/// +/// # Errors +/// On a database error. +pub async fn access(project: &Project) -> laravel::Result> { + let Some(url) = project.repository_url.as_deref() else { return Ok(None) }; + let Some(repository) = Repository::parse_gitlab(url) else { return Ok(None) }; + if project.forge.as_deref() != Some(ForgeKind::Gitlab.as_str()) { + return Ok(None); + } + let repository = repository.with_id(project.repository_id.clone()); + match project.forge_installation.as_deref() { + Some(gitlab::BOT) => { + let config = laravel::config(); + let (Some(gitlab), Some(bot)) = (config.get::(), config.get::()) else { + return Ok(None); + }; + let base = gitlab.url.trim_end_matches('/').to_string(); + let Some(token) = bot.token.clone().filter(|_| repository.site_url().eq_ignore_ascii_case(&base)) else { + return Ok(None); + }; + Ok(Some((base, token, repository))) + } + Some(TOKEN) => { + let Some(instance) = super::instances::for_site(project.organization_id, repository.site_url()).await? + else { + return Ok(None); + }; + let token = project.forge_token_enc.as_deref().and_then(crate::secrets::decrypt); + Ok(token.map(|token| (instance.base_url, token, repository))) + } + _ => Ok(None), + } +} + +/// The hook's URL for a project, on the API's host. +#[must_use] +pub fn hook_url(project: &Project) -> String { + let hosts = laravel::config().get::().cloned(); + let api = hosts.and_then(|h| h.api).unwrap_or_else(|| laravel::config().app.url.clone()); + format!("{}/webhooks/gitlab/{}", api.trim_end_matches('/'), project.pid) +} + +/// Add VisualCI's webhook to a project (merge request and push events, with its secret), or give the one already at +/// VisualCI's URL this secret (a project linked again). `false` when the token can't manage the project's hooks (a +/// Developer, not a Maintainer). +/// +/// # Errors +/// When GitLab can't be reached or refuses for another reason. +pub async fn ensure_hook(base: &str, token: &str, path: &str, url: &str, secret: &str) -> laravel::Result { + let base = base.trim_end_matches('/'); + let project: String = url::form_urlencoded::byte_serialize(path.as_bytes()).collect(); + let hooks = format!("{base}/api/v4/projects/{project}/hooks"); + let (status, existing) = super::outbound::send_json(client::get(&hooks).token(token).accept_json(), base).await?; + if matches!(status, 401 | 403 | 404) { + return Ok(false); + } + if !(200..300).contains(&status) { + return Err(laravel::Error::msg(format!("listing the project's webhooks: HTTP {status}"))); + } + let id = existing.as_array().into_iter().flatten().find(|h| h["url"] == url).and_then(|h| h["id"].as_i64()); + let request = match id { + Some(id) => client::put(format!("{hooks}/{id}")), + None => client::post(&hooks), + }; + let body = json!({ + "url": url, + "token": secret, + "merge_requests_events": true, + // Pushes only for branches deleted (`after` all zeros): their builds stop waiting for review + "push_events": true, + "enable_ssl_verification": url.starts_with("https://"), + }); + let (status, _) = super::outbound::send(request.token(token).json(body), base).await?; + match status { + 200..300 => Ok(true), + 401 | 403 => Ok(false), + _ => Err(laravel::Error::msg(format!("adding the webhook: HTTP {status}"))), + } +} + +/// Add a GitLab project's webhook, when it has none working yet. Returns whether it was added (`false`: it had one, +/// it isn't a GitLab project VisualCI reaches, this server has no `VISUALCI_SECRETS_KEY`, or the token is a Developer +/// rather than a Maintainer and can't manage hooks). +/// +/// # Errors +/// When GitLab can't be reached; database errors. +pub async fn add_webhook(project: &Project) -> laravel::Result { + if project.forge_webhook_at.is_some() { + return Ok(false); + } + let Some(secret) = crate::secrets::webhook_secret(&project.pid) else { return Ok(false) }; + let Some((base, token, repository)) = access(project).await? else { return Ok(false) }; + if !ensure_hook(&base, &token, &repository.path, &hook_url(project), &secret).await? { + return Ok(false); + } + let id = project.id; + db::query!("UPDATE projects SET forge_webhook_at = now() WHERE id = {id}").update().await?; + tracing::info!(project_id = id, repo = repository.path, "GitLab webhook added"); + Ok(true) +} + +/// The hourly run's part: GitLab projects whose webhook isn't working yet, whose bot or token may have become a +/// Maintainer since they were linked, get it now. Returns how many did. +/// +/// # Errors +/// On a database error (one project's GitLab failing is logged, not an error). +pub async fn add_waiting() -> laravel::Result { + let waiting: Vec = + db::query!("SELECT * FROM projects WHERE forge = 'gitlab' AND forge_webhook_at IS NULL ORDER BY id LIMIT 500") + .select_as() + .await?; + let mut added = 0; + for project in &waiting { + match add_webhook(project).await { + Ok(true) => added += 1, + Ok(false) => {} + Err(e) => tracing::warn!(project_id = project.id, error = %e, "adding a GitLab webhook"), + } + } + Ok(added) +} + +/// `POST /api/ui/orgs/{org}/projects/{project}/gitlab-webhook` (admins): add the project's webhook now. Says what's +/// missing when VisualCI can't. +pub async fn add( + Authenticated(user): Authenticated, + Params((org, slug)): Params<(String, String)>, +) -> laravel::Result> { + let (org_id, _) = crate::auth::invitations::admin_org(&user, &org, "add the project's webhook").await?; + let project: Project = db::query!("SELECT * FROM projects WHERE organization_id = {org_id} AND slug = {slug}") + .select_one_as() + .await? + .ok_or_else(|| laravel::abort(404))?; + let added = add_webhook(&project).await?; + if !added && project.forge_webhook_at.is_none() { + return Err(laravel::abort_with( + 400, + "VisualCI can't add webhooks to this project: make @visualci (on your own GitLab, the access token) a \ + Maintainer, or add the webhook yourself with the URL and secret token shown", + )); + } + Ok(Json(json!({ "webhook_added": added, "url": hook_url(&project) }))) +} + +/// One delivery (`X-Gitlab-Event`) as a [`ForgeEvent`]. Checking `X-Gitlab-Token` is the caller's: each project's hook +/// has its own secret. +/// +/// # Errors +/// A merged merge request without its branches or merge commit. +pub fn read_event(kind: &str, event: &Value) -> Result { + let project = || { + let id = event["project"]["id"].as_i64().map(|i| i.to_string()); + event["project"]["web_url"].as_str().and_then(Repository::parse_gitlab).map(|r| r.with_id(id)) + }; + // A fork's branch is named `:` (the CLI names it so too): a fork's `feature` is never the + // project's own `feature`, whose approvals a merge would otherwise carry over + let head_of = |mr: &Value| { + mr["source_branch"].as_str().map(|head| match mr["source"]["path_with_namespace"].as_str() { + Some(fork) if mr["source_project_id"] != mr["target_project_id"] => format!("{fork}:{head}"), + _ => head.to_string(), + }) + }; + let mr = &event["object_attributes"]; + Ok(match (kind, mr["action"].as_str()) { + ("Merge Request Hook", Some("merge")) => { + // A squash merge's commit is the squash commit; otherwise the merge commit (or, fast-forwarded, the head) + let merge = [&mr["merge_commit_sha"], &mr["squash_commit_sha"], &mr["last_commit"]["id"]] + .into_iter() + .find_map(|v| v.as_str().filter(|s| !s.is_empty())); + let (Some(repository), Some(head), Some(base), Some(merge)) = + (project(), head_of(mr), mr["target_branch"].as_str(), merge) + else { + return Err("a merged merge request without its branches or merge commit".into()); + }; + ForgeEvent::Merged { repository, head, base: base.to_string(), merge_commit: merge.to_string() } + } + ("Merge Request Hook", Some(action @ ("close" | "reopen"))) => match (project(), head_of(mr)) { + (Some(repository), Some(branch)) if action == "close" => { + ForgeEvent::Closed { repository, branch, why: "pull_request" } + } + (Some(repository), Some(branch)) => ForgeEvent::Reopened { repository, branch }, + _ => ForgeEvent::Ignored, + }, + // A branch deleted: a push whose new commit is all zeros + ("Push Hook", _) if event["after"].as_str().is_some_and(|a| !a.is_empty() && a.bytes().all(|b| b == b'0')) => { + match (project(), event["ref"].as_str().and_then(|r| r.strip_prefix("refs/heads/"))) { + (Some(repository), Some(branch)) => { + ForgeEvent::Closed { repository, branch: branch.to_string(), why: "branch_deleted" } + } + _ => ForgeEvent::Ignored, + } + } + _ => ForgeEvent::Ignored, + }) +} + +/// Whether a delivery's `X-Gitlab-Token` is the hook's secret, compared in constant time. +#[must_use] +pub fn token_matches(secret: &str, header: &str) -> bool { + let (a, b) = (secret.as_bytes(), header.as_bytes()); + !a.is_empty() && a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 +} + +/// `POST /webhooks/gitlab/{project}`: a project hook's delivery, checked against that project's secret and the +/// repository it links, and acted on for that project only. A project may be on a self-managed instance, so this +/// doesn't need VisualCI's own GitLab configured. Group hooks (membership) name no project, and are left to the hourly +/// sync. +pub async fn delivery( + Params(pid): Params, + headers: axum::http::HeaderMap, + body: axum::body::Bytes, +) -> laravel::Result> { + let refused = || laravel::abort_with(401, "not this project's hook"); + let header = |name: &str| headers.get(name).and_then(|v| v.to_str().ok()).unwrap_or_default().to_string(); + let (kind, token) = (header("x-gitlab-event"), header("x-gitlab-token")); + let pid = laravel::str::Uuid::parse_str(&pid).map_err(|_| refused())?; + let pid_text = pid.to_string(); + let project: Project = + db::query!("SELECT * FROM projects WHERE pid = {pid_text}::uuid").select_one_as().await?.ok_or_else(refused)?; + let secret = crate::secrets::webhook_secret(&project.pid).ok_or_else(refused)?; + if !token_matches(&secret, &token) { + return Err(refused()); + } + let event: Value = serde_json::from_slice(&body).map_err(|e| laravel::abort_with(400, e.to_string()))?; + let named = event["project"]["web_url"].as_str().and_then(Repository::parse_gitlab); + let linked = project.repository_url.as_deref().and_then(Repository::parse_gitlab); + let (Some(repository), Some(linked)) = (named, linked) else { return Err(refused()) }; + if !repository.url.eq_ignore_ascii_case(&linked.url) || access(&project).await?.is_none() { + return Err(refused()); + } + let id = project.id; + db::query!("UPDATE projects SET forge_webhook_at = now() WHERE id = {id}").update().await?; + let outcome = match read_event(&kind, &event).map_err(|e| laravel::abort_with(400, e))? { + ForgeEvent::Merged { head, base, merge_commit, .. } => { + PullRequestMerged { project_id: id, head, base, merge_commit }.dispatch().await?; + json!({ "dispatched": 1 }) + } + ForgeEvent::Closed { branch, why, .. } => { + BranchClosed { project_id: id, branch, why: why.to_string() }.dispatch().await?; + json!({ "dispatched": 1 }) + } + ForgeEvent::Reopened { branch, .. } => { + BranchReopened { project_id: id, branch }.dispatch().await?; + json!({ "dispatched": 1 }) + } + _ => json!({ "ignored": true }), + }; + tracing::info!(forge = "gitlab", kind, repo = repository.path, project_id = id, outcome = %outcome, "webhook"); + Ok(Json(outcome)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn compares_tokens_exactly() { + assert!(token_matches("vciwh_abc", "vciwh_abc")); + assert!(!token_matches("vciwh_abc", "vciwh_abd")); + assert!(!token_matches("vciwh_abc", "vciwh_ab")); + assert!(!token_matches("", ""), "no secret matches nothing"); + } + + #[test] + fn reads_merges_closes_and_deleted_branches() { + let project = json!({ "id": 5, "web_url": "https://gitlab.com/acme/web" }); + let merged = json!({ "project": project, "object_attributes": { + "action": "merge", "source_branch": "feature", "target_branch": "main", + "merge_commit_sha": "m1", "source_project_id": 5, "target_project_id": 5 } }); + let ForgeEvent::Merged { head, base, merge_commit, repository } = + read_event("Merge Request Hook", &merged).unwrap() + else { + panic!("a merge") + }; + assert_eq!((head.as_str(), base.as_str(), merge_commit.as_str()), ("feature", "main", "m1")); + assert_eq!(repository.id.as_deref(), Some("5")); + + let fork = json!({ "project": project, "object_attributes": { + "action": "merge", "source_branch": "feature", "target_branch": "main", "squash_commit_sha": "s1", + "source_project_id": 9, "target_project_id": 5, "source": { "path_with_namespace": "ada/web" } } }); + let ForgeEvent::Merged { head, merge_commit, .. } = read_event("Merge Request Hook", &fork).unwrap() else { + panic!("a merge") + }; + assert_eq!((head.as_str(), merge_commit.as_str()), ("ada/web:feature", "s1"), "a fork's branch is its own"); + + let closed = json!({ "project": project, "object_attributes": { "action": "close", "source_branch": "f" } }); + assert!(matches!( + read_event("Merge Request Hook", &closed).unwrap(), + ForgeEvent::Closed { why: "pull_request", .. } + )); + let deleted = + json!({ "project": project, "ref": "refs/heads/f", "after": "0000000000000000000000000000000000000000" }); + assert!(matches!(read_event("Push Hook", &deleted).unwrap(), ForgeEvent::Closed { why: "branch_deleted", .. })); + let pushed = json!({ "project": project, "ref": "refs/heads/f", "after": "abc" }); + assert_eq!(read_event("Push Hook", &pushed).unwrap(), ForgeEvent::Ignored); + let incomplete = json!({ "project": project, "object_attributes": { "action": "merge" } }); + assert!(read_event("Merge Request Hook", &incomplete).is_err()); + } +} diff --git a/app/src/forge/link.rs b/app/src/forge/link.rs index 929387d4..52cfac46 100644 --- a/app/src/forge/link.rs +++ b/app/src/forge/link.rs @@ -6,8 +6,10 @@ //! link it); a maintainer can move it from another organization, whose admins are told. //! //! GitHub needs the VisualCI GitHub App installed on the repository; GitLab (gitlab.com, or the instance -//! `VISUALCI_GITLAB_URL` names) needs VisualCI's bot as a Developer on the project. Self-managed instances that -//! organizations add are a later port: until then their URLs are refused as unknown. +//! `VISUALCI_GITLAB_URL` names) needs VisualCI's bot as a Developer on the project. A project on a GitLab instance +//! the organization added (`forge::instances`) links with an access token its admin pastes, stored encrypted. Either +//! way VisualCI then adds the project's webhook when it may (a Maintainer); otherwise the project page shows the URL +//! and secret to add (`forge::gitlab_hooks`). use laravel::db; @@ -30,7 +32,7 @@ struct Reached { } /// Link `project` to the repository at `url` for `by`, or unlink it when `url` is empty. Returns the project as it is -/// now. `token` is for self-managed GitLab projects (not ported yet) and is ignored. `move_link` moves a repository +/// now. `token` is the access token for a project on one of the organization's GitLab instances. `move_link` moves a repository /// linked in another organization here; without it that's refused, naming the organization. /// /// Errors are 400s that say what's missing: the forge isn't set up on this server, the URL isn't a repository @@ -46,7 +48,6 @@ pub async fn link_repository( token: Option<&str>, move_link: bool, ) -> laravel::Result { - let _ = token; let config = laravel::config(); let github = config.get::().cloned().ok_or_else(|| laravel::Error::msg("no GitHub App config"))?; let id = project.id; @@ -61,13 +62,30 @@ pub async fn link_repository( super::open_source::refresh(&github, id).await?; return reload(id).await; } - let repository = Repository::parse(url).ok_or_else(|| { + let unknown = || { bad(format!( "{url:?} isn't a repository URL VisualCI knows: https://github.com/owner/name, \ https://gitlab.com/group/project, or a project on a GitLab instance this organization added" )) - })?; + }; + // A repository on GitHub or VisualCI's GitLab, else a project on one of the organization's GitLab instances + let own_gitlab = config.get::().map(|g| g.url.trim_end_matches('/').to_ascii_lowercase()); + let (repository, instance) = match Repository::parse(url) { + Some(r) + if r.forge == ForgeKind::Gitlab && own_gitlab.as_deref() != Some(&r.site_url().to_ascii_lowercase()) => + { + let instance = super::instances::for_site(project.organization_id, r.site_url()).await?; + (r, Some(instance.ok_or_else(unknown)?)) + } + Some(r) => (r, None), + None => { + let r = Repository::parse_gitlab(url).ok_or_else(unknown)?; + let instance = super::instances::for_site(project.organization_id, r.site_url()).await?; + (r, Some(instance.ok_or_else(unknown)?)) + } + }; let label = repository.forge.label(); + let mut stored_token = None; let identity = |site: &str| identity_of(by.id, repository.forge, site.to_string()); let reached = match repository.forge { ForgeKind::Github => { @@ -90,12 +108,41 @@ pub async fn link_repository( }); Reached { installation, permission, repository_id } } + ForgeKind::Gitlab if instance.is_some() => { + let base = instance.as_ref().map(|i| i.base_url.clone()).unwrap_or_default(); + let token = token.map(str::trim).filter(|t| !t.is_empty()).ok_or_else(|| { + bad(format!( + "add an access token for {} (a project or group access token with the api scope and the Developer \ + role, or Maintainer to let VisualCI add its webhook)", + repository.path + )) + })?; + if !gitlab::bot_level(&base, token, &repository.path).await?.is_some_and(|l| l >= 30) { + return Err(bad(format!( + "VisualCI can't reach {} on {base} yet: the access token needs the api scope and at least the \ + Developer role on the project", + repository.path + ))); + } + stored_token = Some( + crate::secrets::encrypt(token) + .ok_or_else(|| bad("this server can't store access tokens (no VISUALCI_SECRETS_KEY)"))?, + ); + let forge_user = identity(&gitlab::site_of(&base)) + .await? + .ok_or_else(|| bad(format!("sign in with {base} first, to show you can manage {}", repository.path)))?; + let permission = gitlab::permission(&base, token, &repository.path, &forge_user).await?; + let repository_id = gitlab::repository_id(&base, token, &repository.path).await.unwrap_or_else(|e| { + tracing::warn!(repo = repository.path, error = %e, "reading the repository's ID"); + None + }); + Reached { installation: super::gitlab_hooks::TOKEN.to_string(), permission, repository_id } + } ForgeKind::Gitlab => { let (Some(gitlab), Some(bot)) = (config.get::(), config.get::()) else { return Err(bad(format!("{label} isn't set up on this server"))); }; let base = gitlab.url.trim_end_matches('/'); - // A project on another GitLab is one an organization added: not ported yet let (true, Some(token)) = (repository.site_url().eq_ignore_ascii_case(base), bot.token.as_deref()) else { return Err(bad(format!("{label} isn't set up on this server"))); }; @@ -134,12 +181,17 @@ pub async fn link_repository( (repository.forge.as_str(), repository.url.clone(), reached.repository_id, reached.installation, by.id); db::query!( "UPDATE projects SET forge = {forge}, repository_url = {repo_url}, repository_id = {repo_id}, \ - forge_installation = {installation}, forge_token_enc = NULL, forge_webhook_at = NULL, \ + forge_installation = {installation}, forge_token_enc = {stored_token}, forge_webhook_at = NULL, \ linked_by = {user_id}, updated_at = now() WHERE id = {id}" ) .update() .await?; tracing::info!(project_id = id, repo = repository.path, by = by.id, "repository linked"); + if repository.forge == ForgeKind::Gitlab + && let Err(e) = super::gitlab_hooks::add_webhook(&reload(id).await?).await + { + tracing::warn!(repo = repository.path, error = %e, "adding the GitLab webhook"); + } // Linking checks the repository at once: public or not, and whether it's open source super::open_source::refresh(&github, id).await?; reload(id).await diff --git a/app/src/forge/mod.rs b/app/src/forge/mod.rs index 1b9bf218..a19dfed6 100644 --- a/app/src/forge/mod.rs +++ b/app/src/forge/mod.rs @@ -6,6 +6,7 @@ pub mod events; pub mod github; pub mod github_app; pub mod gitlab; +pub mod gitlab_hooks; pub mod instances; pub mod link; pub mod open_source; diff --git a/app/src/forge/sync.rs b/app/src/forge/sync.rs index cc211a16..9ad745c2 100644 --- a/app/src/forge/sync.rs +++ b/app/src/forge/sync.rs @@ -204,6 +204,12 @@ pub struct SyncForges; #[job] impl SyncForges { async fn handle(self, app: laravel::config::Section) -> laravel::Result<()> { + // GitLab projects whose webhook isn't working yet, whether or not GitHub is set up here + match super::gitlab_hooks::add_waiting().await { + Ok(0) => {} + Ok(added) => tracing::info!(added, "GitLab webhooks added"), + Err(e) => tracing::warn!(error = %e, "adding GitLab webhooks"), + } 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; diff --git a/app/src/lib.rs b/app/src/lib.rs index 7751c2bb..94204e92 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -78,6 +78,10 @@ pub fn configure() -> ApplicationBuilder { route .post("/webhooks/github", forge::webhooks::github) .middleware(laravel::http::middleware::LimitBody::megabytes(25)); + // Each GitLab project's hook has its own URL and secret + route + .post("/webhooks/gitlab/{project}", forge::gitlab_hooks::delivery) + .middleware(laravel::http::middleware::LimitBody::megabytes(25)); }) .routes(http::renderer::routes) .routes(http::gallery::routes) diff --git a/app/tests/gitlab_hooks.rs b/app/tests/gitlab_hooks.rs new file mode 100644 index 00000000..0c14cb37 --- /dev/null +++ b/app/tests/gitlab_hooks.rs @@ -0,0 +1,150 @@ +//! GitLab projects on an organization's own instance: they link with an access token (stored encrypted), VisualCI adds +//! each project's webhook with its own secret, and a delivery acts on that project alone, refused without its secret +//! or for another repository. + +use app::forge::link::link_repository; +use app::models::{Project, User}; +use app::testing::fixtures; +use laravel::db; +use laravel::http::client; +use laravel::model::create; +use laravel::testing::prelude::*; + +fn with_key() -> Application { + app::testing::configure() + .with_env("VISUALCI_SECRETS_KEY", "test-secrets-key") + .with_env("VISUALCI_API_URL", "https://api.visualci.test") + .create() +} + +/// Ada, signed in with acme's instance at gitlab.example.com (77), admin of `acme` and its project `web`. +async fn ada_and_web() -> laravel::Result<(User, Project)> { + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let id = ada.id; + db::query!( + "INSERT INTO identities (user_id, forge, site, forge_user_id, login, created_at, updated_at) \ + VALUES ({id}, 'gitlab', 'https://gitlab.example.com', '77', 'ada', now(), now())" + ) + .insert() + .await?; + let org = fixtures::organization("acme").await?; + fixtures::member(&org, &ada, "admin").await?; + app::forge::instances::upsert(org.id, "https://gitlab.example.com", "app-id", "app-secret", id).await?; + let web = fixtures::project(&org, "web").await?; + Ok((ada, web)) +} + +/// The instance's answers for acme/web, to its access token: a Maintainer, Ada a Maintainer, no hooks yet. +fn instance() -> client::HttpFake { + client::fake() + .with("gitlab.example.com/api/v4/projects/acme%2Fweb/hooks*", json!({ "id": 1 })) + .with("gitlab.example.com/api/v4/projects/acme%2Fweb/members/all/77", json!({ "access_level": 40 })) + .with( + "gitlab.example.com/api/v4/projects/acme%2Fweb", + json!({ "id": 5, "permissions": { "project_access": { "access_level": 40 } } }), + ) +} + +#[laravel::test(app = with_key)] +async fn a_project_on_the_organizations_instance_links_with_a_token(_app: Application) -> laravel::Result<()> { + let (ada, web) = ada_and_web().await?; + let api = instance(); + let url = "https://gitlab.example.com/acme/web"; + + let refused = link_repository(web.clone(), &ada, url, None, false).await.unwrap_err(); + assert!(refused.to_string().contains("add an access token"), "{refused}"); + + let linked = link_repository(web, &ada, url, Some(" glpat-secret "), false).await?; + assert_eq!(linked.forge.as_deref(), Some("gitlab")); + assert_eq!(linked.repository_url.as_deref(), Some(url)); + assert_eq!(linked.repository_id.as_deref(), Some("5")); + assert_eq!(linked.forge_installation.as_deref(), Some("token")); + let stored = linked.forge_token_enc.clone().expect("the token stored"); + assert!(!stored.contains("glpat"), "stored encrypted"); + assert_eq!(app::secrets::decrypt(&stored).as_deref(), Some("glpat-secret")); + assert!(linked.forge_webhook_at.is_some(), "VisualCI added the webhook"); + + let hook = + api.sent().into_iter().find(|r| r.method() == "POST" && r.url().ends_with("/hooks")).expect("the hook added"); + let body: serde_json::Value = hook.json().unwrap(); + assert_eq!(body["url"], format!("https://api.visualci.test/webhooks/gitlab/{}", linked.pid)); + assert_eq!(body["token"].as_str(), app::secrets::webhook_secret(&linked.pid).as_deref()); + assert_eq!(hook.header("authorization"), Some("Bearer glpat-secret")); + Ok(()) +} + +#[laravel::test(app = with_key)] +async fn a_url_on_an_instance_the_organization_didnt_add_is_unknown(_app: Application) -> laravel::Result<()> { + let (ada, web) = ada_and_web().await?; + let e = link_repository(web, &ada, "https://git.other.example/acme/web", Some("t"), false).await.unwrap_err(); + assert!(e.to_string().contains("isn't a repository URL VisualCI knows"), "{e}"); + Ok(()) +} + +/// `web` linked to acme/web on the instance with a token. +async fn linked_web() -> laravel::Result { + let (_, web) = ada_and_web().await?; + let (id, token) = (web.id, app::secrets::encrypt("glpat-secret").unwrap()); + db::query!( + "UPDATE projects SET forge = 'gitlab', repository_url = 'https://gitlab.example.com/acme/web', \ + forge_installation = 'token', forge_token_enc = {token} WHERE id = {id}" + ) + .update() + .await?; + Project::find_or_fail(id).await +} + +fn merged(web_url: &str) -> serde_json::Value { + json!({ + "project": { "id": 5, "web_url": web_url }, + "object_attributes": { "action": "merge", "source_branch": "feature", "target_branch": "main", + "merge_commit_sha": "m1", "source_project_id": 5, "target_project_id": 5 }, + }) +} + +#[laravel::test(app = with_key)] +async fn a_delivery_acts_on_its_own_project(app: Application) -> laravel::Result<()> { + let web = linked_web().await?; + let secret = app::secrets::webhook_secret(&web.pid).unwrap(); + let path = format!("/webhooks/gitlab/{}", web.pid); + app.post(&path) + .header("x-gitlab-event", "Merge Request Hook") + .header("x-gitlab-token", &secret) + .json(merged("https://gitlab.example.com/acme/web")) + .await + .assert_ok() + .assert_json_path("dispatched", 1); + let web = Project::find_or_fail(web.id).await?; + assert!(web.forge_webhook_at.is_some(), "a delivery shows the hook works"); + Ok(()) +} + +#[laravel::test(app = with_key)] +async fn a_delivery_without_the_projects_secret_or_for_another_repository_is_refused( + app: Application, +) -> laravel::Result<()> { + let web = linked_web().await?; + let secret = app::secrets::webhook_secret(&web.pid).unwrap(); + let path = format!("/webhooks/gitlab/{}", web.pid); + for (token, repo) in [ + ("vciwh_wrong", "https://gitlab.example.com/acme/web"), + ("", "https://gitlab.example.com/acme/web"), + (secret.as_str(), "https://gitlab.example.com/acme/other"), + ] { + app.post(&path) + .header("x-gitlab-event", "Merge Request Hook") + .header("x-gitlab-token", token) + .json(merged(repo)) + .await + .assert_status(401); + } + app.post(format!("/webhooks/gitlab/{}", laravel::str::uuid7())) + .header("x-gitlab-event", "Merge Request Hook") + .header("x-gitlab-token", &secret) + .json(merged("https://gitlab.example.com/acme/web")) + .await + .assert_status(401); + let web = Project::find_or_fail(web.id).await?; + assert!(web.forge_webhook_at.is_none()); + Ok(()) +} From 3165f6a951434b999bef6875d636aa87479a6440 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 12:04:26 +1300 Subject: [PATCH 4/5] app/: the hourly sync's GitLab part (sc-8900, forge, ported): forge::gitlab_sync rechecks everyone's GitLab memberships from each linked project's members, per site (gitlab.com through the bot, an organization's instance through each project's token), changing nobody at a site where some project can't be read; GitLab projects' open source status (only gitlab.com's count); the heartbeat fails when the bot's token expires within 30 days or is revoked, or a GitLab can't be read; webhooks still missing are added each run --- app/src/forge/gitlab.rs | 62 ++++++++++++++++ app/src/forge/gitlab_sync.rs | 121 +++++++++++++++++++++++++++++++ app/src/forge/mod.rs | 1 + app/src/forge/open_source.rs | 54 +++++++++++++- app/src/forge/sync.rs | 38 ++++++---- app/tests/gitlab_sync.rs | 134 +++++++++++++++++++++++++++++++++++ 6 files changed, 393 insertions(+), 17 deletions(-) create mode 100644 app/src/forge/gitlab_sync.rs create mode 100644 app/tests/gitlab_sync.rs diff --git a/app/src/forge/gitlab.rs b/app/src/forge/gitlab.rs index adb035e3..5d998740 100644 --- a/app/src/forge/gitlab.rs +++ b/app/src/forge/gitlab.rs @@ -187,6 +187,54 @@ async fn get(base: &str, token: &str, path: &str) -> laravel::Result laravel::Result> { + all_pages(base, token, &format!("/projects/{project_id}/members/all")).await +} + +/// Days until a personal access token expires (`None`: it never does). +/// +/// # Errors +/// When the token is unknown to GitLab, revoked or already expired, or GitLab can't be reached. +pub async fn token_days_left(base: &str, token: &str) -> laravel::Result> { + let me = get(base, token, "/personal_access_tokens/self") + .await? + .ok_or_else(|| laravel::Error::msg("it isn't known to GitLab"))?; + if me["active"] == false || me["revoked"] == true { + return Err(laravel::Error::msg("it's revoked or expired")); + } + let Some(expires) = me["expires_at"].as_str() else { return Ok(None) }; + let day = days_since_epoch(expires).ok_or_else(|| laravel::Error::msg(format!("an expiry date {expires:?}")))?; + let today = laravel::now().timestamp().as_second().div_euclid(86_400); + Ok(Some(day - today)) +} + +/// Days from 1970-01-01 to a `YYYY-MM-DD` date (the proleptic Gregorian calendar). +fn days_since_epoch(date: &str) -> Option { + let mut parts = date.splitn(3, '-').map(str::parse::); + let (y, m, d) = (parts.next()?.ok()?, parts.next()?.ok()?, parts.next()?.ok()?); + if !(1..=12).contains(&m) || !(1..=31).contains(&d) { + return None; + } + let y = if m <= 2 { y - 1 } else { y }; + let era = y.div_euclid(400); + let yoe = y - era * 400; + let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + Some(era * 146_097 + doe - 719_468) +} + +/// A project (`group/sub/project`, or its ID) with the licence GitLab detected; `None` when the token can't see it. +/// +/// # Errors +/// When GitLab can't be reached or refuses the token. +pub async fn project_with_licence(base: &str, token: &str, path: &str) -> laravel::Result> { + get(base, token, &format!("/projects/{}?license=true", project_id(path))).await +} + /// The bot's access level on a project (`group/sub/project`), when it's a member. /// /// # Errors @@ -230,3 +278,17 @@ pub fn install_hint(base: &str, bot: &str, path: &str) -> String { let base = base.trim_end_matches('/'); format!("invite @{bot} to {path} as a Developer ({base}/{path}/-/project_members), then link it") } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn counts_days_to_a_date() { + assert_eq!(days_since_epoch("1970-01-01"), Some(0)); + assert_eq!(days_since_epoch("2000-03-01"), Some(11_017)); + assert_eq!(days_since_epoch("2026-12-03"), Some(20_790)); + assert_eq!(days_since_epoch("2026-13-01"), None); + assert_eq!(days_since_epoch("soon"), None); + } +} diff --git a/app/src/forge/gitlab_sync.rs b/app/src/forge/gitlab_sync.rs new file mode 100644 index 00000000..4bba14d7 --- /dev/null +++ b/app/src/forge/gitlab_sync.rs @@ -0,0 +1,121 @@ +//! The hourly sync's GitLab part (sc-8900, the forge side), ported from today's `forge:sync`: everyone's +//! GitLab-derived memberships are rechecked from each linked GitLab project's members (through VisualCI's bot, or the +//! project's own access token on an organization's instance), so access lost without a webhook goes within the hour. +//! A site where some linked project can't be read changes nobody's memberships that run: a partial answer would drop +//! people. +//! +//! The bot's token is checked too: GitLab tokens last at most a year, and an expired one stops every status, note and +//! access check, so the sync's heartbeat fails a month ahead. + +use std::collections::HashMap; + +use laravel::db; + +use super::gitlab::{self, GitlabBot, GitlabConfig}; +use super::{ForgeKind, Permission, Repository}; +use crate::models::Project; + +/// How many days before the GitLab bot's token expires the sync's heartbeat starts failing. +pub const BOT_TOKEN_WARN_DAYS: i64 = 30; + +/// What a GitLab sync did. +#[derive(Debug, Default)] +pub struct Synced { + pub people: usize, + pub changed: usize, + /// Sites whose projects couldn't all be read, so nobody there changed. + pub failed_sites: Vec, +} + +/// Each site's linked projects as VisualCI reaches them: site ('' for gitlab.com) -> (base, token, repository). +async fn linked_by_site() -> laravel::Result>> { + let projects: Vec = db::query!( + "SELECT * FROM projects WHERE forge = 'gitlab' AND repository_id IS NOT NULL \ + AND forge_installation IS NOT NULL ORDER BY id" + ) + .select_as() + .await?; + let mut sites: HashMap> = HashMap::new(); + for project in &projects { + if let Some((base, token, repository)) = super::gitlab_hooks::access(project).await? { + let list = sites.entry(gitlab::site_of(&base)).or_default(); + if !list.iter().any(|(_, _, r)| r.id == repository.id) { + list.push((base, token, repository)); + } + } + } + Ok(sites) +} + +/// GitLab user ID -> the linked repositories they're a member of on this site, with their permission. +async fn reach( + projects: &[(String, String, Repository)], +) -> laravel::Result>> { + let mut people: HashMap> = HashMap::new(); + for (base, token, repository) in projects { + let id = repository.id.clone().unwrap_or_default(); + for member in gitlab::members(base, token, &id).await? { + let (Some(user), Some(permission)) = ( + member["id"].as_i64().map(|i| i.to_string()), + member["access_level"].as_i64().and_then(gitlab::permission_from_level), + ) else { + continue; + }; + people.entry(user).or_default().push((repository.clone(), permission)); + } + } + Ok(people) +} + +/// Recheck everyone signed in with a GitLab. +/// +/// # Errors +/// On a database error (a GitLab failing is a failed site). +pub async fn sync_gitlab() -> laravel::Result { + let mut sites = linked_by_site().await?; + let identity_sites: Vec = db::query!("SELECT DISTINCT site FROM identities WHERE forge = 'gitlab'") + .select() + .await? + .iter() + .map(|r| r.try_get("site")) + .collect::>()?; + for site in identity_sites { + sites.entry(site).or_default(); + } + let mut synced = Synced::default(); + for (site, projects) in &sites { + let people = match reach(projects).await { + Ok(people) => people, + Err(e) => { + tracing::warn!(site, error = %e, "GitLab sync: couldn't read every linked project's members"); + synced.failed_sites.push(if site.is_empty() { "gitlab.com".to_string() } else { site.clone() }); + continue; + } + }; + let rows = db::query!("SELECT user_id, forge_user_id FROM identities WHERE forge = 'gitlab' AND site = {site}") + .select() + .await?; + for row in rows { + let (user_id, forge_user): (i64, String) = (row.try_get("user_id")?, row.try_get("forge_user_id")?); + let list = people.get(&forge_user).cloned().unwrap_or_default(); + synced.changed += crate::auth::memberships::apply(user_id, ForgeKind::Gitlab, site, &list).await?; + synced.people += 1; + } + } + Ok(synced) +} + +/// What's wrong with the GitLab bot's token, for the heartbeat: expiring within [`BOT_TOKEN_WARN_DAYS`], revoked, or +/// unknown to GitLab. `None` when it's fine, or no bot is set up. +pub async fn bot_token_problem() -> Option { + let config = laravel::config(); + let token = config.get::()?.token.clone()?; + let base = config.get::()?.url.trim_end_matches('/').to_string(); + match gitlab::token_days_left(&base, &token).await { + Ok(Some(days)) if days < BOT_TOKEN_WARN_DAYS => Some(format!( + "the GitLab bot's token expires in {days} days: make a new one (1Password visualci-gitlab-bot-token)" + )), + Ok(_) => None, + Err(e) => Some(format!("the GitLab bot's token: {e}")), + } +} diff --git a/app/src/forge/mod.rs b/app/src/forge/mod.rs index a19dfed6..61fd545e 100644 --- a/app/src/forge/mod.rs +++ b/app/src/forge/mod.rs @@ -7,6 +7,7 @@ pub mod github; pub mod github_app; pub mod gitlab; pub mod gitlab_hooks; +pub mod gitlab_sync; pub mod instances; pub mod link; pub mod open_source; diff --git a/app/src/forge/open_source.rs b/app/src/forge/open_source.rs index 9ac5ae12..aa89982b 100644 --- a/app/src/forge/open_source.rs +++ b/app/src/forge/open_source.rs @@ -112,13 +112,14 @@ struct Project { repository_url: Option, repository_id: Option, installation: Option, + gitlab: bool, } 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)" + (open_source AND public AND NOT open_source_withdrawn) AS counts, forge = 'gitlab' AS gitlab \ + FROM projects WHERE id = {id} AND (forge IN ('github', 'gitlab') OR forge IS NULL)" ) .select_one() .await? @@ -134,6 +135,7 @@ async fn project(id: i64) -> laravel::Result> { repository_url: r.try_get("repository_url")?, repository_id: r.try_get("repository_id")?, installation: r.try_get("forge_installation")?, + gitlab: r.try_get::>("gitlab")?.unwrap_or(false), })) } @@ -145,6 +147,9 @@ async fn check(app: &GithubApp, p: &Project) -> Option { 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.")); }; + if p.gitlab { + return check_gitlab(p).await; + } 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 @@ -173,6 +178,49 @@ async fn check(app: &GithubApp, p: &Project) -> Option { /// /// # Errors /// On a database error. +/// A GitLab project, through its bot or access token. A self-managed GitLab answers for itself, and anyone can run +/// one: only github.com and gitlab.com repositories draw on the pool (a self-managed one can still be public). +async fn check_gitlab(p: &Project) -> Option { + let answer = async { + let Some(project) = crate::models::Project::find(p.id).await? else { return Ok(None) }; + let Some((base, token, repository)) = super::gitlab_hooks::access(&project).await? else { + return Ok(Some(None)); + }; + let path = repository.id.clone().unwrap_or_else(|| repository.path.clone()); + let repo = super::gitlab::project_with_licence(&base, &token, &path).await?; + Ok::<_, laravel::Error>(Some(Some((base, repo)))) + }; + match answer.await { + Ok(None) => None, + Ok(Some(None)) => Some(Status::no(false, "VisualCI's app or bot doesn't have access to its repository.")), + Ok(Some(Some((_, None)))) => Some(Status::no(false, "VisualCI can't see its repository.")), + Ok(Some(Some((base, Some(repo))))) => { + let public = repo["visibility"] == "public"; + if !base.eq_ignore_ascii_case("https://gitlab.com") { + return Some(Status::no( + public, + "Only github.com and gitlab.com repositories count as open source; this one is on a self-managed \ + GitLab.", + )); + } + // GitLab names licences by a lowercase key (`mit`, `apache-2.0`): as an SPDX id where it's one we know + let licence = repo["license"]["key"].as_str().map(|key| { + OSI_LICENCES + .iter() + .find(|l| l.eq_ignore_ascii_case(key)) + .map_or_else(|| key.to_string(), |l| (*l).to_string()) + }); + Some(Status::of(&serde_json::json!({ + "private": !public, "visibility": repo["visibility"], "license": { "spdx_id": licence }, + }))) + } + Err(e) => { + tracing::warn!(project_id = p.id, error = %e, "couldn't check a project's repository"); + None + } + } +} + 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; @@ -250,7 +298,7 @@ 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) \ + "SELECT id FROM projects WHERE (forge IN ('github', 'gitlab') 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) \ diff --git a/app/src/forge/sync.rs b/app/src/forge/sync.rs index 9ad745c2..e97eefb8 100644 --- a/app/src/forge/sync.rs +++ b/app/src/forge/sync.rs @@ -204,22 +204,31 @@ pub struct SyncForges; #[job] impl SyncForges { async fn handle(self, app: laravel::config::Section) -> laravel::Result<()> { - // GitLab projects whose webhook isn't working yet, whether or not GitHub is set up here + let mut problems = Vec::new(); + // GitLab: memberships, webhooks not working yet, and the bot's token, whether or not GitHub is set up here + match super::gitlab_sync::sync_gitlab().await { + Ok(s) => { + tracing::info!(people = s.people, changed = s.changed, failed_sites = ?s.failed_sites, "GitLab sync"); + if !s.failed_sites.is_empty() { + problems.push(format!("GitLab couldn't be read at {}", s.failed_sites.join(", "))); + } + } + Err(e) => problems.push(format!("GitLab sync: {e}")), + } match super::gitlab_hooks::add_waiting().await { Ok(0) => {} Ok(added) => tracing::info!(added, "GitLab webhooks added"), Err(e) => tracing::warn!(error = %e, "adding GitLab webhooks"), } - 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!( + problems.extend(super::gitlab_sync::bot_token_problem().await); + let result = if app.app_id.as_deref().is_none_or(str::is_empty) { + problems.push("the GitHub App isn't configured (GITHUB_APP_ID), so nobody's access is rechecked".into()); + Ok(()) + } else { + let result = sync_github(&app).await; + match &result { + Err(e) => problems.push(e.to_string()), + Ok(s) => tracing::info!( people = s.people, changed = s.changed, unlinked = s.unlinked, @@ -227,12 +236,13 @@ impl SyncForges { branches_closed = s.branches_closed, deferred = s.deferred, "forge sync" - ); - Ok(()) + ), } + result.map(|_| ()) }; + let health = if problems.is_empty() { Ok(()) } else { Err(problems.join("; ")) }; crate::heartbeat::push("VISUALCI_FORGE_SYNC_HEARTBEAT", health).await; - result.map(|_| ()) + result } } diff --git a/app/tests/gitlab_sync.rs b/app/tests/gitlab_sync.rs new file mode 100644 index 00000000..41cec3ab --- /dev/null +++ b/app/tests/gitlab_sync.rs @@ -0,0 +1,134 @@ +//! The hourly sync's GitLab part: memberships follow each linked project's members (a site where some project can't be +//! read changes nobody), a gitlab.com project's open source status comes from GitLab, and the bot's token is watched +//! for its expiry. + +use app::forge::gitlab_sync::{bot_token_problem, sync_gitlab}; +use app::models::User; +use laravel::db; +use laravel::http::client; +use laravel::model::create; +use laravel::testing::prelude::*; + +fn bot() -> Application { + app::testing::configure().with_env("VISUALCI_GITLAB_BOT_TOKEN", "bot-token").create() +} + +/// Ada (gitlab.com 2002), and `acme/web` linked to gitlab.com/acme/web (5) through the bot. Returns Ada's ID and acme's. +async fn ada_and_acme() -> laravel::Result<(i64, i64)> { + 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}, 'gitlab', '', '2002', '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(); + 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', 'gitlab', 'https://gitlab.com/acme/web', '5', 'bot', \ + now(), now())" + ) + .insert() + .await?; + Ok((ada_id, org)) +} + +async fn role_in(org: i64, user: i64) -> laravel::Result> { + db::query!("SELECT role FROM memberships WHERE organization_id = {org} AND user_id = {user} AND source = 'gitlab'") + .scalar() + .await +} + +#[laravel::test(app = bot)] +async fn memberships_follow_the_projects_members(_app: Application) -> laravel::Result<()> { + let (ada, acme) = ada_and_acme().await?; + let gitlab = client::fake() + .with("gitlab.com/api/v4/projects/5/members/all*", json!([{ "id": 2002, "access_level": 40 }, { "id": 9 }])); + let synced = sync_gitlab().await?; + assert_eq!((synced.people, synced.changed), (1, 1)); + assert!(synced.failed_sites.is_empty()); + assert!(role_in(acme, ada).await?.is_some(), "a Maintainer on the project is in its organization"); + assert!(gitlab.sent()[0].header("authorization").is_some_and(|h| h == "Bearer bot-token")); + + // No longer a member: the membership goes + let _gitlab = client::fake().with("gitlab.com/api/v4/projects/5/members/all*", json!([])); + sync_gitlab().await?; + assert_eq!(role_in(acme, ada).await?, None); + Ok(()) +} + +#[laravel::test(app = bot)] +async fn a_gitlab_that_cant_be_read_changes_nobody(_app: Application) -> laravel::Result<()> { + let (ada, acme) = ada_and_acme().await?; + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({acme}, {ada}, 'member', 'gitlab', now(), now())" + ) + .insert() + .await?; + let _gitlab = client::fake().with("gitlab.com/api/v4/projects/5/members/all*", client::response().status(502)); + let synced = sync_gitlab().await?; + assert_eq!(synced.failed_sites, vec!["gitlab.com".to_string()]); + assert_eq!(role_in(acme, ada).await?.as_deref(), Some("member"), "kept until GitLab answers"); + Ok(()) +} + +#[laravel::test(app = bot)] +async fn a_gitlab_com_projects_open_source_status_comes_from_gitlab(_app: Application) -> laravel::Result<()> { + let (_, acme) = ada_and_acme().await?; + let _gitlab = client::fake() + .with("gitlab.com/api/v4/projects/5*", json!({ "id": 5, "visibility": "public", "license": { "key": "mit" } })); + let id: i64 = db::query!("SELECT id FROM projects WHERE organization_id = {acme}").scalar().await?.unwrap(); + let github = laravel::config().get::().cloned().unwrap(); + app::forge::open_source::refresh(&github, id).await?; + let (public, open_source): (bool, bool) = { + let row = db::query!("SELECT repository_public, open_source FROM projects WHERE id = {id}") + .select_one() + .await? + .unwrap(); + (row.try_get("repository_public")?, row.try_get("open_source")?) + }; + assert!(public && open_source, "public, MIT"); + Ok(()) +} + +#[laravel::test(app = bot)] +async fn the_bots_token_is_watched_for_its_expiry(_app: Application) -> laravel::Result<()> { + let soon = (laravel::now().timestamp().as_second() / 86_400) + 10; + let soon = { + // Days since the epoch back to a date + let z = soon + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = yoe + era * 400 + i64::from(m <= 2); + format!("{y:04}-{m:02}-{d:02}") + }; + let _gitlab = client::fake().with( + "gitlab.com/api/v4/personal_access_tokens/self", + json!({ "active": true, "revoked": false, "expires_at": soon }), + ); + let problem = bot_token_problem().await.expect("a warning"); + assert!(problem.contains("expires in 10 days"), "{problem}"); + + let _gitlab = client::fake() + .with("gitlab.com/api/v4/personal_access_tokens/self", json!({ "active": false, "revoked": true })); + assert!(bot_token_problem().await.expect("a failure").contains("revoked")); + + let _gitlab = client::fake() + .with("gitlab.com/api/v4/personal_access_tokens/self", json!({ "active": true, "expires_at": null })); + assert_eq!(bot_token_problem().await, None, "a token that never expires"); + Ok(()) +} From 8662dafe3da3e1103c1f94d80c9eb357f4c78113 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 12:40:29 +1300 Subject: [PATCH 5/5] app/: GitLab review fixes (sc-8900): gitlab.com subdomains and IP literals refused as instances, proxies off and one 30-second deadline for an organization's server, a 16 MB cap across list pages, one unreadable project holds back only its organizations' memberships, forge tokens never serialised, the webhook's URL and secret shown to admins, instances listed --- app/src/auth/memberships.rs | 18 +++++++- app/src/forge/gitlab.rs | 16 +++++-- app/src/forge/gitlab_hooks.rs | 41 +++++++++++++++--- app/src/forge/gitlab_sync.rs | 78 +++++++++++++++++++++-------------- app/src/forge/instances.rs | 68 +++++++++++++++++++----------- app/src/forge/outbound.rs | 57 ++++++++++++++++++------- app/src/forge/sync.rs | 6 +-- app/src/models/projects.rs | 2 + app/tests/gitlab_hooks.rs | 18 ++++++++ app/tests/gitlab_sync.rs | 41 +++++++++++++++++- 10 files changed, 261 insertions(+), 84 deletions(-) diff --git a/app/src/auth/memberships.rs b/app/src/auth/memberships.rs index 4ea95108..1ce6a0f1 100644 --- a/app/src/auth/memberships.rs +++ b/app/src/auth/memberships.rs @@ -97,12 +97,28 @@ pub async fn apply( forge: ForgeKind, site: &str, repositories: &[(Repository, Permission)], +) -> laravel::Result { + apply_keeping(user_id, forge, site, repositories, &HashSet::new()).await +} + +/// [`apply`], never removing the memberships of the organizations in `keep`: the hourly sync's, for organizations +/// with a linked repository the forge couldn't be asked about this time. +/// +/// # Errors +/// On a database error. +pub async fn apply_keeping( + user_id: i64, + forge: ForgeKind, + site: &str, + repositories: &[(Repository, Permission)], + keep: &HashSet, ) -> laravel::Result { let permissions: HashMap = repositories.iter().filter_map(|(r, p)| r.id.clone().map(|id| (id, *p))).collect(); let all = linked_projects(forge).await?; let here: Vec<&LinkedProject> = all.iter().filter(|p| p.site == site).collect(); - let elsewhere: HashSet = all.iter().filter(|p| p.site != site).map(|p| p.organization_id).collect(); + let mut elsewhere: HashSet = all.iter().filter(|p| p.site != site).map(|p| p.organization_id).collect(); + elsewhere.extend(keep); let grants = grants_from(&here, &permissions); let source = forge.as_str(); diff --git a/app/src/forge/gitlab.rs b/app/src/forge/gitlab.rs index 5d998740..2425802f 100644 --- a/app/src/forge/gitlab.rs +++ b/app/src/forge/gitlab.rs @@ -114,17 +114,25 @@ pub fn site_of(base: &str) -> String { if base == "https://gitlab.com" { String::new() } else { base } } -/// Every item of a paged API list, 100 a page, up to 50 pages. +/// The most a paged list may read in all, across its pages: an organization's own instance answers these. +const MAX_LIST_BYTES: usize = 16 * 1024 * 1024; + +/// Every item of a paged API list, 100 a page, up to 50 pages and [`MAX_LIST_BYTES`] in all. async fn all_pages(base: &str, token: &str, path: &str) -> laravel::Result> { let mut items = Vec::new(); + let mut read = 0; for page in 1..=50 { let sep = if path.contains('?') { '&' } else { '?' }; - let (status, body) = - super::outbound::get_json(base, token, &format!("/api/v4{path}{sep}per_page=100&page={page}")).await?; + let url = format!("{}/api/v4{path}{sep}per_page=100&page={page}", base.trim_end_matches('/')); + let (status, body) = super::outbound::send(client::get(url).token(token).accept_json(), base).await?; if !(200..300).contains(&status) { return Err(laravel::Error::msg(format!("GitLab {path}: HTTP {status}"))); } - let batch: Vec = serde_json::from_value(body).map_err(|e| laravel::Error::msg(e.to_string()))?; + read += body.len(); + if read > MAX_LIST_BYTES { + return Err(laravel::Error::msg(format!("GitLab {path}: more than {MAX_LIST_BYTES} bytes in all"))); + } + let batch: Vec = serde_json::from_str(&body).map_err(|e| laravel::Error::msg(e.to_string()))?; let done = batch.len() < 100; items.extend(batch); if done { diff --git a/app/src/forge/gitlab_hooks.rs b/app/src/forge/gitlab_hooks.rs index a9a739b5..d5d3cd57 100644 --- a/app/src/forge/gitlab_hooks.rs +++ b/app/src/forge/gitlab_hooks.rs @@ -21,9 +21,41 @@ use super::{ForgeKind, Repository}; use crate::models::{Project, User}; pub fn routes(route: &mut Router) { + route.get("/api/ui/orgs/{org}/projects/{project}/gitlab-webhook", show); route.post("/api/ui/orgs/{org}/projects/{project}/gitlab-webhook", add); } +/// A GitLab project's webhook as its page shows it: the URL, and for admins its secret, to add it by hand when VisualCI +/// can't (its bot or token a Developer rather than a Maintainer); when it last worked. `None` for other projects. +#[must_use] +pub fn webhook_json(project: &Project, admin: bool) -> Option { + (project.forge.as_deref() == Some(ForgeKind::Gitlab.as_str())).then(|| { + json!({ + "url": hook_url(project), + "secret": if admin { crate::secrets::webhook_secret(&project.pid) } else { None }, + "working_since": project.forge_webhook_at.map(|t| t.to_string()), + }) + }) +} + +/// An organization's project by slug, for its admins. +async fn admins_project(user: &User, org: &str, slug: &str, action: &str) -> laravel::Result { + let (org_id, _) = crate::auth::invitations::admin_org(user, org, action).await?; + db::query!("SELECT * FROM projects WHERE organization_id = {org_id} AND slug = {slug}") + .select_one_as() + .await? + .ok_or_else(|| laravel::abort(404)) +} + +/// `GET /api/ui/orgs/{org}/projects/{project}/gitlab-webhook` (admins): the hook's URL and secret. +pub async fn show( + Authenticated(user): Authenticated, + Params((org, slug)): Params<(String, String)>, +) -> laravel::Result> { + let project = admins_project(&user, &org, &slug, "see the project's webhook").await?; + Ok(Json(json!({ "gitlab_webhook": webhook_json(&project, true) }))) +} + /// The `installation` of a self-managed GitLab project, reached with an access token its admin pasted. pub const TOKEN: &str = "token"; @@ -158,11 +190,7 @@ pub async fn add( Authenticated(user): Authenticated, Params((org, slug)): Params<(String, String)>, ) -> laravel::Result> { - let (org_id, _) = crate::auth::invitations::admin_org(&user, &org, "add the project's webhook").await?; - let project: Project = db::query!("SELECT * FROM projects WHERE organization_id = {org_id} AND slug = {slug}") - .select_one_as() - .await? - .ok_or_else(|| laravel::abort(404))?; + let project = admins_project(&user, &org, &slug, "add the project's webhook").await?; let added = add_webhook(&project).await?; if !added && project.forge_webhook_at.is_none() { return Err(laravel::abort_with( @@ -171,7 +199,8 @@ pub async fn add( Maintainer, or add the webhook yourself with the URL and secret token shown", )); } - Ok(Json(json!({ "webhook_added": added, "url": hook_url(&project) }))) + let project = Project::find_or_fail(project.id).await?; + Ok(Json(json!({ "webhook_added": added, "gitlab_webhook": webhook_json(&project, true) }))) } /// One delivery (`X-Gitlab-Event`) as a [`ForgeEvent`]. Checking `X-Gitlab-Token` is the caller's: each project's hook diff --git a/app/src/forge/gitlab_sync.rs b/app/src/forge/gitlab_sync.rs index 4bba14d7..ec26a72e 100644 --- a/app/src/forge/gitlab_sync.rs +++ b/app/src/forge/gitlab_sync.rs @@ -1,13 +1,13 @@ //! The hourly sync's GitLab part (sc-8900, the forge side), ported from today's `forge:sync`: everyone's //! GitLab-derived memberships are rechecked from each linked GitLab project's members (through VisualCI's bot, or the //! project's own access token on an organization's instance), so access lost without a webhook goes within the hour. -//! A site where some linked project can't be read changes nobody's memberships that run: a partial answer would drop -//! people. +//! A linked project that can't be read this time (its token revoked, its GitLab down) holds back only the memberships +//! of the organizations linking it: another organization's revoked token doesn't stop everyone else's sync. //! //! The bot's token is checked too: GitLab tokens last at most a year, and an expired one stops every status, note and //! access check, so the sync's heartbeat fails a month ahead. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use laravel::db; @@ -23,48 +23,71 @@ pub const BOT_TOKEN_WARN_DAYS: i64 = 30; pub struct Synced { pub people: usize, pub changed: usize, - /// Sites whose projects couldn't all be read, so nobody there changed. - pub failed_sites: Vec, + /// Linked repositories that couldn't be read (their URLs): their organizations' memberships stayed as they were. + pub failed: Vec, } -/// Each site's linked projects as VisualCI reaches them: site ('' for gitlab.com) -> (base, token, repository). -async fn linked_by_site() -> laravel::Result>> { +/// A linked project as VisualCI reaches it: its organization, base URL, token and repository. +struct Reached { + organization_id: i64, + base: String, + token: String, + repository: Repository, +} + +/// Each site's linked projects as VisualCI reaches them, by site ('' for gitlab.com). +async fn linked_by_site() -> laravel::Result>> { let projects: Vec = db::query!( "SELECT * FROM projects WHERE forge = 'gitlab' AND repository_id IS NOT NULL \ AND forge_installation IS NOT NULL ORDER BY id" ) .select_as() .await?; - let mut sites: HashMap> = HashMap::new(); + let mut sites: HashMap> = HashMap::new(); for project in &projects { if let Some((base, token, repository)) = super::gitlab_hooks::access(project).await? { - let list = sites.entry(gitlab::site_of(&base)).or_default(); - if !list.iter().any(|(_, _, r)| r.id == repository.id) { - list.push((base, token, repository)); - } + let organization_id = project.organization_id; + sites.entry(gitlab::site_of(&base)).or_default().push(Reached { organization_id, base, token, repository }); } } Ok(sites) } -/// GitLab user ID -> the linked repositories they're a member of on this site, with their permission. -async fn reach( - projects: &[(String, String, Repository)], -) -> laravel::Result>> { +/// Who can reach this site's linked repositories, read once each (through the first project whose token works: one +/// organization's revoked token doesn't hide a repository another reaches): GitLab user ID -> the repositories they're +/// a member of, with their permission. Also the organizations linking a repository nobody could read, whose +/// memberships stay as they are, and those repositories' URLs. +async fn reach(projects: &[Reached]) -> (HashMap>, HashSet, Vec) { let mut people: HashMap> = HashMap::new(); - for (base, token, repository) in projects { - let id = repository.id.clone().unwrap_or_default(); - for member in gitlab::members(base, token, &id).await? { + let mut read: HashSet> = HashSet::new(); + let mut unread: HashMap, String> = HashMap::new(); + for p in projects { + let key = p.repository.id.clone(); + if read.contains(&key) { + continue; + } + let members = match gitlab::members(&p.base, &p.token, key.as_deref().unwrap_or_default()).await { + Ok(members) => members, + Err(e) => { + tracing::warn!(repo = p.repository.url, error = %e, "GitLab sync: couldn't read a project's members"); + unread.insert(key, p.repository.url.clone()); + continue; + } + }; + unread.remove(&key); + read.insert(key); + for member in members { let (Some(user), Some(permission)) = ( member["id"].as_i64().map(|i| i.to_string()), member["access_level"].as_i64().and_then(gitlab::permission_from_level), ) else { continue; }; - people.entry(user).or_default().push((repository.clone(), permission)); + people.entry(user).or_default().push((p.repository.clone(), permission)); } } - Ok(people) + let keep = projects.iter().filter(|p| unread.contains_key(&p.repository.id)).map(|p| p.organization_id).collect(); + (people, keep, unread.into_values().collect()) } /// Recheck everyone signed in with a GitLab. @@ -84,21 +107,16 @@ pub async fn sync_gitlab() -> laravel::Result { } let mut synced = Synced::default(); for (site, projects) in &sites { - let people = match reach(projects).await { - Ok(people) => people, - Err(e) => { - tracing::warn!(site, error = %e, "GitLab sync: couldn't read every linked project's members"); - synced.failed_sites.push(if site.is_empty() { "gitlab.com".to_string() } else { site.clone() }); - continue; - } - }; + let (people, keep, failed) = reach(projects).await; + synced.failed.extend(failed); let rows = db::query!("SELECT user_id, forge_user_id FROM identities WHERE forge = 'gitlab' AND site = {site}") .select() .await?; for row in rows { let (user_id, forge_user): (i64, String) = (row.try_get("user_id")?, row.try_get("forge_user_id")?); let list = people.get(&forge_user).cloned().unwrap_or_default(); - synced.changed += crate::auth::memberships::apply(user_id, ForgeKind::Gitlab, site, &list).await?; + synced.changed += + crate::auth::memberships::apply_keeping(user_id, ForgeKind::Gitlab, site, &list, &keep).await?; synced.people += 1; } } diff --git a/app/src/forge/instances.rs b/app/src/forge/instances.rs index 82d13282..e89e4b4a 100644 --- a/app/src/forge/instances.rs +++ b/app/src/forge/instances.rs @@ -19,14 +19,17 @@ use serde_json::{Value, json}; use crate::models::{GitlabInstance, User}; pub fn routes(route: &mut Router) { + route.get("/api/ui/orgs/{org}/gitlab-instances", list); route.post("/api/ui/orgs/{org}/gitlab-instances", add); route.delete("/api/ui/orgs/{org}/gitlab-instances/{id}", remove); } -/// A self-managed instance's base URL, normalised: `https://gitlab.example.com` (http, or an IP address, only for a -/// development server's local GitLab). `None` for anything else, gitlab.com included (VisualCI's own). +/// A self-managed instance's base URL, normalised: `https://gitlab.example.com`. `allow_http` lets a server outside +/// production use http, and `allow_ip` an IP address (only with `VISUALCI_FORGE_PRIVATE_ADDRESSES=1`, a development +/// server's local GitLab: an address never goes through the resolver's public-only check). `None` for anything else, +/// gitlab.com included (VisualCI's own). #[must_use] -pub fn normalise_base(input: &str, allow_http: bool) -> Option { +pub fn normalise_base(input: &str, allow_http: bool, allow_ip: bool) -> Option { let s = input.trim().trim_end_matches('/'); let url = url::Url::parse(s).ok()?; let ok_scheme = url.scheme() == "https" || (allow_http && url.scheme() == "http"); @@ -37,8 +40,9 @@ pub fn normalise_base(input: &str, allow_http: bool) -> Option { if !ok_scheme || url.path() != "/" && !url.path().is_empty() || url.query().is_some() - || host.ends_with("gitlab.com") - || ip_literal && !allow_http + || host == "gitlab.com" + || host.ends_with(".gitlab.com") + || ip_literal && !allow_ip { return None; } @@ -58,12 +62,7 @@ pub async fn for_site(organization_id: i64, base_url: &str) -> laravel::Result laravel::Result laravel::Result = db::query!("SELECT * FROM gitlab_instances WHERE pid = {pid}::uuid").select_one_as().await?; - Ok(found.inspect(recognise)) + Ok(found) } /// The organization's instances as its page shows them: where people sign in, and the callback URL its OAuth @@ -142,7 +140,7 @@ pub async fn upsert( by: i64, ) -> laravel::Result { let allow_http = !laravel::config().app.env.is_production(); - let base = normalise_base(base_url, allow_http).ok_or_else(|| { + let base = normalise_base(base_url, allow_http, super::outbound::private_allowed()).ok_or_else(|| { laravel::abort_with( 422, "the instance's URL is its https:// address with no path, like https://gitlab.example.com", @@ -164,7 +162,6 @@ pub async fn upsert( ) .select_one_as() .await? - .inspect(recognise) .ok_or_else(|| laravel::Error::msg("no instance row")) } @@ -181,6 +178,16 @@ pub async fn add( Ok(Json(json!({ "gitlab_instances": json_for(org_id).await? }))) } +/// `GET /api/ui/orgs/{org}/gitlab-instances`: the organization's instances (admins), with each one's callback URL for +/// its OAuth application. +pub async fn list( + Authenticated(user): Authenticated, + Params(org): Params, +) -> laravel::Result> { + let (org_id, _) = crate::auth::invitations::admin_org(&user, &org, "see the GitLab instances").await?; + Ok(Json(json!({ "gitlab_instances": json_for(org_id).await?, "enabled": enabled() }))) +} + /// `DELETE /api/ui/orgs/{org}/gitlab-instances/{id}`: remove an instance (admins). pub async fn remove( Authenticated(user): Authenticated, @@ -274,18 +281,33 @@ mod tests { #[test] fn normalises_instance_urls() { - assert_eq!(normalise_base("https://GitLab.Example.com/", false).as_deref(), Some("https://gitlab.example.com")); assert_eq!( - normalise_base("https://git.example.com:8443", false).as_deref(), + normalise_base("https://GitLab.Example.com/", false, false).as_deref(), + Some("https://gitlab.example.com") + ); + assert_eq!( + normalise_base("https://git.example.com:8443", false, false).as_deref(), Some("https://git.example.com:8443") ); - assert_eq!(normalise_base("http://git.example.com", false), None, "https only"); - assert_eq!(normalise_base("http://localhost:5196", true).as_deref(), Some("http://localhost:5196")); - assert_eq!(normalise_base("https://git.example.com/gitlab", false), None, "no relative URL root"); - assert_eq!(normalise_base("https://gitlab.com", false), None, "gitlab.com is VisualCI's own"); - assert_eq!(normalise_base("not a url", false), None); + assert_eq!(normalise_base("http://git.example.com", false, false), None, "https only"); + assert_eq!(normalise_base("http://localhost:5196", true, false).as_deref(), Some("http://localhost:5196")); + assert_eq!(normalise_base("https://git.example.com/gitlab", false, false), None, "no relative URL root"); + assert_eq!(normalise_base("https://gitlab.com", false, false), None, "gitlab.com is VisualCI's own"); + assert_eq!(normalise_base("not a url", false, false), None); for ip in ["https://10.0.0.5", "https://127.0.0.1:8443", "https://[::1]", "https://169.254.169.254"] { - assert_eq!(normalise_base(ip, false), None, "{ip}: an address, not a name"); + assert_eq!(normalise_base(ip, false, false), None, "{ip}: an address, not a name"); + assert_eq!( + normalise_base(&ip.replace("https", "http"), true, false), + None, + "{ip}: not even off production" + ); } + assert!(normalise_base("http://10.0.0.5:8080", true, true).is_some(), "with private addresses allowed"); + assert_eq!( + normalise_base("https://mygitlab.com", false, false).as_deref(), + Some("https://mygitlab.com"), + "only gitlab.com itself and its subdomains are VisualCI's" + ); + assert_eq!(normalise_base("https://eu.gitlab.com", false, false), None); } } diff --git a/app/src/forge/outbound.rs b/app/src/forge/outbound.rs index 77ea04cc..6f9a4a09 100644 --- a/app/src/forge/outbound.rs +++ b/app/src/forge/outbound.rs @@ -28,7 +28,9 @@ pub struct Outbound { pub private_addresses: Option, } -fn private_allowed() -> bool { +/// Whether requests may reach private addresses (`VISUALCI_FORGE_PRIVATE_ADDRESSES=1`, development only). +#[must_use] +pub fn private_allowed() -> bool { laravel::config().get::().is_some_and(|o| o.private_addresses.as_deref() == Some("1")) } @@ -57,6 +59,16 @@ pub fn is_public(ip: IpAddr) -> bool { return is_public(IpAddr::V4(v4)); } let s = v6.segments(); + // IPv4-compatible (::a.b.c.d) and 6to4 (2002::/16) addresses carry an IPv4 address to check + if s[..6] == [0; 6] && !v6.is_loopback() && !v6.is_unspecified() { + let o = v6.octets(); + return is_public(IpAddr::V4(std::net::Ipv4Addr::new(o[12], o[13], o[14], o[15]))); + } + if s[0] == 0x2002 { + let [a, b] = s[1].to_be_bytes(); + let [c, d] = s[2].to_be_bytes(); + return is_public(IpAddr::V4(std::net::Ipv4Addr::new(a, b, c, d))); + } !(v6.is_loopback() || v6.is_unspecified() || v6.is_multicast() @@ -95,12 +107,16 @@ fn trusted(base: &str) -> bool { || gitlab.is_some_and(|g| base.eq_ignore_ascii_case(&g)) } +/// How long a whole request to an organization's server may take, body included. +const DEADLINE: Duration = Duration::from_secs(30); + /// A request to an organization's server, guarded: public addresses only (unless allowed for development), no -/// redirects, a 10-second connection and 30-second request limit. +/// proxy (a proxy would resolve the name itself, past the check), no redirects, a 10-second connection limit. pub fn guard(request: PendingRequest) -> PendingRequest { let private = private_allowed(); request.total_timeout(30.seconds()).configure_transport(move |builder| { - let builder = builder.redirect(reqwest::redirect::Policy::none()).connect_timeout(Duration::from_secs(10)); + let builder = + builder.no_proxy().redirect(reqwest::redirect::Policy::none()).connect_timeout(Duration::from_secs(10)); if private { builder } else { builder.dns_resolver(Arc::new(PublicOnly)) } }) } @@ -115,18 +131,25 @@ pub async fn send(request: PendingRequest, base: &str) -> laravel::Result<(u16, let response = request.await?; return Ok((response.status().as_u16(), response.text().into_owned())); } - let response = guard(request).stream().await?; - let status = response.status().as_u16(); - let mut body = Vec::new(); - let mut chunks = response.chunks(); - while let Some(chunk) = chunks.next().await { - let chunk = chunk?; - if body.len() + chunk.len() > MAX_BODY { - return Err(laravel::Error::msg(format!("{base}'s response is larger than {MAX_BODY} bytes"))); + // One deadline for the whole exchange: a server dribbling its body a byte at a time can't hold a sign-in or the + // hourly sync + let read = async { + let response = guard(request).stream().await?; + let status = response.status().as_u16(); + let mut body = Vec::new(); + let mut chunks = response.chunks(); + while let Some(chunk) = chunks.next().await { + let chunk = chunk?; + if body.len() + chunk.len() > MAX_BODY { + return Err(laravel::Error::msg(format!("{base}'s response is larger than {MAX_BODY} bytes"))); + } + body.extend_from_slice(&chunk); } - body.extend_from_slice(&chunk); - } - Ok((status, String::from_utf8_lossy(&body).into_owned())) + Ok((status, String::from_utf8_lossy(&body).into_owned())) + }; + tokio::time::timeout(DEADLINE, read) + .await + .map_err(|_| laravel::Error::msg(format!("{base} took more than {} seconds to answer", DEADLINE.as_secs())))? } /// [`send`], with the body as JSON (`null` for an error status whose body isn't JSON). @@ -169,10 +192,14 @@ mod tests { "fd00::1", "fe80::1", "::ffff:10.0.0.1", + "::10.0.0.1", + "::169.254.169.254", + "2002:a00:1::", + "2002:a9fe:a9fe::", ] { assert!(!is_public(private.parse().unwrap()), "{private}"); } - for public in ["1.1.1.1", "140.82.112.3", "2606:4700::1111"] { + for public in ["1.1.1.1", "140.82.112.3", "2606:4700::1111", "2002:101:101::"] { assert!(is_public(public.parse().unwrap()), "{public}"); } } diff --git a/app/src/forge/sync.rs b/app/src/forge/sync.rs index e97eefb8..1a90830b 100644 --- a/app/src/forge/sync.rs +++ b/app/src/forge/sync.rs @@ -208,9 +208,9 @@ impl SyncForges { // GitLab: memberships, webhooks not working yet, and the bot's token, whether or not GitHub is set up here match super::gitlab_sync::sync_gitlab().await { Ok(s) => { - tracing::info!(people = s.people, changed = s.changed, failed_sites = ?s.failed_sites, "GitLab sync"); - if !s.failed_sites.is_empty() { - problems.push(format!("GitLab couldn't be read at {}", s.failed_sites.join(", "))); + tracing::info!(people = s.people, changed = s.changed, failed = ?s.failed, "GitLab sync"); + if !s.failed.is_empty() { + problems.push(format!("GitLab couldn't be read for {}", s.failed.join(", "))); } } Err(e) => problems.push(format!("GitLab sync: {e}")), diff --git a/app/src/models/projects.rs b/app/src/models/projects.rs index 2e878064..2c674344 100644 --- a/app/src/models/projects.rs +++ b/app/src/models/projects.rs @@ -34,6 +34,8 @@ pub struct Project { #[default] pub public: bool, pub forge_webhook_at: Option, + /// A self-managed GitLab project's access token, encrypted (`secrets`): never serialized. + #[serde(skip)] pub forge_token_enc: Option, #[default] pub repository_public: bool, diff --git a/app/tests/gitlab_hooks.rs b/app/tests/gitlab_hooks.rs index 0c14cb37..ae2f0d75 100644 --- a/app/tests/gitlab_hooks.rs +++ b/app/tests/gitlab_hooks.rs @@ -148,3 +148,21 @@ async fn a_delivery_without_the_projects_secret_or_for_another_repository_is_ref assert!(web.forge_webhook_at.is_none()); Ok(()) } + +#[laravel::test(app = with_key)] +async fn admins_see_the_webhooks_url_and_secret(app: Application) -> laravel::Result<()> { + let web = linked_web().await?; + let ada = User::first_where(User::email.eq("ada@example.com")).await?.unwrap(); + let shown = app + .get("/api/ui/orgs/acme/projects/web/gitlab-webhook") + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .await; + shown.assert_ok(); + assert_eq!(shown.json()["gitlab_webhook"]["url"], format!("https://api.visualci.test/webhooks/gitlab/{}", web.pid)); + assert_eq!(shown.json()["gitlab_webhook"]["secret"].as_str(), app::secrets::webhook_secret(&web.pid).as_deref()); + let listed = + app.get("/api/ui/orgs/acme/gitlab-instances").acting_as(&ada).header("sec-fetch-site", "same-origin").await; + listed.assert_ok().assert_json_path("gitlab_instances.0.base_url", "https://gitlab.example.com"); + Ok(()) +} diff --git a/app/tests/gitlab_sync.rs b/app/tests/gitlab_sync.rs index 41cec3ab..bc897bb2 100644 --- a/app/tests/gitlab_sync.rs +++ b/app/tests/gitlab_sync.rs @@ -54,7 +54,7 @@ async fn memberships_follow_the_projects_members(_app: Application) -> laravel:: .with("gitlab.com/api/v4/projects/5/members/all*", json!([{ "id": 2002, "access_level": 40 }, { "id": 9 }])); let synced = sync_gitlab().await?; assert_eq!((synced.people, synced.changed), (1, 1)); - assert!(synced.failed_sites.is_empty()); + assert!(synced.failed.is_empty()); assert!(role_in(acme, ada).await?.is_some(), "a Maintainer on the project is in its organization"); assert!(gitlab.sent()[0].header("authorization").is_some_and(|h| h == "Bearer bot-token")); @@ -76,11 +76,48 @@ async fn a_gitlab_that_cant_be_read_changes_nobody(_app: Application) -> laravel .await?; let _gitlab = client::fake().with("gitlab.com/api/v4/projects/5/members/all*", client::response().status(502)); let synced = sync_gitlab().await?; - assert_eq!(synced.failed_sites, vec!["gitlab.com".to_string()]); + assert_eq!(synced.failed, vec!["https://gitlab.com/acme/web".to_string()]); assert_eq!(role_in(acme, ada).await?.as_deref(), Some("member"), "kept until GitLab answers"); Ok(()) } +/// One organization's project that can't be read holds back only that organization's memberships. +#[laravel::test(app = bot)] +async fn one_unreadable_project_doesnt_stop_everyone_elses_sync(_app: Application) -> laravel::Result<()> { + let (ada, acme) = ada_and_acme().await?; + let beta: i64 = db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) \ + VALUES (gen_random_uuid(), 'beta', 'Beta', now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + 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(), {beta}, 'app', 'App', 'gitlab', 'https://gitlab.com/beta/app', '6', 'bot', \ + now(), now())" + ) + .insert() + .await?; + for org in [acme, beta] { + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org}, {ada}, 'member', 'gitlab', now(), now())" + ) + .insert() + .await?; + } + let _gitlab = client::fake() + .with("gitlab.com/api/v4/projects/5/members/all*", json!([])) + .with("gitlab.com/api/v4/projects/6/members/all*", client::response().status(401)); + let synced = sync_gitlab().await?; + assert_eq!(synced.failed, vec!["https://gitlab.com/beta/app".to_string()]); + assert_eq!(role_in(acme, ada).await?, None, "acme's project was read: Ada isn't a member any more"); + assert_eq!(role_in(beta, ada).await?.as_deref(), Some("member"), "beta's couldn't be: kept"); + Ok(()) +} + #[laravel::test(app = bot)] async fn a_gitlab_com_projects_open_source_status_comes_from_gitlab(_app: Application) -> laravel::Result<()> { let (_, acme) = ada_and_acme().await?;