Coverage for src/django_device_bound_sessions/api.py: 100%

85 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-06 02:43 -0600

1"""Public helpers for integrating DBSC into views and auth flows.""" 

2 

3import time 

4from dataclasses import dataclass, replace 

5from datetime import datetime 

6from typing import Any, Self, cast 

7 

8from django.contrib.sessions.backends.base import SessionBase 

9from django.core.exceptions import ImproperlyConfigured 

10from django.http import HttpRequest 

11from django.urls import reverse 

12 

13from .challenges import new_refresh_challenge, new_registration_challenge 

14from .conf import BINDING_KEY, OFFER_KEY, dbsc_settings 

15from .cookies import credential_attributes 

16from .proof import JWK 

17from .structured_fields import Token, serialize_inner_list, serialize_item 

18 

19REGISTRATION_HEADER = "Secure-Session-Registration" 

20CHALLENGE_HEADER = "Secure-Session-Challenge" 

21RESPONSE_HEADER = "Secure-Session-Response" 

22SESSION_ID_HEADER = "Sec-Secure-Session-Id" 

23 

24 

25@dataclass(frozen=True) 

26class DeviceBinding: 

27 """The device key a Django session is bound to, stored in the session. 

28 

29 Its lifetime is the Django session's: logging out or flushing the session 

30 removes it, which also ends the DBSC session in the browser. 

31 """ 

32 

33 session_id: str 

34 algorithm: str 

35 public_key: JWK 

36 thumbprint: str 

37 user_agent: str 

38 created_at: datetime 

39 last_refreshed_at: datetime | None = None 

40 

41 def to_session(self) -> dict[str, Any]: 

42 # Plain JSON types so any SESSION_SERIALIZER/engine can store it. 

43 return { 

44 "id": self.session_id, 

45 "alg": self.algorithm, 

46 "jwk": self.public_key, 

47 "thumbprint": self.thumbprint, 

48 "user_agent": self.user_agent, 

49 "created_at": self.created_at.isoformat(), 

50 "last_refreshed_at": ( 

51 self.last_refreshed_at.isoformat() if self.last_refreshed_at else None 

52 ), 

53 } 

54 

55 @classmethod 

56 def from_session(cls, session: SessionBase) -> Self | None: 

57 stored: object = session.get(BINDING_KEY) 

58 if not isinstance(stored, dict): 

59 return None 

60 data = cast(dict[str, Any], stored) 

61 try: 

62 refreshed = data.get("last_refreshed_at") 

63 return cls( 

64 session_id=data["id"], 

65 algorithm=data["alg"], 

66 public_key=data["jwk"], 

67 thumbprint=data["thumbprint"], 

68 user_agent=data.get("user_agent", ""), 

69 created_at=datetime.fromisoformat(data["created_at"]), 

70 last_refreshed_at=datetime.fromisoformat(refreshed) if refreshed else None, 

71 ) 

72 except (KeyError, TypeError, ValueError): 

73 return None 

74 

75 def save(self, session: SessionBase) -> None: 

76 session[BINDING_KEY] = self.to_session() 

77 

78 def refreshed(self, when: datetime) -> Self: 

79 return replace(self, last_refreshed_at=when) 

80 

81 

82@dataclass(frozen=True) 

83class DBSCState: 

84 """Attached to every request as ``request.dbsc``.""" 

85 

86 #: The device binding of this Django session, if it registered. 

87 binding: DeviceBinding | None = None 

88 #: True when the request carried a valid bound cookie for that binding. 

89 bound: bool = False 

90 

91 @property 

92 def session_id(self) -> str | None: 

93 return self.binding.session_id if self.binding else None 

94 

95 @property 

96 def registered(self) -> bool: 

97 return self.binding is not None 

98 

99 

100# There are three ways to reach the DBSC state from a view, depending on how 

101# the app types its requests: 

102# 

103# 1. Plain ``HttpRequest``: call ``get_dbsc_state(request)``. 

104# 2. ``DBSCHttpRequest``: use ``request.dbsc`` directly. 

105# 3. An app's own request class: add ``DBSCRequestMixin`` to it. 

106 

107 

108class DBSCRequestMixin: 

109 """Declares ``request.dbsc`` for an app's own typed request class:: 

110 

111 class AppRequest(DBSCRequestMixin, HttpRequest): 

112 tenant: Tenant 

113 

114 For type checking only. The middleware sets the attribute at runtime. 

115 """ 

116 

117 dbsc: DBSCState 

118 

119 

120class DBSCHttpRequest(DBSCRequestMixin, HttpRequest): 

121 """``HttpRequest`` as seen behind :class:`DeviceBoundSessionMiddleware`. 

122 

123 For type checking only; annotate views with it to use ``request.dbsc``:: 

124 

125 def view(request: DBSCHttpRequest) -> HttpResponse: 

126 if request.dbsc.bound: ... 

127 

128 Views typed against a plain ``HttpRequest`` use :func:`get_dbsc_state`. 

129 """ 

130 

131 

132def get_dbsc_state(request: HttpRequest) -> DBSCState: 

133 """The ``request.dbsc`` state, for code typed against a plain ``HttpRequest``. 

134 

135 Raises ``ImproperlyConfigured`` if the middleware hasn't run on this 

136 request, so a missing middleware fails loudly instead of looking like an 

137 unbound session. 

138 """ 

139 state = getattr(request, "dbsc", None) 

140 if not isinstance(state, DBSCState): 

141 raise ImproperlyConfigured( 

142 "request.dbsc is not set: add " 

143 "django_device_bound_sessions.middleware.DeviceBoundSessionMiddleware to MIDDLEWARE." 

144 ) 

145 return state 

146 

147 

148def get_binding(request: HttpRequest) -> DeviceBinding | None: 

149 """The device binding for this request's session, or ``None``. 

150 

151 Reads the session directly, so it works with or without the middleware. 

152 """ 

153 return DeviceBinding.from_session(request.session) 

154 

155 

156def offer_registration(request: HttpRequest) -> None: 

157 """Ask the middleware to send ``Secure-Session-Registration`` on the 

158 next suitable (non-redirect) response for this session, within 

159 ``OFFER_MAX_AGE`` seconds. 

160 

161 Called automatically on login when ``OFFER_ON_LOGIN`` is enabled. Has no 

162 effect on a session that is already bound: a binding is permanent for the 

163 life of the session, and binding a new device means logging in again. 

164 """ 

165 request.session[OFFER_KEY] = int(time.time()) 

166 

167 

168def registration_path() -> str: 

169 return dbsc_settings.REGISTRATION_PATH or reverse("django_device_bound_sessions:register") 

170 

171 

172def refresh_path() -> str: 

173 return dbsc_settings.REFRESH_PATH or reverse("django_device_bound_sessions:refresh") 

174 

175 

176def registration_header_value(request: HttpRequest) -> str: 

177 algorithms: list[str] = [Token(a) for a in dbsc_settings.ALGORITHMS if a != "none"] 

178 return serialize_inner_list( 

179 algorithms, 

180 { 

181 "path": registration_path(), 

182 "challenge": new_registration_challenge(request.session), 

183 }, 

184 ) 

185 

186 

187def challenge_header_value(session_id: str) -> str: 

188 """A ``Secure-Session-Challenge`` header value with a new refresh challenge.""" 

189 return serialize_item(new_refresh_challenge(session_id), {"id": session_id}) 

190 

191 

192def build_session_config(session_id: str) -> dict[str, Any]: 

193 """The JSON session instructions returned from registration/refresh.""" 

194 s = dbsc_settings 

195 scope: dict[str, Any] = {"include_site": bool(s.SCOPE_INCLUDE_SITE)} 

196 if s.SCOPE_ORIGIN: 

197 scope["origin"] = s.SCOPE_ORIGIN 

198 if s.SCOPE_SPECIFICATION: 

199 scope["scope_specification"] = list(s.SCOPE_SPECIFICATION) 

200 config: dict[str, Any] = { 

201 "session_identifier": session_id, 

202 "refresh_url": refresh_path(), 

203 "scope": scope, 

204 "credentials": [ 

205 { 

206 "type": "cookie", 

207 "name": s.BOUND_COOKIE_NAME, 

208 "attributes": credential_attributes(), 

209 } 

210 ], 

211 } 

212 if s.ALLOWED_REFRESH_INITIATORS: 

213 config["allowed_refresh_initiators"] = list(s.ALLOWED_REFRESH_INITIATORS) 

214 return config