Coverage for src/django_device_bound_sessions/cookies.py: 100%
36 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"""The short-lived cookie that DBSC binds to the device key."""
3from django.core import signing
4from django.http import HttpRequest, HttpResponseBase
5from django.utils.crypto import constant_time_compare
7from .conf import dbsc_settings
9BOUND_COOKIE_SALT = "django_device_bound_sessions.bound_cookie"
12def make_bound_value(session_id: str) -> str:
13 return signing.dumps(session_id, salt=BOUND_COOKIE_SALT)
16def verify_bound_cookie(request: HttpRequest, session_id: str) -> bool:
17 value = request.COOKIES.get(dbsc_settings.BOUND_COOKIE_NAME)
18 if not value:
19 return False
20 max_age = dbsc_settings.BOUND_COOKIE_AGE + dbsc_settings.BOUND_COOKIE_GRACE
21 try:
22 found = signing.loads(value, salt=BOUND_COOKIE_SALT, max_age=max_age)
23 except signing.BadSignature:
24 return False
25 return isinstance(found, str) and constant_time_compare(found, session_id)
28def set_bound_cookie(response: HttpResponseBase, session_id: str) -> None:
29 s = dbsc_settings
30 response.set_cookie(
31 s.BOUND_COOKIE_NAME,
32 make_bound_value(session_id),
33 max_age=s.BOUND_COOKIE_AGE,
34 domain=s.BOUND_COOKIE_DOMAIN,
35 path=s.BOUND_COOKIE_PATH,
36 secure=s.BOUND_COOKIE_SECURE,
37 httponly=s.BOUND_COOKIE_HTTPONLY,
38 samesite=s.BOUND_COOKIE_SAMESITE,
39 )
42def delete_bound_cookie(response: HttpResponseBase) -> None:
43 s = dbsc_settings
44 response.delete_cookie(
45 s.BOUND_COOKIE_NAME,
46 path=s.BOUND_COOKIE_PATH,
47 domain=s.BOUND_COOKIE_DOMAIN,
48 samesite=s.BOUND_COOKIE_SAMESITE,
49 )
52def credential_attributes() -> str:
53 """Cookie attributes for the session config's ``credentials`` entry.
55 These must match how the cookie is actually set, because the browser uses
56 them to decide which cookie it is guarding.
57 """
58 s = dbsc_settings
59 parts: list[str] = []
60 if s.BOUND_COOKIE_DOMAIN:
61 parts.append(f"Domain={s.BOUND_COOKIE_DOMAIN}")
62 parts.append(f"Path={s.BOUND_COOKIE_PATH}")
63 if s.BOUND_COOKIE_SECURE:
64 parts.append("Secure")
65 if s.BOUND_COOKIE_HTTPONLY:
66 parts.append("HttpOnly")
67 if s.BOUND_COOKIE_SAMESITE:
68 parts.append(f"SameSite={s.BOUND_COOKIE_SAMESITE}")
69 return "; ".join(parts)