From b24c98a395378e7639ecf05349e26d6e3186a1c0 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 04:35:20 +1300 Subject: [PATCH 1/2] app/: the setup checklist (sc-8900, ported): auth::setup::state(org, user pid) ticks each step from what happened (an MCP connection or a used personal token, a project, the App installed, a CI build, an approval), the next step, complete and dismissed; POST /api/ui/orgs/{org}/setup closes it or opens it again (admins) --- app/src/auth/mod.rs | 2 + app/src/auth/setup.rs | 92 +++++++++++++++++++++++++++++++++++++++++++ app/tests/setup.rs | 47 ++++++++++++++++++++++ 3 files changed, 141 insertions(+) create mode 100644 app/src/auth/setup.rs create mode 100644 app/tests/setup.rs diff --git a/app/src/auth/mod.rs b/app/src/auth/mod.rs index 434f6a15..983f2196 100644 --- a/app/src/auth/mod.rs +++ b/app/src/auth/mod.rs @@ -11,6 +11,7 @@ pub mod invitations; pub mod memberships; pub mod oauth; +pub mod setup; pub mod sign_in; pub mod tokens; @@ -270,4 +271,5 @@ pub fn routes(route: &mut laravel::prelude::Router) { route.get("/auth/session", sign_in::session); route.get("/auth/providers", sign_in::providers); route.post("/auth/logout", sign_in::logout); + setup::routes(route); } diff --git a/app/src/auth/setup.rs b/app/src/auth/setup.rs new file mode 100644 index 00000000..4b705d16 --- /dev/null +++ b/app/src/auth/setup.rs @@ -0,0 +1,92 @@ +//! The "Set up VisualCI" checklist (sc-8900, ported from today's server): each step ticks itself from what has actually +//! happened, with no "mark done". An organization's admins can close it, or open it again. + +use laravel::auth::Authenticated; +use laravel::db; +use laravel::prelude::*; +use serde_json::{Value, json}; + +use super::Role; +use crate::models::User; + +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 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): each step and whether it's done, the next one, whether it's complete (a build +/// has been approved) and whether someone closed it. +/// +/// # Errors +/// On a database error. +pub async fn state(org_id: i64, user_pid: Option) -> laravel::Result { + let subject = user_pid.map(|p| p.to_string()).unwrap_or_default(); + let row = db::query!( + "SELECT \ + 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::text = {subject} 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) \ + 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, \ + EXISTS (SELECT 1 FROM reviews r JOIN builds b ON b.id = r.build_id JOIN projects p ON p.id = b.project_id \ + WHERE p.organization_id = {org_id} AND r.action = 'approve') AS review_changes, \ + (SELECT setup_dismissed_at IS NOT NULL FROM organizations WHERE id = {org_id}) AS dismissed" + ) + .select_one() + .await? + .ok_or_else(|| laravel::Error::msg("no setup row"))?; + let mut steps = Vec::new(); + for key in STEPS { + steps.push((*key, row.try_get::(*key)?)); + } + let next = steps.iter().find(|(_, done)| !done).map(|(key, _)| *key); + let complete = steps.last().is_some_and(|(_, done)| *done); + 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), + })) +} + +#[laravel::input] +#[validate(authenticated)] +pub struct SetupInput { + dismissed: bool, +} + +/// `POST /api/ui/orgs/{org}/setup` (admins): close the checklist, or open it again. +pub async fn update( + Authenticated(user): Authenticated, + Params(org): Params, + Valid(p): Valid, +) -> laravel::Result> { + let user_id = user.id; + let row = db::query!( + "SELECT o.id, m.role FROM organizations o \ + LEFT JOIN memberships m ON m.organization_id = o.id AND m.user_id = {user_id} WHERE o.slug = {org}" + ) + .select_one() + .await? + .ok_or_else(|| laravel::abort(404))?; + let org_id: i64 = row.try_get("id")?; + match row.try_get::>("role")?.as_deref().and_then(Role::parse) { + Some(Role::Admin) => {} + Some(_) => return Err(laravel::abort_with(403, "only admins can change the setup checklist")), + None => return Err(laravel::abort(404)), + } + let dismissed = p.dismissed; + db::query!( + "UPDATE organizations SET setup_dismissed_at = CASE WHEN {dismissed} THEN now() END, updated_at = now() \ + WHERE id = {org_id}" + ) + .update() + .await?; + Ok(Json(state(org_id, Some(user.pid)).await?)) +} diff --git a/app/tests/setup.rs b/app/tests/setup.rs new file mode 100644 index 00000000..bfde3347 --- /dev/null +++ b/app/tests/setup.rs @@ -0,0 +1,47 @@ +//! The setup checklist ticks itself from what happened, and an organization's admins can close it. + +use app::models::User; +use laravel::db; +use laravel::model::create; +use laravel::testing::prelude::*; + +#[laravel::test] +async fn the_checklist_follows_what_happened(app: Application) -> laravel::Result<()> { + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let ada_id = ada.id; + let org: i64 = db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) \ + VALUES (gen_random_uuid(), 'acme', 'Acme', now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org}, {ada_id}, 'admin', 'created', now(), now())" + ) + .insert() + .await?; + let state = app::auth::setup::state(org, Some(ada.pid)).await?; + assert_eq!(state["next"], "connect_agent"); + 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())" + ) + .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["complete"], false); + + let close = |dismissed: bool| { + app.post("/api/ui/orgs/acme/setup") + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .json(json!({ "dismissed": dismissed })) + }; + close(true).await.assert_ok().assert_json_path("dismissed", true); + close(false).await.assert_ok().assert_json_path("dismissed", false); + Ok(()) +} From c3ef1d11acb5ad930aa58a2c6ee53e44d84e6c44 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 05:11:54 +1300 Subject: [PATCH 2/2] Setup checklist, review fixes: an agent is connected only for a person (a project token's view never ticks it), matched on the pid as a uuid so the index is used; documented that callers authorize first --- app/src/auth/setup.rs | 13 ++++++++----- app/tests/setup.rs | 9 +++++++++ 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/app/src/auth/setup.rs b/app/src/auth/setup.rs index 4b705d16..f9a9bac3 100644 --- a/app/src/auth/setup.rs +++ b/app/src/auth/setup.rs @@ -17,18 +17,21 @@ pub fn routes(route: &mut Router) { pub const STEPS: &[&str] = &["connect_agent", "create_project", "install_github_app", "add_to_ci", "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): each step and whether it's done, the next one, whether it's complete (a build -/// has been approved) and whether someone closed it. +/// personal token that has been used; with no person, such as a project token, it isn't done): each step and whether +/// it's done, the next one, whether it's complete (a build has been approved) and whether someone closed it. Callers +/// check first that the person may see the organization: this reads it as asked. /// /// # Errors /// On a database error. pub async fn state(org_id: i64, user_pid: Option) -> laravel::Result { - let subject = user_pid.map(|p| p.to_string()).unwrap_or_default(); + // An OAuth token's subject is the person's pid as text; the users table is matched on the uuid, by its index + let subject = user_pid.map(|p| p.to_string()); let row = db::query!( "SELECT \ - EXISTS (SELECT 1 FROM oauth_tokens t WHERE t.subject = {subject}) \ + {subject}::text IS NOT NULL AND ( \ + 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::text = {subject} AND ut.last_used_at IS NOT NULL) AS connect_agent, \ + 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) \ AS install_github_app, \ diff --git a/app/tests/setup.rs b/app/tests/setup.rs index bfde3347..16814712 100644 --- a/app/tests/setup.rs +++ b/app/tests/setup.rs @@ -24,6 +24,15 @@ async fn the_checklist_follows_what_happened(app: Application) -> laravel::Resul .await?; let state = app::auth::setup::state(org, Some(ada.pid)).await?; assert_eq!(state["next"], "connect_agent"); + // 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) \ + VALUES ({ada_id}, 'laptop', 'h', 'vcu_abcdef', now(), now(), now())" + ) + .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); 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())"