diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index afc0059..9d9c807 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -58,6 +58,40 @@ jobs:
--with "django~=${{ matrix.django }}.0"
python -c "import django; print('Django', django.get_version())"
+ lowest:
+ # Every other job runs the versions uv.lock pins, which are the newest
+ # releases, so nothing checked the floors pyproject.toml declares. One
+ # was wrong: `fido2>=1.1.2` let an install resolve a 1.x release the
+ # WebAuthn adapter cannot run against, while every job here stayed green
+ # on 2.2.1. lowest-direct resolves each direct dependency to the oldest
+ # version its declared range allows, on the oldest Python supported.
+ # Transitive dependencies stay at their newest: their floors are not a
+ # promise this package makes.
+ #
+ # uv re-locks for this run, inside the runner's checkout only, starting
+ # from the committed uv.lock. Reproducing it locally, do the same from a
+ # clean checkout. A lowest-direct lock left over from an earlier run makes
+ # uv keep the versions it already holds, so a floor loosened since then
+ # is never actually installed and this passes without testing it.
+ name: Lowest declared versions (py3.10)
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v7
+ - uses: astral-sh/setup-uv@v10.0.0
+ with:
+ enable-cache: true
+
+ - name: Report the versions this job resolves
+ # Before the tests rather than after, so the versions are on record
+ # exactly when it matters: when the next step fails.
+ run: >
+ uv run --python 3.10 --resolution lowest-direct
+ python -c "from importlib.metadata import version as v;
+ print(*(f'{p} {v(p)}' for p in ('django', 'fido2', 'qrcode')), sep=' | ')"
+
+ - name: Run the test suite at every direct dependency's floor
+ run: uv run --python 3.10 --resolution lowest-direct python test_runner.py
+
coverage:
name: Coverage
runs-on: ubuntu-latest
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3d97a39..ee83c90 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,83 @@ Versions follow [PEP 440](https://peps.python.org/pep-0440/). The version in
`pyproject.toml` is the only place it is written; the git tag and the GitHub
Release are derived from it (see [docs/contributing.md](docs/contributing.md)).
+## 4.6.1
+
+### Fixed
+
+- **A session opened before its user enrolled was never challenged by
+ `MfaMiddleware`.** Login stamps nothing for a user with no factor, since
+ there is nothing to challenge yet, and the middleware only challenged
+ sessions that carried a pending stamp. So anyone signed in as that user
+ before they enrolled kept every page the middleware alone protects, after
+ enrollment as well as before. That includes someone the user enrolled
+ specifically to lock out. `@mfa_required`, `@mfa_recent_required` and the
+ JSON API were not affected; they already treated such a session as pending
+ (4.5.0). The middleware now does the same, and redirects it to
+ `mfa:verify`.
+- **The declared `fido2` floor was wrong.** Every release since 4.0.0
+ allowed `fido2>=1.1.2`, but the WebAuthn adapter is written against the
+ 2.x API and every WebAuthn test fails on 1.x (1.1.2 and 1.2.0 both
+ checked). An environment that resolved a 1.x release installed cleanly and
+ then broke on the first security-key or passkey ceremony. The requirement
+ is now `fido2>=2.0.0,<3`; the full suite passes on 2.0.0. A new CI job
+ runs the suite with every direct dependency at its declared floor, so a
+ wrong minimum now fails a build instead of a user's install.
+- **A deactivated account could still sign in with a passkey.** Nothing on
+ the passwordless path checked `is_active`: a user with `is_active=False`
+ was refused a password login by Django's `ModelBackend` but signed in with
+ a passkey, and an existing passkey session survived deactivation.
+ Passwordless login now refuses an inactive user with the same response as
+ every other failure, and `WebAuthnBackend` refuses one in `get_user()` and
+ `authenticate()`, as `ModelBackend` does, so deactivating an account ends
+ its passkey sessions on their next request.
+- **Enrolling a factor the user already held returned a 500.** A second
+ authenticator app (a double-clicked submit, a stale tab, a typed URL) hit
+ the one-per-user database constraint. Enrollment, in the HTML views and the
+ JSON API, now refuses a factor `Adapter.is_available()` says the user may
+ not add, and treats a lost race at the constraint the same way: the usual
+ 400.
+- **A TOTP secret no configured key could read returned a 500.** Removing a
+ key from `MFA_SECRET_ENCRYPTION_KEYS` (or the setting) while secrets it
+ signed remained made every TOTP attempt for those users raise
+ `BadSignature`. The attempt now fails like a wrong code, and an error is
+ logged on `django_mfa.adapters.totp` naming the user.
+- **`MFA_NOTIFY_ON_CHANGE` could say "Two-factor authentication is off" more
+ than once.** It was sent after any removal that left no primary factor,
+ so `manage.py mfa_reset` sent it again for recovery codes removed after
+ the last primary factor. It is now sent only when the removed factor was
+ the last primary one.
+- **The method picker could be empty, with no way on.** A session stamped
+ pending at login whose user then lost every factor (`manage.py mfa_reset`,
+ or `MFA_FACTORS` narrowed) was sent to a "Verify it's you" page offering
+ nothing, on every request. The picker now drops that stale stamp and
+ continues to `next`, since a fresh login would not have been challenged;
+ `MFA_REQUIRED` then applies as usual.
+- **A refused passkey showed the user raw JSON.** The bundled `webauthn.js`
+ submitted the passwordless form as a page load, so a failure replaced the
+ login page with `{"error": "Passkey sign-in failed."}`. It now posts with
+ `fetch()` and shows the message in `#webauthn-passkey-error`, including
+ for a passkey chosen from autofill. `mfa:passkey_complete` answers a
+ request that asks for JSON with `{"redirect": url}` on success; a plain
+ form post still gets a redirect.
+- **`django_mfa.E011` refused `MFA_ADMIN_STEPUP` on a site built with
+ `MfaAdminMixin`.** The mixin reads the setting, but the check demanded
+ `MFA_PROTECT_ADMIN`, which also patches the default site and makes every
+ staff user required. It now fires only when nothing reads the setting:
+ `MFA_PROTECT_ADMIN` off and no admin site using `MfaAdminMixin`. To find
+ such a site the check imports the URLconf.
+
+### Upgrading
+
+No migration. Users who had other sessions open when they enrolled are asked
+for their factor once on each of them. Telling a never-challenged session apart
+from one whose user holds no factor costs one query per request, paid only by
+sessions that have not passed a challenge (in practice, users who have not
+enrolled); with `MFA_REQUIRED` on, the enrollment wall shares it. Tests that
+create an `Authenticator` row directly after logging in, then request a page
+only the middleware protects, now get a redirect. See
+[docs/upgrading.md](docs/upgrading.md).
+
## 4.6.0
### Added
diff --git a/README.md b/README.md
index 6c71351..750ce69 100644
--- a/README.md
+++ b/README.md
@@ -163,9 +163,6 @@ The parts that are easy to get subtly wrong, done deliberately:
implement one (iCloud passkeys always report 0).
- **Recovery codes are hashed** with Django's password hasher, marked used
individually, and displayed exactly once.
-- **Encryption at rest for TOTP secrets**, opt-in via `MFA_SECRET_ENCRYPTION_KEYS` —
- a *list*, because the first key encrypts and every key is tried on decrypt. That's
- what makes key rotation a redeploy instead of a migration.
- **Recovery codes can never be someone's only factor.** They're exhaustible, so they
don't count toward "is this user protected" — one source of truth in the registry, not
a rule re-implemented in three places.
@@ -232,11 +229,13 @@ against it from outside the source tree.
- [Translations](http://django-mfa.readthedocs.io/en/latest/translations.html) — the six shipped languages, and how to fix or add one
- [Customizing the UI](http://django-mfa.readthedocs.io/en/latest/customizing.html) — templates, context, and the WebAuthn JS contract
- [Enforcing MFA](http://django-mfa.readthedocs.io/en/latest/enforcement.html) — requiring it for some or all users, and per-view enforcement
-- [Integration recipes](http://django-mfa.readthedocs.io/en/latest/recipes.html) — allauth, passkey buttons, APIs, testing, troubleshooting
+- [Integration recipes](http://django-mfa.readthedocs.io/en/latest/recipes.html): allauth, passkey buttons, APIs and testing
+- [Troubleshooting](http://django-mfa.readthedocs.io/en/latest/troubleshooting.html): redirect loops, dead passkey buttons, rejected codes and locked-out users
- [Writing a custom factor](http://django-mfa.readthedocs.io/en/latest/custom_factors.html) — the Adapter API, with a worked example
- [Security model](http://django-mfa.readthedocs.io/en/latest/security.html) — controls, non-goals, and a production checklist
-- [Flow and URLs](http://django-mfa.readthedocs.io/en/latest/mfa_flow.html) — what happens on enroll, on login, and on passwordless login
+- [How it works](http://django-mfa.readthedocs.io/en/latest/mfa_flow.html): what happens on enroll, on login, and on passwordless login
- [Upgrade notes](http://django-mfa.readthedocs.io/en/latest/upgrading.html) — read before upgrading a project with real users
+- [Changelog](http://django-mfa.readthedocs.io/en/latest/changelog.html): what changed in each release
- [Contributing](http://django-mfa.readthedocs.io/en/latest/contributing.html)
A runnable demo project lives in [`sandbox/`](sandbox/).
diff --git a/django_mfa/adapters/totp.py b/django_mfa/adapters/totp.py
index 0fe6a09..a35bf7f 100644
--- a/django_mfa/adapters/totp.py
+++ b/django_mfa/adapters/totp.py
@@ -1,7 +1,9 @@
import base64
+import logging
import re
import secrets
+from django.core import signing
from django.utils.translation import gettext_lazy as _
from django_mfa import totp as totp_mod
@@ -19,6 +21,8 @@
#: task adds rate limiting on top.
TOTP_VALID_WINDOW = 1
+logger = logging.getLogger(__name__)
+
#: RFC 4226 R6: "The algorithm MUST use a strong shared secret. The length of
#: the shared secret MUST be at least 128 bits. This document RECOMMENDs a
@@ -69,7 +73,20 @@ def complete_verify(self, request, user, data):
auth = self.get_instances(user).first()
if auth is None:
return False
- counter = totp_mod.TOTP(decrypt(auth.data["secret"])).match(
+ try:
+ secret = decrypt(auth.data["secret"])
+ except signing.BadSignature:
+ # Signed under MFA_SECRET_ENCRYPTION_KEYS by a key no longer in
+ # the list (or the setting was removed). The user cannot pass
+ # this factor until a key that signed it is restored or they
+ # re-enroll; that is a failed attempt, not a 500, and only the
+ # log can tell an operator why their codes stopped working.
+ logger.error(
+ "Cannot read the TOTP secret of user %s: no key in "
+ "MFA_SECRET_ENCRYPTION_KEYS matches the one it was signed "
+ "with.", user.pk)
+ return False
+ counter = totp_mod.TOTP(secret).match(
data.get("code", ""), valid_window=TOTP_VALID_WINDOW)
if counter is None:
return False
diff --git a/django_mfa/backends.py b/django_mfa/backends.py
index 3f64f49..76f06f6 100644
--- a/django_mfa/backends.py
+++ b/django_mfa/backends.py
@@ -21,6 +21,18 @@
from django_mfa.handles import user_from_handle, user_handle_for # noqa: F401
+def user_can_authenticate(user):
+ """Whether this user may be logged in at all.
+
+ The same rule as Django's ModelBackend.user_can_authenticate(): an
+ account with is_active=False is turned off, and a user model without
+ that field is always allowed. ModelBackend refuses an inactive user's
+ password and drops their existing sessions; without this, a passkey
+ would still log them in and keep them logged in.
+ """
+ return getattr(user, "is_active", True)
+
+
class WebAuthnBackend:
"""Authenticates a user from a verified WebAuthn assertion.
@@ -36,7 +48,12 @@ class WebAuthnBackend:
"""
def authenticate(self, request, mfa_user=None, **kwargs):
- return mfa_user
+ if mfa_user is not None and user_can_authenticate(mfa_user):
+ return mfa_user
+ return None
def get_user(self, user_id):
- return get_user_model().objects.filter(pk=user_id).first()
+ user = get_user_model().objects.filter(pk=user_id).first()
+ if user is not None and user_can_authenticate(user):
+ return user
+ return None
diff --git a/django_mfa/checks.py b/django_mfa/checks.py
index 66c1735..076b1e3 100644
--- a/django_mfa/checks.py
+++ b/django_mfa/checks.py
@@ -428,20 +428,45 @@ def check_grace_configuration(app_configs, **kwargs):
return errors
+def _mfa_admin_site_exists():
+ """Is any AdminSite built with MfaAdminMixin?
+
+ Such a site reads MFA_ADMIN_STEPUP whatever MFA_PROTECT_ADMIN says. It
+ is usually created in a module the URLconf imports, which may not have
+ happened yet when this runs: Django's own URL check imports the URLconf
+ too, but checks run in no fixed order. So load it first. A URLconf that
+ fails to import is that check's to report, not this one's.
+ """
+ from importlib import import_module
+
+ from django.contrib.admin import sites
+
+ from django_mfa.admin_site import MfaAdminMixin
+
+ try:
+ import_module(django_settings.ROOT_URLCONF)
+ except Exception:
+ pass
+ return any(isinstance(site, MfaAdminMixin) for site in sites.all_sites)
+
+
def check_admin_stepup(app_configs, **kwargs):
- """MFA_ADMIN_STEPUP without MFA_PROTECT_ADMIN does nothing at all.
+ """MFA_ADMIN_STEPUP with nothing to read it does nothing at all.
- Nothing reads MFA_ADMIN_STEPUP unless the admin site has been wrapped,
- and only MFA_PROTECT_ADMIN wraps it. An operator setting the stronger
- of the two alone believes the admin is step-up protected and it is not
- protected at all.
+ Two things read it: the default admin site once MFA_PROTECT_ADMIN has
+ wrapped it, and any AdminSite a project builds with MfaAdminMixin. With
+ neither, an operator setting MFA_ADMIN_STEPUP believes the admin is
+ step-up protected and it is not protected at all.
"""
- if mfa_settings.MFA_ADMIN_STEPUP and not mfa_settings.MFA_PROTECT_ADMIN:
+ if (mfa_settings.MFA_ADMIN_STEPUP and not mfa_settings.MFA_PROTECT_ADMIN
+ and not _mfa_admin_site_exists()):
return [Error(
- "MFA_ADMIN_STEPUP is set but MFA_PROTECT_ADMIN is not.",
- hint="Nothing reads MFA_ADMIN_STEPUP unless MFA_PROTECT_ADMIN "
- "has wrapped the admin site, so the admin is currently "
- "unprotected. Set MFA_PROTECT_ADMIN = True.",
+ "MFA_ADMIN_STEPUP is set but nothing reads it.",
+ hint="MFA_ADMIN_STEPUP applies to the default admin site when "
+ "MFA_PROTECT_ADMIN is on, and to any AdminSite built with "
+ "django_mfa.admin_site.MfaAdminMixin. With neither, the "
+ "admin is unprotected. Set MFA_PROTECT_ADMIN = True, or "
+ "mix MfaAdminMixin into your own AdminSite.",
id="django_mfa.E011",
)]
return []
diff --git a/django_mfa/decorators.py b/django_mfa/decorators.py
index b8f975d..1d6020e 100644
--- a/django_mfa/decorators.py
+++ b/django_mfa/decorators.py
@@ -73,11 +73,14 @@ def enforcement_state(request, require_primary_factor=True):
# falls through to `return None` and is treated exactly as a verified
# one.
#
- # The browser flow reaches this only for a session that missed
- # signals.stamp_pending_verification: a host project's force_login(),
- # or a session predating this app's installation. For a cookie-less
- # API client it is the *normal* state of every request, which is what
- # makes this load-bearing rather than defensive -- see
+ # The browser flow reaches this for a session no login ever stamped.
+ # The common case is one opened while its user held no factor:
+ # signals.stamp_pending_verification skips a factorless user, so
+ # enrolling afterwards leaves that session unstamped. The rarer ones
+ # are a host project's force_login() and a session predating this
+ # app's installation. MfaMiddleware applies this same rung. For a
+ # cookie-less API client it is the *normal* state of every request,
+ # which is what makes this load-bearing rather than defensive; see
# django_mfa/api/tokens.py. An endpoint declared `require_verified=
# True` without `stepup=True` would otherwise serve an unchallenged
# token client; no such endpoint exists today, so the freshness rung
diff --git a/django_mfa/flows.py b/django_mfa/flows.py
index 08ed8ef..05161ed 100644
--- a/django_mfa/flows.py
+++ b/django_mfa/flows.py
@@ -27,6 +27,8 @@
layers legitimately differ.
"""
+from django.db import IntegrityError, transaction
+
from django_mfa import events, ratelimit, session
from django_mfa.registry import registry
@@ -102,7 +104,8 @@ def attempt_verify(request, user, factor_type, data):
def attempt_enroll(request, factor_type, data):
"""Complete one enrollment. Returns the created ``Authenticator``.
- Raises ``FactorRejected`` if the adapter refuses the submission.
+ Raises ``FactorRejected`` if the adapter refuses the submission, or if
+ the user may not add (another) one of this factor.
Deliberately not rate-limited, unlike attempt_verify: the code checked
here is checked against a secret the caller supplied in the same request
@@ -116,9 +119,19 @@ def attempt_enroll(request, factor_type, data):
instead of the one they already hold.
"""
adapter = registry.get(factor_type)
+ # A singleton factor the user already holds (a second authenticator app,
+ # say) is not on offer, but a double-clicked submit, a stale tab or a
+ # hand-typed URL still gets here. Refused like any other rejection
+ # rather than left to the database constraint, which raised a 500.
+ if not adapter.is_available(request.user):
+ raise FactorRejected(factor_type)
try:
- authenticator = adapter.complete_enroll(request, data)
- except (ValueError, TypeError, KeyError) as exc:
+ # The savepoint lets a lost race (two submissions that both passed
+ # the check above) fail at the constraint without breaking the
+ # surrounding transaction, e.g. under ATOMIC_REQUESTS.
+ with transaction.atomic():
+ authenticator = adapter.complete_enroll(request, data)
+ except (ValueError, TypeError, KeyError, IntegrityError) as exc:
raise FactorRejected(factor_type) from exc
session.mark_verified(request, factor_type)
diff --git a/django_mfa/middleware.py b/django_mfa/middleware.py
index f424a0f..ca58a62 100644
--- a/django_mfa/middleware.py
+++ b/django_mfa/middleware.py
@@ -1,3 +1,5 @@
+import functools
+
from django.contrib.auth.views import redirect_to_login
from django.shortcuts import resolve_url
from django.urls import reverse
@@ -105,7 +107,27 @@ def process_request(self, request):
if not request.user.is_authenticated:
return None
- if session.is_pending(request):
+ # Both rungs may need this answer, and it is a query, so it is asked
+ # at most once per request. It is also asked only when a rung reaches
+ # it, which a verified session never does with MFA_REQUIRED off.
+ @functools.cache
+ def has_primary_factor():
+ return registry.has_primary_factor(request.user)
+
+ # Pending (stamped at login, not yet passed), or never challenged at
+ # all while the user holds a factor. The second is a session opened
+ # before its user enrolled, since signals.stamp_pending_verification
+ # skips a factorless user and nothing else stamps it; or one that
+ # missed the signal entirely. Letting it through would leave whoever
+ # opened it inside after the user enrolls, quite possibly in order
+ # to lock that person out. decorators.enforcement_state() treats the
+ # two cases the same way.
+ #
+ # is_verified() first, so a verified session decides this from the
+ # session alone. The query lands on sessions that never passed a
+ # challenge, which in practice means users who have not enrolled.
+ if session.is_pending(request) or (
+ not session.is_verified(request) and has_primary_factor()):
if (self._is_exempt(request.path, self.exempt_paths())
or self.is_api_request(request)):
return None
@@ -124,16 +146,17 @@ def process_request(self, request):
# single authenticated request just to build a list this branch
# immediately discards.
#
- # policy.resolve() gates the other two so MFA_REQUIRED = False (the
- # default) still costs nothing: has_primary_factor() is a query, so
- # it cannot be the unconditional first operand or every authenticated
- # request pays it even with MFA_REQUIRED off. Once past that gate,
- # has_primary_factor() runs before mfa_required_for() so the
+ # policy.resolve() gates the other two so that, with MFA_REQUIRED =
+ # False (the default), this rung costs nothing: has_primary_factor()
+ # is a query, so it cannot be the unconditional first operand or every
+ # verified request pays it even with MFA_REQUIRED off. Once past that
+ # gate, has_primary_factor() runs before mfa_required_for() so the
# exemption lookup inside mfa_required_for() runs only for a user who
# is actually about to be walled, not for every enrolled user this
- # policy applies to.
+ # policy applies to. For a never-challenged session the rung above
+ # has already asked, and this reuses its answer.
if (policy.resolve()
- and not registry.has_primary_factor(request.user)
+ and not has_primary_factor()
and policy.mfa_required_for(request.user)):
if (self._is_exempt(request.path, self.enrollment_exempt_paths())
or self.is_api_request(request)):
diff --git a/django_mfa/notifications.py b/django_mfa/notifications.py
index 66d9e23..e535082 100644
--- a/django_mfa/notifications.py
+++ b/django_mfa/notifications.py
@@ -89,7 +89,15 @@ def notify_factor_removed(sender, user, factor_type, name, request=None,
# derived here rather than emitted as its own event. has_primary_factor,
# not primary_enabled_for: only the yes/no answer is needed to decide
# whether to send mfa_disabled.
- if not registry.has_primary_factor(user):
+ #
+ # Only the removal of a primary factor can turn MFA off. Without that
+ # condition, removing recovery codes from a user who already had no
+ # primary factor said so again: manage.py mfa_reset removes every row in
+ # turn, and sent this once more after the last primary factor went.
+ # `sender` is the adapter class, or None for a type no longer registered,
+ # which never counted towards has_primary_factor() either.
+ if (sender is not None and sender.counts_as_primary_factor
+ and not registry.has_primary_factor(user)):
_notify(user, "mfa_disabled", {"user": user})
diff --git a/django_mfa/static/django_mfa/webauthn.js b/django_mfa/static/django_mfa/webauthn.js
index ddd5628..0b16ef7 100644
--- a/django_mfa/static/django_mfa/webauthn.js
+++ b/django_mfa/static/django_mfa/webauthn.js
@@ -147,17 +147,49 @@
});
}
+ // POST a passwordless assertion and go where the server says.
+ //
+ // Not form.submit(), unlike runCeremony(): the login page belongs to the
+ // host project, and mfa:passkey_complete answers a rejected passkey with
+ // a JSON error, which a plain form post would put on screen as raw JSON
+ // in place of the login page. Asking for JSON keeps the user where they
+ // are; the error is thrown with passkeyRejected set so the callers below
+ // can show it in #webauthn-passkey-error. On success the server answers
+ // with the destination ({"redirect": url}) rather than a redirect, which
+ // fetch() would follow in the background and so load that page twice.
+ function submitPasskey(form) {
+ return fetch(form.action, {
+ method: "POST",
+ body: new FormData(form),
+ credentials: "same-origin",
+ headers: {"Accept": "application/json"}
+ }).then(function (response) {
+ // A body that is not JSON (a CSRF failure page, a proxy error) is
+ // reported with the generic message rather than a parse error.
+ return response.json().catch(function () {
+ return {};
+ }).then(function (body) {
+ if (response.ok && body.redirect) {
+ window.location.assign(body.redirect);
+ return;
+ }
+ var err = new Error(body.error || "Passkey sign-in failed.");
+ err.passkeyRejected = true;
+ throw err;
+ });
+ });
+ }
+
// Passwordless (passkey) login. Unlike runCeremony() above, there is no
// page-embedded {% webauthn_options_script %} to read: the login page
// belongs to the host project, not django_mfa, and no per-request user is
// known yet to have rendered options for in the first place. Options are
// instead fetched from mfa:passkey_begin, an ordinary GET the host page
// wires up via the form's data-begin-url attribute (see this function's
- // caller below). The rest -- decodeOptions/navigator.credentials.get/
- // encodeCredential/form.submit -- is identical in shape to runCeremony(),
- // deliberately reusing the exact same helpers rather than a second set,
- // so the base64url<->ArrayBuffer conversion stays defined in exactly one
- // place.
+ // caller below). decodeOptions/navigator.credentials.get/encodeCredential
+ // are the same helpers runCeremony() uses, so the base64url<->ArrayBuffer
+ // conversion stays defined in exactly one place; the result is sent by
+ // submitPasskey() above.
function runPasskeyLogin(form) {
var beginUrl = form.getAttribute("data-begin-url");
return fetch(beginUrl, {credentials: "same-origin"})
@@ -174,13 +206,13 @@
.then(function (credential) {
form.querySelector("[name=credential]").value =
JSON.stringify(encodeCredential(credential));
- form.submit();
+ return submitPasskey(form);
});
}
// Conditional-mediation ("passkey autofill") variant of runPasskeyLogin.
//
- // Same fetch/decode/get/encode/submit shape, with two additions that are
+ // Same fetch/decode/get/encode/submitPasskey shape, with two additions that are
// what make it autofill rather than a modal prompt:
//
// mediation: "conditional" -- do not show a modal. The promise stays
@@ -217,7 +249,7 @@
.then(function (credential) {
form.querySelector("[name=credential]").value =
JSON.stringify(encodeCredential(credential));
- form.submit();
+ return submitPasskey(form);
});
}
@@ -299,6 +331,18 @@
conditionalAbort = new AbortController();
runConditionalPasskeyLogin(passkeyForm, conditionalAbort)
.catch(function (err) {
+ // The user did choose a passkey, and the server refused it:
+ // that is an answer to something they did, so show it. Autofill
+ // is not restarted here. The button is still there, and where
+ // prompts are answered without a person (a virtual
+ // authenticator, some password managers) a restart would retry
+ // the refused passkey in a loop.
+ if (err && err.passkeyRejected) {
+ if (passkeyError) {
+ passkeyError.textContent = err.message;
+ }
+ return;
+ }
// AbortError is the normal, expected outcome every time the
// button takes over -- reporting it would put "signal is
// aborted without reason" in front of a user who did nothing
diff --git a/django_mfa/tests/support/mixin_admin_urls.py b/django_mfa/tests/support/mixin_admin_urls.py
new file mode 100644
index 0000000..f6b8a3a
--- /dev/null
+++ b/django_mfa/tests/support/mixin_admin_urls.py
@@ -0,0 +1,19 @@
+"""A URLconf whose only admin is a project-built site using MfaAdminMixin.
+
+Kept in a module of its own, imported by nothing but the resolver, so a test
+can prove check_admin_stepup() loads the URLconf before looking for one.
+"""
+
+from django.contrib.admin import AdminSite
+from django.urls import path
+
+from django_mfa.admin_site import MfaAdminMixin
+
+
+class StaffSite(MfaAdminMixin, AdminSite):
+ pass
+
+
+site = StaffSite(name="staff_admin")
+
+urlpatterns = [path("staff/", site.urls)]
diff --git a/django_mfa/tests/test_adapter_totp.py b/django_mfa/tests/test_adapter_totp.py
index a4fef83..788311d 100644
--- a/django_mfa/tests/test_adapter_totp.py
+++ b/django_mfa/tests/test_adapter_totp.py
@@ -4,11 +4,11 @@
import random
from django.contrib.auth.models import User
-from django.test import RequestFactory, TestCase
+from django.test import RequestFactory, TestCase, override_settings
from django_mfa import totp as totp_mod
from django_mfa.adapters.totp import TOTPAdapter, generate_secret
-from django_mfa.crypto import decrypt
+from django_mfa.crypto import decrypt, encrypt
from django_mfa.models import Authenticator
@@ -55,6 +55,25 @@ def test_complete_verify_accepts_current_code(self):
self.assertTrue(self.adapter.complete_verify(
self._request(), self.user, {"code": code}))
+ def test_complete_verify_fails_cleanly_when_no_key_reads_the_secret(self):
+ """A secret signed under MFA_SECRET_ENCRYPTION_KEYS that no
+ configured key can read (the key was rotated out, or the setting
+ removed) used to raise BadSignature out of the verify view as a 500.
+ It is a failed attempt, and an operator needs to hear about it."""
+ secret = generate_secret()
+ with override_settings(MFA_SECRET_ENCRYPTION_KEYS=["old-key"]):
+ stored = encrypt(secret)
+ Authenticator.objects.create(
+ user=self.user, type="totp", data={"secret": stored})
+
+ with override_settings(MFA_SECRET_ENCRYPTION_KEYS=["new-key"]), \
+ self.assertLogs("django_mfa.adapters.totp", "ERROR"):
+ verified = self.adapter.complete_verify(
+ self._request(), self.user,
+ {"code": totp_mod.TOTP(secret).now()})
+
+ self.assertFalse(verified)
+
def test_complete_verify_rejects_wrong_code(self):
Authenticator.objects.create(user=self.user, type="totp",
data={"secret": "JBSWY3DPEHPK3PXP"})
diff --git a/django_mfa/tests/test_api.py b/django_mfa/tests/test_api.py
index 827c0af..57144f4 100644
--- a/django_mfa/tests/test_api.py
+++ b/django_mfa/tests/test_api.py
@@ -278,6 +278,19 @@ def test_wrong_code_creates_nothing(self):
self.assertEqual(self.error_code(response), "invalid")
self.assertFalse(Authenticator.objects.filter(user=self.user).exists())
+ def test_a_second_authenticator_app_is_refused_not_a_500(self):
+ """The same refusal the HTML view gives, from the shared flow."""
+ for expected in (201, 400):
+ secret = self.body(self.post("enroll_begin",
+ factor_type="totp"))["secret_key"]
+ response = self.post("enroll_complete", factor_type="totp",
+ body={"secret_key": secret,
+ "code": code_for(secret)})
+ self.assertEqual(response.status_code, expected)
+ self.assertEqual(self.error_code(response), "invalid")
+ self.assertEqual(Authenticator.objects.filter(
+ user=self.user, type="totp").count(), 1)
+
def test_recovery_codes_are_not_enrollable(self):
"""They are generated, not enrolled -- the same 404 the HTML view
gives a hand-typed URL."""
diff --git a/django_mfa/tests/test_conf.py b/django_mfa/tests/test_conf.py
index cab3012..876fdee 100644
--- a/django_mfa/tests/test_conf.py
+++ b/django_mfa/tests/test_conf.py
@@ -1,5 +1,6 @@
import datetime
from unittest.mock import patch
+from weakref import WeakSet
from django.test import TestCase, override_settings
@@ -165,9 +166,34 @@ def test_both_together_is_fine(self):
@override_settings(MFA_ADMIN_STEPUP=True)
def test_stepup_without_protect_admin_is_an_error(self):
- errors = check_admin_stepup(app_configs=None)
+ with patch("django.contrib.admin.sites.all_sites", WeakSet()):
+ errors = check_admin_stepup(app_configs=None)
self.assertEqual([e.id for e in errors], ["django_mfa.E011"])
+ @override_settings(MFA_ADMIN_STEPUP=True,
+ ROOT_URLCONF="django_mfa.tests.support.mixin_admin_urls")
+ def test_a_mixin_site_only_the_urlconf_creates_is_found(self):
+ """Checks run in no fixed order, so the URLconf that creates a
+ project's own site may not be imported yet. The check loads it."""
+ self.assertEqual(check_admin_stepup(app_configs=None), [])
+
+ @override_settings(MFA_ADMIN_STEPUP=True)
+ def test_stepup_with_an_mfa_admin_mixin_site_is_fine(self):
+ """A project that mounts its own AdminSite with MfaAdminMixin, and
+ leaves the default site alone, gets step-up from MFA_ADMIN_STEPUP:
+ the mixin reads it. E011 used to refuse that setup."""
+ from django.contrib.admin import AdminSite
+
+ from django_mfa.admin_site import MfaAdminMixin
+
+ class Site(MfaAdminMixin, AdminSite):
+ pass
+
+ site = Site(name="mfa_e011_check")
+ with patch("django.contrib.admin.sites.all_sites",
+ WeakSet([site])):
+ self.assertEqual(check_admin_stepup(app_configs=None), [])
+
class MfaFactorsAdapterRegistrationTests(TestCase):
"""MFA_FACTORS controls which built-in adapters get registered --
diff --git a/django_mfa/tests/test_enforcement.py b/django_mfa/tests/test_enforcement.py
index 112d349..77696b9 100644
--- a/django_mfa/tests/test_enforcement.py
+++ b/django_mfa/tests/test_enforcement.py
@@ -63,6 +63,59 @@ def test_verified_session_passes_through(self):
self.assertEqual(response.status_code, 200)
+class SessionOpenedBeforeEnrollmentTests(TestCase):
+ """A session opened while its user held no factor is never stamped
+ (signals.stamp_pending_verification deliberately skips a factorless
+ user), so it carries no `mfa` key at all. Once that user enrolls, the session
+ must be challenged exactly like a pending one. Otherwise whoever opened
+ it keeps every page MfaMiddleware alone protects, and that is precisely
+ the person a user enrolling because "someone is in my account" is trying
+ to lock out.
+ """
+
+ def setUp(self):
+ self.user = User.objects.create_user("a@example.com", password="pw")
+ self.client = Client()
+ self.client.login(username="a@example.com", password="pw")
+
+ def test_is_challenged_once_the_user_enrolls(self):
+ Authenticator.objects.create(user=self.user, type="totp")
+ response = self.client.get(reverse("mfa:security_settings"))
+ self.assertEqual(response.status_code, 302)
+ self.assertIn(reverse("mfa:verify"), response.url)
+ self.assertIn("next=" + reverse("mfa:security_settings"), response.url)
+
+ def test_recovery_codes_alone_do_not_trigger_a_challenge(self):
+ # Not a primary factor, so not something to challenge with. The login
+ # signal applies the same rule.
+ Authenticator.objects.create(user=self.user, type="recovery_codes")
+ response = self.client.get(reverse("mfa:security_settings"))
+ self.assertEqual(response.status_code, 200)
+
+ def test_verify_page_stays_reachable(self):
+ # Otherwise the challenge redirects to itself, forever.
+ Authenticator.objects.create(user=self.user, type="totp")
+ response = self.client.get(reverse("mfa:verify_factor", args=["totp"]))
+ self.assertEqual(response.status_code, 200)
+
+ @override_settings(MFA_EXEMPT_PATHS=["/logout/"])
+ def test_exempt_paths_stay_reachable(self):
+ Authenticator.objects.create(user=self.user, type="totp")
+ response = self.client.get("/logout/")
+ # Not redirected: the request falls through to URL resolution, and
+ # the suite's URLconf has no /logout/.
+ self.assertEqual(response.status_code, 404)
+
+ @override_settings(ROOT_URLCONF="django_mfa.tests.support.api_urls")
+ def test_api_is_left_to_its_own_gate(self):
+ # A 302 to an HTML page is no answer a JSON client can act on; the
+ # API's endpoint() decorator gates these URLs itself.
+ Authenticator.objects.create(user=self.user, type="totp")
+ response = self.client.get(reverse("mfa_api:state"))
+ self.assertEqual(response.status_code, 200)
+ self.assertFalse(response.json()["verified"])
+
+
@override_settings(MFA_REMEMBER_MY_BROWSER=True, MFA_REMEMBER_DAYS=30)
class RememberMyBrowserEnforcementTests(TestCase):
"""Fix round 1, finding 1: MFA_REMEMBER_MY_BROWSER was retained by the
@@ -459,3 +512,37 @@ def test_requiring_mfa_costs_exactly_one_extra_query(self):
"MFA_REQUIRED=False (has_primary_factor's own .exists()), not "
"one per registered adapter. Queries when required: "
f"{[q['sql'] for q in required.captured_queries]}")
+
+
+class NeverChallengedQueryCostTests(TestCase):
+ """What SessionOpenedBeforeEnrollmentTests costs. Telling a session that
+ was never challenged apart from one whose user simply has no factor
+ takes one query, so that query must run only for a session that has not
+ passed a challenge, and only once per request.
+ """
+
+ def setUp(self):
+ self.user = User.objects.create_user("a@example.com", password="pw")
+ self.client = Client()
+ self.client.login(username="a@example.com", password="pw")
+
+ def authenticator_queries(self):
+ table = Authenticator._meta.db_table
+ with CaptureQueriesContext(connection) as queries:
+ self.client.get("/some/other/page/")
+ return [q["sql"] for q in queries.captured_queries if table in q["sql"]]
+
+ def test_verified_session_never_asks(self):
+ Authenticator.objects.create(user=self.user, type="totp")
+ session = self.client.session
+ session["mfa"] = {"verified": True, "method": "totp", "at": 0}
+ session.save()
+ self.assertEqual(self.authenticator_queries(), [])
+
+ def test_never_challenged_session_asks_once(self):
+ self.assertEqual(len(self.authenticator_queries()), 1)
+
+ @override_settings(MFA_REQUIRED=True)
+ def test_never_challenged_session_asks_once_when_mfa_is_required(self):
+ # The enrollment wall needs the same answer; it must not ask again.
+ self.assertEqual(len(self.authenticator_queries()), 1)
diff --git a/django_mfa/tests/test_notifications.py b/django_mfa/tests/test_notifications.py
index 8cb5fce..8cfedfc 100644
--- a/django_mfa/tests/test_notifications.py
+++ b/django_mfa/tests/test_notifications.py
@@ -1,8 +1,10 @@
+import io
import time
from unittest import mock
from django.contrib.auth.models import User
from django.core import mail
+from django.core.management import call_command
from django.test import Client, TestCase, override_settings
from django.urls import reverse
@@ -120,6 +122,23 @@ def test_removing_the_last_primary_factor_also_says_mfa_is_off(self):
bodies = " ".join(m.body for m in mail.outbox)
self.assertIn("no longer", bodies)
+ def test_mfa_is_off_is_sent_once_however_many_factors_go(self):
+ """manage.py mfa_reset removes every row in turn. Only the removal
+ that leaves no primary factor turns MFA off; removing recovery codes
+ after that changes nothing and must not say so again."""
+ Authenticator.objects.create(
+ user=self.user, type="totp",
+ data={"secret": encrypt(generate_secret())})
+ Authenticator.objects.create(
+ user=self.user, type="webauthn", name="Yubikey", data={})
+ RecoveryCodesAdapter().generate(self.user)
+ mail.outbox.clear()
+
+ call_command("mfa_reset", "ashwin", "--yes", stdout=io.StringIO())
+
+ off = [m for m in mail.outbox if "no longer" in m.body]
+ self.assertEqual(len(off), 1)
+
def test_spending_a_recovery_code_reports_the_remaining_count(self):
codes = RecoveryCodesAdapter().generate(self.user)
Authenticator.objects.create(
diff --git a/django_mfa/tests/test_passwordless.py b/django_mfa/tests/test_passwordless.py
index 5a23989..4d40dfe 100644
--- a/django_mfa/tests/test_passwordless.py
+++ b/django_mfa/tests/test_passwordless.py
@@ -32,6 +32,7 @@
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec
+from django.conf import settings
from django.contrib.auth import login as auth_login
from django.contrib.auth.models import User
from django.contrib.sessions.backends.db import SessionStore
@@ -41,11 +42,12 @@
from fido2.webauthn import AuthenticatorData
from django_mfa import events
-from django_mfa.backends import user_from_handle, user_handle_for
+from django_mfa.backends import WebAuthnBackend, user_from_handle, user_handle_for
from django_mfa.conf import settings as mfa_settings
from django_mfa.middleware import MfaMiddleware
from django_mfa.models import Authenticator
from django_mfa.tests.support.authenticator import SoftwareAuthenticator
+from django_mfa.views.verify import _passkey_failure
FLAG_UP = AuthenticatorData.FLAG.UP
@@ -213,6 +215,72 @@ def test_unknown_credential_does_not_reveal_account_existence(self):
self.assertEqual(response.status_code, 400)
self.assertNotIn("a@example.com", response.content.decode())
+ # -- An inactive account is refused, as ModelBackend refuses it ----------
+
+ def _passkey_post(self, **extra):
+ begin = self.client.get(reverse("mfa:passkey_begin"))
+ assertion = self.device.get(json.loads(begin.json()["options"]))
+ return self.client.post(reverse("mfa:passkey_complete"),
+ {"credential": json.dumps(assertion),
+ "next": "/home/"}, **extra)
+
+ def test_inactive_user_cannot_sign_in_with_a_passkey(self):
+ """Deactivating an account (is_active=False) is how Django turns a
+ user off. A password login is refused by ModelBackend; a passkey must
+ be refused too, with the same response as every other failure."""
+ self.user.is_active = False
+ self.user.save()
+
+ response = self._passkey_post()
+
+ self.assertEqual(response.status_code, 400)
+ self.assertEqual(response.content, _passkey_failure().content)
+ self.assertNotIn("_auth_user_id", self.client.session)
+
+ def test_deactivating_a_user_ends_their_passkey_session(self):
+ self._passkey_post()
+ self.assertEqual(
+ self.client.get(reverse("mfa:security_settings")).status_code, 200)
+
+ self.user.is_active = False
+ self.user.save()
+
+ response = self.client.get(reverse("mfa:security_settings"))
+ self.assertEqual(response.status_code, 302)
+ self.assertIn(settings.LOGIN_URL, response.url)
+
+ def test_backend_refuses_an_inactive_user(self):
+ self.user.is_active = False
+ self.user.save()
+ backend = WebAuthnBackend()
+ self.assertIsNone(backend.get_user(self.user.pk))
+ self.assertIsNone(backend.authenticate(None, mfa_user=self.user))
+
+ # -- webauthn.js posts with fetch() and asks for JSON ----------------------
+
+ def test_a_script_asking_for_json_gets_the_destination_as_json(self):
+ """webauthn.js posts the assertion with fetch() so a failure can be
+ shown on the login page. On success it needs the destination as
+ data: following the redirect inside fetch() would load the landing
+ page once for nothing (and consume any one-time messages on it)."""
+ response = self._passkey_post(HTTP_ACCEPT="application/json")
+
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.json(), {"redirect": "/home/"})
+ self.assertEqual(int(self.client.session["_auth_user_id"]), self.user.pk)
+
+ def test_a_form_post_is_still_redirected(self):
+ response = self._passkey_post()
+ self.assertEqual(response.status_code, 302)
+ self.assertEqual(response.url, "/home/")
+
+ def test_a_failure_asked_for_as_json_is_the_usual_failure(self):
+ self.user.is_active = False
+ self.user.save()
+ response = self._passkey_post(HTTP_ACCEPT="application/json")
+ self.assertEqual(response.status_code, 400)
+ self.assertEqual(response.content, _passkey_failure().content)
+
def test_every_named_failure_mode_returns_a_byte_identical_response(self):
"""unknown handle, unknown credential, bad signature, missing
state, and tampered payload must all be indistinguishable to the
diff --git a/django_mfa/tests/test_views.py b/django_mfa/tests/test_views.py
index 906b98c..4b31683 100644
--- a/django_mfa/tests/test_views.py
+++ b/django_mfa/tests/test_views.py
@@ -14,6 +14,7 @@
from django.urls import NoReverseMatch, reverse
from django_mfa import totp as totp_mod
+from django_mfa.adapters.totp import TOTPAdapter
from django_mfa.adapters.webauthn import WebAuthnAdapter
from django_mfa.crypto import encrypt
from django_mfa.models import Authenticator, RateLimitCounter
@@ -34,6 +35,31 @@ def setUp(self):
self.client = Client()
self.client.login(username="a@example.com", password="pw")
+ def _stamp_pending(self):
+ session = self.client.session
+ session["mfa"] = {"verified": False, "method": None, "at": None}
+ session.save()
+
+ def test_pending_session_with_no_methods_left_continues_to_next(self):
+ """A session stamped pending at login whose user then lost every
+ factor (manage.py mfa_reset, or MFA_FACTORS narrowed) has nothing to
+ answer the challenge with. A fresh login would not be challenged at
+ all, so the stale stamp is dropped instead of rendering an empty
+ picker the user cannot leave."""
+ self._stamp_pending()
+
+ response = self.client.get(reverse("mfa:verify") + "?next=/somewhere/")
+
+ self.assertRedirects(response, "/somewhere/",
+ fetch_redirect_response=False)
+ self.assertNotIn("mfa", self.client.session)
+
+ def test_pending_session_with_no_methods_left_and_no_next(self):
+ self._stamp_pending()
+ response = self.client.get(reverse("mfa:verify"))
+ self.assertRedirects(response, "/accounts/profile/",
+ fetch_redirect_response=False)
+
def test_single_factor_redirects_straight_to_it(self):
Authenticator.objects.create(user=self.user, type="totp")
response = self.client.get(reverse("mfa:verify"))
@@ -146,6 +172,31 @@ def _enroll_totp(self):
return self.client.post(reverse("mfa:enroll_factor", args=["totp"]),
{"secret_key": secret, "code": code})
+ def test_enrolling_a_second_authenticator_app_is_refused(self):
+ """TOTP is one per user. A second submission (a double-click, a
+ hand-typed URL, a stale tab) used to hit the database constraint and
+ return a 500."""
+ self._enroll_totp()
+
+ response = self._enroll_totp()
+
+ self.assertEqual(response.status_code, 400)
+ self.assertEqual(Authenticator.objects.filter(
+ user=self.user, type="totp").count(), 1)
+
+ def test_losing_a_race_to_enroll_is_refused(self):
+ """Two submissions that both pass the availability check: the
+ database constraint stops the second, and that must read as a
+ refused attempt rather than a 500."""
+ self._enroll_totp()
+
+ with patch.object(TOTPAdapter, "is_available", return_value=True):
+ response = self._enroll_totp()
+
+ self.assertEqual(response.status_code, 400)
+ self.assertEqual(Authenticator.objects.filter(
+ user=self.user, type="totp").count(), 1)
+
def test_get_renders_enroll_template_with_secret_and_uri(self):
response = self.client.get(reverse("mfa:enroll_factor", args=["totp"]))
self.assertEqual(response.status_code, 200)
@@ -385,8 +436,24 @@ def setUp(self):
self.client = Client()
self.client.login(username="a@example.com", password="pw")
+ def enroll(self, **fields):
+ """Give the user a factor the way enrolling one in this session would.
+
+ A real enrollment verifies the session it runs in (flows.attempt_enroll
+ calls session.mark_verified). A bare row created behind the session's
+ back leaves it never challenged, which MfaMiddleware sends to
+ mfa:verify (see test_enforcement.SessionOpenedBeforeEnrollmentTests),
+ and these tests are about the page, not that gate.
+ """
+ auth = Authenticator.objects.create(user=self.user, **fields)
+ session = self.client.session
+ session["mfa"] = {"verified": True, "method": auth.type,
+ "at": int(time.time())}
+ session.save()
+ return auth
+
def test_renders_enabled_available_and_remaining(self):
- Authenticator.objects.create(user=self.user, type="totp")
+ self.enroll(type="totp")
response = self.client.get(reverse("mfa:security_settings"))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "django_mfa/security.html")
@@ -436,47 +503,44 @@ def test_page_lists_authenticator_with_a_removal_form(self):
authenticator's own pk) must actually be present in the rendered
page, not just work if you already know the URL and pk.
"""
- auth = Authenticator.objects.create(user=self.user, type="totp")
+ auth = self.enroll(type="totp")
response = self.client.get(reverse("mfa:security_settings"))
content = response.content.decode()
self.assertIn(reverse("mfa:manage"), content)
self.assertIn(f'value="{auth.pk}"', content)
def test_a_user_can_delete_their_own_authenticator_through_the_rendered_page(self):
- auth = Authenticator.objects.create(user=self.user, type="totp")
+ auth = self.enroll(type="totp")
get_response = self.client.get(reverse("mfa:security_settings"))
self.assertIn(f'value="{auth.pk}"', get_response.content.decode())
- # mfa:manage is gated by mfa_recent_required -- give this session a
- # fresh stamp so the delete below exercises manage_factors itself
- # rather than the gate (covered by test_stepup.py's GatedViewTests).
- session = self.client.session
- session["mfa"] = {"verified": True, "method": "totp",
- "at": int(time.time())}
- session.save()
+ # mfa:manage is gated by mfa_recent_required. enroll() left this
+ # session freshly verified, so the delete below exercises
+ # manage_factors itself rather than the gate (covered by
+ # test_stepup.py's GatedViewTests).
post_response = self.client.post(reverse("mfa:manage"), {"pk": auth.pk})
self.assertRedirects(post_response, reverse("mfa:security_settings"))
self.assertFalse(Authenticator.objects.filter(pk=auth.pk).exists())
def test_webauthn_credential_lists_its_own_name_and_created_date(self):
- auth = Authenticator.objects.create(
- user=self.user, type="webauthn", name="YubiKey 5C")
+ auth = self.enroll(
+ type="webauthn", name="YubiKey 5C")
response = self.client.get(reverse("mfa:security_settings"))
content = response.content.decode()
self.assertIn("YubiKey 5C", content)
self.assertIn(str(auth.created_at.year), content)
def test_webauthn_removal_form_present_when_not_enterprise_owned(self):
- auth = Authenticator.objects.create(
- user=self.user, type="webauthn", name="key")
+ auth = self.enroll(
+ type="webauthn", name="key")
response = self.client.get(reverse("mfa:security_settings"))
self.assertIn(f'value="{auth.pk}"', response.content.decode())
@override_settings(MFA_OWNED_BY_ENTERPRISE=True)
def test_webauthn_removal_form_absent_when_enterprise_owned(self):
- auth = Authenticator.objects.create(
- user=self.user, type="webauthn", name="key")
+ auth = self.enroll(
+ type="webauthn", name="key")
response = self.client.get(reverse("mfa:security_settings"))
content = response.content.decode()
# Still listed (name visible)...
@@ -490,7 +554,7 @@ def test_totp_removal_form_still_present_when_enterprise_owned(self):
manage_factors in views/manage.py) -- the page must reflect that,
not blanket-hide every removal form.
"""
- auth = Authenticator.objects.create(user=self.user, type="totp")
+ auth = self.enroll(type="totp")
response = self.client.get(reverse("mfa:security_settings"))
self.assertIn(f'value="{auth.pk}"', response.content.decode())
@@ -1053,6 +1117,14 @@ def test_posts_credential_via_form_submit(self):
self.assertIn("name=credential", self.source)
self.assertIn("form.submit()", self.source)
+ def test_passkey_login_reports_a_rejected_assertion_in_the_page(self):
+ """A passkey the server rejects must not navigate the user onto the
+ endpoint's bare JSON error. The passkey path posts with fetch(),
+ asks for JSON, and goes to the destination it is handed."""
+ self.assertIn('"Accept": "application/json"', self.source)
+ self.assertIn("body.redirect", self.source)
+ self.assertIn("passkeyRejected", self.source)
+
def test_uses_get_client_extension_results_method_not_a_property(self):
"""credential.clientExtensionResults is not a real property on the
PublicKeyCredential navigator.credentials.create() resolves with --
diff --git a/django_mfa/views/picker.py b/django_mfa/views/picker.py
index ba39d68..0af4868 100644
--- a/django_mfa/views/picker.py
+++ b/django_mfa/views/picker.py
@@ -1,9 +1,11 @@
from urllib.parse import urlencode
+from django.conf import settings
from django.contrib.auth.decorators import login_required
-from django.shortcuts import redirect, render
+from django.shortcuts import redirect, render, resolve_url
from django.urls import reverse
+from django_mfa import session
from django_mfa.conf import settings as mfa_settings
from django_mfa.registry import registry
from django_mfa.views.verify import safe_next_or_none
@@ -17,6 +19,17 @@ def verify(request):
# asked for, and the step-up gate (decorators.mfa_recent_required) can
# never return anyone to the view it interrupted.
next_url = safe_next_or_none(request)
+ if not adapters:
+ # Nothing to verify with: every factor went after this session was
+ # stamped pending at login (manage.py mfa_reset, or MFA_FACTORS
+ # narrowed). A fresh login would not be challenged at all, since the
+ # login receiver only stamps a user who holds a primary factor, so the
+ # stale stamp is dropped instead of rendering a picker with no choices
+ # and no way out. MfaMiddleware then decides from what the user holds
+ # now; under MFA_REQUIRED that is the enrollment wall.
+ if session.is_pending(request):
+ session.reset(request)
+ return redirect(next_url or resolve_url(settings.LOGIN_REDIRECT_URL))
if len(adapters) == 1:
url = reverse("mfa:verify_factor", args=[adapters[0].type])
if next_url:
diff --git a/django_mfa/views/verify.py b/django_mfa/views/verify.py
index 089b3e9..51b0e83 100644
--- a/django_mfa/views/verify.py
+++ b/django_mfa/views/verify.py
@@ -12,7 +12,7 @@
from django_mfa import events, flows, session
from django_mfa.adapters.webauthn import AUTH_STATE_KEY, WebAuthnAdapter, get_server
-from django_mfa.backends import WebAuthnBackend, user_from_handle
+from django_mfa.backends import WebAuthnBackend, user_can_authenticate, user_from_handle
from django_mfa.conf import settings as mfa_settings
from django_mfa.models import Authenticator
from django_mfa.registry import registry
@@ -223,7 +223,9 @@ def resolve_passkey_assertion(request, credential):
user = user_from_handle(user_handle.decode("utf-8"))
except UnicodeDecodeError:
user = None
- if user is None:
+ # An inactive account fails exactly like an unknown handle: telling the
+ # two apart would reveal which handles belong to disabled accounts.
+ if user is None or not user_can_authenticate(user):
return None
request.session[AUTH_STATE_KEY] = state
@@ -276,6 +278,13 @@ def passkey_complete(request):
POST only. The ceremony itself is resolve_passkey_assertion() above,
shared with the JSON API; everything here is the browser rendering of
its answer -- one generic 400 for every failure, a redirect on success.
+
+ webauthn.js posts here with fetch() and asks for JSON, so that a
+ rejected passkey is reported on the login page instead of navigating
+ the user to the bare JSON error. It then navigates itself, so on
+ success it is handed the destination rather than a redirect, which
+ fetch() would follow in the background and load the landing page for
+ nothing. A plain form post still gets the redirect.
"""
if request.method != "POST":
return HttpResponseNotAllowed(["POST"])
@@ -288,6 +297,8 @@ def passkey_complete(request):
return _passkey_failure()
auth.login(request, user, backend=BACKEND_PATH)
+ if "application/json" in request.headers.get("Accept", ""):
+ return JsonResponse({"redirect": _safe_next(request)})
return redirect(_safe_next(request))
diff --git a/docs/_static/custom.css b/docs/_static/custom.css
new file mode 100644
index 0000000..65071d4
--- /dev/null
+++ b/docs/_static/custom.css
@@ -0,0 +1,71 @@
+/* Small additions on top of Furo. Colours follow the brand values set in
+ conf.py's html_theme_options, so sphinx-design's cards and tabs match the
+ theme instead of using that extension's default blue. */
+
+:root {
+ --sd-color-primary: #0c4b33;
+ --sd-color-primary-highlight: #0a3d29;
+ --sd-color-tabs-label-active: #0c4b33;
+ --sd-color-tabs-underline-active: #0c4b33;
+ --sd-color-tabs-label-hover: #0c6e4a;
+ --sd-color-tabs-underline-hover: #0c6e4a;
+}
+
+body[data-theme="dark"] {
+ --sd-color-primary: #5fd4a0;
+ --sd-color-primary-highlight: #7fe0b5;
+ --sd-color-tabs-label-active: #5fd4a0;
+ --sd-color-tabs-underline-active: #5fd4a0;
+ --sd-color-tabs-label-hover: #7fe0b5;
+ --sd-color-tabs-underline-hover: #7fe0b5;
+}
+
+@media (prefers-color-scheme: dark) {
+ body:not([data-theme="light"]) {
+ --sd-color-primary: #5fd4a0;
+ --sd-color-primary-highlight: #7fe0b5;
+ --sd-color-tabs-label-active: #5fd4a0;
+ --sd-color-tabs-underline-active: #5fd4a0;
+ --sd-color-tabs-label-hover: #7fe0b5;
+ --sd-color-tabs-underline-hover: #7fe0b5;
+ }
+}
+
+/* The landing page's opening paragraph. */
+.mfa-lead {
+ font-size: 1.2rem;
+ line-height: 1.6;
+ color: var(--color-foreground-secondary);
+ margin-bottom: 1.5rem;
+}
+
+.sd-card {
+ border-radius: 0.6rem;
+}
+
+.sd-card-title {
+ font-weight: 600;
+}
+
+.sd-card.sd-card-hover:hover {
+ border-color: var(--color-brand-primary);
+}
+
+/* Settings tables carry long names in their first column. Keep those on one
+ line so the table reads as name, default, purpose. */
+table.docutils td:first-child code {
+ white-space: nowrap;
+}
+
+/* Furo draws html_logo at the full sidebar width; keep it a mark, not a
+ poster. */
+.sidebar-logo {
+ max-width: 3.5rem;
+}
+
+/* Furo centres narrow tables; in a reference page that leaves them floating
+ away from the text that introduces them. */
+article table.docutils.align-default {
+ margin-left: 0;
+ margin-right: 0;
+}
diff --git a/docs/_static/logo.svg b/docs/_static/logo.svg
new file mode 100644
index 0000000..7ec0ade
--- /dev/null
+++ b/docs/_static/logo.svg
@@ -0,0 +1,6 @@
+
diff --git a/docs/api.md b/docs/api.md
index 9341b63..9886e9b 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -1,260 +1,346 @@
# Public API
-The Python surface a host project can depend on. Anything not listed here — the
-adapters' internals, `django_mfa.otp`, `django_mfa.totp`, the view functions
-themselves — is an implementation detail and may change without a deprecation cycle.
+The Python names a host project can rely on. Anything not on this page (adapter
+internals, `django_mfa.otp`, `django_mfa.totp`, `django_mfa.flows`, the view
+functions) is internal and can change without a deprecation period.
-## `django_mfa.session`
+The URL configurations are `django_mfa.urls` (namespace `mfa`) and the opt-in
+`django_mfa.api.urls` (namespace `mfa_api`). See {doc}`installation_setup` and
+{doc}`rest_api`.
-Read and write the MFA state on a session. **Always use these** rather than touching
-`request.session["mfa"]`: the dict's shape is not a public contract and has changed
-once already.
+## Session state: `django_mfa.session`
-| Function | Purpose |
-|---|---|
-| `is_verified(request)` | `True` if this session has completed a second factor. The one you'll actually use. |
-| `is_pending(request)` | `True` if the session is awaiting a second factor. |
-| `start_pending(request)` | Mark the session as awaiting verification. |
-| `mark_verified(request, method)` | Mark it satisfied by `method` (a factor type string). |
-| `verified_at(request)` | Unix timestamp of this session's last successful challenge, or `None`. |
-| `is_fresh(request, max_age)` | `True` if the session verified a factor within the last `max_age` seconds. A verified session with no `verified_at()` (e.g. one from before 4.2.0) counts as stale, not fresh — see {doc}`enforcement`'s step-up section. This is the primitive `mfa_recent_required`/`MfaRecentRequiredMixin` are built on; use it directly if you're writing your own step-up policy instead of the decorator/mixin. |
-| `reset(request)` | Remove MFA state entirely. |
-
-Example:
+Read and write MFA state through these functions, never through
+`request.session["mfa"]`. The shape of that value is not part of the API.
- from django_mfa import session
+```python
+# myapp/views.py
+from django_mfa import session
- if session.is_verified(request):
- ...
+if session.is_verified(request):
+ ...
+```
-You rarely need the writers: the `user_logged_in` receiver calls `start_pending()`
-and the verify view calls `mark_verified()`.
+| Function | Returns or does |
+|---|---|
+| `is_verified(request)` | `True` if this session has passed a second factor. Use this to decide whether to trust a session. |
+| `is_pending(request)` | `True` if the session was marked pending at login and has not passed yet. `False` for a session that was never marked, so `not is_pending()` does not mean verified. |
+| `verified_at(request)` | Unix timestamp (`int`) of the last successful challenge, or `None`. |
+| `is_fresh(request, max_age)` | `True` if the session passed a challenge within the last `max_age` seconds. A verified session with no timestamp counts as stale. |
+| `start_pending(request)` | Mark the session as waiting for a second factor. |
+| `mark_verified(request, method)` | Mark it verified by `method` (a factor type string) and record the time. |
+| `reset(request)` | Remove the MFA state from the session. |
-## `django_mfa.registry`
+You rarely need the last three: login marks the session pending, and the verify
+views mark it verified.
-The registry decides which factors exist and what each user holds. Import the
-singleton — do not construct your own:
+## Factors: `django_mfa.registry`
- from django_mfa.registry import registry
+```python
+from django_mfa.registry import registry
+```
| Method | Returns |
|---|---|
-| `primary_enabled_for(user)` | Adapters that mean this user **is protected**. Excludes recovery codes. **This is the predicate for "does this user have MFA".** |
-| `has_primary_factor(user)` | The same question as a `bool`, in **one** query rather than one per registered adapter. Use this when you only need yes/no — the enrollment wall, `@mfa_required` and the notification receivers all do, and on a busy site the difference is per request. Both methods read `Adapter.counts_as_primary_factor`, so they cannot disagree. |
-| `enabled_for(user)` | Adapters this user can **verify with right now**. Includes recovery codes. This is what to offer on a challenge screen. |
-| `available_for(user)` | Adapters the user could still **add**. Excludes singletons they already hold and factors that aren't enrolled at all. |
+| `has_primary_factor(user)` | `True` if the user holds a factor that protects them on its own: one whose adapter has `counts_as_primary_factor = True`, which for the built-ins is everything except recovery codes. One query. This is the answer to "does this user have MFA". |
+| `primary_enabled_for(user)` | The adapters behind that answer, as a list. One query per registered adapter. |
+| `enabled_for(user)` | Adapters the user can verify with now, including recovery codes. What a challenge screen offers. |
+| `available_for(user)` | Adapters the user could add now: enrollable factors, minus single-instance factors they already hold. Email is left out for a user with no usable address. |
| `all()` | Every registered adapter. |
-| `get(type)` | One adapter by type string. Raises `KeyError` if absent. |
-| `register(adapter)` | Add an adapter instance. Raises `ValueError` on a duplicate type. |
-| `unregister(type)` | Remove one. Raises `KeyError` if it wasn't registered. |
+| `get(type)` | The adapter for a type string. Raises `KeyError` if none is registered. |
+| `register(adapter)` | Register an adapter instance. Raises `ValueError` if its type is taken. |
+| `unregister(type)` | Remove an adapter. Raises `KeyError` if none is registered. |
+
+Never decide whether to challenge a user from `enabled_for()`. A user holding only
+recovery codes appears there but is not protected.
-The distinction between the first two is the one that matters. A user holding only
-recovery codes appears in `enabled_for()` but not `primary_enabled_for()`, because
-recovery codes are exhaustible and must never be someone's sole factor. Deciding
-whether to challenge from `enabled_for()` would challenge users you cannot protect;
-deciding what to offer from `primary_enabled_for()` would hide the recovery option
-from exactly the people who need it.
+`django_mfa.registry.Adapter` is the base class for a factor type; see
+{doc}`custom_factors`. The built-in adapters, which are also the `sender` of their
+signals, are `django_mfa.adapters.totp.TOTPAdapter`,
+`django_mfa.adapters.webauthn.WebAuthnAdapter`,
+`django_mfa.adapters.recovery_codes.RecoveryCodesAdapter` and
+`django_mfa.adapters.email.EmailAdapter`.
-`Adapter` is the base class for factor types — see {doc}`custom_factors`.
+## Models
-## `django_mfa.models.Authenticator`
+### `django_mfa.models.Authenticator`
One row per enrolled factor.
| Field | Notes |
|---|---|
-| `user` | FK to `AUTH_USER_MODEL`, related name `mfa_authenticators`. |
-| `type` | `"totp"`, `"webauthn"`, or `"recovery_codes"` — see `Authenticator.Type`. |
-| `name` | User-supplied label. WebAuthn only, so several keys are distinguishable. |
-| `data` | `JSONField` of factor-specific state. Shape is owned by the adapter; don't reach into it. |
-| `created_at`, `last_used_at` | Timestamps. `last_used_at` is `None` until first use. |
+| `user` | Foreign key to `AUTH_USER_MODEL`, related name `mfa_authenticators`. |
+| `type` | `"totp"`, `"webauthn"`, `"recovery_codes"` or `"email"`: `Authenticator.Type.TOTP`, `.WEBAUTHN`, `.RECOVERY_CODES`, `.EMAIL`. |
+| `name` | The label a user gives a security key or passkey. Empty for other types. |
+| `data` | `JSONField` owned by the adapter. It holds the TOTP secret in readable form, so never display or log it. |
+| `created_at`, `last_used_at` | `last_used_at` is `None` until the first successful verification. |
-`record_usage()` stamps `last_used_at`. Adapters call it on successful verification.
+- `record_usage()` sets `last_used_at` to now. Adapters call it after a successful
+ verification.
+- `Authenticator.objects.for_user(user)` returns that user's rows.
+- The database constraint `mfa_one_singleton_authenticator_per_user` allows at most
+ one `totp`, one `recovery_codes` and one `email` row per user. `webauthn` rows are
+ unlimited.
-A database constraint (`mfa_one_singleton_authenticator_per_user`) allows at most one
-`totp` and one `recovery_codes` row per user; WebAuthn is unlimited.
+To remove every factor a user holds, use `manage.py mfa_reset ` (see
+{doc}`operations`), which sends `factor_removed` for each row.
+`Authenticator.objects.filter(user=user).delete()` removes them without any signal.
-To remove a user's MFA — the administrative recovery path:
+### `django_mfa.models.MfaExemption`
- Authenticator.objects.filter(user=user).delete()
+An operator's exemption of one user from `MFA_REQUIRED`. It is created by
+`manage.py mfa_disable`, never by a web view; see {doc}`operations`.
-## `django_mfa.models.MfaExemption`
+| Field | Notes |
+|---|---|
+| `user` | One-to-one with `AUTH_USER_MODEL`, related name `mfa_exemption`. |
+| `reason` | Required text. |
+| `created_at` | When it was granted. |
+| `expires_at` | `None` for permanent. Otherwise the exemption stops applying at this time. |
-A user `MFA_REQUIRED` does not apply to, despite the predicate — see
-{doc}`enforcement`'s "Exempting a user" section. Written only by the
-`mfa_disable` management command (or by deleting the row, to revoke — see
-{doc}`operations`), never through a web view: exempting somebody from a
-security requirement is an operator action, not something a user can do to
-themselves.
+- `MfaExemption.objects.active_for(user)` returns the user's exemption if it is in
+ force now, else `None`.
+- `exemption.is_active()` is the same check on an instance.
-| Field | Notes |
+An exemption lifts `MFA_REQUIRED` only. It does not open views protected by
+`@mfa_required`.
+
+## Enforcement
+
+### `django_mfa.middleware.MfaMiddleware`
+
+Add it after `django.contrib.auth.middleware.AuthenticationMiddleware`. For an
+authenticated request it makes two checks, in this order:
+
+1. **Pending.** If the session is pending, or was never challenged while the user
+ holds a primary factor, it redirects to `mfa:verify`. The second case covers a
+ session opened before the user enrolled their first factor (since 4.6.1).
+ Exempt: the picker, each factor's verify page and `MFA_EXEMPT_PATHS`.
+2. **Required but not enrolled.** If `MFA_REQUIRED` applies to the user and they hold
+ no primary factor, it redirects to `mfa:security_settings`. Exempt: the enroll
+ pages, the recovery codes page, the security page and `MFA_EXEMPT_PATHS`.
+
+URLs in the JSON API's namespace pass both checks; the API applies them itself and
+answers with status codes. `MFA_EXEMPT_PATHS` matches `request.path` exactly. To
+skip a whole path prefix, subclass the middleware and override
+`process_request()` (see {doc}`recipes`). The middleware also sets and clears the
+`MFA_QUICKLOGIN` cookie. See {doc}`enforcement` for the full behaviour.
+
+### `django_mfa.decorators`
+
+| Name | Use |
|---|---|
-| `user` | `OneToOneField` to `AUTH_USER_MODEL`, related name `mfa_exemption`. |
-| `reason` | Required, free text. `mfa_disable` refuses to grant an exemption without one. |
-| `created_at` | Timestamp. |
-| `expires_at` | `None` means permanent. Otherwise the exemption stops applying once this passes. |
+| `@mfa_required` | The view needs a verified session. Sends an anonymous user to `LOGIN_URL`, a pending or never-challenged session to `mfa:verify`, and a user with no primary factor to `mfa:security_settings`. |
+| `MfaRequiredMixin` | The same for a class-based view. Put it before the view class in the bases. |
+| `@mfa_recent_required(max_age=None, next_url=None, allow_unenrolled=False)` | Everything `@mfa_required` checks, plus a challenge passed within `max_age` seconds (default `MFA_STEPUP_MAX_AGE`). Works bare or called. |
+| `MfaRecentRequiredMixin` | The same for a class-based view, configured with the attributes `mfa_stepup_max_age`, `mfa_stepup_next_url` and `mfa_allow_unenrolled`. |
-| Method | Returns |
+After a step-up challenge on a request other than `GET`, `HEAD`, `OPTIONS` or
+`TRACE`, the user is sent to `next_url` (default `mfa:security_settings`), because
+the request body cannot be replayed. `allow_unenrolled=True` lets a user with no
+factor through; use it only on a view that enrolls a first factor. See
+{doc}`enforcement`.
+
+### `django_mfa.policy`
+
+Who `MFA_REQUIRED` applies to. See {doc}`enforcement`.
+
+| Name | Returns |
|---|---|
-| `MfaExemption.objects.active_for(user)` | This user's exemption if it is currently in force (`expires_at` is `None` or in the future), else `None`. What `policy.mfa_required_for()` consults. |
-| `is_active()` | The same freshness check as an instance method, on an object you already have in hand. |
+| `mfa_required_for(user)` | `True` if `MFA_REQUIRED` selects the user (plus every `is_staff` user when `MFA_PROTECT_ADMIN` is on), their grace period is over, and they have no active `MfaExemption`. It does not check whether they hold a factor. |
+| `is_staff` | A predicate for `MFA_REQUIRED`: users with `is_staff` set. |
+| `in_groups(*names)` | A new predicate for users in any of the named groups. Call it: `MFA_REQUIRED = in_groups("admins", "finance")`. |
+| `required_at(user)` | When the requirement starts for this user: the later of `MFA_REQUIRED_FROM` and the user's grace anchor (`date_joined` unless `MFA_GRACE_ANCHOR` says otherwise) plus `MFA_GRACE_PERIOD`. `None` when neither applies. |
+| `grace_state(user)` | A `GraceState` while the user would be required to enroll but is still inside their grace period, else `None`. |
+| `GraceState` | A frozen dataclass with `required_at` (a datetime) and `days_remaining` (an `int`, rounded up, for display only). |
-Suppresses `MFA_REQUIRED` only. It does not open `@mfa_required` views — see
-{doc}`enforcement` for why the two are deliberately independent.
+### `django_mfa.admin_site.MfaAdminMixin`
-## `django_mfa.conf.settings`
+For an `AdminSite` subclass of your own. `MFA_PROTECT_ADMIN` applies the same
+behaviour to `django.contrib.admin.site` only.
-Resolved settings with defaults applied:
+```python
+# myproject/admin.py
+from django.contrib import admin
- from django_mfa.conf import settings as mfa_settings
- mfa_settings.MFA_VERIFY_RATE_LIMIT # "5/5m" unless overridden
+from django_mfa.admin_site import MfaAdminMixin
-Asking for a name that isn't a django-mfa setting raises `AttributeError`, so typos
-surface immediately. See {doc}`settings` for the full list.
-## `django_mfa.utils`
+class MyAdminSite(MfaAdminMixin, admin.AdminSite):
+ pass
+```
+
+`has_permission()` also requires a verified session and a primary factor.
+`login()` sends a signed-in user who fails those checks to `mfa:verify` or
+`mfa:security_settings` instead of showing the admin login form. `MFA_ADMIN_STEPUP`
+applies here too, with or without `MFA_PROTECT_ADMIN`. See {doc}`enforcement`.
+
+### `django_mfa.context_processors.mfa`
+
+Opt-in: add `"django_mfa.context_processors.mfa"` to the `context_processors` list
+in your `TEMPLATES` setting. It adds `mfa_grace` to every template context: the
+current user's `GraceState`, or `None` for anonymous users and anyone not in a
+grace period. It is computed only if a template uses it.
+
+```html+django
+{% if mfa_grace %}
+
Set up two-factor authentication within {{ mfa_grace.days_remaining }} days.
+{% endif %}
+```
+
+There is no context processor for "is this session verified". Call
+`session.is_verified(request)` in your view instead.
+
+## Settings: `django_mfa.conf.settings`
+
+Every django-mfa setting, with its default applied.
+
+```python
+from django_mfa.conf import settings as mfa_settings
+
+mfa_settings.MFA_VERIFY_RATE_LIMIT # "5/5m" unless your settings override it
+```
+
+Values are read from Django's settings on every access, so `override_settings()`
+works in tests. A name that is not a django-mfa setting raises `AttributeError`.
+See {doc}`settings`.
+
+## Helpers
+
+### `django_mfa.utils`
| Function | Purpose |
|---|---|
-| `strings_equal(a, b)` | Timing-safe comparison. Normalizes to NFKC, then `hmac.compare_digest`. Use for any secret comparison in a custom factor. |
-| `build_uri(secret, name, initial_count=None, issuer_name=None)` | Build an `otpauth://` provisioning URI. |
+| `strings_equal(a, b)` | Constant-time string comparison: NFKC-normalises both, then uses `hmac.compare_digest`. Use it for every secret comparison in a custom factor. |
+| `build_uri(secret, name, initial_count=None, issuer_name=None)` | An `otpauth://` provisioning URI: TOTP, or HOTP when `initial_count` is given. |
-## `django_mfa.crypto`
+### `django_mfa.crypto` (deprecated)
-| Function | Purpose |
+These functions sign values; they do not encrypt them. Do not use them in new code.
+
+| Function | Behaviour |
|---|---|
-| `encrypt(value)` | Encrypt with the first `MFA_SECRET_ENCRYPTION_KEYS` entry. Returns `value` unchanged when the setting is unset. |
-| `decrypt(value)` | Decrypt, trying every configured key. Passes through values stored before encryption was enabled. Raises `BadSignature` if no key works. |
+| `encrypt(value)` | Returns `value` unchanged when `MFA_SECRET_ENCRYPTION_KEYS` is unset. Otherwise returns `"mfa1:"` followed by `value` signed with the first key. The original is readable from the result without any key. |
+| `decrypt(value)` | Returns a value without the `mfa1:` prefix unchanged. Otherwise checks the signature against each configured key in turn and returns the original. Raises `django.core.signing.BadSignature` if no key matches, including after the setting has been removed. |
-Both are no-ops until a host project opts in, so a custom factor can use them
-unconditionally and gain encryption the day someone sets the keys.
+A custom factor that needs a secret kept confidential has to encrypt it some other
+way, such as a column-encryption library or database-level encryption. See
+{doc}`security`.
-## `django_mfa.handles`
+### `django_mfa.handles`
-WebAuthn user handles — opaque, stored, `SECRET_KEY`-independent.
+WebAuthn user handles: a random UUID per user, stored in `MfaUserHandle`.
-| Function | Purpose |
+| Function | Returns |
|---|---|
-| `user_handle_for(user)` | The user's stable handle, creating it on first call. Idempotent. |
-| `user_from_handle(handle)` | Resolve a handle back to a user, or `None`. Never raises — input is untrusted. |
+| `user_handle_for(user)` | The user's handle as a string. Created on the first call, the same value afterwards. |
+| `user_from_handle(handle)` | The user, or `None` for an unknown or malformed handle. Never raises. |
-## `django_mfa.quicklogin`
+### `django_mfa.quicklogin`
-For a login page that offers a passkey to a returning visitor. Requires
-`MFA_QUICKLOGIN = True`.
+For a login page that offers a returning visitor their passkey. Requires
+`MFA_QUICKLOGIN = True`. `MfaMiddleware` already sets the cookie at login and
+clears it at logout; these are for a flow of your own. See {doc}`recipes`.
| Name | Purpose |
|---|---|
| `COOKIE_NAME` | `"mfa_quicklogin"`. |
-| `user_from_hint(value)` | Resolve the cookie to a user, or `None`. Never raises. |
-| `set_hint(response, user, secure)` | Attach the cookie. No-op when the setting is off. |
-| `clear_hint(response)` | Remove it. Unconditional, so a stale cookie is cleaned up even after the feature is switched off. |
-
-The cookie is a **UX hint, never a credential** — it identifies whose passkey prompt
-to show and authenticates nobody. See {doc}`recipes`.
+| `user_from_hint(value)` | The user the cookie value names, or `None`. Never raises. |
+| `set_hint(response, user, secure)` | Sets the cookie (one year, `HttpOnly`, `SameSite=Lax`) and returns `response`. Does nothing when `MFA_QUICKLOGIN` is off. |
+| `clear_hint(response)` | Deletes the cookie, whether or not the setting is on, and returns `response`. |
-## `django_mfa.backends.WebAuthnBackend`
+The cookie identifies an account; it authenticates nobody. Signing in still takes a
+full passkey ceremony.
-Required in `AUTHENTICATION_BACKENDS` for passwordless login. It performs no
-cryptography: the view validates the assertion first, and the backend only returns
-the already-resolved user through Django's standard contract.
+### `django_mfa.backends.WebAuthnBackend`
-`authenticate()` deliberately ignores `username`/`password` and returns a user only
-when handed one explicitly as `mfa_user`, so another backend's call passing
-credentials through the chain can never authenticate anyone here.
+Required for passwordless login. Without it the user is anonymous again on the
+request after signing in; `django_mfa.E003` catches the omission. Like Django's
+`ModelBackend`, it refuses a user with `is_active=False`, so deactivating an account
+also ends its passkey sessions.
-Omitting this backend breaks passkey login **silently, one request later** —
-`django_mfa.E003` exists to catch that at startup.
+```python
+# settings.py
+AUTHENTICATION_BACKENDS = [
+ "django.contrib.auth.backends.ModelBackend",
+ "django_mfa.backends.WebAuthnBackend",
+]
+```
-## `django_mfa.middleware.MfaMiddleware`
+`authenticate(request, mfa_user=None, **kwargs)` returns `mfa_user` and ignores
+everything else, so a username and password passed down the backend chain never
+authenticate anyone here. The passkey view validates the assertion before it calls
+the backend. `get_user(user_id)` returns the user or `None`.
-Redirects authenticated-but-unverified requests to the picker. Its exempt set is
-derived from the registry (the picker, plus each factor's verify page) unioned with
-`MFA_EXEMPT_PATHS`. Subclass and override `process_request` to carve out a path
-prefix — see {doc}`recipes`.
+### `django_mfa.ratelimit`
-## `django_mfa.ratelimit`
-
-Applied for you by the verify view; documented because a custom factor's tests may
-need to reset it.
+Every verification already goes through these; they are public so your tests and
+tools can inspect or reset budgets. `scope` is a factor type string such as
+`"totp"`.
| Function | Purpose |
|---|---|
-| `check(user, factor_type)` | `True` if another attempt is allowed on the per-user budget. |
-| `record_failure(user, factor_type)` | Count a failure against it. |
-| `clear(user, factor_type)` | Reset it, as a success does. |
-| `check_client(request, factor_type)` | The same question for the per-IP budget (`MFA_VERIFY_IP_RATE_LIMIT`). |
-| `record_client(request, factor_type)` | Count a failure against the client's address. |
-| `client_ip(request)` | The address that budget bills to, or `None`. |
-| `prune()` | Delete expired counters; what `manage.py mfa_prune` calls. |
-
-There is deliberately no `clear_client()`. A successful verification clears the
-user's counter but must never clear the shared per-IP one — an attacker needs only
-one account they can log into for that to be a reset button. If a test needs the IP
-counter gone, delete the rows (or clear the cache) directly.
+| `check(user, scope, setting="MFA_VERIFY_RATE_LIMIT")` | `True` if the user has budget left. `setting` names the budget to read. |
+| `record_failure(user, scope, setting="MFA_VERIFY_RATE_LIMIT")` | Count one failure against it. `record` is the same function. |
+| `clear(user, scope)` | Reset the user's counter, as a successful verification does. |
+| `check_client(request, scope)` | `True` if the client address has budget left under `MFA_VERIFY_IP_RATE_LIMIT`. Also `True` when no address is known or the setting is `None`. |
+| `record_client(request, scope)` | Count one failure against the client address. |
+| `client_ip(request)` | The address that budget is charged to, or `None`. |
+| `prune()` | Delete expired database counters and return how many were deleted. `manage.py mfa_prune` calls it. |
+
+There is no `clear_client()`: a success never resets the per-address counter (see
+{doc}`security`). To reset it in a test, delete the `RateLimitCounter` rows, or
+clear the cache on the cache backend.
## Signals
-django-mfa also **receives** `user_logged_in` (to stamp the session pending) and
-`user_logged_out` (to clear the quicklogin hint) — you don't connect anything for
-those, they're internal.
-
-It **sends** six signals of its own, defined in `django_mfa.events` and re-exported
-from `django_mfa.signals` (either import path works):
+Defined in `django_mfa.events` and also importable from `django_mfa.signals`.
-| Signal | kwargs | Fires when |
+| Signal | Keyword arguments | Sent when |
|---|---|---|
-| `factor_added` | `user`, `authenticator`, `request` | An adapter's `complete_enroll()` succeeds — every ordinary enrollment, plus the first time a user generates recovery codes. `authenticator` is the created `Authenticator` row. |
-| `factor_removed` | `user`, `factor_type`, `name`, `request` | `mfa:manage` deletes a row. `factor_type` and `name` are passed by value, not as an instance — the row is already gone by the time this fires. |
-| `mfa_verified` | `user`, `method`, `request` | A second-factor challenge succeeds — from `verify_factor`'s success branch, and from `passkey_complete` when the passkey assertion carries User Verification (a UP-only passkey login logs the user in but has not satisfied a second factor, so it does not fire this). |
-| `mfa_verification_failed` | `user`, `method`, `request` | A challenge fails: a wrong code, a caught adapter exception (`ValueError`/`TypeError`/`KeyError`), **or an attempt refused outright by the rate limiter** — no adapter call happens in that last case, so a receiver watching for brute force needs to see refused attempts too, not only evaluated ones. |
-| `recovery_code_used` | `user`, `remaining`, `request` | A recovery code is spent. Sent from the adapter itself, not the view — only the adapter knows how many codes are left. |
-| `mfa_exemption_changed` | `user`, `reason`, `expires_at`, `revoked`, `request` | The `mfa_disable` management command grants or revokes an `MfaExemption`. `reason` and `expires_at` are `None` on a revoke. `sender` is the `MfaExemption` model class, not an `Adapter` subclass — there is no adapter behind this one. |
-
-`request` is `None` when the event did not originate in a request — the
-`mfa_reset` and `mfa_disable` management commands emit these signals too, so
-that operator actions are auditable. Receivers must handle both, as the
-example below does.
-
-Read the user off the `user` kwarg, never off `request.user`. On the passkey path
-`mfa_verified` fires between `session.mark_verified()` and `auth.login()` — the
-order is forced, since the login signal's own receiver checks whether the session is
-already verified — so `request.user` is still `AnonymousUser` there, while the `user`
-kwarg is correct on every path.
-
-`sender` is the `Adapter` **class** for the factor involved (e.g. `TOTPAdapter`), so
-a receiver can narrow with `sender=TOTPAdapter` — except on `factor_removed`, whose
-`sender` is `None` when the removed row's type is no longer registered (`MFA_FACTORS`
-was narrowed since it was enrolled, or a third-party adapter was unregistered): match
-on the `factor_type` kwarg instead of `sender` if you need to handle that case. On
-`mfa_exemption_changed`, `sender` is always the `MfaExemption` model class — there is
-no adapter behind an exemption at all.
-
-A receiver:
-
- import logging
-
- from django.dispatch import receiver
- from django_mfa.signals import factor_removed
-
- logger = logging.getLogger("myapp.security")
-
- @receiver(factor_removed)
- def audit_factor_removal(sender, user, factor_type, name, request, **kwargs):
- # request is None when mfa_reset/mfa_disable removed the row instead
- # of a request to django_mfa:manage -- log a source that makes sense
- # either way rather than assuming request is never None.
- source = request.META.get("REMOTE_ADDR") if request else "console"
- logger.info("factor removed: user=%s type=%s name=%r from=%s",
- user.pk, factor_type, name, source)
-
-All six are sent with `send_robust()`, not `send()`: a raising receiver cannot break
-the security action it's observing — enrolling, verifying, or removing a factor
-succeeds or fails independently of what your receiver does with the event. The other
-side of that trade is that `send_robust()` catches and discards the exception rather
-than letting it propagate, so a receiver that fails does so **silently** unless it
-logs its own failure.
-
-To react with something other than a signal receiver, `post_save` on `Authenticator`
-still works too — these signals are additional, not a replacement for the model
-layer.
+| `factor_added` | `user`, `authenticator`, `request` | A factor is enrolled (in the HTML views or the JSON API), or a new set of recovery codes is generated. `authenticator` is the new row. |
+| `factor_removed` | `user`, `factor_type`, `name`, `request` | A user removes a factor, or `manage.py mfa_reset` removes one. The row is already deleted, so its type and name are passed as values. |
+| `mfa_verified` | `user`, `method`, `request` | A second-factor challenge succeeds, including a passwordless sign-in whose assertion carries user verification. |
+| `mfa_verification_failed` | `user`, `method`, `request` | A challenge fails: a wrong or malformed submission, or an attempt the rate limiter refused. Failed passwordless sign-ins do not send it. |
+| `recovery_code_used` | `user`, `remaining`, `request` | A recovery code is spent. `remaining` is how many unused codes are left. |
+| `mfa_exemption_changed` | `user`, `reason`, `expires_at`, `revoked`, `request` | `manage.py mfa_disable` grants or revokes an exemption. `reason` and `expires_at` are `None` on a revoke. |
+
+- **`sender`** is the adapter class, for example `TOTPAdapter`, so you can connect
+ with `sender=TOTPAdapter`. Two exceptions: `factor_removed` has `sender=None` when
+ the removed type is no longer registered (match on `factor_type` instead), and
+ `mfa_exemption_changed` always has `sender=MfaExemption`.
+- **`request` is `None`** when a management command (`mfa_reset`, `mfa_disable`)
+ sends the signal. Your receiver must handle that.
+- **Read the user from the `user` argument**, not from `request.user`. During a
+ passwordless sign-in, `mfa_verified` is sent before the user is logged in, while
+ `request.user` is still anonymous.
+- **A receiver cannot break the action it observes.** Signals are sent with
+ `send_robust()`, which catches and discards your receiver's exceptions. Log your
+ own failures.
+- **Some deletions send nothing.** Deleting an `Authenticator` in the admin or with
+ a queryset `delete()` sends no `factor_removed`. Connect `post_delete` on
+ `Authenticator` if you need to see every deletion. Deleting an `MfaExemption` in
+ the admin sends no `mfa_exemption_changed` either.
+
+A receiver for an audit log:
+
+```python
+# myapp/signals.py
+import logging
+
+from django.dispatch import receiver
+
+from django_mfa.signals import factor_removed
+
+logger = logging.getLogger("myapp.security")
+
+
+@receiver(factor_removed)
+def audit_factor_removal(sender, user, factor_type, name, request, **kwargs):
+ # request is None when manage.py mfa_reset removed the factor.
+ source = request.META.get("REMOTE_ADDR") if request else "management command"
+ logger.info("factor removed: user=%s type=%s name=%r from=%s",
+ user.pk, factor_type, name, source)
+```
+
+Import the module from your app's `AppConfig.ready()` so the receiver is connected.
diff --git a/docs/changelog.md b/docs/changelog.md
new file mode 100644
index 0000000..03395c5
--- /dev/null
+++ b/docs/changelog.md
@@ -0,0 +1,3 @@
+```{include} ../CHANGELOG.md
+:relative-docs: docs/
+```
diff --git a/docs/conf.py b/docs/conf.py
index 1f9fe8c..b057e25 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -34,7 +34,10 @@
# autodoc back would also mean running django.setup() in this file, since
# importing django_mfa.models without configured settings raises
# ImproperlyConfigured.
-extensions = ["myst_parser"]
+# sphinx_design supplies the landing page's cards and the pip/uv tabs, and
+# sphinx_copybutton puts a copy button on every code block. Both are docs-group
+# dependencies only; nothing here is imported by the package.
+extensions = ["myst_parser", "sphinx_design", "sphinx_copybutton"]
# Generate anchor slugs for headings down to level 3, so in-page links like
# [System checks](#system-checks) resolve. The pages carry several of these,
@@ -47,7 +50,9 @@
# build still reports success, so this cannot be caught by watching for
# warnings. django_mfa/tests/test_docs.py pins the setting; the `docs` CI job
# builds the pages and asserts the admonitions become real admonition boxes.
-myst_enable_extensions = ["colon_fence"]
+# tasklist turns "- [ ]" lines into checkboxes, which security.md's production
+# checklist uses; without it they render as a literal "[ ]".
+myst_enable_extensions = ["colon_fence", "tasklist"]
# "superpowers" used to be excluded here: internal spec/plan artifacts lived
# in docs/superpowers/. They now live in .superpowers/ at the repo root,
@@ -56,9 +61,58 @@
exclude_patterns = ["_build"]
language = "en"
-html_theme = "sphinx_rtd_theme"
+# Every code block names its language, so nothing should fall through to a
+# guess. "none" makes an unlabelled block plain text rather than Python.
+highlight_language = "none"
+
+html_theme = "furo"
+html_title = "django-mfa"
htmlhelp_basename = "django-mfa"
+html_static_path = ["_static"]
+html_css_files = ["custom.css"]
+html_logo = "_static/logo.svg"
+html_favicon = "_static/logo.svg"
+
+_GITHUB = "https://github.com/MicroPyramid/django-mfa"
+html_theme_options = {
+ "source_repository": _GITHUB,
+ "source_branch": "master",
+ "source_directory": "docs/",
+ "top_of_page_buttons": ["view", "edit"],
+ "light_css_variables": {
+ "color-brand-primary": "#0c4b33",
+ "color-brand-content": "#0c6e4a",
+ "color-brand-visited": "#0c6e4a",
+ },
+ "dark_css_variables": {
+ "color-brand-primary": "#5fd4a0",
+ "color-brand-content": "#5fd4a0",
+ "color-brand-visited": "#5fd4a0",
+ },
+ "footer_icons": [
+ {
+ "name": "GitHub",
+ "url": _GITHUB,
+ "html": (
+ '"
+ ),
+ "class": "",
+ },
+ ],
+}
-# No templates_path/html_static_path: docs/_templates and docs/_static never
-# existed, and naming a directory that isn't there is a build warning.
+# Shell blocks are written without a "$ " prompt, but strip one if a page
+# ever adds it, so the copied text still runs as pasted.
+copybutton_prompt_text = r"\$ |>>> "
+copybutton_prompt_is_regexp = True
diff --git a/docs/contributing.md b/docs/contributing.md
index 9963cf8..da753a2 100644
--- a/docs/contributing.md
+++ b/docs/contributing.md
@@ -1,36 +1,54 @@
# Contributing
-Feel free to create a new Pull request if you want to propose a new feature or fix a bug.
+Feel free to open a pull request if you want to propose a new feature or fix a bug.
## Development setup
-This project uses [uv](https://docs.astral.sh/uv/). There is no `requirements.txt` or `setup.py` -- `pyproject.toml` is the only packaging file, and `uv run` creates and syncs the environment for you, so there is no virtualenv to activate:
+This project uses [uv](https://docs.astral.sh/uv/). There is no `requirements.txt` or `setup.py`: `pyproject.toml` is the only packaging file, and `uv run` creates and syncs the environment for you, so there is no virtualenv to activate.
- uv run python test_runner.py # the whole suite
- uv run ruff check . # lint
- uv run ruff check . --fix # and fix what's auto-fixable
+```bash
+uv run python test_runner.py # the whole suite
+uv run ruff check . # lint
+uv run ruff check . --fix # and fix what's auto-fixable
+```
-To run a single test, pass a label -- `test_runner.py` falls back to the whole suite only when given none:
+To run a single test, pass a label. `test_runner.py` falls back to the whole suite only when given none:
- uv run python test_runner.py django_mfa.tests.test_conf
+```bash
+uv run python test_runner.py django_mfa.tests.test_conf
+```
-To check one Python/Django combination locally (CI runs the grid of Python 3.10-3.13 against Django 4.2, 5.2 and 6.1, minus the two combinations Django 6.1 doesn't support — it needs Python 3.12+):
+To check one Python/Django combination locally (CI runs the grid of Python 3.10–3.13 against Django 4.2, 5.2 and 6.1, minus the two combinations Django 6.1 doesn't support, since it needs Python 3.12+):
- uv run --python 3.12 --with "django~=4.2.0" python test_runner.py
+```bash
+uv run --python 3.12 --with "django~=4.2.0" python test_runner.py
+```
+
+CI also runs the suite once at the *lowest* versions `pyproject.toml` allows: Python 3.10, with Django, `fido2` and `qrcode` each at their declared floor. Every other job runs the newest versions `uv.lock` pins, so this is the only check that those floors are true. To run it yourself, use a separate worktree. The run rewrites `uv.lock`, and a lowest-version lockfile left behind by an earlier run makes uv keep the versions it already holds instead of testing a floor you have since changed:
+
+```bash
+git worktree add --detach ../django-mfa-lowest
+cd ../django-mfa-lowest
+uv run --python 3.10 --resolution lowest-direct python test_runner.py
+```
+
+A worktree holds committed files only, so commit the change you want to check first.
## Documentation
The docs are Markdown, read by Sphinx through [MyST](https://myst-parser.readthedocs.io/), and live in `docs/`:
- cd docs && make html # build into docs/_build/html
- cd docs && make linkcheck # verify external links still resolve
+```bash
+cd docs && make html # build into docs/_build/html
+cd docs && make linkcheck # verify external links still resolve
+```
`-W` is on by default, so a warning fails the build here exactly as it does in CI and on Read the Docs.
Two things that build output alone will *not* catch, both pinned by `django_mfa/tests/test_docs.py` instead:
-- With MyST's `colon_fence` extension off, `:::{warning}` is not an error -- it renders the literal text `:::{warning}` into the published page and the build still reports success.
-- A page missing from `index.md`'s toctree builds fine and simply never gets linked.
+- With MyST's `colon_fence` extension off, `:::{warning}` is not an error. It renders the literal text `:::{warning}` into the published page and the build still reports success.
+- A page missing from `index.md`'s toctree builds fine and is never linked.
When you add a setting to `django_mfa/conf.py`, document it in `docs/settings.md` in the same change; a test asserts every key in `DEFAULTS` appears there.
@@ -47,7 +65,7 @@ To cut a release, in full:
`CHANGELOG.md`, in the same PR. Merge it to `master`.
There is no step 2. You never create a tag and you never create a GitHub
-Release -- `.github/workflows/tag-release.yml` sees the version change, creates
+Release. `.github/workflows/tag-release.yml` sees the version change, creates
tag `v` on the commit that carried it, publishes a GitHub Release
(marked pre-release if PEP 440 says the version is one), and starts
`publish.yml` against that tag.
@@ -63,30 +81,30 @@ installs the wheel into a clean environment and starts Django against it, and
only then uploads.
Two guards survive from when tags were typed by hand, because the cost of
-getting a version wrong is unbounded -- PyPI does not allow re-uploading one:
+getting a version wrong is unbounded: PyPI does not allow re-uploading one.
- The tag must match `pyproject.toml`'s `version`. Nothing in the build
connects them: hatchling never looks at the tag, so a release tagged `v4.0.0`
cut from a tree still saying `4.0.0a1` would publish `4.0.0a1` and report
- success. That is not hypothetical -- it happened on 2026-08-13, and this
+ success. That is not hypothetical. It happened on 2026-08-13, and this
guard is what stopped it.
- The publish job must run on a tag ref. The `pypi` deployment environment only
accepts tags matching `v*`, and the guard fails loudly rather than skipping
when handed a branch.
-To release a version already sitting on `master` -- or the first time, when the
-version predates all of this -- run **Tag release** from the Actions tab
+To release a version already sitting on `master` (or the first time, when the
+version predates all of this), run **Tag release** from the Actions tab
manually. Re-running it is harmless: if `v` already exists it does
nothing.
:::{warning}
-Renaming `publish.yml`, or the `pypi` environment, breaks publishing --
-both names are part of what PyPI trusts, and a mismatch is rejected at upload
+Renaming `publish.yml`, or the `pypi` environment, breaks publishing. Both
+names are part of what PyPI trusts, and a mismatch is rejected at upload
time with an authentication error that does not mention the rename. Change it on
[PyPI](https://pypi.org/manage/project/django-mfa/settings/publishing/) first.
`tag-release.yml` reaches `publish.yml` through `workflow_dispatch`, not through
-the Release it just created, and that is not incidental. GitHub suppresses
+the Release it has created, and that is not incidental. GitHub suppresses
workflow runs caused by its own `GITHUB_TOKEN` so workflows cannot loop, with
`workflow_dispatch` and `repository_dispatch` as the only exceptions. Chaining
on `release: published` instead fails *silently*: the Release appears, nothing
@@ -95,22 +113,45 @@ publishes, and no workflow run exists anywhere to explain why.
## Sending pull requests
-1. Fork the repo:
+1. [Fork](https://docs.github.com/en/pull-requests/how-tos/work-with-forks/fork-a-repo)
+ [MicroPyramid/django-mfa](https://github.com/MicroPyramid/django-mfa) on
+ GitHub, then clone your fork and add the original repository as `upstream`:
+
+ ```bash
+ git clone https://github.com/YOUR-USERNAME/django-mfa.git
+ cd django-mfa
+ git remote add upstream https://github.com/MicroPyramid/django-mfa.git
+ ```
+
+2. Create a branch for your specific changes, starting from an up-to-date
+ `master`:
- https://github.com/MicroPyramid/django-mfa
+ ```bash
+ git checkout master
+ git pull upstream master
+ git checkout -b my-change
+ ```
-2. Create a branch for your specific changes:
+ Please make one branch per issue (and per pull request). Keep your branch
+ up to date with upstream `master`, so that maintainers can merge changes
+ easily.
- $ git checkout master
- $ git pull
- $ git checkout -b feature
+3. Commit your changes. Please update the docs, if relevant.
- To simplify things, please, make one branch per issue (pull request). It's also important to make sure your branch is up-to-date with upstream master, so that maintainers can merge changes easily.
+4. Run the tests and `ruff` (see [Development setup](#development-setup)) to
+ check that nothing breaks:
-3. Commit changes. Please update docs, if relevant.
+ ```bash
+ uv run python test_runner.py
+ uv run ruff check .
+ ```
-4. Don't forget to run the tests (and `ruff`) to check that nothing breaks.
+5. Ideally, write your own tests for the new feature or bug fix.
-5. Ideally, write your own tests for new feature/bug fix.
+6. Push the branch to your fork and
+ [open a pull request](https://docs.github.com/en/pull-requests/how-tos/create-pull-requests/creating-a-pull-request-from-a-fork)
+ against `master`:
-6. Submit a [pull request](https://help.github.com/articles/using-pull-requests).
+ ```bash
+ git push -u origin my-change
+ ```
diff --git a/docs/custom_factors.md b/docs/custom_factors.md
index ad32a75..169b6c9 100644
--- a/docs/custom_factors.md
+++ b/docs/custom_factors.md
@@ -1,248 +1,289 @@
# Writing a custom factor
-Adding a factor type means writing one class and registering it. You do not write
-views, URLs, or middleware changes — those are generic and dispatch to whatever the
-registry holds. The four built-ins (`totp`, `webauthn`, `recovery_codes`, `email`)
-are written against exactly the API below; there is no privileged path.
-
-## The shape of it
-
-A factor is a subclass of `django_mfa.registry.Adapter`. It answers four questions:
-
- from django_mfa.registry import Adapter
-
- class MyAdapter(Adapter):
- type = "my_factor" # the URL segment and the DB `type` value
- verbose_name = "My factor" # shown in the picker and on the security page
-
- def begin_enroll(self, request): ...
- def complete_enroll(self, request, data): ...
- def begin_verify(self, request, user): ...
- def complete_verify(self, request, user, data): ...
-
-The `begin_*` methods return a dict that is merged into the template context. The
-`complete_*` methods receive the POSTed `QueryDict` as `data`.
-
-Once registered, `type` is what appears in `/mfa/enroll//` and
-`/mfa/verify//`, and what gets stored in `Authenticator.type`.
-
-## A worked example: a printed backup token
-
-A factor django-mfa doesn't ship: one static, hashed backup token, handed to a user
-in person or by post, entered once to activate it, and consumed the moment it's used.
-Unlike a TOTP secret it never changes and needs no clock sync; unlike ten recovery
-codes it's a single value, closer to what an administrator would issue someone who's
-lost both their authenticator and their recovery codes. Roughly 40 lines.
-
- # myapp/mfa.py
- import secrets
-
- from django.contrib.auth.hashers import check_password, make_password
-
- from django_mfa.models import Authenticator
- from django_mfa.registry import Adapter
-
- SESSION_KEY = "myapp_backup_token"
-
-
- class BackupTokenAdapter(Adapter):
- type = "backup_token"
- verbose_name = "Backup token"
-
- # One at a time: once the token is spent, complete_verify() below
- # deletes the row outright, so there's never a second one to hold.
- # (This is the default; shown for clarity — set it True only if
- # several instances make sense, the way several security keys do.)
- supports_multiple = False
-
- def begin_enroll(self, request):
- # Generated here to keep the example self-contained. Swap this for
- # your own issuing step if you want tokens minted out of band by
- # an administrator and handed to users in person or by post —
- # begin_enroll would then look up an already-issued token instead
- # of minting one, but complete_enroll's job (confirm they have it
- # right) stays the same.
- token = secrets.token_hex(8)
- request.session[SESSION_KEY] = make_password(token)
- return {"token": token} # shown once: "write this down"
-
- def complete_enroll(self, request, data):
- # Confirms the user actually recorded the token shown above, the
- # same way TOTP's enrollment confirms a scanned secret rather than
- # trusting that the QR code was read correctly.
- expected_hash = request.session.pop(SESSION_KEY, None)
- if not expected_hash or not check_password(
- data.get("token", ""), expected_hash):
- raise ValueError("Token did not match.")
- return Authenticator.objects.create(
- user=request.user, type=self.type, data={"hash": expected_hash})
-
- def begin_verify(self, request, user):
- # Nothing to send: unlike a delivery-based factor, the token was
- # already handed to the user at enrollment, so re-rendering this
- # page on a failed attempt has no side effect to worry about.
- return {}
-
- def complete_verify(self, request, user, data):
- auth = self.get_instances(user).first()
- if auth is None:
- return False
- if not check_password(data.get("token", ""), auth.data["hash"]):
- return False
- # Single-use: spending it deletes the factor outright rather than
- # marking it used, so a stolen-and-reused token is impossible and
- # re-issuing one (self-service, or through an administrator) is
- # the same complete_enroll() flow as the first time.
- auth.delete()
- return True
-
-Two templates, which can be as short as this:
-
- {% comment %} myapp/templates/django_mfa/verify_backup_token.html {% endcomment %}
- {% extends base_template %}
- {% block content %}
-
Enter your backup token
-
- {% endblock %}
-
-`enroll_backup_token.html` is the same minus the `next` field, plus showing `{{
-token }}` once so the user can copy it down before confirming. See {doc}`customizing`
-for the context every page receives.
-
-Then register it once, at startup:
-
- # myapp/apps.py
- from django.apps import AppConfig
-
- class MyAppConfig(AppConfig):
- name = "myapp"
-
- def ready(self):
- from django_mfa.registry import registry
- from myapp.mfa import BackupTokenAdapter
- registry.register(BackupTokenAdapter())
-
-That's the whole integration. The factor now appears on the security page, in the
-picker, in the middleware's exempt set, and under rate limiting — none of which you
-touched.
-
-For a fuller worked example of a *delivery-based* factor — one with a send step, a
-throttle on how often it can be resent, and a masked address shown back to the user —
-see the built-in `django_mfa/adapters/email.py`, which this page used to reproduce
-here before emailed codes shipped as `"email"` in `MFA_FACTORS`.
-
-## What you get for free
-
-Registering an adapter is enough for all of this:
-
-- **Enroll and verify views**, dispatching on `type`, with `@login_required`.
-- **Rate limiting.** `MFA_VERIFY_RATE_LIMIT` applies per user per factor type. You
- do not call it; `verify_factor` does.
-- **Uniform failure responses.** Returning `False` and raising `ValueError`,
- `TypeError`, or `KeyError` all produce the same generic HTTP 400. Let a malformed
- payload raise — do not catch it into a distinct message, which would leak more
- than the generic one.
-- **Middleware exemption.** `MfaMiddleware` derives its exempt set from
- `registry.all()`, so your verify page is reachable by a pending session
- automatically.
-- **Session handling.** The view calls `session.mark_verified()` on success. Do not
- touch `request.session["mfa"]` yourself.
-- **Enforcement.** Once a user enrolls, the `user_logged_in` receiver starts
- challenging them.
-
-## The four flags
-
-| Flag | Default | Set it when |
+A new factor type is one class, two templates and one call to register it. You do
+not write views, URLs or middleware changes: the enroll and verify views, the
+security page, the picker and the JSON API all work from whatever factors are
+registered. The built-in factors (`totp`, `webauthn`, `recovery_codes`, `email`)
+use the same API.
+
+## A worked example: a backup token
+
+This factor is a single static token. The user writes it down when they set it
+up, and it works once. It is a spare way in for someone who already has another
+method, much like a single recovery code.
+
+### 1. The adapter
+
+```python
+# myapp/mfa.py
+import secrets
+
+from django.contrib.auth.hashers import check_password, make_password
+from django.utils.translation import gettext_lazy as _
+
+from django_mfa.models import Authenticator
+from django_mfa.registry import Adapter
+
+SESSION_KEY = "myapp_backup_token"
+
+
+class BackupTokenAdapter(Adapter):
+ type = "backup_token"
+ verbose_name = _("Backup token")
+ # Single-use, so it must never be someone's only factor.
+ counts_as_primary_factor = False
+
+ def begin_enroll(self, request):
+ token = secrets.token_hex(8)
+ request.session[SESSION_KEY] = make_password(token)
+ return {"token": token}
+
+ def complete_enroll(self, request, data):
+ expected = request.session.pop(SESSION_KEY, None)
+ if not expected or not check_password(data.get("token", ""), expected):
+ raise ValueError("Token did not match.")
+ return Authenticator.objects.create(
+ user=request.user, type=self.type, data={"hash": expected})
+
+ def begin_verify(self, request, user):
+ return {}
+
+ def complete_verify(self, request, user, data):
+ authenticator = self.get_instances(user).first()
+ if authenticator is None:
+ return False
+ if not check_password(data.get("token", ""), authenticator.data["hash"]):
+ return False
+ # Spend it. Of two requests racing with the same token, only one
+ # deletes the row, so only one succeeds.
+ deleted = Authenticator.objects.filter(pk=authenticator.pk).delete()[0]
+ return deleted == 1
+```
+
+`begin_enroll` shows the token once and keeps only its hash in the session.
+`complete_enroll` makes the user type it back, the way TOTP setup asks for a code
+before saving the secret. Only the hash is stored.
+
+### 2. The templates
+
+Enroll and verify pages are found by type: `django_mfa/enroll_.html` and
+`django_mfa/verify_.html`. Each receives the dict its `begin_*` method
+returned, plus the context every such page gets (`base_template`, `adapter`,
+`error_message`, and `next` on verify pages; see
+[Template context](customizing.md#template-context)).
+
+```html+django
+{# myapp/templates/django_mfa/enroll_backup_token.html #}
+{% extends base_template %}
+{% block content %}
+
+
Your backup token
+
Write it down now. It works once and is not shown again.
+
+
+{% endblock %}
+```
+
+### 3. Register it
+
+```python
+# myapp/apps.py
+from django.apps import AppConfig
+
+
+class MyAppConfig(AppConfig):
+ name = "myapp"
+
+ def ready(self):
+ from django_mfa.registry import registry
+
+ from myapp.mfa import BackupTokenAdapter
+
+ registry.register(BackupTokenAdapter())
+```
+
+Order in `INSTALLED_APPS` does not matter. Open the security page and "Backup
+token" should appear under "Add a method".
+
+### 4. Test it
+
+```python
+# myapp/tests.py
+from django.contrib.auth import get_user_model
+from django.test import TestCase
+from django.urls import reverse
+
+from django_mfa.models import Authenticator
+
+
+class BackupTokenTests(TestCase):
+ def setUp(self):
+ self.user = get_user_model().objects.create_user("ana", password="pw")
+ self.client.force_login(self.user)
+
+ def test_enroll_then_spend(self):
+ enroll = reverse("mfa:enroll_factor", args=["backup_token"])
+ token = self.client.get(enroll).context["token"]
+ self.assertEqual(self.client.post(enroll, {"token": token}).status_code, 302)
+
+ verify = reverse("mfa:verify_factor", args=["backup_token"])
+ self.assertEqual(self.client.post(verify, {"token": "wrong"}).status_code, 400)
+ self.assertEqual(self.client.post(verify, {"token": token}).status_code, 302)
+
+ # Spent: the row is gone and the same token no longer works.
+ self.assertFalse(Authenticator.objects.filter(type="backup_token").exists())
+ self.assertEqual(self.client.post(verify, {"token": token}).status_code, 400)
+```
+
+For a factor that sends something (a code by email or SMS), read the built-in
+`django_mfa/adapters/email.py`. It shows the send step, a limit on resends and a
+masked address.
+
+## What you get without writing it
+
+- **Pages** at `mfa:enroll_factor` and `mfa:verify_factor`, with `type` as the
+ URL argument. Both need a logged-in user. Enrolling also needs a recent
+ challenge when the user already holds a factor other than recovery codes (see
+ [Step-up re-authentication](enforcement.md#step-up-re-authentication)).
+- **The security page and the picker**: offered under "Add a method", listed with
+ a remove button once held, offered at login.
+- **Rate limiting** of failed verifications, by `MFA_VERIFY_RATE_LIMIT` and
+ `MFA_VERIFY_IP_RATE_LIMIT`.
+- **Uniform failures**: every rejected attempt gets the same message and HTTP 400.
+- **Middleware access**: a session waiting for its challenge can reach the verify
+ page, and a user held by `MFA_REQUIRED` can reach the enroll page.
+- **Session state and signals**: success marks the session verified and sends
+ `factor_added` (with the `Authenticator` you returned) or `mfa_verified`;
+ failure sends `mfa_verification_failed`; removal sends `factor_removed`. With
+ `MFA_NOTIFY_ON_CHANGE` on, the user gets the usual emails.
+- **The JSON API**, if mounted, through its enroll and verify endpoints. See
+ {doc}`rest_api`.
+- **Enforcement**, if `counts_as_primary_factor` is true: a user who holds the
+ factor is challenged at login and satisfies `MFA_REQUIRED`.
+
+## The `Adapter` API
+
+Subclass `django_mfa.registry.Adapter`.
+
+### Attributes
+
+| Attribute | Default | Meaning |
|---|---|---|
-| `supports_multiple` | `False` | A user can hold several — WebAuthn does, so someone can register a laptop and a backup key. `is_available()` uses this to decide whether to keep offering the factor. |
-| `supports_enroll` | `True` | Set `False` for a factor that is *generated* rather than enrolled. Recovery codes do this; `enroll_factor` then returns 404 for it and the security page never offers it. |
-| `counts_as_primary_factor` | `True` | Set `False` for something that must never be a user's only factor. Recovery codes do this — they're exhaustible. It's the difference between "can verify with this" and "is protected by this". |
-| `type` / `verbose_name` | — | Always. `verbose_name` is user-visible. |
+| `type` | `None` | Required. The URL segment, the `Authenticator.type` value and the template suffix. Use lowercase letters, digits and underscores, at most 32 characters, and not a built-in name. |
+| `verbose_name` | `None` | Required. The name users see in the picker and under "Add a method". Wrap it in `gettext_lazy` if your site is translated. |
+| `supports_multiple` | `False` | Whether a user may hold several, as with security keys. When `False`, the factor stops being offered under "Add a method" once the user holds one, and a second enrollment is refused with the usual 400. See [Known limitations](#known-limitations). |
+| `supports_enroll` | `True` | Set `False` for a factor that is created some other way, as recovery codes are generated on their own page. The enroll page then returns 404 and the factor is never offered under "Add a method". You do not need `begin_enroll`, `complete_enroll` or an enroll template. |
+| `counts_as_primary_factor` | `True` | Whether holding this factor protects the user on its own. Set `False` for anything that can run out, as recovery codes and the example above do. Such a factor is still offered at login, but a user holding only it is never challenged and does not satisfy `MFA_REQUIRED`. |
-`counts_as_primary_factor` is the subtle one. `registry.primary_enabled_for()` is the
-**single source of truth** for whether to challenge a user, and it filters on this
-flag. A factor with it `False` still appears in the picker (you can verify with it)
-but never, on its own, causes a challenge — because a user holding only that factor
-isn't protected.
+### Methods
+
+| Method | Return | Called |
+|---|---|---|
+| `begin_enroll(request)` | A dict, merged into the enroll page's context | Every time the enroll page is shown, including after a failed attempt |
+| `complete_enroll(request, data)` | The new `Authenticator` row | On submit. Raise `ValueError` to reject. |
+| `begin_verify(request, user)` | A dict, merged into the verify page's context | Every time the verify page is shown, including after a failed attempt |
+| `complete_verify(request, user, data)` | `True` or `False` | On submit. |
+| `is_available(user)` | `bool` | To decide whether to offer the factor under "Add a method". Override it to add a condition; the email factor hides itself from accounts with no email address. Call `super()` to keep the `supports_multiple` check. |
+
+The base class also gives you `get_instances(user)` (this user's rows of this
+type, as a queryset) and `is_enabled(user)`. The `enroll_template` and
+`verify_template` properties return the template names above; override them to
+use other names.
+
+`data` is `request.POST` for the HTML pages, or the decoded JSON object for the
+JSON API. Read it with `data.get(...)`. For the same reason, anything `begin_*`
+returns must be JSON-serialisable if the JSON API is mounted.
+
+### Rejecting an attempt
+
+- In `complete_enroll`, raise `ValueError`. Its message is not shown to anyone.
+- In `complete_verify`, return `False`.
+- In either, a `ValueError`, `TypeError` or `KeyError` (for example from a
+ malformed payload) is treated exactly like a wrong code. Let those propagate.
+ Do not catch them to show a more specific message: a different response for
+ each failure tells an attacker which check failed.
+- Any other exception is a server error.
## Things to get right
-**Raise, don't return, for bad input during enrollment.** `complete_enroll` signals
-failure by raising `ValueError`; its return value is the created `Authenticator`.
-`complete_verify` signals failure by returning `False`. They are deliberately
-different: enrollment has nothing meaningful to return on failure.
-
-**`begin_verify` runs again on failure.** After a wrong code the view re-renders the
-challenge page, which means `begin_verify` is called a second time. The worked
-example above has no side effect to worry about, but a factor that sends something
-(an email, an SMS) on `begin_verify` — see `django_mfa/adapters/email.py` — will send
-another one on every wrong-code retry unless you cache the issued value with a TTL
-and reuse it, the way `EmailAdapter._ensure_code()` does; decide deliberately.
-
-**Store state in `data`, not in new columns.** `Authenticator.data` is a `JSONField`.
-There is no per-factor table and adding one is not the intended extension point.
-
-**Compare secrets with `django_mfa.utils.strings_equal`**, which normalizes and then
-uses `hmac.compare_digest`. `==` on a secret is a timing side channel.
-
-**Hash or encrypt anything worth stealing.** `django_mfa.crypto.encrypt`/`decrypt`
-give you `MFA_SECRET_ENCRYPTION_KEYS` handling for free — they're a no-op when the
-setting is unset, so using them costs nothing and starts working the day someone sets
-it. For values you never need to read back, hash instead, as recovery codes do.
-
-## Known rough edges
-
-Being honest about where a custom factor is a slightly second-class citizen:
-
-- **`Authenticator.Type` is a fixed `TextChoices`** with the four built-ins. A row
- with a custom `type` saves and queries fine — Django only validates choices in
- `full_clean()`, which these code paths don't call — but `get_type_display()`
- returns the raw string rather than a label, so `security.html` shows `my_factor`
- instead of `My factor`. Override `security.html` and render
- `adapter.verbose_name` if that matters to you.
-- **The singleton database constraint names its types explicitly**
- (`mfa_one_singleton_authenticator_per_user` covers `totp`, `recovery_codes`, and
- `email`). `supports_multiple = False` is enforced in `is_available()` at the
- application level, not by your database, for anything outside that list. For most
- factors that's fine; if you need the guarantee, add your own constraint in a
- migration in your app.
-- **`MFA_FACTORS` only controls the built-ins.** Your adapter is registered by your
- own `ready()`, so listing it there does nothing — and an unrecognized name raises
- `ImproperlyConfigured`. Gate registration on your own setting if you need it
- toggleable.
-- **`registry.register()` raises `ValueError` on a duplicate `type`.** If your
- `ready()` can run twice (some test setups), guard it or use
- `registry.unregister()` first.
-
-## Testing your factor
-
-The suite in `django_mfa/tests/` uses plain `django.test.TestCase` and `Client`, and
-is the best reference. A minimal check that yours is wired up end to end:
-
- from django.contrib.auth import get_user_model
- from django.test import TestCase
- from django_mfa.registry import registry
-
- class BackupTokenFactorTests(TestCase):
- def setUp(self):
- self.user = get_user_model().objects.create_user(
- "u", "u@example.com", "pw")
- self.client.force_login(self.user)
-
- def test_enrolling_protects_the_user(self):
- response = self.client.get("/mfa/enroll/backup_token/") # issues a token
- token = response.context["token"]
- response = self.client.post(
- "/mfa/enroll/backup_token/", {"token": token})
- self.assertEqual(response.status_code, 302)
- self.assertTrue(registry.primary_enabled_for(self.user))
-
-Assert on `primary_enabled_for()` rather than on "a row exists" — that's the
-predicate enforcement actually uses, so it's the one that proves your factor
-protects anybody.
+**`begin_*` runs on every page load**, including a refresh and the page shown
+again after a wrong code. The example shows a fresh token each time, which is
+harmless. A factor that sends something must reuse a code that is still valid
+rather than send a new one each time, as `EmailAdapter` does.
+
+**Make single use hold under concurrency.** Two requests with the same code can
+arrive together. Spend it in one database operation whose result says whether
+you won, as the example does with `delete()`.
+
+**Store state in `Authenticator.data`**, a `JSONField`. There is no per-factor
+table.
+
+**Hash what you only need to compare.** `data` is stored as plain JSON, readable
+by anyone who can read the table. Use `make_password` and `check_password`, as the
+example and recovery codes do. A secret you must read back, such as a TOTP seed,
+cannot be hashed. Compare plain values with `django_mfa.utils.strings_equal`,
+never `==`, so the comparison takes the same time whatever the input.
+
+**Call `authenticator.record_usage()` after a successful verification**, so the
+security page can show when the method was last used.
+
+## Known limitations
+
+- **Display names.** `Authenticator.Type` lists only the built-in types, so for
+ your rows `get_type_display()` returns the raw type (`backup_token`). That is
+ what the security page's list of methods, the notification emails and the JSON
+ API show for a row. If it matters, replace `security.html` and label each row
+ from the matching entry in `enabled_adapters`, whose `verbose_name` is right.
+- **No database constraint for one-per-user.** The database allows only one
+ `totp`, `recovery_codes` and `email` row per user. For your type,
+ `supports_multiple = False` is checked before `complete_enroll` runs, so a
+ second submission is refused, but two submitted at the same moment can both
+ pass that check. If a duplicate would matter, add a `UniqueConstraint` of your
+ own.
+- **`MFA_FACTORS` lists built-ins only.** Your factor is registered by your own
+ `ready()`. Naming it in `MFA_FACTORS` raises `ImproperlyConfigured`. Use your
+ own setting if you need to switch it off.
+- **Registering twice raises `ValueError`.** If your `ready()` can run more than
+ once (some test setups), check `registry.all()` before registering.
+
+## Checklist for a new factor
+
+1. An `Adapter` subclass with `type`, `verbose_name`, the flags you need, and
+ the four methods (`begin_enroll` and `complete_enroll` only if
+ `supports_enroll` is true).
+2. `registry.register(YourAdapter())` in your app's `AppConfig.ready()`.
+3. Two templates, `django_mfa/enroll_.html` and
+ `django_mfa/verify_.html`, extending `base_template` and posting the
+ fields your `complete_*` methods read, plus `next` on the verify page.
+4. Tests: a successful enroll, a successful verify, a wrong attempt returning
+ 400, and whatever your factor promises beyond that (single use, one per
+ user, not counting as primary).
diff --git a/docs/customizing.md b/docs/customizing.md
index 8ba8e37..a951c9d 100644
--- a/docs/customizing.md
+++ b/docs/customizing.md
@@ -1,205 +1,307 @@
# Customizing the UI
-django-mfa ships working screens so you don't have to build them, not so you have to
-keep them. Everything below is overridable, in roughly increasing order of effort.
-
-## Start here: point at your own base template
-
-Every django-mfa page extends whatever `MFA_BASE_TEMPLATE` names, and the built-in
-`django_mfa/base.html` exists only so the package works before you've configured
-anything. Replacing it is usually the entire job:
-
- MFA_BASE_TEMPLATE = "base.html" # your project's own base template
-
-Your template needs to provide one thing: a `{% block content %}` for the pages to
-fill. If yours already has one (most do), you are finished — the MFA screens now
-carry your navigation, your CSS, and your footer.
-
-If your base block has a different name, wrap it rather than renaming everything:
+Three ways to make the MFA screens fit your site, in order of effort. Most
+projects only need the first.
+
+1. [Use your own base template](#use-your-own-base-template).
+2. [Restyle the bundled pages](#restyle-the-bundled-pages) with CSS custom
+ properties.
+3. [Replace individual templates](#replace-individual-templates).
+
+The rest of the page is reference: each template's context, and the rules the
+WebAuthn pages must follow.
+
+## Use your own base template
+
+```python
+# settings.py
+MFA_BASE_TEMPLATE = "base.html"
+```
+
+Your template needs a `{% block content %}`, which every MFA page fills. Open the
+security page (`/mfa/security/` if you mounted the URLs at `mfa/`) and you should
+see it inside your own header and footer.
+
+The bundled stylesheet, `django_mfa/style.css`, is linked only from the default
+base template, so with your own the pages use your CSS. Their classes are listed
+under [Class names](#class-names).
+
+### If your content block has another name
+
+Point the setting at a wrapper template instead. This one maps a `main` block to
+`content`, and loads the bundled stylesheet on the MFA pages only:
+
+```html+django
+{# templates/mfa_base.html #}
+{% extends "base.html" %}
+{% load static %}
+{% block extra_head %}{{ block.super }}{% endblock %}
+{% block main %}{% block content %}{% endblock %}{% endblock %}
+```
+
+```python
+# settings.py
+MFA_BASE_TEMPLATE = "mfa_base.html"
+```
+
+Replace `extra_head` with your base template's head block, or drop that line. The
+bundled stylesheet also styles `body`, headings, links and form controls, so it
+changes your header's look on those pages too.
+
+### Keep the bundled layout, change the header
+
+The default base template has a `nav_menu` block for its header bar (and a
+`main_modifier` block, which the security page uses to widen ``). Override
+the header in a wrapper, and point `MFA_BASE_TEMPLATE` at it as above:
+
+```html+django
+{# templates/mfa_base.html #}
+{% extends "django_mfa/base.html" %}
+{% block nav_menu %}
+
+
+
+{% endblock %}
+```
+
+## Restyle the bundled pages
+
+Load your own stylesheet after `django_mfa/style.css`, and redefine the custom
+properties it is built from:
+
+```css
+/* static/css/mfa.css, loaded after django_mfa/style.css */
+:root {
+ --mfa-accent: #7c3aed;
+ --mfa-accent-hover: #6d28d9;
+ --mfa-focus: #7c3aed;
+ --mfa-radius: 4px;
+ --mfa-radius-sm: 4px;
+}
+```
+
+Link it from your own base template or a wrapper like the one above. The default
+base template has no head block to extend; to keep it, replace
+`django_mfa/base.html` with a copy that adds your ``.
+
+### Custom properties
+
+| Property | Controls |
+|---|---|
+| `--mfa-bg` | Page background |
+| `--mfa-surface` | Cards, the header bar, inputs and buttons |
+| `--mfa-surface-alt` | Subtle fills: the QR panel, the recovery-code grid, ``, hover backgrounds |
+| `--mfa-text` | Body and heading text |
+| `--mfa-muted` | Secondary text: intros, hints, dates |
+| `--mfa-border` | Card borders and list dividers |
+| `--mfa-border-strong` | Borders of inputs, secondary buttons and method links |
+| `--mfa-accent` | Links, primary buttons, focused inputs |
+| `--mfa-accent-hover` | Primary buttons on hover |
+| `--mfa-on-accent` | Text on primary buttons |
+| `--mfa-focus` | Keyboard focus outline |
+| `--mfa-danger` | Error text, and the "Remove" button's text |
+| `--mfa-danger-bg` | Error banner background, and the "Remove" button on hover |
+| `--mfa-danger-border` | Error banner border |
+| `--mfa-radius` | Card corners |
+| `--mfa-radius-sm` | Corners of buttons, inputs, method links and error banners |
+| `--mfa-shadow` | Card shadow |
+
+The colour properties get different values inside
+`@media (prefers-color-scheme: dark)`. A `:root` rule of yours outside a media
+query applies in both modes, so put dark-mode values in a dark-mode media query of
+your own. The "MFA is required" notice (`.mfa-notice--warning`) uses fixed colours,
+not these properties.
+
+### Class names
- {% comment %} myapp/templates/mfa_base.html {% endcomment %}
- {% extends "base.html" %}
- {% block main %}{% block content %}{% endblock %}{% endblock %}
+| Class | Where |
+|---|---|
+| `.mfa-header`, `.mfa-header__inner`, `.mfa-brand` | The header bar of `django_mfa/base.html` |
+| `.mfa-main`, `.mfa-main--wide` | ``; the security page is the wide one |
+| `.mfa-card`, `.mfa-card__title` | Each panel, and a panel's heading row |
+| `.mfa-lede`, `.mfa-muted`, `.mfa-empty` | Intro text, secondary text, "nothing here yet" text |
+| `.mfa-notice`, `.mfa-notice--warning` | The "MFA is required" notice on the security page |
+| `.mfa-list`, `.mfa-item`, `.mfa-item__text`, `.mfa-item__name`, `.mfa-item__meta` | The list of enrolled methods |
+| `.mfa-picker` | The method chooser, and the "Add a method" list |
+| `.mfa-actions` | A row of buttons; stacks full width below 26rem |
+| `.mfa-alert` | Error banners, including the WebAuthn ones |
+| `.mfa-code-input`, `.mfa-code-input--wide` | The one-time code field; the wide one is for recovery codes |
+| `.mfa-qr`, `.qrcode`, `.mfa-secret` | The TOTP QR panel, the QR image, the secret to type in |
+| `.mfa-codes`, `.recovery-code` | The recovery-code grid, and each code |
- MFA_BASE_TEMPLATE = "mfa_base.html"
+Buttons and forms use the common names `.btn`, `.btn-primary`, `.btn-default`,
+`.btn-danger`, `.btn-sm`, `.form-group`, `.form-control`, `.help-block` and
+`.text-danger`, so a CSS framework that defines them styles the pages without the
+bundled stylesheet.
-The built-in pages also set a `title` context variable where relevant, which
-`django_mfa/base.html` renders as `{{ title|default:_("Two-factor authentication") }}`.
-Use it in your own base template if you want per-page titles.
+## Replace individual templates
-`base.html` exposes two blocks of its own: `nav_menu` (the small header bar) and
-`main_modifier` (an extra class on ``, which the security page uses to widen
-itself). An earlier release also had an empty `left_bar` block for a sidebar column
-that was never filled; it is gone.
+Put a file at the same path in a directory listed in `TEMPLATES["DIRS"]`, or in
+the `templates/` folder of an app listed before `django_mfa` in `INSTALLED_APPS`:
-## Replacing individual pages
+```text
+templates/django_mfa/verify_totp.html
+```
-Templates are loaded by path, so an app listed **before** `django_mfa` in
-`INSTALLED_APPS` — or any directory in `TEMPLATES["DIRS"]` — can shadow any of them
-by putting a file at the same path:
+Start from a copy of the original. This prints where they are installed:
- myproject/templates/django_mfa/security.html
+```bash
+python -c "import django_mfa, pathlib; print(pathlib.Path(django_mfa.__file__).parent / 'templates' / 'django_mfa')"
+```
-The full set:
+Text you keep unchanged inside `{% trans %}` keeps its translations. Text you
+change or add is yours to translate; see {doc}`translations`.
-| Template | Rendered by | When |
+| Template | URL name | Shown |
|---|---|---|
-| `django_mfa/base.html` | all pages | the default `MFA_BASE_TEMPLATE` |
-| `django_mfa/security.html` | `mfa:security_settings` | the account's MFA overview |
-| `django_mfa/picker.html` | `mfa:verify` | at login, when the user holds more than one method |
-| `django_mfa/enroll_totp.html` | `mfa:enroll_factor` | setting up an authenticator app |
-| `django_mfa/enroll_webauthn.html` | `mfa:enroll_factor` | registering a security key or passkey |
-| `django_mfa/enroll_email.html` | `mfa:enroll_factor` | confirming an emailed one-time code (`"email"` in `MFA_FACTORS`, off by default — see {doc}`security`) |
-| `django_mfa/verify_totp.html` | `mfa:verify_factor` | the TOTP challenge |
-| `django_mfa/verify_webauthn.html` | `mfa:verify_factor` | the WebAuthn challenge |
-| `django_mfa/verify_recovery_codes.html` | `mfa:verify_factor` | the recovery-code challenge |
-| `django_mfa/verify_email.html` | `mfa:verify_factor` | the emailed-code challenge |
-| `django_mfa/recovery_codes.html` | `mfa:recovery_codes` | displaying freshly generated codes |
-
-Enroll and verify templates are resolved from the factor type, as
-`django_mfa/enroll_.html` and `django_mfa/verify_.html`. That naming is
-the contract — it's also how a custom factor gets its screens, with no view changes
-(see {doc}`custom_factors`).
+| `django_mfa/base.html` | (all pages) | The default `MFA_BASE_TEMPLATE` |
+| `django_mfa/security.html` | `mfa:security_settings` | The user's methods, "Add a method", recovery codes |
+| `django_mfa/picker.html` | `mfa:verify` | At login, to a user with more than one method |
+| `django_mfa/enroll_totp.html` | `mfa:enroll_factor` | Setting up an authenticator app |
+| `django_mfa/enroll_webauthn.html` | `mfa:enroll_factor` | Registering a security key or passkey |
+| `django_mfa/enroll_email.html` | `mfa:enroll_factor` | Confirming an emailed code (when `"email"` is in `MFA_FACTORS`) |
+| `django_mfa/verify_totp.html` | `mfa:verify_factor` | The authenticator-app challenge |
+| `django_mfa/verify_webauthn.html` | `mfa:verify_factor` | The security key or passkey challenge |
+| `django_mfa/verify_recovery_codes.html` | `mfa:verify_factor` | The recovery-code challenge |
+| `django_mfa/verify_email.html` | `mfa:verify_factor` | The emailed-code challenge |
+| `django_mfa/recovery_codes.html` | `mfa:recovery_codes` | Newly generated recovery codes |
+| `django_mfa/email/*.txt` | (none) | The emails; see [Emails](#emails) |
+
+Enroll and verify pages are named after the factor type:
+`django_mfa/enroll_.html` and `django_mfa/verify_.html`. A custom
+factor gets its pages the same way; see {doc}`custom_factors`.
## Template context
-What each page gives you. Every page additionally receives `base_template`, which is
-what the `{% extends base_template %}` line at the top resolves.
+Every page receives `base_template` (the value of `MFA_BASE_TEMPLATE`) and starts
+with `{% extends base_template %}`.
### `security.html`
| Variable | What it is |
|---|---|
-| `enabled_adapters` | Adapters this user holds at least one of. Distinct *types*. |
-| `available_adapters` | Adapters the user could still add. Already excludes singletons they hold and factors that aren't enrolled at all. Link each to `{% url 'mfa:enroll_factor' adapter.type %}`. |
-| `authenticators` | The individual `Authenticator` rows, ordered by type then creation. This — not `enabled_adapters` — is what lets you list three security keys separately so a user can tell them apart and remove exactly one. |
-| `recovery_codes_remaining` | Integer count of unused codes. |
-| `owned_by_enterprise` | The `MFA_OWNED_BY_ENTERPRISE` setting, so the template can hide the remove button for WebAuthn. |
-| `mfa_enrollment_required` | `True` only when this user is both required to hold a factor (`MFA_REQUIRED`, see {doc}`enforcement`) and holds none yet — i.e. exactly when `MfaMiddleware` walled them onto this page. If you shadow this template, render something here: without it, a required user lands on a security page that gives no reason for the wall they just hit. |
-| `grace` | A `policy.GraceState` (`required_at`, `days_remaining`) when this user would be required to enrol but is not yet, else `None`. |
+| `authenticators` | The user's `Authenticator` rows, by type then date added: one per security key, so a user can tell them apart. Each has `pk`, `type`, `name`, `created_at`, `last_used_at` and `get_type_display`. |
+| `enabled_adapters` | One adapter per method type the user holds, recovery codes included. |
+| `available_adapters` | Adapters the user can still add. Link each to `{% url 'mfa:enroll_factor' adapter.type %}`, labelled `adapter.verbose_name`. |
+| `recovery_codes_remaining` | Number of unused recovery codes. |
+| `owned_by_enterprise` | The `MFA_OWNED_BY_ENTERPRISE` setting. When true, hide the remove button on WebAuthn rows; the server refuses to remove them anyway. |
+| `mfa_enrollment_required` | True when `MFA_REQUIRED` applies to the user and they hold no method other than recovery codes, which is when the middleware sends them here. Say why, or they arrive with no explanation. |
+| `grace` | While `MFA_REQUIRED` applies to the user and their grace period is running: an object with `required_at` and `days_remaining`. Otherwise `None`. Set whether or not they have enrolled; see {doc}`enforcement`. |
+
+To remove a method, POST its `pk` to `{% url 'mfa:manage' %}` with a CSRF token.
### `picker.html`
| Variable | What it is |
|---|---|
-| `adapters` | Every method this user can verify with **right now**, including recovery codes. Link each to `{% url 'mfa:verify_factor' adapter.type %}`. |
+| `adapters` | Every method the user can verify with, recovery codes included. Link each to `{% url 'mfa:verify_factor' adapter.type %}`. |
+| `next` | Where to go after verifying, or `None`. Append it to each link as `?next={{ next\|urlencode }}`. |
-The picker is only rendered when the user has more than one method — with exactly
-one, the view redirects straight to that method's challenge. Don't rely on this page
-being seen.
+A user with exactly one method skips this page and goes straight to that method.
-### Enroll pages
+### Enroll and verify pages
-| Variable | What it is |
-|---|---|
-| `adapter` | The adapter being enrolled. `adapter.verbose_name` is the display name. |
-| `error_message` | Present only after a failed POST; the page re-renders with HTTP 400. |
-| *(TOTP)* `secret_key` | The freshly generated Base32 secret. Must be POSTed back in a hidden field — the server does not stash it in the session. |
-| *(TOTP)* `provisioning_uri` | The `otpauth://` URI. Render it with `{% qrcode provisioning_uri "alt text" %}`. |
-| *(WebAuthn)* `options` | JSON ceremony options. Render with `{% webauthn_options_script options "webauthn-options" %}`. |
-| *(email)* `address` | The account's address, masked (`a****n@example.com`) — never the plaintext. `None` when the account has no usable address; `enroll_email.html` shows a "no address on file" message instead of the form in that case (guard on it if you shadow this page). |
-| *(email)* `code_length` | Digit count of the code just emailed — tracks `MFA_EMAIL_CODE_LENGTH` rather than assuming 6, so the input's `maxlength` and label stay correct if you change that setting. Only present alongside a non-`None` `address`. |
+All of them receive `adapter` (`adapter.verbose_name` is the display name) and,
+after a failed attempt, `error_message`; the page is then returned with HTTP 400.
+Verify pages also receive `next`, already checked against open redirects: send it
+back in a hidden field named `next`.
-### Verify pages
+Each factor adds its own variables and reads its own POST fields. Keep the field
+names if you replace a page.
-| Variable | What it is |
-|---|---|
-| `adapter` | The adapter being challenged. |
-| `next` | Where to redirect after success, already validated against open redirects. Pass it through in a hidden field named `next`. |
-| `error_message` | Present only after a failed attempt; the page re-renders with HTTP 400. |
-| *(recovery codes)* `remaining` | How many unused codes are left, so you can warn people running low. |
-| *(WebAuthn)* `options` | JSON ceremony options, as above. |
-| *(email)* `address` | The enrolled address, masked — the address captured at enrollment time, not necessarily the account's current one (see {doc}`security`). `None` when there is no live ceremony to challenge (e.g. the factor was removed after this page was linked to); `verify_email.html` shows a fallback message instead of the form in that case (guard on it if you shadow this page). |
-| *(email)* `code_length` | Digit count of the code just emailed, as on the enroll page above. Only present alongside a non-`None` `address`. |
+| Page | Extra context | Fields to POST |
+|---|---|---|
+| `enroll_totp.html` | `secret_key`, `provisioning_uri` | `secret_key` (hidden; the server does not keep it), `code` |
+| `verify_totp.html` | none | `code`, `next` |
+| `enroll_webauthn.html` | `options` | `credential` (filled in by the script), `name` (optional label, up to 100 characters) |
+| `verify_webauthn.html` | `options` | `credential`, `next` |
+| `verify_recovery_codes.html` | `remaining` (unused codes left) | `code`, `next` |
+| `enroll_email.html` | `address`, `code_length` | `code` |
+| `verify_email.html` | `address`, `code_length` | `code`, `next` |
+
+On the email pages, `address` is masked (`a****n@example.com`). It is `None` when
+there is nothing to send to (no usable address on the account, or no email factor
+to verify); show a message instead of the form, as the bundled templates do.
+`code_length` follows `MFA_EMAIL_CODE_LENGTH`; use it for the input's `maxlength`.
### `recovery_codes.html`
| Variable | What it is |
|---|---|
-| `codes` | A list of plaintext codes on the visit that generates them, and `None` on every visit after. Codes are hashed at rest and cannot be shown twice — your template must handle `None`. |
-| `next_url` | Resolved `LOGIN_REDIRECT_URL`, for the "done" link. |
+| `codes` | The new codes on the visit that generates them, and `None` on every visit after. They are stored hashed and cannot be shown twice. |
+| `next_url` | `LOGIN_REDIRECT_URL`, resolved, for the "Done" link. |
-## The QR code
+### Emails
-`{% qrcode provisioning_uri "Scan this code" %}` (from `{% load otp_tags %}`) renders
-an inline SVG data URI. It is generated entirely server-side — no third-party
-service, no external request, and your users' TOTP secrets never leave your process.
-If you replace `enroll_totp.html`, keep using this tag rather than a QR image API.
+Each email is `django_mfa/email/.txt` for the body and
+`django_mfa/email/_subject.txt` for the subject, which is collapsed onto one
+line.
-## Rules for the WebAuthn templates
-
-WebAuthn pages are driven by `django_mfa/static/django_mfa/webauthn.js`, which finds
-its elements **by ID**. Restyle these pages freely, but keep the IDs and the
-`name` attributes — the script silently does nothing if they're missing, and it will
-look like the button is simply dead.
-
-`enroll_webauthn.html` and `verify_webauthn.html` need:
-
-| Hook | Why |
-|---|---|
-| `id="webauthn-form"` with `data-mode="create"` (enroll) or `data-mode="get"` (verify) | The form the script drives; `data-mode` picks the ceremony. |
-| `id="webauthn-start"` | The button the script binds its click handler to. Keep it `type="button"`. |
-| `` | Where the script writes the ceremony result before submitting. |
-| `id="webauthn-options"` via `{% webauthn_options_script options "webauthn-options" %}` | The ceremony options. Use the tag — see below. |
-| `id="webauthn-unsupported"` | Shown when the browser has no WebAuthn support. |
-| `id="webauthn-error"` | Where ceremony errors are written. |
+| Name | Sent when | Context |
+|---|---|---|
+| `otp_code` | An emailed code is issued | `code`, `user`, `validity_minutes` |
+| `factor_added` | A method is added | `user`, `factor`, `name` |
+| `factor_removed` | A method is removed | `user`, `factor`, `name` |
+| `mfa_disabled` | A removal leaves no method except recovery codes | `user` |
+| `recovery_code_used` | A recovery code is used | `user`, `remaining` |
-For a passkey button on your own login page the IDs are
-`webauthn-passkey-form`, `webauthn-passkey-start`, `webauthn-passkey-unsupported`
-and `webauthn-passkey-error` — see {doc}`recipes`.
+All but `otp_code` are sent only when `MFA_NOTIFY_ON_CHANGE` is on. `factor` is
+the method's display name and `name` a security key's label (often empty).
+`MFA_EMAIL_SUBJECT`, when set, replaces `otp_code_subject.txt`.
-:::{warning}
-**Use `{% webauthn_options_script %}`, not `{{ options|json_script:"..." }}`.**
-`options` is already a JSON *string*. Django's built-in `json_script` filter would
-encode it a second time, so the browser's single `JSON.parse()` hands back the
-original JSON text as a string instead of an object, `options.publicKey` comes out
-`undefined`, and the ceremony never starts. This breaks only in a real browser —
-every server-side test still passes, because the page rendered fine.
-:::
+## The QR code tag
-The bundled stylesheet (`static/django_mfa/style.css`) carries one rule that is not
-cosmetic:
+```html+django
+{% load otp_tags %}
+{% qrcode provisioning_uri "Scan this code with your authenticator app" %}
+```
- [hidden] { display: none !important; }
+This renders an `` holding an SVG drawn on your server, so the
+TOTP secret never goes to another service. Keep using it if you replace
+`enroll_totp.html`. `otp_tags` also has the `mask_email` filter the security page
+uses.
-The HTML `hidden` attribute is implemented by a user-agent rule whose specificity
-loses to *any* class selector that sets `display`. Without the `!important`, a
-`.mfa-alert { display: block }` beats it and the "your browser does not support
-WebAuthn" banner shows permanently — on browsers that support it perfectly well. If
-you replace the stylesheet entirely, carry that rule over.
+## WebAuthn template contract
-## Text and translation
+`django_mfa/static/django_mfa/webauthn.js` drives the security key pages and
+finds its elements by `id`. Restyle freely, but keep the elements below. Without
+any of the first five, the button does nothing or fails after the browser prompt,
+usually with no message on the page.
-Every string is wrapped in `{% trans %}` / `{% blocktrans %}` and ships under the
-`django_mfa` app, so `makemessages` picks it up like any other app's text. To change
-wording without translating, override the template.
+`enroll_webauthn.html` and `verify_webauthn.html` need:
-## Styling without touching templates
+| Element | Purpose |
+|---|---|
+| `