providers/oauth2: accept ML-DSA keys for DPoP (#27174)

This commit is contained in:
Connor Peshek authored and GitHub committed 2026-11-05 11:40:38 -06:00
1 parent edef75fe2a
commit 65b8bce912
2 files changed
+185 -19

No files matched your search

+40 -19
View File
@@ -7,23 +7,26 @@ from hmac import compare_digest
from urllib.parse import urlparse
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey
from cryptography.hazmat.primitives.asymmetric.types import PublicKeyTypes
from django.core.cache import cache
from django.db import transaction
from jwcrypto.jwk import JWK
from jwt import PyJWK
from jwt import decode as jwt_decode
from jwt import decode_complete as jwt_decode_complete
from jwt.exceptions import InvalidTokenError, PyJWTError
from jwt.exceptions import InvalidKeyError, InvalidTokenError, PyJWTError
from structlog.stdlib import get_logger
from authentik.lib.jwt_mldsa import JWK_KTY_AKP, MLDSA_ALGORITHMS, key_from_jwk
LOGGER = get_logger()
# DPoP JWT type header value
DPOP_JWT_TYPE = "dpop+jwt"
# Supported asymmetric key types for DPoP
DPOP_SUPPORTED_KTYS = {"EC", "RSA"}
# Supported asymmetric key types for DPoP. AKP (RFC 9964) carries ML-DSA keys.
DPOP_SUPPORTED_KTYS = {"EC", "RSA", JWK_KTY_AKP}
DPOP_SUPPORTED_EC_CURVES = {"P-256", "P-384", "P-521"}
@@ -44,6 +47,8 @@ DPOP_SUPPORTED_ALGS = {
"PS256",
"PS384",
"PS512",
# ML-DSA (RFC 9964), post-quantum
*MLDSA_ALGORITHMS,
}
# Required JWK members per RFC 7638, by key type. These are exactly the
@@ -53,6 +58,8 @@ DPOP_SUPPORTED_ALGS = {
JWK_REQUIRED_CLAIMS = {
"EC": ("crv", "kty", "x", "y"),
"RSA": ("e", "kty", "n"),
# RFC 9964 Section 5: alg is REQUIRED on AKP keys and is part of the thumbprint
JWK_KTY_AKP: ("alg", "kty", "pub"),
}
# Clock skew tolerance in seconds for `iat` validation
@@ -140,11 +147,11 @@ class DPoPValidator:
raise DPoPError(f"Invalid DPoP typ header: {header.get('typ')}")
return header
def _get_and_validate_jwk(self, header: dict) -> tuple[dict, PyJWK | None]:
def _get_and_validate_jwk(self, header: dict) -> tuple[dict, PublicKeyTypes | None]:
"""Extract jwk from header and validate it.
Returns the raw jwk dict together with the PyJWK already constructed
while validating an RSA key (or None for EC), so `_verify_signature`
Returns the raw jwk dict together with the public key already loaded
while validating an RSA or AKP key (or None for EC), so `_verify_signature`
can reuse it instead of re-parsing the same key material.
"""
jwk = header.get("jwk")
@@ -160,15 +167,19 @@ class DPoPValidator:
raise DPoPError("Missing alg in DPoP header")
if alg not in DPOP_SUPPORTED_ALGS:
raise DPoPError(f"Unsupported DPoP algorithm: {alg}")
jwk = header.get("jwk") or {}
if jwk.get("kty") == JWK_KTY_AKP and jwk.get("alg") != alg:
# An AKP key is bound to one algorithm; a proof naming another is malformed
raise DPoPError(f"DPoP alg {alg} does not match JWK alg {jwk.get('alg')}")
return alg
def _verify_signature(
self, dpop_proof: str, jwk: dict, alg: str, key: PyJWK | None = None
self, dpop_proof: str, jwk: dict, alg: str, key: PublicKeyTypes | None = None
) -> dict:
"""Verify the DPoP proof signature and return the payload."""
try:
key = key or PyJWK.from_dict(jwk)
return jwt_decode(dpop_proof, key.key, algorithms=[alg], options={"verify_iat": False})
key = key or PyJWK.from_dict(jwk).key
return jwt_decode(dpop_proof, key, algorithms=[alg], options={"verify_iat": False})
except (PyJWTError, InvalidTokenError, TypeError, ValueError) as exc:
raise DPoPError("DPoP proof signature verification failed") from exc
@@ -231,31 +242,41 @@ class DPoPValidator:
if not compare_digest(thumbprint, expected_jkt):
raise DPoPError("DPoP proof JWK thumbprint mismatch")
def _validate_jwk(self, jwk: dict) -> PyJWK | None:
def _validate_jwk(self, jwk: dict) -> PublicKeyTypes | None:
"""Ensure the JWK is a public asymmetric key without private material.
Returns the PyJWK constructed while checking the RSA key size, so
`_verify_signature` can reuse it instead of re-parsing the same key.
Returns the public key loaded while checking an RSA key's size or an
AKP key's algorithm, so `_verify_signature` can reuse it instead of
re-parsing the same key.
"""
kty = jwk.get("kty")
if kty not in DPOP_SUPPORTED_KTYS:
raise DPoPError(f"Unsupported JWK kty for DPoP: {kty}")
# Reject private material before loading anything. `priv` is the AKP private seed.
private_fields = {"d", "p", "q", "dp", "dq", "qi", "priv"}
if any(field in jwk for field in private_fields):
raise DPoPError("DPoP JWK must not contain private key material")
key = None
if kty == "RSA":
key = PyJWK.from_dict(jwk)
if isinstance(key.key, RSAPublicKey) and key.key.key_size < DPOP_RSA_MIN_KEY_SIZE:
key = PyJWK.from_dict(jwk).key
if isinstance(key, RSAPublicKey) and key.key_size < DPOP_RSA_MIN_KEY_SIZE:
raise DPoPError("RSA key too small for DPoP (minimum 2048 bits)")
if isinstance(key.key, RSAPublicKey) and key.key.key_size > DPOP_RSA_MAX_KEY_SIZE:
if isinstance(key, RSAPublicKey) and key.key_size > DPOP_RSA_MAX_KEY_SIZE:
raise DPoPError("RSA key too large for DPoP")
elif kty == "EC":
crv = jwk.get("crv")
if crv not in DPOP_SUPPORTED_EC_CURVES:
raise DPoPError(f"Unsupported EC curve for DPoP: {crv}")
private_fields = {"d", "p", "q", "dp", "dq", "qi"}
if any(field in jwk for field in private_fields):
raise DPoPError("DPoP JWK must not contain private key material")
elif kty == JWK_KTY_AKP:
if jwk.get("alg") not in MLDSA_ALGORITHMS:
raise DPoPError(f"Unsupported AKP algorithm for DPoP: {jwk.get('alg')}")
try:
key, _ = key_from_jwk(jwk)
except InvalidKeyError as exc:
# Malformed key, or ML-DSA unavailable in this OpenSSL configuration (FIPS)
raise DPoPError(f"Invalid AKP JWK: {exc}") from exc
return key
@@ -5,7 +5,9 @@ import hashlib
import json
import time
from unittest import skipIf
from unittest.mock import patch
from cryptography.exceptions import UnsupportedAlgorithm
from cryptography.hazmat.backends.openssl.backend import backend
from cryptography.hazmat.primitives.asymmetric.ec import (
SECP256K1,
@@ -13,6 +15,7 @@ from cryptography.hazmat.primitives.asymmetric.ec import (
EllipticCurvePrivateKey,
generate_private_key,
)
from cryptography.hazmat.primitives.asymmetric.mldsa import MLDSA44PrivateKey, MLDSA65PrivateKey
from cryptography.hazmat.primitives.asymmetric.rsa import generate_private_key as generate_rsa_key
from django.core.cache import cache
from django.test import TestCase
@@ -150,6 +153,47 @@ class RSAProofBuilder:
return jwk_thumbprint(self.jwk)
class MLDSAProofBuilder:
"""Helper to build ML-DSA-signed DPoP proof JWTs (RFC 9964 AKP key) for testing"""
def __init__(self, alg: str = "ML-DSA-44"):
self.alg = alg
self.private_key = {"ML-DSA-44": MLDSA44PrivateKey, "ML-DSA-65": MLDSA65PrivateKey}[
alg
].generate()
pub = self.private_key.public_key().public_bytes_raw()
self.jwk = {
"kty": "AKP",
"alg": alg,
"pub": base64.urlsafe_b64encode(pub).rstrip(b"=").decode(),
}
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:
headers = {
"typ": "dpop+jwt",
"jwk": (jwk if jwk is not None else self.jwk).copy(),
"alg": self.alg,
}
payload = {
"htm": htm,
"htu": htu,
"iat": iat if iat is not None else int(time.time()),
"jti": jti,
}
return jwt_encode(payload, self.private_key, algorithm=self.alg, headers=headers)
@property
def jkt(self) -> str:
return jwk_thumbprint(self.jwk)
class TestJWKThumbprint(TestCase):
"""Test JWK thumbprint computation"""
@@ -183,6 +227,20 @@ class TestJWKThumbprint(TestCase):
self.assertIsInstance(thumbprint, str)
self.assertGreater(len(thumbprint), 0)
@skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
def test_mldsa_thumbprint(self):
"""AKP thumbprint is computed over alg, kty and pub (RFC 9964 Section 6)"""
builder = MLDSAProofBuilder()
canonical = json.dumps(
{"alg": "ML-DSA-44", "kty": "AKP", "pub": builder.jwk["pub"]}, separators=(",", ":")
).encode()
expected = base64.urlsafe_b64encode(hashlib.sha256(canonical).digest()).rstrip(b"=")
self.assertEqual(jwk_thumbprint(builder.jwk), expected.decode())
# Extra members must not change the thumbprint
self.assertEqual(
jwk_thumbprint({**builder.jwk, "kid": "x", "use": "sig"}), expected.decode()
)
def test_unsupported_kty(self):
"""Test unsupported key type — jwcrypto may accept it but DPoP validator rejects it"""
validator = DPoPValidator()
@@ -465,6 +523,93 @@ class TestDPoPValidator(TestCase):
self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
self.assertIn("signature", str(cm.exception).lower())
@skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
def test_mldsa_proof_accepted(self):
"""A DPoP proof signed with ML-DSA-44 and an AKP JWK validates; cnf is the canonical key"""
builder = MLDSAProofBuilder()
proof = builder.build(htu=self.htu)
result = self.validator.validate(
proof, expected_htm="POST", expected_htu=self.htu, expected_jkt=builder.jkt
)
self.assertEqual(result, {"alg": "ML-DSA-44", "kty": "AKP", "pub": builder.jwk["pub"]})
@skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
def test_mldsa65_proof_accepted(self):
"""ML-DSA-65 is accepted as well"""
builder = MLDSAProofBuilder("ML-DSA-65")
result = self.validator.validate(
builder.build(htu=self.htu), expected_htm="POST", expected_htu=self.htu
)
self.assertEqual(result["alg"], "ML-DSA-65")
@skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
def test_mldsa_alg_jwk_mismatch_rejected(self):
"""The proof's alg must name the same parameter set as the AKP key"""
builder = MLDSAProofBuilder()
proof = builder.build(htu=self.htu)
# Re-label the protected header's alg; the mismatch is caught before signature checks
header_b64, rest = proof.split(".", 1)
header = json.loads(base64.urlsafe_b64decode(header_b64 + "=="))
header["alg"] = "ML-DSA-65"
header_b64 = (
base64.urlsafe_b64encode(json.dumps(header, separators=(",", ":")).encode())
.rstrip(b"=")
.decode()
)
proof = f"{header_b64}.{rest}"
with self.assertRaises(DPoPError) as cm:
self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
self.assertIn("does not match", str(cm.exception))
@skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
def test_mldsa_wrong_key_rejected(self):
"""A proof whose AKP key is not the signing key fails signature verification"""
builder = MLDSAProofBuilder()
other = MLDSAProofBuilder()
proof = builder.build(htu=self.htu, jwk=other.jwk)
with self.assertRaises(DPoPError) as cm:
self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
self.assertIn("signature", str(cm.exception).lower())
@skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
def test_mldsa_private_material_rejected(self):
"""An AKP JWK carrying the private seed (priv) must be rejected"""
builder = MLDSAProofBuilder()
proof = builder.build(htu=self.htu, jwk={**builder.jwk, "priv": "AAAA"})
with self.assertRaises(DPoPError) as cm:
self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
self.assertIn("private key material", str(cm.exception))
@skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
def test_mldsa_unsupported_akp_alg_rejected(self):
"""AKP keys for algorithms other than ML-DSA are rejected before loading"""
builder = MLDSAProofBuilder()
with self.assertRaises(DPoPError) as cm:
self.validator._validate_jwk({**builder.jwk, "alg": "SLH-DSA-SHA2-128s"})
self.assertIn("Unsupported AKP algorithm", str(cm.exception))
@skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
def test_mldsa_key_unavailable_fails_closed(self):
"""An AKP key OpenSSL cannot load (ML-DSA under a FIPS provider that predates it) is a
DPoP error, not an unhandled exception"""
class UnavailablePublicKey:
@staticmethod
def from_public_bytes(_data: bytes):
raise UnsupportedAlgorithm("ML-DSA is not supported by this version of OpenSSL")
builder = MLDSAProofBuilder()
proof = builder.build(htu=self.htu)
with (
patch.dict(
"authentik.lib.jwt_mldsa.MLDSA_ALGORITHMS",
{"ML-DSA-44": (MLDSA44PrivateKey, UnavailablePublicKey)},
),
self.assertRaises(DPoPError) as cm,
):
self.validator.validate(proof, expected_htm="POST", expected_htu=self.htu)
self.assertIn("Invalid AKP JWK", str(cm.exception))
def test_rsa_proof_accepted(self):
"""A valid 2048-bit RSA DPoP proof should validate."""
builder = RSAProofBuilder(key_size=2048)