From 86b3b9df94c064cbb01adca630dd97215f1d3455 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 02:47:16 +1300 Subject: [PATCH 1/5] app/: invitations and members (sc-8900): invite by email or GitHub login (admins; 50 a day per organization, 3 a day per address, staff exempt), waiting for the invitee to accept or decline whether or not they have an account (recorded for their account when one exists); accepting never lowers a role; admins withdraw invitations, change roles and remove members, except where the forge decides the membership, and the organization keeps an admin; a removed member is told unless they left themselves --- ...6_12_03_000400_create_invitations_table.rs | 33 ++ app/src/auth/invitations.rs | 513 ++++++++++++++++++ app/src/auth/mod.rs | 3 + app/src/notify/outbox.rs | 7 +- app/tests/invitations.rs | 235 ++++++++ 5 files changed, 789 insertions(+), 2 deletions(-) create mode 100644 app/database/migrations/2026_12_03_000400_create_invitations_table.rs create mode 100644 app/src/auth/invitations.rs create mode 100644 app/tests/invitations.rs diff --git a/app/database/migrations/2026_12_03_000400_create_invitations_table.rs b/app/database/migrations/2026_12_03_000400_create_invitations_table.rs new file mode 100644 index 00000000..3ca537ef --- /dev/null +++ b/app/database/migrations/2026_12_03_000400_create_invitations_table.rs @@ -0,0 +1,33 @@ +use laravel::db::AnyTransaction; + +/// Invitations to an organization, by email or by a login on a forge (ported as today's). `for_user_id` is the +/// account it's for when one existed when it was sent, so it shows on their side; it waits for them to accept. +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.query( + "CREATE TABLE invitations ( + id BIGSERIAL PRIMARY KEY, + pid UUID NOT NULL UNIQUE, + organization_id BIGINT NOT NULL REFERENCES organizations(id) ON DELETE CASCADE, + email TEXT, + forge TEXT, + login TEXT, + role TEXT NOT NULL CHECK (role IN ('admin', 'member', 'read')), + invited_by BIGINT REFERENCES users(id) ON DELETE SET NULL, + accepted_by BIGINT REFERENCES users(id) ON DELETE SET NULL, + accepted_at TIMESTAMPTZ, + for_user_id BIGINT REFERENCES users(id) ON DELETE CASCADE, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + CHECK ((email IS NOT NULL) <> (login IS NOT NULL)), + CHECK ((login IS NULL) = (forge IS NULL)) + ); + CREATE UNIQUE INDEX invitations_pending_email ON invitations (organization_id, lower(email)) + WHERE accepted_at IS NULL AND email IS NOT NULL; + CREATE UNIQUE INDEX invitations_pending_login ON invitations (organization_id, forge, lower(login)) + WHERE accepted_at IS NULL AND login IS NOT NULL; + CREATE INDEX invitations_for_user ON invitations (for_user_id) WHERE accepted_at IS NULL;", + ) + .unprepared() + .await?; + Ok(()) +} diff --git a/app/src/auth/invitations.rs b/app/src/auth/invitations.rs new file mode 100644 index 00000000..5f86830d --- /dev/null +++ b/app/src/auth/invitations.rs @@ -0,0 +1,513 @@ +//! Invitations and members (sc-8900, the auth side), ported from today's server. An admin invites someone by email +//! or GitHub login; the invitation waits for its invitee to accept or decline it in the app, whether or not they +//! already have an account, so nobody joins an organization, or shows among its members, without saying so. Admins +//! change members' roles or remove them, except where the forge decides the membership, and an organization always +//! keeps an admin. + +use laravel::auth::Authenticated; +use laravel::db; +use laravel::prelude::*; +use serde_json::{Value, json}; + +use super::Role; +use super::memberships::MembershipChanged; +use crate::forge::ForgeKind; +use crate::models::User; +use crate::notify::{self, Kind, To}; + +pub fn routes(route: &mut Router) { + route.get("/api/ui/invitations", mine); + route.post("/api/ui/invitations/{id}/accept", accept); + route.post("/api/ui/invitations/{id}/decline", decline); + route.get("/api/ui/orgs/{org}/members", members); + route.post("/api/ui/orgs/{org}/invitations", invite); + route.delete("/api/ui/orgs/{org}/invitations/{id}", withdraw); + route.patch("/api/ui/orgs/{org}/members/{id}", update_member); + route.delete("/api/ui/orgs/{org}/members/{id}", remove_member); +} + +/// Invitation emails an organization may send in a day, and one address may receive from all organizations: inviting, +/// withdrawing and inviting again would otherwise send mail without end, from VisualCI's own domain. +pub const DAILY_PER_ORGANIZATION: i64 = 50; +pub const DAILY_PER_RECIPIENT: i64 = 3; + +/// Who an invitation is for: an email address, or a login on a forge. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Invitee { + Email(String), + Login(ForgeKind, String), +} + +impl Invitee { + /// `someone@example.com`, `@octocat` or `octocat` (a GitHub login). + /// + /// # Errors + /// A message when it's neither. + pub fn parse(input: &str) -> Result { + let s = input.trim(); + if s.contains('@') && !s.starts_with('@') { + let (local, domain) = s.split_once('@').unwrap_or_default(); + if local.is_empty() || !domain.contains('.') || s.contains(char::is_whitespace) { + return Err(format!("{s:?} isn't an email address")); + } + return Ok(Self::Email(s.to_lowercase())); + } + let login = s.trim_start_matches('@'); + let valid = !login.is_empty() + && login.len() <= 39 + && login.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') + && !login.starts_with('-'); + if valid { + Ok(Self::Login(ForgeKind::Github, login.to_string())) + } else { + Err(format!("{s:?} isn't an email address or GitHub login")) + } + } + + /// The account it's for when one exists already: a verified email, or a login on github.com or gitlab.com (a + /// self-managed instance's logins are its own). + /// + /// # Errors + /// On a database error. + pub async fn account(&self) -> laravel::Result> { + match self { + Self::Email(e) => db::query!( + "SELECT id FROM users WHERE lower(email) = {e} AND email_verified_at IS NOT NULL ORDER BY id LIMIT 1" + ) + .scalar() + .await, + Self::Login(f, l) => { + let (forge, login) = (f.as_str(), l.to_lowercase()); + db::query!( + "SELECT user_id FROM identities WHERE forge = {forge} AND site = '' AND lower(login) = {login} \ + ORDER BY id LIMIT 1" + ) + .scalar() + .await + } + } + } +} + +/// Where an invitation's email goes: the account's address when it's for one, else the address it names (an +/// invitation by login to someone without an account gets no email). +async fn address(invitee: &Invitee, account: Option) -> laravel::Result> { + if let Some(id) = account { + return db::query!("SELECT email FROM users WHERE id = {id}").scalar().await; + } + Ok(match invitee { + Invitee::Email(e) => Some(e.clone()), + Invitee::Login(..) => None, + }) +} + +/// `Err(message)` when an invitation to `address` from organization `org_id` would go over a daily limit. +/// +/// # Errors +/// On a database error. +pub async fn may_send(org_id: i64, address: Option<&str>) -> laravel::Result> { + let sent_by_org: i64 = db::query!( + "SELECT count(*) FROM emails WHERE kind = 'invited' AND organization_id = {org_id} \ + AND created_at > now() - interval '24 hours'" + ) + .scalar() + .await? + .unwrap_or(0); + if sent_by_org >= DAILY_PER_ORGANIZATION { + return Ok(Err(format!( + "this organization has sent {DAILY_PER_ORGANIZATION} invitations in the last 24 hours, the limit; try \ + again tomorrow" + ))); + } + if let Some(address) = address { + let received: i64 = db::query!( + "SELECT count(*) FROM emails WHERE kind = 'invited' AND lower(recipient) = lower({address}) \ + AND created_at > now() - interval '24 hours'" + ) + .scalar() + .await? + .unwrap_or(0); + if received >= DAILY_PER_RECIPIENT { + return Ok(Err("that person has been invited too often in the last 24 hours; try again tomorrow".into())); + } + } + Ok(Ok(())) +} + +/// The organization by slug and the person's role there; a 404 when they aren't a member (staff see every one as an +/// admin would). +async fn org_role(user: &User, slug: &str) -> laravel::Result<(i64, String, Role)> { + let user_id = user.id; + let row = db::query!( + "SELECT o.id, o.name, m.role FROM organizations o \ + LEFT JOIN memberships m ON m.organization_id = o.id AND m.user_id = {user_id} WHERE o.slug = {slug}" + ) + .select_one() + .await? + .ok_or_else(|| laravel::abort(404))?; + let role = row.try_get::>("role")?.as_deref().and_then(Role::parse); + let role = match role { + Some(r) => r, + None if user.staff => Role::Admin, + None => return Err(laravel::abort(404)), + }; + Ok((row.try_get("id")?, row.try_get("name")?, role)) +} + +/// The organization, when the person is an admin there: a member gets a 403, anyone else a 404. +async fn admin_org(user: &User, slug: &str, action: &str) -> laravel::Result<(i64, String)> { + let (id, name, role) = org_role(user, slug).await?; + if role < Role::Admin { + return Err(laravel::abort_with(403, format!("only admins can {action}"))); + } + Ok((id, name)) +} + +fn json_of(text: &str) -> laravel::Result { + serde_json::from_str(text).map_err(|e| laravel::Error::msg(e.to_string())) +} + +fn uuid(s: &str) -> laravel::Result { + laravel::str::Uuid::parse_str(s).map(|u| u.to_string()).map_err(|_| laravel::abort(404)) +} + +/// An organization's pending invitations, newest first. +/// +/// # Errors +/// On a database error. +pub async fn pending(org_id: i64) -> laravel::Result> { + let rows = db::query!( + "SELECT json_build_object('id', i.pid, \ + 'invitee', COALESCE(i.email, '@' || i.login || CASE i.forge WHEN 'github' THEN ' (GitHub)' \ + WHEN 'gitlab' THEN ' (GitLab)' ELSE '' END), \ + 'email', i.email, 'forge', i.forge, 'login', i.login, 'role', i.role, \ + 'created_at', to_char(i.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"'))::text AS j \ + FROM invitations i WHERE i.organization_id = {org_id} AND i.accepted_at IS NULL ORDER BY i.id DESC" + ) + .select() + .await?; + rows.iter().map(|r| json_of(&r.try_get::("j")?)).collect() +} + +/// An organization's members, admins first then by name, with their forge logins; emails only for its admins. +/// +/// # Errors +/// On a database error. +pub async fn members_json(org_id: i64, with_emails: bool) -> laravel::Result> { + let rows = db::query!( + "SELECT json_build_object('id', u.pid, 'name', u.name, \ + 'email', CASE WHEN {with_emails} THEN u.email END, 'avatar_url', u.avatar_url, \ + 'login', (SELECT login FROM identities WHERE user_id = u.id ORDER BY id LIMIT 1), \ + 'identities', COALESCE((SELECT json_agg(json_build_object('forge', forge, 'login', login) ORDER BY id) \ + FROM identities WHERE user_id = u.id), '[]'::json), \ + 'role', m.role, 'source', m.source, \ + 'synced_at', to_char(m.synced_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"'), \ + 'since', to_char(m.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"'))::text AS j \ + FROM memberships m JOIN users u ON u.id = m.user_id WHERE m.organization_id = {org_id} \ + ORDER BY CASE m.role WHEN 'admin' THEN 0 WHEN 'member' THEN 1 ELSE 2 END, u.name" + ) + .select() + .await?; + rows.iter().map(|r| json_of(&r.try_get::("j")?)).collect() +} + +/// `GET /api/ui/orgs/{org}/members`: its members, and its pending invitations for its admins. +pub async fn members( + Authenticated(user): Authenticated, + Params(org): Params, +) -> laravel::Result> { + let (org_id, _, role) = org_role(&user, &org).await?; + let admin = role == Role::Admin; + let invitations = if admin { pending(org_id).await? } else { Vec::new() }; + Ok(Json(json!({ "members": members_json(org_id, admin).await?, "invitations": invitations }))) +} + +/// The pending invitations for a person: recorded for them, or to their verified email, or to one of their logins on +/// github.com or gitlab.com. Newest first, each with its organization and who invited them. +/// +/// # Errors +/// On a database error. +pub async fn pending_for(user: &User) -> laravel::Result> { + let user_id = user.id; + let email = user.email_verified_at.is_some().then(|| user.email.to_lowercase()); + let rows = db::query!( + "SELECT json_build_object('id', i.pid, 'organization', json_build_object('slug', o.slug, 'name', o.name), \ + 'role', i.role, 'invited_by', inviter.name, \ + 'created_at', to_char(i.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"'))::text AS j \ + FROM invitations i JOIN organizations o ON o.id = i.organization_id \ + LEFT JOIN users inviter ON inviter.id = i.invited_by \ + WHERE i.accepted_at IS NULL AND (i.for_user_id = {user_id} \ + OR (i.email IS NOT NULL AND lower(i.email) = {email}) \ + OR EXISTS (SELECT 1 FROM identities d WHERE d.user_id = {user_id} AND d.site = '' \ + AND d.forge = i.forge AND lower(d.login) = lower(i.login))) \ + ORDER BY i.id DESC" + ) + .select() + .await?; + rows.iter().map(|r| json_of(&r.try_get::("j")?)).collect() +} + +/// The pending invitation `pid` when it's for this person: its ID, organization and role. A 404 otherwise. +async fn theirs(user: &User, pid: &str) -> laravel::Result<(i64, i64, Role)> { + let pid = uuid(pid)?; + let user_id = user.id; + let email = user.email_verified_at.is_some().then(|| user.email.to_lowercase()); + let row = db::query!( + "SELECT i.id, i.organization_id, i.role FROM invitations i \ + WHERE i.pid = {pid}::uuid AND i.accepted_at IS NULL AND (i.for_user_id = {user_id} \ + OR (i.email IS NOT NULL AND lower(i.email) = {email}) \ + OR EXISTS (SELECT 1 FROM identities d WHERE d.user_id = {user_id} AND d.site = '' \ + AND d.forge = i.forge AND lower(d.login) = lower(i.login)))" + ) + .select_one() + .await? + .ok_or_else(|| laravel::abort(404))?; + let role: String = row.try_get("role")?; + Ok((row.try_get("id")?, row.try_get("organization_id")?, Role::parse(&role).unwrap_or(Role::Read))) +} + +/// `GET /api/ui/invitations`: the signed-in person's pending invitations. +pub async fn mine(Authenticated(user): Authenticated) -> laravel::Result> { + Ok(Json(json!({ "invitations": pending_for(&user).await? }))) +} + +#[laravel::input] +#[validate(authenticated)] +pub struct InviteInput { + /// An email address, or a GitHub login (`octocat` or `@octocat`). + #[validate(required, max_length(320))] + invitee: String, + #[validate(required)] + role: String, +} + +/// `POST /api/ui/orgs/{org}/invitations` (admins): invite someone, or change the role of their pending invitation. +/// It waits for them to accept, whether or not they have an account; they get an email either way when there's an +/// address to send it to. +pub async fn invite( + Authenticated(user): Authenticated, + Params(org): Params, + Valid(p): Valid, +) -> laravel::Result> { + let (org_id, _) = admin_org(&user, &org, "invite people").await?; + let role = Role::parse(&p.role).ok_or_else(|| laravel::abort_with(422, "role is admin, member or read"))?; + let invitee = Invitee::parse(&p.invitee).map_err(|e| laravel::abort_with(422, e))?; + let account = invitee.account().await?; + let to = address(&invitee, account).await?; + if !user.staff + && let Err(e) = may_send(org_id, to.as_deref()).await? + { + return Err(laravel::abort_with(429, e)); + } + let (email, forge, login) = match &invitee { + Invitee::Email(e) => (Some(e.clone()), None, None), + Invitee::Login(f, l) => (None, Some(f.as_str().to_string()), Some(l.clone())), + }; + let (role_name, inviter, pid) = (role.as_str(), user.id, laravel::str::uuid7().to_string()); + let lower_login = login.as_deref().map(str::to_lowercase); + let existing: Option = db::query!( + "SELECT id FROM invitations WHERE organization_id = {org_id} AND accepted_at IS NULL \ + AND ((email IS NOT NULL AND lower(email) = {email}) \ + OR (login IS NOT NULL AND forge = {forge} AND lower(login) = {lower_login}))" + ) + .scalar() + .await?; + let id: i64 = match existing { + Some(id) => { + db::query!( + "UPDATE invitations SET role = {role_name}, for_user_id = COALESCE({account}, for_user_id), \ + updated_at = now() WHERE id = {id}" + ) + .update() + .await?; + id + } + None => db::query!( + "INSERT INTO invitations (pid, organization_id, email, forge, login, role, invited_by, for_user_id) \ + VALUES ({pid}::uuid, {org_id}, {email}, {forge}, {login}, {role_name}, {inviter}, {account}) RETURNING id" + ) + .scalar() + .await? + .ok_or_else(|| laravel::Error::msg("no invitation id"))?, + }; + if let Some(to) = to { + let kind = Kind::Invited { inviter: user.name.clone(), role: role_name.to_string() }; + notify::queue(&kind, To::Address(to), Some(org_id), &format!("invited:{id}")).await?; + } + let row = db::query!("SELECT json_build_object('id', i.pid, \ + 'invitee', COALESCE(i.email, '@' || i.login || CASE i.forge WHEN 'github' THEN ' (GitHub)' \ + WHEN 'gitlab' THEN ' (GitLab)' ELSE '' END), \ + 'email', i.email, 'forge', i.forge, 'login', i.login, 'role', i.role, \ + 'created_at', to_char(i.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"'))::text AS j FROM invitations i WHERE i.id = {id}") + .select_one() + .await? + .ok_or_else(|| laravel::abort(404))?; + Ok(Json(json_of(&row.try_get::("j")?)?)) +} + +/// `POST /api/ui/invitations/{id}/accept`: join with its role, or keep a higher one already held (an invitation +/// never lowers a role: otherwise an admin could demote the last admin, or take a forge-derived membership out of the +/// forge's hands by inviting downwards). +pub async fn accept( + Authenticated(user): Authenticated, + Params(id): Params, +) -> laravel::Result> { + let (invitation, org_id, role) = theirs(&user, &id).await?; + let (user_id, role_name) = (user.id, role.as_str()); + db::transaction(async |tx| { + let current: Option = db::query!( + tx, + "SELECT role FROM memberships WHERE organization_id = {org_id} AND user_id = {user_id} FOR UPDATE" + ) + .scalar() + .await?; + match current.as_deref().and_then(Role::parse) { + None => { + db::query!( + tx, + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org_id}, {user_id}, {role_name}, 'invite', now(), now())" + ) + .insert() + .await?; + } + Some(r) if r < role => { + db::query!( + tx, + "UPDATE memberships SET role = {role_name}, source = 'invite', synced_at = NULL, updated_at = now() \ + WHERE organization_id = {org_id} AND user_id = {user_id}" + ) + .update() + .await?; + } + Some(_) => {} + } + db::query!( + tx, + "UPDATE invitations SET accepted_by = {user_id}, accepted_at = now(), updated_at = now() \ + WHERE id = {invitation}" + ) + .update() + .await?; + Ok(()) + }) + .await?; + let slug: Option = db::query!("SELECT slug FROM organizations WHERE id = {org_id}").scalar().await?; + Ok(Json(json!({ "slug": slug }))) +} + +/// `POST /api/ui/invitations/{id}/decline`: it's withdrawn, as if its admin had. +pub async fn decline( + Authenticated(user): Authenticated, + Params(id): Params, +) -> laravel::Result> { + let (invitation, _, _) = theirs(&user, &id).await?; + db::query!("DELETE FROM invitations WHERE id = {invitation}").delete().await?; + Ok(Json(json!({ "ok": true }))) +} + +/// `DELETE /api/ui/orgs/{org}/invitations/{id}` (admins): withdraw a pending invitation. +pub async fn withdraw( + Authenticated(user): Authenticated, + Params((org, id)): Params<(String, String)>, +) -> laravel::Result> { + let (org_id, _) = admin_org(&user, &org, "withdraw invitations").await?; + let pid = uuid(&id)?; + db::query!( + "DELETE FROM invitations WHERE pid = {pid}::uuid AND organization_id = {org_id} AND accepted_at IS NULL" + ) + .delete() + .await?; + Ok(Json(json!({ "ok": true }))) +} + +/// The membership of user `pid` in an organization the person administers: its organization and user IDs. A +/// membership the forge decides can't be changed here. +async fn managed(user: &User, org: &str, pid: &str) -> laravel::Result<(i64, i64)> { + let (org_id, _) = admin_org(user, org, "manage members").await?; + let pid = uuid(pid)?; + let row = db::query!( + "SELECT m.user_id, m.source FROM memberships m JOIN users u ON u.id = m.user_id \ + WHERE m.organization_id = {org_id} AND u.pid = {pid}::uuid" + ) + .select_one() + .await? + .ok_or_else(|| laravel::abort(404))?; + let source: String = row.try_get("source")?; + if let Some(forge) = ForgeKind::parse(&source) { + return Err(laravel::abort_with( + 422, + format!("this access comes from {}: change their permission on the repository there", forge.label()), + )); + } + Ok((org_id, row.try_get("user_id")?)) +} + +async fn other_admins(org_id: i64, except: i64) -> laravel::Result { + Ok(db::query!( + "SELECT count(*) FROM memberships WHERE organization_id = {org_id} AND role = 'admin' AND user_id <> {except}" + ) + .scalar() + .await? + .unwrap_or(0)) +} + +#[laravel::input] +#[validate(authenticated)] +pub struct MemberInput { + #[validate(required)] + role: String, +} + +/// `PATCH /api/ui/orgs/{org}/members/{id}` (admins): change a member's role. The organization keeps an admin. +pub async fn update_member( + Authenticated(user): Authenticated, + Params((org, id)): Params<(String, String)>, + Valid(p): Valid, +) -> laravel::Result> { + let role = Role::parse(&p.role).ok_or_else(|| laravel::abort_with(422, "role is admin, member or read"))?; + let (org_id, member) = managed(&user, &org, &id).await?; + if role != Role::Admin && other_admins(org_id, member).await? == 0 { + return Err(laravel::abort_with(422, "the organization needs another admin first")); + } + let role_name = role.as_str(); + db::query!( + "UPDATE memberships SET role = {role_name}, updated_at = now() \ + WHERE organization_id = {org_id} AND user_id = {member}" + ) + .update() + .await?; + Ok(Json(json!({ "members": members_json(org_id, true).await? }))) +} + +/// `DELETE /api/ui/orgs/{org}/members/{id}` (admins): remove a member, who's told unless they removed themselves. +/// The organization keeps an admin. +pub async fn remove_member( + Authenticated(user): Authenticated, + Params((org, id)): Params<(String, String)>, +) -> laravel::Result> { + let (org_id, member) = managed(&user, &org, &id).await?; + if other_admins(org_id, member).await? == 0 { + return Err(laravel::abort_with(422, "the organization needs another admin first")); + } + db::query!("DELETE FROM memberships WHERE organization_id = {org_id} AND user_id = {member}").delete().await?; + if member != user.id { + MembershipChanged { organization_id: org_id, user_id: member, role: None }.dispatch().await?; + } + Ok(Json(json!({ "members": members_json(org_id, true).await? }))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_invitees() { + assert_eq!(Invitee::parse(" Ann@Example.com "), Ok(Invitee::Email("ann@example.com".into()))); + assert_eq!(Invitee::parse("@octo-cat"), Ok(Invitee::Login(ForgeKind::Github, "octo-cat".into()))); + assert_eq!(Invitee::parse("octocat"), Ok(Invitee::Login(ForgeKind::Github, "octocat".into()))); + for bad in ["", "@", "a@b", "two words", "-x", "a b@c.com"] { + assert!(Invitee::parse(bad).is_err(), "{bad}"); + } + } +} diff --git a/app/src/auth/mod.rs b/app/src/auth/mod.rs index 55196d2f..a5df8bb7 100644 --- a/app/src/auth/mod.rs +++ b/app/src/auth/mod.rs @@ -8,6 +8,8 @@ //! //! Nobody found: `401`. +pub mod oauth; +pub mod invitations; pub mod memberships; pub mod oauth; pub mod sign_in; @@ -262,6 +264,7 @@ pub fn routes(route: &mut laravel::prelude::Router) { route.get("/login", sign_in::login_page); crate::billing::routes::routes(route); tokens::routes(route); + invitations::routes(route); route.get("/auth/{forge}", sign_in::start); route.post("/auth/{forge}/link", sign_in::link); route.get("/auth/{forge}/callback", sign_in::callback); diff --git a/app/src/notify/outbox.rs b/app/src/notify/outbox.rs index 888ed663..9f70d89b 100644 --- a/app/src/notify/outbox.rs +++ b/app/src/notify/outbox.rs @@ -8,7 +8,7 @@ use super::postmark::{self, Postmark}; use super::render::{About, Kind, Preference, render}; /// Who gets an email. -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Debug)] pub enum To { /// The organization's billing email, or else its admins (each one's preferences apply). Billing(i64), @@ -16,6 +16,8 @@ pub enum To { User(i64), /// The organization's admins (each one's preferences apply). Admins(i64), + /// An address with no account behind it yet (an invitation). + Address(String), } /// The organization's admins who haven't turned this email off, with their user IDs. @@ -57,7 +59,7 @@ async fn admins(org_id: i64, preference: Option) -> laravel::Result< pub async fn queue(kind: &Kind, to: To, org_id: Option, dedupe_key: &str) -> laravel::Result { let org_id = match to { To::Billing(o) | To::Admins(o) => Some(o), - To::User(_) => org_id, + To::User(_) | To::Address(_) => org_id, }; let recipients: Vec<(String, Option)> = match to { To::User(id) => db::query!("SELECT email FROM users WHERE id = {id}") @@ -77,6 +79,7 @@ pub async fn queue(kind: &Kind, to: To, org_id: Option, dedupe_key: &str) - } } To::Admins(o) => admins(o, kind.preference()).await?, + To::Address(a) => vec![(a, None)], }; let data = serde_json::to_value(kind).map_err(|e| laravel::Error::msg(e.to_string()))?; let name = kind.name(); diff --git a/app/tests/invitations.rs b/app/tests/invitations.rs new file mode 100644 index 00000000..8ae24848 --- /dev/null +++ b/app/tests/invitations.rs @@ -0,0 +1,235 @@ +//! Invitations wait for their invitee to accept; only admins invite and manage members; an organization keeps an +//! admin; the forge's memberships stay the forge's; invitation emails are limited per day. + +use app::models::User; +use laravel::db; +use laravel::model::create; +use laravel::testing::prelude::*; + +async fn person(name: &str, email: &str) -> laravel::Result { + let user = create!(User { pid: laravel::str::uuid7(), name: name, email: email, staff: false }).await?; + let id = user.id; + db::query!("UPDATE users SET email_verified_at = now() WHERE id = {id}").update().await?; + User::find_or_fail(id).await +} + +async fn org(slug: &str) -> laravel::Result { + Ok(db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) \ + VALUES (gen_random_uuid(), {slug}, 'Acme', now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap()) +} + +async fn join(org: i64, user: &User, role: &str, source: &str) -> laravel::Result<()> { + let id = user.id; + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org}, {id}, {role}, {source}, now(), now())" + ) + .insert() + .await?; + Ok(()) +} + +async fn role_of(org: i64, user: &User) -> laravel::Result> { + let id = user.id; + db::query!("SELECT role FROM memberships WHERE organization_id = {org} AND user_id = {id}").scalar().await +} + +#[laravel::test] +async fn an_invitation_waits_for_its_invitee_to_accept(app: Application) -> laravel::Result<()> { + let acme = org("acme").await?; + let admin = person("Grace", "grace@example.com").await?; + let ada = person("Ada", "ada@example.com").await?; + join(acme, &admin, "admin", "created").await?; + + let sent = app + .post("/api/ui/orgs/acme/invitations") + .acting_as(&admin) + .header("sec-fetch-site", "same-origin") + .json(json!({ "invitee": "Ada@Example.com", "role": "member" })) + .await; + sent.assert_ok().assert_json_path("invitee", "ada@example.com").assert_json_path("role", "member"); + let id = sent.json()["id"].as_str().unwrap().to_string(); + assert_eq!(role_of(acme, &ada).await?, None, "nobody joins without saying so"); + let emails: Option = + db::query!("SELECT count(*) FROM emails WHERE kind = 'invited' AND recipient = 'ada@example.com'") + .scalar() + .await?; + assert_eq!(emails, Some(1)); + + app.get("/api/ui/orgs/acme/members") + .acting_as(&admin) + .await + .assert_ok() + .assert_json_path("invitations.0.id", id.as_str()); + app.get("/api/ui/invitations") + .acting_as(&ada) + .await + .assert_ok() + .assert_json_path("invitations.0.organization.slug", "acme") + .assert_json_path("invitations.0.invited_by", "Grace"); + + // Someone else can't take it. + let eve = person("Eve", "eve@example.com").await?; + app.post(format!("/api/ui/invitations/{id}/accept")) + .acting_as(&eve) + .header("sec-fetch-site", "same-origin") + .await + .assert_status(404); + + app.post(format!("/api/ui/invitations/{id}/accept")) + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .await + .assert_ok() + .assert_json_path("slug", "acme"); + assert_eq!(role_of(acme, &ada).await?.as_deref(), Some("member")); + app.get("/api/ui/invitations").acting_as(&ada).await.assert_json_path("invitations", json!([])); + let members = app.get("/api/ui/orgs/acme/members").acting_as(&ada).await; + members.assert_ok().assert_json_path("members.0.name", "Grace").assert_json_path("members.1.name", "Ada"); + assert!(members.json()["members"][0]["email"].is_null(), "a member doesn't see emails"); + Ok(()) +} + +#[laravel::test] +async fn only_admins_invite_and_an_invitation_never_lowers_a_role(app: Application) -> laravel::Result<()> { + let acme = org("acme").await?; + let admin = person("Grace", "grace@example.com").await?; + let member = person("Ada", "ada@example.com").await?; + let outsider = person("Eve", "eve@example.com").await?; + join(acme, &admin, "admin", "created").await?; + join(acme, &member, "member", "github").await?; + for (who, status) in [(&member, 403), (&outsider, 404)] { + app.post("/api/ui/orgs/acme/invitations") + .acting_as(who) + .header("sec-fetch-site", "same-origin") + .json(json!({ "invitee": "someone@example.com", "role": "admin" })) + .await + .assert_status(status); + } + + // By GitHub login, for someone who has signed in with it: it's recorded for their account. + let ada_id = member.id; + db::query!( + "INSERT INTO identities (user_id, forge, site, forge_user_id, login, created_at, updated_at) \ + VALUES ({ada_id}, 'github', '', '1', 'ada-l', now(), now())" + ) + .insert() + .await?; + let sent = app + .post("/api/ui/orgs/acme/invitations") + .acting_as(&admin) + .header("sec-fetch-site", "same-origin") + .json(json!({ "invitee": "@Ada-L", "role": "read" })) + .await; + sent.assert_ok().assert_json_path("invitee", "@Ada-L (GitHub)"); + let id = sent.json()["id"].as_str().unwrap().to_string(); + app.post(format!("/api/ui/invitations/{id}/accept")) + .acting_as(&member) + .header("sec-fetch-site", "same-origin") + .await + .assert_ok(); + assert_eq!(role_of(acme, &member).await?.as_deref(), Some("member")); + + // Declining withdraws it. + let again = app + .post("/api/ui/orgs/acme/invitations") + .acting_as(&admin) + .header("sec-fetch-site", "same-origin") + .json(json!({ "invitee": "eve@example.com", "role": "member" })) + .await; + let id = again.json()["id"].as_str().unwrap().to_string(); + app.post(format!("/api/ui/invitations/{id}/decline")) + .acting_as(&outsider) + .header("sec-fetch-site", "same-origin") + .await + .assert_ok(); + app.get("/api/ui/orgs/acme/members").acting_as(&admin).await.assert_json_path("invitations", json!([])); + Ok(()) +} + +#[laravel::test] +async fn admins_manage_members_and_the_organization_keeps_an_admin(app: Application) -> laravel::Result<()> { + let acme = org("acme").await?; + let admin = person("Grace", "grace@example.com").await?; + let ada = person("Ada", "ada@example.com").await?; + let forge = person("Linus", "linus@example.com").await?; + join(acme, &admin, "admin", "created").await?; + join(acme, &ada, "member", "invite").await?; + join(acme, &forge, "member", "github").await?; + + app.patch(format!("/api/ui/orgs/acme/members/{}", admin.pid)) + .acting_as(&admin) + .header("sec-fetch-site", "same-origin") + .json(json!({ "role": "member" })) + .await + .assert_status(422); + app.patch(format!("/api/ui/orgs/acme/members/{}", forge.pid)) + .acting_as(&admin) + .header("sec-fetch-site", "same-origin") + .json(json!({ "role": "read" })) + .await + .assert_status(422); + app.patch(format!("/api/ui/orgs/acme/members/{}", ada.pid)) + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .json(json!({ "role": "admin" })) + .await + .assert_status(403); + app.patch(format!("/api/ui/orgs/acme/members/{}", ada.pid)) + .acting_as(&admin) + .header("sec-fetch-site", "same-origin") + .json(json!({ "role": "admin" })) + .await + .assert_ok(); + assert_eq!(role_of(acme, &ada).await?.as_deref(), Some("admin")); + + // With another admin now, Grace can leave; then Ada is the last admin and can't. + app.delete(format!("/api/ui/orgs/acme/members/{}", admin.pid)) + .acting_as(&admin) + .header("sec-fetch-site", "same-origin") + .await + .assert_ok(); + assert_eq!(role_of(acme, &admin).await?, None); + app.delete(format!("/api/ui/orgs/acme/members/{}", ada.pid)) + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .await + .assert_status(422); + let told: Option = + db::query!("SELECT count(*) FROM emails WHERE recipient = 'grace@example.com'").scalar().await?; + assert_eq!(told, Some(0), "someone removing themselves isn't emailed"); + Ok(()) +} + +#[laravel::test] +async fn invitation_emails_are_limited_per_recipient(app: Application) -> laravel::Result<()> { + let acme = org("acme").await?; + let admin = person("Grace", "grace@example.com").await?; + join(acme, &admin, "admin", "created").await?; + for n in 0..3 { + let key = format!("old:{n}"); + db::query!( + "INSERT INTO emails (kind, dedupe_key, recipient, data) VALUES ('invited', {key}, 'ada@example.com', '[]')" + ) + .insert() + .await?; + } + app.post("/api/ui/orgs/acme/invitations") + .acting_as(&admin) + .header("sec-fetch-site", "same-origin") + .json(json!({ "invitee": "ada@example.com", "role": "member" })) + .await + .assert_status(429); + app.post("/api/ui/orgs/acme/invitations") + .acting_as(&admin) + .header("sec-fetch-site", "same-origin") + .json(json!({ "invitee": "not an address", "role": "member" })) + .await + .assert_status(422); + Ok(()) +} From 84a1d8bbc7770dbb29dfda4a8125d559e14a7349 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 03:15:15 +1300 Subject: [PATCH 2/5] Invitations, review fixes: staff are no admins of organizations they aren't in (their tools are the admin MCP's, with its audit log); changing or removing a member locks the admin memberships first, so two admins demoting each other can't leave none; accepting re-reads the invitation FOR UPDATE (a withdrawn one or a second click is a 404) and tells the person they joined --- app/src/auth/invitations.rs | 88 ++++++++++++++++++++++++++----------- app/tests/invitations.rs | 30 +++++++++++++ 2 files changed, 92 insertions(+), 26 deletions(-) diff --git a/app/src/auth/invitations.rs b/app/src/auth/invitations.rs index 5f86830d..b5a11107 100644 --- a/app/src/auth/invitations.rs +++ b/app/src/auth/invitations.rs @@ -134,8 +134,8 @@ pub async fn may_send(org_id: i64, address: Option<&str>) -> laravel::Result laravel::Result<(i64, String, Role)> { let user_id = user.id; let row = db::query!( @@ -148,7 +148,6 @@ async fn org_role(user: &User, slug: &str) -> laravel::Result<(i64, String, Role let role = row.try_get::>("role")?.as_deref().and_then(Role::parse); let role = match role { Some(r) => r, - None if user.staff => Role::Admin, None => return Err(laravel::abort(404)), }; Ok((row.try_get("id")?, row.try_get("name")?, role)) @@ -354,14 +353,24 @@ pub async fn accept( ) -> laravel::Result> { let (invitation, org_id, role) = theirs(&user, &id).await?; let (user_id, role_name) = (user.id, role.as_str()); - db::transaction(async |tx| { + let joined = db::transaction(async |tx| { + // Still pending? Withdrawn meanwhile, or accepted by a double click: nothing to do. + let pending: Option = db::query!( + tx, + "SELECT id FROM invitations WHERE id = {invitation} AND accepted_at IS NULL FOR UPDATE" + ) + .scalar() + .await?; + if pending.is_none() { + return Ok(None); + } let current: Option = db::query!( tx, "SELECT role FROM memberships WHERE organization_id = {org_id} AND user_id = {user_id} FOR UPDATE" ) .scalar() .await?; - match current.as_deref().and_then(Role::parse) { + let joined = match current.as_deref().and_then(Role::parse) { None => { db::query!( tx, @@ -370,6 +379,7 @@ pub async fn accept( ) .insert() .await?; + true } Some(r) if r < role => { db::query!( @@ -379,9 +389,10 @@ pub async fn accept( ) .update() .await?; + true } - Some(_) => {} - } + Some(_) => false, + }; db::query!( tx, "UPDATE invitations SET accepted_by = {user_id}, accepted_at = now(), updated_at = now() \ @@ -389,9 +400,14 @@ pub async fn accept( ) .update() .await?; - Ok(()) + Ok(Some(joined)) }) .await?; + let Some(joined) = joined else { return Err(laravel::abort(404)) }; + // They're told, as today's grant does, once the membership is there. + if joined { + MembershipChanged::now(org_id, user_id, Some(role)).dispatch().await?; + } let slug: Option = db::query!("SELECT slug FROM organizations WHERE id = {org_id}").scalar().await?; Ok(Json(json!({ "slug": slug }))) } @@ -443,13 +459,41 @@ async fn managed(user: &User, org: &str, pid: &str) -> laravel::Result<(i64, i64 Ok((org_id, row.try_get("user_id")?)) } -async fn other_admins(org_id: i64, except: i64) -> laravel::Result { - Ok(db::query!( - "SELECT count(*) FROM memberships WHERE organization_id = {org_id} AND role = 'admin' AND user_id <> {except}" - ) - .scalar() - .await? - .unwrap_or(0)) +/// Change (`Some(role)`) or remove (`None`) a membership, unless that would leave the organization without an admin. +/// The admin memberships are locked first, so two admins demoting or removing each other at once can't both succeed. +/// `false` when it would leave no admin. +async fn change_member(org_id: i64, member: i64, role: Option) -> laravel::Result { + db::transaction(async |tx| { + let admins = db::query!( + tx, + "SELECT user_id FROM memberships WHERE organization_id = {org_id} AND role = 'admin' FOR UPDATE" + ) + .select() + .await?; + let others = admins.iter().filter(|r| r.try_get::("user_id").is_ok_and(|id| id != member)).count(); + if role != Some(Role::Admin) && others == 0 { + return Ok(false); + } + match role { + Some(role) => { + let role_name = role.as_str(); + db::query!( + tx, + "UPDATE memberships SET role = {role_name}, updated_at = now() \ + WHERE organization_id = {org_id} AND user_id = {member}" + ) + .update() + .await?; + } + None => { + db::query!(tx, "DELETE FROM memberships WHERE organization_id = {org_id} AND user_id = {member}") + .delete() + .await?; + } + } + Ok(true) + }) + .await } #[laravel::input] @@ -467,16 +511,9 @@ pub async fn update_member( ) -> laravel::Result> { let role = Role::parse(&p.role).ok_or_else(|| laravel::abort_with(422, "role is admin, member or read"))?; let (org_id, member) = managed(&user, &org, &id).await?; - if role != Role::Admin && other_admins(org_id, member).await? == 0 { + if !change_member(org_id, member, Some(role)).await? { return Err(laravel::abort_with(422, "the organization needs another admin first")); } - let role_name = role.as_str(); - db::query!( - "UPDATE memberships SET role = {role_name}, updated_at = now() \ - WHERE organization_id = {org_id} AND user_id = {member}" - ) - .update() - .await?; Ok(Json(json!({ "members": members_json(org_id, true).await? }))) } @@ -487,12 +524,11 @@ pub async fn remove_member( Params((org, id)): Params<(String, String)>, ) -> laravel::Result> { let (org_id, member) = managed(&user, &org, &id).await?; - if other_admins(org_id, member).await? == 0 { + if !change_member(org_id, member, None).await? { return Err(laravel::abort_with(422, "the organization needs another admin first")); } - db::query!("DELETE FROM memberships WHERE organization_id = {org_id} AND user_id = {member}").delete().await?; if member != user.id { - MembershipChanged { organization_id: org_id, user_id: member, role: None }.dispatch().await?; + MembershipChanged::now(org_id, member, None).dispatch().await?; } Ok(Json(json!({ "members": members_json(org_id, true).await? }))) } diff --git a/app/tests/invitations.rs b/app/tests/invitations.rs index 8ae24848..8320270d 100644 --- a/app/tests/invitations.rs +++ b/app/tests/invitations.rs @@ -88,6 +88,17 @@ async fn an_invitation_waits_for_its_invitee_to_accept(app: Application) -> lara .assert_ok() .assert_json_path("slug", "acme"); assert_eq!(role_of(acme, &ada).await?.as_deref(), Some("member")); + let added: Option = + db::query!("SELECT count(*) FROM emails WHERE kind = 'added_to_org' AND recipient = 'ada@example.com'") + .scalar() + .await?; + assert_eq!(added, Some(1), "she's told she joined"); + // A second click finds nothing to accept. + app.post(format!("/api/ui/invitations/{id}/accept")) + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .await + .assert_status(404); app.get("/api/ui/invitations").acting_as(&ada).await.assert_json_path("invitations", json!([])); let members = app.get("/api/ui/orgs/acme/members").acting_as(&ada).await; members.assert_ok().assert_json_path("members.0.name", "Grace").assert_json_path("members.1.name", "Ada"); @@ -233,3 +244,22 @@ async fn invitation_emails_are_limited_per_recipient(app: Application) -> larave .assert_status(422); Ok(()) } + +#[laravel::test] +async fn staff_are_no_admins_of_organizations_they_are_not_in(app: Application) -> laravel::Result<()> { + let acme = org("acme").await?; + let admin = person("Grace", "grace@example.com").await?; + join(acme, &admin, "admin", "created").await?; + let staff = person("Sam", "sam@example.com").await?; + let staff_id = staff.id; + db::query!("UPDATE users SET staff = true WHERE id = {staff_id}").update().await?; + let staff = User::find_or_fail(staff_id).await?; + app.get("/api/ui/orgs/acme/members").acting_as(&staff).await.assert_status(404); + app.post("/api/ui/orgs/acme/invitations") + .acting_as(&staff) + .header("sec-fetch-site", "same-origin") + .json(json!({ "invitee": "eve@example.com", "role": "admin" })) + .await + .assert_status(404); + Ok(()) +} From 8f5df994785f9a0a19435932937b63e8010c32ff Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 04:55:58 +1300 Subject: [PATCH 3/5] Rebased on main: Cargo.lock resolved from main's, and the boot checks and dependencies merged --- app/src/auth/mod.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/app/src/auth/mod.rs b/app/src/auth/mod.rs index a5df8bb7..434f6a15 100644 --- a/app/src/auth/mod.rs +++ b/app/src/auth/mod.rs @@ -8,7 +8,6 @@ //! //! Nobody found: `401`. -pub mod oauth; pub mod invitations; pub mod memberships; pub mod oauth; From 5ff5f1fc55b68497f4815c741af0d5f2873a200a Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 06:32:15 +1300 Subject: [PATCH 4/5] CI: run on the up-to-date commit From d90deed0c508a9753386147fce8aac704876f5db Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 08:18:29 +1300 Subject: [PATCH 5/5] CI: a pull_request run after GitHub's Actions incident