diff --git a/docs/design.md b/docs/design.md index 0568297c..cc1748ca 100644 --- a/docs/design.md +++ b/docs/design.md @@ -391,6 +391,13 @@ every forge-derived membership through the installation (GitHub's collaborator p without a webhook goes within the hour. Each row records `synced_at`; `/status` reports the oldest as `oldest_forge_sync_seconds`, which the uptime check alerts on. +- 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 + 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). + ## Public galleries A project can publish screenshots (`gallery` groups of snapshot globs in visualci.yml; `models::gallery`). What's diff --git a/server/frontend/content/docs/reference/access.md b/server/frontend/content/docs/reference/access.md index 2b8f58aa..fd97d101 100644 --- a/server/frontend/content/docs/reference/access.md +++ b/server/frontend/content/docs/reference/access.md @@ -16,7 +16,7 @@ can't change settings, make tokens or see the organization's members. ## Access follows GitHub -Link a project to its repository on the project's **Settings** tab. The VisualCI GitHub App must be installed on the repository, and you must be its admin or maintainer on GitHub. From then on, anyone who can reach that repository on GitHub gets the matching role when they sign in to VisualCI with GitHub: +Link a project to its repository on the project's **Settings** tab. The VisualCI GitHub App must be installed on the repository, and you must be its admin or maintainer on GitHub. A repository belongs to one organization (several of its projects may link it). If another organization has it linked, VisualCI says which, and as a maintainer you can move the link to yours with **Move it here** (`move_link` over MCP); that organization's admins get an email. VisualCI follows the repository by GitHub's own ID, so renaming or transferring it keeps the link, and a new repository that takes the old name doesn't get it. Whoever linked it must stay a maintainer: VisualCI checks every hour and unlinks it, with a notice on the project, when they aren't. From then on, anyone who can reach that repository on GitHub gets the matching role when they sign in to VisualCI with GitHub: | On GitHub | In VisualCI | | --- | --- | diff --git a/server/frontend/src/api/hooks.ts b/server/frontend/src/api/hooks.ts index 2a0f0503..792224d5 100644 --- a/server/frontend/src/api/hooks.ts +++ b/server/frontend/src/api/hooks.ts @@ -176,7 +176,7 @@ export function useCreateProject(org: string) { export function useUpdateProject(org: string, project: string) { const qc = useQueryClient() return useMutation({ - mutationFn: (v: Partial & { forge_token?: string; dismiss_notice?: boolean }) => + mutationFn: (v: Partial & { forge_token?: string; dismiss_notice?: boolean; move_link?: boolean }) => patch(projectPath(org, project), v), onSuccess: (settings) => { qc.setQueryData(keys.project(org, project), (d) => (d ? { ...d, project: settings } : d)) diff --git a/server/frontend/src/pages/ProjectPage.tsx b/server/frontend/src/pages/ProjectPage.tsx index c15ae95f..be3209ed 100644 --- a/server/frontend/src/pages/ProjectPage.tsx +++ b/server/frontend/src/pages/ProjectPage.tsx @@ -392,7 +392,7 @@ function Settings({ if ('repository_url' in fields && !fields.repository_url) fields.repository_url = '' // A new access token relinks the repository with it, even when the URL is the same. const withToken = token.trim() && selfManaged(draft) ? { repository_url: draft.repository_url ?? '', forge_token: token.trim() } : {} - const changes: Partial & { forge_token?: string } = rulesChanged + const changes: Partial & { forge_token?: string; move_link?: boolean } = rulesChanged ? { ...fields, ...withToken, ignore_rules: toRules(draft.rules) } : { ...fields, ...withToken } const dirty = Object.keys(fields).length > 0 || rulesChanged || 'forge_token' in withToken @@ -406,20 +406,24 @@ function Settings({ draft.rules.map((r, j) => (j === i ? { ...r, [k]: v } : r)), ) + const saveCallbacks = { + onSuccess: (s: ProjectSettings) => { + setSaved(true) + setToken('') + if (s.slug !== project) { + navigate({ to: '/$org/$project', params: { org, project: s.slug }, search: { tab: 'settings' }, replace: true }) + } + }, + } + // Another organization has the repository linked: its maintainer can move the link here (sc-8728). + const linkedElsewhere = update.isError && errorMessage(update.error).includes('belongs to one organization') + return (
{ e.preventDefault() - update.mutate(changes, { - onSuccess: (s) => { - setSaved(true) - setToken('') - if (s.slug !== project) { - navigate({ to: '/$org/$project', params: { org, project: s.slug }, search: { tab: 'settings' }, replace: true }) - } - }, - }) + update.mutate(changes, saveCallbacks) }} > {!canEdit &&

Only the organization’s admins can change these settings.

} @@ -754,6 +758,15 @@ function Settings({ )} {saved && !dirty && Saved} {update.isError && {errorMessage(update.error)}} + {linkedElsewhere && ( + + )}
) diff --git a/server/migration/src/lib.rs b/server/migration/src/lib.rs index a316ce1e..96da73cd 100644 --- a/server/migration/src/lib.rs +++ b/server/migration/src/lib.rs @@ -42,6 +42,7 @@ mod m20261202_000035_invitation_for_user; mod m20261202_000036_tokens_can_approve; mod m20261202_000037_review_source; mod m20261202_000038_matches_approved; +mod m20261202_000039_repository_id; pub struct Migrator; @@ -90,6 +91,7 @@ impl MigratorTrait for Migrator { Box::new(m20261202_000036_tokens_can_approve::Migration), Box::new(m20261202_000037_review_source::Migration), Box::new(m20261202_000038_matches_approved::Migration), + Box::new(m20261202_000039_repository_id::Migration), // inject-above (do not remove this comment) ] } diff --git a/server/migration/src/m20261202_000039_repository_id.rs b/server/migration/src/m20261202_000039_repository_id.rs new file mode 100644 index 00000000..4222a057 --- /dev/null +++ b/server/migration/src/m20261202_000039_repository_id.rs @@ -0,0 +1,30 @@ +//! A linked repository's permanent ID on its forge, so a renamed or transferred repository stays linked and a new +//! repository that takes the old name doesn't. Filled in when a repository is linked, and by the hourly sync for +//! links made before. +use sea_orm_migration::prelude::*; + +pub struct Migration; + +impl MigrationName for Migration { + fn name(&self) -> &str { + "m20261202_000039_repository_id" + } +} + +#[async_trait::async_trait] +impl MigrationTrait for Migration { + async fn up(&self, m: &SchemaManager) -> Result<(), DbErr> { + m.get_connection() + .execute_unprepared( + "ALTER TABLE projects ADD COLUMN repository_id TEXT; \ + CREATE INDEX projects_forge_repository_id ON projects (forge, repository_id) WHERE repository_id IS NOT NULL;", + ) + .await?; + Ok(()) + } + + async fn down(&self, m: &SchemaManager) -> Result<(), DbErr> { + m.get_connection().execute_unprepared("ALTER TABLE projects DROP COLUMN repository_id;").await?; + Ok(()) + } +} diff --git a/server/src/access.rs b/server/src/access.rs index 632bdfc0..b182aae6 100644 --- a/server/src/access.rs +++ b/server/src/access.rs @@ -9,7 +9,7 @@ use loco_rs::prelude::*; use crate::{ forge::{Forge, ForgeEvent, ForgeKind, Permission, Repository, SignIn}, models::{ - _entities::{identities, invitations, projects, users}, + _entities::{identities, invitations, organizations, projects, users}, baselines, memberships::{self, Role}, }, @@ -88,12 +88,19 @@ async fn site_scope( /// Projects linked to one repository. pub async fn linked(db: &impl ConnectionTrait, repository: &Repository) -> Result> { + // By the forge's permanent ID when the delivery has it: a renamed repository is still the same one, and a new + // repository that took the old name isn't. Links whose ID isn't known yet still match by URL. + let by_url = + sea_orm::sea_query::Expr::cust_with_values("lower(repository_url) = $1", [repository.url.to_lowercase()]); + let matching = match &repository.id { + Some(id) => sea_orm::Condition::any() + .add(projects::Column::RepositoryId.eq(id.clone())) + .add(sea_orm::Condition::all().add(projects::Column::RepositoryId.is_null()).add(by_url)), + None => sea_orm::Condition::all().add(by_url), + }; Ok(projects::Entity::find() .filter(projects::Column::Forge.eq(repository.forge.as_str())) - .filter(sea_orm::sea_query::Expr::cust_with_values( - "lower(repository_url) = $1", - [repository.url.to_lowercase()], - )) + .filter(matching) .all(db) .await?) } @@ -425,7 +432,9 @@ pub async fn sync_all(db: &DatabaseConnection, settings: &Settings, forge: &Forg /// Link a project to a repository for `user`. The forge's app must be installed on the repository and the user must /// be an admin or maintainer of it there, so nobody can attach checks or access to someone else's repository. -/// `url` empty unlinks. +/// `url` empty unlinks. A repository belongs to one organization (several of its projects may link it): one linked +/// elsewhere is refused, naming that organization, unless `move_link`, which moves it here (the user's maintainer +/// permission was just checked with the forge) and emails the other organization's admins. /// /// # Errors /// `BadRequest` saying what's missing; forge or database errors. @@ -435,12 +444,14 @@ pub async fn link_repository( user: &users::Model, url: &str, token: Option<&str>, + move_link: bool, ) -> Result { let organization_id = project.organization_id; let mut a = project.into_active_model(); if url.trim().is_empty() { a.forge = Set(None); a.repository_url = Set(None); + a.repository_id = Set(None); a.forge_installation = Set(None); a.forge_token_enc = Set(None); a.forge_webhook_at = Set(None); @@ -508,8 +519,26 @@ pub async fn link_repository( permission.map_or("not a collaborator".to_string(), |p| format!("{p:?}").to_lowercase()) ))); } + // The forge's permanent ID for the repository, so a rename keeps the link and a new repository that takes the old + // name doesn't inherit it. + let repository_id = match forge.visibility(&repository, &installation).await { + Ok(v) => v.and_then(|v| v.id), + Err(e) => { + tracing::warn!(repo = repository.path, error = %e, "reading the repository's ID"); + None + } + }; + let repository = repository.with_id(repository_id.clone()); + let elsewhere = linked_elsewhere(&ctx.db, &repository, organization_id).await?; + if !elsewhere.is_empty() { + if !move_link { + return Err(Error::BadRequest(linked_elsewhere_message(&ctx.db, &repository, &elsewhere).await?)); + } + move_links_here(ctx, elsewhere, &repository, organization_id, user).await?; + } a.forge = Set(Some(repository.forge.as_str().to_string())); a.repository_url = Set(Some(repository.url.clone())); + a.repository_id = Set(repository_id); a.forge_webhook_at = Set(None); a.linked_by = Set(Some(user.id)); if site.is_empty() { @@ -534,6 +563,88 @@ pub async fn link_repository( crate::open_source::refresh(ctx, project).await } +/// Projects in other organizations that link this repository. A repository belongs to one organization (several of +/// its projects may link it), so these are what a link from `organization_id` would have to move. +/// +/// # Errors +/// On a database error. +pub async fn linked_elsewhere( + db: &impl ConnectionTrait, + repository: &Repository, + organization_id: i64, +) -> Result> { + Ok(linked(db, repository).await?.into_iter().filter(|p| p.organization_id != organization_id).collect()) +} + +/// Why a link is refused: which organization has the repository, and how to move it. +/// +/// # Errors +/// On a database error. +pub async fn linked_elsewhere_message( + db: &impl ConnectionTrait, + repository: &Repository, + elsewhere: &[projects::Model], +) -> Result { + let org = match elsewhere.first() { + Some(p) => organizations::Entity::find_by_id(p.organization_id).one(db).await?, + None => None, + }; + let there = org.map_or_else(|| "another organization".to_string(), |o| format!("{} ({})", o.name, o.slug)); + 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 `user` maintains the repository. +/// +/// # Errors +/// On a database error. +pub async fn move_links_here( + ctx: &AppContext, + elsewhere: Vec, + repository: &Repository, + organization_id: i64, + user: &users::Model, +) -> Result<()> { + let to_org = + organizations::Entity::find_by_id(organization_id).one(&ctx.db).await?.map_or_else(String::new, |o| o.name); + for p in elsewhere { + let org = organizations::Entity::find_by_id(p.organization_id).one(&ctx.db).await?; + let mut a = p.clone().into_active_model(); + a.forge = Set(None); + a.repository_url = Set(None); + a.repository_id = Set(None); + a.forge_installation = Set(None); + a.forge_token_enc = Set(None); + a.forge_webhook_at = Set(None); + a.linked_by = Set(None); + a.notice = Set(Some(format!( + "{} moved {} to {to_org}: a repository belongs to one organization, so this project isn't linked to it any \ + more.", + user.name, repository.path + ))); + let p = a.update(&ctx.db).await?; + tracing::info!(repo = repository.path, from = p.organization_id, to = organization_id, "repository link moved"); + let p = crate::open_source::refresh(ctx, p).await?; + if let Some(org) = org { + let kind = crate::notify::Kind::RepositoryMoved { + project: p.slug.clone(), + repository: repository.path.clone(), + to_org: to_org.clone(), + by: user.name.clone(), + }; + let key = format!("repository_moved:{}:{}", p.id, chrono::Utc::now().timestamp()); + crate::notify::queue(ctx, &kind, crate::notify::To::Admins(&org), None, &key).await?; + } + } + Ok(()) +} + /// Recheck that whoever linked each of a forge's projects still maintains its repository, and unlink the ones whose /// linker has lost it (or is gone), with a notice on the project saying why. Without this, someone who has lost access /// to a repository would keep posting VisualCI's checks and pull request comments there, through the forge app's @@ -548,6 +659,19 @@ pub async fn recheck_links(db: &DatabaseConnection, settings: &Settings, forge: let Some((project_forge, repository, installation)) = Forge::for_project(db, settings, &project).await? else { continue; }; + // A link made before VisualCI stored the forge's repository ID gets it now, once. + let project = if project.repository_id.is_none() { + match project_forge.visibility(&repository, &installation).await { + Ok(Some(v)) if v.id.is_some() => { + let mut a = project.into_active_model(); + a.repository_id = Set(v.id); + a.update(db).await? + } + _ => project, + } + } else { + project + }; let identity = match project.linked_by { Some(user_id) => { identities::Entity::find() @@ -688,7 +812,7 @@ pub async fn handle_event(ctx: &AppContext, forge: &Forge, event: ForgeEvent) -> for project in projects { if private { // GitHub's word is enough: no need to ask it again. - let gone = crate::forge::Visibility { public: false, licence: None }; + let gone = crate::forge::Visibility { id: None, public: false, licence: None }; let status = crate::open_source::check_with(&project, |_, _| std::future::ready(Ok(Some(gone)))).await; crate::open_source::record(ctx, project, status).await?; diff --git a/server/src/controllers/ui.rs b/server/src/controllers/ui.rs index 1e624c77..1eb0be31 100644 --- a/server/src/controllers/ui.rs +++ b/server/src/controllers/ui.rs @@ -691,7 +691,7 @@ async fn update_project( if let Some(url) = p.repository_url.take() && Some(url.trim()) != project.repository_url.as_deref() { - project = access::link_repository(&ctx, project, &user, &url, p.forge_token.as_deref()).await?; + project = access::link_repository(&ctx, project, &user, &url, p.forge_token.as_deref(), p.move_link).await?; } if p.gallery_enabled == Some(false) && project.gallery_enabled { crate::workers::gallery_purge::purge_project_later(&ctx, &project).await?; diff --git a/server/src/forge.rs b/server/src/forge.rs index 2d551cd3..6a50a3c4 100644 --- a/server/src/forge.rs +++ b/server/src/forge.rs @@ -83,6 +83,9 @@ pub struct Repository { pub url: String, /// The forge's own path for it: `acme/web` (GitLab: `group/subgroup/project`, nested groups and all). pub path: String, + /// The forge's permanent ID for it, when known (a webhook delivery carries it). A renamed or transferred + /// repository keeps it, and a new repository that takes the old name gets another. + pub id: Option, } /// GitLab instances other than gitlab.com whose project URLs parse as GitLab repositories (base URLs without a @@ -113,6 +116,13 @@ fn on_gitlab_instance(input: &str) -> Option<(String, String)> { } impl Repository { + /// The same repository, with the forge's ID for it. + #[must_use] + pub fn with_id(mut self, id: Option) -> Self { + self.id = id; + self + } + /// A repository from its web or clone URL (`https://github.com/acme/web`, `…/web.git`, /// `git@github.com:acme/web.git`, `https://gitlab.com/acme/web/app`), or GitHub's `owner/name`. `None` for a /// forge VisualCI doesn't know yet. @@ -132,7 +142,7 @@ impl Repository { return None; } let path = parts.join("/"); - return Some(Self { forge: ForgeKind::Gitlab, url: format!("{base}/{path}"), path }); + return Some(Self { forge: ForgeKind::Gitlab, url: format!("{base}/{path}"), path, id: None }); } let (host, path) = if let Some(rest) = s.strip_prefix("git@") { rest.split_once(':')? @@ -162,7 +172,7 @@ impl Repository { return None; } let path = parts.join("/"); - Some(Self { forge, url: format!("https://{host}/{path}"), path }) + Some(Self { forge, url: format!("https://{host}/{path}"), path, id: None }) } /// The repository a project links to. A GitLab project can be on any host (a self-managed instance). @@ -198,7 +208,7 @@ impl Repository { let path = parts.join("/"); let scheme = if host == "gitlab.com" || host == "www.gitlab.com" { "https" } else { scheme }; let host = host.strip_prefix("www.").filter(|h| *h == "gitlab.com").unwrap_or(&host); - Some(Self { forge: ForgeKind::Gitlab, url: format!("{scheme}://{host}/{path}"), path }) + Some(Self { forge: ForgeKind::Gitlab, url: format!("{scheme}://{host}/{path}"), path, id: None }) } /// The base URL of the site the repository is on: `https://gitlab.example.com`. @@ -212,6 +222,8 @@ impl Repository { /// What the forge says about a repository: whether it's public, and its licence (for open source projects). #[derive(Debug, Clone, PartialEq, Eq)] pub struct Visibility { + /// The forge's permanent ID for the repository. + pub id: Option, pub public: bool, /// The SPDX id of the licence the forge detected, if any. pub licence: Option, diff --git a/server/src/forge/github.rs b/server/src/forge/github.rs index 0d930e8a..a8cec2a7 100644 --- a/server/src/forge/github.rs +++ b/server/src/forge/github.rs @@ -106,6 +106,7 @@ pub async fn visibility( ) -> Result> { let token = installation_token(settings, installation).await?; Ok(get(&token, &format!("/repos/{repo}")).await?.map(|v| crate::forge::Visibility { + id: v["id"].as_i64().map(|i| i.to_string()), public: v["private"] == false && v["visibility"].as_str().is_none_or(|s| s == "public"), licence: v["license"]["spdx_id"].as_str().map(str::to_string), })) @@ -288,7 +289,14 @@ fn signed(secret: &str, header: &str, body: &[u8]) -> bool { fn repositories(list: &Value) -> Vec { list.as_array() - .map(|l| l.iter().filter_map(|r| r["full_name"].as_str().and_then(Repository::parse)).collect()) + .map(|l| { + l.iter() + .filter_map(|r| { + let id = r["id"].as_i64().map(|i| i.to_string()); + r["full_name"].as_str().and_then(Repository::parse).map(|repo| repo.with_id(id)) + }) + .collect() + }) .unwrap_or_default() } @@ -327,7 +335,10 @@ pub fn read_event(kind: &str, event: &Value) -> Result { let from_fork = head_repo.is_some() && head_repo != event["repository"]["full_name"].as_str(); let head = if from_fork { pr["head"]["label"].as_str() } else { pr["head"]["ref"].as_str() }; let (Some(repository), Some(head), Some(base), Some(merge)) = ( - event["repository"]["full_name"].as_str().and_then(Repository::parse), + event["repository"]["full_name"] + .as_str() + .and_then(Repository::parse) + .map(|r| r.with_id(event["repository"]["id"].as_i64().map(|i| i.to_string()))), head, pr["base"]["ref"].as_str(), pr["merge_commit_sha"].as_str(), diff --git a/server/src/forge/gitlab.rs b/server/src/forge/gitlab.rs index f7472bd5..d964e05f 100644 --- a/server/src/forge/gitlab.rs +++ b/server/src/forge/gitlab.rs @@ -278,7 +278,10 @@ pub async fn upsert_mr_note( /// # Errors /// `BadRequest` for a merged merge request without its branches or merge commit. pub fn read_event(kind: &str, event: &Value) -> Result { - let project = || event["project"]["web_url"].as_str().and_then(Repository::parse_gitlab); + let project = || { + let id = event["project"]["id"].as_i64().map(|i| i.to_string()); + event["project"]["web_url"].as_str().and_then(Repository::parse_gitlab).map(|r| r.with_id(id)) + }; let person = |v: &Value| v.as_i64().map(|i| vec![i.to_string()]).unwrap_or_default(); Ok(match kind { "Merge Request Hook" if event["object_attributes"]["action"] == "merge" => { @@ -371,6 +374,7 @@ pub async fn visibility( ) -> Result> { let project = get(settings, token, &format!("/projects/{}?license=true", project_id(path))).await?; Ok(project.map(|p| crate::forge::Visibility { + id: p["id"].as_i64().map(|i| i.to_string()), public: p["visibility"] == "public", licence: p["license"]["key"].as_str().map(|key| { crate::open_source::OSI_LICENCES diff --git a/server/src/mcp.rs b/server/src/mcp.rs index 4eed029c..e1cfb24c 100644 --- a/server/src/mcp.rs +++ b/server/src/mcp.rs @@ -1352,14 +1352,20 @@ impl VisualCi { )); } }; - project = - match crate::access::link_repository(&self.ctx, project, &user, &url, change.forge_token.as_deref()) - .await - { - Ok(p) => p, - Err(loco_rs::Error::BadRequest(m)) => return Ok(tool_error(m)), - Err(e) => return Err(internal(e)), - }; + project = match crate::access::link_repository( + &self.ctx, + project, + &user, + &url, + change.forge_token.as_deref(), + change.move_link, + ) + .await + { + Ok(p) => p, + Err(loco_rs::Error::BadRequest(m)) => return Ok(tool_error(m)), + Err(e) => return Err(internal(e)), + }; } if change.gallery_enabled == Some(false) && project.gallery_enabled { crate::workers::gallery_purge::purge_project_later(&self.ctx, &project).await.map_err(internal)?; diff --git a/server/src/models/_entities/projects.rs b/server/src/models/_entities/projects.rs index 3a42b7b9..ce8a014e 100644 --- a/server/src/models/_entities/projects.rs +++ b/server/src/models/_entities/projects.rs @@ -64,6 +64,9 @@ pub struct Model { pub notice: Option, /// Who linked the repository; the hourly sync checks they still maintain it. pub linked_by: Option, + /// The linked repository's permanent ID on its forge (`forge::Repository::id`). + #[sea_orm(column_type = "Text", nullable)] + pub repository_id: Option, pub created_at: DateTimeWithTimeZone, pub updated_at: DateTimeWithTimeZone, } diff --git a/server/src/models/projects.rs b/server/src/models/projects.rs index d28d1c29..80f4cf87 100644 --- a/server/src/models/projects.rs +++ b/server/src/models/projects.rs @@ -206,6 +206,10 @@ pub struct SettingsChange { /// with the `api` scope and the Developer role, or Maintainer to let VisualCI add its webhook), sent with /// `repository_url`. Stored encrypted; never shown again. pub forge_token: Option, + /// With `repository_url`: a repository belongs to one organization, so when another organization has it linked, + /// `true` moves the link here (you must maintain the repository; that organization's admins get an email). + #[serde(default)] + pub move_link: bool, /// `false` takes the public gallery down (visualci.yml's `gallery` decides what's in it); `true` puts it back. pub gallery_enabled: Option, /// `false`: project tokens can't approve changes (people do); `true` lets CI's agents approve again. diff --git a/server/src/notify.rs b/server/src/notify.rs index ad0ca006..e42d9fdb 100644 --- a/server/src/notify.rs +++ b/server/src/notify.rs @@ -62,6 +62,13 @@ pub enum Kind { MadePrivate { project: String, }, + /// A maintainer of the repository moved its link to their own organization: one organization per repository. + RepositoryMoved { + project: String, + repository: String, + to_org: String, + by: String, + }, Welcome { name: String, }, @@ -96,6 +103,7 @@ impl Kind { Self::PlanChanged { .. } => "plan_changed", Self::OpenSourceLost { .. } => "open_source_lost", Self::MadePrivate { .. } => "made_private", + Self::RepositoryMoved { .. } => "repository_moved", Self::Welcome { .. } => "welcome", Self::Invited { .. } => "invited", Self::AddedToOrg { .. } => "added_to_org", @@ -296,6 +304,21 @@ pub fn render(kind: &Kind, about: &About<'_>) -> Rendered { ], ("Project settings".into(), format!("{}/{}/{project}?tab=settings", about.app_url, about.org_slug)), ), + Kind::RepositoryMoved { project, repository, to_org, by } => ( + format!("{repository} moved to another organization"), + vec![ + format!( + "{by}, a maintainer of {repository}, linked it to their organization {to_org} on VisualCI. A \ + repository belongs to one organization, so {project} isn't linked to it any more: its builds \ + no longer post checks or comments there." + ), + format!( + "If that's wrong, a maintainer of {repository} can link it to {project} again from the project's \ + settings, which moves it back." + ), + ], + ("Project settings".into(), format!("{}/{}/{project}?tab=settings", about.app_url, about.org_slug)), + ), Kind::Welcome { name } => ( "Welcome to VisualCI".to_string(), vec![ @@ -824,6 +847,15 @@ pub fn samples() -> Vec<(&'static str, Kind)> { reason: "Its licence (BUSL-1.1) isn't OSI-approved.".into(), }), ("Project made private", Kind::MadePrivate { project: "widgets".into() }), + ( + "Repository moved", + Kind::RepositoryMoved { + project: "widgets".into(), + repository: "acme/widgets".into(), + to_org: "Acme".into(), + by: "Grace Hopper".into(), + }, + ), ("Welcome", Kind::Welcome { name: "Ada".into() }), ("Invitation", Kind::Invited { inviter: "Grace Hopper".into(), role: "member".into() }), ("Added to an organization", Kind::AddedToOrg { role: "admin".into() }), diff --git a/server/src/snapshots/visualci_server__notify__tests__email_texts.snap b/server/src/snapshots/visualci_server__notify__tests__email_texts.snap index f8415ce9..bf5437f8 100644 --- a/server/src/snapshots/visualci_server__notify__tests__email_texts.snap +++ b/server/src/snapshots/visualci_server__notify__tests__email_texts.snap @@ -121,6 +121,17 @@ Project settings: https://app.visualci.com/acme/widgets?tab=settings Questions? Reply to this email. +## Repository moved +Subject: acme/widgets moved to another organization + +Grace Hopper, a maintainer of acme/widgets, linked it to their organization Acme on VisualCI. A repository belongs to one organization, so widgets isn't linked to it any more: its builds no longer post checks or comments there. + +If that's wrong, a maintainer of acme/widgets can link it to widgets again from the project's settings, which moves it back. + +Project settings: https://app.visualci.com/acme/widgets?tab=settings + +Questions? Reply to this email. + ## Welcome Subject: Welcome to VisualCI diff --git a/server/tests/requests/access.rs b/server/tests/requests/access.rs index 79f8da95..010ae0ad 100644 --- a/server/tests/requests/access.rs +++ b/server/tests/requests/access.rs @@ -593,3 +593,86 @@ async fn an_existing_user_accepts_or_declines_an_invitation_and_only_admins_see_ }) .await; } + +/// Links follow the forge's permanent repository ID: a renamed repository is still the same one, a new repository that +/// takes the old name isn't, and a link whose ID isn't known yet still matches by URL (sc-8728). +#[tokio::test] +#[serial] +async fn links_follow_the_repository_id_through_a_rename() { + request::(|request, ctx| async move { + use visualci_server::{access, forge::Repository}; + let w = world(&request, &ctx).await; + let project = projects::Model::find_by_slugs(&ctx.db, &w.org.slug, "web").await.unwrap(); + let tag = &uuid::Uuid::new_v4().to_string()[..8]; + let id = format!("9{}", u32::from_str_radix(&tag[..6], 16).unwrap()); + let mut a = project.into_active_model(); + a.repository_id = Set(Some(id.clone())); + let project = a.update(&ctx.db).await.unwrap(); + + let path = w.repo.trim_start_matches("https://github.com/"); + let renamed = Repository::parse(&format!("{path}-renamed")).unwrap().with_id(Some(id.clone())); + let found = access::linked(&ctx.db, &renamed).await.unwrap(); + assert!(found.iter().any(|p| p.id == project.id), "renamed, same ID: still linked"); + let impostor = Repository::parse(path).unwrap().with_id(Some(format!("{id}0"))); + let found = access::linked(&ctx.db, &impostor).await.unwrap(); + assert!(found.iter().all(|p| p.id != project.id), "the old name, another repository: not linked"); + + // A link from before the ID was stored matches by URL until the sync fills it in. + let mut a = project.into_active_model(); + a.repository_id = Set(None); + let project = a.update(&ctx.db).await.unwrap(); + let by_url = Repository::parse(path).unwrap().with_id(Some(format!("{id}1"))); + assert!(access::linked(&ctx.db, &by_url).await.unwrap().iter().any(|p| p.id == project.id)); + }) + .await; +} + +/// A repository belongs to one organization: another organization's link is found and refused, naming the +/// organization that has it, and a maintainer can move it, which unlinks the other organization's project with a +/// notice and emails its admins. Projects in the same organization may share it (sc-8728). +#[tokio::test] +#[serial] +async fn a_repository_belongs_to_one_organization_and_its_link_can_move() { + request::(|request, ctx| async move { + use visualci_server::{access, forge::Repository}; + let w = world(&request, &ctx).await; + let repository = Repository::parse(w.repo.trim_start_matches("https://github.com/")).unwrap(); + // Another project of the same organization: fine. + assert!(access::linked_elsewhere(&ctx.db, &repository, w.org.id).await.unwrap().is_empty()); + + let tag = &uuid::Uuid::new_v4().to_string()[..8]; + let email = format!("mover-{tag}@example.com"); + request.post("/auth/dev-login").json(&serde_json::json!({ "email": email })).await; + let mover = visualci_server::models::users::Model::find_by_email(&ctx.db, &email).await.unwrap(); + let other = + organizations::Model::create_with_admin(&ctx.db, &format!("other-{tag}"), "Other", mover.id).await.unwrap(); + let elsewhere = access::linked_elsewhere(&ctx.db, &repository, other.id).await.unwrap(); + assert_eq!(elsewhere.len(), 1); + let message = access::linked_elsewhere_message(&ctx.db, &repository, &elsewhere).await.unwrap(); + assert!( + message.contains(&format!("is linked to Acme ({})", w.org.slug)) && message.contains("Move it here"), + "{message}" + ); + + access::move_links_here(&ctx, elsewhere, &repository, other.id, &mover).await.unwrap(); + let old = projects::Model::find_by_slugs(&ctx.db, &w.org.slug, "web").await.unwrap(); + assert!(old.repository_url.is_none() && old.forge_installation.is_none(), "unlinked"); + assert!(old.notice.as_deref().is_some_and(|n| n.contains("moved") && n.contains("Other")), "{:?}", old.notice); + let emailed: Vec = { + use sea_orm::ConnectionTrait; + ctx.db + .query_all_raw(sea_orm::Statement::from_sql_and_values( + sea_orm::DbBackend::Postgres, + "SELECT recipient FROM emails WHERE organization_id = $1 AND kind = 'repository_moved'", + [w.org.id.into()], + )) + .await + .unwrap() + .iter() + .map(|r| r.try_get("", "recipient").unwrap()) + .collect() + }; + assert!(emailed.contains(&w.admin_email), "the old organization's admin is told: {emailed:?}"); + }) + .await; +} diff --git a/server/tests/requests/open_source.rs b/server/tests/requests/open_source.rs index 48aae692..21eb58d7 100644 --- a/server/tests/requests/open_source.rs +++ b/server/tests/requests/open_source.rs @@ -36,7 +36,7 @@ fn answer( } fn repo(public: bool, licence: Option<&str>) -> Result> { - Ok(Some(Visibility { public, licence: licence.map(str::to_string) })) + Ok(Some(Visibility { id: None, public, licence: licence.map(str::to_string) })) } async fn new_org(request: &axum_test::TestServer, ctx: &AppContext) -> organizations::Model {