From 8d02d40bef1a9fabf05c588ce525a424f4d911e6 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 18:18:43 +1300 Subject: [PATCH 1/2] =?UTF-8?q?app/:=20onboarding=20through=20the=20GitHub?= =?UTF-8?q?=20App=20(sc-9027,=20PR=201):=20installations=20recorded=20from?= =?UTF-8?q?=20sign-ins=20and=20webhooks;=20GET=20/github/setup=20maps=20an?= =?UTF-8?q?=20installation=20to=20an=20organization=20and=20makes=20a=20pr?= =?UTF-8?q?oject=20per=20repository=20the=20person=20can=20maintain;=20no?= =?UTF-8?q?=20Default=20project;=20checklist=20install=5Fgithub=5Fapp=20?= =?UTF-8?q?=E2=86=92=20add=5Fto=5Fci=20=E2=86=92=20connect=5Fagent=20?= =?UTF-8?q?=E2=86=92=20review=5Fchanges?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../2026_12_03_100000_github_installations.rs | 45 ++ app/src/auth/installations.rs | 106 ++++ app/src/auth/mod.rs | 2 + app/src/auth/setup.rs | 39 +- app/src/auth/sign_in.rs | 4 + app/src/forge/github.rs | 32 +- app/src/forge/github_app.rs | 60 ++ app/src/forge/gitlab.rs | 1 + app/src/forge/installations.rs | 545 ++++++++++++++++++ app/src/forge/mod.rs | 15 + app/src/forge/webhooks.rs | 10 +- app/src/listeners/mod.rs | 2 +- app/src/models/organizations.rs | 18 +- .../get_organization.json | 17 +- .../whoami.json | 17 +- .../get_organization.json | 17 +- .../get_organization.json | 17 +- app/tests/installations.rs | 291 ++++++++++ app/tests/organizations.rs | 6 +- app/tests/setup.rs | 12 +- docs/design.md | 12 + 21 files changed, 1199 insertions(+), 69 deletions(-) create mode 100644 app/database/migrations/2026_12_03_100000_github_installations.rs create mode 100644 app/src/auth/installations.rs create mode 100644 app/src/forge/installations.rs create mode 100644 app/tests/installations.rs diff --git a/app/database/migrations/2026_12_03_100000_github_installations.rs b/app/database/migrations/2026_12_03_100000_github_installations.rs new file mode 100644 index 00000000..a5a3927b --- /dev/null +++ b/app/database/migrations/2026_12_03_100000_github_installations.rs @@ -0,0 +1,45 @@ +//! GitHub App installations (sc-9027, onboarding). +//! +//! `github_installations` is every installation of the VisualCI GitHub App VisualCI has heard of, from a person's +//! sign-in (GitHub lists the installations they can reach) or from the `installation` webhook, and the organization +//! it was set up for once someone has. `user_installations` is which installations each person can reach, as of their +//! last sign-in: the setup page and the checklist's "already installed on X" offers read it. + +use laravel::db::AnyTransaction; + +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.query(SCHEMA).unprepared().await?; + Ok(()) +} + +const SCHEMA: &str = r#" +CREATE TABLE github_installations ( + id BIGSERIAL PRIMARY KEY, + -- GitHub's ID for the installation, as text like projects.forge_installation. + installation_id TEXT NOT NULL UNIQUE, + -- The account it's installed on: GitHub's ID, login and type ("User" or "Organization"). + account_id TEXT NOT NULL, + account_login TEXT NOT NULL, + account_type TEXT NOT NULL, + -- The organization it was set up for: none until someone sets it up. + organization_id BIGINT REFERENCES organizations(id) ON DELETE SET NULL, + set_up_by BIGINT REFERENCES users(id) ON DELETE SET NULL, + suspended_at TIMESTAMPTZ, + -- Removed on GitHub. Kept so the account's organization is found again if the App is installed again. + deleted_at TIMESTAMPTZ, + -- What the last set-up did (projects made, repositories skipped and why), for the organization's page. + setup_result JSONB, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE INDEX github_installations_organization ON github_installations (organization_id); +CREATE INDEX github_installations_account ON github_installations (account_id); + +CREATE TABLE user_installations ( + user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + installation_id TEXT NOT NULL REFERENCES github_installations(installation_id) ON DELETE CASCADE, + seen_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (user_id, installation_id) +); +CREATE INDEX user_installations_installation ON user_installations (installation_id); +"#; diff --git a/app/src/auth/installations.rs b/app/src/auth/installations.rs new file mode 100644 index 00000000..b38aa918 --- /dev/null +++ b/app/src/auth/installations.rs @@ -0,0 +1,106 @@ +//! Setting up the GitHub App from the app (sc-9027, onboarding). +//! +//! - `GET /github/setup?installation_id=…` is the GitHub App's Setup URL: GitHub sends people there after they +//! install it. Someone signed out signs in first and comes back; an installation their account can't reach yet +//! sends them through GitHub's sign-in once more, which refreshes the list. Then [`set_up`] gives it an organization +//! and projects, and they land on the organization's page with the next step (adding VisualCI to CI) open. +//! - `POST /api/ui/installations/{id}/setup` does the same for an installation the checklist offers ("already +//! installed on X: set it up"), and answers what it did as JSON. + +use laravel::auth::{Auth, Authenticated}; +use laravel::prelude::*; + +use crate::forge::github_app::GithubApp; +use crate::forge::installations::{self, SetUp}; +use crate::models::User; + +pub fn routes(route: &mut Router) { + route.get("/github/setup", setup_page); + route.post("/api/ui/installations/{id}/setup", setup); +} + +#[laravel::query] +pub struct SetupQuery { + installation_id: Option, + /// Set on the way back from the sign-in that refreshed their installations, so it happens once. + refreshed: Option, +} + +/// Where the organization's page opens after a set-up: the next step, adding VisualCI to CI. +#[must_use] +pub fn landing(outcome: &SetUp) -> String { + format!("/{}?setup=add_to_ci&installation={}", outcome.organization, outcome.installation_id) +} + +/// Back to this page after signing in with GitHub. The ID is digits only, so it's safe in the URL as it is. +fn through_sign_in(installation_id: &str) -> Redirect { + Redirect::to(format!( + "/auth/github?return_to=%2Fgithub%2Fsetup%3Finstallation_id%3D{installation_id}%26refreshed%3D1" + )) +} + +/// `GET /github/setup`: GitHub's redirect after someone installs the App. +pub async fn setup_page( + auth: Auth, + app: laravel::config::Section, + Query(q): Query, +) -> laravel::Result { + // GitHub sends no installation ID when an organization's owner still has to approve the request + let Some(id) = + q.installation_id.filter(|i| !i.is_empty() && i.len() <= 20 && i.bytes().all(|b| b.is_ascii_digit())) + else { + return Ok(page( + "Waiting for GitHub", + "GitHub hasn't installed the VisualCI GitHub App yet: an owner of the organization may need to approve \ + the request. Once they have, come back and set it up from your organization's page.", + )); + }; + let Some(user) = auth.user().await? else { return Ok(laravel::http::Response::new(through_sign_in(&id))) }; + if !installations::reachable(user.id, &id).await? { + if q.refreshed.is_none() { + return Ok(laravel::http::Response::new(through_sign_in(&id))); + } + return Ok(page( + "That installation isn't yours", + "Your GitHub account can't reach this installation of the VisualCI GitHub App. Sign in to VisualCI with \ + the GitHub account that installed it.", + )); + } + match installations::set_up(&app, &user, &id).await { + Ok(outcome) => Ok(laravel::http::Response::new(Redirect::to(landing(&outcome)))), + Err(e) if e.status().is_client_error() => Ok(page("Couldn't set VisualCI up", &e.to_string())), + Err(e) => Err(e), + } +} + +/// `POST /api/ui/installations/{id}/setup`: set up an installation the person can reach. Answers what it did, and +/// where to go next (`landing`). +pub async fn setup( + Authenticated(user): Authenticated, + app: laravel::config::Section, + Params(id): Params, +) -> laravel::Result> { + if id.is_empty() || id.len() > 20 || !id.bytes().all(|b| b.is_ascii_digit()) { + return Err(laravel::abort(404)); + } + let outcome = installations::set_up(&app, &user, &id).await?; + let mut body = serde_json::to_value(&outcome).map_err(|e| laravel::Error::msg(e.to_string()))?; + body["landing"] = landing(&outcome).into(); + Ok(Json(body)) +} + +/// A one-message page, in the sign-in page's style. +fn page(title: &str, message: &str) -> laravel::http::Response { + let esc = |s: &str| s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """); + let html = format!( + "{t} · VisualCI
\ +

{t}

{m}

Go to VisualCI

", + t = esc(title), + m = esc(message) + ); + laravel::http::Response::new(laravel::view::Html::raw(html)) +} diff --git a/app/src/auth/mod.rs b/app/src/auth/mod.rs index 63998074..c9abef5a 100644 --- a/app/src/auth/mod.rs +++ b/app/src/auth/mod.rs @@ -9,6 +9,7 @@ //! Nobody found: `401`. pub mod device; +pub mod installations; pub mod invitations; pub mod me; pub mod memberships; @@ -281,6 +282,7 @@ pub fn routes(route: &mut laravel::prelude::Router) { route.get("/auth/providers", sign_in::providers); route.post("/auth/logout", sign_in::logout); setup::routes(route); + installations::routes(route); // Anything else on the web group is a page of the React app route.fallback(crate::http::app_shell::app_shell); } diff --git a/app/src/auth/setup.rs b/app/src/auth/setup.rs index f9a9bac3..76d4f380 100644 --- a/app/src/auth/setup.rs +++ b/app/src/auth/setup.rs @@ -13,8 +13,8 @@ pub fn routes(route: &mut Router) { route.post("/api/ui/orgs/{org}/setup", update); } -/// The steps, in order. -pub const STEPS: &[&str] = &["connect_agent", "create_project", "install_github_app", "add_to_ci", "review_changes"]; +/// The steps, in order. Installing the GitHub App makes the projects (sc-9027), so it comes first. +pub const STEPS: &[&str] = &["install_github_app", "add_to_ci", "connect_agent", "review_changes"]; /// The checklist for an organization as `user_pid` sees it (a connected agent is per person: an MCP connection, or a /// personal token that has been used; with no person, such as a project token, it isn't done): each step and whether @@ -32,8 +32,8 @@ pub async fn state(org_id: i64, user_pid: Option) -> laravel EXISTS (SELECT 1 FROM oauth_tokens t WHERE t.subject = {subject}) \ OR EXISTS (SELECT 1 FROM user_tokens ut JOIN users u ON u.id = ut.user_id \ WHERE u.pid = {subject}::uuid AND ut.last_used_at IS NOT NULL)) AS connect_agent, \ - EXISTS (SELECT 1 FROM projects WHERE organization_id = {org_id}) AS create_project, \ - EXISTS (SELECT 1 FROM projects WHERE organization_id = {org_id} AND forge_installation IS NOT NULL) \ + (EXISTS (SELECT 1 FROM projects WHERE organization_id = {org_id} AND forge_installation IS NOT NULL) \ + OR EXISTS (SELECT 1 FROM github_installations WHERE organization_id = {org_id} AND deleted_at IS NULL)) \ AS install_github_app, \ EXISTS (SELECT 1 FROM builds b JOIN projects p ON p.id = b.project_id \ WHERE p.organization_id = {org_id} AND b.mode = 'ci') AS add_to_ci, \ @@ -50,11 +50,42 @@ pub async fn state(org_id: i64, user_pid: Option) -> laravel } let next = steps.iter().find(|(_, done)| !done).map(|(key, _)| *key); let complete = steps.last().is_some_and(|(_, done)| *done); + // The person's installations of the App (an offer to set one up that isn't yet), and what setting up this + // organization's installations did (the repositories they couldn't add, and why) + let offers = match &subject { + Some(pid) => { + let user_id: Option = db::query!("SELECT id FROM users WHERE pid = {pid}::uuid").scalar().await?; + match user_id { + Some(id) => crate::forge::installations::offers(id).await?, + None => Vec::new(), + } + } + None => Vec::new(), + }; + let set_up = db::query!( + "SELECT installation_id, account_login, setup_result::text AS result FROM github_installations \ + WHERE organization_id = {org_id} AND deleted_at IS NULL ORDER BY lower(account_login)" + ) + .select() + .await? + .iter() + .map(|r| { + let result: Option = r.try_get("result")?; + Ok(json!({ + "installation_id": r.try_get::("installation_id")?, + "account_login": r.try_get::("account_login")?, + "result": result.and_then(|t| serde_json::from_str::(&t).ok()), + })) + }) + .collect::>>()?; Ok(json!({ "steps": steps.iter().map(|(key, done)| json!({ "key": key, "done": done })).collect::>(), "next": next, "complete": complete, "dismissed": row.try_get::>("dismissed")?.unwrap_or(false), + "install_url": crate::forge::github_app::INSTALL_URL, + "installations": offers, + "github": set_up, })) } diff --git a/app/src/auth/sign_in.rs b/app/src/auth/sign_in.rs index 135ff20d..efeb03b8 100644 --- a/app/src/auth/sign_in.rs +++ b/app/src/auth/sign_in.rs @@ -146,6 +146,10 @@ pub async fn callback( if created { SignedUp { user_id: user.id, via: via.clone() }.dispatch().await?; } + // The GitHub App's installations they can reach, for the setup page and the checklist's offers + if sign_in.identity.forge == ForgeKind::Github { + forge::installations::remember(user.id, &sign_in.installations).await?; + } SignedIn { user_id: user.id, forge: sign_in.identity.forge, diff --git a/app/src/forge/github.rs b/app/src/forge/github.rs index b0dcb84f..f3f3c46a 100644 --- a/app/src/forge/github.rs +++ b/app/src/forge/github.rs @@ -6,7 +6,7 @@ use laravel::http::client; use serde::Deserialize; use serde_json::Value; -use super::{ForgeKind, Identity, Permission, Repository, SignIn}; +use super::{ForgeKind, Identity, Installation, Permission, Repository, SignIn}; const API: &str = "https://api.github.com"; @@ -19,6 +19,7 @@ pub async fn sign_in(profile: &laravel::auth::social::User) -> laravel::Result laravel::Result laravel::Result> { Ok(emails.into_iter().map(|e| e.email.to_lowercase()).collect()) } -/// Every repository the GitHub App can see through its installations that the person has a permission on. -async fn repositories(token: &str) -> laravel::Result> { +/// The App's installations the person can reach, and every repository the App can see through them that the person +/// has a permission on. +async fn installations(token: &str) -> laravel::Result<(Vec, Vec<(Repository, Permission)>)> { + let mut found = Vec::new(); let mut out = Vec::new(); - for installation in all_pages(token, "/user/installations", "installations").await? { - let Some(installation) = installation["id"].as_i64() else { continue }; + for item in all_pages(token, "/user/installations", "installations").await? { + let Some(installation) = item["id"].as_i64() else { continue }; + if let Some(account) = installation_account(installation.to_string(), &item["account"]) { + found.push(account); + } let path = format!("/user/installations/{installation}/repositories"); for repo in all_pages(token, &path, "repositories").await? { let (Some(repository), Some(permission)) = @@ -67,7 +74,18 @@ async fn repositories(token: &str) -> laravel::Result Option { + Some(Installation { + id, + account_id: account["id"].as_i64()?.to_string(), + account_login: account["login"].as_str()?.to_string(), + account_type: account["type"].as_str().unwrap_or("User").to_string(), + }) } /// Every item of a paged list (`key` in each page's object), 100 a page, up to 50 pages. diff --git a/app/src/forge/github_app.rs b/app/src/forge/github_app.rs index 1707cd50..50c031b1 100644 --- a/app/src/forge/github_app.rs +++ b/app/src/forge/github_app.rs @@ -91,6 +91,66 @@ pub async fn installation_exists(app: &GithubApp, id: &str) -> laravel::Result laravel::Result> { + if !id.bytes().all(|b| b.is_ascii_digit()) { + return Ok(None); + } + get(&app_jwt(app)?, &format!("/app/installations/{id}")).await +} + +/// A repository an installation was granted: `owner/name`, GitHub's ID for it, and whether it's archived. +pub struct Granted { + pub full_name: String, + pub id: Option, + pub archived: bool, +} + +/// Every repository an installation was granted (with its token), up to `limit`. +/// +/// # Errors +/// When GitHub can't be reached or refuses. +pub async fn installation_repositories(token: &str, limit: usize) -> laravel::Result> { + let mut out = Vec::new(); + for page in 1..=50 { + let Some(body) = get(token, &format!("/installation/repositories?per_page=100&page={page}")).await? else { + break; + }; + let items = body["repositories"].as_array().cloned().unwrap_or_default(); + let n = items.len(); + for r in items { + let Some(full_name) = r["full_name"].as_str() else { continue }; + out.push(Granted { + full_name: full_name.to_string(), + id: r["id"].as_i64().map(|i| i.to_string()), + archived: r["archived"].as_bool().unwrap_or(false), + }); + if out.len() >= limit { + return Ok(out); + } + } + if n < 100 { + break; + } + } + Ok(out) +} + +/// An account's display name on GitHub (an organization's or a person's `name`), else its login. +/// +/// # Errors +/// When GitHub can't be reached or refuses. +pub async fn account_name(token: &str, login: &str, account_type: &str) -> laravel::Result { + let path = if account_type == "Organization" { format!("/orgs/{login}") } else { format!("/users/{login}") }; + Ok(get(token, &path) + .await? + .and_then(|v| v["name"].as_str().map(str::trim).filter(|n| !n.is_empty()).map(str::to_string)) + .unwrap_or_else(|| login.to_string())) +} + /// Where people install the App on their repositories. pub const INSTALL_URL: &str = "https://github.com/apps/visualci-com/installations/new"; diff --git a/app/src/forge/gitlab.rs b/app/src/forge/gitlab.rs index f519e5fd..0aadecb5 100644 --- a/app/src/forge/gitlab.rs +++ b/app/src/forge/gitlab.rs @@ -102,6 +102,7 @@ pub async fn sign_in(base: &str, profile: &social::User) -> laravel::Result-github` when that's taken), with the person as +//! its admin. The other people with access join through the hourly forge sync. +//! +//! Repositories the person can't maintain are listed with why, not made into projects. Once set up, repositories added +//! to the installation on GitHub become projects in its organization too. + +use laravel::db; +use serde::Serialize; +use serde_json::{Value, json}; + +use super::github_app::{self, GithubApp}; +use super::{Installation, Permission, Repository}; +use crate::auth::Role; +use crate::models::{Membership, Organization, Project, User}; +use crate::models::{slug_from, valid_slug}; + +/// The most repositories one set-up looks at: an installation on "all repositories" of a large organization makes +/// projects for the first ones, and says so. +pub const REPOSITORY_LIMIT: usize = 100; + +/// A project made or found for a repository. +#[derive(Clone, Debug, Serialize, PartialEq, Eq)] +pub struct Linked { + pub project: String, + pub repository: String, +} + +/// A repository that wasn't made into a project, and why. +#[derive(Clone, Debug, Serialize, PartialEq, Eq)] +pub struct Skipped { + pub repository: String, + pub reason: String, +} + +/// What setting an installation up did. +#[derive(Clone, Debug, Serialize, PartialEq, Eq)] +pub struct SetUp { + pub installation_id: String, + pub account_login: String, + /// The organization's slug. + pub organization: String, + pub organization_created: bool, + /// Said once, such as why the organization's slug isn't the account's login. + pub note: Option, + /// Projects made now. + pub linked: Vec, + /// Repositories already linked to a project of this organization. + pub already: Vec, + pub skipped: Vec, + /// More repositories were granted than one set-up looks at ([`REPOSITORY_LIMIT`]). + pub truncated: bool, +} + +fn refused(status: u16, message: impl Into) -> laravel::Error { + laravel::abort_with(status, message.into()) +} + +/// Record the installations a person's GitHub sign-in listed: each installation, and that they can reach exactly +/// these now. +/// +/// # Errors +/// On a database error. +pub async fn remember(user_id: i64, found: &[Installation]) -> laravel::Result<()> { + let found = found.to_vec(); + db::transaction(async |_| { + for i in &found { + upsert(i).await?; + } + db::query!("DELETE FROM user_installations WHERE user_id = {user_id}").delete().await?; + for i in &found { + let id = i.id.clone(); + db::query!( + "INSERT INTO user_installations (user_id, installation_id, seen_at) VALUES ({user_id}, {id}, now()) \ + ON CONFLICT (user_id, installation_id) DO UPDATE SET seen_at = now()" + ) + .insert() + .await?; + } + Ok(()) + }) + .await +} + +/// An installation GitHub says exists: recorded, or brought up to date (its account may have been renamed), and no +/// longer marked removed. +async fn upsert(i: &Installation) -> laravel::Result<()> { + let (id, account_id, login, kind) = + (i.id.clone(), i.account_id.clone(), i.account_login.clone(), i.account_type.clone()); + db::query!( + "INSERT INTO github_installations (installation_id, account_id, account_login, account_type) \ + VALUES ({id}, {account_id}, {login}, {kind}) \ + ON CONFLICT (installation_id) DO UPDATE SET account_id = EXCLUDED.account_id, \ + account_login = EXCLUDED.account_login, account_type = EXCLUDED.account_type, deleted_at = NULL, \ + updated_at = now()" + ) + .insert() + .await?; + Ok(()) +} + +/// The VisualCI user with this GitHub account (its permanent ID). +async fn user_for_github(github_id: &str) -> laravel::Result> { + let user_id: Option = db::query!( + "SELECT user_id FROM identities WHERE forge = 'github' AND site = '' AND forge_user_id = {github_id} \ + ORDER BY id LIMIT 1" + ) + .scalar() + .await?; + match user_id { + Some(id) => User::find(id).await, + None => Ok(None), + } +} + +/// The person's role in an organization. +async fn role_in(organization_id: i64, user_id: i64) -> laravel::Result> { + let role: Option = + db::query!("SELECT role FROM memberships WHERE organization_id = {organization_id} AND user_id = {user_id}") + .scalar() + .await?; + Ok(role.as_deref().and_then(Role::parse)) +} + +/// Act on the App's `installation` and `installation_repositories` deliveries: record installations made, suspended +/// or removed, and make projects for repositories added to one that has been set up. Returns what it did, for the +/// delivery's log; `Value::Null` when the delivery isn't about installations. +/// +/// # Errors +/// On a database error, or when GitHub can't be reached. +pub async fn from_webhook(app: &GithubApp, kind: &str, event: &Value) -> laravel::Result { + let action = event["action"].as_str().unwrap_or_default(); + 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 { + return Ok(Value::Null); + }; + upsert(&found).await?; + db::query!("UPDATE github_installations SET suspended_at = NULL WHERE installation_id = {id}") + .update() + .await?; + // Whoever installed it can reach it: the setup page and checklist offer it to them before they sign in + // again + if let Some(sender) = event["sender"]["id"].as_i64().map(|i| i.to_string()) + && let Some(user) = user_for_github(&sender).await? + { + let user_id = user.id; + db::query!( + "INSERT INTO user_installations (user_id, installation_id, seen_at) VALUES ({user_id}, {id}, now()) \ + ON CONFLICT (user_id, installation_id) DO UPDATE SET seen_at = now()" + ) + .insert() + .await?; + } + Ok(json!({ "installation": "recorded" })) + } + ("installation", "suspend") => { + db::query!( + "UPDATE github_installations SET suspended_at = now(), updated_at = now() WHERE installation_id = {id}" + ) + .update() + .await?; + Ok(json!({ "installation": "suspended" })) + } + ("installation", "deleted") => { + // Kept, marked removed: its organization is found again by the account when the App is installed again + db::query!( + "UPDATE github_installations SET deleted_at = now(), updated_at = now() WHERE installation_id = {id}" + ) + .update() + .await?; + db::query!("DELETE FROM user_installations WHERE installation_id = {id}").delete().await?; + Ok(json!({ "installation": "removed" })) + } + ("installation_repositories", "added") => { + let row = db::query!( + "SELECT organization_id, set_up_by FROM github_installations \ + WHERE installation_id = {id} AND organization_id IS NOT NULL AND deleted_at IS NULL \ + AND suspended_at IS NULL" + ) + .select_one() + .await?; + let Some(row) = row else { return Ok(json!({ "projects": "not set up" })) }; + let organization_id: i64 = row.try_get("organization_id")?; + // The person who added them, if they're an admin there; else whoever set the installation up + let mut by = None; + if let Some(sender) = event["sender"]["id"].as_i64().map(|i| i.to_string()) + && let Some(user) = user_for_github(&sender).await? + && role_in(organization_id, user.id).await? == Some(Role::Admin) + { + by = Some(user); + } + if by.is_none() + && let Some(set_up_by) = row.try_get::>("set_up_by")? + && role_in(organization_id, set_up_by).await? == Some(Role::Admin) + { + by = User::find(set_up_by).await?; + } + let Some(by) = by else { return Ok(json!({ "projects": "no admin to link them" })) }; + let granted = event["repositories_added"] + .as_array() + .map(|l| { + l.iter() + .filter_map(|r| { + Some(github_app::Granted { + full_name: r["full_name"].as_str()?.to_string(), + id: r["id"].as_i64().map(|i| i.to_string()), + archived: false, + }) + }) + .collect::>() + }) + .unwrap_or_default(); + let made = add_repositories(app, organization_id, &by, &id, granted).await?; + Ok(json!({ "projects": made.linked.len(), "skipped": made.skipped.len() })) + } + _ => Ok(Value::Null), + } +} + +/// The installations a person can reach, for the checklist's "already installed" offers: each one's ID, account and +/// the organization it was set up for (`null` until it is). +/// +/// # Errors +/// On a database error. +pub async fn offers(user_id: i64) -> laravel::Result> { + let rows = db::query!( + "SELECT g.installation_id, g.account_login, g.account_type, o.slug AS organization \ + FROM user_installations ui JOIN github_installations g ON g.installation_id = ui.installation_id \ + LEFT JOIN organizations o ON o.id = g.organization_id \ + WHERE ui.user_id = {user_id} AND g.deleted_at IS NULL AND g.suspended_at IS NULL \ + ORDER BY lower(g.account_login)" + ) + .select() + .await?; + rows.iter() + .map(|r| { + Ok(json!({ + "installation_id": r.try_get::("installation_id")?, + "account_login": r.try_get::("account_login")?, + "account_type": r.try_get::("account_type")?, + "organization": r.try_get::>("organization")?, + })) + }) + .collect() +} + +/// Whether the person can reach the installation (as of their last sign-in, or because they installed it). +/// +/// # Errors +/// On a database error. +pub async fn reachable(user_id: i64, installation_id: &str) -> laravel::Result { + let id = installation_id.to_string(); + let found: Option = db::query!( + "SELECT EXISTS (SELECT 1 FROM user_installations ui JOIN github_installations g \ + ON g.installation_id = ui.installation_id \ + WHERE ui.user_id = {user_id} AND ui.installation_id = {id} AND g.deleted_at IS NULL)" + ) + .scalar() + .await?; + Ok(found.unwrap_or(false)) +} + +/// Set an installation up for `user`: find or make its organization and make a project for each repository it was +/// granted that they can maintain. Safe to run again: repositories already linked are left as they are. +/// +/// # Errors +/// 404 when the person can't reach the installation, 409 when it's suspended, 403 when it's set up for an +/// organization they aren't an admin of; GitHub and database errors. +pub async fn set_up(app: &GithubApp, user: &User, installation_id: &str) -> laravel::Result { + if !reachable(user.id, installation_id).await? { + return Err(refused( + 404, + "this installation of the VisualCI GitHub App isn't one your GitHub account can reach: sign in with the \ + GitHub account that installed it", + )); + } + let id = installation_id.to_string(); + let row = db::query!( + "SELECT account_id, account_login, account_type, organization_id, suspended_at IS NOT NULL AS suspended \ + FROM github_installations WHERE installation_id = {id}" + ) + .select_one() + .await? + .ok_or_else(|| laravel::abort(404))?; + let (account_id, login, account_type): (String, String, String) = + (row.try_get("account_id")?, row.try_get("account_login")?, row.try_get("account_type")?); + if row.try_get::("suspended")? { + return Err(refused( + 409, + format!("the VisualCI GitHub App is suspended on {login}: unsuspend it in GitHub's settings first"), + )); + } + let mapped: Option = match row.try_get::>("organization_id")? { + Some(o) => Some(o), + // Installed again after being removed: the organization it was set up for before + None => { + db::query!( + "SELECT organization_id FROM github_installations \ + WHERE account_id = {account_id} AND organization_id IS NOT NULL ORDER BY updated_at DESC LIMIT 1" + ) + .scalar() + .await? + } + }; + let own_account = account_type == "User" && github_id(user.id).await?.as_deref() == Some(account_id.as_str()); + let (organization, created, note) = match mapped { + Some(o) => (Organization::find(o).await?.ok_or_else(|| laravel::abort(404))?, false, None), + None if own_account => (personal(user, &account_id).await?, false, None), + None => { + let token = github_app::installation_token(app, installation_id).await?; + let name = github_app::account_name(&token, &login, &account_type).await?; + let (org, note) = create_for_account(user, &login, &name).await?; + (org, true, note) + } + }; + if role_in(organization.id, user.id).await? != Some(Role::Admin) { + return Err(refused( + 403, + format!( + "VisualCI is set up for {login} in the organization {}: ask one of its admins to make you an admin", + organization.slug + ), + )); + } + let (org_id, user_id) = (organization.id, user.id); + db::query!( + "UPDATE github_installations SET organization_id = {org_id}, set_up_by = {user_id}, updated_at = now() \ + WHERE installation_id = {id}" + ) + .update() + .await?; + let granted = { + let token = github_app::installation_token(app, installation_id).await?; + github_app::installation_repositories(&token, REPOSITORY_LIMIT + 1).await? + }; + let truncated = granted.len() > REPOSITORY_LIMIT; + let granted = granted.into_iter().take(REPOSITORY_LIMIT).collect(); + let made = add_repositories(app, organization.id, user, installation_id, granted).await?; + let outcome = SetUp { + installation_id: id.clone(), + account_login: login, + organization: organization.slug, + organization_created: created, + note, + linked: made.linked, + already: made.already, + skipped: made.skipped, + truncated, + }; + let result = serde_json::to_string(&outcome).map_err(|e| laravel::Error::msg(e.to_string()))?; + db::query!("UPDATE github_installations SET setup_result = {result}::jsonb WHERE installation_id = {id}") + .update() + .await?; + Ok(outcome) +} + +/// The person's GitHub account's permanent ID. +async fn github_id(user_id: i64) -> laravel::Result> { + db::query!( + "SELECT forge_user_id FROM identities WHERE user_id = {user_id} AND forge = 'github' AND site = '' \ + ORDER BY id LIMIT 1" + ) + .scalar() + .await +} + +/// The person's own organization: the first one they created that isn't set up for another GitHub account, else a +/// new one. +async fn personal(user: &User, account_id: &str) -> laravel::Result { + let user_id = user.id; + let found: Option = db::query!( + "SELECT o.id FROM organizations o JOIN memberships m ON m.organization_id = o.id \ + WHERE m.user_id = {user_id} AND m.source = 'created' AND m.role = 'admin' \ + AND NOT EXISTS (SELECT 1 FROM github_installations g \ + WHERE g.organization_id = o.id AND g.account_id <> {account_id}) \ + ORDER BY o.id LIMIT 1" + ) + .scalar() + .await?; + match found { + Some(id) => Organization::find(id).await?.ok_or_else(|| laravel::abort(404)), + None => Organization::create_personal(user).await, + } +} + +/// A new organization for a GitHub account, with `user` as its admin: slug the lowercased login, else +/// `-github` (then `-2`, `-3`…), with a note saying why. +async fn create_for_account(user: &User, login: &str, name: &str) -> laravel::Result<(Organization, Option)> { + let wanted = login.to_lowercase(); + let base = if valid_slug(&wanted) { wanted.clone() } else { slug_from(login) }; + let mut candidates = vec![base.clone(), format!("{base}-github")]; + candidates.extend((2..=20).map(|n| format!("{base}-github-{n}"))); + for slug in candidates.into_iter().filter(|s| valid_slug(s)) { + if Organization::query().filter(Organization::slug.eq(slug.as_str())).exists().await? { + continue; + } + let user_id = user.id; + let made = db::transaction(async |_| { + let org = + laravel::model::create!(Organization { pid: laravel::str::uuid7(), slug: slug.as_str(), name: name }) + .await?; + laravel::model::create!(Membership { + organization_id: org.id, + user_id: user_id, + role: "admin", + source: "created", + }) + .await?; + Ok(org) + }) + .await; + match made { + Ok(org) => { + let note = (org.slug != wanted).then(|| { + format!("{wanted} is already taken on VisualCI, so this organization's address is {}", org.slug) + }); + return Ok((org, note)); + } + Err(e) if laravel::db::is_unique_violation(&e) => {} + Err(e) => return Err(e), + } + } + Err(laravel::Error::msg("no free organization slug")) +} + +/// What [`add_repositories`] did. +struct Added { + linked: Vec, + already: Vec, + skipped: Vec, +} + +/// Make a project for each repository `by` can maintain, linked through `link_repository`'s checks; list the rest. +async fn add_repositories( + app: &GithubApp, + organization_id: i64, + by: &User, + installation_id: &str, + granted: Vec, +) -> laravel::Result { + let mut added = Added { linked: Vec::new(), already: Vec::new(), skipped: Vec::new() }; + let forge_user = github_id(by.id).await?; + for repo in granted { + let Some(repository) = Repository::parse(&repo.full_name).map(|r| r.with_id(repo.id.clone())) else { + continue; + }; + let path = repository.path.clone(); + if let Some(project) = linked_here(&repository, organization_id).await? { + added.already.push(Linked { project, repository: path }); + continue; + } + if repo.archived { + added.skipped.push(Skipped { repository: path, reason: "it's archived".into() }); + continue; + } + let Some(forge_user) = forge_user.as_deref() else { + added.skipped.push(Skipped { repository: path, reason: "sign in with GitHub first".into() }); + continue; + }; + let permission = github_app::permission(app, &path, installation_id, forge_user).await?; + if !permission.is_some_and(|p| p >= Permission::Maintain) { + let you = permission.map_or("not a collaborator".to_string(), |p| format!("{p:?}").to_lowercase()); + let owner = path.split('/').next().unwrap_or_default(); + added.skipped.push(Skipped { + repository: path.clone(), + reason: format!( + "only an admin or maintainer can add it (you're {you}): ask an admin of {owner} to set it up" + ), + }); + continue; + } + let name = path.rsplit('/').next().unwrap_or(&path).to_string(); + let Some(project) = new_project(organization_id, &name).await? else { + added.skipped.push(Skipped { repository: path, reason: "no free project slug".into() }); + continue; + }; + let (project_id, slug) = (project.id, project.slug.clone()); + match super::link::link_repository(project, by, &repository.url, None, false).await { + Ok(_) => added.linked.push(Linked { project: slug, repository: path }), + Err(e) if e.status().is_client_error() => { + db::query!("DELETE FROM projects WHERE id = {project_id}").delete().await?; + added.skipped.push(Skipped { repository: path, reason: e.to_string() }); + } + Err(e) => { + db::query!("DELETE FROM projects WHERE id = {project_id}").delete().await?; + return Err(e); + } + } + } + Ok(added) +} + +/// The slug of a project of this organization already linked to the repository. +async fn linked_here(repository: &Repository, organization_id: i64) -> laravel::Result> { + let (url, repo_id) = (repository.url.to_lowercase(), repository.id.clone()); + db::query!( + "SELECT slug FROM projects WHERE forge = 'github' AND organization_id = {organization_id} \ + AND ((repository_id IS NOT NULL AND repository_id = {repo_id}) OR lower(repository_url) = {url}) \ + ORDER BY id LIMIT 1" + ) + .scalar() + .await +} + +/// A project slug from a repository's name: lowercase letters and digits, other runs as one dash, at most 50. +#[must_use] +pub fn project_slug(name: &str) -> String { + let mut slug = String::new(); + for c in name.chars().flat_map(char::to_lowercase) { + if c.is_ascii_lowercase() || c.is_ascii_digit() { + slug.push(c); + } else if !slug.ends_with('-') && !slug.is_empty() { + slug.push('-'); + } + } + let slug: String = slug.trim_matches('-').chars().take(50).collect(); + let slug = slug.trim_end_matches('-').to_string(); + if crate::domain::projects::valid_slug(&slug) { + slug + } else { + format!("{slug}-project").trim_start_matches('-').to_string() + } +} + +/// A project named after a repository, slug from its name (`-2`, `-3`… when taken). +async fn new_project(organization_id: i64, name: &str) -> laravel::Result> { + let base = project_slug(name); + for n in 1..=20 { + let slug = if n == 1 { base.clone() } else { format!("{base}-{n}") }; + if let Ok(project) = crate::domain::projects::create(organization_id, &slug, name).await? { + return Ok(Some(project)); + } + } + Ok(None) +} diff --git a/app/src/forge/mod.rs b/app/src/forge/mod.rs index aee525e7..5890bbad 100644 --- a/app/src/forge/mod.rs +++ b/app/src/forge/mod.rs @@ -7,6 +7,7 @@ pub mod events; pub mod github; pub mod github_app; pub mod gitlab; +pub mod installations; pub mod link; pub mod open_source; pub mod outbound; @@ -249,4 +250,18 @@ pub struct SignIn { pub identity: Identity, /// Every repository the forge app can see that this person has a permission on. pub repositories: Vec<(Repository, Permission)>, + /// The GitHub App's installations this person can reach (none on GitLab). + pub installations: Vec, +} + +/// An installation of the VisualCI GitHub App, and the account it's installed on. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Installation { + /// GitHub's ID for the installation. + pub id: String, + /// GitHub's permanent ID for the account. + pub account_id: String, + pub account_login: String, + /// `User` or `Organization`. + pub account_type: String, } diff --git a/app/src/forge/webhooks.rs b/app/src/forge/webhooks.rs index 930e2229..23f5114e 100644 --- a/app/src/forge/webhooks.rs +++ b/app/src/forge/webhooks.rs @@ -251,7 +251,15 @@ pub async fn github( let event: Value = serde_json::from_slice(&body).map_err(|e| laravel::abort_with(400, e.to_string()))?; let (kind, delivery) = (header("x-github-event"), header("x-github-delivery")); let read = read_event(&kind, &event).map_err(|e| laravel::abort_with(400, e))?; - let outcome = handle(&app, read).await?; + let mut outcome = handle(&app, read).await?; + // Installations recorded, and repositories added to a set-up installation made into projects (after `handle` + // has attached the ones already linked) + let installations = super::installations::from_webhook(&app, &kind, &event).await?; + if !installations.is_null() + && let Some(map) = outcome.as_object_mut() + { + map.insert("installations".into(), installations); + } tracing::info!(forge = "github", kind, delivery, outcome = %outcome, "webhook"); Ok(Json(outcome)) } diff --git a/app/src/listeners/mod.rs b/app/src/listeners/mod.rs index 8d001181..5ea01952 100644 --- a/app/src/listeners/mod.rs +++ b/app/src/listeners/mod.rs @@ -5,7 +5,7 @@ use laravel::event::{Event, listener}; use crate::auth::sign_in::SignedUp; use crate::models::{Organization, User}; -/// A new account gets its own organization and project. +/// A new account gets its own organization, empty until the GitHub App is set up (sc-9027). #[listener] pub async fn give_new_users_an_organization(event: Event) -> laravel::Result<()> { let user = User::find_or_fail(event.user_id).await?; diff --git a/app/src/models/organizations.rs b/app/src/models/organizations.rs index 677d5d42..b5ebc7d6 100644 --- a/app/src/models/organizations.rs +++ b/app/src/models/organizations.rs @@ -29,8 +29,8 @@ pub struct Organization { /// Paths an organization's slug can't take. pub const RESERVED_SLUGS: &[&str] = &[ - "account", "api", "assets", "auth", "billing", "cli", "device", "docs", "g", "mcp", "new", "settings", "staff", - "status", "visualci", "webhooks", + "account", "api", "assets", "auth", "billing", "cli", "device", "docs", "g", "github", "mcp", "new", "settings", + "staff", "status", "visualci", "webhooks", ]; /// Lowercase letters, digits and dashes, at most 60, and not a reserved path. @@ -59,12 +59,13 @@ pub fn slug_from(name: &str) -> String { } impl Organization { - /// A new user's own organization, named after them, with them as its admin, and its `default` project. The slug + /// A new user's own organization, named after them, with them as its admin and no projects yet (setting up the + /// GitHub App makes them, sc-9027). The slug /// is their forge login's (else their email's local part), with `-2`, `-3`… when it's taken. /// /// # Errors /// On a database error, or when the first hundred slugs are taken. - pub async fn create_personal(user: &crate::models::User) -> laravel::Result<(Self, crate::models::Project)> { + pub async fn create_personal(user: &crate::models::User) -> laravel::Result { let user_id = user.id; let login: Option = laravel::db::query!("SELECT login FROM identities WHERE user_id = {user_id} ORDER BY id LIMIT 1") @@ -92,14 +93,7 @@ impl Organization { source: "created", }) .await?; - let project = laravel::model::create!(crate::models::Project { - pid: laravel::str::uuid7(), - organization_id: org.id, - slug: "default", - name: "Default", - }) - .await?; - Ok((org, project)) + Ok(org) }) .await; // Another sign-up took the slug between the check and the insert: try the next one. diff --git a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/get_organization.json b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/get_organization.json index 728fd5df..da75757a 100644 --- a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/get_organization.json +++ b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/get_organization.json @@ -5,7 +5,7 @@ "result": { "content": [ { - "text": "{\"billing_url\":\"https://app.visualci.test//billing\",\"invitations\":[],\"members\":[{\"avatar_url\":null,\"email\":\"@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"owner\",\"role\":\"admin\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null}],\"name\":\"Org\",\"projects\":[{\"last_build\":null,\"name\":\"PDFs\",\"project\":\"/pdfs\"},{\"last_build\":null,\"name\":\"Screenshots\",\"project\":\"/shots\"}],\"role\":\"admin\",\"setup\":{\"complete\":false,\"dismissed\":false,\"next\":\"install_github_app\",\"steps\":[{\"done\":true,\"key\":\"connect_agent\"},{\"done\":true,\"key\":\"create_project\"},{\"done\":false,\"key\":\"install_github_app\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[]}", + "text": "{\"billing_url\":\"https://app.visualci.test//billing\",\"invitations\":[],\"members\":[{\"avatar_url\":null,\"email\":\"@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"owner\",\"role\":\"admin\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null}],\"name\":\"Org\",\"projects\":[{\"last_build\":null,\"name\":\"PDFs\",\"project\":\"/pdfs\"},{\"last_build\":null,\"name\":\"Screenshots\",\"project\":\"/shots\"}],\"role\":\"admin\",\"setup\":{\"complete\":false,\"dismissed\":false,\"github\":[],\"install_url\":\"https://github.com/apps/visualci-com/installations/new\",\"installations\":[],\"next\":\"install_github_app\",\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":true,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[]}", "type": "text" } ], @@ -44,16 +44,11 @@ "setup": { "complete": false, "dismissed": false, + "github": [], + "install_url": "https://github.com/apps/visualci-com/installations/new", + "installations": [], "next": "install_github_app", "steps": [ - { - "done": true, - "key": "connect_agent" - }, - { - "done": true, - "key": "create_project" - }, { "done": false, "key": "install_github_app" @@ -62,6 +57,10 @@ "done": false, "key": "add_to_ci" }, + { + "done": true, + "key": "connect_agent" + }, { "done": false, "key": "review_changes" diff --git a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/whoami.json b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/whoami.json index f4429033..18024fcd 100644 --- a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/whoami.json +++ b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/whoami.json @@ -3,7 +3,7 @@ "result": { "content": [ { - "text": "{\"email\":\"@example.com\",\"identities\":[],\"kind\":\"user\",\"name\":\"owner\",\"organizations\":[{\"blocked\":null,\"name\":\"Org\",\"projects\":[\"/pdfs\",\"/shots\"],\"role\":\"admin\",\"setup\":{\"complete\":false,\"dismissed\":false,\"next\":\"install_github_app\",\"steps\":[{\"done\":true,\"key\":\"connect_agent\"},{\"done\":true,\"key\":\"create_project\"},{\"done\":false,\"key\":\"install_github_app\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\"}],\"via\":{\"source\":\"personal_token\",\"token_name\":\"agent\"},\"waiting_for_review\":[]}", + "text": "{\"email\":\"@example.com\",\"identities\":[],\"kind\":\"user\",\"name\":\"owner\",\"organizations\":[{\"blocked\":null,\"name\":\"Org\",\"projects\":[\"/pdfs\",\"/shots\"],\"role\":\"admin\",\"setup\":{\"complete\":false,\"dismissed\":false,\"github\":[],\"install_url\":\"https://github.com/apps/visualci-com/installations/new\",\"installations\":[],\"next\":\"install_github_app\",\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":true,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\"}],\"via\":{\"source\":\"personal_token\",\"token_name\":\"agent\"},\"waiting_for_review\":[]}", "type": "text" } ], @@ -25,16 +25,11 @@ "setup": { "complete": false, "dismissed": false, + "github": [], + "install_url": "https://github.com/apps/visualci-com/installations/new", + "installations": [], "next": "install_github_app", "steps": [ - { - "done": true, - "key": "connect_agent" - }, - { - "done": true, - "key": "create_project" - }, { "done": false, "key": "install_github_app" @@ -43,6 +38,10 @@ "done": false, "key": "add_to_ci" }, + { + "done": true, + "key": "connect_agent" + }, { "done": false, "key": "review_changes" diff --git a/app/tests/golden/mcp/a_project_token_acts_as_a_member_not_an_admin/get_organization.json b/app/tests/golden/mcp/a_project_token_acts_as_a_member_not_an_admin/get_organization.json index f647a91e..dfa48a59 100644 --- a/app/tests/golden/mcp/a_project_token_acts_as_a_member_not_an_admin/get_organization.json +++ b/app/tests/golden/mcp/a_project_token_acts_as_a_member_not_an_admin/get_organization.json @@ -5,7 +5,7 @@ "result": { "content": [ { - "text": "{\"billing_url\":\"https://app.visualci.test//billing\",\"invitations\":[],\"members\":[],\"name\":\"Org\",\"projects\":[{\"last_build\":null,\"name\":\"PDFs\",\"project\":\"/pdfs\"}],\"role\":\"project\",\"setup\":{\"complete\":false,\"dismissed\":false,\"next\":\"connect_agent\",\"steps\":[{\"done\":false,\"key\":\"connect_agent\"},{\"done\":true,\"key\":\"create_project\"},{\"done\":false,\"key\":\"install_github_app\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[]}", + "text": "{\"billing_url\":\"https://app.visualci.test//billing\",\"invitations\":[],\"members\":[],\"name\":\"Org\",\"projects\":[{\"last_build\":null,\"name\":\"PDFs\",\"project\":\"/pdfs\"}],\"role\":\"project\",\"setup\":{\"complete\":false,\"dismissed\":false,\"github\":[],\"install_url\":\"https://github.com/apps/visualci-com/installations/new\",\"installations\":[],\"next\":\"install_github_app\",\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[]}", "type": "text" } ], @@ -26,23 +26,22 @@ "setup": { "complete": false, "dismissed": false, - "next": "connect_agent", + "github": [], + "install_url": "https://github.com/apps/visualci-com/installations/new", + "installations": [], + "next": "install_github_app", "steps": [ { "done": false, - "key": "connect_agent" - }, - { - "done": true, - "key": "create_project" + "key": "install_github_app" }, { "done": false, - "key": "install_github_app" + "key": "add_to_ci" }, { "done": false, - "key": "add_to_ci" + "key": "connect_agent" }, { "done": false, diff --git a/app/tests/golden/mcp/runs_a_build_from_uploaded_files/get_organization.json b/app/tests/golden/mcp/runs_a_build_from_uploaded_files/get_organization.json index 3aca3267..e6f46db9 100644 --- a/app/tests/golden/mcp/runs_a_build_from_uploaded_files/get_organization.json +++ b/app/tests/golden/mcp/runs_a_build_from_uploaded_files/get_organization.json @@ -5,7 +5,7 @@ "result": { "content": [ { - "text": "{\"billing_url\":\"https://app.visualci.test//billing\",\"invitations\":[],\"members\":[{\"avatar_url\":null,\"email\":\"@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"owner\",\"role\":\"admin\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null}],\"name\":\"Org\",\"projects\":[{\"last_build\":{\"blocked\":null,\"branch\":\"main\",\"ci_mode\":\"review\",\"commit\":\"abc\",\"conclusion\":\"changes\",\"created_at\":\"\",\"environment\":\"ci\",\"environment_info\":{},\"error\":null,\"id\":\"\",\"mode\":\"ci\",\"name\":\"default\",\"number\":1,\"passed\":true,\"pr_number\":null,\"project\":\"/pdfs\",\"review_state\":\"auto_approved\",\"reviewable\":true,\"reviews\":[],\"state\":\"completed\",\"stats\":{\"added\":1,\"changed\":0,\"config\":0,\"failed\":0,\"ignored\":0,\"pending\":0,\"removed\":0,\"total\":1,\"unchanged\":0},\"url\":\"https://app.visualci.test//pdfs/builds/1\",\"warnings\":[]},\"name\":\"PDFs\",\"project\":\"/pdfs\"},{\"last_build\":null,\"name\":\"Screenshots\",\"project\":\"/shots\"}],\"role\":\"admin\",\"setup\":{\"complete\":false,\"dismissed\":false,\"next\":\"install_github_app\",\"steps\":[{\"done\":true,\"key\":\"connect_agent\"},{\"done\":true,\"key\":\"create_project\"},{\"done\":false,\"key\":\"install_github_app\"},{\"done\":true,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":1,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[{\"created_at\":\"\",\"credits\":1,\"kind\":\"build\",\"reference\":\"build pdfs/1: 1 snapshot checked\"}]}", + "text": "{\"billing_url\":\"https://app.visualci.test//billing\",\"invitations\":[],\"members\":[{\"avatar_url\":null,\"email\":\"@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"owner\",\"role\":\"admin\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null}],\"name\":\"Org\",\"projects\":[{\"last_build\":{\"blocked\":null,\"branch\":\"main\",\"ci_mode\":\"review\",\"commit\":\"abc\",\"conclusion\":\"changes\",\"created_at\":\"\",\"environment\":\"ci\",\"environment_info\":{},\"error\":null,\"id\":\"\",\"mode\":\"ci\",\"name\":\"default\",\"number\":1,\"passed\":true,\"pr_number\":null,\"project\":\"/pdfs\",\"review_state\":\"auto_approved\",\"reviewable\":true,\"reviews\":[],\"state\":\"completed\",\"stats\":{\"added\":1,\"changed\":0,\"config\":0,\"failed\":0,\"ignored\":0,\"pending\":0,\"removed\":0,\"total\":1,\"unchanged\":0},\"url\":\"https://app.visualci.test//pdfs/builds/1\",\"warnings\":[]},\"name\":\"PDFs\",\"project\":\"/pdfs\"},{\"last_build\":null,\"name\":\"Screenshots\",\"project\":\"/shots\"}],\"role\":\"admin\",\"setup\":{\"complete\":false,\"dismissed\":false,\"github\":[],\"install_url\":\"https://github.com/apps/visualci-com/installations/new\",\"installations\":[],\"next\":\"install_github_app\",\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":true,\"key\":\"add_to_ci\"},{\"done\":true,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":1,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[{\"created_at\":\"\",\"credits\":1,\"kind\":\"build\",\"reference\":\"build pdfs/1: 1 snapshot checked\"}]}", "type": "text" } ], @@ -78,16 +78,11 @@ "setup": { "complete": false, "dismissed": false, + "github": [], + "install_url": "https://github.com/apps/visualci-com/installations/new", + "installations": [], "next": "install_github_app", "steps": [ - { - "done": true, - "key": "connect_agent" - }, - { - "done": true, - "key": "create_project" - }, { "done": false, "key": "install_github_app" @@ -96,6 +91,10 @@ "done": true, "key": "add_to_ci" }, + { + "done": true, + "key": "connect_agent" + }, { "done": false, "key": "review_changes" diff --git a/app/tests/installations.rs b/app/tests/installations.rs new file mode 100644 index 00000000..114286bb --- /dev/null +++ b/app/tests/installations.rs @@ -0,0 +1,291 @@ +//! Setting up the GitHub App (sc-9027): installations recorded from sign-ins and webhooks, the Setup URL, and an +//! installation mapped to an organization with a project for each repository the person can maintain. + +use app::forge::Installation; +use app::forge::installations::{self, remember}; +use app::models::{Organization, User}; +use hmac::{Hmac, Mac}; +use laravel::db; +use laravel::http::client; +use laravel::model::create; +use laravel::testing::prelude::*; +use sha2::Sha256; + +const SECRET: &str = "github-webhook-test"; + +/// A GitHub App key made once per run (base64 of its PEM). +fn app_key() -> &'static str { + static KEY: std::sync::OnceLock = std::sync::OnceLock::new(); + KEY.get_or_init(|| { + use base64::Engine; + use rsa::pkcs1::EncodeRsaPrivateKey; + let key = rsa::RsaPrivateKey::new(&mut rsa::rand_core::OsRng, 2048).expect("a key"); + let pem = key.to_pkcs1_pem(rsa::pkcs1::LineEnding::LF).expect("its PEM"); + base64::engine::general_purpose::STANDARD.encode(pem.as_bytes()) + }) +} + +fn github() -> Application { + app::testing::configure() + .with_envs([ + ("GITHUB_WEBHOOK_SECRET", SECRET), + ("GITHUB_APP_ID", "1"), + ("GITHUB_APP_PRIVATE_KEY_BASE64", app_key()), + ]) + .create() +} + +fn github_app() -> app::forge::github_app::GithubApp { + app::forge::github_app::GithubApp { + app_id: Some("1".into()), + private_key_base64: Some(app_key().into()), + webhook_secret: None, + } +} + +async fn deliver(app: &Application, kind: &str, event: serde_json::Value) -> laravel::testing::TestResponse { + let body = event.to_string(); + let mut mac = Hmac::::new_from_slice(SECRET.as_bytes()).unwrap(); + mac.update(body.as_bytes()); + let signature = format!("sha256={}", hex::encode(mac.finalize().into_bytes())); + app.post("/webhooks/github") + .header("x-github-event", kind) + .header("x-github-delivery", "d-1") + .header("x-hub-signature-256", signature) + .header("content-type", "application/json") + .body(body) + .await +} + +/// Ada, GitHub account 1001 (`ada`), with her own organization `ada`, as signing up makes it. +async fn ada() -> laravel::Result<(User, Organization)> { + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let id = ada.id; + db::query!( + "INSERT INTO identities (user_id, forge, site, forge_user_id, login, created_at, updated_at) \ + VALUES ({id}, 'github', '', '1001', 'ada', now(), now())" + ) + .insert() + .await?; + let org = Organization::create_personal(&ada).await?; + Ok((ada, org)) +} + +fn installation(id: &str, account_id: &str, login: &str, kind: &str) -> Installation { + Installation { + id: id.into(), + account_id: account_id.into(), + account_login: login.into(), + account_type: kind.into(), + } +} + +/// GitHub's answers for installation 7 on `owner`, granted `owner/web` (Ada maintains it) and `owner/docs` (she +/// can only write). +fn granted(owner: &str) -> client::HttpFake { + client::fake() + .with("api.github.com/app/installations/7/access_tokens", json!({ "token": "t" })) + .with("api.github.com/app/installations/7", json!({ "id": 7 })) + .with( + "api.github.com/installation/repositories*", + json!({ "repositories": [ + { "full_name": format!("{owner}/web"), "id": 42 }, + { "full_name": format!("{owner}/docs"), "id": 43 }, + ] }), + ) + .with(&format!("api.github.com/orgs/{owner}"), json!({ "login": owner, "name": "Acme Inc" })) + .with("api.github.com/user/1001", json!({ "id": 1001, "login": "ada" })) + .with(&format!("api.github.com/repos/{owner}/web/installation"), json!({ "id": 7 })) + .with(&format!("api.github.com/repos/{owner}/docs/installation"), json!({ "id": 7 })) + .with(&format!("api.github.com/repos/{owner}/web/collaborators/ada"), client::response().status(204)) + .with(&format!("api.github.com/repos/{owner}/docs/collaborators/ada"), client::response().status(204)) + .with( + &format!("api.github.com/repos/{owner}/web/collaborators/ada/permission"), + json!({ "role_name": "maintain" }), + ) + .with( + &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(&format!("api.github.com/repos/{owner}/web"), json!({ "id": 42, "private": true, "license": null })) +} + +async fn projects(org_id: i64) -> laravel::Result, Option)>> { + let rows = db::query!( + "SELECT slug, repository_url, forge_installation FROM projects WHERE organization_id = {org_id} ORDER BY slug" + ) + .select() + .await?; + rows.iter() + .map(|r| Ok((r.try_get("slug")?, r.try_get("repository_url")?, r.try_get("forge_installation")?))) + .collect() +} + +#[laravel::test(app = github)] +async fn installed_on_her_own_account_it_fills_her_organization(_app: Application) -> laravel::Result<()> { + let (ada, org) = ada().await?; + assert!(projects(org.id).await?.is_empty(), "signing up makes no Default project"); + remember(ada.id, &[installation("7", "1001", "ada", "User")]).await?; + let _github = granted("ada"); + + let done = installations::set_up(&github_app(), &ada, "7").await?; + assert_eq!(done.organization, org.slug); + assert!(!done.organization_created); + assert_eq!(done.linked.len(), 1, "{done:?}"); + assert_eq!((done.linked[0].project.as_str(), done.linked[0].repository.as_str()), ("web", "ada/web")); + assert_eq!(done.skipped.len(), 1); + assert_eq!(done.skipped[0].repository, "ada/docs"); + assert!(done.skipped[0].reason.contains("you're write"), "{}", done.skipped[0].reason); + assert_eq!( + projects(org.id).await?, + vec![("web".into(), Some("https://github.com/ada/web".into()), Some("7".into()))] + ); + let state = app::auth::setup::state(org.id, Some(ada.pid)).await?; + assert_eq!(state["next"], "add_to_ci", "{state}"); + assert_eq!(state["installations"][0]["organization"], org.slug.as_str()); + assert_eq!(state["github"][0]["result"]["skipped"][0]["repository"], "ada/docs"); + + // Again: nothing new, the project already there + let again = installations::set_up(&github_app(), &ada, "7").await?; + assert!(again.linked.is_empty()); + assert_eq!(again.already.len(), 1); + assert_eq!(projects(org.id).await?.len(), 1); + Ok(()) +} + +#[laravel::test(app = github)] +async fn installed_on_a_github_organization_it_makes_one_named_after_it(_app: Application) -> laravel::Result<()> { + let (ada, _) = ada().await?; + remember(ada.id, &[installation("7", "5005", "Acme", "Organization")]).await?; + let _github = granted("Acme"); + + let done = installations::set_up(&github_app(), &ada, "7").await?; + assert_eq!(done.organization, "acme"); + assert!(done.organization_created); + assert_eq!(done.note, None); + let org = Organization::query().filter(Organization::slug.eq("acme")).first().await?.expect("acme"); + assert_eq!(org.name, "Acme Inc"); + let (org_id, ada_id) = (org.id, ada.id); + let role: Option = + db::query!("SELECT role FROM memberships WHERE organization_id = {org_id} AND user_id = {ada_id}") + .scalar() + .await?; + assert_eq!(role.as_deref(), Some("admin")); + assert_eq!(projects(org.id).await?.len(), 1); + Ok(()) +} + +#[laravel::test(app = github)] +async fn a_taken_slug_becomes_login_github_with_a_note(_app: Application) -> laravel::Result<()> { + app::testing::fixtures::organization("acme").await?; + let (ada, _) = ada().await?; + remember(ada.id, &[installation("7", "5005", "acme", "Organization")]).await?; + let _github = granted("acme"); + let done = installations::set_up(&github_app(), &ada, "7").await?; + assert_eq!(done.organization, "acme-github"); + assert!(done.note.as_deref().is_some_and(|n| n.contains("acme-github")), "{:?}", done.note); + Ok(()) +} + +#[laravel::test(app = github)] +async fn someone_else_cannot_set_up_an_installation_they_cannot_reach(_app: Application) -> laravel::Result<()> { + let (ada, _) = ada().await?; + remember(ada.id, &[installation("7", "5005", "acme", "Organization")]).await?; + let bob = create!(User { pid: laravel::str::uuid7(), name: "Bob", email: "bob@example.com", staff: false }).await?; + let err = installations::set_up(&github_app(), &bob, "7").await.expect_err("not his"); + assert_eq!(err.status().as_u16(), 404); + Ok(()) +} + +#[laravel::test(app = github)] +async fn the_setup_url_signs_in_refreshes_once_and_lands_on_the_organization(app: Application) -> laravel::Result<()> { + // Signed out: off to sign in, and back here after + let r = app.get("/github/setup?installation_id=7&setup_action=install").await; + r.assert_status(302) + .assert_header("location", "/auth/github?return_to=%2Fgithub%2Fsetup%3Finstallation_id%3D7%26refreshed%3D1"); + let (ada, org) = ada().await?; + // Signed in, but her list doesn't have it: one more sign-in refreshes it + let r = app.get("/github/setup?installation_id=7").acting_as(&ada).await; + r.assert_status(302); + let r = app.get("/github/setup?installation_id=7&refreshed=1").acting_as(&ada).await; + r.assert_ok().assert_see("isn't yours"); + + remember(ada.id, &[installation("7", "1001", "ada", "User")]).await?; + let _github = granted("ada"); + let r = app.get("/github/setup?installation_id=7").acting_as(&ada).await; + r.assert_status(302).assert_header("location", &format!("/{}?setup=add_to_ci&installation=7", org.slug)); + // No installation ID: an owner still has to approve it + app.get("/github/setup?setup_action=request").acting_as(&ada).await.assert_ok().assert_see("Waiting for GitHub"); + Ok(()) +} + +#[laravel::test(app = github)] +async fn the_checklist_offer_sets_it_up_over_the_api(app: Application) -> laravel::Result<()> { + let (ada, org) = ada().await?; + remember(ada.id, &[installation("7", "1001", "ada", "User")]).await?; + let state = app::auth::setup::state(org.id, Some(ada.pid)).await?; + assert_eq!(state["installations"][0]["installation_id"], "7"); + assert_eq!(state["installations"][0]["organization"], serde_json::Value::Null, "an offer: not set up yet"); + let _github = granted("ada"); + app.post("/api/ui/installations/7/setup") + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .header("accept", "application/json") + .json(json!({})) + .await + .assert_ok() + .assert_json_path("organization", org.slug.as_str()) + .assert_json_path("landing", format!("/{}?setup=add_to_ci&installation=7", org.slug).as_str()); + Ok(()) +} + +#[laravel::test(app = github)] +async fn webhooks_record_installations_and_add_repositories(app: Application) -> laravel::Result<()> { + let (ada, org) = ada().await?; + let _github = granted("ada"); + let account = json!({ "id": 1001, "login": "ada", "type": "User" }); + deliver( + &app, + "installation", + json!({ "action": "created", "installation": { "id": 7, "account": account }, "sender": { "id": 1001 }, + "repositories": [] }), + ) + .await + .assert_ok(); + assert!(installations::reachable(ada.id, "7").await?, "the installer can set it up before signing in again"); + + // Not set up yet: an added repository makes no project + let added = json!({ "action": "added", "installation": { "id": 7, "account": account }, "sender": { "id": 1001 }, + "repositories_added": [{ "full_name": "ada/web", "id": 42 }] }); + deliver(&app, "installation_repositories", added.clone()).await.assert_ok(); + assert!(projects(org.id).await?.is_empty()); + + let id = org.id; + db::query!("UPDATE github_installations SET organization_id = {id} WHERE installation_id = '7'").update().await?; + deliver(&app, "installation_repositories", added).await.assert_ok(); + assert_eq!(projects(org.id).await?.len(), 1, "added to a set-up installation: a project"); + + deliver(&app, "installation", json!({ "action": "suspend", "installation": { "id": 7, "account": account } })) + .await + .assert_ok(); + let suspended: Option = + db::query!("SELECT suspended_at IS NOT NULL FROM github_installations WHERE installation_id = '7'") + .scalar() + .await?; + assert_eq!(suspended, Some(true)); + deliver(&app, "installation", json!({ "action": "deleted", "installation": { "id": 7, "account": account } })) + .await + .assert_ok(); + assert!(!installations::reachable(ada.id, "7").await?); + let mapped: Option = + db::query!("SELECT organization_id FROM github_installations WHERE installation_id = '7'").scalar().await?; + assert_eq!(mapped, Some(org.id), "kept, so installing it again finds the organization"); + Ok(()) +} + +#[test] +fn project_slugs_come_from_repository_names() { + assert_eq!(installations::project_slug("My.Repo_2"), "my-repo-2"); + assert_eq!(installations::project_slug("billing"), "billing-project"); +} diff --git a/app/tests/organizations.rs b/app/tests/organizations.rs index d3b6d0ea..6807896c 100644 --- a/app/tests/organizations.rs +++ b/app/tests/organizations.rs @@ -11,7 +11,7 @@ async fn user(name: &str, email: &str) -> laravel::Result { } #[laravel::test] -async fn signing_up_makes_an_organization_with_a_default_project(_app: Application) -> laravel::Result<()> { +async fn signing_up_makes_an_empty_organization(_app: Application) -> laravel::Result<()> { let ada = user("Ada Lovelace", "ada.l@example.com").await?; SignedUp { user_id: ada.id, via: "web".into() }.dispatch().await?; @@ -21,7 +21,7 @@ async fn signing_up_makes_an_organization_with_a_default_project(_app: Applicati assert_eq!((member.user_id, member.role.as_str(), member.source.as_str()), (ada.id, "admin", "created")); let projects: Vec = Project::query().filter(Project::organization_id.eq(org.id)).get().await?.into_iter().map(|p| p.slug).collect(); - assert_eq!(projects, vec!["default"]); + assert!(projects.is_empty(), "setting up the GitHub App makes its projects: {projects:?}"); Ok(()) } @@ -29,7 +29,7 @@ async fn signing_up_makes_an_organization_with_a_default_project(_app: Applicati async fn a_taken_slug_gets_a_number(_app: Application) -> laravel::Result<()> { fixtures::organization("ada").await?; let ada = user("Ada", "ada@example.com").await?; - let (org, _) = Organization::create_personal(&ada).await?; + let org = Organization::create_personal(&ada).await?; assert_eq!(org.slug, "ada-2"); Ok(()) } diff --git a/app/tests/setup.rs b/app/tests/setup.rs index 16814712..da0d787e 100644 --- a/app/tests/setup.rs +++ b/app/tests/setup.rs @@ -23,7 +23,9 @@ async fn the_checklist_follows_what_happened(app: Application) -> laravel::Resul .insert() .await?; let state = app::auth::setup::state(org, Some(ada.pid)).await?; - assert_eq!(state["next"], "connect_agent"); + assert_eq!(state["next"], "install_github_app"); + let keys: Vec<&str> = state["steps"].as_array().unwrap().iter().map(|s| s["key"].as_str().unwrap()).collect(); + assert_eq!(keys, ["install_github_app", "add_to_ci", "connect_agent", "review_changes"]); // A used personal token ticks it for her; nobody's (a project token's view) never does db::query!( "INSERT INTO user_tokens (user_id, name, token_hash, token_prefix, last_used_at, created_at, updated_at) \ @@ -31,8 +33,8 @@ async fn the_checklist_follows_what_happened(app: Application) -> laravel::Resul ) .insert() .await?; - assert_eq!(app::auth::setup::state(org, Some(ada.pid)).await?["steps"][0]["done"], true); - assert_eq!(app::auth::setup::state(org, None).await?["steps"][0]["done"], false); + assert_eq!(app::auth::setup::state(org, Some(ada.pid)).await?["steps"][2]["done"], true); + assert_eq!(app::auth::setup::state(org, None).await?["steps"][2]["done"], false); db::query!( "INSERT INTO projects (pid, organization_id, slug, name, forge_installation, created_at, updated_at) \ VALUES (gen_random_uuid(), {org}, 'web', 'Web', '7', now(), now())" @@ -40,8 +42,8 @@ async fn the_checklist_follows_what_happened(app: Application) -> laravel::Resul .insert() .await?; let state = app::auth::setup::state(org, Some(ada.pid)).await?; - assert_eq!(state["steps"][1]["done"], true); - assert_eq!(state["steps"][2]["done"], true); + assert_eq!(state["steps"][0]["done"], true, "a project on the App's installation"); + assert_eq!(state["steps"][1]["done"], false); assert_eq!(state["complete"], false); let close = |dismissed: bool| { diff --git a/docs/design.md b/docs/design.md index fbcc5c47..8615325d 100644 --- a/docs/design.md +++ b/docs/design.md @@ -343,6 +343,18 @@ A project links to a forge plus a repository URL (`projects.forge`, `projects.re notice on the project), so nobody keeps posting VisualCI's checks to a repository they've lost. Permission is always looked up by the person's permanent forge user ID, never a stored login, which can be renamed and taken. +**Onboarding through the GitHub App (sc-9027).** Signing up makes an empty personal organization; installing the GitHub +App makes the projects. `github_installations` records every installation VisualCI hears of (from a sign-in, which +lists the ones the person can reach into `user_installations`, and from the `installation` webhook: created, +suspended, removed, with removed rows kept so a reinstall finds its organization again). The App's Setup URL, +`GET /github/setup?installation_id=…` on the app host, maps the installation to an organization: the person's own +account to their personal organization; a GitHub organization to the one it was set up for before, else a new one +whose slug is the lowercased login (`-github` when taken), with the installer as admin and everyone else joining +through the hourly sync. Each granted repository the installer can Maintain becomes a project linked through the usual +link checks; the rest are listed with the reason. Repositories added to a set-up installation later become projects +in its organization. The checklist (`install_github_app`, `add_to_ci`, `connect_agent`, `review_changes`) offers +installations the person can reach that aren't set up yet (`POST /api/ui/installations/{id}/setup`). + **GitLab.** GitLab has no app installations, so VisualCI acts through a bot user on gitlab.com (`@visualci`, its personal access token in `settings.gitlab.bot_token`). A project's `forge_installation` is `bot` once the bot is a member: a Developer can post the commit status and the merge request note (one per MR, edited in place) and check From 82390bc274f5c8c2066862d15e50de54e219e6c9 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 18:28:27 +1300 Subject: [PATCH 2/2] app/: sc-9027 PR 1 review fixes: a new claim is checked live on GitHub (own account, an owner of the organization, or its installer) before any organization or mapping is written; the mapping is written only where none exists; GET /github/setup sets up only the install this browser started (state); personal organization by ID; orphaned goldens removed --- .../2026_12_03_100000_github_installations.rs | 9 +- app/src/auth/installations.rs | 60 ++++++++-- app/src/auth/setup.rs | 2 +- app/src/forge/github_app.rs | 20 ++++ app/src/forge/installations.rs | 105 ++++++++++++++---- app/src/models/organizations.rs | 4 + .../get-snapshots.json | 49 -------- .../create_build-2.json | 52 --------- .../create_build.json | 52 --------- .../list_builds-2.json | 54 --------- .../list_builds-3.json | 53 --------- .../list_builds-4.json | 54 --------- .../list_builds.json | 89 --------------- .../whoami-2.json | 66 ----------- .../whoami-3.json | 27 ----- .../whoami-4.json | 66 ----------- .../whoami.json | 73 ------------ .../get_organization.json | 4 +- .../whoami.json | 4 +- .../get_organization.json | 4 +- .../create_organization.json | 15 --- .../get_project.json | 55 --------- .../get_organization.json | 4 +- app/tests/installations.rs | 61 +++++++++- docs/design.md | 14 ++- 25 files changed, 238 insertions(+), 758 deletions(-) delete mode 100644 app/tests/golden/api/registers_snapshots_and_asks_for_new_files/get-snapshots.json delete mode 100644 app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/create_build-2.json delete mode 100644 app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/create_build.json delete mode 100644 app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/list_builds-2.json delete mode 100644 app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/list_builds-3.json delete mode 100644 app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/list_builds-4.json delete mode 100644 app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/list_builds.json delete mode 100644 app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/whoami-2.json delete mode 100644 app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/whoami-3.json delete mode 100644 app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/whoami-4.json delete mode 100644 app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/whoami.json delete mode 100644 app/tests/golden/mcp/a_project_token_reaches_only_its_project/create_organization.json delete mode 100644 app/tests/golden/mcp/a_project_token_reaches_only_its_project/get_project.json diff --git a/app/database/migrations/2026_12_03_100000_github_installations.rs b/app/database/migrations/2026_12_03_100000_github_installations.rs index a5a3927b..c91e4795 100644 --- a/app/database/migrations/2026_12_03_100000_github_installations.rs +++ b/app/database/migrations/2026_12_03_100000_github_installations.rs @@ -3,7 +3,8 @@ //! `github_installations` is every installation of the VisualCI GitHub App VisualCI has heard of, from a person's //! sign-in (GitHub lists the installations they can reach) or from the `installation` webhook, and the organization //! it was set up for once someone has. `user_installations` is which installations each person can reach, as of their -//! last sign-in: the setup page and the checklist's "already installed on X" offers read it. +//! last sign-in: the setup page and the checklist's "already installed on X" offers read it. `users.personal_organization_id` +//! is the organization signing up made. use laravel::db::AnyTransaction; @@ -24,6 +25,9 @@ CREATE TABLE github_installations ( -- The organization it was set up for: none until someone sets it up. organization_id BIGINT REFERENCES organizations(id) ON DELETE SET NULL, set_up_by BIGINT REFERENCES users(id) ON DELETE SET NULL, + -- The GitHub user ID of whoever installed it (the `installation` webhook's sender): they may set it up for a + -- GitHub organization without being one of its owners. + installed_by TEXT, suspended_at TIMESTAMPTZ, -- Removed on GitHub. Kept so the account's organization is found again if the App is installed again. deleted_at TIMESTAMPTZ, @@ -42,4 +46,7 @@ CREATE TABLE user_installations ( PRIMARY KEY (user_id, installation_id) ); CREATE INDEX user_installations_installation ON user_installations (installation_id); + +-- The organization signing up made: an installation on the person's own GitHub account is set up there. +ALTER TABLE users ADD COLUMN personal_organization_id BIGINT REFERENCES organizations(id) ON DELETE SET NULL; "#; diff --git a/app/src/auth/installations.rs b/app/src/auth/installations.rs index b38aa918..8aa420cb 100644 --- a/app/src/auth/installations.rs +++ b/app/src/auth/installations.rs @@ -1,27 +1,38 @@ //! Setting up the GitHub App from the app (sc-9027, onboarding). //! -//! - `GET /github/setup?installation_id=…` is the GitHub App's Setup URL: GitHub sends people there after they -//! install it. Someone signed out signs in first and comes back; an installation their account can't reach yet -//! sends them through GitHub's sign-in once more, which refreshes the list. Then [`set_up`] gives it an organization -//! and projects, and they land on the organization's page with the next step (adding VisualCI to CI) open. -//! - `POST /api/ui/installations/{id}/setup` does the same for an installation the checklist offers ("already +//! - `GET /github/install` sends someone to install the App, with a `state` kept in their session. +//! - `GET /github/setup?installation_id=…&state=…` is the App's Setup URL: GitHub sends people there after they +//! install it, with that `state`. Someone signed out signs in first and comes back; an installation their account +//! can't reach yet sends them through GitHub's sign-in once more, which refreshes the list. With the session's +//! `state`, [`set_up`](installations::set_up) gives it an organization and projects, and they land on the +//! organization's page with the next step (adding VisualCI to CI) open. Without it (a link from another site), it +//! changes nothing: they land on their own organization's page, where the checklist offers the installation and a +//! click sets it up. +//! - `POST /api/ui/installations/{id}/setup` is that click: it sets up an installation the checklist offers ("already //! installed on X: set it up"), and answers what it did as JSON. use laravel::auth::{Auth, Authenticated}; use laravel::prelude::*; +use laravel::session::Session; -use crate::forge::github_app::GithubApp; +use crate::forge::github_app::{self, GithubApp}; use crate::forge::installations::{self, SetUp}; use crate::models::User; pub fn routes(route: &mut Router) { + route.get("/github/install", install); route.get("/github/setup", setup_page); route.post("/api/ui/installations/{id}/setup", setup); } +/// The session key holding the `state` sent to GitHub with an install. +const STATE: &str = "github.install_state"; + #[laravel::query] pub struct SetupQuery { installation_id: Option, + /// What `/github/install` sent GitHub, back from it. + state: Option, /// Set on the way back from the sign-in that refreshed their installations, so it happens once. refreshed: Option, } @@ -32,10 +43,22 @@ pub fn landing(outcome: &SetUp) -> String { format!("/{}?setup=add_to_ci&installation={}", outcome.organization, outcome.installation_id) } -/// Back to this page after signing in with GitHub. The ID is digits only, so it's safe in the URL as it is. -fn through_sign_in(installation_id: &str) -> Redirect { +/// `GET /github/install`: off to GitHub to install the App, with a `state` that brings the set-up back to this +/// browser's session. +pub async fn install(session: Session) -> Redirect { + let state = laravel::str::random(32); + session.put(STATE, state.clone()); + Redirect::to(format!("{}?state={state}", github_app::INSTALL_URL)) +} + +/// Back to this page after signing in with GitHub. The ID is digits and the state letters and digits, so both are +/// safe in the URL as they are. +fn through_sign_in(installation_id: &str, state: Option<&str>) -> Redirect { + let state = state + .filter(|s| s.bytes().all(|b| b.is_ascii_alphanumeric())) + .map_or(String::new(), |s| format!("%26state%3D{s}")); Redirect::to(format!( - "/auth/github?return_to=%2Fgithub%2Fsetup%3Finstallation_id%3D{installation_id}%26refreshed%3D1" + "/auth/github?return_to=%2Fgithub%2Fsetup%3Finstallation_id%3D{installation_id}{state}%26refreshed%3D1" )) } @@ -43,6 +66,7 @@ fn through_sign_in(installation_id: &str) -> Redirect { pub async fn setup_page( auth: Auth, app: laravel::config::Section, + session: Session, Query(q): Query, ) -> laravel::Result { // GitHub sends no installation ID when an organization's owner still has to approve the request @@ -55,10 +79,12 @@ pub async fn setup_page( the request. Once they have, come back and set it up from your organization's page.", )); }; - let Some(user) = auth.user().await? else { return Ok(laravel::http::Response::new(through_sign_in(&id))) }; + let Some(user) = auth.user().await? else { + return Ok(laravel::http::Response::new(through_sign_in(&id, q.state.as_deref()))); + }; if !installations::reachable(user.id, &id).await? { if q.refreshed.is_none() { - return Ok(laravel::http::Response::new(through_sign_in(&id))); + return Ok(laravel::http::Response::new(through_sign_in(&id, q.state.as_deref()))); } return Ok(page( "That installation isn't yours", @@ -66,6 +92,18 @@ pub async fn setup_page( the GitHub account that installed it.", )); } + // Only the install this browser started sets anything up from a GET; anything else asks for a click first + let expected: Option = session.pull(STATE); + if expected.is_none() || expected != q.state { + let user_id = user.id; + let personal: Option = laravel::db::query!( + "SELECT o.slug FROM users u JOIN organizations o ON o.id = u.personal_organization_id WHERE u.id = {user_id}" + ) + .scalar() + .await?; + let to = personal.map_or_else(|| "/".to_string(), |slug| format!("/{slug}?setup=install_github_app")); + return Ok(laravel::http::Response::new(Redirect::to(to))); + } match installations::set_up(&app, &user, &id).await { Ok(outcome) => Ok(laravel::http::Response::new(Redirect::to(landing(&outcome)))), Err(e) if e.status().is_client_error() => Ok(page("Couldn't set VisualCI up", &e.to_string())), diff --git a/app/src/auth/setup.rs b/app/src/auth/setup.rs index 76d4f380..79adf14a 100644 --- a/app/src/auth/setup.rs +++ b/app/src/auth/setup.rs @@ -83,7 +83,7 @@ pub async fn state(org_id: i64, user_pid: Option) -> laravel "next": next, "complete": complete, "dismissed": row.try_get::>("dismissed")?.unwrap_or(false), - "install_url": crate::forge::github_app::INSTALL_URL, + "install_url": "/github/install", "installations": offers, "github": set_up, })) diff --git a/app/src/forge/github_app.rs b/app/src/forge/github_app.rs index 50c031b1..c926689e 100644 --- a/app/src/forge/github_app.rs +++ b/app/src/forge/github_app.rs @@ -151,6 +151,26 @@ pub async fn account_name(token: &str, login: &str, account_type: &str) -> larav .unwrap_or_else(|| login.to_string())) } +/// A GitHub user's role in a GitHub organization (`admin` for an owner, `member`), read live with an installation's +/// token: `None` when they aren't an active member, or the App can't read the organization's members (it needs the +/// Members: read permission). +/// +/// # Errors +/// When GitHub can't be reached. +pub async fn organization_role(token: &str, org: &str, user_id: &str) -> laravel::Result> { + let Ok(id) = user_id.parse::() else { return Ok(None) }; + let Some(user) = get(token, &format!("/user/{id}")).await? else { return Ok(None) }; + let Some(login) = user["login"].as_str() else { return Ok(None) }; + match get(token, &format!("/orgs/{org}/memberships/{login}")).await { + Ok(Some(m)) if m["state"] == "active" => Ok(m["role"].as_str().map(str::to_string)), + Ok(_) => Ok(None), + Err(e) => { + tracing::warn!(org, error = %e, "reading an organization membership"); + Ok(None) + } + } +} + /// Where people install the App on their repositories. pub const INSTALL_URL: &str = "https://github.com/apps/visualci-com/installations/new"; diff --git a/app/src/forge/installations.rs b/app/src/forge/installations.rs index efe3703a..1abc797c 100644 --- a/app/src/forge/installations.rs +++ b/app/src/forge/installations.rs @@ -148,6 +148,13 @@ pub async fn from_webhook(app: &GithubApp, kind: &str, event: &Value) -> laravel db::query!("UPDATE github_installations SET suspended_at = NULL WHERE installation_id = {id}") .update() .await?; + if action == "created" + && let Some(sender) = event["sender"]["id"].as_i64().map(|i| i.to_string()) + { + db::query!("UPDATE github_installations SET installed_by = {sender} WHERE installation_id = {id}") + .update() + .await?; + } // Whoever installed it can reach it: the setup page and checklist offer it to them before they sign in // again if let Some(sender) = event["sender"]["id"].as_i64().map(|i| i.to_string()) @@ -286,7 +293,8 @@ pub async fn set_up(app: &GithubApp, user: &User, installation_id: &str) -> lara } let id = installation_id.to_string(); let row = db::query!( - "SELECT account_id, account_login, account_type, organization_id, suspended_at IS NOT NULL AS suspended \ + "SELECT account_id, account_login, account_type, organization_id, installed_by, \ + suspended_at IS NOT NULL AS suspended \ FROM github_installations WHERE installation_id = {id}" ) .select_one() @@ -294,6 +302,7 @@ pub async fn set_up(app: &GithubApp, user: &User, installation_id: &str) -> lara .ok_or_else(|| laravel::abort(404))?; let (account_id, login, account_type): (String, String, String) = (row.try_get("account_id")?, row.try_get("account_login")?, row.try_get("account_type")?); + let installed_by: Option = row.try_get("installed_by")?; if row.try_get::("suspended")? { return Err(refused( 409, @@ -306,21 +315,29 @@ pub async fn set_up(app: &GithubApp, user: &User, installation_id: &str) -> lara None => { db::query!( "SELECT organization_id FROM github_installations \ - WHERE account_id = {account_id} AND organization_id IS NOT NULL ORDER BY updated_at DESC LIMIT 1" + WHERE account_id = {account_id} AND organization_id IS NOT NULL ORDER BY updated_at DESC LIMIT 1" ) .scalar() .await? } }; - let own_account = account_type == "User" && github_id(user.id).await?.as_deref() == Some(account_id.as_str()); let (organization, created, note) = match mapped { + // Already set up: only that organization's admins add to it Some(o) => (Organization::find(o).await?.ok_or_else(|| laravel::abort(404))?, false, None), - None if own_account => (personal(user, &account_id).await?, false, None), None => { - let token = github_app::installation_token(app, installation_id).await?; - let name = github_app::account_name(&token, &login, &account_type).await?; - let (org, note) = create_for_account(user, &login, &name).await?; - (org, true, note) + // A new claim: checked live on GitHub before anything is written, since reaching one repository through + // an installation says nothing about owning the account it's on + let own = + may_claim(app, user, installation_id, &account_id, &login, &account_type, installed_by.as_deref()) + .await?; + if own { + (personal(user).await?, false, None) + } else { + let token = github_app::installation_token(app, installation_id).await?; + let name = github_app::account_name(&token, &login, &account_type).await?; + let (org, note) = create_for_account(user, &login, &name).await?; + (org, true, note) + } } }; if role_in(organization.id, user.id).await? != Some(Role::Admin) { @@ -333,12 +350,21 @@ pub async fn set_up(app: &GithubApp, user: &User, installation_id: &str) -> lara )); } let (org_id, user_id) = (organization.id, user.id); - db::query!( - "UPDATE github_installations SET organization_id = {org_id}, set_up_by = {user_id}, updated_at = now() \ - WHERE installation_id = {id}" + // Only if nobody mapped it elsewhere meanwhile (two people setting it up at once) + let mapped_now = db::query!( + "UPDATE github_installations SET organization_id = {org_id}, \ + set_up_by = COALESCE(set_up_by, {user_id}), updated_at = now() \ + WHERE installation_id = {id} AND (organization_id IS NULL OR organization_id = {org_id})" ) .update() .await?; + if mapped_now == 0 { + if created { + db::query!("DELETE FROM memberships WHERE organization_id = {org_id}").delete().await?; + db::query!("DELETE FROM organizations WHERE id = {org_id}").delete().await?; + } + return Err(refused(409, format!("someone else has just set VisualCI up for {login}: reload the page"))); + } let granted = { let token = github_app::installation_token(app, installation_id).await?; github_app::installation_repositories(&token, REPOSITORY_LIMIT + 1).await? @@ -374,25 +400,58 @@ async fn github_id(user_id: i64) -> laravel::Result> { .await } -/// The person's own organization: the first one they created that isn't set up for another GitHub account, else a -/// new one. -async fn personal(user: &User, account_id: &str) -> laravel::Result { +/// The person's own organization, the one signing up made (a new one if it's gone). +async fn personal(user: &User) -> laravel::Result { let user_id = user.id; - let found: Option = db::query!( - "SELECT o.id FROM organizations o JOIN memberships m ON m.organization_id = o.id \ - WHERE m.user_id = {user_id} AND m.source = 'created' AND m.role = 'admin' \ - AND NOT EXISTS (SELECT 1 FROM github_installations g \ - WHERE g.organization_id = o.id AND g.account_id <> {account_id}) \ - ORDER BY o.id LIMIT 1" - ) - .scalar() - .await?; + let found: Option> = + db::query!("SELECT personal_organization_id FROM users WHERE id = {user_id}").scalar().await?; + let found = found.flatten(); match found { Some(id) => Organization::find(id).await?.ok_or_else(|| laravel::abort(404)), None => Organization::create_personal(user).await, } } +/// Whether `user` may set up an installation nobody has set up yet, checked live on GitHub: `Ok(true)` for their own +/// account, `Ok(false)` for a GitHub organization they own or installed the App on. Anything else is a 403: another +/// person's account, or an organization where they're only a member. +async fn may_claim( + app: &GithubApp, + user: &User, + installation_id: &str, + account_id: &str, + login: &str, + account_type: &str, + installed_by: Option<&str>, +) -> laravel::Result { + let Some(me) = github_id(user.id).await? else { + return Err(refused(403, "sign in with GitHub first")); + }; + if account_type != "Organization" { + if me == account_id { + return Ok(true); + } + return Err(refused( + 403, + format!("the VisualCI GitHub App is installed on {login}'s own GitHub account: only {login} can set it up"), + )); + } + if installed_by == Some(me.as_str()) { + return Ok(false); + } + let token = github_app::installation_token(app, installation_id).await?; + if github_app::organization_role(&token, login, &me).await?.as_deref() == Some("admin") { + return Ok(false); + } + Err(refused( + 403, + format!( + "only an owner of {login} on GitHub, or whoever installed the VisualCI GitHub App there, can set it up: \ + ask one of them" + ), + )) +} + /// A new organization for a GitHub account, with `user` as its admin: slug the lowercased login, else /// `-github` (then `-2`, `-3`…), with a note saying why. async fn create_for_account(user: &User, login: &str, name: &str) -> laravel::Result<(Organization, Option)> { diff --git a/app/src/models/organizations.rs b/app/src/models/organizations.rs index b5ebc7d6..9101b351 100644 --- a/app/src/models/organizations.rs +++ b/app/src/models/organizations.rs @@ -93,6 +93,10 @@ impl Organization { source: "created", }) .await?; + let org_id = org.id; + laravel::db::query!("UPDATE users SET personal_organization_id = {org_id} WHERE id = {user_id}") + .update() + .await?; Ok(org) }) .await; diff --git a/app/tests/golden/api/registers_snapshots_and_asks_for_new_files/get-snapshots.json b/app/tests/golden/api/registers_snapshots_and_asks_for_new_files/get-snapshots.json deleted file mode 100644 index 7adfabad..00000000 --- a/app/tests/golden/api/registers_snapshots_and_asks_for_new_files/get-snapshots.json +++ /dev/null @@ -1,49 +0,0 @@ -{ - "snapshots": [ - { - "error": null, - "id": "", - "kind": "text", - "name": "api/response", - "platform": "", - "review": null, - "state": "pending" - }, - { - "error": null, - "id": "", - "kind": "document", - "name": "invoice", - "platform": "", - "review": null, - "state": "pending" - }, - { - "error": null, - "id": "", - "kind": "text", - "name": "log", - "platform": "", - "review": null, - "state": "pending" - }, - { - "error": null, - "id": "", - "kind": "text", - "name": "page.html", - "platform": "", - "review": null, - "state": "pending" - }, - { - "error": null, - "id": "", - "kind": "text", - "name": "tree", - "platform": "", - "review": null, - "state": "pending" - } - ] -} diff --git a/app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/create_build-2.json b/app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/create_build-2.json deleted file mode 100644 index 718b41b0..00000000 --- a/app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/create_build-2.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "arguments": { - "branch": "main", - "commit": "abc123", - "mode": "ci", - "project": "/pdfs" - }, - "result": { - "content": [ - { - "text": "{\"blocked\":null,\"branch\":\"main\",\"ci_mode\":\"review\",\"commit\":\"abc123\",\"conclusion\":null,\"created_at\":\"\",\"environment\":\"ci\",\"environment_info\":{},\"error\":null,\"id\":\"\",\"mode\":\"ci\",\"name\":\"default\",\"number\":2,\"passed\":null,\"pr_number\":null,\"project\":\"/pdfs\",\"review_state\":\"none\",\"reviewable\":false,\"reviews\":[],\"state\":\"receiving\",\"stats\":{\"added\":0,\"changed\":0,\"config\":0,\"failed\":0,\"ignored\":0,\"pending\":0,\"removed\":0,\"total\":0,\"unchanged\":0},\"url\":\"https://app.visualci.test//pdfs/builds/2\",\"warnings\":[]}", - "type": "text" - } - ], - "isError": false, - "structuredContent": { - "blocked": null, - "branch": "main", - "ci_mode": "review", - "commit": "abc123", - "conclusion": null, - "created_at": "", - "environment": "ci", - "environment_info": {}, - "error": null, - "id": "", - "mode": "ci", - "name": "default", - "number": 2, - "passed": null, - "pr_number": null, - "project": "/pdfs", - "review_state": "none", - "reviewable": false, - "reviews": [], - "state": "receiving", - "stats": { - "added": 0, - "changed": 0, - "config": 0, - "failed": 0, - "ignored": 0, - "pending": 0, - "removed": 0, - "total": 0, - "unchanged": 0 - }, - "url": "https://app.visualci.test//pdfs/builds/2", - "warnings": [] - } - } -} diff --git a/app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/create_build.json b/app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/create_build.json deleted file mode 100644 index b7ac6304..00000000 --- a/app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/create_build.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "arguments": { - "branch": "my-branch", - "commit": "abc123", - "mode": "local", - "project": "/pdfs" - }, - "result": { - "content": [ - { - "text": "{\"blocked\":null,\"branch\":\"my-branch\",\"ci_mode\":\"review\",\"commit\":\"abc123\",\"conclusion\":null,\"created_at\":\"\",\"environment\":\"local\",\"environment_info\":{},\"error\":null,\"id\":\"\",\"mode\":\"local\",\"name\":\"default\",\"number\":1,\"passed\":null,\"pr_number\":null,\"project\":\"/pdfs\",\"review_state\":\"none\",\"reviewable\":false,\"reviews\":[],\"state\":\"receiving\",\"stats\":{\"added\":0,\"changed\":0,\"config\":0,\"failed\":0,\"ignored\":0,\"pending\":0,\"removed\":0,\"total\":0,\"unchanged\":0},\"url\":\"https://app.visualci.test//pdfs/builds/1\",\"warnings\":[]}", - "type": "text" - } - ], - "isError": false, - "structuredContent": { - "blocked": null, - "branch": "my-branch", - "ci_mode": "review", - "commit": "abc123", - "conclusion": null, - "created_at": "", - "environment": "local", - "environment_info": {}, - "error": null, - "id": "", - "mode": "local", - "name": "default", - "number": 1, - "passed": null, - "pr_number": null, - "project": "/pdfs", - "review_state": "none", - "reviewable": false, - "reviews": [], - "state": "receiving", - "stats": { - "added": 0, - "changed": 0, - "config": 0, - "failed": 0, - "ignored": 0, - "pending": 0, - "removed": 0, - "total": 0, - "unchanged": 0 - }, - "url": "https://app.visualci.test//pdfs/builds/1", - "warnings": [] - } - } -} diff --git a/app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/list_builds-2.json b/app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/list_builds-2.json deleted file mode 100644 index d9900d5a..00000000 --- a/app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/list_builds-2.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "arguments": { - "project": "/pdfs", - "waiting_for_review": true - }, - "result": { - "content": [ - { - "text": "{\"builds\":[{\"blocked\":null,\"branch\":\"main\",\"ci_mode\":\"review\",\"commit\":\"abc123\",\"conclusion\":\"changes\",\"created_at\":\"\",\"environment\":\"ci\",\"environment_info\":{},\"error\":null,\"id\":\"\",\"mode\":\"ci\",\"name\":\"default\",\"number\":2,\"passed\":true,\"pr_number\":null,\"project\":\"/pdfs\",\"review_state\":\"pending\",\"reviewable\":true,\"reviews\":[],\"state\":\"completed\",\"stats\":{\"added\":0,\"changed\":0,\"config\":0,\"failed\":0,\"ignored\":0,\"pending\":0,\"removed\":0,\"total\":0,\"unchanged\":0},\"url\":\"https://app.visualci.test//pdfs/builds/2\",\"warnings\":[]}]}", - "type": "text" - } - ], - "isError": false, - "structuredContent": { - "builds": [ - { - "blocked": null, - "branch": "main", - "ci_mode": "review", - "commit": "abc123", - "conclusion": "changes", - "created_at": "", - "environment": "ci", - "environment_info": {}, - "error": null, - "id": "", - "mode": "ci", - "name": "default", - "number": 2, - "passed": true, - "pr_number": null, - "project": "/pdfs", - "review_state": "pending", - "reviewable": true, - "reviews": [], - "state": "completed", - "stats": { - "added": 0, - "changed": 0, - "config": 0, - "failed": 0, - "ignored": 0, - "pending": 0, - "removed": 0, - "total": 0, - "unchanged": 0 - }, - "url": "https://app.visualci.test//pdfs/builds/2", - "warnings": [] - } - ] - } - } -} diff --git a/app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/list_builds-3.json b/app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/list_builds-3.json deleted file mode 100644 index be3038bc..00000000 --- a/app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/list_builds-3.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "arguments": { - "waiting_for_review": true - }, - "result": { - "content": [ - { - "text": "{\"builds\":[{\"blocked\":null,\"branch\":\"main\",\"ci_mode\":\"review\",\"commit\":\"abc123\",\"conclusion\":\"changes\",\"created_at\":\"\",\"environment\":\"ci\",\"environment_info\":{},\"error\":null,\"id\":\"\",\"mode\":\"ci\",\"name\":\"default\",\"number\":2,\"passed\":true,\"pr_number\":null,\"project\":\"/pdfs\",\"review_state\":\"pending\",\"reviewable\":true,\"reviews\":[],\"state\":\"completed\",\"stats\":{\"added\":0,\"changed\":0,\"config\":0,\"failed\":0,\"ignored\":0,\"pending\":0,\"removed\":0,\"total\":0,\"unchanged\":0},\"url\":\"https://app.visualci.test//pdfs/builds/2\",\"warnings\":[]}]}", - "type": "text" - } - ], - "isError": false, - "structuredContent": { - "builds": [ - { - "blocked": null, - "branch": "main", - "ci_mode": "review", - "commit": "abc123", - "conclusion": "changes", - "created_at": "", - "environment": "ci", - "environment_info": {}, - "error": null, - "id": "", - "mode": "ci", - "name": "default", - "number": 2, - "passed": true, - "pr_number": null, - "project": "/pdfs", - "review_state": "pending", - "reviewable": true, - "reviews": [], - "state": "completed", - "stats": { - "added": 0, - "changed": 0, - "config": 0, - "failed": 0, - "ignored": 0, - "pending": 0, - "removed": 0, - "total": 0, - "unchanged": 0 - }, - "url": "https://app.visualci.test//pdfs/builds/2", - "warnings": [] - } - ] - } - } -} diff --git a/app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/list_builds-4.json b/app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/list_builds-4.json deleted file mode 100644 index d9900d5a..00000000 --- a/app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/list_builds-4.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "arguments": { - "project": "/pdfs", - "waiting_for_review": true - }, - "result": { - "content": [ - { - "text": "{\"builds\":[{\"blocked\":null,\"branch\":\"main\",\"ci_mode\":\"review\",\"commit\":\"abc123\",\"conclusion\":\"changes\",\"created_at\":\"\",\"environment\":\"ci\",\"environment_info\":{},\"error\":null,\"id\":\"\",\"mode\":\"ci\",\"name\":\"default\",\"number\":2,\"passed\":true,\"pr_number\":null,\"project\":\"/pdfs\",\"review_state\":\"pending\",\"reviewable\":true,\"reviews\":[],\"state\":\"completed\",\"stats\":{\"added\":0,\"changed\":0,\"config\":0,\"failed\":0,\"ignored\":0,\"pending\":0,\"removed\":0,\"total\":0,\"unchanged\":0},\"url\":\"https://app.visualci.test//pdfs/builds/2\",\"warnings\":[]}]}", - "type": "text" - } - ], - "isError": false, - "structuredContent": { - "builds": [ - { - "blocked": null, - "branch": "main", - "ci_mode": "review", - "commit": "abc123", - "conclusion": "changes", - "created_at": "", - "environment": "ci", - "environment_info": {}, - "error": null, - "id": "", - "mode": "ci", - "name": "default", - "number": 2, - "passed": true, - "pr_number": null, - "project": "/pdfs", - "review_state": "pending", - "reviewable": true, - "reviews": [], - "state": "completed", - "stats": { - "added": 0, - "changed": 0, - "config": 0, - "failed": 0, - "ignored": 0, - "pending": 0, - "removed": 0, - "total": 0, - "unchanged": 0 - }, - "url": "https://app.visualci.test//pdfs/builds/2", - "warnings": [] - } - ] - } - } -} diff --git a/app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/list_builds.json b/app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/list_builds.json deleted file mode 100644 index e148ddcc..00000000 --- a/app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/list_builds.json +++ /dev/null @@ -1,89 +0,0 @@ -{ - "arguments": { - "project": "/pdfs", - "waiting_for_review": true - }, - "result": { - "content": [ - { - "text": "{\"builds\":[{\"blocked\":null,\"branch\":\"main\",\"ci_mode\":\"review\",\"commit\":\"abc123\",\"conclusion\":\"changes\",\"created_at\":\"\",\"environment\":\"ci\",\"environment_info\":{},\"error\":null,\"id\":\"\",\"mode\":\"ci\",\"name\":\"default\",\"number\":2,\"passed\":true,\"pr_number\":null,\"project\":\"/pdfs\",\"review_state\":\"pending\",\"reviewable\":true,\"reviews\":[],\"state\":\"completed\",\"stats\":{\"added\":0,\"changed\":0,\"config\":0,\"failed\":0,\"ignored\":0,\"pending\":0,\"removed\":0,\"total\":0,\"unchanged\":0},\"url\":\"https://app.visualci.test//pdfs/builds/2\",\"warnings\":[]},{\"blocked\":null,\"branch\":\"my-branch\",\"ci_mode\":\"review\",\"commit\":\"abc123\",\"conclusion\":\"changes\",\"created_at\":\"\",\"environment\":\"local\",\"environment_info\":{},\"error\":null,\"id\":\"\",\"mode\":\"local\",\"name\":\"default\",\"number\":1,\"passed\":true,\"pr_number\":null,\"project\":\"/pdfs\",\"review_state\":\"pending\",\"reviewable\":true,\"reviews\":[],\"state\":\"completed\",\"stats\":{\"added\":0,\"changed\":0,\"config\":0,\"failed\":0,\"ignored\":0,\"pending\":0,\"removed\":0,\"total\":0,\"unchanged\":0},\"url\":\"https://app.visualci.test//pdfs/builds/1\",\"warnings\":[]}]}", - "type": "text" - } - ], - "isError": false, - "structuredContent": { - "builds": [ - { - "blocked": null, - "branch": "main", - "ci_mode": "review", - "commit": "abc123", - "conclusion": "changes", - "created_at": "", - "environment": "ci", - "environment_info": {}, - "error": null, - "id": "", - "mode": "ci", - "name": "default", - "number": 2, - "passed": true, - "pr_number": null, - "project": "/pdfs", - "review_state": "pending", - "reviewable": true, - "reviews": [], - "state": "completed", - "stats": { - "added": 0, - "changed": 0, - "config": 0, - "failed": 0, - "ignored": 0, - "pending": 0, - "removed": 0, - "total": 0, - "unchanged": 0 - }, - "url": "https://app.visualci.test//pdfs/builds/2", - "warnings": [] - }, - { - "blocked": null, - "branch": "my-branch", - "ci_mode": "review", - "commit": "abc123", - "conclusion": "changes", - "created_at": "", - "environment": "local", - "environment_info": {}, - "error": null, - "id": "", - "mode": "local", - "name": "default", - "number": 1, - "passed": true, - "pr_number": null, - "project": "/pdfs", - "review_state": "pending", - "reviewable": true, - "reviews": [], - "state": "completed", - "stats": { - "added": 0, - "changed": 0, - "config": 0, - "failed": 0, - "ignored": 0, - "pending": 0, - "removed": 0, - "total": 0, - "unchanged": 0 - }, - "url": "https://app.visualci.test//pdfs/builds/1", - "warnings": [] - } - ] - } - } -} diff --git a/app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/whoami-2.json b/app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/whoami-2.json deleted file mode 100644 index c845acce..00000000 --- a/app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/whoami-2.json +++ /dev/null @@ -1,66 +0,0 @@ -{ - "arguments": {}, - "result": { - "content": [ - { - "text": "{\"email\":\"@example.com\",\"identities\":[],\"kind\":\"user\",\"name\":\"bob\",\"organizations\":[{\"blocked\":null,\"name\":\"Org\",\"projects\":[\"/pdfs\",\"/shots\"],\"role\":\"member\",\"setup\":{\"complete\":false,\"dismissed\":false,\"next\":\"install_github_app\",\"steps\":[{\"done\":true,\"key\":\"connect_agent\"},{\"done\":true,\"key\":\"create_project\"},{\"done\":false,\"key\":\"install_github_app\"},{\"done\":true,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\"}],\"waiting_for_review\":[{\"branch\":\"main\",\"build\":2,\"commit\":\"abc123\",\"project\":\"/pdfs\",\"url\":\"https://app.visualci.test//pdfs/builds/2\"}]}", - "type": "text" - } - ], - "isError": false, - "structuredContent": { - "email": "@example.com", - "identities": [], - "kind": "user", - "name": "bob", - "organizations": [ - { - "blocked": null, - "name": "Org", - "projects": [ - "/pdfs", - "/shots" - ], - "role": "member", - "setup": { - "complete": false, - "dismissed": false, - "next": "install_github_app", - "steps": [ - { - "done": true, - "key": "connect_agent" - }, - { - "done": true, - "key": "create_project" - }, - { - "done": false, - "key": "install_github_app" - }, - { - "done": true, - "key": "add_to_ci" - }, - { - "done": false, - "key": "review_changes" - } - ] - }, - "slug": "" - } - ], - "waiting_for_review": [ - { - "branch": "main", - "build": 2, - "commit": "abc123", - "project": "/pdfs", - "url": "https://app.visualci.test//pdfs/builds/2" - } - ] - } - } -} diff --git a/app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/whoami-3.json b/app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/whoami-3.json deleted file mode 100644 index 4efb846c..00000000 --- a/app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/whoami-3.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "arguments": {}, - "result": { - "content": [ - { - "text": "{\"blocked\":null,\"kind\":\"project\",\"open_comment_threads\":[],\"project\":\"/pdfs\",\"waiting_for_review\":[{\"branch\":\"main\",\"build\":2,\"commit\":\"abc123\",\"project\":\"/pdfs\",\"url\":\"https://app.visualci.test//pdfs/builds/2\"}]}", - "type": "text" - } - ], - "isError": false, - "structuredContent": { - "blocked": null, - "kind": "project", - "open_comment_threads": [], - "project": "/pdfs", - "waiting_for_review": [ - { - "branch": "main", - "build": 2, - "commit": "abc123", - "project": "/pdfs", - "url": "https://app.visualci.test//pdfs/builds/2" - } - ] - } - } -} diff --git a/app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/whoami-4.json b/app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/whoami-4.json deleted file mode 100644 index 47c1d81d..00000000 --- a/app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/whoami-4.json +++ /dev/null @@ -1,66 +0,0 @@ -{ - "arguments": {}, - "result": { - "content": [ - { - "text": "{\"email\":\"@example.com\",\"identities\":[],\"kind\":\"user\",\"name\":\"owner\",\"organizations\":[{\"blocked\":null,\"name\":\"Org\",\"projects\":[\"/pdfs\",\"/shots\"],\"role\":\"admin\",\"setup\":{\"complete\":false,\"dismissed\":false,\"next\":\"install_github_app\",\"steps\":[{\"done\":true,\"key\":\"connect_agent\"},{\"done\":true,\"key\":\"create_project\"},{\"done\":false,\"key\":\"install_github_app\"},{\"done\":true,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\"}],\"waiting_for_review\":[{\"branch\":\"main\",\"build\":2,\"commit\":\"abc123\",\"project\":\"/pdfs\",\"url\":\"https://app.visualci.test//pdfs/builds/2\"}]}", - "type": "text" - } - ], - "isError": false, - "structuredContent": { - "email": "@example.com", - "identities": [], - "kind": "user", - "name": "owner", - "organizations": [ - { - "blocked": null, - "name": "Org", - "projects": [ - "/pdfs", - "/shots" - ], - "role": "admin", - "setup": { - "complete": false, - "dismissed": false, - "next": "install_github_app", - "steps": [ - { - "done": true, - "key": "connect_agent" - }, - { - "done": true, - "key": "create_project" - }, - { - "done": false, - "key": "install_github_app" - }, - { - "done": true, - "key": "add_to_ci" - }, - { - "done": false, - "key": "review_changes" - } - ] - }, - "slug": "" - } - ], - "waiting_for_review": [ - { - "branch": "main", - "build": 2, - "commit": "abc123", - "project": "/pdfs", - "url": "https://app.visualci.test//pdfs/builds/2" - } - ] - } - } -} diff --git a/app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/whoami.json b/app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/whoami.json deleted file mode 100644 index 85af152c..00000000 --- a/app/tests/golden/mcp/a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle/whoami.json +++ /dev/null @@ -1,73 +0,0 @@ -{ - "arguments": {}, - "result": { - "content": [ - { - "text": "{\"email\":\"@example.com\",\"identities\":[],\"kind\":\"user\",\"name\":\"owner\",\"organizations\":[{\"blocked\":null,\"name\":\"Org\",\"projects\":[\"/pdfs\",\"/shots\"],\"role\":\"admin\",\"setup\":{\"complete\":false,\"dismissed\":false,\"next\":\"install_github_app\",\"steps\":[{\"done\":true,\"key\":\"connect_agent\"},{\"done\":true,\"key\":\"create_project\"},{\"done\":false,\"key\":\"install_github_app\"},{\"done\":true,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\"}],\"waiting_for_review\":[{\"branch\":\"main\",\"build\":2,\"commit\":\"abc123\",\"project\":\"/pdfs\",\"url\":\"https://app.visualci.test//pdfs/builds/2\"},{\"branch\":\"my-branch\",\"build\":1,\"commit\":\"abc123\",\"project\":\"/pdfs\",\"url\":\"https://app.visualci.test//pdfs/builds/1\"}]}", - "type": "text" - } - ], - "isError": false, - "structuredContent": { - "email": "@example.com", - "identities": [], - "kind": "user", - "name": "owner", - "organizations": [ - { - "blocked": null, - "name": "Org", - "projects": [ - "/pdfs", - "/shots" - ], - "role": "admin", - "setup": { - "complete": false, - "dismissed": false, - "next": "install_github_app", - "steps": [ - { - "done": true, - "key": "connect_agent" - }, - { - "done": true, - "key": "create_project" - }, - { - "done": false, - "key": "install_github_app" - }, - { - "done": true, - "key": "add_to_ci" - }, - { - "done": false, - "key": "review_changes" - } - ] - }, - "slug": "" - } - ], - "waiting_for_review": [ - { - "branch": "main", - "build": 2, - "commit": "abc123", - "project": "/pdfs", - "url": "https://app.visualci.test//pdfs/builds/2" - }, - { - "branch": "my-branch", - "build": 1, - "commit": "abc123", - "project": "/pdfs", - "url": "https://app.visualci.test//pdfs/builds/1" - } - ] - } - } -} diff --git a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/get_organization.json b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/get_organization.json index da75757a..de9fca3d 100644 --- a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/get_organization.json +++ b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/get_organization.json @@ -5,7 +5,7 @@ "result": { "content": [ { - "text": "{\"billing_url\":\"https://app.visualci.test//billing\",\"invitations\":[],\"members\":[{\"avatar_url\":null,\"email\":\"@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"owner\",\"role\":\"admin\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null}],\"name\":\"Org\",\"projects\":[{\"last_build\":null,\"name\":\"PDFs\",\"project\":\"/pdfs\"},{\"last_build\":null,\"name\":\"Screenshots\",\"project\":\"/shots\"}],\"role\":\"admin\",\"setup\":{\"complete\":false,\"dismissed\":false,\"github\":[],\"install_url\":\"https://github.com/apps/visualci-com/installations/new\",\"installations\":[],\"next\":\"install_github_app\",\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":true,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[]}", + "text": "{\"billing_url\":\"https://app.visualci.test//billing\",\"invitations\":[],\"members\":[{\"avatar_url\":null,\"email\":\"@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"owner\",\"role\":\"admin\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null}],\"name\":\"Org\",\"projects\":[{\"last_build\":null,\"name\":\"PDFs\",\"project\":\"/pdfs\"},{\"last_build\":null,\"name\":\"Screenshots\",\"project\":\"/shots\"}],\"role\":\"admin\",\"setup\":{\"complete\":false,\"dismissed\":false,\"github\":[],\"install_url\":\"/github/install\",\"installations\":[],\"next\":\"install_github_app\",\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":true,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[]}", "type": "text" } ], @@ -45,7 +45,7 @@ "complete": false, "dismissed": false, "github": [], - "install_url": "https://github.com/apps/visualci-com/installations/new", + "install_url": "/github/install", "installations": [], "next": "install_github_app", "steps": [ diff --git a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/whoami.json b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/whoami.json index 18024fcd..4350f2fe 100644 --- a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/whoami.json +++ b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/whoami.json @@ -3,7 +3,7 @@ "result": { "content": [ { - "text": "{\"email\":\"@example.com\",\"identities\":[],\"kind\":\"user\",\"name\":\"owner\",\"organizations\":[{\"blocked\":null,\"name\":\"Org\",\"projects\":[\"/pdfs\",\"/shots\"],\"role\":\"admin\",\"setup\":{\"complete\":false,\"dismissed\":false,\"github\":[],\"install_url\":\"https://github.com/apps/visualci-com/installations/new\",\"installations\":[],\"next\":\"install_github_app\",\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":true,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\"}],\"via\":{\"source\":\"personal_token\",\"token_name\":\"agent\"},\"waiting_for_review\":[]}", + "text": "{\"email\":\"@example.com\",\"identities\":[],\"kind\":\"user\",\"name\":\"owner\",\"organizations\":[{\"blocked\":null,\"name\":\"Org\",\"projects\":[\"/pdfs\",\"/shots\"],\"role\":\"admin\",\"setup\":{\"complete\":false,\"dismissed\":false,\"github\":[],\"install_url\":\"/github/install\",\"installations\":[],\"next\":\"install_github_app\",\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":true,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\"}],\"via\":{\"source\":\"personal_token\",\"token_name\":\"agent\"},\"waiting_for_review\":[]}", "type": "text" } ], @@ -26,7 +26,7 @@ "complete": false, "dismissed": false, "github": [], - "install_url": "https://github.com/apps/visualci-com/installations/new", + "install_url": "/github/install", "installations": [], "next": "install_github_app", "steps": [ diff --git a/app/tests/golden/mcp/a_project_token_acts_as_a_member_not_an_admin/get_organization.json b/app/tests/golden/mcp/a_project_token_acts_as_a_member_not_an_admin/get_organization.json index dfa48a59..4a450a40 100644 --- a/app/tests/golden/mcp/a_project_token_acts_as_a_member_not_an_admin/get_organization.json +++ b/app/tests/golden/mcp/a_project_token_acts_as_a_member_not_an_admin/get_organization.json @@ -5,7 +5,7 @@ "result": { "content": [ { - "text": "{\"billing_url\":\"https://app.visualci.test//billing\",\"invitations\":[],\"members\":[],\"name\":\"Org\",\"projects\":[{\"last_build\":null,\"name\":\"PDFs\",\"project\":\"/pdfs\"}],\"role\":\"project\",\"setup\":{\"complete\":false,\"dismissed\":false,\"github\":[],\"install_url\":\"https://github.com/apps/visualci-com/installations/new\",\"installations\":[],\"next\":\"install_github_app\",\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[]}", + "text": "{\"billing_url\":\"https://app.visualci.test//billing\",\"invitations\":[],\"members\":[],\"name\":\"Org\",\"projects\":[{\"last_build\":null,\"name\":\"PDFs\",\"project\":\"/pdfs\"}],\"role\":\"project\",\"setup\":{\"complete\":false,\"dismissed\":false,\"github\":[],\"install_url\":\"/github/install\",\"installations\":[],\"next\":\"install_github_app\",\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[]}", "type": "text" } ], @@ -27,7 +27,7 @@ "complete": false, "dismissed": false, "github": [], - "install_url": "https://github.com/apps/visualci-com/installations/new", + "install_url": "/github/install", "installations": [], "next": "install_github_app", "steps": [ diff --git a/app/tests/golden/mcp/a_project_token_reaches_only_its_project/create_organization.json b/app/tests/golden/mcp/a_project_token_reaches_only_its_project/create_organization.json deleted file mode 100644 index 85d14c97..00000000 --- a/app/tests/golden/mcp/a_project_token_reaches_only_its_project/create_organization.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "arguments": { - "name": "X", - "slug": "x-y" - }, - "result": { - "content": [ - { - "text": "creating an organization needs a personal access token", - "type": "text" - } - ], - "isError": true - } -} diff --git a/app/tests/golden/mcp/a_project_token_reaches_only_its_project/get_project.json b/app/tests/golden/mcp/a_project_token_reaches_only_its_project/get_project.json deleted file mode 100644 index a1c6e05f..00000000 --- a/app/tests/golden/mcp/a_project_token_reaches_only_its_project/get_project.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "arguments": {}, - "result": { - "content": [ - { - "text": "{\"gallery\":{\"enabled\":true,\"items\":[],\"manifest_url\":null},\"project\":\"/shots\",\"repository_seen_in_ci\":null,\"settings\":{\"ci_mode\":\"review\",\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[],\"name\":\"Screenshots\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"shots\",\"threshold\":0.0,\"tokens_can_approve\":true},\"tokens\":[{\"created_at\":\"\",\"id\":2,\"last_used_at\":\"\",\"name\":\"ci\",\"prefix\":\"\"}],\"url\":\"https://app.visualci.test//shots\"}", - "type": "text" - } - ], - "isError": false, - "structuredContent": { - "gallery": { - "enabled": true, - "items": [], - "manifest_url": null - }, - "project": "/shots", - "repository_seen_in_ci": null, - "settings": { - "ci_mode": "review", - "default_branch": "main", - "dpi": 140, - "forge": null, - "forge_app_installed": false, - "forge_webhook_at": null, - "gallery_enabled": true, - "ignore_anti_aliasing": false, - "ignore_rules": [], - "name": "Screenshots", - "notice": null, - "open_source": false, - "open_source_note": null, - "open_source_pool": false, - "open_source_withdrawn": false, - "public": false, - "renderer": "pdfbox", - "repository_public": false, - "repository_url": null, - "slug": "shots", - "threshold": 0.0, - "tokens_can_approve": true - }, - "tokens": [ - { - "created_at": "", - "id": 2, - "last_used_at": "", - "name": "ci", - "prefix": "" - } - ], - "url": "https://app.visualci.test//shots" - } - } -} diff --git a/app/tests/golden/mcp/runs_a_build_from_uploaded_files/get_organization.json b/app/tests/golden/mcp/runs_a_build_from_uploaded_files/get_organization.json index e6f46db9..f863f9aa 100644 --- a/app/tests/golden/mcp/runs_a_build_from_uploaded_files/get_organization.json +++ b/app/tests/golden/mcp/runs_a_build_from_uploaded_files/get_organization.json @@ -5,7 +5,7 @@ "result": { "content": [ { - "text": "{\"billing_url\":\"https://app.visualci.test//billing\",\"invitations\":[],\"members\":[{\"avatar_url\":null,\"email\":\"@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"owner\",\"role\":\"admin\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null}],\"name\":\"Org\",\"projects\":[{\"last_build\":{\"blocked\":null,\"branch\":\"main\",\"ci_mode\":\"review\",\"commit\":\"abc\",\"conclusion\":\"changes\",\"created_at\":\"\",\"environment\":\"ci\",\"environment_info\":{},\"error\":null,\"id\":\"\",\"mode\":\"ci\",\"name\":\"default\",\"number\":1,\"passed\":true,\"pr_number\":null,\"project\":\"/pdfs\",\"review_state\":\"auto_approved\",\"reviewable\":true,\"reviews\":[],\"state\":\"completed\",\"stats\":{\"added\":1,\"changed\":0,\"config\":0,\"failed\":0,\"ignored\":0,\"pending\":0,\"removed\":0,\"total\":1,\"unchanged\":0},\"url\":\"https://app.visualci.test//pdfs/builds/1\",\"warnings\":[]},\"name\":\"PDFs\",\"project\":\"/pdfs\"},{\"last_build\":null,\"name\":\"Screenshots\",\"project\":\"/shots\"}],\"role\":\"admin\",\"setup\":{\"complete\":false,\"dismissed\":false,\"github\":[],\"install_url\":\"https://github.com/apps/visualci-com/installations/new\",\"installations\":[],\"next\":\"install_github_app\",\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":true,\"key\":\"add_to_ci\"},{\"done\":true,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":1,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[{\"created_at\":\"\",\"credits\":1,\"kind\":\"build\",\"reference\":\"build pdfs/1: 1 snapshot checked\"}]}", + "text": "{\"billing_url\":\"https://app.visualci.test//billing\",\"invitations\":[],\"members\":[{\"avatar_url\":null,\"email\":\"@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"owner\",\"role\":\"admin\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null}],\"name\":\"Org\",\"projects\":[{\"last_build\":{\"blocked\":null,\"branch\":\"main\",\"ci_mode\":\"review\",\"commit\":\"abc\",\"conclusion\":\"changes\",\"created_at\":\"\",\"environment\":\"ci\",\"environment_info\":{},\"error\":null,\"id\":\"\",\"mode\":\"ci\",\"name\":\"default\",\"number\":1,\"passed\":true,\"pr_number\":null,\"project\":\"/pdfs\",\"review_state\":\"auto_approved\",\"reviewable\":true,\"reviews\":[],\"state\":\"completed\",\"stats\":{\"added\":1,\"changed\":0,\"config\":0,\"failed\":0,\"ignored\":0,\"pending\":0,\"removed\":0,\"total\":1,\"unchanged\":0},\"url\":\"https://app.visualci.test//pdfs/builds/1\",\"warnings\":[]},\"name\":\"PDFs\",\"project\":\"/pdfs\"},{\"last_build\":null,\"name\":\"Screenshots\",\"project\":\"/shots\"}],\"role\":\"admin\",\"setup\":{\"complete\":false,\"dismissed\":false,\"github\":[],\"install_url\":\"/github/install\",\"installations\":[],\"next\":\"install_github_app\",\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":true,\"key\":\"add_to_ci\"},{\"done\":true,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":1,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[{\"created_at\":\"\",\"credits\":1,\"kind\":\"build\",\"reference\":\"build pdfs/1: 1 snapshot checked\"}]}", "type": "text" } ], @@ -79,7 +79,7 @@ "complete": false, "dismissed": false, "github": [], - "install_url": "https://github.com/apps/visualci-com/installations/new", + "install_url": "/github/install", "installations": [], "next": "install_github_app", "steps": [ diff --git a/app/tests/installations.rs b/app/tests/installations.rs index 114286bb..73360497 100644 --- a/app/tests/installations.rs +++ b/app/tests/installations.rs @@ -94,6 +94,7 @@ fn granted(owner: &str) -> client::HttpFake { ] }), ) .with(&format!("api.github.com/orgs/{owner}"), json!({ "login": owner, "name": "Acme Inc" })) + .with(&format!("api.github.com/orgs/{owner}/memberships/ada"), json!({ "state": "active", "role": "admin" })) .with("api.github.com/user/1001", json!({ "id": 1001, "login": "ada" })) .with(&format!("api.github.com/repos/{owner}/web/installation"), json!({ "id": 7 })) .with(&format!("api.github.com/repos/{owner}/docs/installation"), json!({ "id": 7 })) @@ -188,6 +189,39 @@ async fn a_taken_slug_becomes_login_github_with_a_note(_app: Application) -> lar Ok(()) } +#[laravel::test(app = github)] +async fn a_member_who_is_not_an_owner_cannot_claim_a_github_organization(_app: Application) -> laravel::Result<()> { + let (ada, _) = ada().await?; + remember(ada.id, &[installation("7", "5005", "acme", "Organization")]).await?; + let _github = client::fake() + .with("api.github.com/app/installations/7/access_tokens", json!({ "token": "t" })) + .with("api.github.com/user/1001", json!({ "id": 1001, "login": "ada" })) + .with("api.github.com/orgs/acme/memberships/ada", json!({ "state": "active", "role": "member" })); + let err = installations::set_up(&github_app(), &ada, "7").await.expect_err("only a member"); + assert_eq!(err.status().as_u16(), 403); + assert!(err.to_string().contains("only an owner of acme"), "{err}"); + assert!(Organization::query().filter(Organization::slug.eq("acme")).first().await?.is_none(), "nothing made"); + let mapped: Option> = + db::query!("SELECT organization_id FROM github_installations WHERE installation_id = '7'").scalar().await?; + assert_eq!(mapped, Some(None), "nothing mapped"); + + // Whoever installed it may, owner or not + db::query!("UPDATE github_installations SET installed_by = '1001' WHERE installation_id = '7'").update().await?; + let _github = granted("acme"); + assert_eq!(installations::set_up(&github_app(), &ada, "7").await?.organization, "acme"); + Ok(()) +} + +#[laravel::test(app = github)] +async fn nobody_claims_another_persons_account(_app: Application) -> laravel::Result<()> { + let (ada, _) = ada().await?; + remember(ada.id, &[installation("7", "9009", "torvalds", "User")]).await?; + let err = installations::set_up(&github_app(), &ada, "7").await.expect_err("his account"); + assert_eq!(err.status().as_u16(), 403); + assert!(Organization::query().filter(Organization::slug.eq("torvalds")).first().await?.is_none()); + Ok(()) +} + #[laravel::test(app = github)] async fn someone_else_cannot_set_up_an_installation_they_cannot_reach(_app: Application) -> laravel::Result<()> { let (ada, _) = ada().await?; @@ -200,10 +234,12 @@ async fn someone_else_cannot_set_up_an_installation_they_cannot_reach(_app: Appl #[laravel::test(app = github)] async fn the_setup_url_signs_in_refreshes_once_and_lands_on_the_organization(app: Application) -> laravel::Result<()> { - // Signed out: off to sign in, and back here after - let r = app.get("/github/setup?installation_id=7&setup_action=install").await; - r.assert_status(302) - .assert_header("location", "/auth/github?return_to=%2Fgithub%2Fsetup%3Finstallation_id%3D7%26refreshed%3D1"); + // Signed out: off to sign in, and back here after, with GitHub's state + let r = app.get("/github/setup?installation_id=7&setup_action=install&state=abc123").await; + r.assert_status(302).assert_header( + "location", + "/auth/github?return_to=%2Fgithub%2Fsetup%3Finstallation_id%3D7%26state%3Dabc123%26refreshed%3D1", + ); let (ada, org) = ada().await?; // Signed in, but her list doesn't have it: one more sign-in refreshes it let r = app.get("/github/setup?installation_id=7").acting_as(&ada).await; @@ -213,7 +249,22 @@ async fn the_setup_url_signs_in_refreshes_once_and_lands_on_the_organization(app remember(ada.id, &[installation("7", "1001", "ada", "User")]).await?; let _github = granted("ada"); - let r = app.get("/github/setup?installation_id=7").acting_as(&ada).await; + // Without the state this browser's install sent (a link from another site): nothing set up, the offer instead + let r = app.get("/github/setup?installation_id=7&state=forged").acting_as(&ada).await; + r.assert_status(302).assert_header("location", &format!("/{}?setup=install_github_app", org.slug)); + assert!(projects(org.id).await?.is_empty()); + + // The install this browser started: set up, landing on the next step + let install = app.get("/github/install").acting_as(&ada).await; + install.assert_status(302); + let to = install.header("location").expect("to GitHub").to_string(); + assert!(to.starts_with("https://github.com/apps/visualci-com/installations/new?state="), "{to}"); + let state = to.rsplit('=').next().unwrap().to_string(); + let r = app + .get(format!("/github/setup?installation_id=7&state={state}")) + .acting_as(&ada) + .with_cookies_from(&install) + .await; r.assert_status(302).assert_header("location", &format!("/{}?setup=add_to_ci&installation=7", org.slug)); // No installation ID: an owner still has to approve it app.get("/github/setup?setup_action=request").acting_as(&ada).await.assert_ok().assert_see("Waiting for GitHub"); diff --git a/docs/design.md b/docs/design.md index 8615325d..6bd5a242 100644 --- a/docs/design.md +++ b/docs/design.md @@ -347,10 +347,16 @@ looked up by the person's permanent forge user ID, never a stored login, which c App makes the projects. `github_installations` records every installation VisualCI hears of (from a sign-in, which lists the ones the person can reach into `user_installations`, and from the `installation` webhook: created, suspended, removed, with removed rows kept so a reinstall finds its organization again). The App's Setup URL, -`GET /github/setup?installation_id=…` on the app host, maps the installation to an organization: the person's own -account to their personal organization; a GitHub organization to the one it was set up for before, else a new one -whose slug is the lowercased login (`-github` when taken), with the installer as admin and everyone else joining -through the hourly sync. Each granted repository the installer can Maintain becomes a project linked through the usual +`GET /github/setup?installation_id=…&state=…` on the app host, maps the installation to an organization: the person's +own account to their personal organization (`users.personal_organization_id`); a GitHub organization to the one it was +set up for before (only its admins add to it), else a new one whose slug is the lowercased login (`-github` when +taken), with the installer as admin and everyone else joining through the hourly sync. Reaching a repository through an +installation proves nothing about its account, so a new claim is checked live before anything is written: the +person's own account, or for a GitHub organization its owner (`GET /orgs/{org}/memberships/{user}`, which needs the +App's Members: read permission) or whoever installed the App there (the `installation` webhook's sender, +`installed_by`); another person's account is refused. The mapping is written only where none exists, so two people +setting it up at once can't both win. The GET sets up only the install this browser started (`/github/install` puts a +`state` in the session and sends it to GitHub); anything else lands on the checklist, where a click sets it up. Each granted repository the installer can Maintain becomes a project linked through the usual link checks; the rest are listed with the reason. Repositories added to a set-up installation later become projects in its organization. The checklist (`install_github_app`, `add_to_ci`, `connect_agent`, `review_changes`) offers installations the person can reach that aren't set up yet (`POST /api/ui/installations/{id}/setup`).