Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 5 additions & 8 deletions apps/auth-service/src/admin/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -81,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")]
Expand Down Expand Up @@ -237,7 +236,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",
Expand Down Expand Up @@ -336,7 +334,6 @@ impl From<AdminError> for ApiError {
| AdminError::SigningKey(KeyError::Unknown(_)) => Self::not_found(message),
AdminError::AlreadyDisabled
| AdminError::AlreadyActive
| AdminError::EmailClaimed(_)
| AdminError::RecoveryOfDisabledAccount
| AdminError::RecoveryNeedsEmail
| AdminError::InvitationNeedsEmail
Expand Down
21 changes: 12 additions & 9 deletions apps/auth-service/src/admin/service/access.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand All @@ -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
Expand Down
18 changes: 4 additions & 14 deletions apps/auth-service/src/admin/service/accounts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand All @@ -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
}
Expand Down
47 changes: 46 additions & 1 deletion apps/auth-service/src/admin/tests/invitations.rs
Original file line number Diff line number Diff line change
@@ -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};

Expand Down Expand Up @@ -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]
Expand Down
3 changes: 2 additions & 1 deletion apps/auth-service/src/emails/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
10 changes: 5 additions & 5 deletions apps/auth-service/src/emails/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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(());
Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -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()),
};
Expand Down
37 changes: 36 additions & 1 deletion apps/auth-service/src/emails/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand Down Expand Up @@ -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.
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading