mirror of
https://github.com/retspen/webvirtcloud
synced 2026-12-02 08:56:07 +00:00
feat(accounts): an administrator can reset a user's OTP
A user's OTP secret could not be changed: "Lost OTP?" and the admin's "Email OTP QR code" both send the same secret again, so a stolen phone kept making valid codes. The user's profile page now has "Reset OTP", which deletes the user's TOTP device; they sign in with the password alone until a new QR code is mailed, which has a new secret. The mailed link now names the device, not the user: a link mailed before a reset shows nothing, not the next device's secret. A new signing salt refuses the links that named a user, whose id may be another user's device. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Kk4h2TcUiaWmU5MUszYSea
This commit is contained in:
parent
fa0f7f79ac
commit
135839bd66
10 changed files with 992 additions and 888 deletions
|
|
@ -36,6 +36,12 @@
|
|||
<form method="post" action="{% url 'accounts:admin_email_otp' user.id %}">{% csrf_token %}
|
||||
<button type="submit" class="btn btn-outline-secondary">{% bs_icon 'qr-code' %} {% trans "Email OTP QR code" %}</button>
|
||||
</form>
|
||||
{% if has_otp %}
|
||||
<form method="post" action="{% url 'accounts:admin_reset_otp' user.id %}">{% csrf_token %}
|
||||
<button type="submit" class="btn btn-outline-danger"
|
||||
data-confirm="{% blocktrans %}Reset the OTP of {{ user }}? Their authenticator app stops working; they sign in with the password alone until a new QR code is mailed.{% endblocktrans %}">{% bs_icon 'x-circle' %} {% trans "Reset OTP" %}</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -1,10 +1,14 @@
|
|||
from unittest.mock import patch
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.test import TestCase
|
||||
from django.core.signing import TimestampSigner
|
||||
from django.test import TestCase, override_settings
|
||||
from django.urls import reverse
|
||||
from django_otp.plugins.otp_totp.models import TOTPDevice
|
||||
|
||||
from accounts.utils import OTP_LINK
|
||||
from logs.models import Logs
|
||||
|
||||
|
||||
class AdminEmailOtpTestCase(TestCase):
|
||||
"""Sending the OTP QR code by email must not happen on GET."""
|
||||
|
|
@ -37,6 +41,28 @@ class AdminEmailOtpTestCase(TestCase):
|
|||
self.client.post(self.url)
|
||||
self.assertFalse(TOTPDevice.objects.filter(user=self.user).exists())
|
||||
|
||||
@override_settings(OTP_ENABLED=True)
|
||||
def test_a_reset_forgets_the_device_and_the_links_mailed_for_it(self):
|
||||
with patch("accounts.views.send_email_with_otp") as send:
|
||||
self.client.post(self.url)
|
||||
old_link = OTP_LINK.sign(str(send.call_args.args[1].pk))
|
||||
self.assertContains(self.client.get(reverse("accounts:account", args=[self.user.id])), "Reset OTP")
|
||||
response = self.client.post(reverse("accounts:admin_reset_otp", args=[self.user.id]), follow=True)
|
||||
self.assertContains(response, "OTP of otp_user was reset")
|
||||
self.assertNotContains(response, "Reset OTP")
|
||||
self.assertFalse(TOTPDevice.objects.filter(user=self.user).exists())
|
||||
self.assertEqual(Logs.objects.get(message="User otp_user: reset OTP").success, True)
|
||||
# the old mail does not show the new device's secret
|
||||
with patch("accounts.views.send_email_with_otp"):
|
||||
self.client.post(self.url)
|
||||
self.assertEqual(self.client.post(reverse("accounts:otp_qr"), {"token": old_link}).status_code, 404)
|
||||
|
||||
@override_settings(OTP_ENABLED=True)
|
||||
def test_a_link_that_named_a_user_does_not_open_a_device_with_that_id(self):
|
||||
device = TOTPDevice.objects.create(user=self.superuser, confirmed=True)
|
||||
user_link = TimestampSigner(salt="accounts.otp_qr").sign(str(device.pk))
|
||||
self.assertEqual(self.client.post(reverse("accounts:otp_qr"), {"token": user_link}).status_code, 404)
|
||||
|
||||
def test_the_smtp_connection_waits_a_bounded_time(self):
|
||||
from django.core.mail.backends.smtp import EmailBackend
|
||||
|
||||
|
|
|
|||
|
|
@ -93,7 +93,7 @@ class AccountsUtilsTestCase(TestCase):
|
|||
@override_settings(OTP_ENABLED=True)
|
||||
def test_the_mail_links_to_the_qr_code_and_holds_no_secret(self):
|
||||
device = get_user_totp_device(self.user)
|
||||
send_email_with_otp(RequestFactory().get("/"), self.user)
|
||||
send_email_with_otp(RequestFactory().get("/"), device)
|
||||
self.assertEqual(len(mail.outbox), 1)
|
||||
message = mail.outbox[0]
|
||||
self.assertEqual((message.subject, message.to, message.alternatives), ("OTP QR Code", ["user@example.com"], []))
|
||||
|
|
@ -111,8 +111,7 @@ class AccountsUtilsTestCase(TestCase):
|
|||
|
||||
@override_settings(OTP_ENABLED=True)
|
||||
def test_a_link_that_is_old_or_not_signed_shows_nothing(self):
|
||||
get_user_totp_device(self.user)
|
||||
token = OTP_LINK.sign(str(self.user.pk))
|
||||
token = OTP_LINK.sign(str(get_user_totp_device(self.user).pk))
|
||||
with patch("django.core.signing.time.time", return_value=time.time() + OTP_LINK_MAX_AGE + 1):
|
||||
self.assertEqual(self.client.post(reverse("accounts:otp_qr"), {"token": token}).status_code, 404)
|
||||
self.assertEqual(self.client.post(reverse("accounts:otp_qr"), {"token": f"{self.user.pk}:x:y"}).status_code, 404)
|
||||
|
|
|
|||
|
|
@ -44,6 +44,7 @@ urlpatterns = [
|
|||
views.admin_email_otp,
|
||||
name="admin_email_otp",
|
||||
),
|
||||
path("admin_reset_otp/<int:user_id>/", views.admin_reset_otp, name="admin_reset_otp"),
|
||||
]
|
||||
|
||||
if settings.OTP_ENABLED:
|
||||
|
|
|
|||
|
|
@ -61,16 +61,19 @@ def validate_ssh_key(key):
|
|||
return True
|
||||
|
||||
|
||||
# the link a mail carries to its user's OTP QR code: the mail holds no secret
|
||||
OTP_LINK = TimestampSigner(salt="accounts.otp_qr")
|
||||
# the link a mail carries to its device's OTP QR code: the mail holds no secret.
|
||||
# Links once named the user: this salt refuses those, whose id may be another's device.
|
||||
OTP_LINK = TimestampSigner(salt="accounts.otp_qr.device")
|
||||
OTP_LINK_MAX_AGE = 3600
|
||||
|
||||
|
||||
def send_email_with_otp(request, user):
|
||||
"""Mail the user a link to the page of their OTP QR code, good for
|
||||
def send_email_with_otp(request, device):
|
||||
"""Mail the device's user a link to the page of its OTP QR code, good for
|
||||
OTP_LINK_MAX_AGE: the QR code's secret is never in a mailbox. The token
|
||||
is the URL's fragment, which no request carries: it is in no access log."""
|
||||
url = request.build_absolute_uri(reverse("accounts:otp_qr")) + "#" + OTP_LINK.sign(str(user.pk))
|
||||
is the URL's fragment, which no request carries: it is in no access log.
|
||||
It names the device, so after an OTP reset it shows nothing."""
|
||||
user = device.user
|
||||
url = request.build_absolute_uri(reverse("accounts:otp_qr")) + "#" + OTP_LINK.sign(str(device.pk))
|
||||
send_mail(
|
||||
_("OTP QR Code"),
|
||||
_("Open this link within an hour to see the OTP QR code of account '%(user)s':\n\n%(url)s")
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ from django.utils.translation import gettext_lazy as _
|
|||
from django.views.decorators.cache import never_cache
|
||||
from django.views.decorators.http import require_POST
|
||||
from django.views.decorators.debug import sensitive_post_parameters
|
||||
from django_otp.plugins.otp_totp.models import TOTPDevice
|
||||
|
||||
from accounts.apps import admin_password_path
|
||||
from computes.utils import lock_ownership
|
||||
|
|
@ -191,6 +192,7 @@ def account(request, user_id):
|
|||
"publickeys": publickeys,
|
||||
"api_tokens": ApiToken.objects.filter(user_id=user_id),
|
||||
"otp_enabled": settings.OTP_ENABLED,
|
||||
"has_otp": TOTPDevice.objects.filter(user=user).exists(),
|
||||
},
|
||||
)
|
||||
|
||||
|
|
@ -333,7 +335,7 @@ def email_otp(request):
|
|||
try:
|
||||
# the row's user is the requester: anonymous
|
||||
with audit(request, None, f"User {user.username}", "mail OTP QR code (lost OTP)"):
|
||||
send_email_with_otp(request, user)
|
||||
send_email_with_otp(request, device)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Could not mail the OTP QR code to user %s", user.pk)
|
||||
|
||||
|
|
@ -354,21 +356,18 @@ def email_otp(request):
|
|||
|
||||
@login_not_required
|
||||
def otp_qr(request):
|
||||
"""The OTP QR code of the user a mailed link (send_email_with_otp) names.
|
||||
"""The OTP QR code of the device a mailed link (send_email_with_otp) names.
|
||||
The link's token is in its fragment: the page posts it (otp_qr.js)."""
|
||||
if not settings.OTP_ENABLED:
|
||||
raise Http404
|
||||
if request.method != "POST":
|
||||
return render(request, "accounts/otp_qr.html")
|
||||
try:
|
||||
user_id = OTP_LINK.unsign(request.POST.get("token", ""), max_age=OTP_LINK_MAX_AGE)
|
||||
device_id = OTP_LINK.unsign(request.POST.get("token", ""), max_age=OTP_LINK_MAX_AGE)
|
||||
except BadSignature:
|
||||
raise Http404
|
||||
user = get_object_or_404(get_user_model(), pk=user_id, is_active=True)
|
||||
device = get_existing_totp_device(user)
|
||||
if device is None:
|
||||
raise Http404
|
||||
response = render(request, "accounts/otp_qr.html", {"user": user, "qr_svg": otp_qr_svg(device)})
|
||||
device = get_object_or_404(TOTPDevice, pk=device_id, confirmed=True, user__is_active=True)
|
||||
response = render(request, "accounts/otp_qr.html", {"user": device.user, "qr_svg": otp_qr_svg(device)})
|
||||
response["Cache-Control"] = "no-store"
|
||||
return response
|
||||
|
||||
|
|
@ -382,8 +381,7 @@ def admin_email_otp(request, user_id):
|
|||
try:
|
||||
# a device made for a mail that did not go would ask for codes the user never got
|
||||
with audit(request, None, subject, "mail OTP QR code"), transaction.atomic():
|
||||
get_user_totp_device(user)
|
||||
send_email_with_otp(request, user)
|
||||
send_email_with_otp(request, get_user_totp_device(user))
|
||||
except OSError as err: # the SMTP server refused it, or did not answer within EMAIL_TIMEOUT
|
||||
messages.error(request, _("The OTP QR code could not be mailed to %(user)s: %(error)s") % {
|
||||
"user": user, "error": err})
|
||||
|
|
@ -395,3 +393,15 @@ def admin_email_otp(request, user_id):
|
|||
failed(request, None, subject, "mail OTP QR code", "no email address")
|
||||
messages.error(request, _("User email not set, failed to send QR code"))
|
||||
return redirect("accounts:account", user.id)
|
||||
|
||||
|
||||
@require_POST
|
||||
@superuser_only
|
||||
def admin_reset_otp(request, user_id):
|
||||
"""Forget the user's OTP device, as when it is lost or stolen: they sign
|
||||
in with the password alone until a new QR code is mailed."""
|
||||
user = get_object_or_404(get_user_model(), pk=user_id)
|
||||
with audit(request, None, f"User {user.username}", "reset OTP"):
|
||||
TOTPDevice.objects.filter(user=user).delete()
|
||||
messages.success(request, _("OTP of %(user)s was reset: a new QR code can be mailed.") % {"user": user})
|
||||
return redirect("accounts:account", user.id)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue