authentik.providers.oauth2.tests.test_dcr
Tests for OAuth2 Dynamic Client Registration (RFC 7591)
1"""Tests for OAuth2 Dynamic Client Registration (RFC 7591)""" 2 3import json 4from datetime import timedelta 5 6from django.test import TestCase 7from django.urls import reverse 8from django.utils import timezone 9 10from authentik.blueprints.tests import apply_blueprint 11from authentik.common.oauth.constants import SCOPE_AUTHENTIK_DCR 12from authentik.core.models import Application 13from authentik.core.tests.utils import create_test_flow, create_test_user 14from authentik.lib.generators import generate_id 15from authentik.policies.dummy.models import DummyPolicy 16from authentik.policies.models import PolicyBinding 17from authentik.providers.oauth2.models import ( 18 AccessToken, 19 ClientType, 20 GrantType, 21 OAuth2DynamicClientRegistration, 22 OAuth2Provider, 23 RedirectURI, 24 RedirectURIMatchingMode, 25 ScopeMapping, 26) 27 28 29class TestDynamicClientRegistration(TestCase): 30 """RFC 7591 Dynamic Client Registration tests""" 31 32 @apply_blueprint("system/providers-oauth2.yaml") 33 def setUp(self): 34 self.flow = create_test_flow() 35 self.provider = OAuth2Provider.objects.create( 36 name=generate_id(), 37 authorization_flow=self.flow, 38 redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://testserver")], 39 ) 40 self.app = Application.objects.create( 41 name=generate_id(), 42 slug=generate_id(), 43 provider=self.provider, 44 ) 45 self.dcr = OAuth2DynamicClientRegistration.objects.create( 46 provider=self.provider, 47 override_authorization_flow=self.flow, 48 ) 49 self.register_url = reverse( 50 "authentik_providers_oauth2:dynamic-client-registration", 51 kwargs={"application_slug": self.app.slug}, 52 ) 53 54 def _access_token(self, scope: str = SCOPE_AUTHENTIK_DCR, **kwargs) -> AccessToken: 55 return AccessToken.objects.create( 56 user=kwargs.pop("user", None) or create_test_user(), 57 provider=kwargs.pop("provider", None) or self.provider, 58 token=generate_id(), 59 auth_time=timezone.now(), 60 _scope=scope, 61 _id_token=json.dumps({}), 62 **kwargs, 63 ) 64 65 def _post(self, body: dict, token: str | None = None) -> object: 66 headers = {"content_type": "application/json"} 67 if token: 68 headers["HTTP_AUTHORIZATION"] = f"Bearer {token}" 69 return self.client.post(self.register_url, json.dumps(body), **headers) 70 71 def test_registration_success(self): 72 """Basic registration creates a new OAuth2Provider and Application.""" 73 token = self._access_token() 74 response = self._post( 75 {"redirect_uris": ["https://example.com/callback"], "client_name": "Test Client"}, 76 token=token.token, 77 ) 78 self.assertEqual(response.status_code, 201) 79 body = json.loads(response.content) 80 self.assertIn("client_id", body) 81 self.assertIn("client_secret", body) 82 self.assertEqual(body["redirect_uris"], ["https://example.com/callback"]) 83 self.assertEqual(body["client_name"], "Test Client") 84 # Provider created 85 self.assertTrue(OAuth2Provider.objects.filter(client_id=body["client_id"]).exists()) 86 # Application created 87 provider = OAuth2Provider.objects.get(client_id=body["client_id"]) 88 self.assertIsNotNone(provider.application) 89 90 def test_requires_redirect_uris(self): 91 """redirect_uris is required.""" 92 token = self._access_token() 93 response = self._post({"client_name": "No URIs"}, token=token.token) 94 self.assertEqual(response.status_code, 400) 95 body = json.loads(response.content) 96 self.assertEqual(body["error"], "invalid_redirect_uri") 97 98 def test_invalid_json(self): 99 """Non-JSON body is rejected.""" 100 token = self._access_token() 101 response = self.client.post( 102 self.register_url, 103 "not-json", 104 content_type="application/json", 105 HTTP_AUTHORIZATION=f"Bearer {token.token}", 106 ) 107 self.assertEqual(response.status_code, 400) 108 body = json.loads(response.content) 109 self.assertEqual(body["error"], "invalid_client_metadata") 110 111 def test_requires_access_token(self): 112 """Requests without a bearer token are rejected.""" 113 response = self._post({"redirect_uris": ["https://example.com/cb"]}) 114 self.assertEqual(response.status_code, 401) 115 body = json.loads(response.content) 116 self.assertEqual(body["error"], "invalid_token") 117 118 def test_access_token_missing_scope_rejected(self): 119 """An access token without the DCR scope is rejected.""" 120 token = self._access_token(scope="") 121 response = self._post( 122 {"redirect_uris": ["https://example.com/cb"]}, 123 token=token.token, 124 ) 125 self.assertEqual(response.status_code, 401) 126 body = json.loads(response.content) 127 self.assertEqual(body["error"], "invalid_token") 128 129 def test_valid_access_token(self): 130 """A valid access token with the DCR scope grants registration.""" 131 token = self._access_token() 132 response = self._post( 133 {"redirect_uris": ["https://example.com/cb"]}, 134 token=token.token, 135 ) 136 self.assertEqual(response.status_code, 201) 137 138 def test_expired_access_token_rejected(self): 139 """An expired access token cannot be used to register clients.""" 140 token = self._access_token(expires=timezone.now() - timedelta(hours=1)) 141 response = self._post( 142 {"redirect_uris": ["https://example.com/cb"]}, 143 token=token.token, 144 ) 145 self.assertEqual(response.status_code, 401) 146 147 def test_grant_type_restriction(self): 148 """Grant types not in allowed_grant_types are filtered out.""" 149 self.dcr.allowed_grant_types = [GrantType.AUTHORIZATION_CODE] 150 self.dcr.save() 151 token = self._access_token() 152 response = self._post( 153 { 154 "redirect_uris": ["https://example.com/cb"], 155 "grant_types": [GrantType.AUTHORIZATION_CODE, GrantType.CLIENT_CREDENTIALS], 156 }, 157 token=token.token, 158 ) 159 self.assertEqual(response.status_code, 201) 160 body = json.loads(response.content) 161 self.assertNotIn(GrantType.CLIENT_CREDENTIALS, body["grant_types"]) 162 self.assertIn(GrantType.AUTHORIZATION_CODE, body["grant_types"]) 163 164 def test_public_client_no_secret(self): 165 """Public client (auth_method=none) does not receive a client_secret.""" 166 token = self._access_token() 167 response = self._post( 168 { 169 "redirect_uris": ["https://example.com/cb"], 170 "token_endpoint_auth_method": "none", 171 }, 172 token=token.token, 173 ) 174 self.assertEqual(response.status_code, 201) 175 body = json.loads(response.content) 176 self.assertNotIn("client_secret", body) 177 provider = OAuth2Provider.objects.get(client_id=body["client_id"]) 178 self.assertEqual(provider.client_type, ClientType.PUBLIC) 179 180 def test_policy_access_denied(self): 181 """A failing policy binding on the application rejects registration with 403.""" 182 policy = DummyPolicy.objects.create(name=generate_id(), result=False) 183 PolicyBinding.objects.create(target=self.app, policy=policy, order=0) 184 token = self._access_token() 185 response = self._post( 186 {"redirect_uris": ["https://example.com/cb"]}, 187 token=token.token, 188 ) 189 self.assertEqual(response.status_code, 403) 190 body = json.loads(response.content) 191 self.assertEqual(body["error"], "access_denied") 192 193 def test_override_authorization_flow_applied(self): 194 """override_authorization_flow is applied to the registered provider.""" 195 override_flow = create_test_flow() 196 self.dcr.override_authorization_flow = override_flow 197 self.dcr.save() 198 token = self._access_token() 199 response = self._post( 200 {"redirect_uris": ["https://example.com/cb"]}, 201 token=token.token, 202 ) 203 self.assertEqual(response.status_code, 201) 204 body = json.loads(response.content) 205 provider = OAuth2Provider.objects.get(client_id=body["client_id"]) 206 self.assertEqual(provider.authorization_flow, override_flow) 207 208 def test_default_application_group_applied(self): 209 """default_application_group is applied to the created application.""" 210 group = generate_id() 211 self.dcr.default_application_group = group 212 self.dcr.save() 213 token = self._access_token() 214 response = self._post( 215 {"redirect_uris": ["https://example.com/cb"]}, 216 token=token.token, 217 ) 218 self.assertEqual(response.status_code, 201) 219 body = json.loads(response.content) 220 provider = OAuth2Provider.objects.get(client_id=body["client_id"]) 221 self.assertEqual(provider.application.group, group) 222 223 def test_all_grant_types_allowed_when_unrestricted(self): 224 """With an empty allowed_grant_types, all requested grant types are kept.""" 225 token = self._access_token() 226 response = self._post( 227 { 228 "redirect_uris": ["https://example.com/cb"], 229 "grant_types": [GrantType.AUTHORIZATION_CODE, GrantType.CLIENT_CREDENTIALS], 230 }, 231 token=token.token, 232 ) 233 self.assertEqual(response.status_code, 201) 234 body = json.loads(response.content) 235 self.assertIn(GrantType.AUTHORIZATION_CODE, body["grant_types"]) 236 self.assertIn(GrantType.CLIENT_CREDENTIALS, body["grant_types"]) 237 238 def test_override_property_mappings_applied(self): 239 """override_property_mappings are applied to the registered provider.""" 240 mapping = ScopeMapping.objects.create( 241 name=generate_id(), scope_name=generate_id(), expression="return {}" 242 ) 243 self.dcr.override_property_mappings.set([mapping]) 244 token = self._access_token() 245 response = self._post( 246 {"redirect_uris": ["https://example.com/cb"]}, 247 token=token.token, 248 ) 249 self.assertEqual(response.status_code, 201) 250 body = json.loads(response.content) 251 provider = OAuth2Provider.objects.get(client_id=body["client_id"]) 252 self.assertTrue(provider.property_mappings.filter(pk=mapping.pk).exists()) 253 254 def test_policy_bindings_copied_from_dcr(self): 255 """Policy bindings on the DCR config are copied onto the new application.""" 256 policy = DummyPolicy.objects.create(name=generate_id(), result=True) 257 source_binding = PolicyBinding.objects.create(target=self.dcr, policy=policy, order=0) 258 token = self._access_token() 259 response = self._post( 260 {"redirect_uris": ["https://example.com/cb"]}, 261 token=token.token, 262 ) 263 self.assertEqual(response.status_code, 201) 264 body = json.loads(response.content) 265 provider = OAuth2Provider.objects.get(client_id=body["client_id"]) 266 copied = PolicyBinding.objects.filter(target=provider.application, policy=policy) 267 self.assertEqual(copied.count(), 1) 268 # The copy has its own primary key, not the source binding's. 269 self.assertNotEqual(copied.first().pk, source_binding.pk) 270 271 def test_policy_bindings_copied_from_application(self): 272 """When the DCR config has no bindings, the base application's bindings are copied.""" 273 policy = DummyPolicy.objects.create(name=generate_id(), result=True) 274 PolicyBinding.objects.create(target=self.app, policy=policy, order=0) 275 token = self._access_token() 276 response = self._post( 277 {"redirect_uris": ["https://example.com/cb"]}, 278 token=token.token, 279 ) 280 self.assertEqual(response.status_code, 201) 281 body = json.loads(response.content) 282 provider = OAuth2Provider.objects.get(client_id=body["client_id"]) 283 self.assertTrue( 284 PolicyBinding.objects.filter(target=provider.application, policy=policy).exists() 285 ) 286 287 def test_registration_endpoint_in_openid_config(self): 288 """registration_endpoint is advertised in .well-known/openid-configuration.""" 289 response = self.client.get( 290 reverse( 291 "authentik_providers_oauth2:provider-info", 292 kwargs={"application_slug": self.app.slug}, 293 ) 294 ) 295 self.assertEqual(response.status_code, 200) 296 config = json.loads(response.content) 297 self.assertIn("registration_endpoint", config) 298 self.assertIn("/register/", config["registration_endpoint"]) 299 300 def test_no_registration_endpoint_when_dcr_disabled(self): 301 """registration_endpoint is absent when DCR is not configured.""" 302 # Create a separate provider/app without DCR 303 provider2 = OAuth2Provider.objects.create( 304 name=generate_id(), 305 authorization_flow=self.flow, 306 redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://testserver")], 307 ) 308 app2 = Application.objects.create( 309 name=generate_id(), 310 slug=generate_id(), 311 provider=provider2, 312 ) 313 response = self.client.get( 314 reverse( 315 "authentik_providers_oauth2:provider-info", 316 kwargs={"application_slug": app2.slug}, 317 ) 318 ) 319 self.assertEqual(response.status_code, 200) 320 config = json.loads(response.content) 321 self.assertNotIn("registration_endpoint", config) 322 323 def test_register_endpoint_404_without_dcr(self): 324 """Registration endpoint returns 404 when DCR is not configured on that provider.""" 325 provider2 = OAuth2Provider.objects.create( 326 name=generate_id(), 327 authorization_flow=self.flow, 328 redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://testserver")], 329 ) 330 app2_slug = generate_id().lower() 331 app2 = Application.objects.create( 332 name=generate_id(), 333 slug=app2_slug, 334 provider=provider2, 335 ) 336 response = self.client.post( 337 reverse( 338 "authentik_providers_oauth2:dynamic-client-registration", 339 kwargs={"application_slug": app2.slug}, 340 ), 341 json.dumps({"redirect_uris": ["https://x.com/cb"]}), 342 content_type="application/json", 343 ) 344 self.assertEqual(response.status_code, 404)
30class TestDynamicClientRegistration(TestCase): 31 """RFC 7591 Dynamic Client Registration tests""" 32 33 @apply_blueprint("system/providers-oauth2.yaml") 34 def setUp(self): 35 self.flow = create_test_flow() 36 self.provider = OAuth2Provider.objects.create( 37 name=generate_id(), 38 authorization_flow=self.flow, 39 redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://testserver")], 40 ) 41 self.app = Application.objects.create( 42 name=generate_id(), 43 slug=generate_id(), 44 provider=self.provider, 45 ) 46 self.dcr = OAuth2DynamicClientRegistration.objects.create( 47 provider=self.provider, 48 override_authorization_flow=self.flow, 49 ) 50 self.register_url = reverse( 51 "authentik_providers_oauth2:dynamic-client-registration", 52 kwargs={"application_slug": self.app.slug}, 53 ) 54 55 def _access_token(self, scope: str = SCOPE_AUTHENTIK_DCR, **kwargs) -> AccessToken: 56 return AccessToken.objects.create( 57 user=kwargs.pop("user", None) or create_test_user(), 58 provider=kwargs.pop("provider", None) or self.provider, 59 token=generate_id(), 60 auth_time=timezone.now(), 61 _scope=scope, 62 _id_token=json.dumps({}), 63 **kwargs, 64 ) 65 66 def _post(self, body: dict, token: str | None = None) -> object: 67 headers = {"content_type": "application/json"} 68 if token: 69 headers["HTTP_AUTHORIZATION"] = f"Bearer {token}" 70 return self.client.post(self.register_url, json.dumps(body), **headers) 71 72 def test_registration_success(self): 73 """Basic registration creates a new OAuth2Provider and Application.""" 74 token = self._access_token() 75 response = self._post( 76 {"redirect_uris": ["https://example.com/callback"], "client_name": "Test Client"}, 77 token=token.token, 78 ) 79 self.assertEqual(response.status_code, 201) 80 body = json.loads(response.content) 81 self.assertIn("client_id", body) 82 self.assertIn("client_secret", body) 83 self.assertEqual(body["redirect_uris"], ["https://example.com/callback"]) 84 self.assertEqual(body["client_name"], "Test Client") 85 # Provider created 86 self.assertTrue(OAuth2Provider.objects.filter(client_id=body["client_id"]).exists()) 87 # Application created 88 provider = OAuth2Provider.objects.get(client_id=body["client_id"]) 89 self.assertIsNotNone(provider.application) 90 91 def test_requires_redirect_uris(self): 92 """redirect_uris is required.""" 93 token = self._access_token() 94 response = self._post({"client_name": "No URIs"}, token=token.token) 95 self.assertEqual(response.status_code, 400) 96 body = json.loads(response.content) 97 self.assertEqual(body["error"], "invalid_redirect_uri") 98 99 def test_invalid_json(self): 100 """Non-JSON body is rejected.""" 101 token = self._access_token() 102 response = self.client.post( 103 self.register_url, 104 "not-json", 105 content_type="application/json", 106 HTTP_AUTHORIZATION=f"Bearer {token.token}", 107 ) 108 self.assertEqual(response.status_code, 400) 109 body = json.loads(response.content) 110 self.assertEqual(body["error"], "invalid_client_metadata") 111 112 def test_requires_access_token(self): 113 """Requests without a bearer token are rejected.""" 114 response = self._post({"redirect_uris": ["https://example.com/cb"]}) 115 self.assertEqual(response.status_code, 401) 116 body = json.loads(response.content) 117 self.assertEqual(body["error"], "invalid_token") 118 119 def test_access_token_missing_scope_rejected(self): 120 """An access token without the DCR scope is rejected.""" 121 token = self._access_token(scope="") 122 response = self._post( 123 {"redirect_uris": ["https://example.com/cb"]}, 124 token=token.token, 125 ) 126 self.assertEqual(response.status_code, 401) 127 body = json.loads(response.content) 128 self.assertEqual(body["error"], "invalid_token") 129 130 def test_valid_access_token(self): 131 """A valid access token with the DCR scope grants registration.""" 132 token = self._access_token() 133 response = self._post( 134 {"redirect_uris": ["https://example.com/cb"]}, 135 token=token.token, 136 ) 137 self.assertEqual(response.status_code, 201) 138 139 def test_expired_access_token_rejected(self): 140 """An expired access token cannot be used to register clients.""" 141 token = self._access_token(expires=timezone.now() - timedelta(hours=1)) 142 response = self._post( 143 {"redirect_uris": ["https://example.com/cb"]}, 144 token=token.token, 145 ) 146 self.assertEqual(response.status_code, 401) 147 148 def test_grant_type_restriction(self): 149 """Grant types not in allowed_grant_types are filtered out.""" 150 self.dcr.allowed_grant_types = [GrantType.AUTHORIZATION_CODE] 151 self.dcr.save() 152 token = self._access_token() 153 response = self._post( 154 { 155 "redirect_uris": ["https://example.com/cb"], 156 "grant_types": [GrantType.AUTHORIZATION_CODE, GrantType.CLIENT_CREDENTIALS], 157 }, 158 token=token.token, 159 ) 160 self.assertEqual(response.status_code, 201) 161 body = json.loads(response.content) 162 self.assertNotIn(GrantType.CLIENT_CREDENTIALS, body["grant_types"]) 163 self.assertIn(GrantType.AUTHORIZATION_CODE, body["grant_types"]) 164 165 def test_public_client_no_secret(self): 166 """Public client (auth_method=none) does not receive a client_secret.""" 167 token = self._access_token() 168 response = self._post( 169 { 170 "redirect_uris": ["https://example.com/cb"], 171 "token_endpoint_auth_method": "none", 172 }, 173 token=token.token, 174 ) 175 self.assertEqual(response.status_code, 201) 176 body = json.loads(response.content) 177 self.assertNotIn("client_secret", body) 178 provider = OAuth2Provider.objects.get(client_id=body["client_id"]) 179 self.assertEqual(provider.client_type, ClientType.PUBLIC) 180 181 def test_policy_access_denied(self): 182 """A failing policy binding on the application rejects registration with 403.""" 183 policy = DummyPolicy.objects.create(name=generate_id(), result=False) 184 PolicyBinding.objects.create(target=self.app, policy=policy, order=0) 185 token = self._access_token() 186 response = self._post( 187 {"redirect_uris": ["https://example.com/cb"]}, 188 token=token.token, 189 ) 190 self.assertEqual(response.status_code, 403) 191 body = json.loads(response.content) 192 self.assertEqual(body["error"], "access_denied") 193 194 def test_override_authorization_flow_applied(self): 195 """override_authorization_flow is applied to the registered provider.""" 196 override_flow = create_test_flow() 197 self.dcr.override_authorization_flow = override_flow 198 self.dcr.save() 199 token = self._access_token() 200 response = self._post( 201 {"redirect_uris": ["https://example.com/cb"]}, 202 token=token.token, 203 ) 204 self.assertEqual(response.status_code, 201) 205 body = json.loads(response.content) 206 provider = OAuth2Provider.objects.get(client_id=body["client_id"]) 207 self.assertEqual(provider.authorization_flow, override_flow) 208 209 def test_default_application_group_applied(self): 210 """default_application_group is applied to the created application.""" 211 group = generate_id() 212 self.dcr.default_application_group = group 213 self.dcr.save() 214 token = self._access_token() 215 response = self._post( 216 {"redirect_uris": ["https://example.com/cb"]}, 217 token=token.token, 218 ) 219 self.assertEqual(response.status_code, 201) 220 body = json.loads(response.content) 221 provider = OAuth2Provider.objects.get(client_id=body["client_id"]) 222 self.assertEqual(provider.application.group, group) 223 224 def test_all_grant_types_allowed_when_unrestricted(self): 225 """With an empty allowed_grant_types, all requested grant types are kept.""" 226 token = self._access_token() 227 response = self._post( 228 { 229 "redirect_uris": ["https://example.com/cb"], 230 "grant_types": [GrantType.AUTHORIZATION_CODE, GrantType.CLIENT_CREDENTIALS], 231 }, 232 token=token.token, 233 ) 234 self.assertEqual(response.status_code, 201) 235 body = json.loads(response.content) 236 self.assertIn(GrantType.AUTHORIZATION_CODE, body["grant_types"]) 237 self.assertIn(GrantType.CLIENT_CREDENTIALS, body["grant_types"]) 238 239 def test_override_property_mappings_applied(self): 240 """override_property_mappings are applied to the registered provider.""" 241 mapping = ScopeMapping.objects.create( 242 name=generate_id(), scope_name=generate_id(), expression="return {}" 243 ) 244 self.dcr.override_property_mappings.set([mapping]) 245 token = self._access_token() 246 response = self._post( 247 {"redirect_uris": ["https://example.com/cb"]}, 248 token=token.token, 249 ) 250 self.assertEqual(response.status_code, 201) 251 body = json.loads(response.content) 252 provider = OAuth2Provider.objects.get(client_id=body["client_id"]) 253 self.assertTrue(provider.property_mappings.filter(pk=mapping.pk).exists()) 254 255 def test_policy_bindings_copied_from_dcr(self): 256 """Policy bindings on the DCR config are copied onto the new application.""" 257 policy = DummyPolicy.objects.create(name=generate_id(), result=True) 258 source_binding = PolicyBinding.objects.create(target=self.dcr, policy=policy, order=0) 259 token = self._access_token() 260 response = self._post( 261 {"redirect_uris": ["https://example.com/cb"]}, 262 token=token.token, 263 ) 264 self.assertEqual(response.status_code, 201) 265 body = json.loads(response.content) 266 provider = OAuth2Provider.objects.get(client_id=body["client_id"]) 267 copied = PolicyBinding.objects.filter(target=provider.application, policy=policy) 268 self.assertEqual(copied.count(), 1) 269 # The copy has its own primary key, not the source binding's. 270 self.assertNotEqual(copied.first().pk, source_binding.pk) 271 272 def test_policy_bindings_copied_from_application(self): 273 """When the DCR config has no bindings, the base application's bindings are copied.""" 274 policy = DummyPolicy.objects.create(name=generate_id(), result=True) 275 PolicyBinding.objects.create(target=self.app, policy=policy, order=0) 276 token = self._access_token() 277 response = self._post( 278 {"redirect_uris": ["https://example.com/cb"]}, 279 token=token.token, 280 ) 281 self.assertEqual(response.status_code, 201) 282 body = json.loads(response.content) 283 provider = OAuth2Provider.objects.get(client_id=body["client_id"]) 284 self.assertTrue( 285 PolicyBinding.objects.filter(target=provider.application, policy=policy).exists() 286 ) 287 288 def test_registration_endpoint_in_openid_config(self): 289 """registration_endpoint is advertised in .well-known/openid-configuration.""" 290 response = self.client.get( 291 reverse( 292 "authentik_providers_oauth2:provider-info", 293 kwargs={"application_slug": self.app.slug}, 294 ) 295 ) 296 self.assertEqual(response.status_code, 200) 297 config = json.loads(response.content) 298 self.assertIn("registration_endpoint", config) 299 self.assertIn("/register/", config["registration_endpoint"]) 300 301 def test_no_registration_endpoint_when_dcr_disabled(self): 302 """registration_endpoint is absent when DCR is not configured.""" 303 # Create a separate provider/app without DCR 304 provider2 = OAuth2Provider.objects.create( 305 name=generate_id(), 306 authorization_flow=self.flow, 307 redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://testserver")], 308 ) 309 app2 = Application.objects.create( 310 name=generate_id(), 311 slug=generate_id(), 312 provider=provider2, 313 ) 314 response = self.client.get( 315 reverse( 316 "authentik_providers_oauth2:provider-info", 317 kwargs={"application_slug": app2.slug}, 318 ) 319 ) 320 self.assertEqual(response.status_code, 200) 321 config = json.loads(response.content) 322 self.assertNotIn("registration_endpoint", config) 323 324 def test_register_endpoint_404_without_dcr(self): 325 """Registration endpoint returns 404 when DCR is not configured on that provider.""" 326 provider2 = OAuth2Provider.objects.create( 327 name=generate_id(), 328 authorization_flow=self.flow, 329 redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://testserver")], 330 ) 331 app2_slug = generate_id().lower() 332 app2 = Application.objects.create( 333 name=generate_id(), 334 slug=app2_slug, 335 provider=provider2, 336 ) 337 response = self.client.post( 338 reverse( 339 "authentik_providers_oauth2:dynamic-client-registration", 340 kwargs={"application_slug": app2.slug}, 341 ), 342 json.dumps({"redirect_uris": ["https://x.com/cb"]}), 343 content_type="application/json", 344 ) 345 self.assertEqual(response.status_code, 404)
RFC 7591 Dynamic Client Registration tests
33 @apply_blueprint("system/providers-oauth2.yaml") 34 def setUp(self): 35 self.flow = create_test_flow() 36 self.provider = OAuth2Provider.objects.create( 37 name=generate_id(), 38 authorization_flow=self.flow, 39 redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://testserver")], 40 ) 41 self.app = Application.objects.create( 42 name=generate_id(), 43 slug=generate_id(), 44 provider=self.provider, 45 ) 46 self.dcr = OAuth2DynamicClientRegistration.objects.create( 47 provider=self.provider, 48 override_authorization_flow=self.flow, 49 ) 50 self.register_url = reverse( 51 "authentik_providers_oauth2:dynamic-client-registration", 52 kwargs={"application_slug": self.app.slug}, 53 )
Hook method for setting up the test fixture before exercising it.
72 def test_registration_success(self): 73 """Basic registration creates a new OAuth2Provider and Application.""" 74 token = self._access_token() 75 response = self._post( 76 {"redirect_uris": ["https://example.com/callback"], "client_name": "Test Client"}, 77 token=token.token, 78 ) 79 self.assertEqual(response.status_code, 201) 80 body = json.loads(response.content) 81 self.assertIn("client_id", body) 82 self.assertIn("client_secret", body) 83 self.assertEqual(body["redirect_uris"], ["https://example.com/callback"]) 84 self.assertEqual(body["client_name"], "Test Client") 85 # Provider created 86 self.assertTrue(OAuth2Provider.objects.filter(client_id=body["client_id"]).exists()) 87 # Application created 88 provider = OAuth2Provider.objects.get(client_id=body["client_id"]) 89 self.assertIsNotNone(provider.application)
Basic registration creates a new OAuth2Provider and Application.
91 def test_requires_redirect_uris(self): 92 """redirect_uris is required.""" 93 token = self._access_token() 94 response = self._post({"client_name": "No URIs"}, token=token.token) 95 self.assertEqual(response.status_code, 400) 96 body = json.loads(response.content) 97 self.assertEqual(body["error"], "invalid_redirect_uri")
redirect_uris is required.
99 def test_invalid_json(self): 100 """Non-JSON body is rejected.""" 101 token = self._access_token() 102 response = self.client.post( 103 self.register_url, 104 "not-json", 105 content_type="application/json", 106 HTTP_AUTHORIZATION=f"Bearer {token.token}", 107 ) 108 self.assertEqual(response.status_code, 400) 109 body = json.loads(response.content) 110 self.assertEqual(body["error"], "invalid_client_metadata")
Non-JSON body is rejected.
112 def test_requires_access_token(self): 113 """Requests without a bearer token are rejected.""" 114 response = self._post({"redirect_uris": ["https://example.com/cb"]}) 115 self.assertEqual(response.status_code, 401) 116 body = json.loads(response.content) 117 self.assertEqual(body["error"], "invalid_token")
Requests without a bearer token are rejected.
119 def test_access_token_missing_scope_rejected(self): 120 """An access token without the DCR scope is rejected.""" 121 token = self._access_token(scope="") 122 response = self._post( 123 {"redirect_uris": ["https://example.com/cb"]}, 124 token=token.token, 125 ) 126 self.assertEqual(response.status_code, 401) 127 body = json.loads(response.content) 128 self.assertEqual(body["error"], "invalid_token")
An access token without the DCR scope is rejected.
130 def test_valid_access_token(self): 131 """A valid access token with the DCR scope grants registration.""" 132 token = self._access_token() 133 response = self._post( 134 {"redirect_uris": ["https://example.com/cb"]}, 135 token=token.token, 136 ) 137 self.assertEqual(response.status_code, 201)
A valid access token with the DCR scope grants registration.
139 def test_expired_access_token_rejected(self): 140 """An expired access token cannot be used to register clients.""" 141 token = self._access_token(expires=timezone.now() - timedelta(hours=1)) 142 response = self._post( 143 {"redirect_uris": ["https://example.com/cb"]}, 144 token=token.token, 145 ) 146 self.assertEqual(response.status_code, 401)
An expired access token cannot be used to register clients.
148 def test_grant_type_restriction(self): 149 """Grant types not in allowed_grant_types are filtered out.""" 150 self.dcr.allowed_grant_types = [GrantType.AUTHORIZATION_CODE] 151 self.dcr.save() 152 token = self._access_token() 153 response = self._post( 154 { 155 "redirect_uris": ["https://example.com/cb"], 156 "grant_types": [GrantType.AUTHORIZATION_CODE, GrantType.CLIENT_CREDENTIALS], 157 }, 158 token=token.token, 159 ) 160 self.assertEqual(response.status_code, 201) 161 body = json.loads(response.content) 162 self.assertNotIn(GrantType.CLIENT_CREDENTIALS, body["grant_types"]) 163 self.assertIn(GrantType.AUTHORIZATION_CODE, body["grant_types"])
Grant types not in allowed_grant_types are filtered out.
165 def test_public_client_no_secret(self): 166 """Public client (auth_method=none) does not receive a client_secret.""" 167 token = self._access_token() 168 response = self._post( 169 { 170 "redirect_uris": ["https://example.com/cb"], 171 "token_endpoint_auth_method": "none", 172 }, 173 token=token.token, 174 ) 175 self.assertEqual(response.status_code, 201) 176 body = json.loads(response.content) 177 self.assertNotIn("client_secret", body) 178 provider = OAuth2Provider.objects.get(client_id=body["client_id"]) 179 self.assertEqual(provider.client_type, ClientType.PUBLIC)
Public client (auth_method=none) does not receive a client_secret.
181 def test_policy_access_denied(self): 182 """A failing policy binding on the application rejects registration with 403.""" 183 policy = DummyPolicy.objects.create(name=generate_id(), result=False) 184 PolicyBinding.objects.create(target=self.app, policy=policy, order=0) 185 token = self._access_token() 186 response = self._post( 187 {"redirect_uris": ["https://example.com/cb"]}, 188 token=token.token, 189 ) 190 self.assertEqual(response.status_code, 403) 191 body = json.loads(response.content) 192 self.assertEqual(body["error"], "access_denied")
A failing policy binding on the application rejects registration with 403.
209 def test_default_application_group_applied(self): 210 """default_application_group is applied to the created application.""" 211 group = generate_id() 212 self.dcr.default_application_group = group 213 self.dcr.save() 214 token = self._access_token() 215 response = self._post( 216 {"redirect_uris": ["https://example.com/cb"]}, 217 token=token.token, 218 ) 219 self.assertEqual(response.status_code, 201) 220 body = json.loads(response.content) 221 provider = OAuth2Provider.objects.get(client_id=body["client_id"]) 222 self.assertEqual(provider.application.group, group)
default_application_group is applied to the created application.
224 def test_all_grant_types_allowed_when_unrestricted(self): 225 """With an empty allowed_grant_types, all requested grant types are kept.""" 226 token = self._access_token() 227 response = self._post( 228 { 229 "redirect_uris": ["https://example.com/cb"], 230 "grant_types": [GrantType.AUTHORIZATION_CODE, GrantType.CLIENT_CREDENTIALS], 231 }, 232 token=token.token, 233 ) 234 self.assertEqual(response.status_code, 201) 235 body = json.loads(response.content) 236 self.assertIn(GrantType.AUTHORIZATION_CODE, body["grant_types"]) 237 self.assertIn(GrantType.CLIENT_CREDENTIALS, body["grant_types"])
With an empty allowed_grant_types, all requested grant types are kept.
239 def test_override_property_mappings_applied(self): 240 """override_property_mappings are applied to the registered provider.""" 241 mapping = ScopeMapping.objects.create( 242 name=generate_id(), scope_name=generate_id(), expression="return {}" 243 ) 244 self.dcr.override_property_mappings.set([mapping]) 245 token = self._access_token() 246 response = self._post( 247 {"redirect_uris": ["https://example.com/cb"]}, 248 token=token.token, 249 ) 250 self.assertEqual(response.status_code, 201) 251 body = json.loads(response.content) 252 provider = OAuth2Provider.objects.get(client_id=body["client_id"]) 253 self.assertTrue(provider.property_mappings.filter(pk=mapping.pk).exists())
override_property_mappings are applied to the registered provider.
255 def test_policy_bindings_copied_from_dcr(self): 256 """Policy bindings on the DCR config are copied onto the new application.""" 257 policy = DummyPolicy.objects.create(name=generate_id(), result=True) 258 source_binding = PolicyBinding.objects.create(target=self.dcr, policy=policy, order=0) 259 token = self._access_token() 260 response = self._post( 261 {"redirect_uris": ["https://example.com/cb"]}, 262 token=token.token, 263 ) 264 self.assertEqual(response.status_code, 201) 265 body = json.loads(response.content) 266 provider = OAuth2Provider.objects.get(client_id=body["client_id"]) 267 copied = PolicyBinding.objects.filter(target=provider.application, policy=policy) 268 self.assertEqual(copied.count(), 1) 269 # The copy has its own primary key, not the source binding's. 270 self.assertNotEqual(copied.first().pk, source_binding.pk)
Policy bindings on the DCR config are copied onto the new application.
272 def test_policy_bindings_copied_from_application(self): 273 """When the DCR config has no bindings, the base application's bindings are copied.""" 274 policy = DummyPolicy.objects.create(name=generate_id(), result=True) 275 PolicyBinding.objects.create(target=self.app, policy=policy, order=0) 276 token = self._access_token() 277 response = self._post( 278 {"redirect_uris": ["https://example.com/cb"]}, 279 token=token.token, 280 ) 281 self.assertEqual(response.status_code, 201) 282 body = json.loads(response.content) 283 provider = OAuth2Provider.objects.get(client_id=body["client_id"]) 284 self.assertTrue( 285 PolicyBinding.objects.filter(target=provider.application, policy=policy).exists() 286 )
When the DCR config has no bindings, the base application's bindings are copied.
288 def test_registration_endpoint_in_openid_config(self): 289 """registration_endpoint is advertised in .well-known/openid-configuration.""" 290 response = self.client.get( 291 reverse( 292 "authentik_providers_oauth2:provider-info", 293 kwargs={"application_slug": self.app.slug}, 294 ) 295 ) 296 self.assertEqual(response.status_code, 200) 297 config = json.loads(response.content) 298 self.assertIn("registration_endpoint", config) 299 self.assertIn("/register/", config["registration_endpoint"])
registration_endpoint is advertised in .well-known/openid-configuration.
301 def test_no_registration_endpoint_when_dcr_disabled(self): 302 """registration_endpoint is absent when DCR is not configured.""" 303 # Create a separate provider/app without DCR 304 provider2 = OAuth2Provider.objects.create( 305 name=generate_id(), 306 authorization_flow=self.flow, 307 redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://testserver")], 308 ) 309 app2 = Application.objects.create( 310 name=generate_id(), 311 slug=generate_id(), 312 provider=provider2, 313 ) 314 response = self.client.get( 315 reverse( 316 "authentik_providers_oauth2:provider-info", 317 kwargs={"application_slug": app2.slug}, 318 ) 319 ) 320 self.assertEqual(response.status_code, 200) 321 config = json.loads(response.content) 322 self.assertNotIn("registration_endpoint", config)
registration_endpoint is absent when DCR is not configured.
324 def test_register_endpoint_404_without_dcr(self): 325 """Registration endpoint returns 404 when DCR is not configured on that provider.""" 326 provider2 = OAuth2Provider.objects.create( 327 name=generate_id(), 328 authorization_flow=self.flow, 329 redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://testserver")], 330 ) 331 app2_slug = generate_id().lower() 332 app2 = Application.objects.create( 333 name=generate_id(), 334 slug=app2_slug, 335 provider=provider2, 336 ) 337 response = self.client.post( 338 reverse( 339 "authentik_providers_oauth2:dynamic-client-registration", 340 kwargs={"application_slug": app2.slug}, 341 ), 342 json.dumps({"redirect_uris": ["https://x.com/cb"]}), 343 content_type="application/json", 344 ) 345 self.assertEqual(response.status_code, 404)
Registration endpoint returns 404 when DCR is not configured on that provider.