Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Address review of the account change endpoints; refuse email-like usernames

Clauded5303965ef90
diff --git a/mwmbl/evaluation/api.py b/mwmbl/evaluation/api.py
index 0e1837a..b81ab0e 100644
--- a/mwmbl/evaluation/api.py
+++ b/mwmbl/evaluation/api.py
@@ -15,8 +15,9 @@ router = Router(tags=["Evaluation"])
def check_email_verified(request):
"""Check if user's email is verified."""
- from_email_address = request.user.emailaddress_set.first()
- if not from_email_address or not from_email_address.verified:
+ # Not the first address: while an email change awaits confirmation, the user also has
+ # the new, unverified one.
+ if not request.user.emailaddress_set.filter(verified=True).exists():
raise InvalidRequest("Email address is not verified", status=403) # 403 Forbidden
diff --git a/mwmbl/platform/api.py b/mwmbl/platform/api.py
index 0b5b885..c4ab930 100644
--- a/mwmbl/platform/api.py
+++ b/mwmbl/platform/api.py
@@ -108,6 +108,13 @@ logger = logging.getLogger(__name__)
router = Router(tags=["Platform"])
+def _refuse_email_like_username(username: str) -> None:
+ # Usernames are public - on leaderboards and in upload paths - so an email address there
+ # would publish it.
+ if "@" in username:
+ raise InvalidRequest("Usernames cannot contain @, so that they can't be email addresses.")
+
+
def check_email_verified(request):
# Not the first address: while an email change awaits confirmation, the user also has
# the new, unverified one.
@@ -128,11 +135,17 @@ def check_email_verified(request):
),
)
def register(request, registration: Registration):
- if MwmblUser.objects.filter(email=registration.email).exists():
+ # Pending email changes count too: once confirmed, they become their user's email.
+ email_taken = (
+ MwmblUser.objects.filter(email__iexact=registration.email).exists()
+ or EmailAddress.objects.filter(email__iexact=registration.email).exists()
+ )
+ if email_taken:
raise InvalidRequest("Email already registered")
username = registration.username or generate_username()
if registration.username:
+ _refuse_email_like_username(registration.username)
username_taken = MwmblUser.objects.filter(username=registration.username).exists()
# Reserved even before migration 0049 makes the user, so nobody can take it first and
# fail it - and in any case, as allauth's blacklist is, so nobody can pass for it.
@@ -177,8 +190,9 @@ def confirm_email(request, confirm: ConfirmEmail):
if confirmation.email_address.email != confirm.email:
raise InvalidRequest("Invalid email or key")
- adapter = get_adapter()
- adapter.confirm_email(request, confirmation.email_address)
+ # allauth refuses when another account has already verified the address.
+ if not get_adapter().confirm_email(request, confirmation.email_address):
+ raise InvalidRequest("Email already registered")
return {
"status": "ok",
@@ -1229,7 +1243,7 @@ def _pending_email_addresses(user: MwmblUser):
summary="Change username",
description=(
"Change the authenticated user's username. It must be unique, ignoring case, and may "
- "contain only letters, digits and `@.+-_`. Returns the new username."
+ "contain only letters, digits and `.+-_`. Returns the new username."
),
tags=["Users"],
)
@@ -1238,13 +1252,17 @@ def change_username(request, body: ChangeUsernameRequest):
new_username = body.username.strip()
if new_username == user.username:
raise InvalidRequest("That is already your username.")
+ _refuse_email_like_username(new_username)
- # A change of case alone would otherwise collide with the user's own name.
+ # A change of case alone would otherwise collide with the user's own name, so check the
+ # database for other users here instead.
case_change_only = new_username.lower() == user.username.lower()
try:
get_adapter().clean_username(new_username, shallow=case_change_only)
except ValidationError as error:
raise InvalidRequest(error.messages[0])
+ if MwmblUser.objects.filter(username__iexact=new_username).exclude(id=user.id).exists():
+ raise InvalidRequest("Username already exists")
user.username = new_username
user.save(update_fields=["username"])
@@ -1286,6 +1304,8 @@ def change_email(request, body: ChangeEmailRequest):
raise InvalidRequest("Email already registered")
with transaction.atomic():
+ # Serialises concurrent changes by one user, which would otherwise each leave a pending address.
+ MwmblUser.objects.select_for_update().get(id=user.id)
_pending_email_addresses(user).delete()
EmailAddress.objects.add_email(request, user, new_email, confirm=True)
diff --git a/mwmbl/platform/schemas.py b/mwmbl/platform/schemas.py
index 3005d56..371f422 100644
--- a/mwmbl/platform/schemas.py
+++ b/mwmbl/platform/schemas.py
@@ -136,7 +136,7 @@ class ForgotPasswordRequest(Schema):
class ChangeUsernameRequest(Schema):
- username: str = Field(description="The new username. Must be unique, ignoring case.")
+ username: str = Field(description="The new username. Must be unique, ignoring case, and may not contain `@`.")
class ChangeEmailRequest(Schema):
@@ -269,7 +269,8 @@ class Registration(Schema):
default=None,
description=(
"Optional username. If omitted, one is generated automatically in the form "
- "`adjective_noun_NNN` (e.g. `swift_falcon_379`). Must be unique if provided."
+ "`adjective_noun_NNN` (e.g. `swift_falcon_379`). Must be unique if provided, and may not "
+ "contain `@`, since usernames are public."
),
)
agreements: list[AgreementType] = Field(
diff --git a/test/test_platform_accounts_api.py b/test/test_platform_accounts_api.py
index dde2498..eb514e8 100644
--- a/test/test_platform_accounts_api.py
+++ b/test/test_platform_accounts_api.py
@@ -63,6 +63,13 @@ def test_registering_an_existing_username_is_rejected(client, owner):
assert "Username already exists" in response.json()["message"]
+def test_registering_an_email_as_the_username_is_rejected(client, db):
+ response = _register(client, username="[email protected]")
+
+ assert response.status_code == 400
+ assert not User.objects.filter(username="[email protected]").exists()
+
+
def test_registration_records_accepted_agreements(client, db):
response = _register(client, agreements=["TERMS_OF_SERVICE_GUI"])
diff --git a/test/test_platform_user_api.py b/test/test_platform_user_api.py
index 0725eff..76d3017 100644
--- a/test/test_platform_user_api.py
+++ b/test/test_platform_user_api.py
@@ -137,7 +137,17 @@ def test_a_username_can_change_case_alone(client, member):
assert member.username == "Member"
[email protected]("username", ["STRANGER", "mwmbl-seed-crawler", "has space", ""])
+def test_a_case_change_cannot_collide_with_an_existing_case_variant(client, member):
+ _user("MEMBER")
+
+ response = _change_username(client, member, "Member")
+
+ assert response.status_code == 400
+
+
+ "username", ["STRANGER", "mwmbl-seed-crawler", "has space", "", "x" * 151, "[email protected]"]
+)
def test_taken_reserved_and_invalid_usernames_are_refused(client, member, username):
_user("stranger")
@@ -192,6 +202,55 @@ def test_a_new_email_replaces_the_old_one_once_confirmed(client, member):
]
+def test_login_moves_to_the_new_email_once_confirmed(client, member):
+ _change_email(client, member, "[email protected]")
+ pending = EmailAddress.objects.get(email="[email protected]")
+ client.post(
+ f"{BASE}/confirm-email",
+ data={"email": "[email protected]", "key": EmailConfirmationHMAC(pending).key},
+ content_type="application/json",
+ )
+
+ def log_in(username):
+ return client.post(
+ f"{BASE}/token/pair",
+ data={"username": username, "password": "correctpassword"},
+ content_type="application/json",
+ )
+
+ assert log_in("[email protected]").status_code == 200
+ assert log_in("[email protected]").status_code == 401
+
+
+def test_an_email_pending_on_another_account_cannot_be_registered(client, member):
+ _change_email(client, member, "[email protected]")
+
+ response = client.post(
+ f"{BASE}/register",
+ data={"email": "[email protected]", "password": "anotherpassword"},
+ content_type="application/json",
+ )
+
+ assert response.status_code == 400
+
+
+def test_confirming_an_email_another_account_has_verified_is_refused(client, member):
+ _change_email(client, member, "[email protected]")
+ pending = EmailAddress.objects.get(email="[email protected]")
+ stranger = _user("stranger")
+ EmailAddress.objects.create(user=stranger, email="[email protected]", verified=True)
+
+ response = client.post(
+ f"{BASE}/confirm-email",
+ data={"email": "[email protected]", "key": EmailConfirmationHMAC(pending).key},
+ content_type="application/json",
+ )
+
+ assert response.status_code == 400
+ member.refresh_from_db()
+ assert member.email == "[email protected]"
+
+
def test_a_second_email_change_replaces_the_pending_one(client, member):
_change_email(client, member, "[email protected]")
_change_email(client, member, "[email protected]")