Coverage for src/django_device_bound_sessions/challenges.py: 100%
50 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-06 02:43 -0600
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-06 02:43 -0600
1"""Stateless, signed, short-lived challenges with single-use enforcement.
3A challenge is a value produced by ``django.core.signing`` that carries what
4it is for. Its signature and timestamp prove we issued it recently; the cache
5makes sure each one is only accepted once.
6"""
8import hashlib
9import secrets
10from typing import Any, cast
12from django.contrib.sessions.backends.base import SessionBase
13from django.core import signing
14from django.core.cache import caches
15from django.utils.crypto import constant_time_compare
17from .conf import REGISTRATION_NONCE_KEY, dbsc_settings
19REGISTRATION_SALT = "django_device_bound_sessions.challenge.registration"
20REFRESH_SALT = "django_device_bound_sessions.challenge.refresh"
23class ChallengeError(Exception):
24 pass
27class StaleChallenge(ChallengeError):
28 """The challenge was ours, but has expired or was already used."""
31def new_registration_challenge(session: SessionBase) -> str:
32 """Issue a registration challenge tied to this Django session.
34 It's answered right away and only exists before the session is bound, so
35 it gets the short ``CHALLENGE_MAX_AGE``.
36 """
37 nonce = secrets.token_urlsafe(16)
38 session[REGISTRATION_NONCE_KEY] = nonce
39 return signing.dumps({"n": nonce}, salt=REGISTRATION_SALT)
42def check_registration_challenge(session: SessionBase, challenge: str) -> None:
43 max_age = dbsc_settings.CHALLENGE_MAX_AGE
44 data = _load(challenge, REGISTRATION_SALT, max_age)
45 nonce = session.get(REGISTRATION_NONCE_KEY)
46 if not nonce or not constant_time_compare(str(data.get("n", "")), nonce):
47 raise ChallengeError("Registration challenge does not belong to this session")
48 _consume(challenge, max_age)
49 session.pop(REGISTRATION_NONCE_KEY, None)
52def refresh_challenge_lifetime() -> int:
53 """Seconds a refresh challenge stays valid: as long as a bound cookie.
55 The browser caches the challenge sent with each new bound cookie and signs
56 it when that cookie expires, so a challenge must last as long as the server
57 accepts the cookie: ``BOUND_COOKIE_AGE + BOUND_COOKIE_GRACE``. Challenges
58 sent with a 403 get the same lifetime; a shorter one wouldn't narrow the
59 worst case, which these two settings define.
60 """
61 return dbsc_settings.BOUND_COOKIE_AGE + dbsc_settings.BOUND_COOKIE_GRACE
64def new_refresh_challenge(session_id: str) -> str:
65 return signing.dumps({"s": session_id, "n": secrets.token_urlsafe(16)}, salt=REFRESH_SALT)
68def check_refresh_challenge(session_id: str, challenge: str) -> None:
69 max_age = refresh_challenge_lifetime()
70 data = _load(challenge, REFRESH_SALT, max_age)
71 if not constant_time_compare(str(data.get("s", "")), session_id):
72 raise ChallengeError("Challenge was issued for a different session")
73 _consume(challenge, max_age)
76def _load(challenge: str, salt: str, max_age: int) -> dict[str, Any]:
77 try:
78 data = signing.loads(challenge, salt=salt, max_age=max_age)
79 except signing.SignatureExpired as exc:
80 raise StaleChallenge("Challenge expired") from exc
81 except signing.BadSignature as exc:
82 raise ChallengeError("Invalid challenge") from exc
83 if not isinstance(data, dict):
84 raise ChallengeError("Invalid challenge")
85 return cast(dict[str, Any], data)
88def _consume(challenge: str, max_age: int) -> None:
89 key = "django_device_bound_sessions:jti:" + hashlib.sha256(challenge.encode()).hexdigest()
90 cache = caches[dbsc_settings.CACHE_ALIAS]
91 # Remember it a little longer than this challenge can live, so it can't be
92 # replayed after the cache forgets it.
93 if not cache.add(key, 1, timeout=max_age + 60):
94 raise StaleChallenge("Challenge already used")