Skip to content
Closed
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
20 changes: 20 additions & 0 deletions app/src/forge/github_app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,26 @@ pub async fn installation_exists(app: &GithubApp, id: &str) -> laravel::Result<b
Ok(get(&app_jwt(app)?, &format!("/app/installations/{id}")).await?.is_some())
}

/// Where people install the App on their repositories.
pub const INSTALL_URL: &str = "https://github.com/apps/visualci-com/installations/new";

/// The App's installation that reaches a repository (`owner/name`), if it's installed there.
///
/// # Errors
/// When the App isn't configured, or GitHub can't be reached or refuses.
pub async fn installation_for(app: &GithubApp, repo: &str) -> laravel::Result<Option<String>> {
Ok(get(&app_jwt(app)?, &format!("/repos/{repo}/installation"))
.await?
.and_then(|v| v["id"].as_i64())
.map(|i| i.to_string()))
}

/// Whether the App is configured (its ID and private key).
#[must_use]
pub fn configured(app: &GithubApp) -> bool {
app.app_id.is_some() && app.private_key_base64.is_some()
}

/// Below this many API calls left in the hour, a recheck stops instead of using up what webhooks and checks need.
pub const RATE_LIMIT_RESERVE: i64 = 500;

Expand Down
77 changes: 77 additions & 0 deletions app/src/forge/gitlab.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,3 +156,80 @@ fn level_of(project: &Value) -> i64 {
.max()
.unwrap_or(0)
}

/// VisualCI's bot user on the GitLab of [`GitlabConfig`] (`VISUALCI_GITLAB_BOT_TOKEN`, a personal access token with
/// the `api` scope). GitLab has no app installations: a project gives VisualCI access by adding the bot as a member,
/// and every server-side call about it (access checks, commit statuses, merge request notes) uses the bot's token.
#[derive(Clone, laravel::config::Section)]
pub struct GitlabBot {
#[env("VISUALCI_GITLAB_BOT_TOKEN")]
pub token: Option<String>,
/// The bot's username, for telling people whom to invite.
#[env("VISUALCI_GITLAB_BOT_USERNAME", default = "visualci")]
pub username: String,
}

/// The `installation` of a project VisualCI reaches through its bot.
pub const BOT: &str = "bot";

/// A project's ID for the API: its path, URL-encoded (`group%2Fsub%2Fproject`).
fn project_id(path: &str) -> String {
url::form_urlencoded::byte_serialize(path.as_bytes()).collect()
}

/// GET an API path (`/projects/...`) as JSON; `None` on 404.
async fn get(base: &str, token: &str, path: &str) -> laravel::Result<Option<Value>> {
let base = base.trim_end_matches('/');
let response = client::get(format!("{base}/api/v4{path}")).token(token).accept_json().await?;
if response.status() == 404 {
return Ok(None);
}
if !response.successful() {
return Err(laravel::Error::msg(format!("GitLab GET {path}: HTTP {}", response.status())));
}
Ok(Some(response.json()?))
}

/// The bot's access level on a project (`group/sub/project`), when it's a member.
///
/// # Errors
/// When GitLab can't be reached or refuses the bot's token.
pub async fn bot_level(base: &str, token: &str, path: &str) -> laravel::Result<Option<i64>> {
Ok(get(base, token, &format!("/projects/{}", project_id(path))).await?.map(|p| level_of(&p)).filter(|l| *l > 0))
}

/// The bot's access to a project as an installation: a Developer or higher can post statuses and notes.
///
/// # Errors
/// When GitLab can't be reached or refuses the bot's token.
pub async fn installation_for(base: &str, token: &str, path: &str) -> laravel::Result<Option<String>> {
Ok(bot_level(base, token, path).await?.filter(|l| *l >= 30).map(|_| BOT.to_string()))
}

/// A person's permission on a project, inherited access included, by their permanent GitLab user ID.
///
/// # Errors
/// When GitLab can't be reached or refuses the token.
pub async fn permission(base: &str, token: &str, path: &str, user_id: &str) -> laravel::Result<Option<Permission>> {
let Ok(user_id) = user_id.parse::<i64>() else { return Ok(None) };
let member = get(base, token, &format!("/projects/{}/members/all/{user_id}", project_id(path))).await?;
Ok(member.and_then(|m| m["access_level"].as_i64()).and_then(permission_from_level))
}

/// A project's permanent ID (`None` when the token can't see it).
///
/// # Errors
/// When GitLab can't be reached or refuses the token.
pub async fn repository_id(base: &str, token: &str, path: &str) -> laravel::Result<Option<String>> {
Ok(get(base, token, &format!("/projects/{}", project_id(path)))
.await?
.and_then(|p| p["id"].as_i64())
.map(|i| i.to_string()))
}

/// How a project gives VisualCI access: invite the bot as a Developer.
#[must_use]
pub fn install_hint(base: &str, bot: &str, path: &str) -> String {
let base = base.trim_end_matches('/');
format!("invite @{bot} to {path} as a Developer ({base}/{path}/-/project_members), then link it")
}
261 changes: 261 additions & 0 deletions app/src/forge/link.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,261 @@
//! Linking a project to its repository (sc-8900, the forge side), ported from today's `access::link_repository`.
//!
//! A link is what lets VisualCI post a project's checks and pull request comments, and what its open source status is
//! checked against, so only an admin or maintainer of the repository on the forge may make one: someone else's
//! repository can't be given checks or access. A repository belongs to one organization (several of its projects may
//! link it); a maintainer can move it from another organization, whose admins are told.
//!
//! GitHub needs the VisualCI GitHub App installed on the repository; GitLab (gitlab.com, or the instance
//! `VISUALCI_GITLAB_URL` names) needs VisualCI's bot as a Developer on the project. Self-managed instances that
//! organizations add are a later port: until then their URLs are refused as unknown.

use laravel::db;

use super::github_app::{self, GithubApp};
use super::gitlab::{self, GitlabBot, GitlabConfig};
use super::{ForgeKind, Permission, Repository};
use crate::models::{Project, User};
use crate::notify::{self, Kind, To};

fn bad(message: impl Into<String>) -> laravel::Error {
laravel::abort_with(400, message.into())
}

/// What linking learns from the forge: how VisualCI reaches the repository, the person's permission on it, and the
/// forge's permanent ID for it.
struct Reached {
installation: String,
permission: Option<Permission>,
repository_id: Option<String>,
}

/// Link `project` to the repository at `url` for `by`, or unlink it when `url` is empty. Returns the project as it is
/// now. `token` is for self-managed GitLab projects (not ported yet) and is ignored. `move_link` moves a repository
/// linked in another organization here; without it that's refused, naming the organization.
///
/// Errors are 400s that say what's missing: the forge isn't set up on this server, the URL isn't a repository
/// VisualCI knows, the App or bot can't reach it, `by` hasn't signed in with that forge, or isn't an admin or
/// maintainer of it there. The caller checks that `by` is an admin of the project's organization.
///
/// # Errors
/// Those; forge and database errors.
pub async fn link_repository(
project: Project,
by: &User,
url: &str,
token: Option<&str>,
move_link: bool,
) -> laravel::Result<Project> {
let _ = token;
let config = laravel::config();
let github = config.get::<GithubApp>().cloned().ok_or_else(|| laravel::Error::msg("no GitHub App config"))?;
let id = project.id;
if url.trim().is_empty() {
db::query!(
"UPDATE projects SET forge = NULL, repository_url = NULL, repository_id = NULL, forge_installation = NULL, \
forge_token_enc = NULL, forge_webhook_at = NULL, updated_at = now() WHERE id = {id}"
)
.update()
.await?;
// Unlinked: a project without a public repository can't stay public
super::open_source::refresh(&github, id).await?;
return reload(id).await;
}
let repository = Repository::parse(url).ok_or_else(|| {
bad(format!(
"{url:?} isn't a repository URL VisualCI knows: https://github.com/owner/name, \
https://gitlab.com/group/project, or a project on a GitLab instance this organization added"
))
})?;
let label = repository.forge.label();
let identity = |site: &str| identity_of(by.id, repository.forge, site.to_string());
let reached = match repository.forge {
ForgeKind::Github => {
if !github_app::configured(&github) {
return Err(bad(format!("{label} isn't set up on this server")));
}
let Some(installation) = github_app::installation_for(&github, &repository.path).await? else {
return Err(bad(format!(
"VisualCI can't reach {} on {label} yet: install the VisualCI GitHub App on it at {}, then link it",
repository.path,
github_app::INSTALL_URL
)));
};
let forge_user = identity("").await?.ok_or_else(|| signed_out(label, &repository))?;
let permission = github_app::permission(&github, &repository.path, &installation, &forge_user).await?;
let token = github_app::installation_token(&github, &installation).await?;
let repository_id = github_app::repository_id(&token, &repository.path).await.unwrap_or_else(|e| {
tracing::warn!(repo = repository.path, error = %e, "reading the repository's ID");
None
});
Reached { installation, permission, repository_id }
}
ForgeKind::Gitlab => {
let (Some(gitlab), Some(bot)) = (config.get::<GitlabConfig>(), config.get::<GitlabBot>()) else {
return Err(bad(format!("{label} isn't set up on this server")));
};
let base = gitlab.url.trim_end_matches('/');
// A project on another GitLab is one an organization added: not ported yet
let (true, Some(token)) = (repository.site_url().eq_ignore_ascii_case(base), bot.token.as_deref()) else {
return Err(bad(format!("{label} isn't set up on this server")));
};
let Some(installation) = gitlab::installation_for(base, token, &repository.path).await? else {
return Err(bad(format!(
"VisualCI can't reach {} on {label} yet: {}",
repository.path,
gitlab::install_hint(base, &bot.username, &repository.path)
)));
};
let forge_user = identity(&gitlab::site_of(base)).await?.ok_or_else(|| signed_out(label, &repository))?;
let permission = gitlab::permission(base, token, &repository.path, &forge_user).await?;
let repository_id = gitlab::repository_id(base, token, &repository.path).await.unwrap_or_else(|e| {
tracing::warn!(repo = repository.path, error = %e, "reading the repository's ID");
None
});
Reached { installation, permission, repository_id }
}
};
if !reached.permission.is_some_and(|p| p >= Permission::Maintain) {
return Err(bad(format!(
"only an admin or maintainer of {} on {label} can link it (you're {})",
repository.path,
reached.permission.map_or("not a collaborator".to_string(), |p| format!("{p:?}").to_lowercase())
)));
}
let repository = repository.with_id(reached.repository_id.clone());
let elsewhere = linked_elsewhere(&repository, project.organization_id).await?;
if !elsewhere.is_empty() {
if !move_link {
return Err(bad(linked_elsewhere_message(&repository, &elsewhere).await?));
}
move_links_here(&github, &elsewhere, &repository, project.organization_id, by).await?;
}
let (forge, repo_url, repo_id, installation, user_id) =
(repository.forge.as_str(), repository.url.clone(), reached.repository_id, reached.installation, by.id);
db::query!(
"UPDATE projects SET forge = {forge}, repository_url = {repo_url}, repository_id = {repo_id}, \
forge_installation = {installation}, forge_token_enc = NULL, forge_webhook_at = NULL, \
linked_by = {user_id}, updated_at = now() WHERE id = {id}"
)
.update()
.await?;
tracing::info!(project_id = id, repo = repository.path, by = by.id, "repository linked");
// Linking checks the repository at once: public or not, and whether it's open source
super::open_source::refresh(&github, id).await?;
reload(id).await
}

async fn reload(id: i64) -> laravel::Result<Project> {
Project::find(id).await?.ok_or_else(|| laravel::abort(404))
}

fn signed_out(label: &str, repository: &Repository) -> laravel::Error {
bad(format!("sign in with {label} first, to show you can manage {}", repository.path))
}

/// The person's permanent user ID on a forge (`site` is '' for github.com and gitlab.com).
async fn identity_of(user_id: i64, forge: ForgeKind, site: String) -> laravel::Result<Option<String>> {
let forge = forge.as_str();
db::query!(
"SELECT forge_user_id FROM identities WHERE user_id = {user_id} AND forge = {forge} AND site = {site} \
ORDER BY id LIMIT 1"
)
.scalar()
.await
}

/// A project of another organization that links the repository.
pub struct Elsewhere {
pub project_id: i64,
pub slug: String,
pub organization_id: i64,
}

/// Projects in organizations other than `organization_id` linking this repository: by the forge's ID when it's
/// known, and by URL only for links whose ID isn't known yet. A deleted repository's name taken by a new one (a new
/// ID) isn't the same repository, and its old links mustn't be moved or told.
///
/// # Errors
/// On a database error.
pub async fn linked_elsewhere(repository: &Repository, organization_id: i64) -> laravel::Result<Vec<Elsewhere>> {
let (forge, url, repo_id) = (repository.forge.as_str(), repository.url.to_lowercase(), repository.id.clone());
let rows = db::query!(
"SELECT id, slug, organization_id FROM projects WHERE forge = {forge} AND organization_id <> {organization_id} \
AND ((repository_id IS NOT NULL AND repository_id = {repo_id}) \
OR ((repository_id IS NULL OR {repo_id}::text IS NULL) AND lower(repository_url) = {url})) \
ORDER BY id"
)
.select()
.await?;
rows.iter()
.map(|r| {
Ok(Elsewhere {
project_id: r.try_get("id")?,
slug: r.try_get("slug")?,
organization_id: r.try_get("organization_id")?,
})
})
.collect()
}

/// Why a link is refused: which organization has the repository, and how to move it.
async fn linked_elsewhere_message(repository: &Repository, elsewhere: &[Elsewhere]) -> laravel::Result<String> {
let there = match elsewhere.first() {
Some(p) => {
let org = p.organization_id;
let row = db::query!("SELECT name, slug FROM organizations WHERE id = {org}").select_one().await?;
match row {
Some(r) => format!("{} ({})", r.try_get::<String>("name")?, r.try_get::<String>("slug")?),
None => "another organization".to_string(),
}
}
None => "another organization".to_string(),
};
Ok(format!(
"{} is linked to {there} on VisualCI, and a repository belongs to one organization. As a maintainer of it, you \
can move the link here: Move it here in the web app, or update_project with move_link over MCP. {there}'s \
admins get an email saying so.",
repository.path
))
}

/// Move a repository's links from other organizations' projects to `organization_id`: those projects are unlinked
/// with a notice saying who moved it, and their organizations' admins get an email. The caller has checked, with the
/// forge, that `by` maintains the repository.
async fn move_links_here(
github: &GithubApp,
elsewhere: &[Elsewhere],
repository: &Repository,
organization_id: i64,
by: &User,
) -> laravel::Result<()> {
let to_org: Option<String> =
db::query!("SELECT name FROM organizations WHERE id = {organization_id}").scalar().await?;
let to_org = to_org.unwrap_or_default();
let now = laravel::now().timestamp().as_second();
for p in elsewhere {
let (id, from) = (p.project_id, p.organization_id);
let notice = format!(
"{} moved {} to {to_org}: a repository belongs to one organization, so this project isn't linked to it any \
more.",
by.name, repository.path
);
db::query!(
"UPDATE projects SET forge = NULL, repository_url = NULL, repository_id = NULL, forge_installation = NULL, \
forge_token_enc = NULL, forge_webhook_at = NULL, linked_by = NULL, notice = {notice}, \
updated_at = now() WHERE id = {id}"
)
.update()
.await?;
tracing::info!(repo = repository.path, from, to = organization_id, "repository link moved");
super::open_source::refresh(github, id).await?;
let kind = Kind::RepositoryMoved {
project: p.slug.clone(),
repository: repository.path.clone(),
to_org: to_org.clone(),
by: by.name.clone(),
};
notify::queue(&kind, To::Admins(from), None, &format!("repository_moved:{id}:{now}")).await?;
}
Ok(())
}
1 change: 1 addition & 0 deletions app/src/forge/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ pub mod events;
pub mod github;
pub mod github_app;
pub mod gitlab;
pub mod link;
pub mod open_source;
pub mod sync;
pub mod webhooks;
Expand Down
Loading
Loading