From 755c1f8b90e906002b68b01982db654e9b745bc8 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Wed, 2 Dec 2026 15:09:43 +1300 Subject: [PATCH] Invitations wait to be accepted (sc-8739): inviting someone who already has an account (by email or GitHub login) no longer adds them; they're emailed, and the invitation waits in a banner in the app (Accept or Decline) for the account it's for (invitations.for_user_id, migration 000035, set at invite time or when they sign in with that verified email); nothing is accepted at sign-in any more; declining withdraws it; only the invitee can answer it. Members' email addresses are shown to admins only (web app and MCP); others see names and logins --- docs/design.md | 4 +- .../frontend/content/docs/reference/access.md | 4 +- server/frontend/src/api/hooks.ts | 10 ++ server/frontend/src/api/types.ts | 11 ++ server/frontend/src/components/AppShell.tsx | 59 +++++++- server/frontend/src/styles.css | 23 +++ server/migration/src/lib.rs | 2 + .../m20261202_000035_invitation_for_user.rs | 30 ++++ server/src/access.rs | 141 +++++++++++------- server/src/controllers/session.rs | 1 - server/src/controllers/ui.rs | 51 ++++++- server/src/mcp.rs | 13 +- server/src/models/_entities/invitations.rs | 2 + server/src/models/invitations.rs | 36 ++++- server/src/models/organizations.rs | 11 +- server/src/notify.rs | 15 +- ...ci_server__notify__tests__email_texts.snap | 4 +- server/tests/requests/access.rs | 102 ++++++++++++- 18 files changed, 431 insertions(+), 88 deletions(-) create mode 100644 server/migration/src/m20261202_000035_invitation_for_user.rs diff --git a/docs/design.md b/docs/design.md index 31ed74f9..b918f26c 100644 --- a/docs/design.md +++ b/docs/design.md @@ -356,7 +356,9 @@ records its **source**: gives, and owners are admins of every repository, so membership of the GitHub organization that installed the App carries over without a separate rule. Losing every such permission removes the membership. - `invite`: an admin invited them by email or forge login (for people the forge doesn't cover, or organizations with - no linked repository). A pending invitation is accepted when someone signs in with that verified email or login. + no linked repository). An invitation waits for its invitee to accept or decline it in the app, whether or not they + have an account (`invitations.for_user_id` records the account once known); they're emailed either way. Members' + email addresses are shown to admins only. - `staff`: DocSpring support ran `org:add-member`. - `created`: they made the organization. diff --git a/server/frontend/content/docs/reference/access.md b/server/frontend/content/docs/reference/access.md index 8ec81fca..2b8f58aa 100644 --- a/server/frontend/content/docs/reference/access.md +++ b/server/frontend/content/docs/reference/access.md @@ -32,9 +32,9 @@ Access that comes from GitHub shows as **GitHub** in the organization's member l ## Invitations -To add someone GitHub doesn't cover (a designer, a contractor, or anyone in an organization with no linked repository), an admin invites them by email address or GitHub login in the organization's **Members** section, choosing their role. They join when they next sign in with that verified email address or GitHub account. Someone who already has an account joins at once. +To add someone GitHub doesn't cover (a designer, a contractor, or anyone in an organization with no linked repository), an admin invites them by email address or GitHub login in the organization's **Members** section, choosing their role. They get an email, and the invitation waits in VisualCI until they accept or decline it (signed in with that verified email address or GitHub account): nobody joins an organization without saying so. -An organization can send 50 invitations a day, and one address can get 3 a day. An agent can do the same with the MCP tool `invite_member`. `get_organization` lists the members, each with their role and where their access came from. +An organization can send 50 invitations a day, and one address can get 3 a day. An agent can do the same with the MCP tool `invite_member`. `get_organization` lists the members, each with their role and where their access came from. Members' email addresses are shown to admins only; everyone else sees names and logins. ## Several GitHub accounts diff --git a/server/frontend/src/api/hooks.ts b/server/frontend/src/api/hooks.ts index fde3cfec..a266b37f 100644 --- a/server/frontend/src/api/hooks.ts +++ b/server/frontend/src/api/hooks.ts @@ -147,6 +147,16 @@ export function useLogout() { }) } +/** Accept or decline an invitation for the signed-in person; either way it leaves their list. */ +export function useInvitationAnswer() { + const qc = useQueryClient() + return useMutation({ + mutationFn: (v: { id: string; answer: 'accept' | 'decline' }) => + post<{ slug?: string }>(`/api/ui/invitations/${enc(v.id)}/${v.answer}`, {}), + onSuccess: () => qc.invalidateQueries({ queryKey: keys.me }), + }) +} + export function useCreateOrg() { const qc = useQueryClient() return useMutation({ diff --git a/server/frontend/src/api/types.ts b/server/frontend/src/api/types.ts index ea7d449b..82af4e7f 100644 --- a/server/frontend/src/api/types.ts +++ b/server/frontend/src/api/types.ts @@ -71,6 +71,8 @@ export type Me = { /** Forges this server can sign in with (`github`). */ forges: string[] organizations: OrgSummary[] + /** Invitations waiting for this person to accept or decline. */ + invitations?: PendingInvitation[] /** Staff (users.staff): can read customers' feedback. */ staff?: boolean /** Ask "How did you hear about VisualCI?" (once, after sign-up). */ @@ -80,6 +82,15 @@ export type Me = { notifications: Notifications } +/** An invitation to an organization, waiting for the signed-in person's answer. */ +export type PendingInvitation = { + id: string + organization: { slug: string; name: string } + role: 'admin' | 'member' | 'read' + invited_by: string | null + created_at: string +} + /** Emails people can turn off; security emails, billing problems and running out of credits always go. */ export type Notifications = { low_credits: boolean; receipts: boolean } diff --git a/server/frontend/src/components/AppShell.tsx b/server/frontend/src/components/AppShell.tsx index 3e7542e5..8a1e2407 100644 --- a/server/frontend/src/components/AppShell.tsx +++ b/server/frontend/src/components/AppShell.tsx @@ -1,9 +1,10 @@ import { useEffect, useRef, type MouseEvent, type ReactNode } from 'react' -import { Link, Outlet, useParams } from '@tanstack/react-router' +import { Link, Outlet, useNavigate, useParams } from '@tanstack/react-router' import { ChatTextIcon, CreditCardIcon, KeyIcon, MonitorIcon, MoonIcon, PaperPlaneTiltIcon, SignOutIcon, SunIcon, UsersIcon } from '@phosphor-icons/react' -import { useLogout, useMe, useProject, useSnapshot } from '../api/hooks' +import { useInvitationAnswer, useLogout, useMe, useProject, useSnapshot } from '../api/hooks' +import { errorMessage } from '../api/client' import { useTheme, type ThemePref } from '../lib/theme' -import { Avatar, ErrorBox, Spinner } from './ui' +import { Avatar, Button, ErrorBox, Spinner } from './ui' import { Logo } from './Logo' import { appUrl } from '../lib/hosts' import { isDemoPath } from '../lib/demo' @@ -175,11 +176,63 @@ export function AppShell({ children }: { children: ReactNode }) { {isDemoPath(window.location.pathname) && } +
{children}
) } +const roleWords: Record = { admin: 'an admin', member: 'a member', read: 'a read-only member' } + +/** Invitations waiting for the signed-in person: nobody joins an organization without saying so. */ +function InvitationsBanner() { + const me = useMe().data + const answer = useInvitationAnswer() + const navigate = useNavigate() + const invitations = me?.invitations ?? [] + if (!invitations.length) return null + return ( +
+ {invitations.map((i) => { + const busy = answer.isPending && answer.variables?.id === i.id + return ( +
+ + {i.invited_by ? {i.invited_by} : 'Someone'} invited you to join{' '} + {i.organization.name} as {roleWords[i.role] ?? i.role}. + + + + + +
+ ) + })} + {answer.isError && {errorMessage(answer.error)}} +
+ ) +} + /** On the public demo: what it is, and the way to try it on your own tests. */ function DemoBanner() { const me = useMe().data diff --git a/server/frontend/src/styles.css b/server/frontend/src/styles.css index 9debe774..cfcda97d 100644 --- a/server/frontend/src/styles.css +++ b/server/frontend/src/styles.css @@ -4413,6 +4413,29 @@ html.vci-signed-in .site-auth-out { } /* The public demo's banner, under the top bar. */ +/* Invitations waiting for the signed-in person: one line each, with Accept and Decline. */ +.invitations-banner { + display: grid; + gap: var(--space-2); + padding: var(--space-2) var(--space-6); + background: var(--color-accent-soft); + border-bottom: 1px solid var(--color-rule); + font-size: var(--text-sm); +} + +.invitation { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: var(--space-3); +} + +.invitation-actions { + display: inline-flex; + gap: var(--space-2); +} + .demo-banner { display: flex; flex-wrap: wrap; diff --git a/server/migration/src/lib.rs b/server/migration/src/lib.rs index 4184da6e..d63488b4 100644 --- a/server/migration/src/lib.rs +++ b/server/migration/src/lib.rs @@ -38,6 +38,7 @@ mod m20261202_000029_build_error_code; mod m20261202_000030_stripe_order; mod m20261202_000033_linked_by; mod m20261202_000034_render_job_token; +mod m20261202_000035_invitation_for_user; pub struct Migrator; @@ -82,6 +83,7 @@ impl MigratorTrait for Migrator { Box::new(m20261202_000030_stripe_order::Migration), Box::new(m20261202_000033_linked_by::Migration), Box::new(m20261202_000034_render_job_token::Migration), + Box::new(m20261202_000035_invitation_for_user::Migration), // inject-above (do not remove this comment) ] } diff --git a/server/migration/src/m20261202_000035_invitation_for_user.rs b/server/migration/src/m20261202_000035_invitation_for_user.rs new file mode 100644 index 00000000..6fec6e91 --- /dev/null +++ b/server/migration/src/m20261202_000035_invitation_for_user.rs @@ -0,0 +1,30 @@ +//! An invitation waits for its invitee to accept it, even when they already have an account. `for_user_id` is that +//! account once VisualCI knows it (an account with that email or login when they're invited, or the person who signs in +//! with that verified email), so the invitation shows on their side. +use sea_orm_migration::prelude::*; + +pub struct Migration; + +impl MigrationName for Migration { + fn name(&self) -> &str { + "m20261202_000035_invitation_for_user" + } +} + +#[async_trait::async_trait] +impl MigrationTrait for Migration { + async fn up(&self, m: &SchemaManager) -> Result<(), DbErr> { + m.get_connection() + .execute_unprepared( + "ALTER TABLE invitations ADD COLUMN for_user_id BIGINT REFERENCES users(id) ON DELETE CASCADE; + CREATE INDEX invitations_for_user ON invitations (for_user_id) WHERE accepted_at IS NULL;", + ) + .await?; + Ok(()) + } + + async fn down(&self, m: &SchemaManager) -> Result<(), DbErr> { + m.get_connection().execute_unprepared("ALTER TABLE invitations DROP COLUMN for_user_id;").await?; + Ok(()) + } +} diff --git a/server/src/access.rs b/server/src/access.rs index 01b356b7..632bdfc0 100644 --- a/server/src/access.rs +++ b/server/src/access.rs @@ -234,70 +234,107 @@ pub async fn after_sign_in( let grants = grants_from(&projects, &permissions); let scope = site_scope(db, settings, user.id, forge, site).await?; let changed = memberships::Model::apply_forge(db, user.id, forge, &grants, scope.as_deref()).await?; - let accepted = accept_invitations(db, user, sign_in.identity.trusted_emails()).await?; - Ok(changed + accepted) + note_invitations(db, user, sign_in.identity.trusted_emails()).await?; + Ok(changed) } -/// Accept the pending invitations for any of the user's verified addresses (their own, when verified, and -/// `verified_emails` from a forge) or forge logins. Returns how many. +/// Record that the pending invitations to these verified addresses (a forge's trusted emails at sign-in) are for this +/// person, so they show on their side even when it isn't their account's address. Nothing is accepted. /// /// # Errors /// On a database error. -pub async fn accept_invitations( - db: &DatabaseConnection, - user: &users::Model, - verified_emails: &[String], -) -> Result { - let logins = identities::Entity::find().filter(identities::Column::UserId.eq(user.id)).all(db).await?; - let pending = invitations::Entity::find().filter(invitations::Column::AcceptedAt.is_null()).all(db).await?; - let mut emails: Vec = verified_emails.iter().map(|e| e.to_lowercase()).collect(); - if user.email_verified_at.is_some() { - emails.push(user.email.to_lowercase()); +pub async fn note_invitations(db: &DatabaseConnection, user: &users::Model, verified_emails: &[String]) -> Result<()> { + let emails: Vec = verified_emails.iter().map(|e| e.to_lowercase()).collect(); + if emails.is_empty() { + return Ok(()); } - let mut accepted = 0; + let pending = invitations::Entity::find() + .filter(invitations::Column::AcceptedAt.is_null()) + .filter(invitations::Column::ForUserId.is_null()) + .all(db) + .await?; for invitation in pending { - let by_email = invitation.email.as_deref().is_some_and(|e| emails.contains(&e.to_lowercase())); - let by_login = invitation.login.as_deref().is_some_and(|l| { - logins - .iter() - // An invitation by login is for github.com or gitlab.com: a self-managed instance's logins are its own. - .any(|i| { - i.site.is_empty() - && Some(i.forge.as_str()) == invitation.forge.as_deref() - && i.login.eq_ignore_ascii_case(l) - }) - }); - if !(by_email || by_login) { - continue; - } - let role = Role::parse(&invitation.role).unwrap_or(Role::Read); - // An invitation adds someone or raises their role, never lowers it: otherwise an admin could demote the last - // admin (themselves included) or take a forge-derived row out of the forge's hands by inviting downwards. - let current = memberships::Entity::find() - .filter(memberships::memberships::Column::OrganizationId.eq(invitation.organization_id)) - .filter(memberships::memberships::Column::UserId.eq(user.id)) - .one(db) - .await? - .map(|m| m.role()); - if current.is_none_or(|r| r < role) { - memberships::Model::grant(db, invitation.organization_id, user.id, role, memberships::INVITE).await?; + if invitation.email.as_deref().is_some_and(|e| emails.contains(&e.to_lowercase())) { + let mut a = invitation.into_active_model(); + a.for_user_id = Set(Some(user.id)); + a.update(db).await?; } - let mut a = invitation.into_active_model(); - a.accepted_by = Set(Some(user.id)); - a.accepted_at = Set(Some(chrono::Utc::now().into())); - a.update(db).await?; - accepted += 1; } - Ok(accepted) + Ok(()) +} + +/// The person's pending invitation `pid`, if it's theirs. +async fn their_invitation(db: &DatabaseConnection, user: &users::Model, pid: Uuid) -> Result { + let logins = identities::Entity::find().filter(identities::Column::UserId.eq(user.id)).all(db).await?; + crate::models::invitations::Model::pending_for(db, user, &logins) + .await? + .into_iter() + .find(|i| i.pid == pid) + .ok_or(Error::NotFound) +} + +/// Accept an invitation that's for this person: they join with its role, or keep a higher one they have (an +/// invitation never lowers a role: otherwise an admin could demote the last admin, themselves included, or take a +/// forge-derived row out of the forge's hands by inviting downwards). Returns the organization's id. +/// +/// # Errors +/// `NotFound` when it isn't a pending invitation for them; database errors. +pub async fn accept_invitation(db: &DatabaseConnection, user: &users::Model, pid: Uuid) -> Result { + let invitation = their_invitation(db, user, pid).await?; + let org = invitation.organization_id; + let role = Role::parse(&invitation.role).unwrap_or(Role::Read); + let current = memberships::Entity::find() + .filter(memberships::memberships::Column::OrganizationId.eq(org)) + .filter(memberships::memberships::Column::UserId.eq(user.id)) + .one(db) + .await? + .map(|m| m.role()); + if current.is_none_or(|r| r < role) { + memberships::Model::grant(db, org, user.id, role, memberships::INVITE).await?; + } + let mut a = invitation.into_active_model(); + a.accepted_by = Set(Some(user.id)); + a.accepted_at = Set(Some(chrono::Utc::now().into())); + a.update(db).await?; + Ok(org) +} + +/// Decline an invitation that's for this person: it's withdrawn, as if its admin had. +/// +/// # Errors +/// `NotFound` when it isn't a pending invitation for them; database errors. +pub async fn decline_invitation(db: &DatabaseConnection, user: &users::Model, pid: Uuid) -> Result<()> { + let invitation = their_invitation(db, user, pid).await?; + invitations::Entity::delete_by_id(invitation.id).exec(db).await?; + Ok(()) +} + +/// The invitation, recorded for its invitee's account when they have one already. +/// +/// # Errors +/// On a database error. +pub async fn for_invitee( + db: &DatabaseConnection, + invitation: invitations::Model, + invitee: &crate::models::invitations::Invitee, +) -> Result { + let Some(account) = invitee_user(db, invitee).await? else { return Ok(invitation) }; + let mut a = invitation.into_active_model(); + a.for_user_id = Set(Some(account.id)); + Ok(a.update(db).await?) } -/// An invitation for someone who already has an account (a verified email, or a forge login) takes effect at once. +/// The account an invitation is for, when one exists already: a verified email, or a login on github.com or +/// gitlab.com. /// /// # Errors /// On a database error. -pub async fn accept_existing(db: &DatabaseConnection, invitee: &crate::models::invitations::Invitee) -> Result<()> { +pub async fn invitee_user( + db: &DatabaseConnection, + invitee: &crate::models::invitations::Invitee, +) -> Result> { use crate::models::invitations::Invitee; - let user = match invitee { + Ok(match invitee { Invitee::Email(e) => { users::Entity::find() .filter(sea_orm::sea_query::Expr::cust_with_values("lower(email) = $1", [e.clone()])) @@ -315,11 +352,7 @@ pub async fn accept_existing(db: &DatabaseConnection, invitee: &crate::models::i Some(i) => users::Entity::find_by_id(i.user_id).one(db).await?, None => None, }, - }; - if let Some(user) = user { - accept_invitations(db, &user, &[]).await?; - } - Ok(()) + }) } /// Recompute one person's memberships from one forge through the projects' installations (`installation` limits it diff --git a/server/src/controllers/session.rs b/server/src/controllers/session.rs index 9300f7dd..bcf08a3d 100644 --- a/server/src/controllers/session.rs +++ b/server/src/controllers/session.rs @@ -418,7 +418,6 @@ async fn dev_login( (user, true) } }; - access::accept_invitations(&ctx.db, &user, &[]).await?; let return_to = params.return_to.as_deref().and_then(safe_return); let jar = signed_in(&ctx, jar, &user, created, return_to.as_deref(), "dev").await?; Ok((jar, Json(serde_json::json!({ "ok": true }))).into_response()) diff --git a/server/src/controllers/ui.rs b/server/src/controllers/ui.rs index 9db033e2..53e1f591 100644 --- a/server/src/controllers/ui.rs +++ b/server/src/controllers/ui.rs @@ -109,6 +109,21 @@ async fn me(CurrentUser(user): CurrentUser, State(ctx): State) -> Re } let staff = user.staff; let ids = identities::for_users(&ctx.db, &[user.id]).await?.remove(&user.id).unwrap_or_default(); + // Invitations waiting for them to accept or decline, with the organization and who invited them. + let logins = + identities::Entity::find().filter(identities::identities::Column::UserId.eq(user.id)).all(&ctx.db).await?; + let mut invited = Vec::new(); + for i in invitations::Model::pending_for(&ctx.db, &user, &logins).await? { + let Some(org) = org_entity::Entity::find_by_id(i.organization_id).one(&ctx.db).await? else { continue }; + let by = match i.invited_by { + Some(id) => crate::models::_entities::users::Entity::find_by_id(id).one(&ctx.db).await?.map(|u| u.name), + None => None, + }; + invited.push(serde_json::json!({ + "id": i.pid, "organization": { "slug": org.slug, "name": org.name }, "role": i.role, + "invited_by": by, "created_at": i.created_at.to_rfc3339(), + })); + } format::json(serde_json::json!({ "user": { "name": user.name, "email": user.email, "avatar_url": user.avatar_url, @@ -117,6 +132,7 @@ async fn me(CurrentUser(user): CurrentUser, State(ctx): State) -> Re "forges": crate::forge::Forge::all(&crate::settings::Settings::from_context(&ctx)?) .iter().map(|f| f.kind().as_str()).collect::>(), "organizations": orgs, + "invitations": invited, "staff": staff, // Ask "How did you hear about VisualCI?" (once, after sign-up), with these choices. "heard_about_pending": user.heard_about_pending, @@ -368,7 +384,7 @@ async fn show_org( .map(|t| serde_json::json!({ "credits": -t.amount, "kind": t.kind, "reference": t.reference, "created_at": t.created_at.to_rfc3339() })) .collect(); let usage = org.usage(&ctx.db).await?; - let members = org.members_json(&ctx.db).await?; + let members = org.members_json(&ctx.db, role.is_admin()).await?; let invitations: Vec = if role.is_admin() { invitations::Model::pending(&ctx.db, org.id).await?.iter().map(invitations::Model::json).collect() } else { @@ -1058,13 +1074,36 @@ async fn invite( } } let invitation = invitations::Model::invite(&ctx.db, org.id, &invitee, p.role, user.id).await?; - // Someone already signed up with that address or login joins now; anyone else gets an email. - access::accept_existing(&ctx.db, &invitee).await?; + // It waits for them to accept, whether or not they have an account; they get an email either way. + let invitation = access::for_invitee(&ctx.db, invitation, &invitee).await?; crate::notify::invited(&ctx, &org, &user, &invitation).await?; crate::notify::deliver_soon(&ctx); format::json(invitation.json()) } +/// Accept an invitation for the signed-in person: they join with its role. Returns the organization's slug. +#[debug_handler] +async fn accept_invitation( + CurrentUser(user): CurrentUser, + State(ctx): State, + Path(pid): Path, +) -> Result { + let org_id = access::accept_invitation(&ctx.db, &user, pid).await?; + let org = org_entity::Entity::find_by_id(org_id).one(&ctx.db).await?.ok_or(Error::NotFound)?; + format::json(serde_json::json!({ "slug": org.slug })) +} + +/// Decline an invitation for the signed-in person: it's withdrawn. +#[debug_handler] +async fn decline_invitation( + CurrentUser(user): CurrentUser, + State(ctx): State, + Path(pid): Path, +) -> Result { + access::decline_invitation(&ctx.db, &user, pid).await?; + format::json(serde_json::json!({ "ok": true })) +} + /// Withdraw a pending invitation (admins). #[debug_handler] async fn delete_invitation( @@ -1139,7 +1178,7 @@ async fn update_member( let mut a = membership.into_active_model(); a.role = Set(p.role.as_str().to_string()); a.update(&ctx.db).await?; - format::json(serde_json::json!({ "members": org.members_json(&ctx.db).await? })) + format::json(serde_json::json!({ "members": org.members_json(&ctx.db, true).await? })) } /// Remove someone (admins; not forge-derived access). @@ -1160,7 +1199,7 @@ async fn delete_member( crate::notify::member_changed(&ctx.db, org.id, removed, None).await?; crate::notify::deliver_soon(&ctx); } - format::json(serde_json::json!({ "members": org.members_json(&ctx.db).await? })) + format::json(serde_json::json!({ "members": org.members_json(&ctx.db, true).await? })) } /// A pull request's changeset across all its builds (`models::changeset`). @@ -1296,6 +1335,8 @@ pub fn routes() -> Routes { Routes::new() .prefix("/api/ui") .add("/me", get(me)) + .add("/invitations/{id}/accept", post(accept_invitation)) + .add("/invitations/{id}/decline", post(decline_invitation)) .add("/staff/feedback", get(staff_feedback)) .add("/staff/signups", get(staff_signups)) .add("/staff/emails", get(staff_emails)) diff --git a/server/src/mcp.rs b/server/src/mcp.rs index 97ffc1a0..3f731052 100644 --- a/server/src/mcp.rs +++ b/server/src/mcp.rs @@ -1123,8 +1123,11 @@ impl VisualCi { _ => None, }; let setup = crate::models::setup::state(&self.ctx.db, &org, user_pid).await.map_err(internal)?; - let members = - if only.is_some() { Vec::new() } else { org.members_json(&self.ctx.db).await.map_err(internal)? }; + let members = if only.is_some() { + Vec::new() + } else { + org.members_json(&self.ctx.db, role == "admin" || role == "staff").await.map_err(internal)? + }; let pending: Vec = if role == "admin" || role == "staff" { invitations::Model::pending(&self.ctx.db, org.id) .await @@ -1142,7 +1145,7 @@ impl VisualCi { } #[tool( - description = "Invite someone to an organization by email address or GitHub login (admins, with a personal access token). They join with `role` (admin, member or read) when they next sign in with that verified email or login; someone who already has an account joins now. People with access to a linked repository on GitHub don't need an invitation: their access follows their permission there.", + description = "Invite someone to an organization by email address or GitHub login (admins, with a personal access token). They're emailed, and join with `role` (admin, member or read) once they accept it in the web app, whether or not they already have an account. People with access to a linked repository on GitHub don't need an invitation: their access follows their permission there.", annotations( title = "Invite member", read_only_hint = false, @@ -1175,12 +1178,12 @@ impl VisualCi { } let invitation = invitations::Model::invite(&self.ctx.db, org.id, &invitee, args.role, u.id).await.map_err(internal)?; - crate::access::accept_existing(&self.ctx.db, &invitee).await.map_err(internal)?; + let invitation = crate::access::for_invitee(&self.ctx.db, invitation, &invitee).await.map_err(internal)?; crate::notify::invited(&self.ctx, &org, &u, &invitation).await.map_err(internal)?; crate::notify::deliver_soon(&self.ctx); Ok(CallToolResult::structured(json!({ "invitation": invitation.json(), - "members": org.members_json(&self.ctx.db).await.map_err(internal)?, + "members": org.members_json(&self.ctx.db, true).await.map_err(internal)?, }))) } diff --git a/server/src/models/_entities/invitations.rs b/server/src/models/_entities/invitations.rs index 79a04941..e45687f2 100644 --- a/server/src/models/_entities/invitations.rs +++ b/server/src/models/_entities/invitations.rs @@ -21,6 +21,8 @@ pub struct Model { pub role: String, pub invited_by: Option, pub accepted_by: Option, + /// The account it's for, once known; it waits for them to accept. + pub for_user_id: Option, pub accepted_at: Option, pub created_at: DateTimeWithTimeZone, pub updated_at: DateTimeWithTimeZone, diff --git a/server/src/models/invitations.rs b/server/src/models/invitations.rs index 978cb556..ced5c444 100644 --- a/server/src/models/invitations.rs +++ b/server/src/models/invitations.rs @@ -1,6 +1,6 @@ //! Invitations to an organization by email or forge login, for people the forge doesn't give access (see "Access -//! and forges" in docs/design.md). A pending invitation is accepted when someone signs in with that verified email or -//! forge login (`access::accept_invitations`). +//! and forges" in docs/design.md). An invitation waits for its invitee to accept or decline it in the app, whether or +//! not they already have an account: nobody joins an organization, or shows up among its members, without saying so. use loco_rs::prelude::*; @@ -170,6 +170,38 @@ impl Model { .await?) } + /// The pending invitations for `user`: recorded for them (`for_user_id`), or to their verified email, or to one of + /// their logins on github.com or gitlab.com (a self-managed instance's logins are its own). Newest first. + /// + /// # Errors + /// On a database error. + pub async fn pending_for( + db: &impl ConnectionTrait, + user: &super::_entities::users::Model, + logins: &[super::_entities::identities::Model], + ) -> ModelResult> { + let email = user.email_verified_at.is_some().then(|| user.email.to_lowercase()); + let all = Entity::find() + .filter(invitations::Column::AcceptedAt.is_null()) + .order_by_desc(invitations::Column::Id) + .all(db) + .await?; + Ok(all + .into_iter() + .filter(|i| { + i.for_user_id == Some(user.id) + || i.email.as_deref().is_some_and(|e| Some(e.to_lowercase()) == email) + || i.login.as_deref().is_some_and(|l| { + logins.iter().any(|id| { + id.site.is_empty() + && Some(id.forge.as_str()) == i.forge.as_deref() + && id.login.eq_ignore_ascii_case(l) + }) + }) + }) + .collect()) + } + /// An organization's pending invitations, newest first. /// /// # Errors diff --git a/server/src/models/organizations.rs b/server/src/models/organizations.rs index 6a999006..2018ccc6 100644 --- a/server/src/models/organizations.rs +++ b/server/src/models/organizations.rs @@ -179,11 +179,16 @@ impl Model { } /// Everyone in the organization with their role, where it came from (`created`, `invite`, `staff`, or a forge - /// such as `github`), and their forge identities, admins first. + /// such as `github`), and their forge identities, admins first. Their email addresses only `with_emails` (for + /// admins and staff); everyone else sees names and logins. /// /// # Errors /// On a database error. - pub async fn members_json(&self, db: &impl ConnectionTrait) -> ModelResult> { + pub async fn members_json( + &self, + db: &impl ConnectionTrait, + with_emails: bool, + ) -> ModelResult> { let rows = memberships::Entity::find() .filter(memberships::Column::OrganizationId.eq(self.id)) .find_also_related(super::_entities::users::Entity) @@ -199,7 +204,7 @@ impl Model { Some(( m.role(), serde_json::json!({ - "id": u.pid, "name": u.name, "email": u.email, "avatar_url": u.avatar_url, + "id": u.pid, "name": u.name, "email": with_emails.then_some(u.email), "avatar_url": u.avatar_url, "login": ids.first().map(|i| i.login.clone()), "identities": super::identities::json(ids), "role": m.role, "source": m.source, diff --git a/server/src/notify.rs b/server/src/notify.rs index d41a47c8..ad0ca006 100644 --- a/server/src/notify.rs +++ b/server/src/notify.rs @@ -310,10 +310,10 @@ pub fn render(kind: &Kind, about: &About<'_>) -> Rendered { format!("{inviter} invited you to {org} on VisualCI"), vec![format!( "{inviter} invited you to join {org} on VisualCI as {}. Sign in with this email address, or with GitHub, \ - to join.", + and accept it there.", article(role) )], - ("Sign in".into(), about.app_url.to_string()), + ("See the invitation".into(), about.app_url.to_string()), ), Kind::AddedToOrg { role } => ( format!("You joined {org} on VisualCI"), @@ -467,11 +467,14 @@ pub async fn invited( inviter: &users::Model, invitation: &crate::models::_entities::invitations::Model, ) -> Result<()> { - let Some(address) = invitation.email.as_deref() else { return Ok(()) }; - let exists = users::Entity::find().filter(users::Column::Email.eq(address)).one(&ctx.db).await?.is_some(); - if exists { + // To the account it's for when there is one (an invitation by login names no address), else the address. + let account = match invitation.for_user_id { + Some(id) => users::Entity::find_by_id(id).one(&ctx.db).await?, + None => None, + }; + let Some(address) = account.as_ref().map(|u| u.email.as_str()).or(invitation.email.as_deref()) else { return Ok(()); - } + }; let kind = Kind::Invited { inviter: inviter.name.clone(), role: invitation.role.clone() }; let key = format!("invited:{}", invitation.id); let data = serde_json::to_value(&kind).map_err(|e| Error::string(&e.to_string()))?; diff --git a/server/src/snapshots/visualci_server__notify__tests__email_texts.snap b/server/src/snapshots/visualci_server__notify__tests__email_texts.snap index f1749bbb..f8415ce9 100644 --- a/server/src/snapshots/visualci_server__notify__tests__email_texts.snap +++ b/server/src/snapshots/visualci_server__notify__tests__email_texts.snap @@ -139,9 +139,9 @@ Questions? Reply to this email. ## Invitation Subject: Grace Hopper invited you to Acme on VisualCI -Grace Hopper invited you to join Acme on VisualCI as a member. Sign in with this email address, or with GitHub, to join. +Grace Hopper invited you to join Acme on VisualCI as a member. Sign in with this email address, or with GitHub, and accept it there. -Sign in: https://app.visualci.com +See the invitation: https://app.visualci.com Questions? Reply to this email. diff --git a/server/tests/requests/access.rs b/server/tests/requests/access.rs index 53b78cdc..79f8da95 100644 --- a/server/tests/requests/access.rs +++ b/server/tests/requests/access.rs @@ -105,7 +105,9 @@ async fn repository_permission_sets_the_role_and_losing_it_removes_the_membershi let org: serde_json::Value = request.get(&format!("/api/ui/orgs/{}", w.org.slug)).add_header("cookie", bob_jar.clone()).await.json(); assert_eq!(org["role"], "member"); - let bob = org["members"].as_array().unwrap().iter().find(|m| m["email"] == email.as_str()).unwrap().clone(); + // By login: members see each other's names and logins, not email addresses. + let bob = org["members"].as_array().unwrap().iter().find(|m| m["login"] == "bob").unwrap().clone(); + assert!(bob["email"].is_null(), "{bob}"); assert_eq!((bob["role"].as_str(), bob["source"].as_str()), (Some("member"), Some("github"))); assert_eq!(bob["identities"][0]["login"], "bob"); assert_eq!(org["invitations"], serde_json::json!([]), "only admins see invitations"); @@ -209,12 +211,27 @@ async fn invitations_by_email_and_by_login_are_accepted_at_sign_in() { request.get(&format!("/api/ui/orgs/{}", w.org.slug)).add_header("cookie", w.admin_jar.clone()).await.json(); assert_eq!(org["invitations"].as_array().unwrap().len(), 2, "{org}"); - // Carol signs in with that email (any sign-in); Dave with GitHub as that login, under another address. - request.post("/auth/dev-login").json(&serde_json::json!({ "email": carol })).await; + // Carol signs in with that email (any sign-in); Dave with GitHub as that login, under another address. Neither + // joins until they accept: the invitation waits on their side. + let carol_jar = cookies(&request.post("/auth/dev-login").json(&serde_json::json!({ "email": carol })).await); + assert!(membership(&ctx, w.org.id, &carol).await.is_none(), "not until carol accepts"); + let accept = |jar: String| { + let request = &request; + async move { + let me: serde_json::Value = request.get("/api/ui/me").add_header("cookie", jar.clone()).await.json(); + let invitation = me["invitations"][0]["id"].as_str().expect("an invitation waits").to_string(); + let r = + request.post(&format!("/api/ui/invitations/{invitation}/accept")).add_header("cookie", jar).await; + assert_eq!(r.status_code(), 200, "{}", r.text()); + } + }; + accept(carol_jar).await; let m = membership(&ctx, w.org.id, &carol).await.expect("carol joined"); assert_eq!((m.role(), m.source.as_str()), (Role::Read, "invite")); let dave = format!("dave-{tag}@example.com"); - github_sign_in(&request, None, &dave, &format!("gh-{tag}"), &dave_login, &[]).await; + let dave_jar = cookies(&github_sign_in(&request, None, &dave, &format!("gh-{tag}"), &dave_login, &[]).await); + assert!(membership(&ctx, w.org.id, &dave).await.is_none(), "not until dave accepts"); + accept(dave_jar).await; let m = membership(&ctx, w.org.id, &dave).await.expect("dave joined"); assert_eq!((m.role(), m.source.as_str()), (Role::Member, "invite")); let org: serde_json::Value = @@ -408,6 +425,13 @@ async fn an_invitation_never_lowers_a_role() { .json(&serde_json::json!({ "invitee": w.admin_email, "role": "read" })) .await; assert_eq!(r.status_code(), 200, "{}", r.text()); + let me: serde_json::Value = request.get("/api/ui/me").add_header("cookie", w.admin_jar.clone()).await.json(); + let invitation = me["invitations"][0]["id"].as_str().unwrap().to_string(); + let r = request + .post(&format!("/api/ui/invitations/{invitation}/accept")) + .add_header("cookie", w.admin_jar.clone()) + .await; + assert_eq!(r.status_code(), 200, "{}", r.text()); assert_eq!(membership(&ctx, w.org.id, &w.admin_email).await.unwrap().role(), Role::Admin); }) .await; @@ -499,3 +523,73 @@ async fn a_link_whose_linker_lost_access_is_removed() { }) .await; } + +/// An invitation to someone who already has an account doesn't add them: it waits for them to accept or decline it, +/// they're emailed, nobody else can accept it, and declining withdraws it. Only admins see members' email addresses. +#[tokio::test] +#[serial] +async fn an_existing_user_accepts_or_declines_an_invitation_and_only_admins_see_emails() { + request::(|request, ctx| async move { + let w = world(&request, &ctx).await; + let tag = uuid::Uuid::new_v4().to_string(); + let erin = format!("erin-{tag}@example.com"); + let erin_jar = cookies(&request.post("/auth/dev-login").json(&serde_json::json!({ "email": erin })).await); + let invite = |role: &str| { + request + .post(&format!("/api/ui/orgs/{}/invitations", w.org.slug)) + .add_header("cookie", w.admin_jar.clone()) + .json(&serde_json::json!({ "invitee": erin, "role": role })) + }; + assert_eq!(invite("read").await.status_code(), 200); + assert!(membership(&ctx, w.org.id, &erin).await.is_none(), "not added without saying so"); + let emailed: Vec = { + use sea_orm::ConnectionTrait; + ctx.db + .query_all_raw(sea_orm::Statement::from_sql_and_values( + sea_orm::DbBackend::Postgres, + "SELECT recipient FROM emails WHERE organization_id = $1 AND kind = 'invited'", + [w.org.id.into()], + )) + .await + .unwrap() + .iter() + .map(|r| r.try_get("", "recipient").unwrap()) + .collect() + }; + assert!(emailed.contains(&erin), "erin is emailed about it"); + + let me: serde_json::Value = request.get("/api/ui/me").add_header("cookie", erin_jar.clone()).await.json(); + assert_eq!(me["invitations"][0]["organization"]["slug"], w.org.slug, "{me}"); + let id = me["invitations"][0]["id"].as_str().unwrap().to_string(); + // Someone else can't accept it. + let other = cookies( + &request + .post("/auth/dev-login") + .json(&serde_json::json!({ "email": format!("x-{tag}@example.com") })) + .await, + ); + assert_eq!( + request.post(&format!("/api/ui/invitations/{id}/accept")).add_header("cookie", other).await.status_code(), + 404 + ); + // Declining withdraws it. + let r = request.post(&format!("/api/ui/invitations/{id}/decline")).add_header("cookie", erin_jar.clone()).await; + assert_eq!(r.status_code(), 200); + let me: serde_json::Value = request.get("/api/ui/me").add_header("cookie", erin_jar.clone()).await.json(); + assert_eq!(me["invitations"], serde_json::json!([])); + assert!(membership(&ctx, w.org.id, &erin).await.is_none()); + + // Invited again and accepted: a read-only member sees names and logins, not email addresses; the admin does. + assert_eq!(invite("read").await.status_code(), 200); + let me: serde_json::Value = request.get("/api/ui/me").add_header("cookie", erin_jar.clone()).await.json(); + let id = me["invitations"][0]["id"].as_str().unwrap().to_string(); + request.post(&format!("/api/ui/invitations/{id}/accept")).add_header("cookie", erin_jar.clone()).await; + let seen: serde_json::Value = + request.get(&format!("/api/ui/orgs/{}", w.org.slug)).add_header("cookie", erin_jar).await.json(); + assert!(seen["members"].as_array().unwrap().iter().all(|m| m["email"].is_null()), "{seen}"); + let admin: serde_json::Value = + request.get(&format!("/api/ui/orgs/{}", w.org.slug)).add_header("cookie", w.admin_jar.clone()).await.json(); + assert!(admin["members"].as_array().unwrap().iter().all(|m| m["email"].is_string()), "{admin}"); + }) + .await; +}