Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion server/frontend/content/docs/reference/access.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
| --- | --- |
Expand Down
2 changes: 1 addition & 1 deletion server/frontend/src/api/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ export function useCreateProject(org: string) {
export function useUpdateProject(org: string, project: string) {
const qc = useQueryClient()
return useMutation({
mutationFn: (v: Partial<ProjectSettings> & { forge_token?: string; dismiss_notice?: boolean }) =>
mutationFn: (v: Partial<ProjectSettings> & { forge_token?: string; dismiss_notice?: boolean; move_link?: boolean }) =>
patch<ProjectSettings>(projectPath(org, project), v),
onSuccess: (settings) => {
qc.setQueryData<ProjectData>(keys.project(org, project), (d) => (d ? { ...d, project: settings } : d))
Expand Down
33 changes: 23 additions & 10 deletions server/frontend/src/pages/ProjectPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<ProjectSettings> & { forge_token?: string } = rulesChanged
const changes: Partial<ProjectSettings> & { 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
Expand All @@ -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 (
<form
className="settings"
onSubmit={(e) => {
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 && <p className="hint">Only the organization’s admins can change these settings.</p>}
Expand Down Expand Up @@ -754,6 +758,15 @@ function Settings({
)}
{saved && !dirty && <span className="muted">Saved</span>}
{update.isError && <span className="field-error">{errorMessage(update.error)}</span>}
{linkedElsewhere && (
<Button
variant="ghost"
loading={update.isPending}
onClick={() => update.mutate({ ...changes, repository_url: draft.repository_url ?? '', move_link: true }, saveCallbacks)}
>
Move it here
</Button>
)}
</div>
</form>
)
Expand Down
2 changes: 2 additions & 0 deletions server/migration/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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)
]
}
Expand Down
30 changes: 30 additions & 0 deletions server/migration/src/m20261202_000039_repository_id.rs
Original file line number Diff line number Diff line change
@@ -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(())
}
}
138 changes: 131 additions & 7 deletions server/src/access.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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},
},
Expand Down Expand Up @@ -88,12 +88,19 @@ async fn site_scope(

/// Projects linked to one repository.
pub async fn linked(db: &impl ConnectionTrait, repository: &Repository) -> Result<Vec<projects::Model>> {
// 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?)
}
Expand Down Expand Up @@ -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.
Expand All @@ -435,12 +444,14 @@ pub async fn link_repository(
user: &users::Model,
url: &str,
token: Option<&str>,
move_link: bool,
) -> Result<projects::Model> {
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);
Expand Down Expand Up @@ -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() {
Expand All @@ -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<Vec<projects::Model>> {
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<String> {
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<projects::Model>,
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
Expand All @@ -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()
Expand Down Expand Up @@ -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?;
Expand Down
2 changes: 1 addition & 1 deletion server/src/controllers/ui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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?;
Expand Down
Loading
Loading