Skip to content
Merged
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
2 changes: 2 additions & 0 deletions server/config/production.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 2 additions & 0 deletions server/migration/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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)
]
}
Expand Down
40 changes: 40 additions & 0 deletions server/migration/src/m20261203_000046_waitlist.rs
Original file line number Diff line number Diff line change
@@ -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(())
}
}
22 changes: 22 additions & 0 deletions server/src/access.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<bool> {
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`);
Expand Down
13 changes: 13 additions & 0 deletions server/src/controllers/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()));
Expand Down Expand Up @@ -393,6 +401,11 @@ async fn dev_login(
if let Some(forge) = params.forge {
let sign_in = forge.sign_in(&params.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);
Expand Down
1 change: 1 addition & 0 deletions server/src/models/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,4 @@ pub mod snapshots;
pub mod user_tokens;
pub mod users;
pub mod variants;
pub mod waitlist;
79 changes: 79 additions & 0 deletions server/src/models/waitlist.rs
Original file line number Diff line number Diff line change
@@ -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: <client's name>` 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<String> {
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::<Option<String>>("", "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!(
"<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" \
content=\"width=device-width, initial-scale=1\"><title>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}}}}p{{max-width:32rem;\
margin:0}}</style></head><body><p>{line}</p></body></html>"
);
(
[
(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('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
}
12 changes: 12 additions & 0 deletions server/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down
1 change: 1 addition & 0 deletions server/tests/requests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,4 @@ mod open_source;
mod public_projects;
mod render_metrics;
mod staff;
mod waitlist;
121 changes: 121 additions & 0 deletions server/tests/requests/waitlist.rs
Original file line number Diff line number Diff line change
@@ -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<String>)> {
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::<App, _, _>(|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::<App, _, _>(|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;
}
Loading