From d0e333d9bb6aa875e89abb04604ea248ca99004f Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 00:51:39 +1300 Subject: [PATCH] Close sign-ups quietly: someone who signs in without an account goes on a waitlist table (forge account, login, name, email, how they arrived) and sees one line, 'VisualCI opens in about 48 hours. We'll email you at .'; no account, organization, session or email; an MCP client's newcomer stops at the forge callback, so never reaches consent or gets a token; existing users unchanged; on in production (settings.waitlist), VISUALCI_WAITLIST=1 for tests --- server/config/production.yaml | 2 + server/migration/src/lib.rs | 2 + .../src/m20261203_000046_waitlist.rs | 40 ++++++ server/src/access.rs | 22 ++++ server/src/controllers/session.rs | 13 ++ server/src/models/mod.rs | 1 + server/src/models/waitlist.rs | 79 ++++++++++++ server/src/settings.rs | 12 ++ server/tests/requests/mod.rs | 1 + server/tests/requests/waitlist.rs | 121 ++++++++++++++++++ 10 files changed, 293 insertions(+) create mode 100644 server/migration/src/m20261203_000046_waitlist.rs create mode 100644 server/src/models/waitlist.rs create mode 100644 server/tests/requests/waitlist.rs diff --git a/server/config/production.yaml b/server/config/production.yaml index 399b1fc4..010f2555 100644 --- a/server/config/production.yaml +++ b/server/config/production.yaml @@ -136,6 +136,8 @@ settings: # Baked into both images from docker/renderer.version, so the server and the renderers always agree. renderer_version: "<%= get_env(name="RENDERER_VERSION") %>" dev_login: false + # Sign-ups are closed until the rebuild opens: someone new goes on the waitlist (models::waitlist) + waitlist: true <% if get_env(name="VISUALCI_GITLAB_CLIENT_ID", default="") != "" %> # GitLab sign-in (VisualCI's OAuth application) and the VisualCI bot user's token (statuses, MR notes, access). gitlab: diff --git a/server/migration/src/lib.rs b/server/migration/src/lib.rs index 3a19b03d..b06595e5 100644 --- a/server/migration/src/lib.rs +++ b/server/migration/src/lib.rs @@ -46,6 +46,7 @@ mod m20261202_000039_repository_id; mod m20261202_000040_closed_builds; mod m20261202_000041_build_creator; mod m20261202_000042_build_groups; +mod m20261203_000046_waitlist; pub struct Migrator; @@ -98,6 +99,7 @@ impl MigratorTrait for Migrator { Box::new(m20261202_000040_closed_builds::Migration), Box::new(m20261202_000041_build_creator::Migration), Box::new(m20261202_000042_build_groups::Migration), + Box::new(m20261203_000046_waitlist::Migration), // inject-above (do not remove this comment) ] } diff --git a/server/migration/src/m20261203_000046_waitlist.rs b/server/migration/src/m20261203_000046_waitlist.rs new file mode 100644 index 00000000..9dc94344 --- /dev/null +++ b/server/migration/src/m20261203_000046_waitlist.rs @@ -0,0 +1,40 @@ +//! The waitlist (closed sign-ups, 3 Dec 2026): someone who signs in without an account gets no account or organization, +//! only a row here, and Nathan writes to them when VisualCI opens. +use sea_orm_migration::prelude::*; + +pub struct Migration; + +impl MigrationName for Migration { + fn name(&self) -> &str { + "m20261203_000046_waitlist" + } +} + +#[async_trait::async_trait] +impl MigrationTrait for Migration { + async fn up(&self, m: &SchemaManager) -> Result<(), DbErr> { + m.get_connection() + .execute_unprepared( + "CREATE TABLE waitlist ( + id BIGSERIAL PRIMARY KEY, + forge TEXT NOT NULL, + site TEXT NOT NULL DEFAULT '', + forge_user_id TEXT NOT NULL, + login TEXT NOT NULL, + name TEXT, + email TEXT, + source TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + last_seen_at TIMESTAMPTZ NOT NULL DEFAULT now(), + UNIQUE (forge, site, forge_user_id) + );", + ) + .await?; + Ok(()) + } + + async fn down(&self, m: &SchemaManager) -> Result<(), DbErr> { + m.get_connection().execute_unprepared("DROP TABLE waitlist;").await?; + Ok(()) + } +} diff --git a/server/src/access.rs b/server/src/access.rs index 4032a9ee..7188486b 100644 --- a/server/src/access.rs +++ b/server/src/access.rs @@ -133,6 +133,28 @@ pub async fn identity_owner(db: &DatabaseConnection, id: &crate::forge::Identity .map(|i| i.user_id)) } +/// Whether a forge sign-in would make a new account: its identity isn't anyone's, it isn't being linked to the +/// signed-in user, and none of its trusted emails is an account's. With sign-ups closed, such a person goes on the +/// waitlist instead (`models::waitlist`). +/// +/// # Errors +/// On a database error. +pub async fn is_new_person(db: &DatabaseConnection, sign_in: &SignIn, link_to: Option<&users::Model>) -> Result { + if link_to.is_some() || identity_owner(db, &sign_in.identity).await?.is_some() { + return Ok(false); + } + for address in sign_in.identity.trusted_emails() { + let found = users::Entity::find() + .filter(sea_orm::sea_query::Expr::cust_with_values("lower(email) = $1", [address.clone()])) + .one(db) + .await?; + if found.is_some() { + return Ok(false); + } + } + Ok(true) +} + /// The user a forge sign-in belongs to, and whether it was created just now: /// 1. the user with this forge identity; /// 2. else the signed-in user, who asked to link it (the caller decides: see `session::may_finish`); diff --git a/server/src/controllers/session.rs b/server/src/controllers/session.rs index bcf08a3d..8bd0d3ac 100644 --- a/server/src/controllers/session.rs +++ b/server/src/controllers/session.rs @@ -277,6 +277,14 @@ async fn forge_callback( let owner = access::identity_owner(&ctx.db, &sign_in.identity).await?; let acts_for_current = may_finish(current.as_ref().map(|u| (u.id, u.pid)), link_for, owner)?; let link_to = current.as_ref().filter(|_| acts_for_current); + // Sign-ups closed: someone new goes on the waitlist, with no account, organization, session or email + if settings.waitlist() && access::is_new_person(&ctx.db, &sign_in, link_to).await? { + let return_to = jar.get(RETURN_COOKIE).and_then(|c| safe_return(c.value())); + let source = crate::models::waitlist::source(&ctx.db, return_to.as_deref()).await?; + crate::models::waitlist::record(&ctx.db, &sign_in.identity, &source).await?; + let jar = jar.remove(Cookie::from(STATE_COOKIE)).remove(Cookie::from(RETURN_COOKIE)); + return Ok((jar, crate::models::waitlist::page(&sign_in.identity)).into_response()); + } let (user, created) = access::user_for_sign_in(&ctx.db, &sign_in, link_to).await?; access::after_sign_in(&ctx.db, &settings, &user, &sign_in).await?; let return_to = jar.get(RETURN_COOKIE).and_then(|c| safe_return(c.value())); @@ -393,6 +401,11 @@ async fn dev_login( if let Some(forge) = params.forge { let sign_in = forge.sign_in(¶ms.email); let current = user_from_jar(&ctx, &jar).await.ok(); + if settings.waitlist() && access::is_new_person(&ctx.db, &sign_in, current.as_ref()).await? { + let source = crate::models::waitlist::source(&ctx.db, params.return_to.as_deref()).await?; + crate::models::waitlist::record(&ctx.db, &sign_in.identity, &source).await?; + return Ok(crate::models::waitlist::page(&sign_in.identity)); + } let (user, created) = access::user_for_sign_in(&ctx.db, &sign_in, current.as_ref()).await?; access::after_sign_in(&ctx.db, &settings, &user, &sign_in).await?; let return_to = params.return_to.as_deref().and_then(safe_return); diff --git a/server/src/models/mod.rs b/server/src/models/mod.rs index 1bdf83a5..624dc7ac 100644 --- a/server/src/models/mod.rs +++ b/server/src/models/mod.rs @@ -31,3 +31,4 @@ pub mod snapshots; pub mod user_tokens; pub mod users; pub mod variants; +pub mod waitlist; diff --git a/server/src/models/waitlist.rs b/server/src/models/waitlist.rs new file mode 100644 index 00000000..2f3c04db --- /dev/null +++ b/server/src/models/waitlist.rs @@ -0,0 +1,79 @@ +//! The waitlist (closed sign-ups): someone who signs in without an account is written here instead of getting one. +//! Nathan reads it and writes to them himself when VisualCI opens; nothing is emailed from here. + +use loco_rs::prelude::*; +use sea_orm::{DbBackend, Statement}; + +use crate::forge::Identity; + +/// Record a sign-in on the waitlist: once per forge account, with its newest name, email and how they arrived. +/// +/// # Errors +/// On a database error. +pub async fn record(db: &DatabaseConnection, identity: &Identity, source: &str) -> ModelResult<()> { + let email = identity.trusted_emails().first().cloned(); + db.execute_raw(Statement::from_sql_and_values( + DbBackend::Postgres, + "INSERT INTO waitlist (forge, site, forge_user_id, login, name, email, source) \ + VALUES ($1, $2, $3, $4, $5, $6, $7) \ + ON CONFLICT (forge, site, forge_user_id) DO UPDATE SET login = EXCLUDED.login, \ + name = COALESCE(EXCLUDED.name, waitlist.name), email = COALESCE(EXCLUDED.email, waitlist.email), \ + last_seen_at = now()", + [ + identity.forge.as_str().into(), + identity.site.clone().into(), + identity.id.clone().into(), + identity.login.clone().into(), + identity.name.clone().into(), + email.into(), + source.into(), + ], + )) + .await?; + Ok(()) +} + +/// How they arrived: `web`, or `mcp: ` when the sign-in came from an MCP client's authorization. +/// +/// # Errors +/// On a database error. +pub async fn source(db: &DatabaseConnection, return_to: Option<&str>) -> ModelResult { + let Some(client_id) = return_to.and_then(crate::oauth::connecting_client) else { return Ok("web".to_string()) }; + let name = db + .query_one_raw(Statement::from_sql_and_values( + DbBackend::Postgres, + "SELECT name FROM oauth_clients WHERE client_id = $1", + [client_id.clone().into()], + )) + .await? + .and_then(|r| r.try_get::>("", "name").ok().flatten()); + Ok(format!("mcp: {}", name.unwrap_or(client_id))) +} + +/// The one page someone on the waitlist sees. +#[must_use] +pub fn page(identity: &Identity) -> Response { + let line = match identity.trusted_emails().first() { + Some(email) => format!("VisualCI opens in about 48 hours. We'll email you at {}.", escape(email)), + None => "VisualCI opens in about 48 hours.".to_string(), + }; + let html = format!( + "VisualCI

{line}

" + ); + ( + [ + (axum::http::header::CONTENT_TYPE, "text/html; charset=utf-8"), + (axum::http::header::CACHE_CONTROL, "no-store"), + ], + html, + ) + .into_response() +} + +fn escape(s: &str) -> String { + s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) +} diff --git a/server/src/settings.rs b/server/src/settings.rs index 7e286054..1934ddf5 100644 --- a/server/src/settings.rs +++ b/server/src/settings.rs @@ -38,6 +38,18 @@ pub struct Settings { /// Lets `/auth/dev-login` sign anyone in. Development and tests only. #[serde(default)] pub dev_login: bool, + /// Sign-ups are closed: someone signing in without an account goes on the waitlist (`models::waitlist`) instead + /// of getting one. `VISUALCI_WAITLIST=1` turns it on too (tests). + #[serde(default)] + pub waitlist: bool, +} + +impl Settings { + /// Whether sign-ups are closed: the setting, or `VISUALCI_WAITLIST=1`, read each time so a test can turn it on. + #[must_use] + pub fn waitlist(&self) -> bool { + self.waitlist || std::env::var("VISUALCI_WAITLIST").is_ok_and(|v| v == "1") + } } #[derive(Clone, Debug, Deserialize)] diff --git a/server/tests/requests/mod.rs b/server/tests/requests/mod.rs index 1942de49..74b4246b 100644 --- a/server/tests/requests/mod.rs +++ b/server/tests/requests/mod.rs @@ -21,3 +21,4 @@ mod open_source; mod public_projects; mod render_metrics; mod staff; +mod waitlist; diff --git a/server/tests/requests/waitlist.rs b/server/tests/requests/waitlist.rs new file mode 100644 index 00000000..c6c705d7 --- /dev/null +++ b/server/tests/requests/waitlist.rs @@ -0,0 +1,121 @@ +//! Closed sign-ups: an existing user signs in as before; someone new goes on the waitlist with no account, +//! organization, session or email, and so never reaches an MCP client's consent step or gets a token. + +use loco_rs::testing::prelude::*; +use serial_test::serial; +use visualci_server::{app::App, models::users}; + +/// Turns sign-ups off for one test, and back on when it ends (even when it fails). +struct Closed; + +impl Closed { + fn new() -> Self { + // SAFETY: the tests here run one at a time (#[serial]), and nothing else reads the environment meanwhile. + unsafe { std::env::set_var("VISUALCI_WAITLIST", "1") }; + Self + } +} + +impl Drop for Closed { + fn drop(&mut self) { + // SAFETY: as above. + unsafe { std::env::remove_var("VISUALCI_WAITLIST") }; + } +} + +fn sign_in(email: &str, id: &str, login: &str, return_to: Option<&str>) -> serde_json::Value { + serde_json::json!({ "email": email, "forge": { "id": id, "login": login }, "return_to": return_to }) +} + +async fn waitlist_rows(ctx: &loco_rs::prelude::AppContext, login: &str) -> Vec<(String, Option)> { + use sea_orm::{ConnectionTrait, DbBackend, Statement}; + ctx.db + .query_all_raw(Statement::from_sql_and_values( + DbBackend::Postgres, + "SELECT source, email FROM waitlist WHERE login = $1", + [login.into()], + )) + .await + .unwrap() + .into_iter() + .map(|r| (r.try_get("", "source").unwrap(), r.try_get("", "email").unwrap())) + .collect() +} + +#[tokio::test] +#[serial] +async fn an_existing_user_signs_in_and_someone_new_goes_on_the_waitlist() { + request::(|request, ctx| async move { + let suffix = &uuid::Uuid::new_v4().to_string()[..8]; + let (old_email, old_login) = (format!("old-{suffix}@example.com"), format!("old-{suffix}")); + // An account made while sign-ups were open + let r = + request.post("/auth/dev-login").json(&sign_in(&old_email, &format!("1{suffix}"), &old_login, None)).await; + assert_eq!(r.status_code(), 200, "{}", r.text()); + + let _closed = Closed::new(); + // They still sign in, and nothing goes on the waitlist for them + let r = + request.post("/auth/dev-login").json(&sign_in(&old_email, &format!("1{suffix}"), &old_login, None)).await; + assert_eq!(r.status_code(), 200, "{}", r.text()); + assert!(r.text().contains("\"ok\""), "signed in: {}", r.text()); + assert!(waitlist_rows(&ctx, &old_login).await.is_empty()); + + // Someone new: the page, a row, and no account or session + let (new_email, new_login) = (format!("new-{suffix}@example.com"), format!("new-{suffix}")); + let r = + request.post("/auth/dev-login").json(&sign_in(&new_email, &format!("2{suffix}"), &new_login, None)).await; + assert_eq!(r.status_code(), 200, "{}", r.text()); + assert!( + r.text().contains(&format!("VisualCI opens in about 48 hours. We'll email you at {new_email}.")), + "{}", + r.text() + ); + assert!(r.headers().get("set-cookie").is_none(), "no session"); + assert!(users::Model::find_by_email(&ctx.db, &new_email).await.is_err(), "no account"); + assert_eq!(waitlist_rows(&ctx, &new_login).await, vec![("web".to_string(), Some(new_email.clone()))]); + + // Again, from an MCP client's sign-in: still no account, and the row says where they came from + let r = request + .post("/auth/dev-login") + .json(&sign_in( + &new_email, + &format!("2{suffix}"), + &new_login, + Some("/oauth/authorize?client_id=claude-test&response_type=code"), + )) + .await; + assert!(r.text().contains("VisualCI opens in about 48 hours"), "{}", r.text()); + assert!(users::Model::find_by_email(&ctx.db, &new_email).await.is_err(), "still no account"); + assert_eq!(waitlist_rows(&ctx, &new_login).await.len(), 1, "one row per person"); + }) + .await; +} + +#[tokio::test] +#[serial] +async fn someone_on_the_waitlist_gets_no_mcp_token() { + request::(|request, ctx| async move { + let _closed = Closed::new(); + let suffix = &uuid::Uuid::new_v4().to_string()[..8]; + let email = format!("mcp-{suffix}@example.com"); + let r = request + .post("/auth/dev-login") + .json(&sign_in( + &email, + &format!("3{suffix}"), + &format!("mcp-{suffix}"), + Some("/oauth/authorize?client_id=x"), + )) + .await; + assert!(r.text().contains("VisualCI opens in about 48 hours"), "{}", r.text()); + // With no session, the authorization page asks them to sign in: there's no consent step to approve, so no + // code and no token + assert!(r.headers().get("set-cookie").is_none(), "no session"); + let page: serde_json::Value = + request.get("/api/ui/oauth/authorize?client_id=x&response_type=code").await.json(); + assert_ne!(page["status"], "consent", "{page}"); + assert!(users::Model::find_by_email(&ctx.db, &email).await.is_err()); + }) + .await; +}