authentik.providers.oauth2.tests.test_provider_info

Provider info (OpenID discovery) tests

  1"""Provider info (OpenID discovery) tests"""
  2
  3from unittest.mock import patch
  4
  5from django.core.cache import cache
  6from django.db import connection
  7from django.test.utils import CaptureQueriesContext
  8from django.urls import reverse
  9
 10from authentik.blueprints.tests import apply_blueprint
 11from authentik.core.models import Application
 12from authentik.core.tests.utils import RequestFactory, create_test_flow
 13from authentik.lib.generators import generate_id
 14from authentik.providers.oauth2.models import (
 15    OAuth2Provider,
 16    RedirectURI,
 17    RedirectURIMatchingMode,
 18    ScopeMapping,
 19)
 20from authentik.providers.oauth2.tests.utils import OAuthTestCase
 21from authentik.providers.oauth2.views.provider import ProviderInfoView, claims_cache_key
 22
 23
 24class TestProviderInfo(OAuthTestCase):
 25    """Test provider info view"""
 26
 27    @apply_blueprint("system/providers-oauth2.yaml")
 28    def setUp(self) -> None:
 29        super().setUp()
 30        self.provider = OAuth2Provider.objects.create(
 31            name=generate_id(),
 32            client_id=generate_id(),
 33            authorization_flow=create_test_flow(),
 34            redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://local.invalid")],
 35            signing_key=self.keypair,
 36        )
 37        self.provider.property_mappings.set(ScopeMapping.objects.all())
 38        self.app = Application.objects.create(
 39            name=generate_id(), slug=generate_id(), provider=self.provider
 40        )
 41
 42    def get_info(self, app: Application | None = None) -> dict:
 43        """Fetch the discovery document"""
 44        response = self.client.get(
 45            reverse(
 46                "authentik_providers_oauth2:provider-info",
 47                kwargs={"application_slug": (app or self.app).slug},
 48            )
 49        )
 50        self.assertEqual(response.status_code, 200)
 51        return response.json()
 52
 53    def test_info(self):
 54        """Test discovery document"""
 55        body = self.get_info()
 56        self.assertTrue(body["issuer"].endswith(f"/application/o/{self.app.slug}/"))
 57        self.assertTrue(body["token_endpoint"].endswith("/token/"))
 58        self.assertIn("openid", body["scopes_supported"])
 59        self.assertIn("email", body["scopes_supported"])
 60        for claim in ["sub", "iss", "aud", "exp", "iat", "acr", "amr", "nonce"]:
 61            self.assertIn(claim, body["claims_supported"])
 62        # Claims from the default scope mappings
 63        self.assertIn("email", body["claims_supported"])
 64        self.assertIn("preferred_username", body["claims_supported"])
 65
 66    def test_claims_cached(self):
 67        """Test claims are only evaluated once"""
 68        claims = self.get_info()["claims_supported"]
 69        # Anything hitting get_claims again means the cache didn't take
 70        with patch.object(ProviderInfoView, "get_claims", return_value=claims) as get_claims:
 71            self.assertEqual(self.get_info()["claims_supported"], claims)
 72        get_claims.assert_not_called()
 73
 74    def test_claims_cached_per_provider(self):
 75        """Test cached claims aren't shared between providers"""
 76        self.get_info()
 77        other = OAuth2Provider.objects.create(
 78            name=generate_id(),
 79            client_id=generate_id(),
 80            authorization_flow=create_test_flow(),
 81            redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://local.invalid")],
 82            signing_key=self.keypair,
 83        )
 84        other.property_mappings.set(
 85            ScopeMapping.objects.filter(managed="goauthentik.io/providers/oauth2/scope-openid")
 86        )
 87        other_app = Application.objects.create(
 88            name=generate_id(), slug=generate_id(), provider=other
 89        )
 90        self.assertNotIn("email", self.get_info(other_app)["claims_supported"])
 91        self.assertIn("email", self.get_info()["claims_supported"])
 92
 93    def test_claims_mapping_error(self):
 94        """Test failing scope mapping is skipped"""
 95        self.provider.property_mappings.add(
 96            ScopeMapping.objects.create(
 97                name=generate_id(),
 98                scope_name=generate_id(),
 99                expression="raise Exception('test')",
100            )
101        )
102        body = self.get_info()
103        self.assertIn("email", body["claims_supported"])
104
105    def test_private_key_not_loaded(self):
106        """Test the signing algorithm is read without loading the private key, whose validation
107        is slow for RSA keys"""
108        with patch("authentik.crypto.models._load_private_key", side_effect=AssertionError):
109            body = self.get_info()
110        self.assertEqual(body["id_token_signing_alg_values_supported"], ["RS256"])
111
112    def test_queries(self):
113        """Test a request with cached claims loads the application, provider and keys in one
114        query"""
115        self.get_info()
116        request = RequestFactory().get("/")
117        # provider, scope names, cached claims and dynamic client registration
118        with self.assertNumQueries(4):
119            response = ProviderInfoView.as_view()(request, application_slug=self.app.slug)
120        self.assertEqual(response.status_code, 200)
121
122    def test_claims_queries(self):
123        """Test evaluating the claims does not query once per scope mapping"""
124        request = RequestFactory().get("/")
125
126        def count_queries() -> int:
127            cache.delete(claims_cache_key(self.provider))
128            with CaptureQueriesContext(connection) as ctx:
129                ProviderInfoView.as_view()(request, application_slug=self.app.slug)
130            return len(ctx.captured_queries)
131
132        def mapping() -> ScopeMapping:
133            return ScopeMapping.objects.create(
134                name=generate_id(), scope_name=generate_id(), expression="return {'claim': 1}"
135            )
136
137        self.provider.property_mappings.set([mapping()])
138        one = count_queries()
139        self.provider.property_mappings.add(mapping(), mapping(), mapping())
140        self.assertEqual(count_queries(), one)
class TestProviderInfo(authentik.providers.oauth2.tests.utils.OAuthTestCase):
 25class TestProviderInfo(OAuthTestCase):
 26    """Test provider info view"""
 27
 28    @apply_blueprint("system/providers-oauth2.yaml")
 29    def setUp(self) -> None:
 30        super().setUp()
 31        self.provider = OAuth2Provider.objects.create(
 32            name=generate_id(),
 33            client_id=generate_id(),
 34            authorization_flow=create_test_flow(),
 35            redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://local.invalid")],
 36            signing_key=self.keypair,
 37        )
 38        self.provider.property_mappings.set(ScopeMapping.objects.all())
 39        self.app = Application.objects.create(
 40            name=generate_id(), slug=generate_id(), provider=self.provider
 41        )
 42
 43    def get_info(self, app: Application | None = None) -> dict:
 44        """Fetch the discovery document"""
 45        response = self.client.get(
 46            reverse(
 47                "authentik_providers_oauth2:provider-info",
 48                kwargs={"application_slug": (app or self.app).slug},
 49            )
 50        )
 51        self.assertEqual(response.status_code, 200)
 52        return response.json()
 53
 54    def test_info(self):
 55        """Test discovery document"""
 56        body = self.get_info()
 57        self.assertTrue(body["issuer"].endswith(f"/application/o/{self.app.slug}/"))
 58        self.assertTrue(body["token_endpoint"].endswith("/token/"))
 59        self.assertIn("openid", body["scopes_supported"])
 60        self.assertIn("email", body["scopes_supported"])
 61        for claim in ["sub", "iss", "aud", "exp", "iat", "acr", "amr", "nonce"]:
 62            self.assertIn(claim, body["claims_supported"])
 63        # Claims from the default scope mappings
 64        self.assertIn("email", body["claims_supported"])
 65        self.assertIn("preferred_username", body["claims_supported"])
 66
 67    def test_claims_cached(self):
 68        """Test claims are only evaluated once"""
 69        claims = self.get_info()["claims_supported"]
 70        # Anything hitting get_claims again means the cache didn't take
 71        with patch.object(ProviderInfoView, "get_claims", return_value=claims) as get_claims:
 72            self.assertEqual(self.get_info()["claims_supported"], claims)
 73        get_claims.assert_not_called()
 74
 75    def test_claims_cached_per_provider(self):
 76        """Test cached claims aren't shared between providers"""
 77        self.get_info()
 78        other = OAuth2Provider.objects.create(
 79            name=generate_id(),
 80            client_id=generate_id(),
 81            authorization_flow=create_test_flow(),
 82            redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://local.invalid")],
 83            signing_key=self.keypair,
 84        )
 85        other.property_mappings.set(
 86            ScopeMapping.objects.filter(managed="goauthentik.io/providers/oauth2/scope-openid")
 87        )
 88        other_app = Application.objects.create(
 89            name=generate_id(), slug=generate_id(), provider=other
 90        )
 91        self.assertNotIn("email", self.get_info(other_app)["claims_supported"])
 92        self.assertIn("email", self.get_info()["claims_supported"])
 93
 94    def test_claims_mapping_error(self):
 95        """Test failing scope mapping is skipped"""
 96        self.provider.property_mappings.add(
 97            ScopeMapping.objects.create(
 98                name=generate_id(),
 99                scope_name=generate_id(),
100                expression="raise Exception('test')",
101            )
102        )
103        body = self.get_info()
104        self.assertIn("email", body["claims_supported"])
105
106    def test_private_key_not_loaded(self):
107        """Test the signing algorithm is read without loading the private key, whose validation
108        is slow for RSA keys"""
109        with patch("authentik.crypto.models._load_private_key", side_effect=AssertionError):
110            body = self.get_info()
111        self.assertEqual(body["id_token_signing_alg_values_supported"], ["RS256"])
112
113    def test_queries(self):
114        """Test a request with cached claims loads the application, provider and keys in one
115        query"""
116        self.get_info()
117        request = RequestFactory().get("/")
118        # provider, scope names, cached claims and dynamic client registration
119        with self.assertNumQueries(4):
120            response = ProviderInfoView.as_view()(request, application_slug=self.app.slug)
121        self.assertEqual(response.status_code, 200)
122
123    def test_claims_queries(self):
124        """Test evaluating the claims does not query once per scope mapping"""
125        request = RequestFactory().get("/")
126
127        def count_queries() -> int:
128            cache.delete(claims_cache_key(self.provider))
129            with CaptureQueriesContext(connection) as ctx:
130                ProviderInfoView.as_view()(request, application_slug=self.app.slug)
131            return len(ctx.captured_queries)
132
133        def mapping() -> ScopeMapping:
134            return ScopeMapping.objects.create(
135                name=generate_id(), scope_name=generate_id(), expression="return {'claim': 1}"
136            )
137
138        self.provider.property_mappings.set([mapping()])
139        one = count_queries()
140        self.provider.property_mappings.add(mapping(), mapping(), mapping())
141        self.assertEqual(count_queries(), one)

Test provider info view

@apply_blueprint('system/providers-oauth2.yaml')
def setUp(self) -> None:
28    @apply_blueprint("system/providers-oauth2.yaml")
29    def setUp(self) -> None:
30        super().setUp()
31        self.provider = OAuth2Provider.objects.create(
32            name=generate_id(),
33            client_id=generate_id(),
34            authorization_flow=create_test_flow(),
35            redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://local.invalid")],
36            signing_key=self.keypair,
37        )
38        self.provider.property_mappings.set(ScopeMapping.objects.all())
39        self.app = Application.objects.create(
40            name=generate_id(), slug=generate_id(), provider=self.provider
41        )

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

def get_info(self, app: authentik.core.models.Application | None = None) -> dict:
43    def get_info(self, app: Application | None = None) -> dict:
44        """Fetch the discovery document"""
45        response = self.client.get(
46            reverse(
47                "authentik_providers_oauth2:provider-info",
48                kwargs={"application_slug": (app or self.app).slug},
49            )
50        )
51        self.assertEqual(response.status_code, 200)
52        return response.json()

Fetch the discovery document

def test_info(self):
54    def test_info(self):
55        """Test discovery document"""
56        body = self.get_info()
57        self.assertTrue(body["issuer"].endswith(f"/application/o/{self.app.slug}/"))
58        self.assertTrue(body["token_endpoint"].endswith("/token/"))
59        self.assertIn("openid", body["scopes_supported"])
60        self.assertIn("email", body["scopes_supported"])
61        for claim in ["sub", "iss", "aud", "exp", "iat", "acr", "amr", "nonce"]:
62            self.assertIn(claim, body["claims_supported"])
63        # Claims from the default scope mappings
64        self.assertIn("email", body["claims_supported"])
65        self.assertIn("preferred_username", body["claims_supported"])

Test discovery document

def test_claims_cached(self):
67    def test_claims_cached(self):
68        """Test claims are only evaluated once"""
69        claims = self.get_info()["claims_supported"]
70        # Anything hitting get_claims again means the cache didn't take
71        with patch.object(ProviderInfoView, "get_claims", return_value=claims) as get_claims:
72            self.assertEqual(self.get_info()["claims_supported"], claims)
73        get_claims.assert_not_called()

Test claims are only evaluated once

def test_claims_cached_per_provider(self):
75    def test_claims_cached_per_provider(self):
76        """Test cached claims aren't shared between providers"""
77        self.get_info()
78        other = OAuth2Provider.objects.create(
79            name=generate_id(),
80            client_id=generate_id(),
81            authorization_flow=create_test_flow(),
82            redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://local.invalid")],
83            signing_key=self.keypair,
84        )
85        other.property_mappings.set(
86            ScopeMapping.objects.filter(managed="goauthentik.io/providers/oauth2/scope-openid")
87        )
88        other_app = Application.objects.create(
89            name=generate_id(), slug=generate_id(), provider=other
90        )
91        self.assertNotIn("email", self.get_info(other_app)["claims_supported"])
92        self.assertIn("email", self.get_info()["claims_supported"])

Test cached claims aren't shared between providers

def test_claims_mapping_error(self):
 94    def test_claims_mapping_error(self):
 95        """Test failing scope mapping is skipped"""
 96        self.provider.property_mappings.add(
 97            ScopeMapping.objects.create(
 98                name=generate_id(),
 99                scope_name=generate_id(),
100                expression="raise Exception('test')",
101            )
102        )
103        body = self.get_info()
104        self.assertIn("email", body["claims_supported"])

Test failing scope mapping is skipped

def test_private_key_not_loaded(self):
106    def test_private_key_not_loaded(self):
107        """Test the signing algorithm is read without loading the private key, whose validation
108        is slow for RSA keys"""
109        with patch("authentik.crypto.models._load_private_key", side_effect=AssertionError):
110            body = self.get_info()
111        self.assertEqual(body["id_token_signing_alg_values_supported"], ["RS256"])

Test the signing algorithm is read without loading the private key, whose validation is slow for RSA keys

def test_queries(self):
113    def test_queries(self):
114        """Test a request with cached claims loads the application, provider and keys in one
115        query"""
116        self.get_info()
117        request = RequestFactory().get("/")
118        # provider, scope names, cached claims and dynamic client registration
119        with self.assertNumQueries(4):
120            response = ProviderInfoView.as_view()(request, application_slug=self.app.slug)
121        self.assertEqual(response.status_code, 200)

Test a request with cached claims loads the application, provider and keys in one query

def test_claims_queries(self):
123    def test_claims_queries(self):
124        """Test evaluating the claims does not query once per scope mapping"""
125        request = RequestFactory().get("/")
126
127        def count_queries() -> int:
128            cache.delete(claims_cache_key(self.provider))
129            with CaptureQueriesContext(connection) as ctx:
130                ProviderInfoView.as_view()(request, application_slug=self.app.slug)
131            return len(ctx.captured_queries)
132
133        def mapping() -> ScopeMapping:
134            return ScopeMapping.objects.create(
135                name=generate_id(), scope_name=generate_id(), expression="return {'claim': 1}"
136            )
137
138        self.provider.property_mappings.set([mapping()])
139        one = count_queries()
140        self.provider.property_mappings.add(mapping(), mapping(), mapping())
141        self.assertEqual(count_queries(), one)

Test evaluating the claims does not query once per scope mapping