From ad342328cb8ef52b110ac4881692374044d3fcd4 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 11:17:18 +1300 Subject: [PATCH 1/2] 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 919e7cca00813618096b3e5836bb9ebd73bf88a7 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 12:30:32 +1300 Subject: [PATCH 2/2] 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?;