-
-
Notifications
You must be signed in to change notification settings - Fork 4.8k
fix(auth): do not update email in UserDetailsEndpoint #119253
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 6 commits
c9c0582
ff9dae0
0e7eb3b
2e40aa0
57dc341
f48ca2e
709cd35
86625c0
0e7bd87
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -10,13 +10,14 @@ | |
| from django.contrib.auth.models import UserManager as DjangoUserManager | ||
| from django.contrib.auth.signals import user_logged_out | ||
| from django.db import IntegrityError, models, router, transaction | ||
| from django.db.models import Count, Subquery | ||
| from django.db.models import Count, Q, Subquery | ||
| from django.db.models.query import QuerySet | ||
| from django.dispatch import receiver | ||
| from django.forms import model_to_dict | ||
| from django.http.request import HttpRequest | ||
| from django.urls import reverse | ||
| from django.utils import timezone | ||
| from django.utils.crypto import get_random_string | ||
| from django.utils.translation import gettext_lazy as _ | ||
|
|
||
| from bitfield import TypedClassBitField | ||
|
|
@@ -34,7 +35,6 @@ | |
| from sentry.db.models import Model, control_silo_model, sane_repr | ||
| from sentry.db.models.manager.base import BaseManager | ||
| from sentry.db.models.manager.base_query_set import BaseQuerySet | ||
| from sentry.db.models.utils import unique_db_instance | ||
| from sentry.db.postgres.transactions import enforce_constraints | ||
| from sentry.hybridcloud.models.outbox import ControlOutboxBase, outbox_context | ||
| from sentry.hybridcloud.outbox.category import OutboxCategory | ||
|
|
@@ -482,8 +482,6 @@ def set_password(self, raw_password: str | None) -> None: | |
| self.is_password_expired = False | ||
|
|
||
| def refresh_session_nonce(self, request: HttpRequest | None = None) -> None: | ||
| from django.utils.crypto import get_random_string | ||
|
|
||
| self.session_nonce = get_random_string(12) | ||
| if request is not None: | ||
| request.session["_nonce"] = self.session_nonce | ||
|
|
@@ -537,6 +535,29 @@ def normalize_before_relocation_import( | |
|
|
||
| return old_pk | ||
|
|
||
| @classmethod | ||
| def is_username_available(cls, username: str, *, exclude_user_id: int = 0) -> bool: | ||
| """ | ||
| A username is available only if it is not already in use as another account's | ||
| username, primary email, or verified email. Login resolves a username before | ||
| falling back to email (see find_users in sentry/utils/auth.py), so a username | ||
| equal to an email another account owns would collide with its login identity. | ||
|
|
||
| `exclude_user_id` is the user being updated (excluded from the check); leave it | ||
| as the default when checking a not-yet-saved user (e.g. a relocation import). | ||
| """ | ||
| username_or_primary_taken = ( | ||
| cls.objects.exclude(id=exclude_user_id) | ||
| .filter(Q(username__iexact=username) | Q(email__iexact=username)) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thoughts on defensively adding a |
||
| .exists() | ||
| ) | ||
|
cursor[bot] marked this conversation as resolved.
|
||
| verified_email_taken = ( | ||
| UserEmail.objects.filter(email__iexact=username, is_verified=True) | ||
| .exclude(user_id=exclude_user_id) | ||
| .exists() | ||
| ) | ||
|
Comment on lines
+558
to
+562
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If |
||
| return not (username_or_primary_taken or verified_email_taken) | ||
|
|
||
| def write_relocation_import( | ||
| self, scope: ImportScope, flags: ImportFlags | ||
| ) -> tuple[int, ImportKind] | None: | ||
|
|
@@ -551,7 +572,7 @@ def do_write() -> tuple[int, ImportKind]: | |
| DatabaseLostPasswordHashService, | ||
| ) | ||
|
|
||
| serializer_cls = BaseUserSerializer | ||
| serializer_cls: type[BaseUserSerializer] | ||
|
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. driveby cleanup |
||
| if scope not in {ImportScope.Config, ImportScope.Global}: | ||
| serializer_cls = UserSerializer | ||
| else: | ||
|
|
@@ -570,29 +591,30 @@ def do_write() -> tuple[int, ImportKind]: | |
| # that actually goes, and how to prevent it from happening during the validation pass. | ||
| return (self.pk, ImportKind.Inserted) | ||
|
|
||
| # If there is no existing user with this `username`, no special renaming or merging | ||
| # shenanigans are needed, as we can just insert this exact model directly. | ||
| existing = User.objects.filter(username=self.username).first() | ||
| if not existing: | ||
| return do_write() | ||
|
|
||
| # Re-use the existing user if merging is enabled. | ||
| # Merging is enabled only for SAAS_TO_SAAS relocations, where the data is | ||
| # server-generated and `username` is unique, so matching on username alone is safe. | ||
| # Reuse the existing account instead of inserting. | ||
| if flags.merge_users: | ||
| return (existing.pk, ImportKind.Existing) | ||
|
|
||
| # We already have a user with this `username`, but merging users has not been enabled. In | ||
| # this case, add a random suffix to the importing username. | ||
| lock = locks.get(f"user:username:{self.id}", duration=10, name="username") | ||
| with TimedRetryPolicy(10)(lock.acquire): | ||
| unique_db_instance( | ||
| self, | ||
| self.username, | ||
| max_length=MAX_USERNAME_LENGTH, | ||
| field_name="username", | ||
| ) | ||
| username_match = User.objects.filter(username__iexact=self.username).first() | ||
| if username_match: | ||
| return (username_match.pk, ImportKind.Existing) | ||
|
|
||
| # Suffix until the username collides with neither an existing username nor | ||
| # email; the standard slug helper (unique_db_instance) does not support cross-column checking. | ||
| if not User.is_username_available(self.username): | ||
| lock = locks.get(f"user:username:{self.id}", duration=10, name="username") | ||
|
sentry[bot] marked this conversation as resolved.
Outdated
|
||
| with TimedRetryPolicy(10)(lock.acquire): | ||
| base = self.username[: MAX_USERNAME_LENGTH - 13] | ||
| for _ in range(3): | ||
| suffix = get_random_string( | ||
| 12, allowed_chars="abcdefghijklmnopqrstuvwxyz0123456789" | ||
| ) | ||
| self.username = f"{base}-{suffix}" | ||
| if User.is_username_available(self.username): | ||
| return do_write() | ||
| raise RuntimeError("Could not generate a unique username during relocation import") | ||
|
|
||
| # Perform the remainder of the write while we're still holding the lock. | ||
| return do_write() | ||
| return do_write() | ||
|
sentry[bot] marked this conversation as resolved.
|
||
|
|
||
| @classmethod | ||
| def sanitize_relocation_json( | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It looks like
BaseUserSerializeris inherited by a bunch of other serializers, so removing this might affect how the other serializers work.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think this is actually a good consequence - the sync removal now applies uniformly to regular, superuser, and staff edits. I don't think changing username should ever change email, but let me take a look at how
BaseUserSerializeris being used.Looks like
BaseUserSerializeris only being used for the 3 otherUserSerializersin this file, which are only used here and in 1 other place:write_relocation_importon theUsermodel. (note there is another unrelatedUserSerializerinsrc/sentry/users/api/serializers/user.py)The
validate()function I removed was mutatingvalidated_dataso the changes it caused would only persist ifserializer.save()was used.This is not the case for the uses in
src/sentry/users/models/user.py, which useself.save(), so the removed code was already not being used inwrite_relocation_import