authentik.providers.oauth2.tests.test_token_cc_jwt_source
Test token view
1"""Test token view""" 2 3from datetime import datetime, timedelta 4from json import loads 5from unittest import skipIf 6from unittest.mock import patch 7 8from cryptography.exceptions import UnsupportedAlgorithm 9from cryptography.hazmat.backends.openssl.backend import backend 10from cryptography.hazmat.primitives.asymmetric.mldsa import MLDSA44PrivateKey 11from django.test import RequestFactory 12from django.urls import reverse 13from jwt import decode, encode 14 15from authentik.blueprints.tests import apply_blueprint 16from authentik.common.oauth.constants import ( 17 GRANT_TYPE_CLIENT_CREDENTIALS, 18 SCOPE_OPENID, 19 SCOPE_OPENID_EMAIL, 20 SCOPE_OPENID_PROFILE, 21 TOKEN_TYPE, 22) 23from authentik.core.models import USERNAME_MAX_LENGTH, Application, Group, User 24from authentik.core.tests.utils import create_test_cert, create_test_flow 25from authentik.crypto.builder import PrivateKeyAlg 26from authentik.crypto.models import CertificateKeyPair 27from authentik.lib.generators import generate_id 28from authentik.lib.jwt_mldsa import MLDSAAlgorithm 29from authentik.policies.models import PolicyBinding 30from authentik.providers.oauth2.models import ( 31 GrantType, 32 OAuth2Provider, 33 RedirectURI, 34 RedirectURIMatchingMode, 35 ScopeMapping, 36) 37from authentik.providers.oauth2.tests.utils import OAuthTestCase 38from authentik.providers.oauth2.views.jwks import JWKSView 39from authentik.sources.oauth.models import OAuthSource, OAuthSourcePropertyMapping 40 41 42def mldsa_jwk(cert: CertificateKeyPair) -> dict: 43 """Public AKP JWK (RFC 9964) for an ML-DSA certificate, as an upstream IdP would publish it""" 44 jwk = MLDSAAlgorithm.to_jwk(cert.private_key.public_key(), as_dict=True) 45 jwk["kid"] = cert.kid 46 jwk["use"] = "sig" 47 return jwk 48 49 50class TestTokenClientCredentialsJWTSource(OAuthTestCase): 51 """Test token (client_credentials, with JWT) view""" 52 53 @apply_blueprint("system/providers-oauth2.yaml") 54 def setUp(self) -> None: 55 super().setUp() 56 self.factory = RequestFactory() 57 self.other_cert = create_test_cert() 58 # Provider used as a helper to sign JWTs with the same key as the OAuth source has 59 self.helper_provider = OAuth2Provider.objects.create( 60 name=generate_id(), 61 authorization_flow=create_test_flow(), 62 signing_key=self.other_cert, 63 ) 64 self.cert = create_test_cert() 65 66 jwk = JWKSView().get_jwk_for_key(self.other_cert, "sig") 67 self.source: OAuthSource = OAuthSource.objects.create( 68 name=generate_id(), 69 slug=generate_id(), 70 provider_type="openidconnect", 71 consumer_key=generate_id(), 72 consumer_secret=generate_id(), 73 authorization_url="http://foo", 74 access_token_url=f"http://{generate_id()}", 75 profile_url="http://foo", 76 oidc_well_known_url="", 77 oidc_jwks_url="", 78 oidc_jwks={ 79 "keys": [jwk], 80 }, 81 ) 82 83 self.provider: OAuth2Provider = OAuth2Provider.objects.create( 84 name="test", 85 authorization_flow=create_test_flow(), 86 redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://testserver")], 87 signing_key=self.cert, 88 grant_types=[GrantType.CLIENT_CREDENTIALS], 89 ) 90 self.provider.jwt_federation_sources.add(self.source) 91 self.provider.property_mappings.set(ScopeMapping.objects.all()) 92 self.app = Application.objects.create(name="test", slug="test", provider=self.provider) 93 94 def test_invalid_type(self): 95 """test invalid type""" 96 response = self.client.post( 97 reverse("authentik_providers_oauth2:token"), 98 { 99 "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS, 100 "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}", 101 "client_id": self.provider.client_id, 102 "client_assertion_type": "foo", 103 "client_assertion": "foo.bar", 104 }, 105 ) 106 self.assertEqual(response.status_code, 400) 107 body = loads(response.content.decode()) 108 self.assertEqual(body["error"], "invalid_grant") 109 110 def test_invalid_jwt(self): 111 """test invalid JWT""" 112 response = self.client.post( 113 reverse("authentik_providers_oauth2:token"), 114 { 115 "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS, 116 "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}", 117 "client_id": self.provider.client_id, 118 "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", 119 "client_assertion": "foo.bar", 120 }, 121 ) 122 self.assertEqual(response.status_code, 400) 123 body = loads(response.content.decode()) 124 self.assertEqual(body["error"], "invalid_grant") 125 126 def test_invalid_signature(self): 127 """test invalid JWT""" 128 token = self.helper_provider.encode( 129 { 130 "sub": "foo", 131 "exp": datetime.now() + timedelta(hours=2), 132 } 133 ) 134 response = self.client.post( 135 reverse("authentik_providers_oauth2:token"), 136 { 137 "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS, 138 "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}", 139 "client_id": self.provider.client_id, 140 "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", 141 "client_assertion": token + "foo", 142 }, 143 ) 144 self.assertEqual(response.status_code, 400) 145 body = loads(response.content.decode()) 146 self.assertEqual(body["error"], "invalid_grant") 147 148 def test_invalid_expired(self): 149 """test invalid JWT""" 150 token = self.helper_provider.encode( 151 { 152 "sub": "foo", 153 "exp": datetime.now() - timedelta(hours=2), 154 } 155 ) 156 response = self.client.post( 157 reverse("authentik_providers_oauth2:token"), 158 { 159 "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS, 160 "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}", 161 "client_id": self.provider.client_id, 162 "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", 163 "client_assertion": token, 164 }, 165 ) 166 self.assertEqual(response.status_code, 400) 167 body = loads(response.content.decode()) 168 self.assertEqual(body["error"], "invalid_grant") 169 170 def test_invalid_no_app(self): 171 """test invalid JWT""" 172 self.app.provider = None 173 self.app.save() 174 token = self.helper_provider.encode( 175 { 176 "sub": "foo", 177 "exp": datetime.now() + timedelta(hours=2), 178 } 179 ) 180 response = self.client.post( 181 reverse("authentik_providers_oauth2:token"), 182 { 183 "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS, 184 "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}", 185 "client_id": self.provider.client_id, 186 "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", 187 "client_assertion": token, 188 }, 189 ) 190 self.assertEqual(response.status_code, 400) 191 body = loads(response.content.decode()) 192 self.assertEqual(body["error"], "invalid_grant") 193 194 def test_invalid_access_denied(self): 195 """test invalid JWT""" 196 group = Group.objects.create(name="foo") 197 PolicyBinding.objects.create( 198 group=group, 199 target=self.app, 200 order=0, 201 ) 202 token = self.helper_provider.encode( 203 { 204 "sub": "foo", 205 "exp": datetime.now() + timedelta(hours=2), 206 } 207 ) 208 response = self.client.post( 209 reverse("authentik_providers_oauth2:token"), 210 { 211 "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS, 212 "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}", 213 "client_id": self.provider.client_id, 214 "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", 215 "client_assertion": token, 216 }, 217 ) 218 self.assertEqual(response.status_code, 400) 219 body = loads(response.content.decode()) 220 self.assertEqual(body["error"], "invalid_grant") 221 222 def test_successful(self): 223 """test successful""" 224 token = self.helper_provider.encode( 225 { 226 "sub": "foo", 227 "exp": datetime.now() + timedelta(hours=2), 228 } 229 ) 230 response = self.client.post( 231 reverse("authentik_providers_oauth2:token"), 232 { 233 "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS, 234 "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}", 235 "client_id": self.provider.client_id, 236 "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", 237 "client_assertion": token, 238 }, 239 ) 240 self.assertEqual(response.status_code, 200) 241 242 user = User.objects.filter(username=f"{self.provider.name}-foo").first() 243 self.assertIsNotNone(user) 244 245 body = loads(response.content.decode()) 246 self.assertEqual(body["token_type"], TOKEN_TYPE) 247 _, alg = self.provider.jwt_key 248 jwt = decode( 249 body["access_token"], 250 key=self.provider.signing_key.public_key, 251 algorithms=[alg], 252 audience=self.provider.client_id, 253 ) 254 self.assertEqual( 255 jwt["given_name"], "Autogenerated user from application test (client credentials JWT)" 256 ) 257 self.assertEqual(jwt["preferred_username"], "test-foo") 258 259 def test_successful_attributes_verifying_source(self): 260 """A second federation source advertising the same kid must not be credited with 261 the verification. The resolved source selects the user path and property mappings, 262 so crediting the wrong one creates the user under the wrong source.""" 263 real_jwk = JWKSView().get_jwk_for_key(self.other_cert, "sig") 264 # Same kid, different key material: this source is found by the kid lookup but 265 # can never verify the assertion. 266 decoy_jwk = JWKSView().get_jwk_for_key(create_test_cert(), "sig") 267 decoy_jwk["kid"] = real_jwk["kid"] 268 decoy_source = OAuthSource.objects.create( 269 name=generate_id(), 270 slug=generate_id(), 271 provider_type="openidconnect", 272 consumer_key=generate_id(), 273 consumer_secret=generate_id(), 274 authorization_url="http://foo", 275 access_token_url=f"http://{generate_id()}", 276 profile_url="http://foo", 277 oidc_well_known_url="", 278 oidc_jwks_url="", 279 oidc_jwks={"keys": [decoy_jwk]}, 280 ) 281 self.provider.jwt_federation_sources.add(decoy_source) 282 283 token = self.helper_provider.encode( 284 { 285 "sub": "foo", 286 "exp": datetime.now() + timedelta(hours=2), 287 } 288 ) 289 response = self.client.post( 290 reverse("authentik_providers_oauth2:token"), 291 { 292 "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS, 293 "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}", 294 "client_id": self.provider.client_id, 295 "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", 296 "client_assertion": token, 297 }, 298 ) 299 self.assertEqual(response.status_code, 200) 300 301 user = User.objects.filter(username=f"{self.provider.name}-foo").first() 302 self.assertIsNotNone(user) 303 self.assertEqual(user.path, self.source.get_user_path()) 304 self.assertNotEqual(user.path, decoy_source.get_user_path()) 305 306 def test_successful_mapping(self): 307 """test successful""" 308 test_username = ("mapped-foo" + ("a" * 150))[:USERNAME_MAX_LENGTH] 309 mapping = OAuthSourcePropertyMapping.objects.create( 310 name="test-mapping", 311 expression="""return { 312 "email": oauth_userinfo.get("email"), 313 "name": oauth_userinfo.get("name"), 314 "username": oauth_userinfo.get("username"), 315 }""", 316 ) 317 self.source.user_property_mappings.add(mapping) 318 319 token = self.helper_provider.encode( 320 { 321 "sub": "foo", 322 "email": "test-user@example.com", 323 "name": "Mapped Test User", 324 "username": "mapped-foo" + ("a" * 150), 325 "exp": datetime.now() + timedelta(hours=2), 326 } 327 ) 328 response = self.client.post( 329 reverse("authentik_providers_oauth2:token"), 330 { 331 "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS, 332 "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}", 333 "client_id": self.provider.client_id, 334 "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", 335 "client_assertion": token, 336 }, 337 ) 338 self.assertEqual(response.status_code, 200) 339 340 user = User.objects.filter(username=test_username).first() 341 self.assertIsNotNone(user) 342 343 body = loads(response.content.decode()) 344 self.assertEqual(body["token_type"], TOKEN_TYPE) 345 key_obj, alg = self.provider.jwt_key 346 jwt = decode( 347 body["access_token"], 348 key=key_obj.public_key(), 349 algorithms=[alg], 350 audience=self.provider.client_id, 351 ) 352 353 self.assertEqual(jwt["email"], "test-user@example.com") 354 self.assertEqual(jwt["given_name"], "Mapped Test User") 355 self.assertEqual(jwt["preferred_username"], test_username) 356 357 @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA") 358 def test_successful_mldsa_source(self): 359 """test successful with a client assertion signed by an ML-DSA key (RFC 9964 AKP JWK)""" 360 mldsa_cert = create_test_cert(PrivateKeyAlg.MLDSA44) 361 jwk = mldsa_jwk(mldsa_cert) 362 self.assertEqual(jwk["kty"], "AKP") 363 self.assertEqual(jwk["alg"], "ML-DSA-44") 364 self.source.oidc_jwks = {"keys": [jwk]} 365 self.source.save() 366 token = encode( 367 { 368 "sub": "foo", 369 "exp": datetime.now() + timedelta(hours=2), 370 }, 371 key=mldsa_cert.private_key, 372 algorithm="ML-DSA-44", 373 headers={"kid": mldsa_cert.kid}, 374 ) 375 response = self.client.post( 376 reverse("authentik_providers_oauth2:token"), 377 { 378 "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS, 379 "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}", 380 "client_id": self.provider.client_id, 381 "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", 382 "client_assertion": token, 383 }, 384 ) 385 self.assertEqual(response.status_code, 200) 386 self.assertIsNotNone(User.objects.filter(username=f"{self.provider.name}-foo").first()) 387 388 @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA") 389 def test_successful_mldsa_key_unavailable(self): 390 """An AKP key in the source's JWKS that OpenSSL cannot load (ML-DSA under a FIPS provider 391 that predates it) is skipped, and the remaining keys are still tried""" 392 393 class UnavailablePublicKey: 394 @staticmethod 395 def from_public_bytes(_data: bytes): 396 raise UnsupportedAlgorithm("ML-DSA is not supported by this version of OpenSSL") 397 398 mldsa_cert = create_test_cert(PrivateKeyAlg.MLDSA44) 399 unavailable_jwk = mldsa_jwk(mldsa_cert) 400 # Without a kid, the key is not skipped by the kid match and must actually be loaded 401 del unavailable_jwk["kid"] 402 helper_jwk = JWKSView().get_jwk_for_key(self.other_cert, "sig") 403 self.source.oidc_jwks = {"keys": [unavailable_jwk, helper_jwk]} 404 self.source.save() 405 token = self.helper_provider.encode( 406 { 407 "sub": "foo", 408 "exp": datetime.now() + timedelta(hours=2), 409 } 410 ) 411 with patch.dict( 412 "authentik.lib.jwt_mldsa.MLDSA_ALGORITHMS", 413 {"ML-DSA-44": (MLDSA44PrivateKey, UnavailablePublicKey)}, 414 ): 415 response = self.client.post( 416 reverse("authentik_providers_oauth2:token"), 417 { 418 "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS, 419 "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}", 420 "client_id": self.provider.client_id, 421 "client_assertion_type": ( 422 "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" 423 ), 424 "client_assertion": token, 425 }, 426 ) 427 self.assertEqual(response.status_code, 200) 428 self.assertIsNotNone(User.objects.filter(username=f"{self.provider.name}-foo").first())
43def mldsa_jwk(cert: CertificateKeyPair) -> dict: 44 """Public AKP JWK (RFC 9964) for an ML-DSA certificate, as an upstream IdP would publish it""" 45 jwk = MLDSAAlgorithm.to_jwk(cert.private_key.public_key(), as_dict=True) 46 jwk["kid"] = cert.kid 47 jwk["use"] = "sig" 48 return jwk
Public AKP JWK (RFC 9964) for an ML-DSA certificate, as an upstream IdP would publish it
51class TestTokenClientCredentialsJWTSource(OAuthTestCase): 52 """Test token (client_credentials, with JWT) view""" 53 54 @apply_blueprint("system/providers-oauth2.yaml") 55 def setUp(self) -> None: 56 super().setUp() 57 self.factory = RequestFactory() 58 self.other_cert = create_test_cert() 59 # Provider used as a helper to sign JWTs with the same key as the OAuth source has 60 self.helper_provider = OAuth2Provider.objects.create( 61 name=generate_id(), 62 authorization_flow=create_test_flow(), 63 signing_key=self.other_cert, 64 ) 65 self.cert = create_test_cert() 66 67 jwk = JWKSView().get_jwk_for_key(self.other_cert, "sig") 68 self.source: OAuthSource = OAuthSource.objects.create( 69 name=generate_id(), 70 slug=generate_id(), 71 provider_type="openidconnect", 72 consumer_key=generate_id(), 73 consumer_secret=generate_id(), 74 authorization_url="http://foo", 75 access_token_url=f"http://{generate_id()}", 76 profile_url="http://foo", 77 oidc_well_known_url="", 78 oidc_jwks_url="", 79 oidc_jwks={ 80 "keys": [jwk], 81 }, 82 ) 83 84 self.provider: OAuth2Provider = OAuth2Provider.objects.create( 85 name="test", 86 authorization_flow=create_test_flow(), 87 redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://testserver")], 88 signing_key=self.cert, 89 grant_types=[GrantType.CLIENT_CREDENTIALS], 90 ) 91 self.provider.jwt_federation_sources.add(self.source) 92 self.provider.property_mappings.set(ScopeMapping.objects.all()) 93 self.app = Application.objects.create(name="test", slug="test", provider=self.provider) 94 95 def test_invalid_type(self): 96 """test invalid type""" 97 response = self.client.post( 98 reverse("authentik_providers_oauth2:token"), 99 { 100 "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS, 101 "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}", 102 "client_id": self.provider.client_id, 103 "client_assertion_type": "foo", 104 "client_assertion": "foo.bar", 105 }, 106 ) 107 self.assertEqual(response.status_code, 400) 108 body = loads(response.content.decode()) 109 self.assertEqual(body["error"], "invalid_grant") 110 111 def test_invalid_jwt(self): 112 """test invalid JWT""" 113 response = self.client.post( 114 reverse("authentik_providers_oauth2:token"), 115 { 116 "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS, 117 "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}", 118 "client_id": self.provider.client_id, 119 "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", 120 "client_assertion": "foo.bar", 121 }, 122 ) 123 self.assertEqual(response.status_code, 400) 124 body = loads(response.content.decode()) 125 self.assertEqual(body["error"], "invalid_grant") 126 127 def test_invalid_signature(self): 128 """test invalid JWT""" 129 token = self.helper_provider.encode( 130 { 131 "sub": "foo", 132 "exp": datetime.now() + timedelta(hours=2), 133 } 134 ) 135 response = self.client.post( 136 reverse("authentik_providers_oauth2:token"), 137 { 138 "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS, 139 "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}", 140 "client_id": self.provider.client_id, 141 "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", 142 "client_assertion": token + "foo", 143 }, 144 ) 145 self.assertEqual(response.status_code, 400) 146 body = loads(response.content.decode()) 147 self.assertEqual(body["error"], "invalid_grant") 148 149 def test_invalid_expired(self): 150 """test invalid JWT""" 151 token = self.helper_provider.encode( 152 { 153 "sub": "foo", 154 "exp": datetime.now() - timedelta(hours=2), 155 } 156 ) 157 response = self.client.post( 158 reverse("authentik_providers_oauth2:token"), 159 { 160 "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS, 161 "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}", 162 "client_id": self.provider.client_id, 163 "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", 164 "client_assertion": token, 165 }, 166 ) 167 self.assertEqual(response.status_code, 400) 168 body = loads(response.content.decode()) 169 self.assertEqual(body["error"], "invalid_grant") 170 171 def test_invalid_no_app(self): 172 """test invalid JWT""" 173 self.app.provider = None 174 self.app.save() 175 token = self.helper_provider.encode( 176 { 177 "sub": "foo", 178 "exp": datetime.now() + timedelta(hours=2), 179 } 180 ) 181 response = self.client.post( 182 reverse("authentik_providers_oauth2:token"), 183 { 184 "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS, 185 "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}", 186 "client_id": self.provider.client_id, 187 "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", 188 "client_assertion": token, 189 }, 190 ) 191 self.assertEqual(response.status_code, 400) 192 body = loads(response.content.decode()) 193 self.assertEqual(body["error"], "invalid_grant") 194 195 def test_invalid_access_denied(self): 196 """test invalid JWT""" 197 group = Group.objects.create(name="foo") 198 PolicyBinding.objects.create( 199 group=group, 200 target=self.app, 201 order=0, 202 ) 203 token = self.helper_provider.encode( 204 { 205 "sub": "foo", 206 "exp": datetime.now() + timedelta(hours=2), 207 } 208 ) 209 response = self.client.post( 210 reverse("authentik_providers_oauth2:token"), 211 { 212 "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS, 213 "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}", 214 "client_id": self.provider.client_id, 215 "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", 216 "client_assertion": token, 217 }, 218 ) 219 self.assertEqual(response.status_code, 400) 220 body = loads(response.content.decode()) 221 self.assertEqual(body["error"], "invalid_grant") 222 223 def test_successful(self): 224 """test successful""" 225 token = self.helper_provider.encode( 226 { 227 "sub": "foo", 228 "exp": datetime.now() + timedelta(hours=2), 229 } 230 ) 231 response = self.client.post( 232 reverse("authentik_providers_oauth2:token"), 233 { 234 "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS, 235 "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}", 236 "client_id": self.provider.client_id, 237 "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", 238 "client_assertion": token, 239 }, 240 ) 241 self.assertEqual(response.status_code, 200) 242 243 user = User.objects.filter(username=f"{self.provider.name}-foo").first() 244 self.assertIsNotNone(user) 245 246 body = loads(response.content.decode()) 247 self.assertEqual(body["token_type"], TOKEN_TYPE) 248 _, alg = self.provider.jwt_key 249 jwt = decode( 250 body["access_token"], 251 key=self.provider.signing_key.public_key, 252 algorithms=[alg], 253 audience=self.provider.client_id, 254 ) 255 self.assertEqual( 256 jwt["given_name"], "Autogenerated user from application test (client credentials JWT)" 257 ) 258 self.assertEqual(jwt["preferred_username"], "test-foo") 259 260 def test_successful_attributes_verifying_source(self): 261 """A second federation source advertising the same kid must not be credited with 262 the verification. The resolved source selects the user path and property mappings, 263 so crediting the wrong one creates the user under the wrong source.""" 264 real_jwk = JWKSView().get_jwk_for_key(self.other_cert, "sig") 265 # Same kid, different key material: this source is found by the kid lookup but 266 # can never verify the assertion. 267 decoy_jwk = JWKSView().get_jwk_for_key(create_test_cert(), "sig") 268 decoy_jwk["kid"] = real_jwk["kid"] 269 decoy_source = OAuthSource.objects.create( 270 name=generate_id(), 271 slug=generate_id(), 272 provider_type="openidconnect", 273 consumer_key=generate_id(), 274 consumer_secret=generate_id(), 275 authorization_url="http://foo", 276 access_token_url=f"http://{generate_id()}", 277 profile_url="http://foo", 278 oidc_well_known_url="", 279 oidc_jwks_url="", 280 oidc_jwks={"keys": [decoy_jwk]}, 281 ) 282 self.provider.jwt_federation_sources.add(decoy_source) 283 284 token = self.helper_provider.encode( 285 { 286 "sub": "foo", 287 "exp": datetime.now() + timedelta(hours=2), 288 } 289 ) 290 response = self.client.post( 291 reverse("authentik_providers_oauth2:token"), 292 { 293 "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS, 294 "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}", 295 "client_id": self.provider.client_id, 296 "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", 297 "client_assertion": token, 298 }, 299 ) 300 self.assertEqual(response.status_code, 200) 301 302 user = User.objects.filter(username=f"{self.provider.name}-foo").first() 303 self.assertIsNotNone(user) 304 self.assertEqual(user.path, self.source.get_user_path()) 305 self.assertNotEqual(user.path, decoy_source.get_user_path()) 306 307 def test_successful_mapping(self): 308 """test successful""" 309 test_username = ("mapped-foo" + ("a" * 150))[:USERNAME_MAX_LENGTH] 310 mapping = OAuthSourcePropertyMapping.objects.create( 311 name="test-mapping", 312 expression="""return { 313 "email": oauth_userinfo.get("email"), 314 "name": oauth_userinfo.get("name"), 315 "username": oauth_userinfo.get("username"), 316 }""", 317 ) 318 self.source.user_property_mappings.add(mapping) 319 320 token = self.helper_provider.encode( 321 { 322 "sub": "foo", 323 "email": "test-user@example.com", 324 "name": "Mapped Test User", 325 "username": "mapped-foo" + ("a" * 150), 326 "exp": datetime.now() + timedelta(hours=2), 327 } 328 ) 329 response = self.client.post( 330 reverse("authentik_providers_oauth2:token"), 331 { 332 "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS, 333 "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}", 334 "client_id": self.provider.client_id, 335 "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", 336 "client_assertion": token, 337 }, 338 ) 339 self.assertEqual(response.status_code, 200) 340 341 user = User.objects.filter(username=test_username).first() 342 self.assertIsNotNone(user) 343 344 body = loads(response.content.decode()) 345 self.assertEqual(body["token_type"], TOKEN_TYPE) 346 key_obj, alg = self.provider.jwt_key 347 jwt = decode( 348 body["access_token"], 349 key=key_obj.public_key(), 350 algorithms=[alg], 351 audience=self.provider.client_id, 352 ) 353 354 self.assertEqual(jwt["email"], "test-user@example.com") 355 self.assertEqual(jwt["given_name"], "Mapped Test User") 356 self.assertEqual(jwt["preferred_username"], test_username) 357 358 @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA") 359 def test_successful_mldsa_source(self): 360 """test successful with a client assertion signed by an ML-DSA key (RFC 9964 AKP JWK)""" 361 mldsa_cert = create_test_cert(PrivateKeyAlg.MLDSA44) 362 jwk = mldsa_jwk(mldsa_cert) 363 self.assertEqual(jwk["kty"], "AKP") 364 self.assertEqual(jwk["alg"], "ML-DSA-44") 365 self.source.oidc_jwks = {"keys": [jwk]} 366 self.source.save() 367 token = encode( 368 { 369 "sub": "foo", 370 "exp": datetime.now() + timedelta(hours=2), 371 }, 372 key=mldsa_cert.private_key, 373 algorithm="ML-DSA-44", 374 headers={"kid": mldsa_cert.kid}, 375 ) 376 response = self.client.post( 377 reverse("authentik_providers_oauth2:token"), 378 { 379 "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS, 380 "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}", 381 "client_id": self.provider.client_id, 382 "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", 383 "client_assertion": token, 384 }, 385 ) 386 self.assertEqual(response.status_code, 200) 387 self.assertIsNotNone(User.objects.filter(username=f"{self.provider.name}-foo").first()) 388 389 @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA") 390 def test_successful_mldsa_key_unavailable(self): 391 """An AKP key in the source's JWKS that OpenSSL cannot load (ML-DSA under a FIPS provider 392 that predates it) is skipped, and the remaining keys are still tried""" 393 394 class UnavailablePublicKey: 395 @staticmethod 396 def from_public_bytes(_data: bytes): 397 raise UnsupportedAlgorithm("ML-DSA is not supported by this version of OpenSSL") 398 399 mldsa_cert = create_test_cert(PrivateKeyAlg.MLDSA44) 400 unavailable_jwk = mldsa_jwk(mldsa_cert) 401 # Without a kid, the key is not skipped by the kid match and must actually be loaded 402 del unavailable_jwk["kid"] 403 helper_jwk = JWKSView().get_jwk_for_key(self.other_cert, "sig") 404 self.source.oidc_jwks = {"keys": [unavailable_jwk, helper_jwk]} 405 self.source.save() 406 token = self.helper_provider.encode( 407 { 408 "sub": "foo", 409 "exp": datetime.now() + timedelta(hours=2), 410 } 411 ) 412 with patch.dict( 413 "authentik.lib.jwt_mldsa.MLDSA_ALGORITHMS", 414 {"ML-DSA-44": (MLDSA44PrivateKey, UnavailablePublicKey)}, 415 ): 416 response = self.client.post( 417 reverse("authentik_providers_oauth2:token"), 418 { 419 "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS, 420 "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}", 421 "client_id": self.provider.client_id, 422 "client_assertion_type": ( 423 "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" 424 ), 425 "client_assertion": token, 426 }, 427 ) 428 self.assertEqual(response.status_code, 200) 429 self.assertIsNotNone(User.objects.filter(username=f"{self.provider.name}-foo").first())
Test token (client_credentials, with JWT) view
@apply_blueprint('system/providers-oauth2.yaml')
def
setUp(self) -> None:
54 @apply_blueprint("system/providers-oauth2.yaml") 55 def setUp(self) -> None: 56 super().setUp() 57 self.factory = RequestFactory() 58 self.other_cert = create_test_cert() 59 # Provider used as a helper to sign JWTs with the same key as the OAuth source has 60 self.helper_provider = OAuth2Provider.objects.create( 61 name=generate_id(), 62 authorization_flow=create_test_flow(), 63 signing_key=self.other_cert, 64 ) 65 self.cert = create_test_cert() 66 67 jwk = JWKSView().get_jwk_for_key(self.other_cert, "sig") 68 self.source: OAuthSource = OAuthSource.objects.create( 69 name=generate_id(), 70 slug=generate_id(), 71 provider_type="openidconnect", 72 consumer_key=generate_id(), 73 consumer_secret=generate_id(), 74 authorization_url="http://foo", 75 access_token_url=f"http://{generate_id()}", 76 profile_url="http://foo", 77 oidc_well_known_url="", 78 oidc_jwks_url="", 79 oidc_jwks={ 80 "keys": [jwk], 81 }, 82 ) 83 84 self.provider: OAuth2Provider = OAuth2Provider.objects.create( 85 name="test", 86 authorization_flow=create_test_flow(), 87 redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://testserver")], 88 signing_key=self.cert, 89 grant_types=[GrantType.CLIENT_CREDENTIALS], 90 ) 91 self.provider.jwt_federation_sources.add(self.source) 92 self.provider.property_mappings.set(ScopeMapping.objects.all()) 93 self.app = Application.objects.create(name="test", slug="test", provider=self.provider)
Hook method for setting up the test fixture before exercising it.
def
test_invalid_type(self):
95 def test_invalid_type(self): 96 """test invalid type""" 97 response = self.client.post( 98 reverse("authentik_providers_oauth2:token"), 99 { 100 "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS, 101 "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}", 102 "client_id": self.provider.client_id, 103 "client_assertion_type": "foo", 104 "client_assertion": "foo.bar", 105 }, 106 ) 107 self.assertEqual(response.status_code, 400) 108 body = loads(response.content.decode()) 109 self.assertEqual(body["error"], "invalid_grant")
test invalid type
def
test_invalid_jwt(self):
111 def test_invalid_jwt(self): 112 """test invalid JWT""" 113 response = self.client.post( 114 reverse("authentik_providers_oauth2:token"), 115 { 116 "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS, 117 "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}", 118 "client_id": self.provider.client_id, 119 "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", 120 "client_assertion": "foo.bar", 121 }, 122 ) 123 self.assertEqual(response.status_code, 400) 124 body = loads(response.content.decode()) 125 self.assertEqual(body["error"], "invalid_grant")
test invalid JWT
def
test_invalid_signature(self):
127 def test_invalid_signature(self): 128 """test invalid JWT""" 129 token = self.helper_provider.encode( 130 { 131 "sub": "foo", 132 "exp": datetime.now() + timedelta(hours=2), 133 } 134 ) 135 response = self.client.post( 136 reverse("authentik_providers_oauth2:token"), 137 { 138 "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS, 139 "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}", 140 "client_id": self.provider.client_id, 141 "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", 142 "client_assertion": token + "foo", 143 }, 144 ) 145 self.assertEqual(response.status_code, 400) 146 body = loads(response.content.decode()) 147 self.assertEqual(body["error"], "invalid_grant")
test invalid JWT
def
test_invalid_expired(self):
149 def test_invalid_expired(self): 150 """test invalid JWT""" 151 token = self.helper_provider.encode( 152 { 153 "sub": "foo", 154 "exp": datetime.now() - timedelta(hours=2), 155 } 156 ) 157 response = self.client.post( 158 reverse("authentik_providers_oauth2:token"), 159 { 160 "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS, 161 "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}", 162 "client_id": self.provider.client_id, 163 "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", 164 "client_assertion": token, 165 }, 166 ) 167 self.assertEqual(response.status_code, 400) 168 body = loads(response.content.decode()) 169 self.assertEqual(body["error"], "invalid_grant")
test invalid JWT
def
test_invalid_no_app(self):
171 def test_invalid_no_app(self): 172 """test invalid JWT""" 173 self.app.provider = None 174 self.app.save() 175 token = self.helper_provider.encode( 176 { 177 "sub": "foo", 178 "exp": datetime.now() + timedelta(hours=2), 179 } 180 ) 181 response = self.client.post( 182 reverse("authentik_providers_oauth2:token"), 183 { 184 "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS, 185 "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}", 186 "client_id": self.provider.client_id, 187 "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", 188 "client_assertion": token, 189 }, 190 ) 191 self.assertEqual(response.status_code, 400) 192 body = loads(response.content.decode()) 193 self.assertEqual(body["error"], "invalid_grant")
test invalid JWT
def
test_invalid_access_denied(self):
195 def test_invalid_access_denied(self): 196 """test invalid JWT""" 197 group = Group.objects.create(name="foo") 198 PolicyBinding.objects.create( 199 group=group, 200 target=self.app, 201 order=0, 202 ) 203 token = self.helper_provider.encode( 204 { 205 "sub": "foo", 206 "exp": datetime.now() + timedelta(hours=2), 207 } 208 ) 209 response = self.client.post( 210 reverse("authentik_providers_oauth2:token"), 211 { 212 "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS, 213 "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}", 214 "client_id": self.provider.client_id, 215 "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", 216 "client_assertion": token, 217 }, 218 ) 219 self.assertEqual(response.status_code, 400) 220 body = loads(response.content.decode()) 221 self.assertEqual(body["error"], "invalid_grant")
test invalid JWT
def
test_successful(self):
223 def test_successful(self): 224 """test successful""" 225 token = self.helper_provider.encode( 226 { 227 "sub": "foo", 228 "exp": datetime.now() + timedelta(hours=2), 229 } 230 ) 231 response = self.client.post( 232 reverse("authentik_providers_oauth2:token"), 233 { 234 "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS, 235 "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}", 236 "client_id": self.provider.client_id, 237 "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", 238 "client_assertion": token, 239 }, 240 ) 241 self.assertEqual(response.status_code, 200) 242 243 user = User.objects.filter(username=f"{self.provider.name}-foo").first() 244 self.assertIsNotNone(user) 245 246 body = loads(response.content.decode()) 247 self.assertEqual(body["token_type"], TOKEN_TYPE) 248 _, alg = self.provider.jwt_key 249 jwt = decode( 250 body["access_token"], 251 key=self.provider.signing_key.public_key, 252 algorithms=[alg], 253 audience=self.provider.client_id, 254 ) 255 self.assertEqual( 256 jwt["given_name"], "Autogenerated user from application test (client credentials JWT)" 257 ) 258 self.assertEqual(jwt["preferred_username"], "test-foo")
test successful
def
test_successful_attributes_verifying_source(self):
260 def test_successful_attributes_verifying_source(self): 261 """A second federation source advertising the same kid must not be credited with 262 the verification. The resolved source selects the user path and property mappings, 263 so crediting the wrong one creates the user under the wrong source.""" 264 real_jwk = JWKSView().get_jwk_for_key(self.other_cert, "sig") 265 # Same kid, different key material: this source is found by the kid lookup but 266 # can never verify the assertion. 267 decoy_jwk = JWKSView().get_jwk_for_key(create_test_cert(), "sig") 268 decoy_jwk["kid"] = real_jwk["kid"] 269 decoy_source = OAuthSource.objects.create( 270 name=generate_id(), 271 slug=generate_id(), 272 provider_type="openidconnect", 273 consumer_key=generate_id(), 274 consumer_secret=generate_id(), 275 authorization_url="http://foo", 276 access_token_url=f"http://{generate_id()}", 277 profile_url="http://foo", 278 oidc_well_known_url="", 279 oidc_jwks_url="", 280 oidc_jwks={"keys": [decoy_jwk]}, 281 ) 282 self.provider.jwt_federation_sources.add(decoy_source) 283 284 token = self.helper_provider.encode( 285 { 286 "sub": "foo", 287 "exp": datetime.now() + timedelta(hours=2), 288 } 289 ) 290 response = self.client.post( 291 reverse("authentik_providers_oauth2:token"), 292 { 293 "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS, 294 "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}", 295 "client_id": self.provider.client_id, 296 "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", 297 "client_assertion": token, 298 }, 299 ) 300 self.assertEqual(response.status_code, 200) 301 302 user = User.objects.filter(username=f"{self.provider.name}-foo").first() 303 self.assertIsNotNone(user) 304 self.assertEqual(user.path, self.source.get_user_path()) 305 self.assertNotEqual(user.path, decoy_source.get_user_path())
A second federation source advertising the same kid must not be credited with the verification. The resolved source selects the user path and property mappings, so crediting the wrong one creates the user under the wrong source.
def
test_successful_mapping(self):
307 def test_successful_mapping(self): 308 """test successful""" 309 test_username = ("mapped-foo" + ("a" * 150))[:USERNAME_MAX_LENGTH] 310 mapping = OAuthSourcePropertyMapping.objects.create( 311 name="test-mapping", 312 expression="""return { 313 "email": oauth_userinfo.get("email"), 314 "name": oauth_userinfo.get("name"), 315 "username": oauth_userinfo.get("username"), 316 }""", 317 ) 318 self.source.user_property_mappings.add(mapping) 319 320 token = self.helper_provider.encode( 321 { 322 "sub": "foo", 323 "email": "test-user@example.com", 324 "name": "Mapped Test User", 325 "username": "mapped-foo" + ("a" * 150), 326 "exp": datetime.now() + timedelta(hours=2), 327 } 328 ) 329 response = self.client.post( 330 reverse("authentik_providers_oauth2:token"), 331 { 332 "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS, 333 "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}", 334 "client_id": self.provider.client_id, 335 "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", 336 "client_assertion": token, 337 }, 338 ) 339 self.assertEqual(response.status_code, 200) 340 341 user = User.objects.filter(username=test_username).first() 342 self.assertIsNotNone(user) 343 344 body = loads(response.content.decode()) 345 self.assertEqual(body["token_type"], TOKEN_TYPE) 346 key_obj, alg = self.provider.jwt_key 347 jwt = decode( 348 body["access_token"], 349 key=key_obj.public_key(), 350 algorithms=[alg], 351 audience=self.provider.client_id, 352 ) 353 354 self.assertEqual(jwt["email"], "test-user@example.com") 355 self.assertEqual(jwt["given_name"], "Mapped Test User") 356 self.assertEqual(jwt["preferred_username"], test_username)
test successful
@skipIf(backend._fips_enabled, 'The FIPS provider has no ML-DSA')
def
test_successful_mldsa_source(self):
358 @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA") 359 def test_successful_mldsa_source(self): 360 """test successful with a client assertion signed by an ML-DSA key (RFC 9964 AKP JWK)""" 361 mldsa_cert = create_test_cert(PrivateKeyAlg.MLDSA44) 362 jwk = mldsa_jwk(mldsa_cert) 363 self.assertEqual(jwk["kty"], "AKP") 364 self.assertEqual(jwk["alg"], "ML-DSA-44") 365 self.source.oidc_jwks = {"keys": [jwk]} 366 self.source.save() 367 token = encode( 368 { 369 "sub": "foo", 370 "exp": datetime.now() + timedelta(hours=2), 371 }, 372 key=mldsa_cert.private_key, 373 algorithm="ML-DSA-44", 374 headers={"kid": mldsa_cert.kid}, 375 ) 376 response = self.client.post( 377 reverse("authentik_providers_oauth2:token"), 378 { 379 "grant_type": GRANT_TYPE_CLIENT_CREDENTIALS, 380 "scope": f"{SCOPE_OPENID} {SCOPE_OPENID_EMAIL} {SCOPE_OPENID_PROFILE}", 381 "client_id": self.provider.client_id, 382 "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", 383 "client_assertion": token, 384 }, 385 ) 386 self.assertEqual(response.status_code, 200) 387 self.assertIsNotNone(User.objects.filter(username=f"{self.provider.name}-foo").first())
test successful with a client assertion signed by an ML-DSA key (RFC 9964 AKP JWK)