Coverage for src/django_device_bound_sessions/checks.py: 100%
30 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"""Django system checks for django-device-bound-sessions.
3Run with ``manage.py check`` (and automatically by ``runserver``, ``migrate``
4and the test runner). Silence one with ``SILENCED_SYSTEM_CHECKS``.
5"""
7from collections.abc import Sequence
8from typing import Any
10from django.apps import AppConfig
11from django.conf import settings
12from django.core import checks
13from django.core.cache.backends.dummy import DummyCache
14from django.core.cache.backends.locmem import LocMemCache
15from django.utils.module_loading import import_string
17from .conf import dbsc_settings
19#: CACHE_ALIAS names a cache that isn't in CACHES.
20E001 = "django_device_bound_sessions.E001"
21#: The replay cache is a DummyCache, so replay protection is disabled.
22E002 = "django_device_bound_sessions.E002"
23#: The replay cache is per-process (LocMemCache).
24W001 = "django_device_bound_sessions.W001"
26_SHARED_CACHE_HINT = (
27 "Point DBSC['CACHE_ALIAS'] at a cache every worker shares, with an atomic add(), "
28 "such as Redis, Memcached or django.core.cache.backends.db.DatabaseCache."
29)
32@checks.register(checks.Tags.caches, checks.Tags.security)
33def check_replay_cache(
34 app_configs: Sequence[AppConfig] | None, **kwargs: Any
35) -> list[checks.CheckMessage]:
36 """The cache that makes challenges single-use must be shared by every worker.
38 Looks at the configured backend *class* without creating the cache, so the
39 check never connects anywhere or needs the backend's client library.
40 """
41 alias = dbsc_settings.CACHE_ALIAS
42 config = settings.CACHES.get(alias)
43 if config is None:
44 return [
45 checks.Error(
46 f"DBSC['CACHE_ALIAS'] is {alias!r}, which is not a cache in CACHES.",
47 hint=_SHARED_CACHE_HINT,
48 id=E001,
49 )
50 ]
51 try:
52 backend = import_string(config.get("BACKEND", ""))
53 except ImportError:
54 # A misnamed backend fails loudly as soon as the cache is used.
55 return []
56 if not isinstance(backend, type):
57 return []
58 if issubclass(backend, DummyCache):
59 return [
60 checks.Error(
61 f"The DBSC replay cache {alias!r} is a DummyCache, so replay protection "
62 "is disabled: its add() always succeeds, and a used proof can be replayed.",
63 hint=_SHARED_CACHE_HINT,
64 id=E002,
65 )
66 ]
67 if issubclass(backend, LocMemCache):
68 return [
69 checks.Warning(
70 f"The DBSC replay cache {alias!r} is a LocMemCache, which each process "
71 "keeps separately. With more than one worker, a used proof can be "
72 "replayed on another worker until its challenge expires.",
73 hint=_SHARED_CACHE_HINT + f" If you only ever run one process, silence {W001}.",
74 id=W001,
75 )
76 ]
77 return []