From 9474924fd3356ae05210349ba037ad3239bdccc1 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 11:17:18 +1300 Subject: [PATCH 1/3] app/: linking a project to its repository (sc-8900, forge, ported): forge::link::link_repository(project, by, url, token, move_link) for GitHub (the App installed on the repository) and the GitLab of VISUALCI_GITLAB_URL (VisualCI's bot a Developer, VISUALCI_GITLAB_BOT_TOKEN); only an admin or maintainer of the repository on the forge may link it; the forge's permanent ID is stored; a repository belongs to one organization: linked elsewhere is refused naming it, or with move_link moved here, unlinking the other projects with a notice and an email to their admins; an empty URL unlinks; both check the repository's open source status at once; self-managed GitLab instances are refused as unknown until they're ported --- app/src/forge/github_app.rs | 20 +++ app/src/forge/gitlab.rs | 77 +++++++++++ app/src/forge/link.rs | 259 ++++++++++++++++++++++++++++++++++++ app/src/forge/mod.rs | 1 + app/tests/link.rs | 174 ++++++++++++++++++++++++ 5 files changed, 531 insertions(+) create mode 100644 app/src/forge/link.rs create mode 100644 app/tests/link.rs diff --git a/app/src/forge/github_app.rs b/app/src/forge/github_app.rs index 301edf03..1707cd50 100644 --- a/app/src/forge/github_app.rs +++ b/app/src/forge/github_app.rs @@ -91,6 +91,26 @@ pub async fn installation_exists(app: &GithubApp, id: &str) -> laravel::Result laravel::Result> { + Ok(get(&app_jwt(app)?, &format!("/repos/{repo}/installation")) + .await? + .and_then(|v| v["id"].as_i64()) + .map(|i| i.to_string())) +} + +/// Whether the App is configured (its ID and private key). +#[must_use] +pub fn configured(app: &GithubApp) -> bool { + app.app_id.is_some() && app.private_key_base64.is_some() +} + /// Below this many API calls left in the hour, a recheck stops instead of using up what webhooks and checks need. pub const RATE_LIMIT_RESERVE: i64 = 500; diff --git a/app/src/forge/gitlab.rs b/app/src/forge/gitlab.rs index 15d6f5ab..f519e5fd 100644 --- a/app/src/forge/gitlab.rs +++ b/app/src/forge/gitlab.rs @@ -156,3 +156,80 @@ fn level_of(project: &Value) -> i64 { .max() .unwrap_or(0) } + +/// VisualCI's bot user on the GitLab of [`GitlabConfig`] (`VISUALCI_GITLAB_BOT_TOKEN`, a personal access token with +/// the `api` scope). GitLab has no app installations: a project gives VisualCI access by adding the bot as a member, +/// and every server-side call about it (access checks, commit statuses, merge request notes) uses the bot's token. +#[derive(Clone, laravel::config::Section)] +pub struct GitlabBot { + #[env("VISUALCI_GITLAB_BOT_TOKEN")] + pub token: Option, + /// The bot's username, for telling people whom to invite. + #[env("VISUALCI_GITLAB_BOT_USERNAME", default = "visualci")] + pub username: String, +} + +/// The `installation` of a project VisualCI reaches through its bot. +pub const BOT: &str = "bot"; + +/// A project's ID for the API: its path, URL-encoded (`group%2Fsub%2Fproject`). +fn project_id(path: &str) -> String { + url::form_urlencoded::byte_serialize(path.as_bytes()).collect() +} + +/// 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()))); + } + Ok(Some(response.json()?)) +} + +/// The bot's access level on a project (`group/sub/project`), when it's a member. +/// +/// # Errors +/// When GitLab can't be reached or refuses the bot's token. +pub async fn bot_level(base: &str, token: &str, path: &str) -> laravel::Result> { + Ok(get(base, token, &format!("/projects/{}", project_id(path))).await?.map(|p| level_of(&p)).filter(|l| *l > 0)) +} + +/// The bot's access to a project as an installation: a Developer or higher can post statuses and notes. +/// +/// # Errors +/// When GitLab can't be reached or refuses the bot's token. +pub async fn installation_for(base: &str, token: &str, path: &str) -> laravel::Result> { + Ok(bot_level(base, token, path).await?.filter(|l| *l >= 30).map(|_| BOT.to_string())) +} + +/// A person's permission on a project, inherited access included, by their permanent GitLab user ID. +/// +/// # Errors +/// When GitLab can't be reached or refuses the token. +pub async fn permission(base: &str, token: &str, path: &str, user_id: &str) -> laravel::Result> { + let Ok(user_id) = user_id.parse::() else { return Ok(None) }; + let member = get(base, token, &format!("/projects/{}/members/all/{user_id}", project_id(path))).await?; + Ok(member.and_then(|m| m["access_level"].as_i64()).and_then(permission_from_level)) +} + +/// A project's permanent ID (`None` when the token can't see it). +/// +/// # Errors +/// When GitLab can't be reached or refuses the token. +pub async fn repository_id(base: &str, token: &str, path: &str) -> laravel::Result> { + Ok(get(base, token, &format!("/projects/{}", project_id(path))) + .await? + .and_then(|p| p["id"].as_i64()) + .map(|i| i.to_string())) +} + +/// How a project gives VisualCI access: invite the bot as a Developer. +#[must_use] +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") +} diff --git a/app/src/forge/link.rs b/app/src/forge/link.rs new file mode 100644 index 00000000..9bee16d6 --- /dev/null +++ b/app/src/forge/link.rs @@ -0,0 +1,259 @@ +//! Linking a project to its repository (sc-8900, the forge side), ported from today's `access::link_repository`. +//! +//! A link is what lets VisualCI post a project's checks and pull request comments, and what its open source status is +//! checked against, so only an admin or maintainer of the repository on the forge may make one: someone else's +//! repository can't be given checks or access. A repository belongs to one organization (several of its projects may +//! 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. + +use laravel::db; + +use super::github_app::{self, GithubApp}; +use super::gitlab::{self, GitlabBot, GitlabConfig}; +use super::{ForgeKind, Permission, Repository}; +use crate::models::{Project, User}; +use crate::notify::{self, Kind, To}; + +fn bad(message: impl Into) -> laravel::Error { + laravel::abort_with(400, message.into()) +} + +/// What linking learns from the forge: how VisualCI reaches the repository, the person's permission on it, and the +/// forge's permanent ID for it. +struct Reached { + installation: String, + permission: Option, + repository_id: Option, +} + +/// 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 +/// 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 +/// VisualCI knows, the App or bot can't reach it, `by` hasn't signed in with that forge, or isn't an admin or +/// maintainer of it there. The caller checks that `by` is an admin of the project's organization. +/// +/// # Errors +/// Those; forge and database errors. +pub async fn link_repository( + project: Project, + by: &User, + url: &str, + 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; + if url.trim().is_empty() { + db::query!( + "UPDATE projects SET forge = NULL, repository_url = NULL, repository_id = NULL, forge_installation = NULL, \ + forge_token_enc = NULL, forge_webhook_at = NULL, updated_at = now() WHERE id = {id}" + ) + .update() + .await?; + // Unlinked: a project without a public repository can't stay public + super::open_source::refresh(&github, id).await?; + return reload(id).await; + } + let repository = Repository::parse(url).ok_or_else(|| { + 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" + )) + })?; + let label = repository.forge.label(); + let identity = |site: &str| identity_of(by.id, repository.forge, site.to_string()); + let reached = match repository.forge { + ForgeKind::Github => { + if !github_app::configured(&github) { + return Err(bad(format!("{label} isn't set up on this server"))); + } + let Some(installation) = github_app::installation_for(&github, &repository.path).await? else { + return Err(bad(format!( + "VisualCI can't reach {} on {label} yet: install the VisualCI GitHub App on it at {}, then link it", + repository.path, + github_app::INSTALL_URL + ))); + }; + let forge_user = identity("").await?.ok_or_else(|| signed_out(label, &repository))?; + let permission = github_app::permission(&github, &repository.path, &installation, &forge_user).await?; + let token = github_app::installation_token(&github, &installation).await?; + let repository_id = github_app::repository_id(&token, &repository.path).await.unwrap_or_else(|e| { + tracing::warn!(repo = repository.path, error = %e, "reading the repository's ID"); + None + }); + Reached { installation, 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"))); + }; + let Some(installation) = gitlab::installation_for(base, token, &repository.path).await? else { + return Err(bad(format!( + "VisualCI can't reach {} on {label} yet: {}", + repository.path, + gitlab::install_hint(base, &bot.username, &repository.path) + ))); + }; + let forge_user = identity(&gitlab::site_of(base)).await?.ok_or_else(|| signed_out(label, &repository))?; + 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, permission, repository_id } + } + }; + if !reached.permission.is_some_and(|p| p >= Permission::Maintain) { + return Err(bad(format!( + "only an admin or maintainer of {} on {label} can link it (you're {})", + repository.path, + reached.permission.map_or("not a collaborator".to_string(), |p| format!("{p:?}").to_lowercase()) + ))); + } + let repository = repository.with_id(reached.repository_id.clone()); + let elsewhere = linked_elsewhere(&repository, project.organization_id).await?; + if !elsewhere.is_empty() { + if !move_link { + return Err(bad(linked_elsewhere_message(&repository, &elsewhere).await?)); + } + move_links_here(&github, &elsewhere, &repository, project.organization_id, by).await?; + } + let (forge, repo_url, repo_id, installation, user_id) = + (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, \ + 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"); + // 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 +} + +async fn reload(id: i64) -> laravel::Result { + Project::find(id).await?.ok_or_else(|| laravel::abort(404)) +} + +fn signed_out(label: &str, repository: &Repository) -> laravel::Error { + bad(format!("sign in with {label} first, to show you can manage {}", repository.path)) +} + +/// The person's permanent user ID on a forge (`site` is '' for github.com and gitlab.com). +async fn identity_of(user_id: i64, forge: ForgeKind, site: String) -> laravel::Result> { + let forge = forge.as_str(); + db::query!( + "SELECT forge_user_id FROM identities WHERE user_id = {user_id} AND forge = {forge} AND site = {site} \ + ORDER BY id LIMIT 1" + ) + .scalar() + .await +} + +/// A project of another organization that links the repository. +pub struct Elsewhere { + pub project_id: i64, + pub slug: String, + pub organization_id: i64, +} + +/// Projects in organizations other than `organization_id` linking this repository: by the forge's ID when both +/// sides know it, else by URL. +/// +/// # Errors +/// On a database error. +pub async fn linked_elsewhere(repository: &Repository, organization_id: i64) -> laravel::Result> { + let (forge, url, repo_id) = (repository.forge.as_str(), repository.url.to_lowercase(), repository.id.clone()); + let rows = db::query!( + "SELECT id, slug, organization_id FROM projects WHERE forge = {forge} AND organization_id <> {organization_id} \ + AND ((repository_id IS NOT NULL AND repository_id = {repo_id}) OR lower(repository_url) = {url}) \ + ORDER BY id" + ) + .select() + .await?; + rows.iter() + .map(|r| { + Ok(Elsewhere { + project_id: r.try_get("id")?, + slug: r.try_get("slug")?, + organization_id: r.try_get("organization_id")?, + }) + }) + .collect() +} + +/// Why a link is refused: which organization has the repository, and how to move it. +async fn linked_elsewhere_message(repository: &Repository, elsewhere: &[Elsewhere]) -> laravel::Result { + let there = match elsewhere.first() { + Some(p) => { + let org = p.organization_id; + let row = db::query!("SELECT name, slug FROM organizations WHERE id = {org}").select_one().await?; + match row { + Some(r) => format!("{} ({})", r.try_get::("name")?, r.try_get::("slug")?), + None => "another organization".to_string(), + } + } + None => "another organization".to_string(), + }; + Ok(format!( + "{} is linked to {there} on VisualCI, and a repository belongs to one organization. As a maintainer of it, you \ + can move the link here: Move it here in the web app, or update_project with move_link over MCP. {there}'s \ + admins get an email saying so.", + repository.path + )) +} + +/// Move a repository's links from other organizations' projects to `organization_id`: those projects are unlinked +/// with a notice saying who moved it, and their organizations' admins get an email. The caller has checked, with the +/// forge, that `by` maintains the repository. +async fn move_links_here( + github: &GithubApp, + elsewhere: &[Elsewhere], + repository: &Repository, + organization_id: i64, + by: &User, +) -> laravel::Result<()> { + let to_org: Option = + db::query!("SELECT name FROM organizations WHERE id = {organization_id}").scalar().await?; + let to_org = to_org.unwrap_or_default(); + let now = laravel::now().timestamp().as_second(); + for p in elsewhere { + let (id, from) = (p.project_id, p.organization_id); + let notice = format!( + "{} moved {} to {to_org}: a repository belongs to one organization, so this project isn't linked to it any \ + more.", + by.name, repository.path + ); + db::query!( + "UPDATE projects SET forge = NULL, repository_url = NULL, repository_id = NULL, forge_installation = NULL, \ + forge_token_enc = NULL, forge_webhook_at = NULL, linked_by = NULL, notice = {notice}, \ + updated_at = now() WHERE id = {id}" + ) + .update() + .await?; + tracing::info!(repo = repository.path, from, to = organization_id, "repository link moved"); + super::open_source::refresh(github, id).await?; + let kind = Kind::RepositoryMoved { + project: p.slug.clone(), + repository: repository.path.clone(), + to_org: to_org.clone(), + by: by.name.clone(), + }; + notify::queue(&kind, To::Admins(from), None, &format!("repository_moved:{id}:{now}")).await?; + } + Ok(()) +} diff --git a/app/src/forge/mod.rs b/app/src/forge/mod.rs index 0d8113fd..d4c3984c 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 link; pub mod open_source; pub mod sync; pub mod webhooks; diff --git a/app/tests/link.rs b/app/tests/link.rs new file mode 100644 index 00000000..1abedc75 --- /dev/null +++ b/app/tests/link.rs @@ -0,0 +1,174 @@ +//! Linking a project to its repository: only a maintainer of it may, VisualCI must reach it (the GitHub App +//! installed, the GitLab bot a Developer), a repository belongs to one organization (moving it tells the other one), +//! and an empty URL unlinks. + +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::*; + +/// A GitHub App key made once per run (base64 of its PEM). +fn app_key() -> &'static str { + static KEY: std::sync::OnceLock = std::sync::OnceLock::new(); + KEY.get_or_init(|| { + use base64::Engine; + use rsa::pkcs1::EncodeRsaPrivateKey; + let key = rsa::RsaPrivateKey::new(&mut rsa::rand_core::OsRng, 2048).expect("a key"); + let pem = key.to_pkcs1_pem(rsa::pkcs1::LineEnding::LF).expect("its PEM"); + base64::engine::general_purpose::STANDARD.encode(pem.as_bytes()) + }) +} + +/// The GitHub App and the gitlab.com bot both set up. +fn forges() -> Application { + app::testing::configure() + .with_env("GITHUB_APP_ID", "1") + .with_env("GITHUB_APP_PRIVATE_KEY_BASE64", app_key()) + .with_env("VISUALCI_GITLAB_BOT_TOKEN", "bot-token") + .create() +} + +/// Ada, with a GitHub identity (1001) and a gitlab.com one (2002), 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}, 'github', '', '1001', 'ada', now(), now()), ({id}, 'gitlab', '', '2002', 'ada', now(), now())" + ) + .insert() + .await?; + let org = fixtures::organization("acme").await?; + fixtures::member(&org, &ada, "admin").await?; + let web = fixtures::project(&org, "web").await?; + Ok((ada, web)) +} + +/// GitHub's answers for acme/web: the App installed (7), and Ada's role on it. +fn github(role: &str) -> client::HttpFake { + client::fake() + .with("api.github.com/repos/acme/web/installation", json!({ "id": 7 })) + .with("api.github.com/app/installations/7/access_tokens", json!({ "token": "t" })) + .with("api.github.com/user/1001", json!({ "id": 1001, "login": "ada" })) + .with("api.github.com/repos/acme/web/collaborators/ada", client::response().status(204)) + .with("api.github.com/repos/acme/web/collaborators/ada/permission", json!({ "role_name": role })) + .with("api.github.com/repositories/42", json!({ "full_name": "acme/web" })) + .with("api.github.com/repos/acme/web", json!({ "id": 42, "private": false, "license": { "spdx_id": "MIT" } })) +} + +#[laravel::test(app = forges)] +async fn a_maintainer_links_a_github_repository(_app: Application) -> laravel::Result<()> { + let (ada, web) = ada_and_web().await?; + let _github = github("maintain"); + let linked = link_repository(web, &ada, "https://github.com/acme/web", None, false).await?; + assert_eq!(linked.forge.as_deref(), Some("github")); + assert_eq!(linked.repository_url.as_deref(), Some("https://github.com/acme/web")); + assert_eq!(linked.repository_id.as_deref(), Some("42")); + assert_eq!(linked.forge_installation.as_deref(), Some("7")); + assert_eq!(linked.linked_by, Some(ada.id)); + assert!(linked.repository_public, "linking checks the repository at once"); + + let unlinked = link_repository(linked, &ada, "", None, false).await?; + assert_eq!((unlinked.forge, unlinked.repository_url, unlinked.forge_installation), (None, None, None)); + Ok(()) +} + +#[laravel::test(app = forges)] +async fn a_writer_cannot_link_it(_app: Application) -> laravel::Result<()> { + let (ada, web) = ada_and_web().await?; + let _github = github("write"); + let e = link_repository(web, &ada, "https://github.com/acme/web", None, false).await.unwrap_err(); + assert!( + e.to_string().contains("only an admin or maintainer of acme/web on GitHub can link it (you're write)"), + "{e}" + ); + Ok(()) +} + +#[laravel::test(app = forges)] +async fn the_app_must_be_installed_first(_app: Application) -> laravel::Result<()> { + let (ada, web) = ada_and_web().await?; + let _github = client::fake() + .with("api.github.com/repos/acme/web/installation", client::response().status(404).json(json!({}))); + let e = link_repository(web, &ada, "https://github.com/acme/web", None, false).await.unwrap_err(); + assert!(e.to_string().contains("install the VisualCI GitHub App on it"), "{e}"); + Ok(()) +} + +#[laravel::test] +async fn a_forge_this_server_has_no_app_for_is_refused(_app: Application) -> laravel::Result<()> { + let (ada, web) = ada_and_web().await?; + let e = link_repository(web.clone(), &ada, "https://github.com/acme/web", None, false).await.unwrap_err(); + assert!(e.to_string().contains("GitHub isn't set up on this server"), "{e}"); + let e = link_repository(web, &ada, "https://example.com/acme/web", None, false).await.unwrap_err(); + assert!(e.to_string().contains("isn't a repository URL VisualCI knows"), "{e}"); + Ok(()) +} + +#[laravel::test(app = forges)] +async fn a_repository_belongs_to_one_organization(_app: Application) -> laravel::Result<()> { + let (ada, web) = ada_and_web().await?; + let other = fixtures::organization("other").await?; + let bob = create!(User { pid: laravel::str::uuid7(), name: "Bob", email: "bob@example.com", staff: false }).await?; + fixtures::member(&other, &bob, "admin").await?; + let theirs = fixtures::project(&other, "site").await?; + let theirs_id = theirs.id; + db::query!( + "UPDATE projects SET forge = 'github', repository_url = 'https://github.com/acme/web', repository_id = '42', \ + forge_installation = '7' WHERE id = {theirs_id}" + ) + .update() + .await?; + let _github = github("admin"); + + let e = link_repository(web.clone(), &ada, "https://github.com/acme/web", None, false).await.unwrap_err(); + assert!(e.to_string().contains("acme/web is linked to other (other) on VisualCI"), "{e}"); + + let linked = link_repository(web, &ada, "https://github.com/acme/web", None, true).await?; + assert_eq!(linked.forge_installation.as_deref(), Some("7")); + let theirs = Project::find(theirs_id).await?.unwrap(); + assert_eq!(theirs.repository_url, None); + assert!( + theirs.notice.as_deref().is_some_and(|n| n.starts_with("Ada moved acme/web to acme")), + "{:?}", + theirs.notice + ); + let told: Option = db::query!("SELECT count(*) FROM emails WHERE kind = 'repository_moved'").scalar().await?; + assert_eq!( + told, + Some(1), + "the other organization's admins hear about it (it has none here, so the outbox has one)" + ); + Ok(()) +} + +#[laravel::test(app = forges)] +async fn a_maintainer_links_a_gitlab_project_through_the_bot(_app: Application) -> laravel::Result<()> { + let (ada, web) = ada_and_web().await?; + let _gitlab = client::fake() + .with( + "gitlab.com/api/v4/projects/acme%2Fweb", + json!({ "id": 9, "permissions": { "project_access": { "access_level": 30 } } }), + ) + .with("gitlab.com/api/v4/projects/acme%2Fweb/members/all/2002", json!({ "access_level": 40 })); + let linked = link_repository(web, &ada, "https://gitlab.com/acme/web", None, false).await?; + assert_eq!(linked.forge.as_deref(), Some("gitlab")); + assert_eq!(linked.forge_installation.as_deref(), Some("bot")); + assert_eq!(linked.repository_id.as_deref(), Some("9")); + Ok(()) +} + +#[laravel::test(app = forges)] +async fn the_bot_must_be_a_developer(_app: Application) -> laravel::Result<()> { + let (ada, web) = ada_and_web().await?; + let _gitlab = client::fake().with( + "gitlab.com/api/v4/projects/acme%2Fweb", + json!({ "id": 9, "permissions": { "project_access": { "access_level": 20 } } }), + ); + let e = link_repository(web, &ada, "https://gitlab.com/acme/web", None, false).await.unwrap_err(); + assert!(e.to_string().contains("invite @visualci to acme/web as a Developer"), "{e}"); + Ok(()) +} From f0360177e45fef379bc7034a2997d58f6835babf Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 12:30:32 +1300 Subject: [PATCH 2/3] Review: a repository linked elsewhere matches by the forge's ID when it's known, by URL only for links without one (as server/ does): a new repository under a deleted one's name isn't moved or told --- app/src/forge/link.rs | 8 +++++--- app/tests/link.rs | 24 ++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/app/src/forge/link.rs b/app/src/forge/link.rs index 9bee16d6..929387d4 100644 --- a/app/src/forge/link.rs +++ b/app/src/forge/link.rs @@ -171,8 +171,9 @@ pub struct Elsewhere { pub organization_id: i64, } -/// Projects in organizations other than `organization_id` linking this repository: by the forge's ID when both -/// sides know it, else by URL. +/// Projects in organizations other than `organization_id` linking this repository: by the forge's ID when it's +/// known, and by URL only for links whose ID isn't known yet. A deleted repository's name taken by a new one (a new +/// ID) isn't the same repository, and its old links mustn't be moved or told. /// /// # Errors /// On a database error. @@ -180,7 +181,8 @@ pub async fn linked_elsewhere(repository: &Repository, organization_id: i64) -> let (forge, url, repo_id) = (repository.forge.as_str(), repository.url.to_lowercase(), repository.id.clone()); let rows = db::query!( "SELECT id, slug, organization_id FROM projects WHERE forge = {forge} AND organization_id <> {organization_id} \ - AND ((repository_id IS NOT NULL AND repository_id = {repo_id}) OR lower(repository_url) = {url}) \ + AND ((repository_id IS NOT NULL AND repository_id = {repo_id}) \ + OR ((repository_id IS NULL OR {repo_id}::text IS NULL) AND lower(repository_url) = {url})) \ ORDER BY id" ) .select() diff --git a/app/tests/link.rs b/app/tests/link.rs index 1abedc75..814eb8ad 100644 --- a/app/tests/link.rs +++ b/app/tests/link.rs @@ -145,6 +145,30 @@ async fn a_repository_belongs_to_one_organization(_app: Application) -> laravel: Ok(()) } +/// A repository deleted and made again under the same name has a new ID: it isn't the old one, so the old one's links +/// in another organization stay where they are, untold. +#[laravel::test(app = forges)] +async fn a_new_repository_under_an_old_name_is_another_repository(_app: Application) -> laravel::Result<()> { + let (ada, web) = ada_and_web().await?; + let other = fixtures::organization("other").await?; + let theirs = fixtures::project(&other, "site").await?; + let theirs_id = theirs.id; + db::query!( + "UPDATE projects SET forge = 'github', repository_url = 'https://github.com/acme/web', repository_id = '41', \ + forge_installation = '7' WHERE id = {theirs_id}" + ) + .update() + .await?; + let _github = github("admin"); + let linked = link_repository(web, &ada, "https://github.com/acme/web", None, false).await?; + assert_eq!(linked.repository_id.as_deref(), Some("42")); + let theirs = Project::find(theirs_id).await?.unwrap(); + assert_eq!(theirs.repository_url.as_deref(), Some("https://github.com/acme/web"), "the old link stays"); + let told: Option = db::query!("SELECT count(*) FROM emails WHERE kind = 'repository_moved'").scalar().await?; + assert_eq!(told, Some(0)); + Ok(()) +} + #[laravel::test(app = forges)] async fn a_maintainer_links_a_gitlab_project_through_the_bot(_app: Application) -> laravel::Result<()> { let (ada, web) = ada_and_web().await?; From 81c6d7b3dd4140f5192d77903096e71904ab7f57 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 11:22:51 +1300 Subject: [PATCH 3/3] app/: checks and pull request comments on the forge (sc-8900, forge, ported): BuildChanged queues forge::checks::ReportCheck (a GitHub check run, or a GitLab commit status through VisualCI's GitLab bot, per suite) and forge::pr_comment::PostPrComment (one comment per project and pull request, edited in place), both debounced per build; one post at a time per build's check and per pull request's comment (advisory locks, read under them); a retry finds VisualCI's comment already on the pull request and edits it; a rate limit releases the job until it resets; the comment's hash leaves out its images' signatures; the comment's Markdown has golden files --- app/src/forge/checks.rs | 167 +++++++++++ app/src/forge/mod.rs | 4 + app/src/forge/outbound.rs | 239 +++++++++++++++ app/src/forge/pr_comment.rs | 366 +++++++++++++++++++++++ app/src/forge/report.rs | 303 +++++++++++++++++++ app/tests/forge_reports.rs | 318 ++++++++++++++++++++ app/tests/goldens/pr_comment.md | 19 ++ app/tests/goldens/pr_comment_approved.md | 8 + 8 files changed, 1424 insertions(+) create mode 100644 app/src/forge/checks.rs create mode 100644 app/src/forge/outbound.rs create mode 100644 app/src/forge/pr_comment.rs create mode 100644 app/src/forge/report.rs create mode 100644 app/tests/forge_reports.rs create mode 100644 app/tests/goldens/pr_comment.md create mode 100644 app/tests/goldens/pr_comment_approved.md diff --git a/app/src/forge/checks.rs b/app/src/forge/checks.rs new file mode 100644 index 00000000..7ee1e379 --- /dev/null +++ b/app/src/forge/checks.rs @@ -0,0 +1,167 @@ +//! A build's check on its forge (sc-8900, the forge side), ported from today's `workers::forge_check`: a GitHub check +//! run or a GitLab commit status per suite. It stays in progress while changes wait for review (a required check +//! blocks the merge) and completes when the build is approved, rejected or unchanged. +//! +//! `BuildChanged` queues [`ReportCheck`]. Dispatches for the same build within a few seconds are one post (the jobs +//! are debounced), so a build whose snapshots are reviewed one by one doesn't post once for each. + +use laravel::queue::{Attempt, Queueable, job}; + +use super::report::{self, Check, RateLimited}; +use crate::domain::build_settings::BuildSettings; +use crate::domain::builds::stats; +use crate::models::{Build, Organization, Project}; + +/// The check's name for a suite: "VisualCI" for the default build name, "VisualCI: pdf" for `--name pdf`. A +/// repository with several suites gets one check each, which branch protection can require by name. +#[must_use] +pub fn check_name(build_name: &str) -> String { + if build_name == "default" { "VisualCI".to_string() } else { format!("VisualCI: {build_name}") } +} + +/// How to review a build whose check is waiting: over MCP for an agent, on the build's page for a person. +#[must_use] +pub fn review_hint(org: &str, project: &str, number: i32) -> String { + format!( + "**To review:** an agent with VisualCI's MCP server calls `get_build` (project `{org}/{project}`, build {number}), \ + opens each change with `get_snapshot`, and approves the changes that were meant with `review`; for a change \ + that wasn't, it fixes the code and pushes again. A person reviews on the build's page. This check turns green \ + once the changes are approved." + ) +} + +/// The check's status, conclusion and title for a build. `superseded_by` is the number of the build whose review +/// covered this one's changes. +#[must_use] +pub fn check_state(build: &Build, project: &Project, superseded_by: Option) -> (String, Option, String) { + let stats = stats(build); + let changes = stats.changes(); + let done = |c: &str, t: String| ("completed".to_string(), Some(c.to_string()), t); + match (build.state.as_str(), build.conclusion.as_deref(), build.review_state.as_str()) { + // A build that failed as a whole (abandoned, out of credits, nothing sent) says why in its first sentence + ("failed", _, _) | (_, Some("failed"), _) if stats.failed == 0 && build.error.is_some() => { + let why = build.error.as_deref().and_then(|e| e.split(", so ").next()).unwrap_or("Build failed"); + done("failure", why.chars().take(120).collect()) + } + ("failed", _, _) | (_, Some("failed"), _) => { + let n = stats.failed.max(1); + done("failure", format!("{n} {} failed", if n == 1 { "snapshot" } else { "snapshots" })) + } + ("completed", Some("unchanged"), _) => done("success", format!("{} snapshots unchanged", stats.total)), + ("completed", _, "approved" | "auto_approved") => done("success", format!("{changes} changes approved")), + ("completed", _, "rejected") => done("failure", format!("{changes} changes rejected")), + // A later build's review covered this one's changes + ("completed", _, "superseded") => { + done("neutral", superseded_by.map_or_else(|| "Superseded".to_string(), |n| format!("Superseded by #{n}"))) + } + // Its pull request was closed without merging, or its branch deleted + ("completed", _, "closed") => done("neutral", "Closed without review".to_string()), + ("completed", _, _) if build.mode == "local" => done("neutral", format!("{changes} changes (local run)")), + ("completed", _, _) if BuildSettings::new(project, build).ci_mode() == "strict" => { + done("failure", format!("{changes} changes to review")) + } + ("completed", _, _) => ("in_progress".to_string(), None, format!("{changes} changes waiting for review")), + _ => ("in_progress".to_string(), None, "Processing".to_string()), + } +} + +/// The whole check for a CI build: its state, the counts, who reviewed it, what changed, and how to review it. +/// +/// # Errors +/// On a database error. +pub async fn check_for(build: &Build, project: &Project, org: &Organization) -> laravel::Result { + let superseded_by = match build.superseded_by_build_id { + Some(id) => Build::find(id).await?.map(|b| b.number), + None => None, + }; + let (status, conclusion, title) = check_state(build, project, superseded_by); + let stats = stats(build); + let url = crate::http::api::builds::BuildResponse::new(build, project, org).url; + let mut summary = format!( + "{} unchanged, {} changed, {} added, {} removed, {} ignored, {} failed.\n\n[Review build #{}]({url})", + stats.unchanged, stats.changed, stats.added, stats.removed, stats.ignored, stats.failed, build.number + ); + // Who reviewed it: an agent for its person reads as the agent, never as the person's own review + if let Some(r) = crate::domain::reviews::shown(build.id, 1).await?.into_iter().next() { + let mut line = r.line(); + if let Some(c) = line.get_mut(..1) { + c.make_ascii_uppercase(); + } + summary.push_str(&format!("\n\n{line}.")); + if let Some(note) = &r.note { + summary.push_str(&format!(" {note}")); + } + } + // What changed, from the comparison + if let Some(line) = crate::domain::summary::summary_line(build).await? { + summary = format!("{line}\n\n{summary}"); + } + if status == "in_progress" && build.state == "completed" { + summary = format!("{summary}\n\n{}", review_hint(&org.slug, &project.slug, build.number)); + } + Ok(Check { + name: check_name(&build.name), + head_sha: build.commit_sha.clone(), + status, + conclusion, + details_url: url, + title, + summary, + }) +} + +/// The advisory lock namespace for posting a build's check ("VCI2"). +const LOCKS: i32 = 1_447_249_202; + +/// Post a CI build's check to its project's forge, and remember the check's ID for the next update. +#[derive(Queueable)] +pub struct ReportCheck { + pub build_id: i64, +} + +#[job( + name = "forge.check", + tries = 5, + backoff = [10.seconds(), 1.minutes(), 5.minutes()], + debounce_for = 3.seconds(), + max_wait = 30.seconds() +)] +impl ReportCheck { + async fn handle(self, attempt: &Attempt) -> laravel::Result<()> { + let build_id = self.build_id; + // One post at a time per build, from the build as it is once the lock is held: a slow post can't land after + // a newer one and leave the forge showing an older state + let posted = laravel::db::transaction(async |_| { + laravel::db::query!("SELECT pg_advisory_xact_lock({LOCKS}, ({build_id} % 2147483647)::int)") + .select() + .await?; + let Some(build) = Build::find(build_id).await? else { return Ok(()) }; + if build.mode != "ci" { + return Ok(()); + } + let project = Project::find_or_fail(build.project_id).await?; + let Some((target, repository)) = report::target(&project).await? else { return Ok(()) }; + let org = Organization::find_or_fail(project.organization_id).await?; + let check = check_for(&build, &project, &org).await?; + let id = report::report_check(&target, &repository, build.forge_check_id.as_deref(), &check).await?; + if build.forge_check_id.as_deref() != Some(id.as_str()) { + laravel::db::query!("UPDATE builds SET forge_check_id = {id} WHERE id = {build_id}").update().await?; + } + Ok(()) + }) + .await; + match posted { + Err(e) if e.downcast_ref::().is_some() => { + let wait = e.downcast_ref::().map(|r| r.retry_in).unwrap_or_default(); + tracing::warn!(build_id, error = %e, "the forge's rate limit: posting the check later"); + attempt.release(wait); + Ok(()) + } + other => other, + } + } + + fn debounce_id(&self) -> i64 { + self.build_id + } +} diff --git a/app/src/forge/mod.rs b/app/src/forge/mod.rs index d4c3984c..aee525e7 100644 --- a/app/src/forge/mod.rs +++ b/app/src/forge/mod.rs @@ -2,12 +2,16 @@ //! side). These are the forge-neutral types: kinds, permissions, repository URLs, and what a sign-in learns. Each //! forge's API calls are in its own module. +pub mod checks; pub mod events; pub mod github; pub mod github_app; pub mod gitlab; pub mod link; pub mod open_source; +pub mod outbound; +pub mod pr_comment; +pub mod report; 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..da89713d --- /dev/null +++ b/app/src/forge/outbound.rs @@ -0,0 +1,239 @@ +//! 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. A base URL that is an IP literal skips the resolver, so callers refuse IP literals before sending. +//! `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, +} + +/// 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")) +} + +/// 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(); + // 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() + || (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)) +} + +/// 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 +/// 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.no_proxy().redirect(reqwest::redirect::Policy::none()).connect_timeout(Duration::from_secs(10)); + if private { builder } else { builder.dns_resolver(Arc::new(PublicOnly)) } + }) +} + +/// A forge's answer: its status, headers and body. +#[derive(Debug, Clone)] +pub struct Reply { + pub status: u16, + pub headers: reqwest::header::HeaderMap, + pub body: String, +} + +impl Reply { + /// A header's value, when it's text. + #[must_use] + pub fn header(&self, name: &str) -> Option<&str> { + self.headers.get(name).and_then(|v| v.to_str().ok()) + } + + #[must_use] + pub fn successful(&self) -> bool { + (200..300).contains(&self.status) + } +} + +/// Send a request to `base` (a forge's base URL) and read its answer: 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 exchange(request: PendingRequest, base: &str) -> laravel::Result { + if trusted(base) { + let response = request.await?; + return Ok(Reply { + status: response.status().as_u16(), + headers: response.headers().clone(), + body: response.text().into_owned(), + }); + } + // 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, headers) = (response.status().as_u16(), response.headers().clone()); + 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(Reply { status, headers, body: 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())))? +} + +/// [`exchange`], for its status and body. +/// +/// # Errors +/// As [`exchange`]. +pub async fn send(request: PendingRequest, base: &str) -> laravel::Result<(u16, String)> { + exchange(request, base).await.map(|r| (r.status, r.body)) +} + +/// [`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", + "::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", "2002:101:101::"] { + assert!(is_public(public.parse().unwrap()), "{public}"); + } + } +} diff --git a/app/src/forge/pr_comment.rs b/app/src/forge/pr_comment.rs new file mode 100644 index 00000000..bfa58eb6 --- /dev/null +++ b/app/src/forge/pr_comment.rs @@ -0,0 +1,366 @@ +//! VisualCI's comment on a pull request (sc-8900, the forge side), ported from today's `workers::pr_comment`: one per +//! project and pull request, edited in place as its builds change. It gives each suite's newest build for the pull +//! request: counts, the review state, before and after images of the changed screenshots and pages (week-long signed +//! URLs, since the forge shows them long after VisualCI could refresh them), what was removed, and a link to the +//! build. +//! +//! A pull request whose suites are all unchanged gets no comment (the passing check says so, and a comment would +//! only fill inboxes), unless the project's `comment_when_unchanged` is on. A comment already there is still +//! updated: GitHub doesn't email about edits. `BuildChanged` queues [`PostPrComment`], debounced per build. + +use std::collections::HashSet; + +use laravel::db; +use laravel::queue::{Attempt, Queueable, job}; +use sha2::Digest; + +use super::ForgeKind; +use super::report::{self, RateLimited}; +use crate::domain::builds::{Stats, stats}; +use crate::domain::changeset::{self, Target}; +use crate::domain::reviews::{self, Shown}; +use crate::models::{Build, Organization, Project}; +use crate::storage::BlobStore; + +/// The comment's first line, so a person (or an agent) sees whose it is. +pub const MARKER: &str = ""; +/// At most this many changed snapshots get images; the rest are counted. +pub const MAX_IMAGES: usize = 8; +/// At most this many removed snapshots are named. +pub const MAX_REMOVED: usize = 20; + +/// One changed snapshot, with its before and after images when it has them. +#[derive(Debug, Clone, Default)] +pub struct Change { + pub name: String, + pub state: String, + /// `document`, `image` or `text`: a text snapshot has no images to show. + pub kind: String, + pub before: Option, + pub after: Option, +} + +/// One suite's newest build for the pull request. +#[derive(Debug, Clone, Default)] +pub struct Suite { + pub project: String, + pub name: String, + pub number: i32, + pub url: String, + pub state: String, + pub review_state: String, + pub stats: Stats, + pub error: Option, + pub changes: Vec, + pub more_changes: usize, + pub removed: Vec, + pub more_removed: usize, + /// "This PR vs base", across all the pull request's builds of the suite. + pub pr_vs_base: Option, + /// The latest review: who made it ("Claude Code for Ada") and their note. + pub review: Option, +} + +fn status_line(s: &Suite) -> String { + match (s.state.as_str(), s.review_state.as_str()) { + ("failed", _) => format!("failed: {}", s.error.as_deref().unwrap_or("see the build")), + ("receiving" | "processing", _) => "comparing…".to_string(), + (_, "pending") => "waiting for review".to_string(), + (_, "approved" | "rejected") if s.review.is_some() && s.stats.changes() > 0 => { + s.review.as_ref().map(Shown::line).unwrap_or_default() + } + (_, "approved" | "auto_approved") if s.stats.changes() > 0 => "approved".to_string(), + (_, "rejected") => "rejected".to_string(), + (_, "superseded") => "superseded by a newer build".to_string(), + (_, "closed") => "closed without review".to_string(), + _ if s.stats.changes() == 0 => "no changes".to_string(), + _ => s.review_state.replace('_', " "), + } +} + +fn counts(stats: &Stats) -> String { + let parts: Vec = [ + (stats.changed, "changed"), + (stats.added, "added"), + (stats.removed, "removed"), + (stats.failed, "failed"), + (stats.unchanged, "unchanged"), + ] + .into_iter() + .filter(|(n, _)| *n > 0) + .map(|(n, label)| format!("{n} {label}")) + .collect(); + if parts.is_empty() { "nothing sent".to_string() } else { parts.join(", ") } +} + +fn builds_word(n: usize) -> String { + if n == 1 { "1 build".to_string() } else { format!("{n} builds") } +} + +/// The comment's Markdown. `request` is the forge's short name for a pull request: `PR` (GitHub), `MR` (GitLab). +#[must_use] +pub fn render(suites: &[Suite], request: &str) -> String { + let mut out = vec![MARKER.to_string(), "### VisualCI".to_string(), String::new()]; + for s in suites { + let suite = if s.name == "default" { String::new() } else { format!(" · {}", s.name) }; + out.push(format!( + "**{}**{suite} · [build #{}]({}) · {} · {}", + s.project, + s.number, + s.url, + counts(&s.stats), + status_line(s) + )); + if let Some(note) = s.review.as_ref().and_then(|r| r.note.as_deref()) { + out.push(String::new()); + out.push(format!("> {}", note.replace('\n', " "))); + } + if let Some(line) = &s.pr_vs_base { + out.push(String::new()); + out.push(format!("This {request} vs base: {line}")); + } + out.push(String::new()); + if !s.changes.is_empty() { + out.push("| Snapshot | Before | After |".to_string()); + out.push("| --- | --- | --- |".to_string()); + let img = |u: &Option| { + u.as_ref().map_or_else(|| "–".to_string(), |u| format!("")) + }; + for c in &s.changes { + let (before, after) = if c.kind == "text" { + ("text".to_string(), "text, see the build".to_string()) + } else { + (img(&c.before), img(&c.after)) + }; + out.push(format!("| `{}` ({}) | {before} | {after} |", c.name.replace('|', "\\|"), c.state)); + } + if s.more_changes > 0 { + out.push(format!("| and {} more in [the build]({}) | | |", s.more_changes, s.url)); + } + out.push(String::new()); + } + if !s.removed.is_empty() { + let mut names: Vec = s.removed.iter().map(|n| format!("`{n}`")).collect(); + if s.more_removed > 0 { + names.push(format!("and {} more", s.more_removed)); + } + out.push(format!("Removed: {}", names.join(", "))); + out.push(String::new()); + } + } + out.push("Updated as builds change. Agents can review with VisualCI's MCP tools.".to_string()); + out.join("\n") +} + +/// Whether to post or update the pull request's comment: always when there's something to look at, or a comment to +/// update; when every suite is unchanged, only with the project's `comment_when_unchanged` on. +#[must_use] +pub fn posts(has_comment: bool, comment_when_unchanged: bool, suites: &[Suite]) -> bool { + has_comment || comment_when_unchanged || !all_unchanged(suites) +} + +/// Whether every suite's newest build has finished with nothing to look at: no changed, added, removed or failed +/// snapshots, and no error. +#[must_use] +pub fn all_unchanged(suites: &[Suite]) -> bool { + suites.iter().all(|s| { + s.state == "completed" + && s.error.is_none() + && s.stats.changed == 0 + && s.stats.added == 0 + && s.stats.removed == 0 + && s.stats.failed == 0 + }) +} + +/// A week-long URL for an image, unless retention has deleted it. +async fn embed(store: &BlobStore, sha: Option<&String>) -> laravel::Result> { + let Some(sha) = sha else { return Ok(None) }; + let kept: Option = db::query!("SELECT true FROM blobs WHERE sha256 = {sha}").scalar().await?; + if kept.is_none() { + return Ok(None); + } + Ok(Some(store.embed_url(sha)?)) +} + +/// "This PR vs base" for one suite of the pull request's changeset. +fn pr_vs_base(changes: &[changeset::Suite], name: &str) -> Option { + let c = changes.iter().find(|c| c.name == name)?; + let parts: Vec = ["changed", "added", "removed"] + .into_iter() + .map(|k| (c.count(k), k)) + .filter(|(n, _)| *n > 0) + .map(|(n, k)| format!("{n} {k}")) + .collect(); + let since = c.base_build.map_or_else(String::new, |n| format!(" since #{n}")); + let pending = c.entries.iter().filter(|e| e.review == "pending").count(); + Some(if parts.is_empty() { + format!("nothing{since}, across {}", builds_word(c.builds)) + } else { + let waiting = if pending > 0 { format!(" · {pending} not approved yet") } else { String::new() }; + format!("{}{since}, across {}{waiting}", parts.join(", "), builds_word(c.builds)) + }) +} + +/// Each suite's newest CI build for this pull request, ready to render, suites by name. +/// +/// # Errors +/// On a database or blob store error. +pub async fn suites(project: &Project, org: &Organization, pr_number: i32) -> laravel::Result> { + let store = BlobStore::current().await?; + let project_id = project.id; + let all: Vec = db::query!( + "SELECT * FROM builds WHERE project_id = {project_id} AND pr_number = {pr_number} AND mode = 'ci' \ + ORDER BY id DESC" + ) + .select_as() + .await?; + let changes = changeset::changeset(project, &Target::Pr(pr_number)).await?; + let mut seen = HashSet::new(); + let mut out = Vec::new(); + for build in all.into_iter().filter(|b| seen.insert(b.name.clone())) { + let list = crate::domain::snapshots::of_build(build.id).await?; + let mut changed: Vec<_> = + list.iter().filter(|s| matches!(s.state.as_str(), "changed" | "added" | "failed")).collect(); + // Screenshots and PDFs first: they're what the images in the comment are for + changed.sort_by_key(|s| (s.kind == "text", s.state != "changed", s.name.clone())); + let mut shown = Vec::new(); + for s in changed.iter().take(MAX_IMAGES) { + let snapshot_id = s.id; + let pages: Vec = + db::query!("SELECT * FROM snapshot_pages WHERE snapshot_id = {snapshot_id} ORDER BY position") + .select_as() + .await?; + let page = pages.iter().find(|p| p.state == "changed").or(pages.first()); + shown.push(Change { + name: s.name.clone(), + state: s.state.clone(), + kind: s.kind.clone(), + before: embed(&store, page.and_then(|p| p.base_image.as_ref())).await?, + after: embed(&store, page.and_then(|p| p.head_image.as_ref())).await?, + }); + } + let removed: Vec = list.iter().filter(|s| s.state == "removed").map(|s| s.name.clone()).collect(); + out.push(Suite { + project: format!("{}/{}", org.slug, project.slug), + name: build.name.clone(), + number: build.number, + url: crate::http::api::builds::BuildResponse::new(&build, project, org).url, + state: build.state.clone(), + review_state: build.review_state.clone(), + stats: stats(&build), + error: build.error.clone(), + more_changes: changed.len().saturating_sub(MAX_IMAGES), + changes: shown, + more_removed: removed.len().saturating_sub(MAX_REMOVED), + removed: removed.into_iter().take(MAX_REMOVED).collect(), + pr_vs_base: pr_vs_base(&changes, &build.name), + review: reviews::shown(build.id, 1).await?.into_iter().next(), + }); + } + out.sort_by(|a, b| a.name.cmp(&b.name)); + Ok(out) +} + +/// The advisory lock namespace for a pull request's comment ("VCI3"). +const LOCKS: i32 = 1_447_249_203; + +/// Post or update VisualCI's comment on a CI build's pull request. +#[derive(Queueable)] +pub struct PostPrComment { + pub build_id: i64, +} + +#[job( + name = "forge.pr_comment", + tries = 5, + backoff = [10.seconds(), 1.minutes(), 5.minutes()], + debounce_for = 5.seconds(), + max_wait = 1.minutes() +)] +impl PostPrComment { + async fn handle(self, attempt: &Attempt) -> laravel::Result<()> { + let build_id = self.build_id; + let Some(build) = Build::find(build_id).await? else { return Ok(()) }; + let Some(pr_number) = build.pr_number.filter(|_| build.mode == "ci") else { return Ok(()) }; + let project_id = build.project_id; + // One post at a time per project and pull request (builds of two suites post to the same comment), the + // comment's row read and written under the lock + let posted = db::transaction(async |_| { + db::query!( + "SELECT pg_advisory_xact_lock({LOCKS}, hashtext({project_id}::text || ':' || {pr_number}::text))" + ) + .select() + .await?; + post(project_id, pr_number, build_id).await + }) + .await; + match posted { + Err(e) if e.downcast_ref::().is_some() => { + let wait = e.downcast_ref::().map(|r| r.retry_in).unwrap_or_default(); + tracing::warn!(build_id, error = %e, "the forge's rate limit: posting the comment later"); + attempt.release(wait); + Ok(()) + } + // Without permission to comment (403), retrying won't help: it waits for the installation's owner + Err(e) if e.to_string().contains("HTTP 403") => { + tracing::warn!(build_id, error = %e, "no permission to comment on the pull request"); + Ok(()) + } + other => other, + } + } + + fn debounce_id(&self) -> i64 { + self.build_id + } +} + +/// Post or update the comment on a project's pull request. Run under the pull request's lock. +async fn post(project_id: i64, pr_number: i32, build_id: i64) -> laravel::Result<()> { + let project = Project::find_or_fail(project_id).await?; + let Some((target, repository)) = report::target(&project).await? else { return Ok(()) }; + let org = Organization::find_or_fail(project.organization_id).await?; + let request = if repository.forge == ForgeKind::Gitlab { "MR" } else { "PR" }; + let suites = suites(&project, &org, pr_number).await?; + let existing = db::query!( + "SELECT forge_comment_id, body_sha256 FROM pr_comments WHERE project_id = {project_id} AND pr_number = {pr_number}" + ) + .select_one() + .await?; + let existing: Option<(String, Option)> = match existing { + Some(r) => Some((r.try_get("forge_comment_id")?, r.try_get("body_sha256")?)), + None => None, + }; + // Nothing changed: the check says so, and a comment would only fill people's inboxes. One already there (an + // earlier build had changes) is still updated, to show the pull request is clean now + if !posts(existing.is_some(), project.comment_when_unchanged, &suites) { + return Ok(()); + } + let body = render(&suites, request); + let hash = body_hash(&body); + if existing.as_ref().and_then(|e| e.1.as_deref()) == Some(hash.as_str()) { + return Ok(()); + } + let id = + report::upsert_comment(&target, &repository, pr_number, existing.as_ref().map(|e| e.0.as_str()), &body).await?; + tracing::debug!(build_id, pr_number, comment = id, "posted the pull request comment"); + db::query!( + "INSERT INTO pr_comments (project_id, pr_number, forge_comment_id, body_sha256, created_at, updated_at) \ + VALUES ({project_id}, {pr_number}, {id}, {hash}, now(), now()) \ + ON CONFLICT (project_id, pr_number) DO UPDATE SET forge_comment_id = EXCLUDED.forge_comment_id, \ + body_sha256 = EXCLUDED.body_sha256, updated_at = now()" + ) + .insert() + .await?; + Ok(()) +} + +/// The comment's hash, to skip posting a body the forge already shows: its images' signed URLs left out (their +/// signatures change with every render, and the images behind them don't). +#[must_use] +pub fn body_hash(body: &str) -> String { + static SIGNED: std::sync::LazyLock = + std::sync::LazyLock::new(|| regex::Regex::new(r"(https?://[^\s()<>\x22']+?)\?[^\s()<>\x22']*").unwrap()); + hex::encode(sha2::Sha256::digest(SIGNED.replace_all(body, "$1").as_bytes())) +} diff --git a/app/src/forge/report.rs b/app/src/forge/report.rs new file mode 100644 index 00000000..229a1c54 --- /dev/null +++ b/app/src/forge/report.rs @@ -0,0 +1,303 @@ +//! Posting to a linked project's forge (sc-8900, the forge side), ported from today's server: a build's check (a +//! GitHub check run, a GitLab commit status) and VisualCI's comment on a pull request (an issue comment, a merge +//! request note). The jobs that decide what to post are `forge::checks` and `forge::pr_comment`. + +use laravel::http::client; +use serde_json::{Value, json}; + +use super::github_app::{self, GithubApp}; +use super::gitlab::{self, GitlabBot, GitlabConfig}; +use super::outbound::{self, Reply}; +use super::{ForgeKind, Repository}; +use crate::models::Project; + +const GITHUB: &str = "https://api.github.com"; + +/// A check on a pull request's commit. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Check { + pub name: String, + pub head_sha: String, + /// `queued`, `in_progress` or `completed`. + pub status: String, + /// With `completed`: `success`, `failure`, `neutral` or `action_required`. + pub conclusion: Option, + pub details_url: String, + pub title: String, + pub summary: String, +} + +/// Where a linked project's posts go, with the credentials to post them. +pub enum Target { + /// The GitHub App, through the installation on the repository. + Github { app: GithubApp, installation: String }, + /// A GitLab: VisualCI's own, as its bot, or an organization's instance, with the project's access token. + Gitlab { base: String, token: String }, +} + +/// The forge a linked project posts to, and its repository. `None` when the project isn't linked, or its forge +/// isn't set up on this server. +/// +/// # Errors +/// On a database error. +pub async fn target(project: &Project) -> laravel::Result> { + if project.forge.as_deref() == Some(ForgeKind::Gitlab.as_str()) { + return Ok(gitlab_target(project)); + } + let Some(repository) = project.repository_url.as_deref().and_then(Repository::parse) else { return Ok(None) }; + let config = laravel::config(); + let (Some(installation), Some(app)) = (project.forge_installation.clone(), config.get::().cloned()) + else { + return Ok(None); + }; + if repository.forge != ForgeKind::Github || !github_app::configured(&app) { + return Ok(None); + } + Ok(Some((Target::Github { app, installation }, repository.with_id(project.repository_id.clone())))) +} + +/// A GitLab project's target: VisualCI's own GitLab, as its bot (organizations' instances come with sc-8634). +fn gitlab_target(project: &Project) -> Option<(Target, Repository)> { + let repository = + Repository::parse(project.repository_url.as_deref()?).map(|r| r.with_id(project.repository_id.clone()))?; + let config = laravel::config(); + let base = config.get::()?.url.trim_end_matches('/').to_string(); + let token = config.get::()?.token.clone()?; + (project.forge_installation.as_deref() == Some(gitlab::BOT) && repository.site_url().eq_ignore_ascii_case(&base)) + .then_some((Target::Gitlab { base, token }, repository)) +} + +fn err(what: &str, status: u16, body: &str) -> laravel::Error { + laravel::Error::msg(format!("{what}: HTTP {status}: {}", body.chars().take(300).collect::())) +} + +/// The forge's rate limit was reached: try again after `retry_in` (the jobs release themselves for that long, rather +/// than taking it for missing permission). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RateLimited { + pub what: String, + pub retry_in: std::time::Duration, +} + +impl std::fmt::Display for RateLimited { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}: rate limited, trying again in {} seconds", self.what, self.retry_in.as_secs()) + } +} + +impl std::error::Error for RateLimited {} + +/// How long a rate-limited answer says to wait: a 429, or a 403 that GitHub sends for its primary limit +/// (`x-ratelimit-remaining: 0`) or secondary one (the body says so). From `retry-after`, else +/// `x-ratelimit-reset`, else a minute; between a second and an hour. +#[must_use] +pub fn rate_limit_wait(reply: &Reply) -> Option { + let limited = reply.status == 429 + || (reply.status == 403 + && (reply.header("x-ratelimit-remaining") == Some("0") + || reply.body.to_ascii_lowercase().contains("rate limit"))); + if !limited { + return None; + } + let now = laravel::now().timestamp().as_second(); + let secs = reply + .header("retry-after") + .and_then(|v| v.trim().parse::().ok()) + .or_else(|| reply.header("x-ratelimit-reset").and_then(|v| v.trim().parse::().ok()).map(|t| t - now)) + .unwrap_or(60) + .clamp(1, 3600); + Some(std::time::Duration::from_secs(secs.unsigned_abs())) +} + +/// The error for a refused request: [`RateLimited`] when it was the rate limit. +fn refused(what: &str, reply: &Reply) -> laravel::Error { + match rate_limit_wait(reply) { + Some(retry_in) => RateLimited { what: what.to_string(), retry_in }.into(), + None => err(what, reply.status, &reply.body), + } +} + +/// A project ID in GitLab's API: its path, URL-encoded. +fn gitlab_project(path: &str) -> String { + url::form_urlencoded::byte_serialize(path.as_bytes()).collect() +} + +/// A check as a GitLab commit status: `pending`, `running`, `success`, `failed` (or `canceled`). A neutral result +/// (local, superseded) passes: it shouldn't block a merge. +#[must_use] +pub fn status_state(check: &Check) -> &'static str { + match (check.status.as_str(), check.conclusion.as_deref()) { + ("queued", _) => "pending", + ("completed", Some("success" | "neutral")) => "success", + ("completed", Some("cancelled" | "canceled")) => "canceled", + ("completed", _) => "failed", + _ => "running", + } +} + +/// Create or update a check on a commit; returns its ID for the next update (GitLab keeps one status per name and +/// commit, so its "ID" is the status's name). +/// +/// # Errors +/// When the forge refuses it. +pub async fn report_check( + target: &Target, + repository: &Repository, + existing: Option<&str>, + check: &Check, +) -> laravel::Result { + let path = &repository.path; + match target { + Target::Github { app, installation } => { + let token = github_app::installation_token(app, installation).await?; + let request = match existing { + Some(id) => client::patch(format!("{GITHUB}/repos/{path}/check-runs/{id}")), + None => client::post(format!("{GITHUB}/repos/{path}/check-runs")), + }; + let request = request + .token(token) + .header("accept", "application/vnd.github+json") + .header("user-agent", "visualci") + .json(json!({ + "name": check.name, "head_sha": check.head_sha, "status": check.status, + "conclusion": check.conclusion, "details_url": check.details_url, + "output": { "title": check.title, "summary": check.summary }, + })); + let reply = outbound::exchange(request, GITHUB).await?; + if !reply.successful() { + return Err(refused("GitHub check run", &reply)); + } + let created: Value = + serde_json::from_str(&reply.body).map_err(|e| laravel::Error::msg(format!("GitHub check run: {e}")))?; + created["id"] + .as_i64() + .map(|i| i.to_string()) + .ok_or_else(|| laravel::Error::msg("a check run without an id")) + } + Target::Gitlab { base, token } => { + let description: String = check.title.chars().take(255).collect(); + let request = + client::post(format!("{base}/api/v4/projects/{}/statuses/{}", gitlab_project(path), check.head_sha)) + .token(token) + .json(json!({ + "state": status_state(check), "name": check.name, + "target_url": check.details_url, "description": description, + })); + let reply = outbound::exchange(request, base).await?; + // Setting the state a status already has is refused ("Cannot transition status via :run from :running") + if reply.status == 400 && reply.body.contains("Cannot transition status") { + return Ok(check.name.clone()); + } + if !reply.successful() { + return Err(refused("GitLab commit status", &reply)); + } + Ok(check.name.clone()) + } + } +} + +/// Create or edit VisualCI's comment on a pull request (`existing` is the one it made before; one someone deleted is +/// made again). Returns the comment's ID. +/// +/// # Errors +/// When the forge refuses it. +pub async fn upsert_comment( + target: &Target, + repository: &Repository, + pr_number: i32, + existing: Option<&str>, + body: &str, +) -> laravel::Result { + let path = &repository.path; + let (token, comments, one, what) = match target { + Target::Github { app, installation } => ( + github_app::installation_token(app, installation).await?, + format!("{GITHUB}/repos/{path}/issues/{pr_number}/comments"), + format!("{GITHUB}/repos/{path}/issues/comments"), + "GitHub PR comment", + ), + Target::Gitlab { base, token } => { + let notes = format!("{base}/api/v4/projects/{}/merge_requests/{pr_number}/notes", gitlab_project(path)); + (token.clone(), notes.clone(), notes, "GitLab MR note") + } + }; + let (github, base) = match target { + Target::Github { .. } => (true, GITHUB.to_string()), + Target::Gitlab { base, .. } => (false, base.clone()), + }; + let send = async |request: client::PendingRequest, body: Option<&str>| { + let request = request.token(&token); + let request = match body { + Some(body) => request.json(json!({ "body": body })), + None => request.accept_json(), + }; + let request = if github { + request.header("accept", "application/vnd.github+json").header("user-agent", "visualci") + } else { + request + }; + outbound::exchange(request, &base).await + }; + // No comment remembered (the first post, or one whose row wasn't saved after the forge took it): look for + // VisualCI's own on the pull request before posting, so a retry edits it instead of posting a second + let existing = match existing { + Some(id) => Some(id.to_string()), + None => { + let mut found = None; + for page in 1..=10 { + let reply = send(client::get(format!("{comments}?per_page=100&page={page}")), None).await?; + if !reply.successful() { + return Err(refused(what, &reply)); + } + let list: Vec = serde_json::from_str(&reply.body).unwrap_or_default(); + found = list.iter().find(|c| ours(c, github)).and_then(|c| c["id"].as_i64()).map(|i| i.to_string()); + if found.is_some() || list.len() < 100 { + break; + } + } + found + } + }; + if let Some(id) = existing { + let edit = if github { client::patch(format!("{one}/{id}")) } else { client::put(format!("{one}/{id}")) }; + let reply = send(edit, Some(body)).await?; + if reply.successful() { + return Ok(id); + } + if reply.status != 404 { + return Err(refused(what, &reply)); + } + } + let reply = send(client::post(comments), Some(body)).await?; + if !reply.successful() { + return Err(refused(what, &reply)); + } + let created: Value = serde_json::from_str(&reply.body).map_err(|e| laravel::Error::msg(format!("{what}: {e}")))?; + created["id"].as_i64().map(|i| i.to_string()).ok_or_else(|| laravel::Error::msg(format!("a {what} without an id"))) +} + +/// Whether a comment on a pull request is VisualCI's: it starts with the marker, and on GitHub a bot (the App) +/// wrote it, so a person quoting the marker isn't taken for it. +fn ours(comment: &Value, github: bool) -> bool { + let marked = comment["body"].as_str().is_some_and(|b| b.starts_with(super::pr_comment::MARKER)); + marked && (!github || comment["user"]["type"] == "Bot") && comment["system"] != true +} + +/// A build's state, review or snapshots changed: its check, and its pull request's comment when it has one, are +/// posted again (debounced, so a burst of changes is one post each). Only CI builds of linked projects post. +#[laravel::event::listener] +pub async fn post_to_the_forge(event: laravel::event::Event) -> laravel::Result<()> { + let Some(build) = crate::models::Build::find(event.build_id).await? else { return Ok(()) }; + if build.mode != "ci" { + return Ok(()); + } + let project = Project::find_or_fail(build.project_id).await?; + if target(&project).await?.is_none() { + return Ok(()); + } + super::checks::ReportCheck { build_id: build.id }.dispatch().await?; + if build.pr_number.is_some() { + super::pr_comment::PostPrComment { build_id: build.id }.dispatch().await?; + } + Ok(()) +} diff --git a/app/tests/forge_reports.rs b/app/tests/forge_reports.rs new file mode 100644 index 00000000..c1758fd2 --- /dev/null +++ b/app/tests/forge_reports.rs @@ -0,0 +1,318 @@ +//! What VisualCI posts to a linked project's forge: a check per suite and one comment per pull request, kept up to +//! date as builds change. The comment's Markdown is compared with golden files in `tests/goldens/`; run with +//! `UPDATE_GOLDENS=1` to rewrite them after a change you meant, and read the diff. + +use app::domain::builds::Stats; +use app::domain::reviews::Shown; +use app::events::BuildChanged; +use app::forge::checks::check_state; +use app::forge::pr_comment::{Change, MARKER, Suite, posts, render}; +use app::models::{Build, User}; +use app::testing::fixtures; +use laravel::db; +use laravel::http::client; +use laravel::model::create; +use laravel::testing::prelude::*; + +/// The golden file `tests/goldens/` says `body`, or is rewritten with it under `UPDATE_GOLDENS=1`. +fn golden(name: &str, body: &str) { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/goldens").join(name); + if std::env::var("UPDATE_GOLDENS").is_ok_and(|v| v == "1") { + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, body).unwrap(); + return; + } + let expected = std::fs::read_to_string(&path) + .unwrap_or_else(|_| panic!("no golden {name}: run with UPDATE_GOLDENS=1 to write it, then read it")); + assert_eq!(body, expected, "the {name} golden differs: run with UPDATE_GOLDENS=1 if the change is meant"); +} + +fn suite(state: &str, stats: Stats) -> Suite { + Suite { name: "default".into(), state: state.into(), stats, ..Default::default() } +} + +#[test] +fn nothing_changed_gets_no_new_comment_unless_the_project_asks() { + let clean = [suite("completed", Stats { unchanged: 40, total: 40, ..Default::default() })]; + assert!(!posts(false, false, &clean), "no comment for an unchanged pull request"); + assert!(posts(false, true, &clean), "with comment_when_unchanged on"); + assert!(posts(true, false, &clean), "a comment already there is still updated"); + for stats in [ + Stats { changed: 1, ..Default::default() }, + Stats { added: 1, ..Default::default() }, + Stats { removed: 1, ..Default::default() }, + Stats { failed: 1, ..Default::default() }, + ] { + assert!(posts(false, false, &[suite("completed", stats)]), "changes are always posted"); + } + // One suite clean, another with a change; a build still processing or one that failed isn't "unchanged" + let mixed = [clean[0].clone(), suite("completed", Stats { changed: 2, ..Default::default() })]; + assert!(posts(false, false, &mixed)); + assert!(posts(false, false, &[suite("processing", Stats::default())])); + let errored = Suite { error: Some("out of credits".into()), ..suite("failed", Stats::default()) }; + assert!(posts(false, false, &[errored])); +} + +#[test] +fn the_comment_shows_counts_images_and_removals() { + let image = |name: &str, state: &str, before: Option<&str>, after: Option<&str>| Change { + name: name.into(), + state: state.into(), + kind: "image".into(), + before: before.map(Into::into), + after: after.map(Into::into), + }; + let web = Suite { + project: "acme/web".into(), + name: "default".into(), + number: 12, + url: "https://app.visualci.com/acme/web/builds/12".into(), + state: "completed".into(), + review_state: "pending".into(), + stats: Stats { changed: 2, removed: 1, unchanged: 40, total: 43, ..Default::default() }, + changes: vec![ + image("home|1440", "changed", Some("https://b"), Some("https://a")), + image("cart", "added", None, Some("https://c")), + Change { name: "api.json".into(), state: "changed".into(), kind: "text".into(), ..Default::default() }, + ], + more_changes: 3, + removed: vec!["old".into()], + pr_vs_base: Some("3 changed, 1 removed since #10, across 2 builds · 1 not approved yet".into()), + ..Default::default() + }; + let pdf = Suite { + project: "acme/web".into(), + name: "pdf".into(), + number: 13, + url: "https://app.visualci.com/acme/web/builds/13".into(), + state: "completed".into(), + review_state: "auto_approved".into(), + stats: Stats { unchanged: 8, total: 8, ..Default::default() }, + ..Default::default() + }; + let body = render(&[web, pdf], "PR"); + assert!(body.starts_with(MARKER), "{body}"); + golden("pr_comment.md", &body); +} + +/// An agent's approval says it was the agent, for its person, never the person alone (Nathan, 2 Dec 2026). +#[test] +fn the_comment_says_who_approved_and_why() { + let suite = Suite { + project: "acme/web".into(), + name: "default".into(), + number: 12, + url: "https://app.visualci.com/acme/web/builds/12".into(), + state: "completed".into(), + review_state: "approved".into(), + stats: Stats { changed: 2, total: 2, ..Default::default() }, + review: Some(Shown { + action: "approve".into(), + by: "Claude Code for Ada Lovelace".into(), + note: Some("The new header, as asked.".into()), + snapshots: 2, + created_at: String::new(), + }), + ..Default::default() + }; + golden("pr_comment_approved.md", &render(&[suite], "MR")); +} + +/// A GitHub App key made once per run (base64 of its PEM). +fn app_key() -> &'static str { + static KEY: std::sync::OnceLock = std::sync::OnceLock::new(); + KEY.get_or_init(|| { + use base64::Engine; + use rsa::pkcs1::EncodeRsaPrivateKey; + let key = rsa::RsaPrivateKey::new(&mut rsa::rand_core::OsRng, 2048).expect("a key"); + let pem = key.to_pkcs1_pem(rsa::pkcs1::LineEnding::LF).expect("its PEM"); + base64::engine::general_purpose::STANDARD.encode(pem.as_bytes()) + }) +} + +fn github_app() -> Application { + app::testing::configure() + .with_env("GITHUB_APP_ID", "1") + .with_env("GITHUB_APP_PRIVATE_KEY_BASE64", app_key()) + .create() +} + +/// A build's stats, every count given (a missing one makes the whole thing unreadable). +fn counts(changed: usize, unchanged: usize) -> serde_json::Value { + serde_json::to_value(Stats { total: changed + unchanged, changed, unchanged, ..Default::default() }).unwrap() +} + +/// `acme/web` linked to github.com/acme/web through installation 7, and a CI build of pull request 5 with `stats`. +async fn linked_build(stats: serde_json::Value) -> laravel::Result { + let org = fixtures::organization("acme").await?; + let web = fixtures::project(&org, "web").await?; + let id = web.id; + db::query!( + "UPDATE projects SET forge = 'github', repository_url = 'https://github.com/acme/web', repository_id = '42', \ + forge_installation = '7' WHERE id = {id}" + ) + .update() + .await?; + let build = create!(Build { + pid: laravel::str::uuid7(), + project_id: id, + number: 1, + commit_sha: "abc123", + branch: "feature", + pr_number: Some(5), + mode: "ci", + state: "completed", + review_state: "pending", + stats: stats, + base_build_id: None, + }) + .await?; + Ok(build) +} + +fn github() -> client::HttpFake { + client::fake() + .with("api.github.com/app/installations/7/access_tokens", json!({ "token": "t" })) + .with("api.github.com/repos/acme/web/check-runs", json!({ "id": 900 })) + .with("api.github.com/repos/acme/web/issues/5/comments", json!({ "id": 700 })) +} + +#[laravel::test(app = github_app)] +async fn a_changed_build_gets_a_waiting_check_and_a_comment(_app: Application) -> laravel::Result<()> { + let build = linked_build(counts(1, 2)).await?; + let github = github(); + BuildChanged { build_id: build.id }.dispatch().await?; + + let sent = github.sent(); + let check = sent.iter().find(|r| r.url().ends_with("/check-runs")).expect("a check run"); + let check: serde_json::Value = check.json().unwrap(); + assert_eq!(check["name"], "VisualCI"); + assert_eq!(check["head_sha"], "abc123"); + assert_eq!(check["status"], "in_progress"); + assert_eq!(check["output"]["title"], "1 changes waiting for review"); + assert!(check["output"]["summary"].as_str().unwrap().contains("**To review:**"), "{check}"); + let comment = sent.iter().find(|r| r.url().ends_with("/issues/5/comments")).expect("a comment"); + let body: serde_json::Value = comment.json().unwrap(); + assert!(body["body"].as_str().unwrap().contains("· 1 changed, 2 unchanged · waiting for review"), "{body}"); + + let build_id = build.id; + let check_id: Option = + db::query!("SELECT forge_check_id FROM builds WHERE id = {build_id}").scalar().await?; + assert_eq!(check_id.as_deref(), Some("900"), "the next update edits the same check run"); + let comments: Option = db::query!("SELECT count(*) FROM pr_comments WHERE pr_number = 5").scalar().await?; + assert_eq!(comments, Some(1)); + Ok(()) +} + +#[laravel::test(app = github_app)] +async fn an_unchanged_pull_request_gets_a_passing_check_and_no_comment(_app: Application) -> laravel::Result<()> { + let build = linked_build(counts(0, 3)).await?; + let build_id = build.id; + db::query!("UPDATE builds SET conclusion = 'unchanged', review_state = 'auto_approved' WHERE id = {build_id}") + .update() + .await?; + let github = github(); + BuildChanged { build_id }.dispatch().await?; + + let sent = github.sent(); + let check: serde_json::Value = + sent.iter().find(|r| r.url().ends_with("/check-runs")).expect("a check run").json().unwrap(); + assert_eq!((check["status"].as_str(), check["conclusion"].as_str()), (Some("completed"), Some("success"))); + assert!(!sent.iter().any(|r| r.url().contains("/comments")), "no comment when nothing changed"); + Ok(()) +} + +#[laravel::test] +async fn the_check_says_what_state_the_build_is_in(_app: Application) -> laravel::Result<()> { + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let _ = ada; + let mut build = linked_build(counts(2, 3)).await?; + let project = app::models::Project::find_or_fail(build.project_id).await?; + let state = |b: &Build, by: Option| check_state(b, &project, by); + assert_eq!(state(&build, None), ("in_progress".into(), None, "2 changes waiting for review".into())); + build.review_state = "approved".into(); + assert_eq!(state(&build, None), ("completed".into(), Some("success".into()), "2 changes approved".into())); + build.review_state = "superseded".into(); + assert_eq!(state(&build, Some(4)), ("completed".into(), Some("neutral".into()), "Superseded by #4".into())); + build.state = "failed".into(); + build.error = Some("The organization is out of credits, so the build stopped".into()); + build.stats = counts(0, 0); + assert_eq!( + state(&build, None), + ("completed".into(), Some("failure".into()), "The organization is out of credits".into()) + ); + Ok(()) +} + +/// A comment the forge took whose row wasn't saved (the insert failed after the post) is found on the pull request +/// and edited by the retry, not posted a second time. A person's comment quoting the marker isn't taken for it. +#[laravel::test(app = github_app)] +async fn a_retry_edits_the_comment_already_posted(_app: Application) -> laravel::Result<()> { + let build = linked_build(counts(1, 2)).await?; + let marker = app::forge::pr_comment::MARKER; + let github = client::fake() + .with("api.github.com/app/installations/7/access_tokens", json!({ "token": "t" })) + .with("api.github.com/repos/acme/web/check-runs", json!({ "id": 900 })) + .with( + "api.github.com/repos/acme/web/issues/5/comments?*", + json!([ + { "id": 600, "body": format!("{marker} quoted"), "user": { "type": "User" } }, + { "id": 701, "body": format!("{marker}\n### VisualCI"), "user": { "type": "Bot" } }, + ]), + ) + .with("api.github.com/repos/acme/web/issues/comments/701", json!({ "id": 701 })) + .with("api.github.com/repos/acme/web/issues/5/comments", json!({ "id": 702 })); + BuildChanged { build_id: build.id }.dispatch().await?; + + let sent = github.sent(); + assert!(sent.iter().any(|r| r.method() == "PATCH" && r.url().ends_with("/issues/comments/701")), "edited"); + assert!(!sent.iter().any(|r| r.method() == "POST" && r.url().contains("/comments")), "no second comment"); + let id: Option = + db::query!("SELECT forge_comment_id FROM pr_comments WHERE pr_number = 5").scalar().await?; + assert_eq!(id.as_deref(), Some("701")); + Ok(()) +} + +/// The forge's rate limit is a wait, not missing permission: the jobs release themselves until it resets. +#[laravel::test(app = github_app)] +async fn a_rate_limit_is_waited_out(_app: Application) -> laravel::Result<()> { + use app::forge::outbound::Reply; + use app::forge::report::rate_limit_wait; + let reply = |status: u16, headers: &[(&'static str, String)], body: &str| { + let mut map = laravel::http::client::reqwest::header::HeaderMap::new(); + for (k, v) in headers { + map.insert(*k, v.parse().unwrap()); + } + Reply { status, headers: map, body: body.to_string() } + }; + let reset = (laravel::now().timestamp().as_second() + 120).to_string(); + let primary = reply(403, &[("x-ratelimit-remaining", "0".into()), ("x-ratelimit-reset", reset)], "{}"); + let wait = rate_limit_wait(&primary).expect("the primary limit").as_secs(); + assert!((115..=120).contains(&wait), "{wait}"); + let secondary = + reply(403, &[("retry-after", "30".into())], r#"{"message":"You have exceeded a secondary rate limit"}"#); + assert_eq!(rate_limit_wait(&secondary).map(|d| d.as_secs()), Some(30)); + assert_eq!(rate_limit_wait(&reply(429, &[], "")).map(|d| d.as_secs()), Some(60)); + let forbidden = reply(403, &[], r#"{"message":"Resource not accessible by integration"}"#); + assert_eq!(rate_limit_wait(&forbidden), None, "missing permission isn't a rate limit"); + + // The jobs don't fail on it + let build = linked_build(counts(1, 2)).await?; + let _github = client::fake() + .with("api.github.com/app/installations/7/access_tokens", json!({ "token": "t" })) + .with("api.github.com/repos/acme/web/check-runs", client::response().status(429).header("retry-after", "5")) + .with("api.github.com/repos/acme/web/issues/5/comments*", client::response().status(429)); + BuildChanged { build_id: build.id }.dispatch().await?; + let comments: Option = db::query!("SELECT count(*) FROM pr_comments").scalar().await?; + assert_eq!(comments, Some(0)); + Ok(()) +} + +#[test] +fn the_comments_hash_leaves_out_its_images_signatures() { + use app::forge::pr_comment::body_hash; + let a = "![after](https://blobs.example/ab12?X-Amz-Signature=one&X-Amz-Date=1) [Review](https://app.example/b/1)"; + let b = "![after](https://blobs.example/ab12?X-Amz-Signature=two&X-Amz-Date=2) [Review](https://app.example/b/1)"; + assert_eq!(body_hash(a), body_hash(b)); + assert_ne!(body_hash(a), body_hash(&a.replace("ab12", "cd34")), "another image is another body"); +} diff --git a/app/tests/goldens/pr_comment.md b/app/tests/goldens/pr_comment.md new file mode 100644 index 00000000..21753d5f --- /dev/null +++ b/app/tests/goldens/pr_comment.md @@ -0,0 +1,19 @@ + +### VisualCI + +**acme/web** · [build #12](https://app.visualci.com/acme/web/builds/12) · 2 changed, 1 removed, 40 unchanged · waiting for review + +This PR vs base: 3 changed, 1 removed since #10, across 2 builds · 1 not approved yet + +| Snapshot | Before | After | +| --- | --- | --- | +| `home\|1440` (changed) | | | +| `cart` (added) | – | | +| `api.json` (changed) | text | text, see the build | +| and 3 more in [the build](https://app.visualci.com/acme/web/builds/12) | | | + +Removed: `old` + +**acme/web** · pdf · [build #13](https://app.visualci.com/acme/web/builds/13) · 8 unchanged · no changes + +Updated as builds change. Agents can review with VisualCI's MCP tools. \ No newline at end of file diff --git a/app/tests/goldens/pr_comment_approved.md b/app/tests/goldens/pr_comment_approved.md new file mode 100644 index 00000000..fc601279 --- /dev/null +++ b/app/tests/goldens/pr_comment_approved.md @@ -0,0 +1,8 @@ + +### VisualCI + +**acme/web** · [build #12](https://app.visualci.com/acme/web/builds/12) · 2 changed · approved by Claude Code for Ada Lovelace + +> The new header, as asked. + +Updated as builds change. Agents can review with VisualCI's MCP tools. \ No newline at end of file