:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(admin): hide password hash and reset link in user admin (#82795)
Tom Piccirello93c1c700a021
diff --git a/posthog/admin/admins/user_admin.py b/posthog/admin/admins/user_admin.pyindex c23dd72ca0f7..45b1989d9473 100644--- a/posthog/admin/admins/user_admin.py+++ b/posthog/admin/admins/user_admin.py@@ -1,13 +1,20 @@import datetime+from typing import Anyfrom django.contrib import admin, messagesfrom django.contrib.auth.admin import UserAdmin as DjangoUserAdmin-from django.contrib.auth.forms import UserChangeForm as DjangoUserChangeForm+from django.contrib.auth.forms import (+ ReadOnlyPasswordHashWidget as DjangoReadOnlyPasswordHashWidget,+ UserChangeForm as DjangoUserChangeForm,+)from django.core.exceptions import ValidationErrorfrom django.http import HttpResponseRedirectfrom django.urls import reversefrom django.utils.html import format_html-from django.utils.translation import gettext_lazy as _+from django.utils.translation import (+ gettext,+ gettext_lazy as _,+)from django_otp.plugins.otp_totp.models import TOTPDevice@@ -24,21 +31,22 @@ from posthog.models.webauthn_credential import WebauthnCredentialfrom posthog.session.activity import revoke_other_sessionsfrom posthog.tasks.email import send_password_reset, send_two_factor_reset_email+# Django's default widget masks salt/hash but still shows their first few characters; keep those out of the admin entirely.+_HIDDEN_SUMMARY_LABELS = {"salt", "hash", "checksum"}+++class ReadOnlyPasswordHashWidget(DjangoReadOnlyPasswordHashWidget):+ def get_context(self, name: str, value: str | None, attrs: dict[str, Any] | None) -> dict[str, Any]:+ context = super().get_context(name, value, attrs)+ hidden_labels = {gettext(label) for label in _HIDDEN_SUMMARY_LABELS}+ context["summary"] = [entry for entry in context["summary"] if entry["label"] not in hidden_labels]+ return context+class UserChangeForm(DjangoUserChangeForm):def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)- # This is a riff on https://github.com/django/django/blob/stable/4.1.x/django/contrib/auth/forms.py#L151-L153.- # The difference from the Django default is that instead of a form where the _admin_ sets the new password,- # we have a link to the password reset page which the _user_ can use themselves.- # This way if some user needs to reset their password and there's a problem with receiving the reset link email,- # an admin can provide that reset link manually – much better than sending a new password in plain text.- password_reset_token = password_reset_token_generator.make_token(self.instance)- self.fields["password"].help_text = (- "Raw passwords are not stored, so there is no way to see this user's password, but you can send them "- f'<a target="_blank" href="/reset/{self.instance.uuid}/{password_reset_token}">this password reset link</a> '- "(it only works when logged out)."- )+ self.fields["password"].widget = ReadOnlyPasswordHashWidget()def clean_is_staff(self):is_staff = bool(self.cleaned_data.get("is_staff", False))diff --git a/posthog/admin/test_user_admin.py b/posthog/admin/test_user_admin.pyindex d13f51d08826..6faa7c0bceb0 100644--- a/posthog/admin/test_user_admin.py+++ b/posthog/admin/test_user_admin.py@@ -11,7 +11,7 @@ from django.contrib.messages.storage.fallback import FallbackStoragefrom django.test import RequestFactoryfrom django.urls import reverse-from posthog.admin.admins.user_admin import UserAdmin+from posthog.admin.admins.user_admin import UserAdmin, UserChangeFormfrom posthog.models import Userfrom posthog.session.models import Session@@ -85,3 +85,28 @@ class TestUserAdminPasswordReset(BaseTest):# A usable reset token must be forwarded — an empty/None token would email a dead link.self.assertIsInstance(token, str)self.assertTrue(token)+++class TestUserChangeFormPasswordField(BaseTest):+ def test_password_field_omits_salt_and_hash(self):+ # Guards against the partial (masked) hash material Django's default widget shows reappearing.+ user = User.objects.create(email=f"test-{uuid.uuid4()}@example.com", distinct_id=str(uuid.uuid4()))+ # nosemgrep: python.django.security.audit.unvalidated-password.unvalidated-password (test fixture, not a user-facing password-set path)+ user.set_password("a-strong-password-123")+ user.save()++ rendered = str(UserChangeForm(instance=user)["password"])++ self.assertIn("algorithm", rendered)+ self.assertNotIn("salt", rendered)+ self.assertNotIn("hash", rendered)++ def test_password_field_help_text_omits_reset_link(self):+ # A raw reset link/token in the help text would let a staff member reset the user's+ # password themselves; the "Reset password" button emails it to the user instead.+ user = User.objects.create(email=f"test-{uuid.uuid4()}@example.com", distinct_id=str(uuid.uuid4()))++ help_text = UserChangeForm(instance=user).fields["password"].help_text++ self.assertNotIn("/reset/", help_text)+ self.assertNotIn("href", help_text)