Coverage for src/django_device_bound_sessions/testing.py: 91%

119 statements  

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

1"""A simulated DBSC-capable browser for tests. 

2 

3Wraps a ``django.test.Client`` and plays the browser's side of the protocol: 

4it watches for ``Secure-Session-Registration``, registers a fresh key pair, 

5and refreshes the bound cookie (including the 403 challenge round trip) 

6before requests when the cookie is missing:: 

7 

8 browser = DBSCBrowser(client) 

9 client.force_login(user) 

10 browser.get("/") # receives the registration offer, registers 

11 browser.expire_bound_cookie() 

12 browser.get("/private/") # refreshes first, like Chrome would 

13""" 

14 

15from typing import TYPE_CHECKING, Any, Literal 

16 

17import jwt 

18from cryptography.hazmat.primitives.asymmetric import ec, rsa 

19from django.test import Client 

20from jwt.algorithms import ECAlgorithm, RSAAlgorithm 

21 

22from .api import CHALLENGE_HEADER, REGISTRATION_HEADER, RESPONSE_HEADER, SESSION_ID_HEADER 

23from .proof import JWK 

24from .structured_fields import parse_list, serialize_string 

25 

26if TYPE_CHECKING: 

27 # django-stubs' name for what the test client returns; not public API. 

28 from django.test.client import ( 

29 _MonkeyPatchedWSGIResponse as TestResponse, # pyright: ignore[reportPrivateUsage] 

30 ) 

31 

32type PrivateKey = ec.EllipticCurvePrivateKey | rsa.RSAPrivateKey 

33type Algorithm = Literal["ES256", "RS256"] 

34 

35 

36class DBSCBrowser: 

37 def __init__( 

38 self, 

39 client: Client, 

40 algorithm: Algorithm = "ES256", 

41 auto_register: bool = True, 

42 auto_refresh: bool = True, 

43 ) -> None: 

44 self.client = client 

45 self.algorithm: Algorithm = algorithm 

46 self.auto_register = auto_register 

47 self.auto_refresh = auto_refresh 

48 self.private_key: PrivateKey 

49 if algorithm == "ES256": 

50 self.private_key = ec.generate_private_key(ec.SECP256R1()) 

51 elif algorithm == "RS256": 

52 self.private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048) 

53 else: 

54 raise ValueError(f"Unsupported algorithm {algorithm!r}") 

55 #: ``(path, challenge)`` from the last registration offer, until used. 

56 self.pending_registration: tuple[str, str | None] | None = None 

57 #: The last session config received from the server. 

58 self.config: dict[str, Any] | None = None 

59 #: The cached refresh challenge. 

60 self.challenge: str | None = None 

61 #: Every response from the most recent :meth:`refresh`. 

62 self.last_refresh_responses: list[TestResponse] = [] 

63 

64 # -- keys / proofs ---------------------------------------------------- 

65 

66 @property 

67 def public_jwk(self) -> JWK: 

68 public_key = self.private_key.public_key() 

69 if isinstance(public_key, ec.EllipticCurvePublicKey): 

70 return ECAlgorithm.to_jwk(public_key, as_dict=True) 

71 return RSAAlgorithm.to_jwk(public_key, as_dict=True) 

72 

73 def make_proof( 

74 self, 

75 jti: str | None, 

76 include_jwk: bool = False, 

77 key: PrivateKey | None = None, 

78 **extra_claims: Any, 

79 ) -> str: 

80 headers: dict[str, Any] = {"typ": "dbsc+jwt"} 

81 if include_jwk: 

82 headers["jwk"] = self.public_jwk 

83 return jwt.encode( 

84 {"jti": jti, **extra_claims}, 

85 key or self.private_key, 

86 algorithm=self.algorithm, 

87 headers=headers, 

88 ) 

89 

90 # -- state ------------------------------------------------------------ 

91 

92 @property 

93 def session_config(self) -> dict[str, Any]: 

94 """The current session config. Raises if the browser isn't registered.""" 

95 if self.config is None: 

96 raise RuntimeError("Not registered: no session config") 

97 return self.config 

98 

99 @property 

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

101 return self.config["session_identifier"] if self.config else None 

102 

103 @property 

104 def bound_cookie_name(self) -> str | None: 

105 return self.config["credentials"][0]["name"] if self.config else None 

106 

107 def has_bound_cookie(self) -> bool: 

108 name = self.bound_cookie_name 

109 morsel = self.client.cookies.get(name) if name else None 

110 return bool(morsel and morsel.value and morsel["max-age"] not in (0, "0")) 

111 

112 def expire_bound_cookie(self) -> None: 

113 if self.bound_cookie_name: 113 ↛ exitline 113 didn't return from function 'expire_bound_cookie' because the condition on line 113 was always true

114 self.client.cookies.pop(self.bound_cookie_name, None) 

115 

116 # -- protocol --------------------------------------------------------- 

117 

118 def observe(self, response: "TestResponse") -> "TestResponse": 

119 """Process DBSC headers on a response, as a browser would.""" 

120 if REGISTRATION_HEADER in response.headers: 

121 for item, params in parse_list(response.headers[REGISTRATION_HEADER]): 121 ↛ 127line 121 didn't jump to line 127 because the loop on line 121 didn't complete

122 algs = [v for v, _ in item] if isinstance(item, list) else [] 

123 path = params.get("path") 

124 if self.algorithm in algs and path is not None: 124 ↛ 121line 124 didn't jump to line 121 because the condition on line 124 was always true

125 self.pending_registration = (path, params.get("challenge")) 

126 break 

127 if CHALLENGE_HEADER in response.headers: 

128 for value, params in parse_list(response.headers[CHALLENGE_HEADER]): 

129 if not isinstance(value, str): 129 ↛ 130line 129 didn't jump to line 130 because the condition on line 129 was never true

130 continue 

131 if self.session_id is None or params.get("id") == self.session_id: 131 ↛ 128line 131 didn't jump to line 128 because the condition on line 131 was always true

132 self.challenge = value 

133 return response 

134 

135 def register(self) -> "TestResponse": 

136 if self.pending_registration is None: 

137 raise RuntimeError("No pending registration offer") 

138 path, challenge = self.pending_registration 

139 self.pending_registration = None 

140 proof = self.make_proof(challenge, include_jwk=True) 

141 response = self.client.post(path, headers={RESPONSE_HEADER: serialize_string(proof)}) 

142 if response.status_code == 200: 142 ↛ 146line 142 didn't jump to line 146 because the condition on line 142 was always true

143 self.config = response.json() 

144 self.challenge = None 

145 self.observe(response) 

146 return response 

147 

148 def refresh(self, max_attempts: int = 3) -> "TestResponse": 

149 """Run the refresh flow. Returns the final response.""" 

150 if self.config is None or self.session_id is None: 

151 raise RuntimeError("Not registered") 

152 session_id = self.session_id 

153 refresh_url: str = self.config["refresh_url"] 

154 self.last_refresh_responses = [] 

155 for _ in range(max_attempts): 155 ↛ 164line 155 didn't jump to line 164 because the loop on line 155 didn't complete

156 headers = {SESSION_ID_HEADER: serialize_string(session_id)} 

157 if self.challenge: 

158 headers[RESPONSE_HEADER] = serialize_string(self.make_proof(self.challenge)) 

159 self.challenge = None 

160 response = self.observe(self.client.post(refresh_url, headers=headers)) 

161 self.last_refresh_responses.append(response) 

162 if not (response.status_code == 403 and self.challenge): 

163 break 

164 response = self.last_refresh_responses[-1] 

165 if response.status_code == 200: 165 ↛ 171line 165 didn't jump to line 171 because the condition on line 165 was always true

166 body: dict[str, Any] = response.json() if response.content else {} 

167 if body.get("continue") is False: 

168 self.config = None 

169 elif body: 169 ↛ 173line 169 didn't jump to line 173 because the condition on line 169 was always true

170 self.config = body 

171 elif 400 <= response.status_code < 500 and response.status_code not in (403, 407, 429): 

172 self.config = None # the browser terminates the session 

173 return response 

174 

175 # -- requests --------------------------------------------------------- 

176 

177 def request(self, method: Literal["get", "post"], path: str, **kwargs: Any) -> "TestResponse": 

178 if self.auto_refresh and self.config and not self.has_bound_cookie(): 

179 self.refresh() 

180 send = self.client.get if method == "get" else self.client.post 

181 response = self.observe(send(path, **kwargs)) 

182 if self.auto_register and self.pending_registration: 

183 self.register() 

184 return response 

185 

186 def get(self, path: str, **kwargs: Any) -> "TestResponse": 

187 return self.request("get", path, **kwargs) 

188 

189 def post(self, path: str, **kwargs: Any) -> "TestResponse": 

190 return self.request("post", path, **kwargs)