Skip to content

Commit 6ff93af

Browse files
committed
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.
1 parent 079d475 commit 6ff93af

10 files changed

Lines changed: 83 additions & 32 deletions

File tree

‎apps/auth-service/src/admin/error.rs‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -78,9 +78,11 @@ pub enum AdminError {
7878
/// so its link would never arrive.
7979
#[error("email can't be sent to the address to invite; check it, or use another one")]
8080
InvitationUnsendable(#[source] lettre::address::AddressError),
81-
/// An active account already holds the address verified: its owner signs in
82-
/// rather than signing up.
83-
#[error("an account already holds this address verified; its owner can sign in")]
81+
/// An account already holds the address verified, whatever its status: its
82+
/// owner signs in rather than signing up, once enabled if it is disabled.
83+
#[error(
84+
"an account already holds this address verified, even if it is disabled; its owner signs in to it instead"
85+
)]
8486
InvitationAddressTaken,
8587
/// Only an invitation mailed to an address can be sent again.
8688
#[error("this invitation was not mailed, so it has no address to send it to again")]

‎apps/auth-service/src/admin/service/access.rs‎

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,9 @@ impl AdminService {
3232
/// tracked signup link. With an `email`, its link is mailed there, and the
3333
/// account created with it starts with that address, verified; it is refused
3434
/// before anything is created while email is disabled, when the sender can't
35-
/// send to the address, or when an active account already holds it verified.
36-
/// Without one, its link is returned for the operator to pass on: only its
37-
/// token's digest is stored, so it is never shown again.
35+
/// send to the address, or when an account already holds it verified, even a
36+
/// disabled one. Without one, its link is returned for the operator to pass
37+
/// on: only its token's digest is stored, so it is never shown again.
3838
///
3939
/// # Errors
4040
/// Fails when the operator may not make changes, the invitation cannot be
@@ -88,7 +88,8 @@ impl AdminService {
8888
}
8989

9090
/// Mails an open invitation's link again, to the address it was mailed to,
91-
/// for `reason`, unless an active account holds that address verified since.
91+
/// for `reason`, unless an account holds that address verified since, even a
92+
/// disabled one.
9293
/// The link and its expiry stay the same: to give more time, revoke it and
9394
/// invite again.
9495
pub(crate) async fn resend_invitation(
@@ -113,16 +114,18 @@ impl AdminService {
113114
Self::finish(tx, operator, &reason, None, vec![mailed]).await
114115
}
115116

116-
/// Refuses to mail an invitation to `email` while an active account holds it
117-
/// verified: its owner signs in rather than signing up.
117+
/// Refuses to mail an invitation to `email` while any account holds it
118+
/// verified, whatever its status: its owner signs in rather than signing up,
119+
/// and a disabled account keeps its addresses until it is purged, so the
120+
/// account the invitation creates could never have it.
118121
async fn untaken(
119122
tx: &mut DatabaseTransaction<'_>,
120123
email: &NormalizedEmail,
121124
) -> Result<(), AdminError> {
122-
match tx.emails().find_active_verified(email.as_str()).await? {
123-
Some(_) => Err(AdminError::InvitationAddressTaken),
124-
None => Ok(()),
125+
if tx.emails().is_owned(email.as_str(), None).await? {
126+
return Err(AdminError::InvitationAddressTaken);
125127
}
128+
Ok(())
126129
}
127130

128131
/// The event mailing invitation `invitation_id` to `email`, which queues its

‎apps/auth-service/src/admin/tests/invitations.rs‎

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
//! Creating, mailing and revoking invitations.
22
33
use super::*;
4-
use crate::tests::invitation_links;
4+
use crate::tests::{invitation_links, verified_address};
55
use sourceorigin_common::{admin::InvitationSent, email::NormalizedEmail};
66
use sourceorigin_repository::{Channel, Invitation, InvitationKey};
77

@@ -108,6 +108,51 @@ async fn mailed_invitations_need_email_and_queue_their_link() {
108108
);
109109
}
110110

111+
/// An address a disabled account holds verified can't be invited, and an
112+
/// invitation mailed before the account verified it can't be resent: the account
113+
/// keeps it until it is purged, so the one the invitation creates never could.
114+
#[tokio::test]
115+
#[ignore = "requires TEST_DATABASE_URL"]
116+
async fn a_disabled_accounts_address_cannot_be_invited() {
117+
let harness = Harness::new().await;
118+
let service = harness.service();
119+
let links = invitation_links();
120+
// Unique, since other scenarios share the database.
121+
let jane = format!("jane-{}@example.com", TokenId::new());
122+
let address = || Some(NormalizedEmail::parse(&jane).expect("address"));
123+
let invite = async || {
124+
service
125+
.create_invitation(
126+
&cli(),
127+
&links,
128+
InviteExpiry::default(),
129+
address(),
130+
reason("Jane"),
131+
)
132+
.await
133+
};
134+
let mailed = invite().await.expect("mailed");
135+
let holder = harness.account().await;
136+
verified_address(&harness.database, holder.user_id, &jane, true).await;
137+
service
138+
.disable_user(&cli(), holder.user_id, reason("Compromised"))
139+
.await
140+
.expect("disable");
141+
142+
let refused = invite().await;
143+
assert!(
144+
matches!(refused, Err(AdminError::InvitationAddressTaken)),
145+
"{refused:?}"
146+
);
147+
let resent = service
148+
.resend_invitation(&cli(), mailed.id, reason("Jane lost it"))
149+
.await;
150+
assert!(
151+
matches!(resent, Err(AdminError::InvitationAddressTaken)),
152+
"{resent:?}"
153+
);
154+
}
155+
111156
/// An invitation link works until an administrator revokes it, which also ends
112157
/// its expiry, for the previous release; revoking it again finds nothing.
113158
#[tokio::test]

‎apps/auth-service/src/emails/mod.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -301,7 +301,7 @@ impl EmailApplication {
301301
.any(|email| email.verified_at.is_some() || email.normalized_email == address.as_str())
302302
|| tx
303303
.emails()
304-
.is_owned_elsewhere(address.as_str(), user_id)
304+
.is_owned(address.as_str(), Some(user_id))
305305
.await?
306306
{
307307
return Ok(());
@@ -351,7 +351,7 @@ impl EmailApplication {
351351
) -> Result<(), EmailError> {
352352
if tx
353353
.emails()
354-
.is_owned_elsewhere(address.as_str(), user_id)
354+
.is_owned(address.as_str(), Some(user_id))
355355
.await?
356356
{
357357
tracing::info!("invited address held by another account; not added");

crates/database/.sqlx/query-56bc4c4cd9cf2fcfe243c25f1e47bf7cf80a85206df8ad13a1b738bdd549d951.json renamed to crates/database/.sqlx/query-1c76ff9d673457295b1464f192818b2b67b7937a444e62152464fb012d0d7bd1.json

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎crates/database/src/repositories/emails/mod.rs‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -313,29 +313,29 @@ impl EmailRepository<'_> {
313313
Ok(())
314314
}
315315

316-
/// Whether an account other than `user_id` holds `normalized` verified,
317-
/// whatever its status: an account keeps its verified addresses until it is
318-
/// purged, so enabling or restoring it finds them. Verifying the address for
319-
/// `user_id` would fail meanwhile.
316+
/// Whether an account holds `normalized` verified, other than `except` when
317+
/// given, whatever its status: an account keeps its verified addresses until
318+
/// it is purged, so enabling or restoring it finds them. Verifying the address
319+
/// for any other account would fail meanwhile.
320320
///
321321
/// # Errors
322322
///
323323
/// Returns [`DatabaseError`] if the query fails.
324-
pub async fn is_owned_elsewhere(
324+
pub async fn is_owned(
325325
&mut self,
326326
normalized: &str,
327-
user_id: UserId,
327+
except: Option<UserId>,
328328
) -> Result<bool, DatabaseError> {
329329
run!(
330330
self,
331331
fetch_one,
332332
sqlx::query_scalar!(
333333
r#"SELECT EXISTS (
334334
SELECT 1 FROM verified_email_ownership
335-
WHERE normalized_email = $1 AND user_id <> $2
335+
WHERE normalized_email = $1 AND user_id IS DISTINCT FROM $2
336336
) AS "owned!""#,
337337
normalized,
338-
user_id.as_uuid(),
338+
except.map(UserId::as_uuid),
339339
)
340340
)
341341
}

‎docs/dev/architecture/database.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -163,13 +163,14 @@ Important invariants:
163163
cascades with its account, so a purge by any release removes it.
164164
- Active provider subjects and active provider-per-account links are unique.
165165
Unlink marks the identity revoked and releases both constraints.
166-
- Verified email ownership is unique across active accounts. Email is optional;
166+
- Verified email ownership is unique across every account, whatever its status,
167+
until the account is purged or the address removed. Email is optional;
167168
explicit provider linking never transfers ownership of another account's email.
168169
An unverified address keeps the digest of its verification token in
169170
`email_verification_secrets` until it is verified, which deletes the row under
170171
the account's lock, or until the token expires, when cleanup deletes the
171172
address with it. Verifying runs the ownership trigger, so an address another
172-
active account verified fails as a conflict.
173+
account verified fails as a conflict, even while that account is disabled.
173174
- A session's `acr`, `amr` and `auth_time` are derived from its methods,
174175
`authenticated_at` and `passkey_confirmed_at` (`SessionAuthentication`). Codes
175176
copy them when issued, and refresh families copy them from the code, so a grant

‎docs/dev/architecture/surfaces.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,7 @@ an address binds the account created with it to that address, which starts
215215
verified and primary, since opening the mailed link proves what a verification
216216
email would. `AdminService::create_invitation` holds the rule for both surfaces:
217217
it refuses a mailed invitation before anything changes while email is disabled,
218-
or when an active account holds the address verified. Its link's token is
218+
or when any account holds the address verified, even a disabled one. Its link's token is
219219
derived from its ID, so the email sender, and **Resend**, rebuild the link and
220220
nobody sees it; one without an address is shown once instead (see
221221
[invite someone](../operations/administration.md#invite-someone) and

‎docs/dev/operations/administration.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -118,13 +118,13 @@ Its link stops working at once.
118118
- Mailing an invitation needs email enabled (`AUTH_SMTP_URL`). Without it, the
119119
dashboard's form asks for no **Email address**, and the terminal refuses
120120
`--email` before creating anything. A link to pass on still works.
121-
- An address an account already holds confirmed can't be invited: its owner
122-
signs in instead.
121+
- An address an account already holds confirmed can't be invited, even when
122+
that account is disabled: its owner signs in instead, once you enable it.
123123
- If another account confirms the address before the person signs up, the new
124124
account starts without it.
125125
- Only a mailed invitation can be sent again, and only while email is enabled:
126126
the dashboard offers **Resend** only then. It can't go to an address an
127-
account has confirmed since.
127+
account has confirmed since, even a disabled account.
128128
- Where signup is open, a signup that starts at GitHub or Google doesn't carry
129129
the invitation: the account is created without it, and without its address.
130130

‎docs/dev/security/threat-model.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ own. It builds on the [security boundaries](boundaries.md); the
4343
| 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)). |
4444
| Learning who has an account | Accepted: handles are public, and handle sign-in says whether one has an active account ([handles](handles.md)). |
4545
| Look-alike handles | Signup and renames refuse a handle that reads like a reserved or held one ([handles](handles.md)). |
46-
| 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)). |
46+
| 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)). |
4747

4848
### Against an account
4949

0 commit comments

Comments
 (0)