From 484f294a193b804b4ea3f114a9bca3fd05a485c7 Mon Sep 17 00:00:00 2001 From: piquel Date: Sat, 21 Nov 2026 15:35:03 +0100 Subject: [PATCH 1/2] fix(auth): a disabled account keeps its verified addresses, so no new account can register one Disabling an account no longer releases its verified addresses: they stay its own until it is purged, as an account scheduled for deletion's already did. Verifying one on another account is refused as OwnedElsewhere, and enabling the account again can no longer fail on a lost address. Migration 0002 drops the status sync trigger, renames active_verified_email_ownership to verified_email_ownership, and leaves every verified address with one account: its owner keeps it, otherwise the account that verified it last. --- apps/auth-service/src/admin/error.rs | 5 - .../src/admin/service/accounts.rs | 18 +--- apps/auth-service/src/emails/error.rs | 3 +- apps/auth-service/src/emails/mod.rs | 6 +- apps/auth-service/src/emails/tests.rs | 37 ++++++- ...bf7cf80a85206df8ad13a1b738bdd549d951.json} | 4 +- ...91446e07ccbdb52ab1c7138975eb1cc94239.json} | 4 +- ...disabled_accounts_keep_verified_emails.sql | 102 ++++++++++++++++++ crates/database/src/inventory/mod.rs | 6 +- .../database/src/repositories/emails/mod.rs | 20 ++-- .../database/src/repositories/emails/tests.rs | 32 +++--- crates/database/src/repositories/users/mod.rs | 10 +- docs/dev/architecture/database.md | 4 +- docs/dev/architecture/email.md | 16 +-- docs/dev/operations/administration.md | 3 +- docs/user/account/email-addresses.md | 3 +- 16 files changed, 196 insertions(+), 77 deletions(-) rename crates/database/.sqlx/{query-9f233de84352634ef8d6fec15bdb4090adf42c7adedb7fef7e9a12f70d74f98a.json => query-56bc4c4cd9cf2fcfe243c25f1e47bf7cf80a85206df8ad13a1b738bdd549d951.json} (50%) rename crates/database/.sqlx/{query-e134208696acb95ab91d3557f095b8342958001aecb7cdb1824220edc7ed1f35.json => query-8b62bc977f99c53711677348abfc91446e07ccbdb52ab1c7138975eb1cc94239.json} (61%) create mode 100644 crates/database/migrations/0002_disabled_accounts_keep_verified_emails.sql diff --git a/apps/auth-service/src/admin/error.rs b/apps/auth-service/src/admin/error.rs index 83030bf56..37be5b926 100644 --- a/apps/auth-service/src/admin/error.rs +++ b/apps/auth-service/src/admin/error.rs @@ -59,9 +59,6 @@ pub enum AdminError { /// The account is already active. #[error("the account is already active")] AlreadyActive, - /// Reactivation found a verified email of the account owned by another active account. - #[error("another active account has claimed one of this account's verified emails")] - EmailClaimed(#[source] DatabaseError), /// The reason is blank, longer than 500 characters or holds control characters. #[error("give a reason of 1 to 500 characters, without control characters")] InvalidReason, @@ -237,7 +234,6 @@ impl AdminError { Self::AdministratorTarget => "administrator_target", Self::AlreadyDisabled => "already_disabled", Self::AlreadyActive => "already_active", - Self::EmailClaimed(_) => "email_claimed", Self::InvalidReason => "invalid_reason", Self::InvalidInviteExpiry(_) => "invalid_invite_expiry", Self::InvalidInvitationEmail(_) => "invalid_invitation_email", @@ -336,7 +332,6 @@ impl From for ApiError { | AdminError::SigningKey(KeyError::Unknown(_)) => Self::not_found(message), AdminError::AlreadyDisabled | AdminError::AlreadyActive - | AdminError::EmailClaimed(_) | AdminError::RecoveryOfDisabledAccount | AdminError::RecoveryNeedsEmail | AdminError::InvitationNeedsEmail diff --git a/apps/auth-service/src/admin/service/accounts.rs b/apps/auth-service/src/admin/service/accounts.rs index ce9e7e7fa..78ecb7d84 100644 --- a/apps/auth-service/src/admin/service/accounts.rs +++ b/apps/auth-service/src/admin/service/accounts.rs @@ -17,7 +17,7 @@ use sourceorigin_common::{ email::NormalizedEmail, events::{DomainEvent, RevocationReason}, }; -use sourceorigin_repository::{DatabaseError, DatabaseTransaction, StoredUser}; +use sourceorigin_repository::{DatabaseTransaction, StoredUser}; /// Accounts per search page. const USER_PAGE_SIZE: u16 = 50; @@ -189,8 +189,8 @@ impl AdminService { Self::finish(tx, operator, &reason, Some(user_id), vec![]).await } - /// Reactivates a disabled account, for `reason`. Fails if another active - /// account claimed one of its verified emails meanwhile. + /// Reactivates a disabled account, for `reason`. It kept its verified emails + /// while disabled, so nobody can have claimed them meanwhile. pub(crate) async fn enable_user( &self, operator: &Operator, @@ -205,17 +205,7 @@ impl AdminService { } tx.users() .set_status(user_id, AccountStatus::Active) - .await - .map_err(|error| match error { - DatabaseError::Conflict(_) => AdminError::EmailClaimed(error), - DatabaseError::NotFound - | DatabaseError::Refused(_) - | DatabaseError::Timeout(_) - | DatabaseError::Cancelled(_) - | DatabaseError::LockUnavailable(_) - | DatabaseError::InvalidStoredData { .. } - | DatabaseError::Operation(_) => error.into(), - })?; + .await?; let enabled = DomainEvent::AccountEnabled {}; Self::finish(tx, operator, &reason, Some(user_id), vec![enabled]).await } diff --git a/apps/auth-service/src/emails/error.rs b/apps/auth-service/src/emails/error.rs index 52d6a394a..aa86deacc 100644 --- a/apps/auth-service/src/emails/error.rs +++ b/apps/auth-service/src/emails/error.rs @@ -52,7 +52,8 @@ pub(crate) enum EmailError { /// account. #[error("verification token is unknown, expired or used")] InvalidToken, - /// Another active account verified this address first. + /// Another account verified this address first; it keeps it until it is + /// purged, even while disabled. #[error("address is verified by another account")] OwnedElsewhere, /// Persistence failed. diff --git a/apps/auth-service/src/emails/mod.rs b/apps/auth-service/src/emails/mod.rs index 28aca5e66..e79a2ed02 100644 --- a/apps/auth-service/src/emails/mod.rs +++ b/apps/auth-service/src/emails/mod.rs @@ -276,8 +276,8 @@ impl EmailApplication { /// it; otherwise unverified, with its verification email, as when the owner /// adds it, since it may have changed owners since the provider verified it. /// Only an account with no verified address and without it takes one, and - /// never one another account holds verified, even while that one is being - /// deleted: a provider never replaces the owner's own address or takes + /// never one another account holds verified, even while that one is disabled + /// or being deleted: a provider never replaces the owner's own address or takes /// someone else's. An address that would be one /// too many, or whose link cannot be sent now, is skipped, since signing in /// matters more: the owner can add it later. Another account verifying the @@ -545,7 +545,7 @@ impl AccountService { { Ok(primary) => primary, Err(DatabaseError::NotFound) => return Err(EmailError::InvalidToken.into()), - // The ownership trigger: another active account verified it first. + // The ownership trigger: another account, of any status, verified it first. Err(DatabaseError::Conflict(_)) => return Err(EmailError::OwnedElsewhere.into()), Err(error) => return Err(error.into()), }; diff --git a/apps/auth-service/src/emails/tests.rs b/apps/auth-service/src/emails/tests.rs index 87c2ec3ff..66db1e7d8 100644 --- a/apps/auth-service/src/emails/tests.rs +++ b/apps/auth-service/src/emails/tests.rs @@ -12,7 +12,7 @@ use axum::{ response::Response, }; use serde_json::{Value, json}; -use sourceorigin_common::AuthenticationMethod; +use sourceorigin_common::{AccountStatus, AuthenticationMethod}; use sourceorigin_repository::DeliverySummary; use std::net::{IpAddr, Ipv6Addr}; @@ -286,6 +286,41 @@ async fn verification_rejects_an_address_another_account_owns() { assert_eq!(harness.list(&other).await[0]["verified"], false); } +/// A disabled account keeps its verified address: another account verifying it +/// is refused as owned elsewhere, and enabling the account again finds it still +/// verified. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn a_disabled_account_keeps_its_verified_address() { + let harness = Harness::new(true).await; + let owner = harness.account(AuthenticationMethod::Passkey).await; + let other = harness.account(AuthenticationMethod::Passkey).await; + let address = format!("{}@example.com", owner.user_id); + let verified = harness.added(&owner, &address).await; + assert_eq!(harness.verify(verified).await.0, StatusCode::OK); + let set_status = async |status| { + let changed = harness + .database + .users() + .set_status(owner.user_id, status) + .await; + assert!(changed.expect("status")); + }; + + set_status(AccountStatus::Disabled).await; + let claimed = harness.added(&other, &address).await; + let (status, body) = harness.verify(claimed).await; + assert_eq!(status, StatusCode::CONFLICT); + assert_eq!( + body["error"], + "This address is already used by another Origin Account." + ); + assert_eq!(harness.list(&other).await[0]["verified"], false); + + set_status(AccountStatus::Active).await; + assert_eq!(harness.list(&owner).await[0]["verified"], true); +} + /// A verification link works signed out, and a browser signed in to the account /// confirms it as the owner. A browser signed in to another account is refused, /// and the link still works afterwards. diff --git a/crates/database/.sqlx/query-9f233de84352634ef8d6fec15bdb4090adf42c7adedb7fef7e9a12f70d74f98a.json b/crates/database/.sqlx/query-56bc4c4cd9cf2fcfe243c25f1e47bf7cf80a85206df8ad13a1b738bdd549d951.json similarity index 50% rename from crates/database/.sqlx/query-9f233de84352634ef8d6fec15bdb4090adf42c7adedb7fef7e9a12f70d74f98a.json rename to crates/database/.sqlx/query-56bc4c4cd9cf2fcfe243c25f1e47bf7cf80a85206df8ad13a1b738bdd549d951.json index af1141f8f..3accc5931 100644 --- a/crates/database/.sqlx/query-9f233de84352634ef8d6fec15bdb4090adf42c7adedb7fef7e9a12f70d74f98a.json +++ b/crates/database/.sqlx/query-56bc4c4cd9cf2fcfe243c25f1e47bf7cf80a85206df8ad13a1b738bdd549d951.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT EXISTS (\n SELECT 1 FROM active_verified_email_ownership\n WHERE normalized_email = $1 AND user_id <> $2\n ) AS \"owned!\"", + "query": "SELECT EXISTS (\n SELECT 1 FROM verified_email_ownership\n WHERE normalized_email = $1 AND user_id <> $2\n ) AS \"owned!\"", "describe": { "columns": [ { @@ -19,5 +19,5 @@ null ] }, - "hash": "9f233de84352634ef8d6fec15bdb4090adf42c7adedb7fef7e9a12f70d74f98a" + "hash": "56bc4c4cd9cf2fcfe243c25f1e47bf7cf80a85206df8ad13a1b738bdd549d951" } diff --git a/crates/database/.sqlx/query-e134208696acb95ab91d3557f095b8342958001aecb7cdb1824220edc7ed1f35.json b/crates/database/.sqlx/query-8b62bc977f99c53711677348abfc91446e07ccbdb52ab1c7138975eb1cc94239.json similarity index 61% rename from crates/database/.sqlx/query-e134208696acb95ab91d3557f095b8342958001aecb7cdb1824220edc7ed1f35.json rename to crates/database/.sqlx/query-8b62bc977f99c53711677348abfc91446e07ccbdb52ab1c7138975eb1cc94239.json index faa43c262..832d56f8b 100644 --- a/crates/database/.sqlx/query-e134208696acb95ab91d3557f095b8342958001aecb7cdb1824220edc7ed1f35.json +++ b/crates/database/.sqlx/query-8b62bc977f99c53711677348abfc91446e07ccbdb52ab1c7138975eb1cc94239.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT e.id AS \"id: EmailId\", e.user_id AS \"user_id: UserId\", e.normalized_email,\n e.verified_at, e.is_primary FROM active_verified_email_ownership o\n JOIN users u ON u.id = o.user_id\n AND u.status = 'active'\n JOIN user_emails e ON e.user_id = o.user_id\n AND e.normalized_email = o.normalized_email\n AND e.verified_at IS NOT NULL\n WHERE o.normalized_email = $1\n ORDER BY e.is_primary DESC, e.created_at\n LIMIT 1", + "query": "SELECT e.id AS \"id: EmailId\", e.user_id AS \"user_id: UserId\", e.normalized_email,\n e.verified_at, e.is_primary FROM verified_email_ownership o\n JOIN users u ON u.id = o.user_id\n AND u.status = 'active'\n JOIN user_emails e ON e.user_id = o.user_id\n AND e.normalized_email = o.normalized_email\n AND e.verified_at IS NOT NULL\n WHERE o.normalized_email = $1\n ORDER BY e.is_primary DESC, e.created_at\n LIMIT 1", "describe": { "columns": [ { @@ -42,5 +42,5 @@ false ] }, - "hash": "e134208696acb95ab91d3557f095b8342958001aecb7cdb1824220edc7ed1f35" + "hash": "8b62bc977f99c53711677348abfc91446e07ccbdb52ab1c7138975eb1cc94239" } diff --git a/crates/database/migrations/0002_disabled_accounts_keep_verified_emails.sql b/crates/database/migrations/0002_disabled_accounts_keep_verified_emails.sql new file mode 100644 index 000000000..4d4e0a946 --- /dev/null +++ b/crates/database/migrations/0002_disabled_accounts_keep_verified_emails.sql @@ -0,0 +1,102 @@ +-- A verified address belongs to its account until the account is purged, whatever +-- its status. Disabling an account used to release its addresses, so another +-- account could verify one, and enabling it again failed once one had. Now a +-- disabled account keeps them, as an account scheduled for deletion already did, +-- and deleting the account's row at its purge is what releases them. +-- +-- `active_verified_email_ownership` becomes `verified_email_ownership`, one row +-- per verified address naming the account that holds it. The rename breaks the +-- expand-then-contract rule: the previous release's lookups of who holds an +-- address fail until its replacement is healthy. There are no real users yet, +-- so that window costs less than keeping the old name around. + +DROP TRIGGER users_synchronize_email_ownership ON users; +DROP FUNCTION synchronize_user_email_ownership(); +DROP TRIGGER user_emails_claim_active_verified ON user_emails; +DROP FUNCTION claim_active_verified_email(); +DROP TRIGGER user_emails_release_active_verified ON user_emails; +DROP FUNCTION release_active_verified_email(); + +ALTER TABLE active_verified_email_ownership RENAME TO verified_email_ownership; +ALTER INDEX active_verified_email_ownership_pkey RENAME TO verified_email_ownership_pkey; +ALTER INDEX active_verified_email_ownership_user_idx RENAME TO verified_email_ownership_user_idx; +ALTER TABLE verified_email_ownership + RENAME CONSTRAINT active_verified_email_ownership_user_id_fkey TO verified_email_ownership_user_id_fkey; + +-- Claims ownership when an account gains a verified address, and fails as a +-- unique violation if another account holds it. +CREATE FUNCTION claim_verified_email() RETURNS TRIGGER +LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $$ +BEGIN + IF NEW.verified_at IS NOT NULL THEN + INSERT INTO verified_email_ownership(normalized_email, user_id) + VALUES (NEW.normalized_email, NEW.user_id) + ON CONFLICT (normalized_email) DO UPDATE SET user_id = EXCLUDED.user_id + WHERE verified_email_ownership.user_id = EXCLUDED.user_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'verified email already belongs to another account' USING ERRCODE = 'unique_violation'; + END IF; + END IF; + RETURN NEW; +END $$; +CREATE TRIGGER user_emails_claim_verified + BEFORE INSERT OR UPDATE OF normalized_email, verified_at, user_id ON user_emails + FOR EACH ROW EXECUTE FUNCTION claim_verified_email(); + +-- Releases ownership once no verified row of the owner still holds the address. +-- AFTER triggers see the updated table, including an unchanged verified row. +CREATE FUNCTION release_verified_email() RETURNS TRIGGER +LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $$ +BEGIN + IF OLD.verified_at IS NOT NULL AND NOT EXISTS ( + SELECT 1 FROM user_emails + WHERE user_id=OLD.user_id AND normalized_email=OLD.normalized_email + AND verified_at IS NOT NULL + ) THEN + DELETE FROM verified_email_ownership + WHERE normalized_email=OLD.normalized_email AND user_id=OLD.user_id; + END IF; + RETURN OLD; +END $$; +CREATE TRIGGER user_emails_release_verified + AFTER DELETE OR UPDATE OF normalized_email, verified_at, user_id ON user_emails + FOR EACH ROW EXECUTE FUNCTION release_verified_email(); + +-- Disabled accounts own nothing yet, so an address may be verified on several +-- accounts. One keeps it: the account that owns it, otherwise the one that +-- verified it last. The others' rows become unverified and stop being primary; +-- their owners can remove them, or verify them once the address is free. +WITH keepers AS ( + SELECT DISTINCT ON (e.normalized_email) e.normalized_email, e.user_id + FROM user_emails e + LEFT JOIN verified_email_ownership o + ON o.normalized_email = e.normalized_email AND o.user_id = e.user_id + WHERE e.verified_at IS NOT NULL + ORDER BY e.normalized_email, o.user_id IS NOT NULL DESC, e.verified_at DESC, e.id DESC +) +UPDATE user_emails e SET verified_at = NULL, is_primary = FALSE +FROM keepers k +WHERE e.normalized_email = k.normalized_email + AND e.user_id <> k.user_id + AND e.verified_at IS NOT NULL; + +-- An account that lost its primary keeps its other verified addresses, so its +-- earliest verified one becomes primary, as `user_emails_exactly_one_primary` +-- requires at commit. +UPDATE user_emails SET is_primary = TRUE +WHERE id IN ( + SELECT DISTINCT ON (e.user_id) e.id + FROM user_emails e + WHERE e.verified_at IS NOT NULL + AND NOT EXISTS ( + SELECT 1 FROM user_emails p + WHERE p.user_id = e.user_id AND p.is_primary AND p.verified_at IS NOT NULL + ) + ORDER BY e.user_id, e.verified_at, e.id +); + +-- Every remaining verified address now has one account: record the ones disabled +-- accounts verified, which nothing owned. +INSERT INTO verified_email_ownership (normalized_email, user_id) +SELECT DISTINCT normalized_email, user_id FROM user_emails WHERE verified_at IS NOT NULL +ON CONFLICT (normalized_email) DO NOTHING; diff --git a/crates/database/src/inventory/mod.rs b/crates/database/src/inventory/mod.rs index 42954b626..f892c1b19 100644 --- a/crates/database/src/inventory/mod.rs +++ b/crates/database/src/inventory/mod.rs @@ -14,8 +14,6 @@ sourceorigin_common::str_enum! { AccountDeletions = "account_deletions", /// Recoveries support started for accounts. AccountRecoveries = "account_recoveries", - /// Which account holds each verified address. - ActiveVerifiedEmailOwnership = "active_verified_email_ownership", /// Administrator rights. Administrators = "administrators", /// What administrators post on an alert while they handle it. @@ -96,6 +94,8 @@ sourceorigin_common::str_enum! { UserEmails = "user_emails", /// Accounts. Users = "users", + /// Which account holds each verified address. + VerifiedEmailOwnership = "verified_email_ownership", /// Passkey ceremonies in progress. WebauthnCeremonies = "webauthn_ceremonies", } @@ -130,7 +130,7 @@ impl Table { Self::DashboardSessions => Holds::Exported("sessions/*/dashboard"), Self::UserEmails => Holds::Exported("emails"), // A copy of the verified addresses. - Self::ActiveVerifiedEmailOwnership => Holds::Exported("emails/*/verified"), + Self::VerifiedEmailOwnership => Holds::Exported("emails/*/verified"), Self::PasskeyCredentials => Holds::Exported("passkeys"), Self::ExternalLoginIdentities => Holds::Exported("identities"), Self::Sessions => Holds::Exported("sessions"), diff --git a/crates/database/src/repositories/emails/mod.rs b/crates/database/src/repositories/emails/mod.rs index 63c8fd775..169fbd38e 100644 --- a/crates/database/src/repositories/emails/mod.rs +++ b/crates/database/src/repositories/emails/mod.rs @@ -91,8 +91,8 @@ impl EmailRepository<'_> { /// /// # Errors /// - /// Returns [`DatabaseError::Conflict`] if another active account owns the - /// address, or another [`DatabaseError`] if the query fails. + /// Returns [`DatabaseError::Conflict`] if another account owns the address, + /// or another [`DatabaseError`] if the query fails. pub async fn insert_verified( &mut self, input: &InsertVerifiedEmail, @@ -225,8 +225,8 @@ impl EmailRepository<'_> { /// # Errors /// /// Returns [`DatabaseError::NotFound`] if the secret expired or was used - /// since it was found, [`DatabaseError::Conflict`] if another active account - /// owns the address, or another [`DatabaseError`] if a query fails. + /// since it was found, [`DatabaseError::Conflict`] if another account owns + /// the address, or another [`DatabaseError`] if a query fails. pub async fn consume_verification( &mut self, pending: &PendingVerification, @@ -317,10 +317,10 @@ impl EmailRepository<'_> { Ok(()) } - /// Whether an account other than `user_id` holds `normalized` verified: an - /// active one, or one scheduled for deletion, which keeps its addresses so - /// that restoring it finds them. Verifying the address for `user_id` would - /// fail meanwhile. + /// Whether an account other than `user_id` holds `normalized` verified, + /// whatever its status: an account keeps its verified addresses until it is + /// purged, so enabling or restoring it finds them. Verifying the address for + /// `user_id` would fail meanwhile. /// /// # Errors /// @@ -335,7 +335,7 @@ impl EmailRepository<'_> { fetch_one, sqlx::query_scalar!( r#"SELECT EXISTS ( - SELECT 1 FROM active_verified_email_ownership + SELECT 1 FROM verified_email_ownership WHERE normalized_email = $1 AND user_id <> $2 ) AS "owned!""#, normalized, @@ -359,7 +359,7 @@ impl EmailRepository<'_> { fetch_optional, emails!( "SELECT", - "FROM active_verified_email_ownership o + "FROM verified_email_ownership o JOIN users u ON u.id = o.user_id AND u.status = 'active' JOIN user_emails e ON e.user_id = o.user_id diff --git a/crates/database/src/repositories/emails/tests.rs b/crates/database/src/repositories/emails/tests.rs index 366690d99..abba66de3 100644 --- a/crates/database/src/repositories/emails/tests.rs +++ b/crates/database/src/repositories/emails/tests.rs @@ -3,7 +3,7 @@ use super::InsertUnverifiedEmail; use crate::{Database, UserRepository}; use chrono::{Duration, Utc}; use sourceorigin_common::{EmailId, UserId}; -/// Verified email ownership follows active account status and verification changes. +/// Verified email ownership follows verification changes. #[expect( clippy::too_many_lines, reason = "Keep the ownership lifecycle scenario of one address together." @@ -40,7 +40,7 @@ async fn verified_email_updates_preserve_and_release_ownership() { .await .expect("update verification"); let owner: uuid::Uuid = sqlx::query_scalar( - "SELECT user_id FROM active_verified_email_ownership WHERE normalized_email=$1", + "SELECT user_id FROM verified_email_ownership WHERE normalized_email=$1", ) .bind(&address) .fetch_one(&mut *tx) @@ -77,7 +77,7 @@ async fn verified_email_updates_preserve_and_release_ownership() { .await .expect("move address and owner"); let old_exists: bool = sqlx::query_scalar( - "SELECT EXISTS(SELECT 1 FROM active_verified_email_ownership WHERE normalized_email=$1)", + "SELECT EXISTS(SELECT 1 FROM verified_email_ownership WHERE normalized_email=$1)", ) .bind(&address) .fetch_one(&mut *tx) @@ -89,13 +89,12 @@ async fn verified_email_updates_preserve_and_release_ownership() { .execute(&mut *tx) .await .expect("unverify"); - let count: i64 = sqlx::query_scalar( - "SELECT count(*) FROM active_verified_email_ownership WHERE user_id=ANY($1)", - ) - .bind(users.map(UserId::as_uuid).as_slice()) - .fetch_one(&mut *tx) - .await - .expect("ownership count"); + let count: i64 = + sqlx::query_scalar("SELECT count(*) FROM verified_email_ownership WHERE user_id=ANY($1)") + .bind(users.map(UserId::as_uuid).as_slice()) + .fetch_one(&mut *tx) + .await + .expect("ownership count"); assert_eq!(count, 0); sqlx::query("UPDATE user_emails SET verified_at=now(),is_primary=true WHERE id=$1") .bind(email) @@ -107,13 +106,12 @@ async fn verified_email_updates_preserve_and_release_ownership() { .execute(&mut *tx) .await .expect("delete"); - let count: i64 = sqlx::query_scalar( - "SELECT count(*) FROM active_verified_email_ownership WHERE user_id=ANY($1)", - ) - .bind(users.map(UserId::as_uuid).as_slice()) - .fetch_one(&mut *tx) - .await - .expect("ownership count"); + let count: i64 = + sqlx::query_scalar("SELECT count(*) FROM verified_email_ownership WHERE user_id=ANY($1)") + .bind(users.map(UserId::as_uuid).as_slice()) + .fetch_one(&mut *tx) + .await + .expect("ownership count"); assert_eq!(count, 0); sqlx::query("SET CONSTRAINTS ALL IMMEDIATE") .execute(&mut *tx) diff --git a/crates/database/src/repositories/users/mod.rs b/crates/database/src/repositories/users/mod.rs index fbc892f95..5468cbdd3 100644 --- a/crates/database/src/repositories/users/mod.rs +++ b/crates/database/src/repositories/users/mod.rs @@ -297,16 +297,12 @@ impl UserRepository<'_> { Ok(()) } - /// Changes the account's status. Returns `false` if it already had it. - /// - /// Disabling releases the account's verified emails and reactivating reclaims - /// them, through the schema's triggers. + /// Changes the account's status. Returns `false` if it already had it. The + /// account keeps its verified emails whatever its status. /// /// # Errors /// - /// Returns [`DatabaseError::Conflict`] if reactivation finds one of its verified - /// emails owned by another active account, or another [`DatabaseError`] if the - /// query fails. + /// Returns [`DatabaseError`] if the query fails. pub async fn set_status( &mut self, id: UserId, diff --git a/docs/dev/architecture/database.md b/docs/dev/architecture/database.md index a1d9e857b..160112035 100644 --- a/docs/dev/architecture/database.md +++ b/docs/dev/architecture/database.md @@ -133,8 +133,8 @@ Important invariants: and reads their session and confirmation without locking either, so it joins no lock cycle. - An account scheduled for deletion has status `deleting` and an - `account_deletions` row; it keeps its verified emails until it is purged, so - restoring it never collides. Scheduling and purging take + `account_deletions` row; it keeps its verified emails until it is purged, as + a disabled account does, so restoring it never collides. Scheduling and purging take `administrators().lock()` before the account lock, as grants and disabling do, so the last active administrator's account cannot be deleted. Callers end its sessions and delete the clients it manages first. `deletions().purge` then deletes the rows diff --git a/docs/dev/architecture/email.md b/docs/dev/architecture/email.md index 5395fb99c..a12e72f2d 100644 --- a/docs/dev/architecture/email.md +++ b/docs/dev/architecture/email.md @@ -10,7 +10,7 @@ anything under `apps/auth-service/src/emails` or the `email` delivery channel. | --- | --- | | `user_emails` | an account's addresses, each normalized, with when it was verified and whether it is primary | | `email_verification_secrets` | the SHA-256 digest of an unverified address's link token, and when it expires | -| `active_verified_email_ownership` | one row per verified address of an active account, naming that account | +| `verified_email_ownership` | one row per verified address, naming the account that holds it | Addresses are compared as `NormalizedEmail` (`sourceorigin_common::email`), whose rules [email normalization](../security/email-normalization.md) sets out. @@ -20,13 +20,13 @@ The schema holds the invariants itself: - **One primary verified address per account**, by a unique partial index. The OIDC `email` claim reports that address, and an account without one has no `email` claim. -- **A verified address belongs to one active account.** Triggers on `user_emails` - and on account status keep `active_verified_email_ownership` in step, and - verifying an address another active account verified fails as a unique - violation. Disabling an account releases its addresses, and enabling it again - fails if another account claimed one meanwhile. An account scheduled for - deletion keeps its verified addresses, so nobody claims them before it is - restored or purged. +- **A verified address belongs to one account until it is purged.** Triggers + on `user_emails` keep `verified_email_ownership` in step, and verifying an + address another account verified fails as a unique violation, whatever that + account's status. A disabled account, or one scheduled for deletion, keeps its + verified addresses, so nobody can claim one before it is enabled, restored or + purged, and enabling or restoring it never collides. The purge deletes the + account's row, which releases them. - **An unverified address waits for its link.** Verifying it deletes its secret, under the account's lock. Once the link expires, the cleanup job deletes the address with its secret. diff --git a/docs/dev/operations/administration.md b/docs/dev/operations/administration.md index 106dd0902..881caa951 100644 --- a/docs/dev/operations/administration.md +++ b/docs/dev/operations/administration.md @@ -161,7 +161,8 @@ auth-service user enable alice --reason "Appealed by email" ``` Disabling ends the account's sessions and refresh tokens, and it can't sign in -until you enable it. On the dashboard, open the account, select **Disable** or +until you enable it. It keeps its verified email addresses, so no other account +can verify one of them meanwhile, and enabling it again always gets them back. On the dashboard, open the account, select **Disable** or **Enable**, and give a reason. The owner sees it in their security history, so write what was asked, never the evidence. Nobody can disable the last active administrator's account. diff --git a/docs/user/account/email-addresses.md b/docs/user/account/email-addresses.md index 965f35644..852d84dec 100644 --- a/docs/user/account/email-addresses.md +++ b/docs/user/account/email-addresses.md @@ -80,7 +80,8 @@ Without a confirmed address, apps receive none. ## Troubleshooting - **"This address is already used by another Origin Account."** Another - account confirmed it first. An address belongs to one account at a time. + account confirmed it first. An address belongs to one account at a time, + even while that account is disabled, until the account is deleted. - **"Too many verification emails were sent recently. Please try again later."** SourceOrigin limits how many confirmation emails it sends in an hour. Wait, then select **Resend link**. From 2257407f0c7e1c3c2d2d67145b78a3624131cc6a Mon Sep 17 00:00:00 2001 From: piquel Date: Sat, 21 Nov 2026 15:59:12 +0100 Subject: [PATCH 2/2] fix(auth): an invitation is refused for a disabled account's verified address An operator could create or resend an invitation to an address a disabled account holds verified, and redeeming it created the account without the address. Invitations now check ownership across every account, whatever its status, through EmailRepository::is_owned. The docs on verified ownership say it covers every account until it is purged or the address is removed. --- apps/auth-service/src/admin/error.rs | 8 ++-- apps/auth-service/src/admin/service/access.rs | 21 +++++---- .../src/admin/tests/invitations.rs | 47 ++++++++++++++++++- apps/auth-service/src/emails/mod.rs | 4 +- ...8b2b67b7937a444e62152464fb012d0d7bd1.json} | 4 +- .../database/src/repositories/emails/mod.rs | 16 +++---- docs/dev/architecture/database.md | 5 +- docs/dev/architecture/surfaces.md | 2 +- docs/dev/operations/administration.md | 6 +-- docs/dev/security/threat-model.md | 2 +- 10 files changed, 83 insertions(+), 32 deletions(-) rename crates/database/.sqlx/{query-56bc4c4cd9cf2fcfe243c25f1e47bf7cf80a85206df8ad13a1b738bdd549d951.json => query-1c76ff9d673457295b1464f192818b2b67b7937a444e62152464fb012d0d7bd1.json} (72%) diff --git a/apps/auth-service/src/admin/error.rs b/apps/auth-service/src/admin/error.rs index 37be5b926..e717e2a28 100644 --- a/apps/auth-service/src/admin/error.rs +++ b/apps/auth-service/src/admin/error.rs @@ -78,9 +78,11 @@ pub enum AdminError { /// so its link would never arrive. #[error("email can't be sent to the address to invite; check it, or use another one")] InvitationUnsendable(#[source] lettre::address::AddressError), - /// An active account already holds the address verified: its owner signs in - /// rather than signing up. - #[error("an account already holds this address verified; its owner can sign in")] + /// An account already holds the address verified, whatever its status: its + /// owner signs in rather than signing up, once enabled if it is disabled. + #[error( + "an account already holds this address verified, even if it is disabled; its owner signs in to it instead" + )] InvitationAddressTaken, /// Only an invitation mailed to an address can be sent again. #[error("this invitation was not mailed, so it has no address to send it to again")] diff --git a/apps/auth-service/src/admin/service/access.rs b/apps/auth-service/src/admin/service/access.rs index e6b32bcfb..e272e5ba1 100644 --- a/apps/auth-service/src/admin/service/access.rs +++ b/apps/auth-service/src/admin/service/access.rs @@ -32,9 +32,9 @@ impl AdminService { /// tracked signup link. With an `email`, its link is mailed there, and the /// account created with it starts with that address, verified; it is refused /// before anything is created while email is disabled, when the sender can't - /// send to the address, or when an active account already holds it verified. - /// Without one, its link is returned for the operator to pass on: only its - /// token's digest is stored, so it is never shown again. + /// send to the address, or when an account already holds it verified, even a + /// disabled one. Without one, its link is returned for the operator to pass + /// on: only its token's digest is stored, so it is never shown again. /// /// # Errors /// Fails when the operator may not make changes, the invitation cannot be @@ -88,7 +88,8 @@ impl AdminService { } /// Mails an open invitation's link again, to the address it was mailed to, - /// for `reason`, unless an active account holds that address verified since. + /// for `reason`, unless an account holds that address verified since, even a + /// disabled one. /// The link and its expiry stay the same: to give more time, revoke it and /// invite again. pub(crate) async fn resend_invitation( @@ -113,16 +114,18 @@ impl AdminService { Self::finish(tx, operator, &reason, None, vec![mailed]).await } - /// Refuses to mail an invitation to `email` while an active account holds it - /// verified: its owner signs in rather than signing up. + /// Refuses to mail an invitation to `email` while any account holds it + /// verified, whatever its status: its owner signs in rather than signing up, + /// and a disabled account keeps its addresses until it is purged, so the + /// account the invitation creates could never have it. async fn untaken( tx: &mut DatabaseTransaction<'_>, email: &NormalizedEmail, ) -> Result<(), AdminError> { - match tx.emails().find_active_verified(email.as_str()).await? { - Some(_) => Err(AdminError::InvitationAddressTaken), - None => Ok(()), + if tx.emails().is_owned(email.as_str(), None).await? { + return Err(AdminError::InvitationAddressTaken); } + Ok(()) } /// The event mailing invitation `invitation_id` to `email`, which queues its diff --git a/apps/auth-service/src/admin/tests/invitations.rs b/apps/auth-service/src/admin/tests/invitations.rs index 996d844ae..089490fa3 100644 --- a/apps/auth-service/src/admin/tests/invitations.rs +++ b/apps/auth-service/src/admin/tests/invitations.rs @@ -1,7 +1,7 @@ //! Creating, mailing and revoking invitations. use super::*; -use crate::tests::invitation_links; +use crate::tests::{invitation_links, verified_address}; use sourceorigin_common::{admin::InvitationSent, email::NormalizedEmail}; use sourceorigin_repository::{Channel, Invitation, InvitationKey}; @@ -108,6 +108,51 @@ async fn mailed_invitations_need_email_and_queue_their_link() { ); } +/// An address a disabled account holds verified can't be invited, and an +/// invitation mailed before the account verified it can't be resent: the account +/// keeps it until it is purged, so the one the invitation creates never could. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn a_disabled_accounts_address_cannot_be_invited() { + let harness = Harness::new().await; + let service = harness.service(); + let links = invitation_links(); + // Unique, since other scenarios share the database. + let jane = format!("jane-{}@example.com", TokenId::new()); + let address = || Some(NormalizedEmail::parse(&jane).expect("address")); + let invite = async || { + service + .create_invitation( + &cli(), + &links, + InviteExpiry::default(), + address(), + reason("Jane"), + ) + .await + }; + let mailed = invite().await.expect("mailed"); + let holder = harness.account().await; + verified_address(&harness.database, holder.user_id, &jane, true).await; + service + .disable_user(&cli(), holder.user_id, reason("Compromised")) + .await + .expect("disable"); + + let refused = invite().await; + assert!( + matches!(refused, Err(AdminError::InvitationAddressTaken)), + "{refused:?}" + ); + let resent = service + .resend_invitation(&cli(), mailed.id, reason("Jane lost it")) + .await; + assert!( + matches!(resent, Err(AdminError::InvitationAddressTaken)), + "{resent:?}" + ); +} + /// An invitation link works until an administrator revokes it, which also ends /// its expiry, for the previous release; revoking it again finds nothing. #[tokio::test] diff --git a/apps/auth-service/src/emails/mod.rs b/apps/auth-service/src/emails/mod.rs index e79a2ed02..b1ce28bf7 100644 --- a/apps/auth-service/src/emails/mod.rs +++ b/apps/auth-service/src/emails/mod.rs @@ -301,7 +301,7 @@ impl EmailApplication { .any(|email| email.verified_at.is_some() || email.normalized_email == address.as_str()) || tx .emails() - .is_owned_elsewhere(address.as_str(), user_id) + .is_owned(address.as_str(), Some(user_id)) .await? { return Ok(()); @@ -351,7 +351,7 @@ impl EmailApplication { ) -> Result<(), EmailError> { if tx .emails() - .is_owned_elsewhere(address.as_str(), user_id) + .is_owned(address.as_str(), Some(user_id)) .await? { tracing::info!("invited address held by another account; not added"); diff --git a/crates/database/.sqlx/query-56bc4c4cd9cf2fcfe243c25f1e47bf7cf80a85206df8ad13a1b738bdd549d951.json b/crates/database/.sqlx/query-1c76ff9d673457295b1464f192818b2b67b7937a444e62152464fb012d0d7bd1.json similarity index 72% rename from crates/database/.sqlx/query-56bc4c4cd9cf2fcfe243c25f1e47bf7cf80a85206df8ad13a1b738bdd549d951.json rename to crates/database/.sqlx/query-1c76ff9d673457295b1464f192818b2b67b7937a444e62152464fb012d0d7bd1.json index 3accc5931..c3d07575b 100644 --- a/crates/database/.sqlx/query-56bc4c4cd9cf2fcfe243c25f1e47bf7cf80a85206df8ad13a1b738bdd549d951.json +++ b/crates/database/.sqlx/query-1c76ff9d673457295b1464f192818b2b67b7937a444e62152464fb012d0d7bd1.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT EXISTS (\n SELECT 1 FROM verified_email_ownership\n WHERE normalized_email = $1 AND user_id <> $2\n ) AS \"owned!\"", + "query": "SELECT EXISTS (\n SELECT 1 FROM verified_email_ownership\n WHERE normalized_email = $1 AND user_id IS DISTINCT FROM $2\n ) AS \"owned!\"", "describe": { "columns": [ { @@ -19,5 +19,5 @@ null ] }, - "hash": "56bc4c4cd9cf2fcfe243c25f1e47bf7cf80a85206df8ad13a1b738bdd549d951" + "hash": "1c76ff9d673457295b1464f192818b2b67b7937a444e62152464fb012d0d7bd1" } diff --git a/crates/database/src/repositories/emails/mod.rs b/crates/database/src/repositories/emails/mod.rs index 169fbd38e..55f1e21c5 100644 --- a/crates/database/src/repositories/emails/mod.rs +++ b/crates/database/src/repositories/emails/mod.rs @@ -317,18 +317,18 @@ impl EmailRepository<'_> { Ok(()) } - /// Whether an account other than `user_id` holds `normalized` verified, - /// whatever its status: an account keeps its verified addresses until it is - /// purged, so enabling or restoring it finds them. Verifying the address for - /// `user_id` would fail meanwhile. + /// Whether an account holds `normalized` verified, other than `except` when + /// given, whatever its status: an account keeps its verified addresses until + /// it is purged, so enabling or restoring it finds them. Verifying the address + /// for any other account would fail meanwhile. /// /// # Errors /// /// Returns [`DatabaseError`] if the query fails. - pub async fn is_owned_elsewhere( + pub async fn is_owned( &mut self, normalized: &str, - user_id: UserId, + except: Option, ) -> Result { run!( self, @@ -336,10 +336,10 @@ impl EmailRepository<'_> { sqlx::query_scalar!( r#"SELECT EXISTS ( SELECT 1 FROM verified_email_ownership - WHERE normalized_email = $1 AND user_id <> $2 + WHERE normalized_email = $1 AND user_id IS DISTINCT FROM $2 ) AS "owned!""#, normalized, - user_id.as_uuid(), + except.map(UserId::as_uuid), ) ) } diff --git a/docs/dev/architecture/database.md b/docs/dev/architecture/database.md index 160112035..7c46038b7 100644 --- a/docs/dev/architecture/database.md +++ b/docs/dev/architecture/database.md @@ -163,13 +163,14 @@ Important invariants: cascades with its account, so a purge by any release removes it. - Active provider subjects and active provider-per-account links are unique. Unlink marks the identity revoked and releases both constraints. -- Verified email ownership is unique across active accounts. Email is optional; +- Verified email ownership is unique across every account, whatever its status, + until the account is purged or the address removed. Email is optional; explicit provider linking never transfers ownership of another account's email. An unverified address keeps the digest of its verification token in `email_verification_secrets` until it is verified, which deletes the row under the account's lock, or until the token expires, when cleanup deletes the address with it. Verifying runs the ownership trigger, so an address another - active account verified fails as a conflict. + account verified fails as a conflict, even while that account is disabled. - A session's `acr`, `amr` and `auth_time` are derived from its methods, `authenticated_at` and `passkey_confirmed_at` (`SessionAuthentication`). Codes copy them when issued, and refresh families copy them from the code, so a grant diff --git a/docs/dev/architecture/surfaces.md b/docs/dev/architecture/surfaces.md index 15741662c..8a27b3623 100644 --- a/docs/dev/architecture/surfaces.md +++ b/docs/dev/architecture/surfaces.md @@ -215,7 +215,7 @@ an address binds the account created with it to that address, which starts verified and primary, since opening the mailed link proves what a verification email would. `AdminService::create_invitation` holds the rule for both surfaces: it refuses a mailed invitation before anything changes while email is disabled, -or when an active account holds the address verified. Its link's token is +or when any account holds the address verified, even a disabled one. Its link's token is derived from its ID, so the email sender, and **Resend**, rebuild the link and nobody sees it; one without an address is shown once instead (see [invite someone](../operations/administration.md#invite-someone) and diff --git a/docs/dev/operations/administration.md b/docs/dev/operations/administration.md index 881caa951..c74174abd 100644 --- a/docs/dev/operations/administration.md +++ b/docs/dev/operations/administration.md @@ -118,13 +118,13 @@ Its link stops working at once. - Mailing an invitation needs email enabled (`AUTH_SMTP_URL`). Without it, the dashboard's form asks for no **Email address**, and the terminal refuses `--email` before creating anything. A link to pass on still works. -- An address an account already holds confirmed can't be invited: its owner - signs in instead. +- An address an account already holds confirmed can't be invited, even when + that account is disabled: its owner signs in instead, once you enable it. - If another account confirms the address before the person signs up, the new account starts without it. - Only a mailed invitation can be sent again, and only while email is enabled: the dashboard offers **Resend** only then. It can't go to an address an - account has confirmed since. + account has confirmed since, even a disabled account. - Where signup is open, a signup that starts at GitHub or Google doesn't carry the invitation: the account is created without it, and without its address. diff --git a/docs/dev/security/threat-model.md b/docs/dev/security/threat-model.md index 8777156f7..cf82d243b 100644 --- a/docs/dev/security/threat-model.md +++ b/docs/dev/security/threat-model.md @@ -43,7 +43,7 @@ own. It builds on the [security boundaries](boundaries.md); the | Brute force and floods from one source | Per-IP budgets per category, in PostgreSQL; never per account, so naming an account cannot lock its owner out ([handles](handles.md#threat-model)). | | Learning who has an account | Accepted: handles are public, and handle sign-in says whether one has an active account ([handles](handles.md)). | | Look-alike handles | Signup and renames refuse a handle that reads like a reserved or held one ([handles](handles.md)). | -| Claiming another person's email | Email is a verified contact, never an identifier, and a verified address belongs to one active account at most ([email normalization](email-normalization.md), [database](../architecture/database.md)). | +| Claiming another person's email | Email is a verified contact, never an identifier, and a verified address belongs to one account at most, whatever its status, until the account is purged or the address removed ([email normalization](email-normalization.md), [database](../architecture/database.md)). | ### Against an account