authentik.providers.oauth2.tests.test_dpop

Test DPoP validation utilities

  1"""Test DPoP validation utilities"""
  2
  3import base64
  4import hashlib
  5import json
  6import time
  7from unittest import skipIf
  8from unittest.mock import patch
  9
 10from cryptography.exceptions import UnsupportedAlgorithm
 11from cryptography.hazmat.backends.openssl.backend import backend
 12from cryptography.hazmat.primitives.asymmetric.ec import (
 13    SECP256K1,
 14    SECP256R1,
 15    EllipticCurvePrivateKey,
 16    generate_private_key,
 17)
 18from cryptography.hazmat.primitives.asymmetric.mldsa import MLDSA44PrivateKey, MLDSA65PrivateKey
 19from cryptography.hazmat.primitives.asymmetric.rsa import generate_private_key as generate_rsa_key
 20from django.core.cache import cache
 21from django.test import TestCase
 22from jwt import encode as jwt_encode
 23
 24from authentik.providers.oauth2.dpop import DPoPError, DPoPValidator, jwk_thumbprint
 25from authentik.providers.oauth2.utils import pkce_s256_challenge
 26
 27
 28class DPoPProofBuilder:
 29    """Helper to build DPoP proof JWTs for testing"""
 30
 31    def __init__(self, private_key: EllipticCurvePrivateKey | None = None):
 32        if private_key is None:
 33            private_key = generate_private_key(SECP256R1())
 34        self.private_key = private_key
 35        self.public_key = private_key.public_key()
 36        nums = self.public_key.public_numbers()
 37        self.x = base64.urlsafe_b64encode(nums.x.to_bytes(32, "big")).rstrip(b"=").decode()
 38        self.y = base64.urlsafe_b64encode(nums.y.to_bytes(32, "big")).rstrip(b"=").decode()
 39        self.jwk = {"kty": "EC", "crv": "P-256", "x": self.x, "y": self.y}
 40
 41    def build(  # noqa: PLR0913, PLR0917
 42        self,
 43        htm: str = "POST",
 44        htu: str = "https://server.example.com/token",
 45        c_s256: str | None = None,
 46        iat: int | None = None,
 47        jti: str = "test-jti-001",
 48        alg: str = "ES256",
 49        typ: str = "dpop+jwt",
 50        include_private: bool = False,
 51    ) -> str:
 52        headers = {"typ": typ, "jwk": self.jwk.copy(), "alg": alg}
 53        if include_private:
 54            # Add a fake private key component to test rejection
 55            headers["jwk"]["d"] = "fake-private-key"
 56
 57        payload = {
 58            "htm": htm,
 59            "htu": htu,
 60            "iat": iat if iat is not None else int(time.time()),
 61            "jti": jti,
 62        }
 63        if c_s256 is not None:
 64            payload["c_s256"] = c_s256
 65
 66        return jwt_encode(payload, self.private_key, algorithm=alg, headers=headers)
 67
 68    def make_header(self, htu: str, c_s256: str | None = None) -> str:
 69        """Build a DPoP proof header for the given token endpoint"""
 70        return self.build(htm="POST", htu=htu, c_s256=c_s256)
 71
 72    @property
 73    def jkt(self) -> str:
 74        return jwk_thumbprint(self.jwk)
 75
 76
 77def _craft_jwt(payload: dict, private_key, algorithm: str, headers: dict) -> str:
 78    """Craft a JWT manually, bypassing PyJWT's algorithm validation.
 79
 80    This allows creating JWTs where the header claims a different algorithm
 81    than what was used to sign, for testing rejection of such proofs.
 82    """
 83    from cryptography.hazmat.primitives import hashes
 84    from cryptography.hazmat.primitives.asymmetric import ec, padding
 85
 86    header_bytes = json.dumps(headers, separators=(",", ":")).encode()
 87    payload_bytes = json.dumps(payload, separators=(",", ":")).encode()
 88    segments = [
 89        base64.urlsafe_b64encode(header_bytes).rstrip(b"="),
 90        base64.urlsafe_b64encode(payload_bytes).rstrip(b"="),
 91    ]
 92    signing_input = b".".join(segments)
 93
 94    if algorithm == "ES256":
 95        signature = private_key.sign(signing_input, ec.ECDSA(hashes.SHA256()))
 96    elif algorithm == "ES384":
 97        signature = private_key.sign(signing_input, ec.ECDSA(hashes.SHA384()))
 98    elif algorithm == "ES512":
 99        signature = private_key.sign(signing_input, ec.ECDSA(hashes.SHA512()))
100    elif algorithm in ("RS256", "PS256"):
101        signature = private_key.sign(
102            signing_input,
103            (
104                padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH)
105                if algorithm.startswith("PS")
106                else padding.PKCS1v15()
107            ),
108            hashes.SHA256(),
109        )
110    else:
111        raise ValueError(f"Unsupported test algorithm: {algorithm}")
112
113    segments.append(base64.urlsafe_b64encode(signature).rstrip(b"="))
114    return b".".join(segments).decode()
115
116
117def _b64_uint(value: int) -> str:
118    """Encode an unsigned integer as a base64url string (no padding)."""
119    length = (value.bit_length() + 7) // 8
120    return base64.urlsafe_b64encode(value.to_bytes(length, "big")).rstrip(b"=").decode()
121
122
123class RSAProofBuilder:
124    """Helper to build RSA-signed DPoP proof JWTs for testing"""
125
126    def __init__(self, key_size: int = 2048):
127        self.private_key = generate_rsa_key(public_exponent=65537, key_size=key_size)
128        nums = self.private_key.public_key().public_numbers()
129        self.jwk = {"kty": "RSA", "n": _b64_uint(nums.n), "e": _b64_uint(nums.e)}
130
131    def build(
132        self,
133        htm: str = "POST",
134        htu: str = "https://server.example.com/token",
135        c_s256: str | None = None,
136        iat: int | None = None,
137        jti: str = "rsa-jti-001",
138        alg: str = "RS256",
139    ) -> str:
140        headers = {"typ": "dpop+jwt", "jwk": self.jwk.copy(), "alg": alg}
141        payload = {
142            "htm": htm,
143            "htu": htu,
144            "iat": iat if iat is not None else int(time.time()),
145            "jti": jti,
146        }
147        if c_s256 is not None:
148            payload["c_s256"] = c_s256
149        return jwt_encode(payload, self.private_key, algorithm=alg, headers=headers)
150
151    @property
152    def jkt(self) -> str:
153        return jwk_thumbprint(self.jwk)
154
155
156class MLDSAProofBuilder:
157    """Helper to build ML-DSA-signed DPoP proof JWTs (RFC 9964 AKP key) for testing"""
158
159    def __init__(self, alg: str = "ML-DSA-44"):
160        self.alg = alg
161        self.private_key = {"ML-DSA-44": MLDSA44PrivateKey, "ML-DSA-65": MLDSA65PrivateKey}[
162            alg
163        ].generate()
164        pub = self.private_key.public_key().public_bytes_raw()
165        self.jwk = {
166            "kty": "AKP",
167            "alg": alg,
168            "pub": base64.urlsafe_b64encode(pub).rstrip(b"=").decode(),
169        }
170
171    def build(
172        self,
173        htm: str = "POST",
174        htu: str = "https://server.example.com/token",
175        iat: int | None = None,
176        jti: str = "mldsa-jti-001",
177        jwk: dict | None = None,
178    ) -> str:
179        headers = {
180            "typ": "dpop+jwt",
181            "jwk": (jwk if jwk is not None else self.jwk).copy(),
182            "alg": self.alg,
183        }
184        payload = {
185            "htm": htm,
186            "htu": htu,
187            "iat": iat if iat is not None else int(time.time()),
188            "jti": jti,
189        }
190        return jwt_encode(payload, self.private_key, algorithm=self.alg, headers=headers)
191
192    @property
193    def jkt(self) -> str:
194        return jwk_thumbprint(self.jwk)
195
196
197class TestJWKThumbprint(TestCase):
198    """Test JWK thumbprint computation"""
199
200    def test_ec_thumbprint(self):
201        """Test EC P-256 thumbprint computation."""
202        builder = DPoPProofBuilder()
203        thumbprint = jwk_thumbprint(builder.jwk)
204        self.assertIsInstance(thumbprint, str)
205        self.assertGreater(len(thumbprint), 0)
206        # Verify consistency
207        self.assertEqual(thumbprint, jwk_thumbprint(builder.jwk))
208
209    def test_rsa_thumbprint(self):
210        """Test RSA thumbprint computation."""
211        from cryptography.hazmat.primitives.asymmetric.rsa import generate_private_key
212
213        private_key = generate_private_key(public_exponent=65537, key_size=2048)
214        public_key = private_key.public_key()
215        n = (
216            base64.urlsafe_b64encode(public_key.public_numbers().n.to_bytes(256, "big"))
217            .rstrip(b"=")
218            .decode()
219        )
220        e = (
221            base64.urlsafe_b64encode(public_key.public_numbers().e.to_bytes(3, "big"))
222            .rstrip(b"=")
223            .decode()
224        )
225        jwk = {"kty": "RSA", "n": n, "e": e}
226        thumbprint = jwk_thumbprint(jwk)
227        self.assertIsInstance(thumbprint, str)
228        self.assertGreater(len(thumbprint), 0)
229
230    @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
231    def test_mldsa_thumbprint(self):
232        """AKP thumbprint is computed over alg, kty and pub (RFC 9964 Section 6)"""
233        builder = MLDSAProofBuilder()
234        canonical = json.dumps(
235            {"alg": "ML-DSA-44", "kty": "AKP", "pub": builder.jwk["pub"]}, separators=(",", ":")
236        ).encode()
237        expected = base64.urlsafe_b64encode(hashlib.sha256(canonical).digest()).rstrip(b"=")
238        self.assertEqual(jwk_thumbprint(builder.jwk), expected.decode())
239        # Extra members must not change the thumbprint
240        self.assertEqual(
241            jwk_thumbprint({**builder.jwk, "kid": "x", "use": "sig"}), expected.decode()
242        )
243
244    def test_unsupported_kty(self):
245        """Test unsupported key type — jwcrypto may accept it but DPoP validator rejects it"""
246        validator = DPoPValidator()
247        with self.assertRaises(DPoPError):
248            validator._validate_jwk({"kty": "oct", "k": "foo"})
249
250
251class TestComputeCS256(TestCase):
252    """Test c_s256 computation"""
253
254    def test_code_sha256(self):
255        """Test c_s256 matches expected BASE64URL(SHA256(ASCII(value)))"""
256        value = "SplxlOBeZQQYbYS6WxSbIA"
257        expected = (
258            base64.urlsafe_b64encode(hashlib.sha256(value.encode("ascii")).digest())
259            .rstrip(b"=")
260            .decode("ascii")
261        )
262        self.assertEqual(pkce_s256_challenge(value), expected)
263
264    def test_code_sha256_empty(self):
265        """Test c_s256 with empty string"""
266        expected = (
267            base64.urlsafe_b64encode(hashlib.sha256(b"").digest()).rstrip(b"=").decode("ascii")
268        )
269        self.assertEqual(pkce_s256_challenge(""), expected)
270
271
272class TestDPoPValidator(TestCase):
273    """Test DPoP proof validation."""
274
275    def setUp(self):
276        self.validator = DPoPValidator()
277        self.builder = DPoPProofBuilder()
278        self.htu = "https://server.example.com/token"
279        cache.clear()
280
281    def tearDown(self):
282        cache.clear()
283
284    def test_valid_proof(self):
285        """Test a completely valid DPoP proof"""
286        c_s256 = pkce_s256_challenge("test-code")
287        proof = self.builder.build(c_s256=c_s256)
288        result = self.validator.validate(
289            proof,
290            expected_htm="POST",
291            expected_htu=self.htu,
292            expected_jkt=self.builder.jkt,
293            expected_c_s256=c_s256,
294        )
295        self.assertEqual(result["kty"], "EC")
296        self.assertEqual(result["crv"], "P-256")
297
298    def test_valid_proof_without_expected_jkt(self):
299        """Test valid proof without expected_jkt check"""
300        proof = self.builder.build(htu=self.htu)
301        result = self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
302        self.assertEqual(result["kty"], "EC")
303
304    def test_invalid_signature(self):
305        """Test proof signed with different key than embedded jwk"""
306        other_builder = DPoPProofBuilder()
307        # Sign with other key but embed original jwk
308        payload = {
309            "htm": "POST",
310            "htu": self.htu,
311            "iat": int(time.time()),
312            "jti": "test-jti-002",
313        }
314        proof = jwt_encode(
315            payload,
316            other_builder.private_key,
317            algorithm="ES256",
318            headers={"typ": "dpop+jwt", "jwk": self.builder.jwk},
319        )
320        with self.assertRaises(DPoPError) as cm:
321            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
322        self.assertIn("signature", str(cm.exception).lower())
323
324    def test_missing_typ_header(self):
325        """Test rejection when typ header is not dpop+jwt"""
326        proof = self.builder.build(typ="jwt")
327        with self.assertRaises(DPoPError) as cm:
328            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
329        self.assertIn("typ", str(cm.exception).lower())
330
331    def test_private_key_material(self):
332        """Test rejection when jwk contains private key material"""
333        proof = self.builder.build(include_private=True)
334        with self.assertRaises(DPoPError) as cm:
335            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
336        self.assertIn("private", str(cm.exception).lower())
337
338    def test_htm_mismatch(self):
339        """Test rejection when htm doesn't match"""
340        proof = self.builder.build(htm="GET", htu=self.htu)
341        with self.assertRaises(DPoPError) as cm:
342            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
343        self.assertIn("htm", str(cm.exception).lower())
344
345    def test_htu_mismatch(self):
346        """Test rejection when htu doesn't match"""
347        proof = self.builder.build(htu="https://other.example.com/token")
348        with self.assertRaises(DPoPError) as cm:
349            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
350        self.assertIn("htu", str(cm.exception).lower())
351
352    def test_htu_ignores_query_and_fragment(self):
353        """Test htu matching ignores query and fragment"""
354        proof = self.builder.build(htu=self.htu + "?foo=bar#baz")
355        result = self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
356        self.assertEqual(result["kty"], "EC")
357
358    def test_expired_iat(self):
359        """Test rejection when iat is too old"""
360        proof = self.builder.build(htu=self.htu, iat=int(time.time()) - 120)
361        with self.assertRaises(DPoPError) as cm:
362            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
363        self.assertIn("iat", str(cm.exception).lower())
364
365    def test_future_iat(self):
366        """Test rejection when iat is in the future"""
367        proof = self.builder.build(htu=self.htu, iat=int(time.time()) + 120)
368        with self.assertRaises(DPoPError) as cm:
369            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
370        self.assertIn("iat", str(cm.exception).lower())
371
372    def test_missing_jti(self):
373        """Test rejection when jti is missing"""
374        proof = self.builder.build(htu=self.htu, jti="")
375        with self.assertRaises(DPoPError) as cm:
376            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
377        self.assertIn("jti", str(cm.exception).lower())
378
379    def test_expected_jkt_mismatch(self):
380        """Test rejection when JWK thumbprint doesn't match expected_jkt"""
381        other_builder = DPoPProofBuilder()
382        proof = other_builder.build(htu=self.htu)
383        with self.assertRaises(DPoPError) as cm:
384            self.validator.validate(
385                proof, expected_htm="POST", expected_htu=self.htu, expected_jkt=self.builder.jkt
386            )
387        self.assertIn("thumbprint", str(cm.exception).lower())
388
389    def test_expected_jkt_match(self):
390        """Test acceptance when JWK thumbprint matches expected_jkt"""
391        proof = self.builder.build(htu=self.htu)
392        result = self.validator.validate(
393            proof, expected_htm="POST", expected_htu=self.htu, expected_jkt=self.builder.jkt
394        )
395        self.assertEqual(result["kty"], "EC")
396
397    def test_c_s256_mismatch(self):
398        """Test rejection when c_s256 doesn't match"""
399        proof = self.builder.build(c_s256="wrong-hash")
400        with self.assertRaises(DPoPError) as cm:
401            self.validator.validate(
402                proof,
403                expected_htm="POST",
404                expected_htu=self.htu,
405                expected_c_s256=pkce_s256_challenge("correct-code"),
406            )
407        self.assertIn("c_s256", str(cm.exception).lower())
408
409    def test_c_s256_match(self):
410        """Test acceptance when c_s256 matches"""
411        code = "test-auth-code-123"
412        c_s256 = pkce_s256_challenge(code)
413        proof = self.builder.build(c_s256=c_s256)
414        result = self.validator.validate(
415            proof, expected_htm="POST", expected_htu=self.htu, expected_c_s256=c_s256
416        )
417        self.assertEqual(result["kty"], "EC")
418
419    def test_c_s256_missing_when_required(self):
420        """Test rejection when c_s256 param provided but claim absent"""
421        proof = self.builder.build(htu=self.htu)
422        with self.assertRaises(DPoPError) as cm:
423            self.validator.validate(
424                proof,
425                expected_htm="POST",
426                expected_htu=self.htu,
427                expected_c_s256=pkce_s256_challenge("some-code"),
428            )
429        self.assertIn("c_s256", str(cm.exception).lower())
430
431    def test_symmetric_key_rejected(self):
432        """Test rejection of symmetric keys"""
433        with self.assertRaises(DPoPError) as cm:
434            self.validator._validate_jwk({"kty": "oct", "k": "foo"})
435        self.assertIn("Unsupported", str(cm.exception))
436
437    def test_invalid_jwt(self):
438        """Test rejection of malformed JWT"""
439        with self.assertRaises(DPoPError):
440            self.validator.validate("not-a-jwt", expected_htm="POST", expected_htu=self.htu)
441
442    def test_missing_jwk(self):
443        """Test rejection when jwk is missing from header"""
444        payload = {
445            "htm": "POST",
446            "htu": self.htu,
447            "iat": int(time.time()),
448            "jti": "test-jti-004",
449        }
450        proof = jwt_encode(
451            payload,
452            self.builder.private_key,
453            algorithm="ES256",
454            headers={"typ": "dpop+jwt"},
455        )
456        with self.assertRaises(DPoPError) as cm:
457            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
458        self.assertIn("jwk", str(cm.exception).lower())
459
460    def test_cnf_strips_extra_jwk_members(self):
461        """Test that any claims in the JWK not covered by the JKT are removed"""
462        builder = DPoPProofBuilder()
463        builder.jwk["jku"] = "https://attacker.example/keys"
464        builder.jwk["alg"] = "RS256"
465        result = self.validator.validate(
466            builder.build(htu=self.htu), expected_htm="POST", expected_htu=self.htu
467        )
468        self.assertEqual(set(result), {"crv", "kty", "x", "y"})
469
470    def test_jti_replay_rejected(self):
471        """Test that reusing the same jti is rejected"""
472        jti = "unique-jti-12345"
473        proof = self.builder.build(htu=self.htu, jti=jti)
474        # First use should succeed
475        self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
476        # Second use with same jti should fail
477        with self.assertRaises(DPoPError) as cm:
478            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
479        self.assertIn("replay", str(cm.exception).lower())
480
481    def test_jti_different_accepted(self):
482        """Test that different jti values are both accepted"""
483        proof1 = self.builder.build(htu=self.htu, jti="jti-first")
484        proof2 = self.builder.build(htu=self.htu, jti="jti-second")
485        self.validator.validate(proof1, expected_htm="POST", expected_htu=self.htu)
486        self.validator.validate(proof2, expected_htm="POST", expected_htu=self.htu)
487
488    def test_symmetric_alg_rejected(self):
489        """Test rejection when alg header claims a symmetric algorithm"""
490        payload = {
491            "htm": "POST",
492            "htu": self.htu,
493            "iat": int(time.time()),
494            "jti": "test-jti-sym",
495        }
496        # Craft a JWT with HS256 in the header but signed with EC key
497        proof = _craft_jwt(
498            payload,
499            self.builder.private_key,
500            algorithm="ES256",
501            headers={"typ": "dpop+jwt", "jwk": self.builder.jwk, "alg": "HS256"},
502        )
503        with self.assertRaises(DPoPError) as cm:
504            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
505        self.assertIn("algorithm", str(cm.exception).lower())
506
507    def test_alg_jwk_mismatch_rejected(self):
508        """Test rejection when alg doesn't match JWK key type"""
509        payload = {
510            "htm": "POST",
511            "htu": self.htu,
512            "iat": int(time.time()),
513            "jti": "test-jti-mismatch",
514        }
515        # Craft a JWT with RS256 in the header but EC jwk and signature
516        proof = _craft_jwt(
517            payload,
518            self.builder.private_key,
519            algorithm="ES256",
520            headers={"typ": "dpop+jwt", "jwk": self.builder.jwk, "alg": "RS256"},
521        )
522        with self.assertRaises(DPoPError) as cm:
523            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
524        self.assertIn("signature", str(cm.exception).lower())
525
526    @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
527    def test_mldsa_proof_accepted(self):
528        """A DPoP proof signed with ML-DSA-44 and an AKP JWK validates; cnf is the canonical key"""
529        builder = MLDSAProofBuilder()
530        proof = builder.build(htu=self.htu)
531        result = self.validator.validate(
532            proof, expected_htm="POST", expected_htu=self.htu, expected_jkt=builder.jkt
533        )
534        self.assertEqual(result, {"alg": "ML-DSA-44", "kty": "AKP", "pub": builder.jwk["pub"]})
535
536    @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
537    def test_mldsa65_proof_accepted(self):
538        """ML-DSA-65 is accepted as well"""
539        builder = MLDSAProofBuilder("ML-DSA-65")
540        result = self.validator.validate(
541            builder.build(htu=self.htu), expected_htm="POST", expected_htu=self.htu
542        )
543        self.assertEqual(result["alg"], "ML-DSA-65")
544
545    @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
546    def test_mldsa_alg_jwk_mismatch_rejected(self):
547        """The proof's alg must name the same parameter set as the AKP key"""
548        builder = MLDSAProofBuilder()
549        proof = builder.build(htu=self.htu)
550        # Re-label the protected header's alg; the mismatch is caught before signature checks
551        header_b64, rest = proof.split(".", 1)
552        header = json.loads(base64.urlsafe_b64decode(header_b64 + "=="))
553        header["alg"] = "ML-DSA-65"
554        header_b64 = (
555            base64.urlsafe_b64encode(json.dumps(header, separators=(",", ":")).encode())
556            .rstrip(b"=")
557            .decode()
558        )
559        proof = f"{header_b64}.{rest}"
560        with self.assertRaises(DPoPError) as cm:
561            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
562        self.assertIn("does not match", str(cm.exception))
563
564    @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
565    def test_mldsa_wrong_key_rejected(self):
566        """A proof whose AKP key is not the signing key fails signature verification"""
567        builder = MLDSAProofBuilder()
568        other = MLDSAProofBuilder()
569        proof = builder.build(htu=self.htu, jwk=other.jwk)
570        with self.assertRaises(DPoPError) as cm:
571            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
572        self.assertIn("signature", str(cm.exception).lower())
573
574    @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
575    def test_mldsa_private_material_rejected(self):
576        """An AKP JWK carrying the private seed (priv) must be rejected"""
577        builder = MLDSAProofBuilder()
578        proof = builder.build(htu=self.htu, jwk={**builder.jwk, "priv": "AAAA"})
579        with self.assertRaises(DPoPError) as cm:
580            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
581        self.assertIn("private key material", str(cm.exception))
582
583    @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
584    def test_mldsa_unsupported_akp_alg_rejected(self):
585        """AKP keys for algorithms other than ML-DSA are rejected before loading"""
586        builder = MLDSAProofBuilder()
587        with self.assertRaises(DPoPError) as cm:
588            self.validator._validate_jwk({**builder.jwk, "alg": "SLH-DSA-SHA2-128s"})
589        self.assertIn("Unsupported AKP algorithm", str(cm.exception))
590
591    @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
592    def test_mldsa_key_unavailable_fails_closed(self):
593        """An AKP key OpenSSL cannot load (ML-DSA under a FIPS provider that predates it) is a
594        DPoP error, not an unhandled exception"""
595
596        class UnavailablePublicKey:
597            @staticmethod
598            def from_public_bytes(_data: bytes):
599                raise UnsupportedAlgorithm("ML-DSA is not supported by this version of OpenSSL")
600
601        builder = MLDSAProofBuilder()
602        proof = builder.build(htu=self.htu)
603        with (
604            patch.dict(
605                "authentik.lib.jwt_mldsa.MLDSA_ALGORITHMS",
606                {"ML-DSA-44": (MLDSA44PrivateKey, UnavailablePublicKey)},
607            ),
608            self.assertRaises(DPoPError) as cm,
609        ):
610            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
611        self.assertIn("Invalid AKP JWK", str(cm.exception))
612
613    def test_rsa_proof_accepted(self):
614        """A valid 2048-bit RSA DPoP proof should validate."""
615        builder = RSAProofBuilder(key_size=2048)
616        proof = builder.build(htu=self.htu)
617        result = self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
618        self.assertEqual(result["kty"], "RSA")
619
620    @skipIf(backend._fips_enabled, "FIPS mode can't sign with a 1024-bit RSA key")
621    def test_rsa_key_too_small_rejected(self):
622        """An RSA key below the minimum size (2048 bits) must be rejected."""
623        builder = RSAProofBuilder(key_size=1024)
624        proof = builder.build(htu=self.htu)
625        with self.assertRaises(DPoPError) as cm:
626            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
627        self.assertIn("too small", str(cm.exception).lower())
628
629    @skipIf(backend._fips_enabled, "FIPS mode can't sign with secp256k1")
630    def test_unsupported_ec_curve_rejected(self):
631        """An EC key on a curve outside the supported set must be rejected."""
632        priv = generate_private_key(SECP256K1())
633        nums = priv.public_key().public_numbers()
634        x = base64.urlsafe_b64encode(nums.x.to_bytes(32, "big")).rstrip(b"=").decode()
635        y = base64.urlsafe_b64encode(nums.y.to_bytes(32, "big")).rstrip(b"=").decode()
636        jwk = {"kty": "EC", "crv": "secp256k1", "x": x, "y": y}
637        payload = {
638            "htm": "POST",
639            "htu": self.htu,
640            "iat": int(time.time()),
641            "jti": "curve-jti-001",
642        }
643        proof = _craft_jwt(
644            payload,
645            priv,
646            algorithm="ES256",
647            headers={"typ": "dpop+jwt", "jwk": jwk, "alg": "ES256"},
648        )
649        with self.assertRaises(DPoPError) as cm:
650            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
651        self.assertIn("curve", str(cm.exception).lower())
class DPoPProofBuilder:
29class DPoPProofBuilder:
30    """Helper to build DPoP proof JWTs for testing"""
31
32    def __init__(self, private_key: EllipticCurvePrivateKey | None = None):
33        if private_key is None:
34            private_key = generate_private_key(SECP256R1())
35        self.private_key = private_key
36        self.public_key = private_key.public_key()
37        nums = self.public_key.public_numbers()
38        self.x = base64.urlsafe_b64encode(nums.x.to_bytes(32, "big")).rstrip(b"=").decode()
39        self.y = base64.urlsafe_b64encode(nums.y.to_bytes(32, "big")).rstrip(b"=").decode()
40        self.jwk = {"kty": "EC", "crv": "P-256", "x": self.x, "y": self.y}
41
42    def build(  # noqa: PLR0913, PLR0917
43        self,
44        htm: str = "POST",
45        htu: str = "https://server.example.com/token",
46        c_s256: str | None = None,
47        iat: int | None = None,
48        jti: str = "test-jti-001",
49        alg: str = "ES256",
50        typ: str = "dpop+jwt",
51        include_private: bool = False,
52    ) -> str:
53        headers = {"typ": typ, "jwk": self.jwk.copy(), "alg": alg}
54        if include_private:
55            # Add a fake private key component to test rejection
56            headers["jwk"]["d"] = "fake-private-key"
57
58        payload = {
59            "htm": htm,
60            "htu": htu,
61            "iat": iat if iat is not None else int(time.time()),
62            "jti": jti,
63        }
64        if c_s256 is not None:
65            payload["c_s256"] = c_s256
66
67        return jwt_encode(payload, self.private_key, algorithm=alg, headers=headers)
68
69    def make_header(self, htu: str, c_s256: str | None = None) -> str:
70        """Build a DPoP proof header for the given token endpoint"""
71        return self.build(htm="POST", htu=htu, c_s256=c_s256)
72
73    @property
74    def jkt(self) -> str:
75        return jwk_thumbprint(self.jwk)

Helper to build DPoP proof JWTs for testing

DPoPProofBuilder( private_key: cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey | None = None)
32    def __init__(self, private_key: EllipticCurvePrivateKey | None = None):
33        if private_key is None:
34            private_key = generate_private_key(SECP256R1())
35        self.private_key = private_key
36        self.public_key = private_key.public_key()
37        nums = self.public_key.public_numbers()
38        self.x = base64.urlsafe_b64encode(nums.x.to_bytes(32, "big")).rstrip(b"=").decode()
39        self.y = base64.urlsafe_b64encode(nums.y.to_bytes(32, "big")).rstrip(b"=").decode()
40        self.jwk = {"kty": "EC", "crv": "P-256", "x": self.x, "y": self.y}
private_key
public_key
x
y
jwk
def build( self, htm: str = 'POST', htu: str = 'https://server.example.com/token', c_s256: str | None = None, iat: int | None = None, jti: str = 'test-jti-001', alg: str = 'ES256', typ: str = 'dpop+jwt', include_private: bool = False) -> str:
42    def build(  # noqa: PLR0913, PLR0917
43        self,
44        htm: str = "POST",
45        htu: str = "https://server.example.com/token",
46        c_s256: str | None = None,
47        iat: int | None = None,
48        jti: str = "test-jti-001",
49        alg: str = "ES256",
50        typ: str = "dpop+jwt",
51        include_private: bool = False,
52    ) -> str:
53        headers = {"typ": typ, "jwk": self.jwk.copy(), "alg": alg}
54        if include_private:
55            # Add a fake private key component to test rejection
56            headers["jwk"]["d"] = "fake-private-key"
57
58        payload = {
59            "htm": htm,
60            "htu": htu,
61            "iat": iat if iat is not None else int(time.time()),
62            "jti": jti,
63        }
64        if c_s256 is not None:
65            payload["c_s256"] = c_s256
66
67        return jwt_encode(payload, self.private_key, algorithm=alg, headers=headers)
def make_header(self, htu: str, c_s256: str | None = None) -> str:
69    def make_header(self, htu: str, c_s256: str | None = None) -> str:
70        """Build a DPoP proof header for the given token endpoint"""
71        return self.build(htm="POST", htu=htu, c_s256=c_s256)

Build a DPoP proof header for the given token endpoint

jkt: str
73    @property
74    def jkt(self) -> str:
75        return jwk_thumbprint(self.jwk)
class RSAProofBuilder:
124class RSAProofBuilder:
125    """Helper to build RSA-signed DPoP proof JWTs for testing"""
126
127    def __init__(self, key_size: int = 2048):
128        self.private_key = generate_rsa_key(public_exponent=65537, key_size=key_size)
129        nums = self.private_key.public_key().public_numbers()
130        self.jwk = {"kty": "RSA", "n": _b64_uint(nums.n), "e": _b64_uint(nums.e)}
131
132    def build(
133        self,
134        htm: str = "POST",
135        htu: str = "https://server.example.com/token",
136        c_s256: str | None = None,
137        iat: int | None = None,
138        jti: str = "rsa-jti-001",
139        alg: str = "RS256",
140    ) -> str:
141        headers = {"typ": "dpop+jwt", "jwk": self.jwk.copy(), "alg": alg}
142        payload = {
143            "htm": htm,
144            "htu": htu,
145            "iat": iat if iat is not None else int(time.time()),
146            "jti": jti,
147        }
148        if c_s256 is not None:
149            payload["c_s256"] = c_s256
150        return jwt_encode(payload, self.private_key, algorithm=alg, headers=headers)
151
152    @property
153    def jkt(self) -> str:
154        return jwk_thumbprint(self.jwk)

Helper to build RSA-signed DPoP proof JWTs for testing

RSAProofBuilder(key_size: int = 2048)
127    def __init__(self, key_size: int = 2048):
128        self.private_key = generate_rsa_key(public_exponent=65537, key_size=key_size)
129        nums = self.private_key.public_key().public_numbers()
130        self.jwk = {"kty": "RSA", "n": _b64_uint(nums.n), "e": _b64_uint(nums.e)}
private_key
jwk
def build( self, htm: str = 'POST', htu: str = 'https://server.example.com/token', c_s256: str | None = None, iat: int | None = None, jti: str = 'rsa-jti-001', alg: str = 'RS256') -> str:
132    def build(
133        self,
134        htm: str = "POST",
135        htu: str = "https://server.example.com/token",
136        c_s256: str | None = None,
137        iat: int | None = None,
138        jti: str = "rsa-jti-001",
139        alg: str = "RS256",
140    ) -> str:
141        headers = {"typ": "dpop+jwt", "jwk": self.jwk.copy(), "alg": alg}
142        payload = {
143            "htm": htm,
144            "htu": htu,
145            "iat": iat if iat is not None else int(time.time()),
146            "jti": jti,
147        }
148        if c_s256 is not None:
149            payload["c_s256"] = c_s256
150        return jwt_encode(payload, self.private_key, algorithm=alg, headers=headers)
jkt: str
152    @property
153    def jkt(self) -> str:
154        return jwk_thumbprint(self.jwk)
class MLDSAProofBuilder:
157class MLDSAProofBuilder:
158    """Helper to build ML-DSA-signed DPoP proof JWTs (RFC 9964 AKP key) for testing"""
159
160    def __init__(self, alg: str = "ML-DSA-44"):
161        self.alg = alg
162        self.private_key = {"ML-DSA-44": MLDSA44PrivateKey, "ML-DSA-65": MLDSA65PrivateKey}[
163            alg
164        ].generate()
165        pub = self.private_key.public_key().public_bytes_raw()
166        self.jwk = {
167            "kty": "AKP",
168            "alg": alg,
169            "pub": base64.urlsafe_b64encode(pub).rstrip(b"=").decode(),
170        }
171
172    def build(
173        self,
174        htm: str = "POST",
175        htu: str = "https://server.example.com/token",
176        iat: int | None = None,
177        jti: str = "mldsa-jti-001",
178        jwk: dict | None = None,
179    ) -> str:
180        headers = {
181            "typ": "dpop+jwt",
182            "jwk": (jwk if jwk is not None else self.jwk).copy(),
183            "alg": self.alg,
184        }
185        payload = {
186            "htm": htm,
187            "htu": htu,
188            "iat": iat if iat is not None else int(time.time()),
189            "jti": jti,
190        }
191        return jwt_encode(payload, self.private_key, algorithm=self.alg, headers=headers)
192
193    @property
194    def jkt(self) -> str:
195        return jwk_thumbprint(self.jwk)

Helper to build ML-DSA-signed DPoP proof JWTs (RFC 9964 AKP key) for testing

MLDSAProofBuilder(alg: str = 'ML-DSA-44')
160    def __init__(self, alg: str = "ML-DSA-44"):
161        self.alg = alg
162        self.private_key = {"ML-DSA-44": MLDSA44PrivateKey, "ML-DSA-65": MLDSA65PrivateKey}[
163            alg
164        ].generate()
165        pub = self.private_key.public_key().public_bytes_raw()
166        self.jwk = {
167            "kty": "AKP",
168            "alg": alg,
169            "pub": base64.urlsafe_b64encode(pub).rstrip(b"=").decode(),
170        }
alg
private_key
jwk
def build( self, htm: str = 'POST', htu: str = 'https://server.example.com/token', iat: int | None = None, jti: str = 'mldsa-jti-001', jwk: dict | None = None) -> str:
172    def build(
173        self,
174        htm: str = "POST",
175        htu: str = "https://server.example.com/token",
176        iat: int | None = None,
177        jti: str = "mldsa-jti-001",
178        jwk: dict | None = None,
179    ) -> str:
180        headers = {
181            "typ": "dpop+jwt",
182            "jwk": (jwk if jwk is not None else self.jwk).copy(),
183            "alg": self.alg,
184        }
185        payload = {
186            "htm": htm,
187            "htu": htu,
188            "iat": iat if iat is not None else int(time.time()),
189            "jti": jti,
190        }
191        return jwt_encode(payload, self.private_key, algorithm=self.alg, headers=headers)
jkt: str
193    @property
194    def jkt(self) -> str:
195        return jwk_thumbprint(self.jwk)
class TestJWKThumbprint(django.test.testcases.TestCase):
198class TestJWKThumbprint(TestCase):
199    """Test JWK thumbprint computation"""
200
201    def test_ec_thumbprint(self):
202        """Test EC P-256 thumbprint computation."""
203        builder = DPoPProofBuilder()
204        thumbprint = jwk_thumbprint(builder.jwk)
205        self.assertIsInstance(thumbprint, str)
206        self.assertGreater(len(thumbprint), 0)
207        # Verify consistency
208        self.assertEqual(thumbprint, jwk_thumbprint(builder.jwk))
209
210    def test_rsa_thumbprint(self):
211        """Test RSA thumbprint computation."""
212        from cryptography.hazmat.primitives.asymmetric.rsa import generate_private_key
213
214        private_key = generate_private_key(public_exponent=65537, key_size=2048)
215        public_key = private_key.public_key()
216        n = (
217            base64.urlsafe_b64encode(public_key.public_numbers().n.to_bytes(256, "big"))
218            .rstrip(b"=")
219            .decode()
220        )
221        e = (
222            base64.urlsafe_b64encode(public_key.public_numbers().e.to_bytes(3, "big"))
223            .rstrip(b"=")
224            .decode()
225        )
226        jwk = {"kty": "RSA", "n": n, "e": e}
227        thumbprint = jwk_thumbprint(jwk)
228        self.assertIsInstance(thumbprint, str)
229        self.assertGreater(len(thumbprint), 0)
230
231    @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
232    def test_mldsa_thumbprint(self):
233        """AKP thumbprint is computed over alg, kty and pub (RFC 9964 Section 6)"""
234        builder = MLDSAProofBuilder()
235        canonical = json.dumps(
236            {"alg": "ML-DSA-44", "kty": "AKP", "pub": builder.jwk["pub"]}, separators=(",", ":")
237        ).encode()
238        expected = base64.urlsafe_b64encode(hashlib.sha256(canonical).digest()).rstrip(b"=")
239        self.assertEqual(jwk_thumbprint(builder.jwk), expected.decode())
240        # Extra members must not change the thumbprint
241        self.assertEqual(
242            jwk_thumbprint({**builder.jwk, "kid": "x", "use": "sig"}), expected.decode()
243        )
244
245    def test_unsupported_kty(self):
246        """Test unsupported key type — jwcrypto may accept it but DPoP validator rejects it"""
247        validator = DPoPValidator()
248        with self.assertRaises(DPoPError):
249            validator._validate_jwk({"kty": "oct", "k": "foo"})

Test JWK thumbprint computation

def test_ec_thumbprint(self):
201    def test_ec_thumbprint(self):
202        """Test EC P-256 thumbprint computation."""
203        builder = DPoPProofBuilder()
204        thumbprint = jwk_thumbprint(builder.jwk)
205        self.assertIsInstance(thumbprint, str)
206        self.assertGreater(len(thumbprint), 0)
207        # Verify consistency
208        self.assertEqual(thumbprint, jwk_thumbprint(builder.jwk))

Test EC P-256 thumbprint computation.

def test_rsa_thumbprint(self):
210    def test_rsa_thumbprint(self):
211        """Test RSA thumbprint computation."""
212        from cryptography.hazmat.primitives.asymmetric.rsa import generate_private_key
213
214        private_key = generate_private_key(public_exponent=65537, key_size=2048)
215        public_key = private_key.public_key()
216        n = (
217            base64.urlsafe_b64encode(public_key.public_numbers().n.to_bytes(256, "big"))
218            .rstrip(b"=")
219            .decode()
220        )
221        e = (
222            base64.urlsafe_b64encode(public_key.public_numbers().e.to_bytes(3, "big"))
223            .rstrip(b"=")
224            .decode()
225        )
226        jwk = {"kty": "RSA", "n": n, "e": e}
227        thumbprint = jwk_thumbprint(jwk)
228        self.assertIsInstance(thumbprint, str)
229        self.assertGreater(len(thumbprint), 0)

Test RSA thumbprint computation.

@skipIf(backend._fips_enabled, 'The FIPS provider has no ML-DSA')
def test_mldsa_thumbprint(self):
231    @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
232    def test_mldsa_thumbprint(self):
233        """AKP thumbprint is computed over alg, kty and pub (RFC 9964 Section 6)"""
234        builder = MLDSAProofBuilder()
235        canonical = json.dumps(
236            {"alg": "ML-DSA-44", "kty": "AKP", "pub": builder.jwk["pub"]}, separators=(",", ":")
237        ).encode()
238        expected = base64.urlsafe_b64encode(hashlib.sha256(canonical).digest()).rstrip(b"=")
239        self.assertEqual(jwk_thumbprint(builder.jwk), expected.decode())
240        # Extra members must not change the thumbprint
241        self.assertEqual(
242            jwk_thumbprint({**builder.jwk, "kid": "x", "use": "sig"}), expected.decode()
243        )

AKP thumbprint is computed over alg, kty and pub (RFC 9964 Section 6)

def test_unsupported_kty(self):
245    def test_unsupported_kty(self):
246        """Test unsupported key type — jwcrypto may accept it but DPoP validator rejects it"""
247        validator = DPoPValidator()
248        with self.assertRaises(DPoPError):
249            validator._validate_jwk({"kty": "oct", "k": "foo"})

Test unsupported key type — jwcrypto may accept it but DPoP validator rejects it

class TestComputeCS256(django.test.testcases.TestCase):
252class TestComputeCS256(TestCase):
253    """Test c_s256 computation"""
254
255    def test_code_sha256(self):
256        """Test c_s256 matches expected BASE64URL(SHA256(ASCII(value)))"""
257        value = "SplxlOBeZQQYbYS6WxSbIA"
258        expected = (
259            base64.urlsafe_b64encode(hashlib.sha256(value.encode("ascii")).digest())
260            .rstrip(b"=")
261            .decode("ascii")
262        )
263        self.assertEqual(pkce_s256_challenge(value), expected)
264
265    def test_code_sha256_empty(self):
266        """Test c_s256 with empty string"""
267        expected = (
268            base64.urlsafe_b64encode(hashlib.sha256(b"").digest()).rstrip(b"=").decode("ascii")
269        )
270        self.assertEqual(pkce_s256_challenge(""), expected)

Test c_s256 computation

def test_code_sha256(self):
255    def test_code_sha256(self):
256        """Test c_s256 matches expected BASE64URL(SHA256(ASCII(value)))"""
257        value = "SplxlOBeZQQYbYS6WxSbIA"
258        expected = (
259            base64.urlsafe_b64encode(hashlib.sha256(value.encode("ascii")).digest())
260            .rstrip(b"=")
261            .decode("ascii")
262        )
263        self.assertEqual(pkce_s256_challenge(value), expected)

Test c_s256 matches expected BASE64URL(SHA256(ASCII(value)))

def test_code_sha256_empty(self):
265    def test_code_sha256_empty(self):
266        """Test c_s256 with empty string"""
267        expected = (
268            base64.urlsafe_b64encode(hashlib.sha256(b"").digest()).rstrip(b"=").decode("ascii")
269        )
270        self.assertEqual(pkce_s256_challenge(""), expected)

Test c_s256 with empty string

class TestDPoPValidator(django.test.testcases.TestCase):
273class TestDPoPValidator(TestCase):
274    """Test DPoP proof validation."""
275
276    def setUp(self):
277        self.validator = DPoPValidator()
278        self.builder = DPoPProofBuilder()
279        self.htu = "https://server.example.com/token"
280        cache.clear()
281
282    def tearDown(self):
283        cache.clear()
284
285    def test_valid_proof(self):
286        """Test a completely valid DPoP proof"""
287        c_s256 = pkce_s256_challenge("test-code")
288        proof = self.builder.build(c_s256=c_s256)
289        result = self.validator.validate(
290            proof,
291            expected_htm="POST",
292            expected_htu=self.htu,
293            expected_jkt=self.builder.jkt,
294            expected_c_s256=c_s256,
295        )
296        self.assertEqual(result["kty"], "EC")
297        self.assertEqual(result["crv"], "P-256")
298
299    def test_valid_proof_without_expected_jkt(self):
300        """Test valid proof without expected_jkt check"""
301        proof = self.builder.build(htu=self.htu)
302        result = self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
303        self.assertEqual(result["kty"], "EC")
304
305    def test_invalid_signature(self):
306        """Test proof signed with different key than embedded jwk"""
307        other_builder = DPoPProofBuilder()
308        # Sign with other key but embed original jwk
309        payload = {
310            "htm": "POST",
311            "htu": self.htu,
312            "iat": int(time.time()),
313            "jti": "test-jti-002",
314        }
315        proof = jwt_encode(
316            payload,
317            other_builder.private_key,
318            algorithm="ES256",
319            headers={"typ": "dpop+jwt", "jwk": self.builder.jwk},
320        )
321        with self.assertRaises(DPoPError) as cm:
322            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
323        self.assertIn("signature", str(cm.exception).lower())
324
325    def test_missing_typ_header(self):
326        """Test rejection when typ header is not dpop+jwt"""
327        proof = self.builder.build(typ="jwt")
328        with self.assertRaises(DPoPError) as cm:
329            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
330        self.assertIn("typ", str(cm.exception).lower())
331
332    def test_private_key_material(self):
333        """Test rejection when jwk contains private key material"""
334        proof = self.builder.build(include_private=True)
335        with self.assertRaises(DPoPError) as cm:
336            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
337        self.assertIn("private", str(cm.exception).lower())
338
339    def test_htm_mismatch(self):
340        """Test rejection when htm doesn't match"""
341        proof = self.builder.build(htm="GET", htu=self.htu)
342        with self.assertRaises(DPoPError) as cm:
343            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
344        self.assertIn("htm", str(cm.exception).lower())
345
346    def test_htu_mismatch(self):
347        """Test rejection when htu doesn't match"""
348        proof = self.builder.build(htu="https://other.example.com/token")
349        with self.assertRaises(DPoPError) as cm:
350            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
351        self.assertIn("htu", str(cm.exception).lower())
352
353    def test_htu_ignores_query_and_fragment(self):
354        """Test htu matching ignores query and fragment"""
355        proof = self.builder.build(htu=self.htu + "?foo=bar#baz")
356        result = self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
357        self.assertEqual(result["kty"], "EC")
358
359    def test_expired_iat(self):
360        """Test rejection when iat is too old"""
361        proof = self.builder.build(htu=self.htu, iat=int(time.time()) - 120)
362        with self.assertRaises(DPoPError) as cm:
363            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
364        self.assertIn("iat", str(cm.exception).lower())
365
366    def test_future_iat(self):
367        """Test rejection when iat is in the future"""
368        proof = self.builder.build(htu=self.htu, iat=int(time.time()) + 120)
369        with self.assertRaises(DPoPError) as cm:
370            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
371        self.assertIn("iat", str(cm.exception).lower())
372
373    def test_missing_jti(self):
374        """Test rejection when jti is missing"""
375        proof = self.builder.build(htu=self.htu, jti="")
376        with self.assertRaises(DPoPError) as cm:
377            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
378        self.assertIn("jti", str(cm.exception).lower())
379
380    def test_expected_jkt_mismatch(self):
381        """Test rejection when JWK thumbprint doesn't match expected_jkt"""
382        other_builder = DPoPProofBuilder()
383        proof = other_builder.build(htu=self.htu)
384        with self.assertRaises(DPoPError) as cm:
385            self.validator.validate(
386                proof, expected_htm="POST", expected_htu=self.htu, expected_jkt=self.builder.jkt
387            )
388        self.assertIn("thumbprint", str(cm.exception).lower())
389
390    def test_expected_jkt_match(self):
391        """Test acceptance when JWK thumbprint matches expected_jkt"""
392        proof = self.builder.build(htu=self.htu)
393        result = self.validator.validate(
394            proof, expected_htm="POST", expected_htu=self.htu, expected_jkt=self.builder.jkt
395        )
396        self.assertEqual(result["kty"], "EC")
397
398    def test_c_s256_mismatch(self):
399        """Test rejection when c_s256 doesn't match"""
400        proof = self.builder.build(c_s256="wrong-hash")
401        with self.assertRaises(DPoPError) as cm:
402            self.validator.validate(
403                proof,
404                expected_htm="POST",
405                expected_htu=self.htu,
406                expected_c_s256=pkce_s256_challenge("correct-code"),
407            )
408        self.assertIn("c_s256", str(cm.exception).lower())
409
410    def test_c_s256_match(self):
411        """Test acceptance when c_s256 matches"""
412        code = "test-auth-code-123"
413        c_s256 = pkce_s256_challenge(code)
414        proof = self.builder.build(c_s256=c_s256)
415        result = self.validator.validate(
416            proof, expected_htm="POST", expected_htu=self.htu, expected_c_s256=c_s256
417        )
418        self.assertEqual(result["kty"], "EC")
419
420    def test_c_s256_missing_when_required(self):
421        """Test rejection when c_s256 param provided but claim absent"""
422        proof = self.builder.build(htu=self.htu)
423        with self.assertRaises(DPoPError) as cm:
424            self.validator.validate(
425                proof,
426                expected_htm="POST",
427                expected_htu=self.htu,
428                expected_c_s256=pkce_s256_challenge("some-code"),
429            )
430        self.assertIn("c_s256", str(cm.exception).lower())
431
432    def test_symmetric_key_rejected(self):
433        """Test rejection of symmetric keys"""
434        with self.assertRaises(DPoPError) as cm:
435            self.validator._validate_jwk({"kty": "oct", "k": "foo"})
436        self.assertIn("Unsupported", str(cm.exception))
437
438    def test_invalid_jwt(self):
439        """Test rejection of malformed JWT"""
440        with self.assertRaises(DPoPError):
441            self.validator.validate("not-a-jwt", expected_htm="POST", expected_htu=self.htu)
442
443    def test_missing_jwk(self):
444        """Test rejection when jwk is missing from header"""
445        payload = {
446            "htm": "POST",
447            "htu": self.htu,
448            "iat": int(time.time()),
449            "jti": "test-jti-004",
450        }
451        proof = jwt_encode(
452            payload,
453            self.builder.private_key,
454            algorithm="ES256",
455            headers={"typ": "dpop+jwt"},
456        )
457        with self.assertRaises(DPoPError) as cm:
458            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
459        self.assertIn("jwk", str(cm.exception).lower())
460
461    def test_cnf_strips_extra_jwk_members(self):
462        """Test that any claims in the JWK not covered by the JKT are removed"""
463        builder = DPoPProofBuilder()
464        builder.jwk["jku"] = "https://attacker.example/keys"
465        builder.jwk["alg"] = "RS256"
466        result = self.validator.validate(
467            builder.build(htu=self.htu), expected_htm="POST", expected_htu=self.htu
468        )
469        self.assertEqual(set(result), {"crv", "kty", "x", "y"})
470
471    def test_jti_replay_rejected(self):
472        """Test that reusing the same jti is rejected"""
473        jti = "unique-jti-12345"
474        proof = self.builder.build(htu=self.htu, jti=jti)
475        # First use should succeed
476        self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
477        # Second use with same jti should fail
478        with self.assertRaises(DPoPError) as cm:
479            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
480        self.assertIn("replay", str(cm.exception).lower())
481
482    def test_jti_different_accepted(self):
483        """Test that different jti values are both accepted"""
484        proof1 = self.builder.build(htu=self.htu, jti="jti-first")
485        proof2 = self.builder.build(htu=self.htu, jti="jti-second")
486        self.validator.validate(proof1, expected_htm="POST", expected_htu=self.htu)
487        self.validator.validate(proof2, expected_htm="POST", expected_htu=self.htu)
488
489    def test_symmetric_alg_rejected(self):
490        """Test rejection when alg header claims a symmetric algorithm"""
491        payload = {
492            "htm": "POST",
493            "htu": self.htu,
494            "iat": int(time.time()),
495            "jti": "test-jti-sym",
496        }
497        # Craft a JWT with HS256 in the header but signed with EC key
498        proof = _craft_jwt(
499            payload,
500            self.builder.private_key,
501            algorithm="ES256",
502            headers={"typ": "dpop+jwt", "jwk": self.builder.jwk, "alg": "HS256"},
503        )
504        with self.assertRaises(DPoPError) as cm:
505            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
506        self.assertIn("algorithm", str(cm.exception).lower())
507
508    def test_alg_jwk_mismatch_rejected(self):
509        """Test rejection when alg doesn't match JWK key type"""
510        payload = {
511            "htm": "POST",
512            "htu": self.htu,
513            "iat": int(time.time()),
514            "jti": "test-jti-mismatch",
515        }
516        # Craft a JWT with RS256 in the header but EC jwk and signature
517        proof = _craft_jwt(
518            payload,
519            self.builder.private_key,
520            algorithm="ES256",
521            headers={"typ": "dpop+jwt", "jwk": self.builder.jwk, "alg": "RS256"},
522        )
523        with self.assertRaises(DPoPError) as cm:
524            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
525        self.assertIn("signature", str(cm.exception).lower())
526
527    @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
528    def test_mldsa_proof_accepted(self):
529        """A DPoP proof signed with ML-DSA-44 and an AKP JWK validates; cnf is the canonical key"""
530        builder = MLDSAProofBuilder()
531        proof = builder.build(htu=self.htu)
532        result = self.validator.validate(
533            proof, expected_htm="POST", expected_htu=self.htu, expected_jkt=builder.jkt
534        )
535        self.assertEqual(result, {"alg": "ML-DSA-44", "kty": "AKP", "pub": builder.jwk["pub"]})
536
537    @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
538    def test_mldsa65_proof_accepted(self):
539        """ML-DSA-65 is accepted as well"""
540        builder = MLDSAProofBuilder("ML-DSA-65")
541        result = self.validator.validate(
542            builder.build(htu=self.htu), expected_htm="POST", expected_htu=self.htu
543        )
544        self.assertEqual(result["alg"], "ML-DSA-65")
545
546    @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
547    def test_mldsa_alg_jwk_mismatch_rejected(self):
548        """The proof's alg must name the same parameter set as the AKP key"""
549        builder = MLDSAProofBuilder()
550        proof = builder.build(htu=self.htu)
551        # Re-label the protected header's alg; the mismatch is caught before signature checks
552        header_b64, rest = proof.split(".", 1)
553        header = json.loads(base64.urlsafe_b64decode(header_b64 + "=="))
554        header["alg"] = "ML-DSA-65"
555        header_b64 = (
556            base64.urlsafe_b64encode(json.dumps(header, separators=(",", ":")).encode())
557            .rstrip(b"=")
558            .decode()
559        )
560        proof = f"{header_b64}.{rest}"
561        with self.assertRaises(DPoPError) as cm:
562            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
563        self.assertIn("does not match", str(cm.exception))
564
565    @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
566    def test_mldsa_wrong_key_rejected(self):
567        """A proof whose AKP key is not the signing key fails signature verification"""
568        builder = MLDSAProofBuilder()
569        other = MLDSAProofBuilder()
570        proof = builder.build(htu=self.htu, jwk=other.jwk)
571        with self.assertRaises(DPoPError) as cm:
572            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
573        self.assertIn("signature", str(cm.exception).lower())
574
575    @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
576    def test_mldsa_private_material_rejected(self):
577        """An AKP JWK carrying the private seed (priv) must be rejected"""
578        builder = MLDSAProofBuilder()
579        proof = builder.build(htu=self.htu, jwk={**builder.jwk, "priv": "AAAA"})
580        with self.assertRaises(DPoPError) as cm:
581            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
582        self.assertIn("private key material", str(cm.exception))
583
584    @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
585    def test_mldsa_unsupported_akp_alg_rejected(self):
586        """AKP keys for algorithms other than ML-DSA are rejected before loading"""
587        builder = MLDSAProofBuilder()
588        with self.assertRaises(DPoPError) as cm:
589            self.validator._validate_jwk({**builder.jwk, "alg": "SLH-DSA-SHA2-128s"})
590        self.assertIn("Unsupported AKP algorithm", str(cm.exception))
591
592    @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
593    def test_mldsa_key_unavailable_fails_closed(self):
594        """An AKP key OpenSSL cannot load (ML-DSA under a FIPS provider that predates it) is a
595        DPoP error, not an unhandled exception"""
596
597        class UnavailablePublicKey:
598            @staticmethod
599            def from_public_bytes(_data: bytes):
600                raise UnsupportedAlgorithm("ML-DSA is not supported by this version of OpenSSL")
601
602        builder = MLDSAProofBuilder()
603        proof = builder.build(htu=self.htu)
604        with (
605            patch.dict(
606                "authentik.lib.jwt_mldsa.MLDSA_ALGORITHMS",
607                {"ML-DSA-44": (MLDSA44PrivateKey, UnavailablePublicKey)},
608            ),
609            self.assertRaises(DPoPError) as cm,
610        ):
611            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
612        self.assertIn("Invalid AKP JWK", str(cm.exception))
613
614    def test_rsa_proof_accepted(self):
615        """A valid 2048-bit RSA DPoP proof should validate."""
616        builder = RSAProofBuilder(key_size=2048)
617        proof = builder.build(htu=self.htu)
618        result = self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
619        self.assertEqual(result["kty"], "RSA")
620
621    @skipIf(backend._fips_enabled, "FIPS mode can't sign with a 1024-bit RSA key")
622    def test_rsa_key_too_small_rejected(self):
623        """An RSA key below the minimum size (2048 bits) must be rejected."""
624        builder = RSAProofBuilder(key_size=1024)
625        proof = builder.build(htu=self.htu)
626        with self.assertRaises(DPoPError) as cm:
627            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
628        self.assertIn("too small", str(cm.exception).lower())
629
630    @skipIf(backend._fips_enabled, "FIPS mode can't sign with secp256k1")
631    def test_unsupported_ec_curve_rejected(self):
632        """An EC key on a curve outside the supported set must be rejected."""
633        priv = generate_private_key(SECP256K1())
634        nums = priv.public_key().public_numbers()
635        x = base64.urlsafe_b64encode(nums.x.to_bytes(32, "big")).rstrip(b"=").decode()
636        y = base64.urlsafe_b64encode(nums.y.to_bytes(32, "big")).rstrip(b"=").decode()
637        jwk = {"kty": "EC", "crv": "secp256k1", "x": x, "y": y}
638        payload = {
639            "htm": "POST",
640            "htu": self.htu,
641            "iat": int(time.time()),
642            "jti": "curve-jti-001",
643        }
644        proof = _craft_jwt(
645            payload,
646            priv,
647            algorithm="ES256",
648            headers={"typ": "dpop+jwt", "jwk": jwk, "alg": "ES256"},
649        )
650        with self.assertRaises(DPoPError) as cm:
651            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
652        self.assertIn("curve", str(cm.exception).lower())

Test DPoP proof validation.

def setUp(self):
276    def setUp(self):
277        self.validator = DPoPValidator()
278        self.builder = DPoPProofBuilder()
279        self.htu = "https://server.example.com/token"
280        cache.clear()

Hook method for setting up the test fixture before exercising it.

def tearDown(self):
282    def tearDown(self):
283        cache.clear()

Hook method for deconstructing the test fixture after testing it.

def test_valid_proof(self):
285    def test_valid_proof(self):
286        """Test a completely valid DPoP proof"""
287        c_s256 = pkce_s256_challenge("test-code")
288        proof = self.builder.build(c_s256=c_s256)
289        result = self.validator.validate(
290            proof,
291            expected_htm="POST",
292            expected_htu=self.htu,
293            expected_jkt=self.builder.jkt,
294            expected_c_s256=c_s256,
295        )
296        self.assertEqual(result["kty"], "EC")
297        self.assertEqual(result["crv"], "P-256")

Test a completely valid DPoP proof

def test_valid_proof_without_expected_jkt(self):
299    def test_valid_proof_without_expected_jkt(self):
300        """Test valid proof without expected_jkt check"""
301        proof = self.builder.build(htu=self.htu)
302        result = self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
303        self.assertEqual(result["kty"], "EC")

Test valid proof without expected_jkt check

def test_invalid_signature(self):
305    def test_invalid_signature(self):
306        """Test proof signed with different key than embedded jwk"""
307        other_builder = DPoPProofBuilder()
308        # Sign with other key but embed original jwk
309        payload = {
310            "htm": "POST",
311            "htu": self.htu,
312            "iat": int(time.time()),
313            "jti": "test-jti-002",
314        }
315        proof = jwt_encode(
316            payload,
317            other_builder.private_key,
318            algorithm="ES256",
319            headers={"typ": "dpop+jwt", "jwk": self.builder.jwk},
320        )
321        with self.assertRaises(DPoPError) as cm:
322            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
323        self.assertIn("signature", str(cm.exception).lower())

Test proof signed with different key than embedded jwk

def test_missing_typ_header(self):
325    def test_missing_typ_header(self):
326        """Test rejection when typ header is not dpop+jwt"""
327        proof = self.builder.build(typ="jwt")
328        with self.assertRaises(DPoPError) as cm:
329            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
330        self.assertIn("typ", str(cm.exception).lower())

Test rejection when typ header is not dpop+jwt

def test_private_key_material(self):
332    def test_private_key_material(self):
333        """Test rejection when jwk contains private key material"""
334        proof = self.builder.build(include_private=True)
335        with self.assertRaises(DPoPError) as cm:
336            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
337        self.assertIn("private", str(cm.exception).lower())

Test rejection when jwk contains private key material

def test_htm_mismatch(self):
339    def test_htm_mismatch(self):
340        """Test rejection when htm doesn't match"""
341        proof = self.builder.build(htm="GET", htu=self.htu)
342        with self.assertRaises(DPoPError) as cm:
343            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
344        self.assertIn("htm", str(cm.exception).lower())

Test rejection when htm doesn't match

def test_htu_mismatch(self):
346    def test_htu_mismatch(self):
347        """Test rejection when htu doesn't match"""
348        proof = self.builder.build(htu="https://other.example.com/token")
349        with self.assertRaises(DPoPError) as cm:
350            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
351        self.assertIn("htu", str(cm.exception).lower())

Test rejection when htu doesn't match

def test_htu_ignores_query_and_fragment(self):
353    def test_htu_ignores_query_and_fragment(self):
354        """Test htu matching ignores query and fragment"""
355        proof = self.builder.build(htu=self.htu + "?foo=bar#baz")
356        result = self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
357        self.assertEqual(result["kty"], "EC")

Test htu matching ignores query and fragment

def test_expired_iat(self):
359    def test_expired_iat(self):
360        """Test rejection when iat is too old"""
361        proof = self.builder.build(htu=self.htu, iat=int(time.time()) - 120)
362        with self.assertRaises(DPoPError) as cm:
363            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
364        self.assertIn("iat", str(cm.exception).lower())

Test rejection when iat is too old

def test_future_iat(self):
366    def test_future_iat(self):
367        """Test rejection when iat is in the future"""
368        proof = self.builder.build(htu=self.htu, iat=int(time.time()) + 120)
369        with self.assertRaises(DPoPError) as cm:
370            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
371        self.assertIn("iat", str(cm.exception).lower())

Test rejection when iat is in the future

def test_missing_jti(self):
373    def test_missing_jti(self):
374        """Test rejection when jti is missing"""
375        proof = self.builder.build(htu=self.htu, jti="")
376        with self.assertRaises(DPoPError) as cm:
377            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
378        self.assertIn("jti", str(cm.exception).lower())

Test rejection when jti is missing

def test_expected_jkt_mismatch(self):
380    def test_expected_jkt_mismatch(self):
381        """Test rejection when JWK thumbprint doesn't match expected_jkt"""
382        other_builder = DPoPProofBuilder()
383        proof = other_builder.build(htu=self.htu)
384        with self.assertRaises(DPoPError) as cm:
385            self.validator.validate(
386                proof, expected_htm="POST", expected_htu=self.htu, expected_jkt=self.builder.jkt
387            )
388        self.assertIn("thumbprint", str(cm.exception).lower())

Test rejection when JWK thumbprint doesn't match expected_jkt

def test_expected_jkt_match(self):
390    def test_expected_jkt_match(self):
391        """Test acceptance when JWK thumbprint matches expected_jkt"""
392        proof = self.builder.build(htu=self.htu)
393        result = self.validator.validate(
394            proof, expected_htm="POST", expected_htu=self.htu, expected_jkt=self.builder.jkt
395        )
396        self.assertEqual(result["kty"], "EC")

Test acceptance when JWK thumbprint matches expected_jkt

def test_c_s256_mismatch(self):
398    def test_c_s256_mismatch(self):
399        """Test rejection when c_s256 doesn't match"""
400        proof = self.builder.build(c_s256="wrong-hash")
401        with self.assertRaises(DPoPError) as cm:
402            self.validator.validate(
403                proof,
404                expected_htm="POST",
405                expected_htu=self.htu,
406                expected_c_s256=pkce_s256_challenge("correct-code"),
407            )
408        self.assertIn("c_s256", str(cm.exception).lower())

Test rejection when c_s256 doesn't match

def test_c_s256_match(self):
410    def test_c_s256_match(self):
411        """Test acceptance when c_s256 matches"""
412        code = "test-auth-code-123"
413        c_s256 = pkce_s256_challenge(code)
414        proof = self.builder.build(c_s256=c_s256)
415        result = self.validator.validate(
416            proof, expected_htm="POST", expected_htu=self.htu, expected_c_s256=c_s256
417        )
418        self.assertEqual(result["kty"], "EC")

Test acceptance when c_s256 matches

def test_c_s256_missing_when_required(self):
420    def test_c_s256_missing_when_required(self):
421        """Test rejection when c_s256 param provided but claim absent"""
422        proof = self.builder.build(htu=self.htu)
423        with self.assertRaises(DPoPError) as cm:
424            self.validator.validate(
425                proof,
426                expected_htm="POST",
427                expected_htu=self.htu,
428                expected_c_s256=pkce_s256_challenge("some-code"),
429            )
430        self.assertIn("c_s256", str(cm.exception).lower())

Test rejection when c_s256 param provided but claim absent

def test_symmetric_key_rejected(self):
432    def test_symmetric_key_rejected(self):
433        """Test rejection of symmetric keys"""
434        with self.assertRaises(DPoPError) as cm:
435            self.validator._validate_jwk({"kty": "oct", "k": "foo"})
436        self.assertIn("Unsupported", str(cm.exception))

Test rejection of symmetric keys

def test_invalid_jwt(self):
438    def test_invalid_jwt(self):
439        """Test rejection of malformed JWT"""
440        with self.assertRaises(DPoPError):
441            self.validator.validate("not-a-jwt", expected_htm="POST", expected_htu=self.htu)

Test rejection of malformed JWT

def test_missing_jwk(self):
443    def test_missing_jwk(self):
444        """Test rejection when jwk is missing from header"""
445        payload = {
446            "htm": "POST",
447            "htu": self.htu,
448            "iat": int(time.time()),
449            "jti": "test-jti-004",
450        }
451        proof = jwt_encode(
452            payload,
453            self.builder.private_key,
454            algorithm="ES256",
455            headers={"typ": "dpop+jwt"},
456        )
457        with self.assertRaises(DPoPError) as cm:
458            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
459        self.assertIn("jwk", str(cm.exception).lower())

Test rejection when jwk is missing from header

def test_cnf_strips_extra_jwk_members(self):
461    def test_cnf_strips_extra_jwk_members(self):
462        """Test that any claims in the JWK not covered by the JKT are removed"""
463        builder = DPoPProofBuilder()
464        builder.jwk["jku"] = "https://attacker.example/keys"
465        builder.jwk["alg"] = "RS256"
466        result = self.validator.validate(
467            builder.build(htu=self.htu), expected_htm="POST", expected_htu=self.htu
468        )
469        self.assertEqual(set(result), {"crv", "kty", "x", "y"})

Test that any claims in the JWK not covered by the JKT are removed

def test_jti_replay_rejected(self):
471    def test_jti_replay_rejected(self):
472        """Test that reusing the same jti is rejected"""
473        jti = "unique-jti-12345"
474        proof = self.builder.build(htu=self.htu, jti=jti)
475        # First use should succeed
476        self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
477        # Second use with same jti should fail
478        with self.assertRaises(DPoPError) as cm:
479            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
480        self.assertIn("replay", str(cm.exception).lower())

Test that reusing the same jti is rejected

def test_jti_different_accepted(self):
482    def test_jti_different_accepted(self):
483        """Test that different jti values are both accepted"""
484        proof1 = self.builder.build(htu=self.htu, jti="jti-first")
485        proof2 = self.builder.build(htu=self.htu, jti="jti-second")
486        self.validator.validate(proof1, expected_htm="POST", expected_htu=self.htu)
487        self.validator.validate(proof2, expected_htm="POST", expected_htu=self.htu)

Test that different jti values are both accepted

def test_symmetric_alg_rejected(self):
489    def test_symmetric_alg_rejected(self):
490        """Test rejection when alg header claims a symmetric algorithm"""
491        payload = {
492            "htm": "POST",
493            "htu": self.htu,
494            "iat": int(time.time()),
495            "jti": "test-jti-sym",
496        }
497        # Craft a JWT with HS256 in the header but signed with EC key
498        proof = _craft_jwt(
499            payload,
500            self.builder.private_key,
501            algorithm="ES256",
502            headers={"typ": "dpop+jwt", "jwk": self.builder.jwk, "alg": "HS256"},
503        )
504        with self.assertRaises(DPoPError) as cm:
505            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
506        self.assertIn("algorithm", str(cm.exception).lower())

Test rejection when alg header claims a symmetric algorithm

def test_alg_jwk_mismatch_rejected(self):
508    def test_alg_jwk_mismatch_rejected(self):
509        """Test rejection when alg doesn't match JWK key type"""
510        payload = {
511            "htm": "POST",
512            "htu": self.htu,
513            "iat": int(time.time()),
514            "jti": "test-jti-mismatch",
515        }
516        # Craft a JWT with RS256 in the header but EC jwk and signature
517        proof = _craft_jwt(
518            payload,
519            self.builder.private_key,
520            algorithm="ES256",
521            headers={"typ": "dpop+jwt", "jwk": self.builder.jwk, "alg": "RS256"},
522        )
523        with self.assertRaises(DPoPError) as cm:
524            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
525        self.assertIn("signature", str(cm.exception).lower())

Test rejection when alg doesn't match JWK key type

@skipIf(backend._fips_enabled, 'The FIPS provider has no ML-DSA')
def test_mldsa_proof_accepted(self):
527    @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
528    def test_mldsa_proof_accepted(self):
529        """A DPoP proof signed with ML-DSA-44 and an AKP JWK validates; cnf is the canonical key"""
530        builder = MLDSAProofBuilder()
531        proof = builder.build(htu=self.htu)
532        result = self.validator.validate(
533            proof, expected_htm="POST", expected_htu=self.htu, expected_jkt=builder.jkt
534        )
535        self.assertEqual(result, {"alg": "ML-DSA-44", "kty": "AKP", "pub": builder.jwk["pub"]})

A DPoP proof signed with ML-DSA-44 and an AKP JWK validates; cnf is the canonical key

@skipIf(backend._fips_enabled, 'The FIPS provider has no ML-DSA')
def test_mldsa65_proof_accepted(self):
537    @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
538    def test_mldsa65_proof_accepted(self):
539        """ML-DSA-65 is accepted as well"""
540        builder = MLDSAProofBuilder("ML-DSA-65")
541        result = self.validator.validate(
542            builder.build(htu=self.htu), expected_htm="POST", expected_htu=self.htu
543        )
544        self.assertEqual(result["alg"], "ML-DSA-65")

ML-DSA-65 is accepted as well

@skipIf(backend._fips_enabled, 'The FIPS provider has no ML-DSA')
def test_mldsa_alg_jwk_mismatch_rejected(self):
546    @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
547    def test_mldsa_alg_jwk_mismatch_rejected(self):
548        """The proof's alg must name the same parameter set as the AKP key"""
549        builder = MLDSAProofBuilder()
550        proof = builder.build(htu=self.htu)
551        # Re-label the protected header's alg; the mismatch is caught before signature checks
552        header_b64, rest = proof.split(".", 1)
553        header = json.loads(base64.urlsafe_b64decode(header_b64 + "=="))
554        header["alg"] = "ML-DSA-65"
555        header_b64 = (
556            base64.urlsafe_b64encode(json.dumps(header, separators=(",", ":")).encode())
557            .rstrip(b"=")
558            .decode()
559        )
560        proof = f"{header_b64}.{rest}"
561        with self.assertRaises(DPoPError) as cm:
562            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
563        self.assertIn("does not match", str(cm.exception))

The proof's alg must name the same parameter set as the AKP key

@skipIf(backend._fips_enabled, 'The FIPS provider has no ML-DSA')
def test_mldsa_wrong_key_rejected(self):
565    @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
566    def test_mldsa_wrong_key_rejected(self):
567        """A proof whose AKP key is not the signing key fails signature verification"""
568        builder = MLDSAProofBuilder()
569        other = MLDSAProofBuilder()
570        proof = builder.build(htu=self.htu, jwk=other.jwk)
571        with self.assertRaises(DPoPError) as cm:
572            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
573        self.assertIn("signature", str(cm.exception).lower())

A proof whose AKP key is not the signing key fails signature verification

@skipIf(backend._fips_enabled, 'The FIPS provider has no ML-DSA')
def test_mldsa_private_material_rejected(self):
575    @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
576    def test_mldsa_private_material_rejected(self):
577        """An AKP JWK carrying the private seed (priv) must be rejected"""
578        builder = MLDSAProofBuilder()
579        proof = builder.build(htu=self.htu, jwk={**builder.jwk, "priv": "AAAA"})
580        with self.assertRaises(DPoPError) as cm:
581            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
582        self.assertIn("private key material", str(cm.exception))

An AKP JWK carrying the private seed (priv) must be rejected

@skipIf(backend._fips_enabled, 'The FIPS provider has no ML-DSA')
def test_mldsa_unsupported_akp_alg_rejected(self):
584    @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
585    def test_mldsa_unsupported_akp_alg_rejected(self):
586        """AKP keys for algorithms other than ML-DSA are rejected before loading"""
587        builder = MLDSAProofBuilder()
588        with self.assertRaises(DPoPError) as cm:
589            self.validator._validate_jwk({**builder.jwk, "alg": "SLH-DSA-SHA2-128s"})
590        self.assertIn("Unsupported AKP algorithm", str(cm.exception))

AKP keys for algorithms other than ML-DSA are rejected before loading

@skipIf(backend._fips_enabled, 'The FIPS provider has no ML-DSA')
def test_mldsa_key_unavailable_fails_closed(self):
592    @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
593    def test_mldsa_key_unavailable_fails_closed(self):
594        """An AKP key OpenSSL cannot load (ML-DSA under a FIPS provider that predates it) is a
595        DPoP error, not an unhandled exception"""
596
597        class UnavailablePublicKey:
598            @staticmethod
599            def from_public_bytes(_data: bytes):
600                raise UnsupportedAlgorithm("ML-DSA is not supported by this version of OpenSSL")
601
602        builder = MLDSAProofBuilder()
603        proof = builder.build(htu=self.htu)
604        with (
605            patch.dict(
606                "authentik.lib.jwt_mldsa.MLDSA_ALGORITHMS",
607                {"ML-DSA-44": (MLDSA44PrivateKey, UnavailablePublicKey)},
608            ),
609            self.assertRaises(DPoPError) as cm,
610        ):
611            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
612        self.assertIn("Invalid AKP JWK", str(cm.exception))

An AKP key OpenSSL cannot load (ML-DSA under a FIPS provider that predates it) is a DPoP error, not an unhandled exception

def test_rsa_proof_accepted(self):
614    def test_rsa_proof_accepted(self):
615        """A valid 2048-bit RSA DPoP proof should validate."""
616        builder = RSAProofBuilder(key_size=2048)
617        proof = builder.build(htu=self.htu)
618        result = self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
619        self.assertEqual(result["kty"], "RSA")

A valid 2048-bit RSA DPoP proof should validate.

@skipIf(backend._fips_enabled, "FIPS mode can't sign with a 1024-bit RSA key")
def test_rsa_key_too_small_rejected(self):
621    @skipIf(backend._fips_enabled, "FIPS mode can't sign with a 1024-bit RSA key")
622    def test_rsa_key_too_small_rejected(self):
623        """An RSA key below the minimum size (2048 bits) must be rejected."""
624        builder = RSAProofBuilder(key_size=1024)
625        proof = builder.build(htu=self.htu)
626        with self.assertRaises(DPoPError) as cm:
627            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
628        self.assertIn("too small", str(cm.exception).lower())

An RSA key below the minimum size (2048 bits) must be rejected.

@skipIf(backend._fips_enabled, "FIPS mode can't sign with secp256k1")
def test_unsupported_ec_curve_rejected(self):
630    @skipIf(backend._fips_enabled, "FIPS mode can't sign with secp256k1")
631    def test_unsupported_ec_curve_rejected(self):
632        """An EC key on a curve outside the supported set must be rejected."""
633        priv = generate_private_key(SECP256K1())
634        nums = priv.public_key().public_numbers()
635        x = base64.urlsafe_b64encode(nums.x.to_bytes(32, "big")).rstrip(b"=").decode()
636        y = base64.urlsafe_b64encode(nums.y.to_bytes(32, "big")).rstrip(b"=").decode()
637        jwk = {"kty": "EC", "crv": "secp256k1", "x": x, "y": y}
638        payload = {
639            "htm": "POST",
640            "htu": self.htu,
641            "iat": int(time.time()),
642            "jti": "curve-jti-001",
643        }
644        proof = _craft_jwt(
645            payload,
646            priv,
647            algorithm="ES256",
648            headers={"typ": "dpop+jwt", "jwk": jwk, "alg": "ES256"},
649        )
650        with self.assertRaises(DPoPError) as cm:
651            self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
652        self.assertIn("curve", str(cm.exception).lower())

An EC key on a curve outside the supported set must be rejected.