Coverage for src/django_device_bound_sessions/views.py: 100%
76 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
1import logging
2import secrets
3from collections.abc import Callable
5from django.contrib.auth import SESSION_KEY as AUTH_SESSION_KEY
6from django.http import HttpRequest, HttpResponse, HttpResponseBase, JsonResponse
7from django.utils import timezone
8from django.views.decorators.cache import never_cache
9from django.views.decorators.clickjacking import xframe_options_deny
10from django.views.decorators.csrf import csrf_exempt
11from django.views.decorators.http import require_http_methods
13from .api import (
14 CHALLENGE_HEADER,
15 RESPONSE_HEADER,
16 SESSION_ID_HEADER,
17 DeviceBinding,
18 build_session_config,
19 challenge_header_value,
20)
21from .challenges import (
22 ChallengeError,
23 StaleChallenge,
24 check_refresh_challenge,
25 check_registration_challenge,
26)
27from .conf import dbsc_settings
28from .cookies import delete_bound_cookie, set_bound_cookie
29from .decorators import dbsc_exempt
30from .proof import (
31 ProofError,
32 jwk_thumbprint,
33 parse_proof_header,
34 verify_refresh_proof,
35 verify_registration_proof,
36)
37from .structured_fields import StructuredFieldError, parse_string_item
39logger = logging.getLogger("django_device_bound_sessions")
42View = Callable[[HttpRequest], HttpResponseBase]
45def _endpoint(view: View) -> View:
46 # The browser calls these directly, without a CSRF token; the signed
47 # challenge in the proof is what authenticates the request.
48 # require_http_methods(["POST"]) is exactly require_POST, but django-stubs
49 # types it as a generic function, which every type checker (incl. ty) can solve.
50 post_only = require_http_methods(["POST"])
51 return csrf_exempt(post_only(never_cache(xframe_options_deny(dbsc_exempt(view)))))
54def _error(status: int, message: str) -> HttpResponse:
55 logger.info("DBSC request rejected: %s", message)
56 return HttpResponse(message, status=status, content_type="text/plain")
59def _terminate_response() -> JsonResponse:
60 response = JsonResponse({"continue": False})
61 delete_bound_cookie(response)
62 return response
65def _challenge(session_id: str) -> HttpResponse:
66 response = HttpResponse(status=403)
67 response.headers[CHALLENGE_HEADER] = challenge_header_value(session_id)
68 return response
71@_endpoint
72def register(request: HttpRequest) -> HttpResponseBase:
73 """Registration endpoint: the browser POSTs a proof carrying its new key."""
74 if AUTH_SESSION_KEY not in request.session:
75 return _error(401, "Not logged in")
76 if DeviceBinding.from_session(request.session) is not None:
77 # A session is bound to the device that registered it, for good.
78 # Rebinding would let anyone holding the session cookie move the
79 # session to their own device; binding a new device means a new login.
80 return _error(409, "Session is already bound to a device")
82 try:
83 token = parse_proof_header(request.headers.get(RESPONSE_HEADER))
84 proof = verify_registration_proof(token, dbsc_settings.ALGORITHMS)
85 check_registration_challenge(request.session, proof.claims["jti"])
86 except (ProofError, ChallengeError) as exc:
87 return _error(400, str(exc))
89 binding = DeviceBinding(
90 session_id=secrets.token_urlsafe(32),
91 algorithm=proof.algorithm,
92 public_key=proof.jwk,
93 thumbprint=jwk_thumbprint(proof.jwk),
94 user_agent=request.headers.get("User-Agent", "")[:512],
95 created_at=timezone.now(),
96 )
97 binding.save(request.session)
99 response = JsonResponse(build_session_config(binding.session_id))
100 set_bound_cookie(response, binding.session_id)
101 # Send the next challenge ahead: the browser caches it and signs it on its
102 # first refresh, skipping the 403 round trip. It stays valid as long as the
103 # bound cookie does (see refresh_challenge_lifetime).
104 response.headers[CHALLENGE_HEADER] = challenge_header_value(binding.session_id)
105 return response
108@_endpoint
109def refresh(request: HttpRequest) -> HttpResponseBase:
110 """Refresh endpoint: exchange proof of key possession for a bound cookie."""
111 try:
112 session_id = parse_string_item(request.headers.get(SESSION_ID_HEADER, ""))
113 except StructuredFieldError:
114 return _error(400, "Missing or malformed Sec-Secure-Session-Id")
116 # The binding lives in the Django session, so the long-lived session
117 # cookie must accompany the refresh. If it's gone, expired, logged out,
118 # or bound to a different key, tell the browser to stop refreshing.
119 binding = DeviceBinding.from_session(request.session)
120 if (
121 binding is None
122 or binding.session_id != session_id
123 or AUTH_SESSION_KEY not in request.session
124 ):
125 return _terminate_response()
127 header = request.headers.get(RESPONSE_HEADER)
128 if not header:
129 return _challenge(session_id)
131 try:
132 token = parse_proof_header(header)
133 proof = verify_refresh_proof(token, binding.algorithm, binding.public_key)
134 check_refresh_challenge(session_id, proof.claims["jti"])
135 except StaleChallenge:
136 return _challenge(session_id)
137 except (ProofError, ChallengeError) as exc:
138 # Not proof of this key: reject without unbinding, so a stolen
139 # cookie can't be used to kill the legitimate device's session.
140 return _error(400, str(exc))
142 binding.refreshed(timezone.now()).save(request.session)
144 response = JsonResponse(build_session_config(session_id))
145 set_bound_cookie(response, session_id)
146 response.headers[CHALLENGE_HEADER] = challenge_header_value(session_id)
147 return response