diff --git a/app/src/console/staff.rs b/app/src/console/staff.rs index cf069626..bcd43ac7 100644 --- a/app/src/console/staff.rs +++ b/app/src/console/staff.rs @@ -1,7 +1,8 @@ //! Staff commands, run in a web pod (`visualci-app `), ported from the Loco server's tasks with the same //! arguments and behaviour: make someone staff, add someone to an organization, put an organization on a plan, delete -//! an empty organization, and set up the Stripe catalog. Each refuses clearly (an error naming what's wrong) where the -//! old task did, and running one again with the same arguments changes nothing more. +//! an empty organization, and set up the Stripe catalog; and link a GitHub App installation to an organization. Each +//! refuses clearly (an error naming what's wrong) where the old task did, and running one again with the same +//! arguments changes nothing more. use laravel::console::{Console, clap, command}; use laravel::db; @@ -255,3 +256,111 @@ impl StripeSetup { Ok(()) } } + +/// `github:link-installation --installation --org --account-id --account-login +/// --account-type [--set-up-by ] --reason ""`: record that an +/// installation of the GitHub App is set up for an organization, as setting it up in the app would, for an +/// organization made by hand (production's docspring at cutover). The account is GitHub's (`gh api orgs/` or +/// `users/` gives its `id`). It refuses an installation already set up for another organization, and writes an +/// `admin_audit` row (client `console`). Running it again changes nothing more. +#[derive(clap::Parser)] +#[command(name = "github:link-installation")] +pub struct GithubLinkInstallation { + /// GitHub's ID for the installation. + #[arg(long)] + installation: String, + /// The organization's slug. + #[arg(long)] + org: String, + /// GitHub's ID for the account the App is installed on. + #[arg(long)] + account_id: String, + /// The account's login. + #[arg(long)] + account_login: String, + /// `Organization` or `User`. + #[arg(long)] + account_type: String, + /// Who set it up: a user's email or GitHub login. + #[arg(long)] + set_up_by: Option, + /// Why, for the audit log. + #[arg(long)] + reason: String, +} + +#[command] +impl GithubLinkInstallation { + async fn handle(self, console: &mut Console) -> laravel::Result<()> { + if !["Organization", "User"].contains(&self.account_type.as_str()) { + return Err(refuse("account-type must be Organization or User")); + } + let all_digits = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_digit()); + if !all_digits(&self.installation) || !all_digits(&self.account_id) { + return Err(refuse("installation and account-id are GitHub's numeric IDs")); + } + if self.reason.trim().is_empty() { + return Err(refuse("give a reason")); + } + let org = organization(&self.org).await?; + let set_up_by: Option = match &self.set_up_by { + Some(who) => { + let who = who.to_lowercase(); + let found: Option> = db::query!( + "SELECT COALESCE((SELECT user_id FROM identities WHERE forge = 'github' AND site = '' \ + AND lower(login) = {who} ORDER BY id LIMIT 1), \ + (SELECT id FROM users WHERE lower(email) = {who} LIMIT 1))" + ) + .scalar() + .await?; + Some(found.flatten().ok_or_else(|| refuse(format!("no user with the email or GitHub login {who}")))?) + } + None => None, + }; + let (id, account_id, login, kind, org_id) = ( + self.installation.clone(), + self.account_id.clone(), + self.account_login.clone(), + self.account_type.clone(), + org.id, + ); + let elsewhere: Option = db::query!( + "SELECT o.slug FROM github_installations g JOIN organizations o ON o.id = g.organization_id \ + WHERE g.installation_id = {id} AND g.organization_id <> {org_id}" + ) + .scalar() + .await?; + if let Some(slug) = elsewhere { + return Err(refuse(format!("installation {id} is set up for {slug}: not moving it"))); + } + let arguments = serde_json::json!({ + "installation": id, "org": org.slug, "account_id": account_id, "account_login": login, + "account_type": kind, "set_up_by": self.set_up_by, + }) + .to_string(); + let reason = self.reason.clone(); + db::transaction(async |_| { + db::query!( + "INSERT INTO github_installations (installation_id, account_id, account_login, account_type, \ + organization_id, set_up_by) \ + VALUES ({id}, {account_id}, {login}, {kind}, {org_id}, {set_up_by}) \ + ON CONFLICT (installation_id) DO UPDATE SET organization_id = EXCLUDED.organization_id, \ + set_up_by = COALESCE(github_installations.set_up_by, EXCLUDED.set_up_by), \ + account_id = EXCLUDED.account_id, account_login = EXCLUDED.account_login, \ + account_type = EXCLUDED.account_type, deleted_at = NULL, updated_at = now()" + ) + .insert() + .await?; + db::query!( + "INSERT INTO admin_audit (user_id, client, agent, tool, arguments, reason, ok) \ + VALUES (NULL, 'console', NULL, 'github:link-installation', {arguments}::jsonb, {reason}, true)" + ) + .insert() + .await?; + Ok(()) + }) + .await?; + console.line(format!("installation {} ({}) is set up for {}", self.installation, self.account_login, org.slug)); + Ok(()) + } +} diff --git a/app/src/lib.rs b/app/src/lib.rs index db52982e..bec39fa3 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -115,6 +115,7 @@ pub fn configure() -> ApplicationBuilder { commands.add::(); commands.add::(); commands.add::(); + commands.add::(); commands.add::(); commands.add::(); commands.add::(); diff --git a/app/tests/staff_commands.rs b/app/tests/staff_commands.rs index 54d53894..a925f455 100644 --- a/app/tests/staff_commands.rs +++ b/app/tests/staff_commands.rs @@ -215,3 +215,54 @@ async fn stripe_setup_needs_stripe(app: Application) -> laravel::Result<()> { app.command("stripe:setup").await.assert_failed().assert_error_output_contains("Stripe isn't configured"); Ok(()) } + +/// github:link-installation records an installation as set up for an organization (the checklist then counts the +/// App as installed there), refuses one set up elsewhere, and audits each run. +#[laravel::test] +async fn github_link_installation_links_audits_and_refuses_a_move(app: Application) -> laravel::Result<()> { + let ada = person("Ada", "ada@example.com").await?; + let acme = org("acme").await?; + let other = org("other").await?; + let link = "github:link-installation --installation 187 --org acme --account-id 320 --account-login Acme \ + --account-type Organization --set-up-by ada@example.com --reason cutover"; + for _ in 0..2 { + app.command(link) + .await + .assert_successful() + .assert_output_contains("installation 187 (Acme) is set up for acme"); + } + let (org_id, set_up_by, login): (Option, Option, String) = { + let row = db::query!( + "SELECT organization_id, set_up_by, account_login FROM github_installations WHERE installation_id = '187'" + ) + .select_one() + .await? + .unwrap(); + (row.try_get("organization_id")?, row.try_get("set_up_by")?, row.try_get("account_login")?) + }; + assert_eq!((org_id, set_up_by, login.as_str()), (Some(acme.id), Some(ada.id), "Acme")); + let audits: Option = db::query!( + "SELECT COUNT(*) FROM admin_audit WHERE tool = 'github:link-installation' AND reason = 'cutover' \ + AND arguments->>'org' = 'acme' AND client = 'console' AND ok" + ) + .scalar() + .await?; + assert_eq!(audits, Some(2)); + let steps = app::auth::setup::state(acme.id, None).await?; + assert_eq!(steps["steps"][0], json!({ "key": "install_github_app", "done": true })); + + app.command(&link.replace("--org acme", "--org other")) + .await + .assert_failed() + .assert_error_output_contains("installation 187 is set up for acme"); + let other_id = other.id; + let moved: Option = + db::query!("SELECT COUNT(*) FROM github_installations WHERE organization_id = {other_id}").scalar().await?; + assert_eq!(moved, Some(0)); + app.command(&link.replace("Organization", "Team")).await.assert_failed(); + app.command(&link.replace("ada@example.com", "nobody")) + .await + .assert_failed() + .assert_error_output_contains("no user"); + Ok(()) +} diff --git a/docs/deploy.md b/docs/deploy.md index cd1a31c9..cd691649 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -148,6 +148,11 @@ Run in a web pod (`visualci-app `): forge's sync never changes. Someone new to the organization gets the joined email. - `org:set-plan --org --plan `: put an organization on a plan by hand. Team set here is comped (nobody is billed); Staff is unlimited and only for DocSpring's own organizations. + - `github:link-installation --installation --org --account-id --account-login + --account-type [--set-up-by ] --reason ""`: record a GitHub App + installation as set up for an organization, as setting it up in the app does, for an organization made by hand + (`gh api orgs/` gives the account's `id`). It refuses one set up for another organization, and writes an + `admin_audit` row. - `org:delete --org `: delete an empty organization (a test or a mistake) and its Stripe customer. It refuses one with projects, a subscription, or any Stripe subscription or invoice. - `stripe:setup`: create or update the Stripe products, prices and customer portal configuration (the app also does