From 5281fa3ae43e71a462e9eb2b18e7724c5d9964cf Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Sat, 5 Dec 2026 11:50:22 +0000 Subject: [PATCH 1/4] Follow GitHub repository and organization renames GitHub answers a renamed repository's old /repos/{owner}/{name} path with a 301, which VisualCI's client doesn't follow, so a rename (on 5 Dec 2026 the visualci-com organization became visualcihq) broke checks and PR comments. - Calls about a linked repository go to /repositories/{id}/... when GitHub's ID is known: check runs, PR comments, branch checks, collaborators and the visibility/licence check (now one call instead of two). /repos/{path} stays only for links without an ID and for linking by a typed URL. - The hourly sync already reads each linked repository's name by ID; it now gives projects (and the picker's user_repositories cache) the current https://github.com/ where it differs. - installation_target "renamed" updates github_installations.account_login and rewrites the installation's project URLs and cached repository names under the old login (case-insensitive) to the new one. Tests: ID-based URLs (stale URL still posts by ID; no ID posts by name), the sync following renames, an installation_target delivery; fakes moved to the /repositories/{id} form. --- app/src/forge/calls.rs | 2 +- app/src/forge/github_app.rs | 118 ++++++++++++--- app/src/forge/installations.rs | 8 +- app/src/forge/mod.rs | 7 + app/src/forge/open_source.rs | 11 +- app/src/forge/report.rs | 14 +- app/src/forge/sync.rs | 66 +++++++- app/src/forge/webhooks.rs | 151 +++++++++++++++++-- app/tests/forge_reports.rs | 107 +++++++++++-- app/tests/forge_sync.rs | 266 ++++++++++++++++++++++++++++++++- app/tests/installations.rs | 16 +- app/tests/link.rs | 15 +- app/tests/mcp.rs | 5 +- app/tests/ui.rs | 5 +- app/tests/webhooks.rs | 229 +++++++++++++++++++++++++++- docs/design.md | 15 +- 16 files changed, 949 insertions(+), 86 deletions(-) diff --git a/app/src/forge/calls.rs b/app/src/forge/calls.rs index ab28d25ce..652c193e4 100644 --- a/app/src/forge/calls.rs +++ b/app/src/forge/calls.rs @@ -44,7 +44,7 @@ pub const SIGN_IN_SYNC_BUDGET: u32 = 1 + super::github::SIGN_IN_REPOSITORY_PAGES /// Linking a repository checks it live (`link::link_repository`): the installation that reaches it, the person's /// permission (a token, their login, collaborator and permission), its ID, then its visibility and licence -/// (`open_source::refresh`: a token, its path by ID, the repository, and its licence file when GitHub can't name the +/// (`open_source::refresh`: a token, the repository by its ID, and its licence file when GitHub can't name the /// licence). Eleven at most, when the installation token isn't cached between the two. pub const LINK_BUDGET: u32 = 11; diff --git a/app/src/forge/github_app.rs b/app/src/forge/github_app.rs index b70af2d6e..194d20d9f 100644 --- a/app/src/forge/github_app.rs +++ b/app/src/forge/github_app.rs @@ -54,12 +54,44 @@ async fn get(token: &str, path: &str) -> laravel::Result> { if response.status() == 401 { token_refused(token).await; } + if rate_limit_answer(&response) { + return Err(rate_limit_error(&format!("GET {path}"), &response)); + } if !response.successful() { return Err(err(format!("GET {path}: HTTP {}", response.status()))); } Ok(Some(response.json()?)) } +/// What [`rate_limited`] looks for in an error made from a rate-limit answer. +const RATE_LIMIT_ANSWER: &str = "GitHub's rate limit answered"; + +/// Whether GitHub's answer is its rate limit, primary or secondary: a 429, or a 403 with no calls left, a +/// `retry-after`, or a message naming a rate limit. Such an answer says nothing about access. +fn rate_limit_answer(response: &client::Response) -> bool { + response.status() == 429 + || (response.status() == 403 + && (response.header("x-ratelimit-remaining") == Some("0") + || response.header("retry-after").is_some() + || response.text().to_ascii_lowercase().contains("rate limit"))) +} + +/// The error for a rate-limit answer, which [`rate_limited`] recognises so the sync defers instead of failing. +fn rate_limit_error(what: &str, response: &client::Response) -> laravel::Error { + err(format!("{what}: HTTP {}, {RATE_LIMIT_ANSWER}", response.status())) +} + +/// Whether a 403 says the installation can't read the resource ("Resource not accessible by integration"), and isn't +/// a rate limit. Any other 403 (no message, or another reason) isn't taken as "can't see it". +fn not_accessible(response: &client::Response) -> bool { + response.status() == 403 + && !rate_limit_answer(response) + && response + .json::() + .ok() + .is_some_and(|body| body["message"].as_str() == Some("Resource not accessible by integration")) +} + /// How long before GitHub's expiry a cached installation token stops being used. const TOKEN_MARGIN_SECONDS: i64 = 300; @@ -95,6 +127,9 @@ pub async fn installation_token(app: &GithubApp, installation: &str) -> laravel: .header("accept", "application/vnd.github+json") .header("user-agent", "visualci") .await?; + if rate_limit_answer(&response) { + return Err(rate_limit_error("installation token", &response)); + } if !response.successful() { return Err(err(format!("installation token: HTTP {}", response.status()))); } @@ -271,17 +306,49 @@ pub fn configured(app: &GithubApp) -> bool { /// Below this many API calls left in the hour, a recheck stops instead of using up what webhooks and checks need. pub const RATE_LIMIT_RESERVE: i64 = 500; -/// Every collaborator on a repository (`owner/name`) with their permission, keyed by GitHub user ID: direct +/// Where GitHub's API serves a repository: `/repositories/{id}` by its permanent ID when it's known, else +/// `/repos/{owner}/{name}`. A renamed or transferred repository, or one whose organization was renamed, keeps its ID, +/// and GitHub answers its old name with a 301. This module's client follows redirects (its reads would survive one), +/// but checks and PR comments go through the `outbound` client, which refuses them, so those writes to a stale name +/// fail. The ID never goes stale. (5 Dec 2026: the +/// `visualci-com` organization became `visualcihq`.) +#[must_use] +pub fn repo_api(id: Option<&str>, path: &str) -> String { + match numeric(id) { + Some(id) => format!("/repositories/{id}"), + None => format!("/repos/{path}"), + } +} + +/// A linked project's repository at [`repo_api`], from its stored ID and URL (`None` with neither). +#[must_use] +pub fn linked_repo_api(id: Option<&str>, url: Option<&str>) -> Option { + match numeric(id) { + Some(id) => Some(format!("/repositories/{id}")), + None => url.and_then(super::Repository::parse).map(|r| format!("/repos/{}", r.path)), + } +} + +/// A GitHub ID: digits only. +fn numeric(id: Option<&str>) -> Option<&str> { + id.filter(|id| !id.is_empty() && id.bytes().all(|b| b.is_ascii_digit())) +} + +/// Every collaborator on a repository (at [`repo_api`]) with their permission, keyed by GitHub user ID: direct /// collaborators, team members and organization members with access, as `affiliation=all` lists them. Public -/// visibility gives nobody a place on it. `Err` when it can't be read completely (a partial list would drop people); -/// also when GitHub's rate limit is down to [`RATE_LIMIT_RESERVE`]. +/// visibility gives nobody a place on it. `None` when GitHub answers 404, or 403 "Resource not accessible by +/// integration": the installation can't read it (a public repository transferred to an account the installation +/// doesn't cover still answers `GET /repositories/{id}`, but not this), so the caller treats the repository as unseen. +/// `Err` when it can't be read completely (a partial list would drop people); also when GitHub's rate limit is down to +/// [`RATE_LIMIT_RESERVE`] or answers instead (a 429, or a primary or secondary limit's 403), which [`rate_limited`] +/// recognises, and on any other 403. /// /// # Errors /// Those. -pub async fn collaborators(token: &str, repo: &str) -> laravel::Result> { +pub async fn collaborators(token: &str, repo: &str) -> laravel::Result>> { let mut out = Vec::new(); for page in 1..=50 { - let response = client::get(format!("{}/repos/{repo}/collaborators", api())) + let response = client::get(format!("{}{repo}/collaborators", api())) .token(token) .header("accept", "application/vnd.github+json") .header("user-agent", "visualci") @@ -290,10 +357,18 @@ pub async fn collaborators(token: &str, repo: &str) -> laravel::Result().ok()); + // Not readable by this installation: only a 404, or a 403 that says so. A rate limit (403 or 429, primary or + // secondary) or any other 403 is an error, so the sync defers or fails instead of unlinking anyone + if response.status() == 404 || not_accessible(&response) { + return Ok(None); + } + if rate_limit_answer(&response) { + return Err(rate_limit_error(&format!("GET {repo}/collaborators"), &response)); + } if !response.successful() { - return Err(err(format!("GET /repos/{repo}/collaborators: HTTP {}", response.status()))); + return Err(err(format!("GET {repo}/collaborators: HTTP {}", response.status()))); } - let remaining = response.header("x-ratelimit-remaining").and_then(|v| v.parse::().ok()); let list: Vec = response.json()?; let done = list.len() < 100; for c in &list { @@ -309,7 +384,7 @@ pub async fn collaborators(token: &str, repo: &str) -> laravel::Result laravel::Result laravel::Result> { - get(token, &format!("/repos/{repo}")).await + get(token, repo).await } -/// A repository's licence file as GitHub finds it (`GET /repos/{repo}/license`): its path and text. `None` when it -/// has none GitHub found. GitHub returns the file even when it can't name the licence (`NOASSERTION`). +/// A repository's licence file as GitHub finds it (`GET {repo}/license`, the repository at [`repo_api`]): its path and +/// text. `None` when it has none GitHub found. GitHub returns the file even when it can't name the licence +/// (`NOASSERTION`). /// /// # Errors /// When GitHub can't be reached or refuses. pub async fn licence_file(token: &str, repo: &str) -> laravel::Result> { use base64::Engine; - let Some(answer) = get(token, &format!("/repos/{repo}/license")).await? else { return Ok(None) }; + let Some(answer) = get(token, &format!("{repo}/license")).await? else { return Ok(None) }; let (Some(path), Some(content)) = (answer["path"].as_str(), answer["content"].as_str()) else { return Ok(None) }; let bytes = base64::engine::general_purpose::STANDARD .decode(content.split_whitespace().collect::()) - .map_err(|e| err(format!("GET /repos/{repo}/license: {e}")))?; + .map_err(|e| err(format!("GET {repo}/license: {e}")))?; Ok(Some((path.to_string(), String::from_utf8_lossy(&bytes).into_owned()))) } -/// Whether a branch exists in a repository (`None` when the installation can't see the repository). +/// Whether a branch exists in a repository (at [`repo_api`]; `None` when the installation can't see the repository). /// /// # Errors /// When GitHub can't be reached or refuses. pub async fn branch_exists(token: &str, repo: &str, branch: &str) -> laravel::Result> { - if get(token, &format!("/repos/{repo}")).await?.is_none() { + if get(token, repo).await?.is_none() { return Ok(None); } let branch: String = branch @@ -382,7 +458,7 @@ pub async fn branch_exists(token: &str, repo: &str, branch: &str) -> laravel::Re } }) .collect(); - Ok(Some(get(token, &format!("/repos/{repo}/branches/{branch}")).await?.is_some())) + Ok(Some(get(token, &format!("{repo}/branches/{branch}")).await?.is_some())) } /// A repository's permanent ID, by its path (`None` when the installation can't see it). @@ -393,10 +469,12 @@ pub async fn repository_id(token: &str, repo: &str) -> laravel::Result bool { - e.to_string().contains("the rate limit is down") + let e = e.to_string(); + e.contains("the rate limit is down") || e.contains(RATE_LIMIT_ANSWER) } /// GitHub's role name for a collaborator (`admin`, `maintain`, `write`, `triage`, `read`). diff --git a/app/src/forge/installations.rs b/app/src/forge/installations.rs index 6020b8077..fbadda9aa 100644 --- a/app/src/forge/installations.rs +++ b/app/src/forge/installations.rs @@ -273,7 +273,8 @@ async fn role_in(organization_id: i64, user_id: i64) -> laravel::Result laravel::Result { let Some(id) = event["installation"]["id"].as_i64().map(|i| i.to_string()) else { return Ok(Value::Null) }; match (kind, action) { ("installation", "created" | "unsuspend" | "new_permissions_accepted") => { - let Some(found) = super::github::installation_account(id.clone(), &event["installation"]["account"]) else { + // A login that isn't one (`read_event` checks a rename's the same way) isn't stored: it goes into URLs + let Some(found) = super::github::installation_account(id.clone(), &event["installation"]["account"]) + .filter(|found| super::webhooks::login(&found.account_login)) + else { return Ok(Value::Null); }; upsert(&found).await?; diff --git a/app/src/forge/mod.rs b/app/src/forge/mod.rs index b816a1e8c..380e2fc00 100644 --- a/app/src/forge/mod.rs +++ b/app/src/forge/mod.rs @@ -257,6 +257,13 @@ impl Repository { Some(Self { forge: ForgeKind::Gitlab, url: format!("{scheme}://{host}/{path}"), path, id: None }) } + /// Where GitHub's API serves it: by its permanent ID when known, so a renamed repository or organization doesn't + /// break the call (`github_app::repo_api`). + #[must_use] + pub fn github_api_path(&self) -> String { + github_app::repo_api(self.id.as_deref(), &self.path) + } + /// The base URL of the site the repository is on: `https://gitlab.example.com`. #[must_use] pub fn site_url(&self) -> &str { diff --git a/app/src/forge/open_source.rs b/app/src/forge/open_source.rs index 3c72ec16a..7e8f1230e 100644 --- a/app/src/forge/open_source.rs +++ b/app/src/forge/open_source.rs @@ -19,7 +19,6 @@ use laravel::db; use laravel::event::{Event, listener}; use serde_json::Value; -use super::Repository; use super::events::RepositoryVisibilityChanged; use super::github_app; use crate::config::GithubApp; @@ -483,14 +482,10 @@ async fn check(app: &GithubApp, p: &Project) -> Option { let answer = async { let token = github_app::installation_token(app, installation).await?; // By GitHub's ID when known, so a rename can't mislead it - let path = match p.repository_id.as_deref() { - Some(id) => github_app::repository_path(&token, id).await?, - None => Repository::parse(url).map(|r| r.path), - }; - let Some(path) = path else { return Ok(None) }; - let Some(repo) = github_app::repository(&token, &path).await? else { return Ok(None) }; + let Some(repo_api) = github_app::linked_repo_api(p.repository_id.as_deref(), Some(url)) else { return Ok(None) }; + let Some(repo) = github_app::repository(&token, &repo_api).await? else { return Ok(None) }; let file = if needs_file(&repo) { - github_app::licence_file(&token, &path).await?.map(|(path, text)| LicenceFile { path, text }) + github_app::licence_file(&token, &repo_api).await?.map(|(path, text)| LicenceFile { path, text }) } else { None }; diff --git a/app/src/forge/report.rs b/app/src/forge/report.rs index 5d716c9de..b341dbdf7 100644 --- a/app/src/forge/report.rs +++ b/app/src/forge/report.rs @@ -173,7 +173,8 @@ pub fn github_check_run(check: &Check) -> Value { } /// 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). +/// commit, so its "ID" is the status's name). GitHub's repository is addressed by its ID when known +/// ([`Repository::github_api_path`]), so a renamed repository or organization still gets its checks. /// /// # Errors /// When the forge refuses it. @@ -187,9 +188,10 @@ pub async fn report_check( match target { Target::Github { app, installation } => { let token = github_app::installation_token(app, installation).await?; + let repo = repository.github_api_path(); let request = match existing { - Some(id) => client::patch(format!("{}/repos/{path}/check-runs/{id}", github())), - None => client::post(format!("{}/repos/{path}/check-runs", github())), + Some(id) => client::patch(format!("{}{repo}/check-runs/{id}", github())), + None => client::post(format!("{}{repo}/check-runs", github())), }; let request = request.token(&token).header("accept", "application/vnd.github+json").header("user-agent", "visualci"); @@ -231,7 +233,7 @@ pub async fn report_check( } /// 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. +/// made again). Returns the comment's ID. On GitHub, by the repository's ID when known, as [`report_check`]. /// /// # Errors /// When the forge refuses it. @@ -246,8 +248,8 @@ pub async fn upsert_comment( let (token, comments, one, what) = match target { Target::Github { app, installation } => ( github_app::installation_token(app, installation).await?, - format!("{}/repos/{path}/issues/{pr_number}/comments", github()), - format!("{}/repos/{path}/issues/comments", github()), + format!("{}{}/issues/{pr_number}/comments", github(), repository.github_api_path()), + format!("{}{}/issues/comments", github(), repository.github_api_path()), "GitHub PR comment", ), Target::Gitlab { base, token } => { diff --git a/app/src/forge/sync.rs b/app/src/forge/sync.rs index ed98649e7..5efdad4ae 100644 --- a/app/src/forge/sync.rs +++ b/app/src/forge/sync.rs @@ -1,6 +1,8 @@ //! The hourly forge sync (sc-8900, the forge side), ported from today's `forge:sync` for GitHub: //! //! - links made before VisualCI stored GitHub's repository ID get it; +//! - links follow their repository's name by that ID, so a rename whose webhook was missed (an organization's rename +//! sends none per repository) is followed within the hour ([`follow_renames`]); //! - every linked repository's collaborators are listed once ([`webhooks::reach`]) and everyone with a GitHub identity //! is rechecked from that, so access lost without a webhook goes within the hour; //! - a project whose linker no longer maintains its repository (or whose repository the App can't see) is unlinked, so @@ -27,6 +29,9 @@ use crate::config::GithubApp; pub struct Synced { pub people: usize, pub changed: usize, + /// Links whose repository was renamed or transferred (or its organization renamed) without a webhook saying so, + /// given its URL now. + pub renamed: usize, pub unlinked: usize, /// Projects made private, or no longer open source, by the daily recheck. pub open_source: usize, @@ -59,6 +64,7 @@ pub async fn sync_github(app: &GithubApp) -> laravel::Result { .iter() .map(|r| r.try_get("user_id")) .collect::>()?; + let renamed = follow_renames(&reach).await?; let changed = webhooks::apply_reach(&reach, &people).await?; db::query!("DELETE FROM access_rechecks WHERE queued_at <= {started}::timestamptz").delete().await?; let unlinked = recheck_links(&reach, &unseen).await?; @@ -73,7 +79,7 @@ pub async fn sync_github(app: &GithubApp) -> laravel::Result { Err(e) if github_app::rate_limited(&e) => 0, Err(e) => return Err(e), }; - Ok(Synced { people: people.len(), changed, unlinked, open_source, branches_closed, deferred: false }) + Ok(Synced { people: people.len(), changed, renamed, unlinked, open_source, branches_closed, deferred: false }) } /// Give links without GitHub's repository ID their ID. Returns the projects whose repository the App can't see. @@ -103,6 +109,56 @@ async fn backfill_ids(app: &GithubApp) -> laravel::Result> { Ok(unseen) } +/// Give links the URL their repository has now, by GitHub's ID ([`Reach::paths`]): a repository renamed or transferred, +/// or an organization renamed (which sends no per-repository `renamed` delivery), whose webhook was missed. Only links +/// through the installation that read it, and only where that installation could list its collaborators, so a project +/// is never pointed at an owner its installation doesn't cover. A URL is replaced only if it's still the one read before +/// GitHub was asked ([`Reach::links`]): a webhook that moved it meanwhile knows a newer name than this run read. The +/// repository picker's cached names follow too. Returns how many projects changed. +/// +/// # Errors +/// On a database error. +pub async fn follow_renames(reach: &Reach) -> laravel::Result { + let list: Vec = reach + .links + .iter() + .filter_map(|l| { + let path = reach.paths.get(&(l.repository_id.clone(), l.installation.clone()))?; + Some(serde_json::json!({ + "project": l.project_id, "url": l.url, "id": l.repository_id, "installation": l.installation, + "path": path, + })) + }) + .collect(); + if list.is_empty() { + return Ok(0); + } + let list = serde_json::Value::Array(list).to_string(); + // A GitHub project's URL is always on github.com: `Repository::parse` gives `forge = 'github'` only to github.com + // (another `GITHUB_URL` is for testing and local only, `forge::check_github`), so the host is fixed here. The + // picker's cache is updated in a data-modifying CTE, which Postgres runs whether or not the outer query reads it. + let rows = db::query!( + "WITH r AS (SELECT * FROM jsonb_to_recordset({list}::jsonb) \ + AS x(project bigint, url text, id text, installation text, path text)), \ + picker AS (UPDATE user_repositories u SET full_name = n.path \ + FROM (SELECT DISTINCT id, installation, path FROM r) n \ + WHERE u.repository_id = n.id AND u.installation_id = n.installation AND u.full_name <> n.path) \ + UPDATE projects p SET repository_url = 'https://github.com/' || r.path, updated_at = now() FROM r \ + WHERE p.id = r.project AND p.forge = 'github' AND p.repository_id = r.id \ + AND p.forge_installation = r.installation AND p.deleted_at IS NULL \ + AND p.repository_url IS NOT DISTINCT FROM r.url \ + AND p.repository_url IS DISTINCT FROM 'https://github.com/' || r.path \ + RETURNING p.id, p.repository_url" + ) + .select() + .await?; + for r in &rows { + let (id, url): (i64, String) = (r.try_get("id")?, r.try_get("repository_url")?); + tracing::info!(project_id = id, url, "its repository was renamed: following it"); + } + Ok(rows.len()) +} + /// Unlink projects whose linker no longer has Maintain or Admin on the repository, or whose repository the App can't /// see. Returns how many. async fn recheck_links(reach: &Reach, unseen: &[i64]) -> laravel::Result { @@ -173,11 +229,8 @@ pub async fn close_deleted_branches(app: &GithubApp, limit: i64) -> laravel::Res t } }; - let path = match repository_id.as_deref() { - Some(id) => github_app::repository_path(&token, id).await?, - None => url.as_deref().and_then(super::Repository::parse).map(|r| r.path), - }; - let Some(path) = path else { continue }; + // By GitHub's ID when known, so a renamed repository or organization is still found + let Some(path) = github_app::linked_repo_api(repository_id.as_deref(), url.as_deref()) else { continue }; match github_app::branch_exists(&token, &path, &branch).await { Ok(Some(false)) => { super::events::BranchClosed { project_id, branch: branch.clone(), why: "branch_deleted".into() } @@ -222,6 +275,7 @@ impl SyncForges { tracing::info!( people = s.people, changed = s.changed, + renamed = s.renamed, unlinked = s.unlinked, open_source = s.open_source, branches_closed = s.branches_closed, diff --git a/app/src/forge/webhooks.rs b/app/src/forge/webhooks.rs index 4af53969e..fe926522e 100644 --- a/app/src/forge/webhooks.rs +++ b/app/src/forge/webhooks.rs @@ -5,6 +5,8 @@ //! the domain as `forge::events`, once per linked project; //! - installation changes attach or detach the App's installation on linked projects, so checks stop without errors, //! and recheck the access of the people whose memberships those organizations' repositories decide; +//! - a renamed or transferred repository, or a renamed account the App is installed on (`installation_target`), moves +//! its links' URLs (links match by GitHub's repository ID; calls to GitHub use it too); //! - membership changes (collaborators, teams, organization members) recheck the people they name ([`RecheckAccess`]); //! - a GitHub Actions run that was cancelled, failed or timed out closes the builds it was still sending. //! @@ -63,9 +65,17 @@ pub enum ForgeEvent { repository: Repository, private: bool, }, - /// Renamed or transferred: the same repository (by ID) at a new URL. + /// Renamed or transferred: the same repository (by ID) at a new URL, for the installation that sent it. Moved { repository: Repository, + installation: String, + }, + /// The account an installation is on was renamed (an `installation_target` delivery, action `renamed`): its + /// repositories' URLs follow. GitHub sends no per-repository `renamed` delivery for an organization's rename. + AccountRenamed { + installation: String, + from: String, + to: String, }, /// A GitHub Actions run ended without succeeding (`cancelled`, `failure` or `timed_out`): builds it was still /// sending are closed at once instead of after the hour the sweep waits. @@ -109,6 +119,11 @@ fn repository(event: &Value) -> Option { .map(|r| r.with_id(event["repository"]["id"].as_i64().map(|i| i.to_string()))) } +/// Whether a string is a GitHub account login (letters, digits and dashes), safe to put in a URL. +pub(crate) fn login(s: &str) -> bool { + !s.is_empty() && s.len() <= 100 && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') +} + /// A pull request's branch: a fork's goes by its head label (`octocat:main`), as the CLI names it, so a fork's `main` /// isn't taken for the base repository's. fn pr_branch(event: &Value) -> Option<&str> { @@ -193,9 +208,21 @@ pub fn read_event(kind: &str, event: &Value) -> Result { }, // The same repository at a new URL; links follow by its ID ("repository", "renamed" | "transferred") => match repository(event) { - Some(repository) if repository.id.is_some() => ForgeEvent::Moved { repository }, + Some(repository) if repository.id.is_some() => match installation { + Some(installation) => ForgeEvent::Moved { repository, installation }, + None => ForgeEvent::Ignored, + }, _ => ForgeEvent::Ignored, }, + // The account the App is installed on was renamed: its repositories have new URLs + ("installation_target", "renamed") => { + match (installation, event["changes"]["login"]["from"].as_str(), event["account"]["login"].as_str()) { + (Some(installation), Some(from), Some(to)) if login(from) && login(to) => { + ForgeEvent::AccountRenamed { installation, from: from.to_string(), to: to.to_string() } + } + _ => ForgeEvent::Ignored, + } + } // A collaborator added, removed or changed; someone joined or left a team ("member" | "membership", _) => ForgeEvent::Access { people: person(&event["member"]) }, // Someone joined or left the organization @@ -908,16 +935,25 @@ pub async fn handle(app: &GithubApp, event: ForgeEvent, claimed: bool) -> larave } json!({ "dispatched": projects.len() }) } - ForgeEvent::Moved { repository } => { + ForgeEvent::Moved { repository, installation } => { + // Only links through the installation that sent it, as the hourly sync: another installation's link to + // the same repository ID may not cover its new owner let (id, url) = (repository.id.clone(), repository.url.clone()); let moved = db::query!( "UPDATE projects SET repository_url = {url}, updated_at = now() \ - WHERE forge = 'github' AND repository_id = {id} AND repository_url IS DISTINCT FROM {url}" + WHERE forge = 'github' AND repository_id = {id} AND forge_installation = {installation} \ + AND repository_url IS DISTINCT FROM {url}" ) .update() .await?; json!({ "moved": moved }) } + ForgeEvent::AccountRenamed { installation, from, to } => { + match account_renamed(app, &installation, &from, &to).await? { + Some(moved) => json!({ "moved": moved, "installation": "renamed" }), + None => json!({ "moved": 0, "installation": "stale" }), + } + } ForgeEvent::Installation { installation, previous, repositories } => { let mut changes = Vec::new(); for p in linked_any(&repositories).await? { @@ -987,6 +1023,69 @@ pub async fn handle(app: &GithubApp, event: ForgeEvent, claimed: bool) -> larave }) } +/// The account an installation is on was renamed from `from` to `to`: the installation's login, its linked projects' +/// URLs under the old login (any case) and the repository picker's cached names move to the new one. Links match by +/// repository ID, so this only keeps URLs, checks' paths and what people see current; the hourly sync would follow it +/// too ([`super::sync`]). Returns how many projects moved, or `None` for a stale delivery, which changes nothing. +/// +/// A delivery can arrive late (the recovery job redelivers missed ones), after a newer rename: a late `acme→beta` after +/// `beta→acme` would move everything back to `beta`, and its logins can't tell it from a new rename. So GitHub is asked +/// what the account is called now (one call), and only a rename to that name is applied. Once GitHub has confirmed it, +/// the installation's login becomes GitHub's, whatever VisualCI had stored, and URLs move from both `from` and the +/// login VisualCI had: after quick renames (`acme→beta→gamma`, both delivered once GitHub says `gamma`, so the first is +/// ignored as stale) or a lost delivery, VisualCI still reads `acme` while this delivery says `beta`. +/// +/// # Errors +/// When GitHub can't be asked (the delivery fails, so it's redelivered), or on a database error. +pub async fn account_renamed( + app: &GithubApp, + installation: &str, + from: &str, + to: &str, +) -> laravel::Result> { + let now = github_app::installation(app, installation).await?; + let Some(current) = now + .as_ref() + .and_then(|i| i["account"]["login"].as_str()) + .filter(|c| c.eq_ignore_ascii_case(to) && login(c)) + .map(str::to_string) + else { + tracing::info!(installation, from, to, "a stale installation_target rename: ignored"); + return Ok(None); + }; + let id = installation.to_string(); + let from = from.to_lowercase(); + let stored: Option = + db::query!("SELECT account_login FROM github_installations WHERE installation_id = {id}").scalar().await?; + // The login VisualCI had, when there's a row: its URLs are under it if a delivery before this one was missed + let old = stored.map_or_else(|| from.clone(), |l| l.to_lowercase()); + db::query!( + "UPDATE github_installations SET account_login = {current}, updated_at = now() \ + WHERE installation_id = {id} AND account_login IS DISTINCT FROM {current}" + ) + .update() + .await?; + let moved = db::query!( + "UPDATE projects \ + SET repository_url = 'https://github.com/' || {current} || '/' || split_part(repository_url, '/', 5), \ + updated_at = now() \ + WHERE forge = 'github' AND forge_installation = {id} AND deleted_at IS NULL \ + AND split_part(repository_url, '/', 3) = 'github.com' \ + AND lower(split_part(repository_url, '/', 4)) IN ({from}, {old}) \ + AND split_part(repository_url, '/', 4) <> {current}" + ) + .update() + .await?; + db::query!( + "UPDATE user_repositories SET full_name = {current} || '/' || split_part(full_name, '/', 2) \ + WHERE installation_id = {id} AND lower(split_part(full_name, '/', 1)) IN ({from}, {old}) \ + AND split_part(full_name, '/', 1) <> {current}" + ) + .update() + .await?; + Ok(Some(moved)) +} + /// Recheck everyone whose membership in these organizations GitHub decides. async fn recheck_organizations(orgs: Vec) -> laravel::Result<()> { let mut users = HashSet::new(); @@ -1065,27 +1164,53 @@ pub struct Reach { pub people: HashMap>, /// GitHub repository ID -> GitHub user ID -> permission. A repository the App can't see any more has no entry. pub repositories: HashMap>, + /// (GitHub repository ID, installation) -> its `owner/name` now, which the hourly sync gives that installation's + /// links whose URL went stale. Only repositories whose collaborators the installation could list. + pub paths: HashMap<(String, String), String>, + /// Every linked project as it was read before GitHub was asked. + pub links: Vec, +} + +/// A linked project's repository, installation and URL when [`reach`] read them. +#[derive(Debug)] +pub struct Link { + pub project_id: i64, + pub repository_id: String, + pub installation: String, + pub url: Option, } /// List every linked repository's collaborators once: one installation token per installation, each repository's -/// path looked up by GitHub's ID so a rename can't mislead it. A repository the installation can't see any more -/// gives nobody anything. +/// path looked up by GitHub's ID so a rename can't mislead it. A repository the installation can't see any more, or +/// whose collaborators it can't list (403 or 404), gives nobody anything. /// /// # Errors /// When GitHub can't answer for some repository (a partial answer would drop people), when its rate limit is low, or /// on a database error. pub async fn reach(app: &GithubApp) -> laravel::Result { + // Each link's URL as it is before GitHub is asked, so the sync only replaces a URL nothing changed meanwhile let rows = db::query!( - "SELECT DISTINCT repository_id, forge_installation FROM projects \ - WHERE forge = 'github' AND repository_id IS NOT NULL AND forge_installation IS NOT NULL AND deleted_at IS NULL" + "SELECT id, repository_id, forge_installation, repository_url FROM projects \ + WHERE forge = 'github' AND repository_id IS NOT NULL AND forge_installation IS NOT NULL AND deleted_at IS NULL \ + ORDER BY repository_id, forge_installation, id" ) .select() .await?; let mut tokens: HashMap = HashMap::new(); let mut reach = Reach::default(); + let mut asked = HashSet::new(); for r in rows { let (repository_id, installation): (String, String) = (r.try_get("repository_id")?, r.try_get("forge_installation")?); + reach.links.push(Link { + project_id: r.try_get("id")?, + repository_id: repository_id.clone(), + installation: installation.clone(), + url: r.try_get("repository_url")?, + }); + if !asked.insert((repository_id.clone(), installation.clone())) { + continue; + } let token = match tokens.get(&installation) { Some(t) => t.clone(), None => { @@ -1097,8 +1222,16 @@ pub async fn reach(app: &GithubApp) -> laravel::Result { let Some(path) = github_app::repository_path(&token, &repository_id).await? else { continue }; let Some(repository) = Repository::parse(&path) else { continue }; let repository = repository.with_id(Some(repository_id.clone())); + // A repository this installation can read the name of but not the collaborators (a public one transferred to + // an account it doesn't cover) is unseen: its links are unlinked, and its new path isn't followed, so no + // project is pointed at an owner its installation doesn't cover + let Some(collaborators) = github_app::collaborators(&token, &repository.github_api_path()).await? else { + tracing::info!(repository_id, installation, "the installation can't list its collaborators: unseen"); + continue; + }; + reach.paths.insert((repository_id.clone(), installation), path); let people = reach.repositories.entry(repository_id).or_default(); - for (person, permission) in github_app::collaborators(&token, &path).await? { + for (person, permission) in collaborators { people.insert(person.clone(), permission); reach.people.entry(person).or_default().push((repository.clone(), permission)); } diff --git a/app/tests/forge_reports.rs b/app/tests/forge_reports.rs index 34cefb6a1..bf797312b 100644 --- a/app/tests/forge_reports.rs +++ b/app/tests/forge_reports.rs @@ -194,14 +194,14 @@ fn github_check_run_problem(body: &serde_json::Value) -> Option { 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", |request: &client::Request| { + .with("api.github.com/repositories/42/check-runs", |request: &client::Request| { let body: serde_json::Value = request.json().unwrap_or_default(); match github_check_run_problem(&body) { Some(problem) => client::response().status(422).json(json!({ "message": problem })), None => client::response().json(json!({ "id": 900 })), } }) - .with("api.github.com/repos/acme/web/issues/5/comments", json!({ "id": 700 })) + .with("api.github.com/repositories/42/issues/5/comments", json!({ "id": 700 })) } #[laravel::test(app = github_app)] @@ -232,6 +232,91 @@ async fn a_changed_build_gets_a_waiting_check_and_a_comment(_app: Application) - Ok(()) } +/// GitHub's permanent repository ID addresses the repository, so a repository or organization renamed since it was +/// linked (its stored URL stale, which GitHub answers with a redirect VisualCI doesn't follow) still gets its check and +/// comment. (5 Dec 2026: the `visualci-com` organization became `visualcihq`.) +#[laravel::test(app = github_app)] +async fn a_renamed_repository_still_gets_its_check_and_comment(_app: Application) -> laravel::Result<()> { + let build = linked_build(counts(1, 2)).await?; + let project_id = build.project_id; + db::query!("UPDATE projects SET repository_url = 'https://github.com/old-org/web' WHERE id = {project_id}") + .update() + .await?; + let github = github() + .with("api.github.com/repositories/42/issues/5/comments?*", json!([])) + .with("api.github.com/repos/*", client::response().status(301).json(json!({ "message": "Moved Permanently" }))) + .prevent_stray_requests(); + BuildChanged { build_id: build.id }.dispatch().await?; + + let sent = github.sent(); + let urls: Vec<&str> = sent.iter().map(|r| r.url()).collect(); + assert!(urls.contains(&"https://api.github.com/repositories/42/check-runs"), "{urls:?}"); + assert!(urls.contains(&"https://api.github.com/repositories/42/issues/5/comments"), "{urls:?}"); + assert!(!urls.iter().any(|u| u.contains("/repos/")), "nothing by the stale name: {urls:?}"); + 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")); + Ok(()) +} + +/// The check and comment posted before a rename are updated after it by the repository's ID too: the check run is +/// PATCHed (`forge_check_id` set) and the comment edited at `/repositories/42/...`, never at the stale name. +#[laravel::test(app = github_app)] +async fn after_a_rename_the_existing_check_and_comment_are_edited_by_id(_app: Application) -> laravel::Result<()> { + let build = linked_build(counts(1, 2)).await?; + let first = github().with("api.github.com/repositories/42/issues/5/comments?*", json!([])); + BuildChanged { build_id: build.id }.dispatch().await?; + drop(first); + let (build_id, project_id) = (build.id, build.project_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")); + let comment_id: Option = + db::query!("SELECT forge_comment_id FROM pr_comments WHERE pr_number = 5").scalar().await?; + assert_eq!(comment_id.as_deref(), Some("700")); + + db::query!("UPDATE projects SET repository_url = 'https://github.com/old-org/web' WHERE id = {project_id}") + .update() + .await?; + db::query!("UPDATE builds SET review_state = 'approved' WHERE id = {build_id}").update().await?; + let github = client::fake() + .with("api.github.com/app/installations/7/access_tokens", json!({ "token": "t" })) + .with("api.github.com/repositories/42/check-runs/900", json!({ "id": 900 })) + .with("api.github.com/repositories/42/issues/comments/700", json!({ "id": 700 })) + .with("api.github.com/repos/*", client::response().status(301).json(json!({ "message": "Moved Permanently" }))) + .prevent_stray_requests(); + BuildChanged { build_id }.dispatch().await?; + + let sent = github.sent(); + let calls: Vec<(String, String)> = sent.iter().map(|r| (r.method().to_string(), r.url().to_string())).collect(); + let patched = |url: &str| calls.iter().any(|(m, u)| m == "PATCH" && u == url); + assert!(patched("https://api.github.com/repositories/42/check-runs/900"), "{calls:?}"); + assert!(patched("https://api.github.com/repositories/42/issues/comments/700"), "{calls:?}"); + assert!(!calls.iter().any(|(_, u)| u.contains("/repos/")), "nothing by the stale name: {calls:?}"); + Ok(()) +} + +/// A link whose repository ID isn't known yet still posts, by its `owner/name`. +#[laravel::test(app = github_app)] +async fn a_link_without_its_repository_id_posts_by_name(_app: Application) -> laravel::Result<()> { + let build = linked_build(counts(1, 2)).await?; + let project_id = build.project_id; + db::query!("UPDATE projects SET repository_id = NULL WHERE id = {project_id}").update().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", json!({ "id": 900 })) + .with("api.github.com/repos/acme/web/issues/5/comments?*", json!([])) + .with("api.github.com/repos/acme/web/issues/5/comments", json!({ "id": 700 })) + .prevent_stray_requests(); + BuildChanged { build_id: build.id }.dispatch().await?; + + let urls: Vec = github.sent().iter().map(|r| r.url().to_string()).collect(); + assert!(urls.iter().any(|u| u == "https://api.github.com/repos/acme/web/check-runs"), "{urls:?}"); + assert!(urls.iter().any(|u| u == "https://api.github.com/repos/acme/web/issues/5/comments"), "{urls:?}"); + 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?; @@ -280,16 +365,16 @@ async fn a_retry_edits_the_comment_already_posted(_app: Application) -> laravel: 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/repositories/42/check-runs", json!({ "id": 900 })) .with( - "api.github.com/repos/acme/web/issues/5/comments?*", + "api.github.com/repositories/42/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 })); + .with("api.github.com/repositories/42/issues/comments/701", json!({ "id": 701 })) + .with("api.github.com/repositories/42/issues/5/comments", json!({ "id": 702 })); BuildChanged { build_id: build.id }.dispatch().await?; let sent = github.sent(); @@ -328,8 +413,8 @@ async fn a_rate_limit_is_waited_out(_app: Application) -> laravel::Result<()> { 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)); + .with("api.github.com/repositories/42/check-runs", client::response().status(429).header("retry-after", "5")) + .with("api.github.com/repositories/42/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)); @@ -403,9 +488,9 @@ async fn deleting_a_project_clears_its_pull_requests_check_and_edits_its_comment 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": 901 })) - .with("api.github.com/repos/acme/web/issues/comments/700", json!({ "id": 700 })) - .with("api.github.com/repos/acme/web/issues/5/comments*", json!([])); + .with("api.github.com/repositories/42/check-runs/*", json!({ "id": 901 })) + .with("api.github.com/repositories/42/issues/comments/700", json!({ "id": 700 })) + .with("api.github.com/repositories/42/issues/5/comments*", json!([])); let admin = create!(User { pid: laravel::str::uuid7(), name: "Admin", email: "admin@example.com", staff: false }).await?; app::domain::project_deletion::delete(&project, &admin).await?; diff --git a/app/tests/forge_sync.rs b/app/tests/forge_sync.rs index e872b6b9b..6d351dd6d 100644 --- a/app/tests/forge_sync.rs +++ b/app/tests/forge_sync.rs @@ -38,7 +38,7 @@ async fn access_github_no_longer_grants_goes_within_the_hour(_app: Application) let app = GithubApp { app_id: Some("1".into()), private_key_base64: None, webhook_secret: None }; assert_eq!( sync_github(&app).await?, - Synced { people: 1, changed: 1, unlinked: 0, open_source: 0, branches_closed: 0, deferred: false } + Synced { people: 1, changed: 1, renamed: 0, unlinked: 0, open_source: 0, branches_closed: 0, deferred: false } ); let left: Vec = db::query!("SELECT organization_id FROM memberships WHERE user_id = {ada_id}") .select() @@ -92,7 +92,7 @@ async fn a_link_whose_linker_lost_maintain_is_removed(_app: Application) -> lara let _github = laravel::http::client::fake() .with("api.github.com/app/installations/7/access_tokens", json!({ "token": "t" })) .with("api.github.com/repositories/42", json!({ "full_name": "acme/web" })) - .with("api.github.com/repos/acme/web/collaborators*", json!([{ "id": 1001, "role_name": "write" }])); + .with("api.github.com/repositories/42/collaborators*", json!([{ "id": 1001, "role_name": "write" }])); let app = GithubApp { app_id: Some("1".into()), private_key_base64: Some(app_key().into()), webhook_secret: None }; let synced = sync_github(&app).await?; assert_eq!(synced.unlinked, 1); @@ -184,10 +184,13 @@ async fn a_deleted_branchs_waiting_builds_are_closed(_app: Application) -> larav let events = laravel::event::fake(); let _github = laravel::http::client::fake() .with("api.github.com/app/installations/7/access_tokens", json!({ "token": "t" })) - .with("api.github.com/repositories/42", json!({ "full_name": "acme/web" })) - .with("api.github.com/repos/acme/web/branches/still-here", json!({ "name": "still-here" })) - .with("api.github.com/repos/acme/web/branches/*", laravel::http::client::response().status(404).json(json!({}))) - .with("api.github.com/repos/acme/web", json!({ "id": 42 })); + .with("api.github.com/repositories/42/branches/still-here", json!({ "name": "still-here" })) + .with( + "api.github.com/repositories/42/branches/*", + laravel::http::client::response().status(404).json(json!({})), + ) + .with("api.github.com/repositories/42", json!({ "id": 42, "full_name": "acme/web" })) + .prevent_stray_requests(); let app = GithubApp { app_id: Some("1".into()), private_key_base64: Some(app_key().into()), webhook_secret: None }; assert_eq!(app::forge::sync::close_deleted_branches(&app, 500).await?, 1); events.assert_dispatched_where::(|e| { @@ -198,3 +201,254 @@ async fn a_deleted_branchs_waiting_builds_are_closed(_app: Application) -> larav assert_eq!(app::forge::sync::close_deleted_branches(&app, 500).await?, 0); Ok(()) } + +/// A repository renamed, or its organization renamed, without a webhook VisualCI acted on (an organization's rename +/// sends no per-repository delivery): the hourly sync reads each linked repository's name by GitHub's ID anyway, and +/// gives the projects linked to it, and the repository picker's cached name, the name it has now. +#[laravel::test] +async fn a_renamed_repository_is_followed_within_the_hour(_app: Application) -> laravel::Result<()> { + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let ada_id = ada.id; + let org: i64 = db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) \ + VALUES (gen_random_uuid(), 'acme', 'Acme', now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + let mut projects = Vec::new(); + for (slug, url, repository_id) in [ + ("web", "https://github.com/old-org/web", "42"), + ("docs", "https://github.com/old-org/docs", "43"), + ("site", "https://github.com/acme/site", "44"), + ] { + let id: i64 = db::query!( + "INSERT INTO projects (pid, organization_id, slug, name, forge, repository_url, repository_id, \ + forge_installation, created_at, updated_at) \ + VALUES (gen_random_uuid(), {org}, {slug}, {slug}, 'github', {url}, {repository_id}, '7', now(), now()) \ + RETURNING id" + ) + .scalar() + .await? + .unwrap(); + projects.push(id); + } + db::query!( + "INSERT INTO github_installations (installation_id, account_id, account_login, account_type) \ + VALUES ('7', '5005', 'acme', 'Organization')" + ) + .insert() + .await?; + db::query!( + "INSERT INTO user_repositories (user_id, installation_id, repository_id, full_name, permission) \ + VALUES ({ada_id}, '7', '42', 'old-org/web', 'admin')" + ) + .insert() + .await?; + let _github = laravel::http::client::fake() + .with("api.github.com/app/installations/7/access_tokens", json!({ "token": "t" })) + .with("api.github.com/repositories/42/collaborators*", json!([])) + .with("api.github.com/repositories/43/collaborators*", json!([])) + .with("api.github.com/repositories/44/collaborators*", json!([])) + .with("api.github.com/repositories/42", json!({ "id": 42, "full_name": "acme/web" })) + // Renamed within the organization too + .with("api.github.com/repositories/43", json!({ "id": 43, "full_name": "acme/handbook" })) + .with("api.github.com/repositories/44", json!({ "id": 44, "full_name": "acme/site" })) + .with("api.github.com/repos/*", laravel::http::client::response().status(301).json(json!({}))) + .prevent_stray_requests(); + let app = GithubApp { app_id: Some("1".into()), private_key_base64: Some(app_key().into()), webhook_secret: None }; + let synced = sync_github(&app).await?; + assert_eq!(synced.renamed, 2, "{synced:?}"); + let mut urls = Vec::new(); + for &id in &projects { + let url: Option = db::query!("SELECT repository_url FROM projects WHERE id = {id}").scalar().await?; + urls.push(url.unwrap_or_default()); + } + assert_eq!( + urls, + ["https://github.com/acme/web", "https://github.com/acme/handbook", "https://github.com/acme/site"] + ); + let name: Option = + db::query!("SELECT full_name FROM user_repositories WHERE user_id = {ada_id}").scalar().await?; + assert_eq!(name.as_deref(), Some("acme/web")); + // Already current: the next run changes nothing + assert_eq!(sync_github(&app).await?.renamed, 0); + Ok(()) +} + +/// A project linked to GitHub repository `repository_id` through installation 7 (or a GitLab one), by Ada. +async fn project(org: i64, slug: &str, forge: &str, url: &str, repository_id: &str) -> laravel::Result { + let installation = (forge == "github").then_some("7"); + Ok(db::query!( + "INSERT INTO projects (pid, organization_id, slug, name, forge, repository_url, repository_id, \ + forge_installation, created_at, updated_at) \ + VALUES (gen_random_uuid(), {org}, {slug}, {slug}, {forge}, {url}, {repository_id}, {installation}, now(), \ + now()) RETURNING id" + ) + .scalar() + .await? + .unwrap()) +} + +async fn url_of(project: i64) -> laravel::Result { + let url: Option = db::query!("SELECT repository_url FROM projects WHERE id = {project}").scalar().await?; + Ok(url.unwrap_or_default()) +} + +async fn installation_of(project: i64) -> laravel::Result> { + Ok(db::query!("SELECT forge_installation FROM projects WHERE id = {project}") + .scalar::>() + .await? + .flatten()) +} + +/// One repository whose collaborators the installation can't list (a public repository transferred to an account the +/// installation doesn't cover still answers `GET /repositories/{id}`, then 403 for its collaborators) doesn't stop the +/// hourly sync for everyone: it's unseen, so its project is unlinked and not pointed at the new owner, and the other +/// repositories are still followed. A GitLab project with the same numeric ID is GitLab's, untouched; a repository +/// GitHub answers 404 for keeps its URL (and is unlinked as unseen). +#[laravel::test] +async fn a_repository_the_installation_cant_read_doesnt_stop_the_sync(_app: Application) -> laravel::Result<()> { + let org: i64 = db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) \ + VALUES (gen_random_uuid(), 'acme', 'Acme', now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + let transferred = project(org, "lib", "github", "https://github.com/acme/lib", "41").await?; + let renamed = project(org, "web", "github", "https://github.com/old-org/web", "42").await?; + let gone = project(org, "old", "github", "https://github.com/acme/old", "43").await?; + let gitlab = project(org, "gl", "gitlab", "https://gitlab.com/old-org/web", "42").await?; + // Ada linked the transferred one: with its collaborators unreadable, she can't be shown to maintain it + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let ada_id = ada.id; + db::query!( + "INSERT INTO identities (user_id, forge, site, forge_user_id, login, created_at, updated_at) \ + VALUES ({ada_id}, 'github', '', '1001', 'ada', now(), now())" + ) + .insert() + .await?; + db::query!("UPDATE projects SET linked_by = {ada_id} WHERE id = {transferred}").update().await?; + let forbidden = || { + laravel::http::client::response() + .status(403) + .json(json!({ "message": "Resource not accessible by integration" })) + }; + let _github = laravel::http::client::fake() + .with("api.github.com/app/installations/7/access_tokens", json!({ "token": "t" })) + .with("api.github.com/repositories/41/collaborators*", forbidden()) + .with("api.github.com/repositories/42/collaborators*", json!([])) + .with("api.github.com/repositories/41", json!({ "id": 41, "full_name": "someone-else/lib" })) + .with("api.github.com/repositories/42", json!({ "id": 42, "full_name": "acme/web" })) + .with("api.github.com/repositories/43", laravel::http::client::response().status(404).json(json!({}))) + .prevent_stray_requests(); + let app = GithubApp { app_id: Some("1".into()), private_key_base64: Some(app_key().into()), webhook_secret: None }; + let synced = sync_github(&app).await?; + assert_eq!(synced.renamed, 1, "{synced:?}"); + assert_eq!(url_of(renamed).await?, "https://github.com/acme/web"); + assert_eq!(url_of(transferred).await?, "https://github.com/acme/lib", "not pointed at an owner it can't cover"); + assert_eq!(url_of(gone).await?, "https://github.com/acme/old"); + assert_eq!(url_of(gitlab).await?, "https://gitlab.com/old-org/web"); + assert_eq!(installation_of(renamed).await?.as_deref(), Some("7")); + assert_eq!(installation_of(transferred).await?, None, "unlinked as unseen"); + assert_eq!(synced.unlinked, 1, "{synced:?}"); + Ok(()) +} + +/// GitHub's rate limit answering for a repository's collaborators (a secondary limit's 403 with `retry-after`, a +/// primary limit's 403 with no calls left, or a 429) says nothing about access: the run defers, so nobody is unlinked +/// and its heartbeat stays healthy, and the next run tries again. A 403 that doesn't say the installation can't read +/// the repository is an error, never an unlink. +#[laravel::test] +async fn a_rate_limit_answer_defers_the_sync_and_unlinks_nobody(_app: Application) -> laravel::Result<()> { + let org: i64 = db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) \ + VALUES (gen_random_uuid(), 'acme', 'Acme', now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + let web = project(org, "web", "github", "https://github.com/acme/web", "42").await?; + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let ada_id = ada.id; + db::query!( + "INSERT INTO identities (user_id, forge, site, forge_user_id, login, created_at, updated_at) \ + VALUES ({ada_id}, 'github', '', '1001', 'ada', now(), now())" + ) + .insert() + .await?; + db::query!("UPDATE projects SET linked_by = {ada_id} WHERE id = {web}").update().await?; + let app = GithubApp { app_id: Some("1".into()), private_key_base64: Some(app_key().into()), webhook_secret: None }; + let response = || laravel::http::client::response(); + let limits = [ + ( + "secondary", + response() + .status(403) + .header("retry-after", "60") + .header("x-ratelimit-remaining", "4000") + .json(json!({ "message": "You have exceeded a secondary rate limit" })), + ), + ( + "primary", + response() + .status(403) + .header("x-ratelimit-remaining", "0") + .json(json!({ "message": "API rate limit exceeded for installation" })), + ), + ("429", response().status(429).json(json!({}))), + ]; + for (what, answer) in limits { + let _github = laravel::http::client::fake() + .with("api.github.com/app/installations/7/access_tokens", json!({ "token": "t" })) + .with("api.github.com/repositories/42/collaborators*", answer) + .with("api.github.com/repositories/42", json!({ "id": 42, "full_name": "acme/web" })) + .prevent_stray_requests(); + let synced = sync_github(&app).await?; + assert!(synced.deferred, "{what}: {synced:?}"); + assert_eq!(installation_of(web).await?.as_deref(), Some("7"), "{what}: still linked"); + } + // A 403 without a reason: an error the run reports, not an unlink + let _github = laravel::http::client::fake() + .with("api.github.com/app/installations/7/access_tokens", json!({ "token": "t" })) + .with("api.github.com/repositories/42/collaborators*", response().status(403).json(json!({}))) + .with("api.github.com/repositories/42", json!({ "id": 42, "full_name": "acme/web" })) + .prevent_stray_requests(); + assert!(sync_github(&app).await.is_err()); + assert_eq!(installation_of(web).await?.as_deref(), Some("7"), "a bare 403 unlinks nobody"); + Ok(()) +} + +/// The sync reads each link's URL before asking GitHub and replaces it only if it's still that URL: a webhook that +/// moved the link in between (here, to `acme/website`) knows a newer name than the run read, and isn't undone. +#[laravel::test] +async fn the_sync_doesnt_undo_a_rename_a_webhook_applied_meanwhile(_app: Application) -> laravel::Result<()> { + use app::forge::webhooks::{Link, Reach}; + let org: i64 = db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) \ + VALUES (gen_random_uuid(), 'acme', 'Acme', now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + let moved = project(org, "web", "github", "https://github.com/acme/website", "42").await?; + let stale = project(org, "docs", "github", "https://github.com/old-org/docs", "43").await?; + let mut reach = Reach::default(); + for (project_id, id, read, path) in [ + (moved, "42", "https://github.com/acme/web", "acme/web"), + (stale, "43", "https://github.com/old-org/docs", "acme/docs"), + ] { + reach.links.push(Link { + project_id, + repository_id: id.into(), + installation: "7".into(), + url: Some(read.into()), + }); + reach.paths.insert((id.into(), "7".into()), path.into()); + } + assert_eq!(app::forge::sync::follow_renames(&reach).await?, 1); + assert_eq!(url_of(moved).await?, "https://github.com/acme/website", "the webhook's newer name stays"); + assert_eq!(url_of(stale).await?, "https://github.com/acme/docs"); + Ok(()) +} diff --git a/app/tests/installations.rs b/app/tests/installations.rs index 4c3e730bc..a4b5d795a 100644 --- a/app/tests/installations.rs +++ b/app/tests/installations.rs @@ -109,7 +109,10 @@ fn granted(owner: &str) -> client::HttpFake { &format!("api.github.com/repos/{owner}/docs/collaborators/ada/permission"), json!({ "role_name": "write" }), ) - .with("api.github.com/repositories/42", json!({ "full_name": format!("{owner}/web") })) + .with( + "api.github.com/repositories/42", + json!({ "id": 42, "full_name": format!("{owner}/web"), "private": true, "license": null }), + ) .with(&format!("api.github.com/repos/{owner}/web"), json!({ "id": 42, "private": true, "license": null })) } @@ -417,7 +420,10 @@ fn acme_all(id: &str) -> client::HttpFake { &format!("api.github.com/repos/acme/{name}/collaborators/ada/permission"), json!({ "role_name": "admin" }), ) - .with(&format!("api.github.com/repositories/{repo_id}"), json!({ "full_name": format!("acme/{name}") })) + .with( + &format!("api.github.com/repositories/{repo_id}"), + json!({ "id": repo_id, "full_name": format!("acme/{name}"), "private": true, "license": null }), + ) .with( &format!("api.github.com/repos/acme/{name}"), json!({ "id": repo_id, "private": true, "license": null }), @@ -508,7 +514,7 @@ async fn a_reinstall_moves_projects_to_the_new_installation_with_no_new_organiza let account = json!({ "id": 5005, "login": "acme", "type": "Organization" }); let web = json!([{ "full_name": "acme/web", "id": 42 }]); - let _github = acme_all("8").with("api.github.com/repos/acme/web/collaborators*", json!([])); + let _github = acme_all("8").with("api.github.com/repositories/42/collaborators*", json!([])); deliver( &app, "installation", @@ -654,7 +660,9 @@ fn acme_three_hundred() -> client::HttpFake { } if let Some(id) = path.strip_prefix("/repositories/") { return match by_id.get(id) { - Some(name) => client::response().json(json!({ "full_name": name })), + Some(name) => client::response().json(json!({ + "id": id.parse::().unwrap(), "full_name": name, "private": true, "license": null, + })), None => client::response().status(404).json(json!({})), }; } diff --git a/app/tests/link.rs b/app/tests/link.rs index 5c27e2caa..0f360f224 100644 --- a/app/tests/link.rs +++ b/app/tests/link.rs @@ -55,21 +55,28 @@ fn github(role: &str) -> client::HttpFake { .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" } })) + .with( + "api.github.com/repositories/42", + json!({ "id": 42, "full_name": "acme/web", "private": false, "license": { "spdx_id": "MIT" } }), + ) + // Linking by a typed URL finds the ID by name; the visibility and licence check asks by ID, so this answer + // (private, no licence) must never decide it + .with("api.github.com/repos/acme/web", json!({ "id": 42, "private": true, "license": null })) } #[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 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"); + assert!(linked.repository_public, "linking checks the repository at once, by its ID"); + let urls: Vec = github.sent().iter().map(|r| r.url().to_string()).collect(); + assert!(urls.iter().any(|u| u == "https://api.github.com/repositories/42"), "{urls:?}"); let unlinked = link_repository(linked, &ada, "", None, false).await?; assert_eq!((unlinked.forge, unlinked.repository_url, unlinked.forge_installation), (None, None, None)); diff --git a/app/tests/mcp.rs b/app/tests/mcp.rs index 8be00a3bc..92f5c13ed 100644 --- a/app/tests/mcp.rs +++ b/app/tests/mcp.rs @@ -1267,7 +1267,10 @@ async fn mcp_links(app: Application) -> laravel::Result<()> { .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/repositories/42", + json!({ "id": 42, "full_name": "acme/web", "private": false, "license": { "spdx_id": "MIT" } }), + ) .with( "api.github.com/repos/acme/web", json!({ "id": 42, "private": false, "license": { "spdx_id": "MIT" } }), diff --git a/app/tests/ui.rs b/app/tests/ui.rs index 6cbdd7f58..c26e62bf2 100644 --- a/app/tests/ui.rs +++ b/app/tests/ui.rs @@ -378,7 +378,10 @@ fn github(role: &str) -> laravel::http::client::HttpFake { .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/repositories/42", + json!({ "id": 42, "full_name": "acme/web", "private": false, "license": { "spdx_id": "MIT" } }), + ) .with("api.github.com/repos/acme/web", json!({ "id": 42, "private": false, "license": { "spdx_id": "MIT" } })) } diff --git a/app/tests/webhooks.rs b/app/tests/webhooks.rs index a61aa6dff..6d7d2d9ff 100644 --- a/app/tests/webhooks.rs +++ b/app/tests/webhooks.rs @@ -191,7 +191,7 @@ async fn a_recheck_reads_each_repositorys_collaborators_once(_app: Application) .with("api.github.com/app/installations/7/access_tokens", json!({ "token": "t" })) .with("api.github.com/repositories/42", json!({ "full_name": "acme/web" })) .with( - "api.github.com/repos/acme/web/collaborators*", + "api.github.com/repositories/42/collaborators*", json!([{ "id": 1001, "role_name": "maintain" }, { "id": 2002, "role_name": "read" }]), ); assert_eq!(app::forge::webhooks::recheck(&github_app(), &[ada_id]).await?, 1); @@ -225,7 +225,7 @@ async fn a_listing_that_fails_changes_nobody(_app: Application) -> laravel::Resu .with("api.github.com/app/installations/7/access_tokens", json!({ "token": "t" })) .with("api.github.com/repositories/42", json!({ "full_name": "acme/web" })) .with( - "api.github.com/repos/acme/web/collaborators*", + "api.github.com/repositories/42/collaborators*", laravel::http::client::response().status(502).json(json!({})), ); assert!(app::forge::webhooks::recheck(&github_app(), &[ada_id]).await.is_err()); @@ -241,12 +241,24 @@ async fn a_listing_that_fails_changes_nobody(_app: Application) -> laravel::Resu async fn a_renamed_repository_moves_its_links_and_edits_say_whether_it_is_private( app: Application, ) -> laravel::Result<()> { - let (_, by_id, by_url) = linked().await?; + let (org, by_id, by_url) = linked().await?; + // The same repository ID linked through another installation: that installation didn't send the rename, and may + // not cover the new owner, so its link waits for its own delivery or the hourly sync + let elsewhere: i64 = db::query!( + "INSERT INTO projects (pid, organization_id, slug, name, forge, repository_url, repository_id, \ + forge_installation, created_at, updated_at) \ + VALUES (gen_random_uuid(), {org}, 'web2', 'Web2', 'github', 'https://github.com/acme/web', '42', '9', now(), \ + now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); let events = laravel::event::fake(); - let renamed = json!({ "action": "renamed", "repository": { "id": 42, "full_name": "acme/website" } }); + let renamed = json!({ + "action": "renamed", "installation": { "id": 7 }, "repository": { "id": 42, "full_name": "acme/website" }, + }); deliver(&app, "repository", renamed).await.assert_ok().assert_json_path("moved", 1); - let url: Option = db::query!("SELECT repository_url FROM projects WHERE id = {by_id}").scalar().await?; - assert_eq!(url.as_deref(), Some("https://github.com/acme/website")); + assert_eq!(urls(&[by_id, elsewhere]).await?, ["https://github.com/acme/website", "https://github.com/acme/web"]); // A delivery naming the ID backfills a link that only had the URL let edited = json!({ "action": "edited", "repository": { "id": 77, "full_name": "acme/web", "private": true } }); deliver(&app, "repository", edited).await.assert_ok(); @@ -322,3 +334,208 @@ async fn a_cancelled_or_failed_run_closes_the_builds_it_was_sending(app: Applica events.assert_dispatched_where::(|e| e.build_id == sending); Ok(()) } + +/// The URL of each of these projects. +async fn urls(projects: &[i64]) -> laravel::Result> { + let mut out = Vec::new(); + for &id in projects { + let url: Option = db::query!("SELECT repository_url FROM projects WHERE id = {id}").scalar().await?; + out.push(url.unwrap_or_default()); + } + Ok(out) +} + +/// An `installation_target` delivery: installation 7's account renamed from `from` to `to`. +fn renamed(from: &str, to: &str) -> serde_json::Value { + json!({ + "action": "renamed", "target_type": "Organization", "installation": { "id": 7 }, + "account": { "id": 5005, "login": to, "type": "Organization" }, + "changes": { "login": { "from": from } }, + }) +} + +/// GitHub's App API, saying installation 7's account is called `login` now. +fn account_now(login: &str) -> laravel::http::client::HttpFake { + laravel::http::client::fake() + .with("api.github.com/app/installations/7", json!({ "id": 7, "account": { "id": 5005, "login": login } })) + .prevent_stray_requests() +} + +/// Installation 7 on `acme`, with a project linked to acme/web through it and acme/web in Ada's repository picker. +/// Returns the project. +async fn installed_on(login: &str) -> laravel::Result { + let (_, by_id, _) = linked().await?; + db::query!( + "INSERT INTO github_installations (installation_id, account_id, account_login, account_type) \ + VALUES ('7', '5005', {login}, 'Organization')" + ) + .insert() + .await?; + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let ada_id = ada.id; + db::query!( + "INSERT INTO user_repositories (user_id, installation_id, repository_id, full_name, permission) \ + VALUES ({ada_id}, '7', '42', 'acme/web', 'admin')" + ) + .insert() + .await?; + Ok(by_id) +} + +/// What a rename can change: installation 7's login, the project's URL and the picker's cached name. +async fn rename_state(project: i64) -> laravel::Result<(String, String, String)> { + let login: Option = + db::query!("SELECT account_login FROM github_installations WHERE installation_id = '7'").scalar().await?; + let name: Option = db::query!("SELECT full_name FROM user_repositories").scalar().await?; + Ok((login.unwrap_or_default(), urls(&[project]).await?.remove(0), name.unwrap_or_default())) +} + +/// A rename delivered late (the recovery job redelivers missed deliveries) after a newer one: `acme→beta`, then +/// `beta→acme`, then `acme→beta` again. Its logins can't tell it from a new rename, so GitHub is asked what the +/// account is called now (`acme`), and the stale delivery changes nothing. +#[laravel::test(app = github)] +async fn a_late_rename_after_a_newer_one_changes_nothing(app: Application) -> laravel::Result<()> { + let project = installed_on("acme").await?; + let now = ("acme".to_string(), "https://github.com/acme/web".to_string(), "acme/web".to_string()); + let _github = account_now("acme"); + deliver(&app, "installation_target", renamed("acme", "beta")) + .await + .assert_ok() + .assert_json_path("moved", 0) + .assert_json_path("installation", "stale"); + assert_eq!(rename_state(project).await?, now); + + // Once GitHub says `beta`, the rename applies; redelivered, it moves nothing further + let _github = account_now("beta"); + for _ in 0..2 { + deliver(&app, "installation_target", renamed("acme", "beta")) + .await + .assert_ok() + .assert_json_path("installation", "renamed"); + } + assert_eq!( + rename_state(project).await?, + ("beta".to_string(), "https://github.com/beta/web".to_string(), "beta/web".to_string()) + ); + Ok(()) +} + +/// Two quick renames, `acme→beta→gamma`, both delivered once GitHub already says `gamma`: the first is stale and +/// ignored, and the second, though VisualCI still has `acme` and the delivery says `beta`, moves everything to `gamma`. +/// A lost delivery (only `beta→gamma` arrives) ends the same way. +#[laravel::test(app = github)] +async fn quick_renames_and_a_lost_delivery_end_at_githubs_name(app: Application) -> laravel::Result<()> { + let project = installed_on("acme").await?; + let gamma = ("gamma".to_string(), "https://github.com/gamma/web".to_string(), "gamma/web".to_string()); + let _github = account_now("gamma"); + deliver(&app, "installation_target", renamed("acme", "beta")) + .await + .assert_ok() + .assert_json_path("installation", "stale"); + deliver(&app, "installation_target", renamed("beta", "gamma")) + .await + .assert_ok() + .assert_json_path("moved", 2) + .assert_json_path("installation", "renamed"); + assert_eq!(rename_state(project).await?, gamma); + + // Lost delivery: back at acme, and only beta→gamma arrives + db::query!("UPDATE github_installations SET account_login = 'acme'").update().await?; + db::query!("UPDATE projects SET repository_url = 'https://github.com/acme/web' WHERE forge_installation = '7'") + .update() + .await?; + db::query!("UPDATE user_repositories SET full_name = 'acme/web'").update().await?; + deliver(&app, "installation_target", renamed("beta", "gamma")).await.assert_ok().assert_json_path("moved", 2); + assert_eq!(rename_state(project).await?, gamma); + Ok(()) +} + +/// A login that isn't one (a path, empty, longer than GitHub allows) is never stored or put into URLs: not from a +/// rename, and not from an installation's account. +#[laravel::test(app = github)] +async fn a_rename_to_a_login_that_isnt_one_changes_nothing(app: Application) -> laravel::Result<()> { + let project = installed_on("acme").await?; + let now = ("acme".to_string(), "https://github.com/acme/web".to_string(), "acme/web".to_string()); + let long = "a".repeat(101); + for bad in ["../x", "", long.as_str()] { + let _github = account_now(bad); + deliver(&app, "installation_target", renamed("acme", bad)).await.assert_ok(); + deliver(&app, "installation_target", renamed(bad, "acme")).await.assert_ok(); + assert_eq!(rename_state(project).await?, now, "{bad:?}"); + } + // An installation made on an account whose login isn't one isn't recorded + let _github = laravel::http::client::fake().prevent_stray_requests(); + let created = json!({ + "action": "created", "installation": { "id": 8, "account": { "id": 6006, "login": "../x", "type": "User" } }, + "sender": { "id": 1001 }, + }); + deliver(&app, "installation", created).await.assert_ok(); + let recorded: Option = + db::query!("SELECT count(*) FROM github_installations WHERE installation_id = '8'").scalar().await?; + assert_eq!(recorded, Some(0)); + Ok(()) +} + +/// The account the App is installed on is renamed (`installation_target`): GitHub sends nothing per repository, so +/// the installation's login and the URLs of its projects under the old login (any case) follow from this delivery. +/// Another account's repositories, and another installation's projects, stay as they were. +#[laravel::test(app = github)] +async fn a_renamed_account_moves_its_installations_projects(app: Application) -> laravel::Result<()> { + let (org, by_id, by_url) = linked().await?; + let mut others = Vec::new(); + for (url, installation) in [ + ("https://github.com/ACME/docs", "7"), + ("https://github.com/acmeco/x", "7"), + ("https://github.com/acme/web", "9"), + ] { + let slug = format!("p{}", others.len()); + let id: i64 = db::query!( + "INSERT INTO projects (pid, organization_id, slug, name, forge, repository_url, forge_installation, \ + created_at, updated_at) \ + VALUES (gen_random_uuid(), {org}, {slug}, {slug}, 'github', {url}, {installation}, now(), now()) \ + RETURNING id" + ) + .scalar() + .await? + .unwrap(); + others.push(id); + } + db::query!( + "INSERT INTO github_installations (installation_id, account_id, account_login, account_type) \ + VALUES ('7', '5005', 'acme', 'Organization')" + ) + .insert() + .await?; + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let ada_id = ada.id; + db::query!( + "INSERT INTO user_repositories (user_id, installation_id, repository_id, full_name, permission) \ + VALUES ({ada_id}, '7', '42', 'acme/web', 'admin')" + ) + .insert() + .await?; + + let _github = account_now("acmehq"); + deliver(&app, "installation_target", renamed("acme", "acmehq")) + .await + .assert_ok() + .assert_json_path("moved", 3) + .assert_json_path("installation", "renamed"); + assert_eq!( + urls(&[by_id, by_url, others[0], others[1], others[2]]).await?, + [ + "https://github.com/acmehq/web", + "https://github.com/acmehq/web", + "https://github.com/acmehq/docs", + "https://github.com/acmeco/x", + "https://github.com/acme/web", + ] + ); + let login: Option = + db::query!("SELECT account_login FROM github_installations WHERE installation_id = '7'").scalar().await?; + assert_eq!(login.as_deref(), Some("acmehq")); + let name: Option = + db::query!("SELECT full_name FROM user_repositories WHERE user_id = {ada_id}").scalar().await?; + assert_eq!(name.as_deref(), Some("acmehq/web"), "the repository picker shows the new name"); + Ok(()) +} diff --git a/docs/design.md b/docs/design.md index 1626235f2..ad17ea2c3 100644 --- a/docs/design.md +++ b/docs/design.md @@ -646,7 +646,20 @@ without a webhook goes within the hour. Each row records `synced_at`; `/status` - A repository belongs to one organization; several of its projects may link it. Links match by the forge's permanent repository ID (`projects.repository_id`, from the forge at link time and filled in by the hourly sync for older - links), so a renamed or transferred repository stays linked and a new one that takes its old name doesn't. A link + links), so a renamed or transferred repository stays linked and a new one that takes its old name doesn't. Calls to + GitHub about a linked repository (checks, comments, branches, collaborators, licence) go to + `/repositories/{id}/...`, not `/repos/{owner}/{name}/...`, whose old name GitHub answers with a 301 that checks and + comments (sent by the `outbound` client, which follows no redirects) don't survive. The stored URL follows the name: a repository's `renamed`/`transferred` delivery, the + `installation_target` `renamed` delivery when the account the App is installed on changes its login (an + organization's rename sends nothing per repository), and the hourly sync, which reads each repository's name by its + ID anyway, for any delivery that was missed. An account rename is applied only when GitHub says the account has + that name now (a late redelivery of an older rename changes nothing); the installation's login then becomes GitHub's, + and URLs move from both the delivery's old login and the one VisualCI had (a missed or out-of-order delivery). A + repository's rename moves only the links through the installation that sent it. The sync follows a repository only + through an installation that can list its collaborators, replaces a URL only if it's unchanged since the run read + it, and treats a repository whose collaborators answer 404 or 403 "Resource not accessible by integration" as unseen + (its links are unlinked). A rate limit's answer (a 429, or a primary or secondary limit's 403) defers the run; any + other 403 fails it without unlinking anyone. A link from a second organization is refused, naming the one that has it; a maintainer of the repository (checked live) can move it (`move_link`), which unlinks the other organization's projects with a notice and emails their admins (sc-8728). From 5aaba4b38001e7736e1248117ed8d85596a9bbc2 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Sat, 5 Dec 2026 11:53:38 +0000 Subject: [PATCH 2/4] Renames after #266 and #290: the licence file is read at the repository's ID path; the changelog line is an entry file --- app/src/forge/open_source.rs | 4 +++- app/tests/link.rs | 15 ++++++++++----- .../changelog/2026-12-06-0053-github-renames.md | 1 + 3 files changed, 14 insertions(+), 6 deletions(-) create mode 100644 frontend/content/changelog/2026-12-06-0053-github-renames.md diff --git a/app/src/forge/open_source.rs b/app/src/forge/open_source.rs index 7e8f1230e..43516c1e7 100644 --- a/app/src/forge/open_source.rs +++ b/app/src/forge/open_source.rs @@ -482,7 +482,9 @@ async fn check(app: &GithubApp, p: &Project) -> Option { let answer = async { let token = github_app::installation_token(app, installation).await?; // By GitHub's ID when known, so a rename can't mislead it - let Some(repo_api) = github_app::linked_repo_api(p.repository_id.as_deref(), Some(url)) else { return Ok(None) }; + let Some(repo_api) = github_app::linked_repo_api(p.repository_id.as_deref(), Some(url)) else { + return Ok(None); + }; let Some(repo) = github_app::repository(&token, &repo_api).await? else { return Ok(None) }; let file = if needs_file(&repo) { github_app::licence_file(&token, &repo_api).await?.map(|(path, text)| LicenceFile { path, text }) diff --git a/app/tests/link.rs b/app/tests/link.rs index 0f360f224..765fb77b3 100644 --- a/app/tests/link.rs +++ b/app/tests/link.rs @@ -96,9 +96,8 @@ async fn a_licence_github_cant_name_is_read_from_the_file(_app: Application) -> .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": "admin" })) - .with("api.github.com/repositories/42", json!({ "full_name": "acme/web" })) .with( - "api.github.com/repos/acme/web/license", + "api.github.com/repositories/42/license", json!({ "path": "LICENSE", "encoding": "base64", @@ -107,9 +106,15 @@ async fn a_licence_github_cant_name_is_read_from_the_file(_app: Application) -> }), ) .with( - "api.github.com/repos/acme/web", - json!({ "id": 42, "private": false, "license": { "key": "other", "spdx_id": "NOASSERTION" } }), - ); + "api.github.com/repositories/42", + json!({ + "id": 42, + "full_name": "acme/web", + "private": false, + "license": { "key": "other", "spdx_id": "NOASSERTION" } + }), + ) + .with("api.github.com/repos/acme/web", json!({ "id": 42, "private": true, "license": null })); let linked = link_repository(web, &ada, "https://github.com/acme/web", None, false).await?; assert!(linked.repository_public); assert!(linked.open_source, "{:?}", linked.open_source_note); diff --git a/frontend/content/changelog/2026-12-06-0053-github-renames.md b/frontend/content/changelog/2026-12-06-0053-github-renames.md new file mode 100644 index 000000000..92a5dac7f --- /dev/null +++ b/frontend/content/changelog/2026-12-06-0053-github-renames.md @@ -0,0 +1 @@ +Renaming a GitHub repository or the organization it belongs to no longer breaks its checks and pull request comments: VisualCI reaches each linked repository by GitHub's permanent ID, and the project's repository link follows the new name, at once when GitHub tells VisualCI and within the hour otherwise. From 2e05986098caef51b432adec4fff040d89fbc10e Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Sat, 5 Dec 2026 12:02:55 +0000 Subject: [PATCH 3/4] Renames: linking makes ten calls at most (the path lookup by ID is gone) --- app/src/forge/calls.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/src/forge/calls.rs b/app/src/forge/calls.rs index 652c193e4..8ceb37934 100644 --- a/app/src/forge/calls.rs +++ b/app/src/forge/calls.rs @@ -45,8 +45,8 @@ pub const SIGN_IN_SYNC_BUDGET: u32 = 1 + super::github::SIGN_IN_REPOSITORY_PAGES /// Linking a repository checks it live (`link::link_repository`): the installation that reaches it, the person's /// permission (a token, their login, collaborator and permission), its ID, then its visibility and licence /// (`open_source::refresh`: a token, the repository by its ID, and its licence file when GitHub can't name the -/// licence). Eleven at most, when the installation token isn't cached between the two. -pub const LINK_BUDGET: u32 = 11; +/// licence). +pub const LINK_BUDGET: u32 = 10; /// Requests allowed more (or fewer) than [`DEFAULT_BUDGET`]: method, path (`*` is one segment), the most calls, and /// why. Each is still a fixed number, whatever the size of the organization. From 41e57a3770d4896416fc75b619e436dc976055da Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Sat, 5 Dec 2026 15:12:06 +0000 Subject: [PATCH 4/4] Renames: main's locked-conversation comment test posts at the repository's ID path --- app/tests/forge_reports.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/tests/forge_reports.rs b/app/tests/forge_reports.rs index bf797312b..29aeaf10e 100644 --- a/app/tests/forge_reports.rs +++ b/app/tests/forge_reports.rs @@ -553,9 +553,9 @@ async fn a_comment_the_pull_request_cant_take_fails_once(_app: Application) -> l 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/issues/5/comments?*", json!([])) + .with("api.github.com/repositories/42/issues/5/comments?*", json!([])) .with( - "api.github.com/repos/acme/web/issues/5/comments", + "api.github.com/repositories/42/issues/5/comments", client::response() .status(422) .json(json!({ "message": "Unable to create comment because issue is locked." })),