Skip to content
Merged

Dev #98

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
77 changes: 77 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 4 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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/).
Expand Down
19 changes: 18 additions & 1 deletion django_mfa/adapters/totp.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
21 changes: 19 additions & 2 deletions django_mfa/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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
45 changes: 35 additions & 10 deletions django_mfa/checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 []
13 changes: 8 additions & 5 deletions django_mfa/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
19 changes: 16 additions & 3 deletions django_mfa/flows.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand Down
Loading
Loading