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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions app/database/migrations/2026_12_03_100000_github_installations.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
//! 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. `users.personal_organization_id`
//! is the organization signing up made.

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,
-- 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,
-- 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);

-- 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;
"#;
144 changes: 144 additions & 0 deletions app/src/auth/installations.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
//! Setting up the GitHub App from the app (sc-9027, onboarding).
//!
//! - `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::{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<String>,
/// What `/github/install` sent GitHub, back from it.
state: Option<String>,
/// Set on the way back from the sign-in that refreshed their installations, so it happens once.
refreshed: Option<String>,
}

/// 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)
}

/// `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}{state}%26refreshed%3D1"
))
}

/// `GET /github/setup`: GitHub's redirect after someone installs the App.
pub async fn setup_page(
auth: Auth<User>,
app: laravel::config::Section<GithubApp>,
session: Session,
Query(q): Query<SetupQuery>,
) -> laravel::Result<laravel::http::Response> {
// 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, 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, q.state.as_deref())));
}
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.",
));
}
// Only the install this browser started sets anything up from a GET; anything else asks for a click first
let expected: Option<String> = session.pull(STATE);
if expected.is_none() || expected != q.state {
let user_id = user.id;
let personal: Option<String> = 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())),
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<User>,
app: laravel::config::Section<GithubApp>,
Params(id): Params<String>,
) -> laravel::Result<Json<serde_json::Value>> {
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('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;");
let html = format!(
"<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" \
content=\"width=device-width, initial-scale=1\"><title>{t} · VisualCI</title><style>body{{font:16px/1.5 \
system-ui,sans-serif;margin:0;min-height:100vh;display:grid;place-items:center;padding:16px;color:#1a1a1a;\
background:#fff}}@media (prefers-color-scheme:dark){{body{{color:#eee;background:#111}}a{{color:#9cf}}}}\
main{{max-width:34rem}}h1{{font-size:1.25rem;margin:0 0 8px}}p{{margin:0 0 12px}}</style></head><body><main>\
<h1>{t}</h1><p>{m}</p><p><a href=\"/\">Go to VisualCI</a></p></main></body></html>",
t = esc(title),
m = esc(message)
);
laravel::http::Response::new(laravel::view::Html::raw(html))
}
2 changes: 2 additions & 0 deletions app/src/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
//! Nobody found: `401`.

pub mod device;
pub mod installations;
pub mod invitations;
pub mod me;
pub mod memberships;
Expand Down Expand Up @@ -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);
}
39 changes: 35 additions & 4 deletions app/src/auth/setup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -32,8 +32,8 @@ pub async fn state(org_id: i64, user_pid: Option<laravel::str::Uuid>) -> 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, \
Expand All @@ -50,11 +50,42 @@ pub async fn state(org_id: i64, user_pid: Option<laravel::str::Uuid>) -> 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<i64> = 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<String> = r.try_get("result")?;
Ok(json!({
"installation_id": r.try_get::<String>("installation_id")?,
"account_login": r.try_get::<String>("account_login")?,
"result": result.and_then(|t| serde_json::from_str::<Value>(&t).ok()),
}))
})
.collect::<laravel::Result<Vec<_>>>()?;
Ok(json!({
"steps": steps.iter().map(|(key, done)| json!({ "key": key, "done": done })).collect::<Vec<_>>(),
"next": next,
"complete": complete,
"dismissed": row.try_get::<Option<bool>>("dismissed")?.unwrap_or(false),
"install_url": "/github/install",
"installations": offers,
"github": set_up,
}))
}

Expand Down
4 changes: 4 additions & 0 deletions app/src/auth/sign_in.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
32 changes: 25 additions & 7 deletions app/src/forge/github.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand All @@ -19,6 +19,7 @@ pub async fn sign_in(profile: &laravel::auth::social::User) -> laravel::Result<S
// The GitHub username: the profile's nickname, or the `/user` payload's `login`
let login =
profile.nickname.clone().or_else(|| profile.raw["login"].as_str().map(str::to_string)).unwrap_or_default();
let (installations, repositories) = installations(token).await?;
Ok(SignIn {
identity: Identity {
forge: ForgeKind::Github,
Expand All @@ -29,7 +30,8 @@ pub async fn sign_in(profile: &laravel::auth::social::User) -> laravel::Result<S
verified_emails: verified_emails(token).await?,
site: String::new(),
},
repositories: repositories(token).await?,
repositories,
installations,
})
}

Expand All @@ -52,11 +54,16 @@ async fn verified_emails(token: &str) -> laravel::Result<Vec<String>> {
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<Vec<(Repository, Permission)>> {
/// 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<Installation>, 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)) =
Expand All @@ -67,7 +74,18 @@ async fn repositories(token: &str) -> laravel::Result<Vec<(Repository, Permissio
out.push((repository.with_id(repo["id"].as_i64().map(|i| i.to_string())), permission));
}
}
Ok(out)
Ok((found, out))
}

/// An installation from GitHub's `account` object (on `/user/installations` and the `installation` webhook).
#[must_use]
pub fn installation_account(id: String, account: &Value) -> Option<Installation> {
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.
Expand Down
Loading
Loading