Coverage for src/django_device_bound_sessions/proof.py: 100%
96 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"""Verification of DBSC proof JWTs (``typ: dbsc+jwt``)."""
3import base64
4import hashlib
5import json
6from collections.abc import Iterable
7from dataclasses import dataclass
8from typing import Any, cast
10import jwt
11from cryptography.hazmat.primitives.asymmetric import ec, rsa
13from .structured_fields import StructuredFieldError, parse_string_item
15#: A JSON Web Key (RFC 7517) as a decoded JSON object.
16type JWK = dict[str, Any]
17type PublicKey = rsa.RSAPublicKey | ec.EllipticCurvePublicKey
19SUPPORTED_ALGORITHMS = ("ES256", "RS256")
20PROOF_TYP = "dbsc+jwt"
21MIN_RSA_BITS = 2048
23_PUBLIC_MEMBERS = {"EC": ("crv", "kty", "x", "y"), "RSA": ("e", "kty", "n")}
24_PRIVATE_MEMBERS = {"d", "p", "q", "dp", "dq", "qi", "oth", "k"}
27class ProofError(Exception):
28 """The proof is malformed or does not verify."""
31@dataclass(frozen=True)
32class Proof:
33 """A verified proof JWT."""
35 algorithm: str
36 claims: dict[str, Any]
39@dataclass(frozen=True)
40class RegistrationProof(Proof):
41 """A verified registration proof, with the public key it carried."""
43 jwk: JWK
46def parse_proof_header(value: str | None) -> str:
47 """Extract the JWT from a ``Secure-Session-Response`` header.
49 The spec makes it a structured-field string; Chrome's docs show it bare, so a bare
50 token is accepted too.
51 """
52 if not value:
53 raise ProofError("Missing Secure-Session-Response header")
54 try:
55 token = parse_string_item(value)
56 except StructuredFieldError as exc:
57 raise ProofError(f"Malformed Secure-Session-Response header: {exc}") from exc
58 return token
61def public_jwk(jwk: JWK) -> JWK:
62 """Reduce a JWK to its required public members (RFC 7638 order)."""
63 kty = jwk.get("kty")
64 if kty not in _PUBLIC_MEMBERS:
65 raise ProofError(f"Unsupported key type: {kty!r}")
66 try:
67 return {k: jwk[k] for k in _PUBLIC_MEMBERS[kty]}
68 except KeyError as exc:
69 raise ProofError(f"JWK is missing member {exc}") from exc
72def jwk_thumbprint(jwk: JWK) -> str:
73 """RFC 7638 SHA-256 thumbprint, base64url without padding."""
74 canonical = json.dumps(public_jwk(jwk), separators=(",", ":"), sort_keys=True)
75 digest = hashlib.sha256(canonical.encode()).digest()
76 return base64.urlsafe_b64encode(digest).rstrip(b"=").decode()
79def _load_key(jwk: object, algorithm: str) -> PublicKey:
80 if not isinstance(jwk, dict):
81 raise ProofError("JWK must be an object")
82 jwk = cast(JWK, jwk)
83 if _PRIVATE_MEMBERS & jwk.keys():
84 raise ProofError("JWK contains private key material")
85 expected_kty = "EC" if algorithm == "ES256" else "RSA"
86 if jwk.get("kty") != expected_kty:
87 raise ProofError(f"{algorithm} requires a {expected_kty} key")
88 if algorithm == "ES256" and jwk.get("crv") != "P-256":
89 raise ProofError("ES256 requires a P-256 key")
90 try:
91 key = jwt.PyJWK(public_jwk(jwk), algorithm=algorithm).key
92 except (jwt.exceptions.PyJWKError, jwt.exceptions.InvalidKeyError, ValueError) as exc:
93 raise ProofError(f"Invalid JWK: {exc}") from exc
94 if isinstance(key, rsa.RSAPublicKey) and key.key_size < MIN_RSA_BITS:
95 raise ProofError(f"RSA keys must be at least {MIN_RSA_BITS} bits")
96 if not isinstance(key, (rsa.RSAPublicKey, ec.EllipticCurvePublicKey)):
97 # Unreachable today: private JWKs were rejected above. Kept so a change
98 # there can never let a non-public key through.
99 raise ProofError("JWK is not a public key") # pragma: no cover
100 return key
103def _unverified_header(token: str, allowed_algorithms: Iterable[str]) -> dict[str, Any]:
104 try:
105 header = jwt.get_unverified_header(token)
106 except jwt.exceptions.DecodeError as exc:
107 raise ProofError(f"Malformed JWT: {exc}") from exc
108 if header.get("typ") != PROOF_TYP:
109 raise ProofError(f"JWT typ must be {PROOF_TYP!r}")
110 alg = header.get("alg")
111 allowed = [a for a in allowed_algorithms if a in SUPPORTED_ALGORITHMS]
112 if alg not in allowed:
113 raise ProofError(f"Algorithm {alg!r} is not allowed")
114 return header
117def _decode(token: str, key: PublicKey, algorithm: str) -> dict[str, Any]:
118 try:
119 claims = jwt.decode(
120 token,
121 key,
122 algorithms=[algorithm],
123 options={
124 "verify_aud": False,
125 "verify_iss": False,
126 # Chrome has been seen sending iat as a string; we don't rely
127 # on it -- freshness comes from the signed challenge.
128 "verify_iat": False,
129 "require": ["jti"],
130 },
131 )
132 except jwt.exceptions.InvalidTokenError as exc:
133 raise ProofError(f"Proof verification failed: {exc}") from exc
134 if not isinstance(claims.get("jti"), str):
135 # PyJWT already rejects a non-string jti; don't rely on that alone.
136 raise ProofError("jti must be a string") # pragma: no cover
137 return claims
140def verify_registration_proof(
141 token: str, allowed_algorithms: Iterable[str] = SUPPORTED_ALGORITHMS
142) -> RegistrationProof:
143 """Verify a registration proof, which carries its own public key."""
144 header = _unverified_header(token, allowed_algorithms)
145 alg = header["alg"]
146 jwk = header.get("jwk")
147 if jwk is None:
148 raise ProofError("Registration proof must include a jwk header")
149 key = _load_key(jwk, alg)
150 claims = _decode(token, key, alg)
151 return RegistrationProof(algorithm=alg, claims=claims, jwk=public_jwk(jwk))
154def verify_refresh_proof(token: str, algorithm: str, jwk: JWK) -> Proof:
155 """Verify a refresh proof against the key stored at registration."""
156 _unverified_header(token, [algorithm])
157 key = _load_key(jwk, algorithm)
158 claims = _decode(token, key, algorithm)
159 return Proof(algorithm=algorithm, claims=claims)