authentik.sources.oauth.tests.test_type_entra_id

Entra ID Type tests

  1"""Entra ID Type tests"""
  2
  3from json import dumps
  4from unittest.mock import patch
  5
  6from django.test import RequestFactory, TestCase
  7from httpx import Response
  8from requests_mock import Mocker
  9
 10from authentik.lib.generators import generate_id
 11from authentik.sources.oauth.models import OAuthSource
 12from authentik.sources.oauth.types.entra_id import (
 13    EntraIDClient,
 14    EntraIDOAuthCallback,
 15    EntraIDOAuthRedirect,
 16    EntraIDType,
 17)
 18
 19# https://docs.microsoft.com/en-us/graph/api/user-get?view=graph-rest-1.0&tabs=http#response-2
 20EID_USER = {
 21    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users/$entity",
 22    "@odata.id": (
 23        "https://graph.microsoft.com/v2/7ce9b89e-646a-41d2-9fa6-8371c6a8423d/"
 24        "directoryObjects/018b0aff-8aff-473e-bf9c-b50e27f52208/Microsoft.DirectoryServices.User"
 25    ),
 26    "businessPhones": [],
 27    "displayName": "foo bar",
 28    "givenName": "foo",
 29    "jobTitle": None,
 30    "mail": "foo@goauthentik.io",
 31    "mobilePhone": None,
 32    "officeLocation": None,
 33    "preferredLanguage": None,
 34    "surname": "bar",
 35    "userPrincipalName": "foo@goauthentik.io",
 36    "id": "018b0aff-8aff-473e-bf9c-b50e27f52208",
 37}
 38
 39
 40class TestTypeAzureAD(TestCase):
 41    """OAuth Source tests"""
 42
 43    def setUp(self):
 44        self.source = OAuthSource.objects.create(
 45            name="test",
 46            slug="test",
 47            provider_type="openidconnect",
 48            authorization_url="",
 49            profile_url="",
 50            consumer_key="",
 51        )
 52
 53    def test_enroll_context(self):
 54        """Test azure_ad Enrollment context"""
 55        ak_context = EntraIDType().get_base_user_properties(source=self.source, info=EID_USER)
 56        self.assertEqual(ak_context["username"], EID_USER["userPrincipalName"])
 57        self.assertEqual(ak_context["email"], EID_USER["mail"])
 58        self.assertEqual(ak_context["name"], EID_USER["displayName"])
 59
 60    def test_user_id(self):
 61        """Test Entra ID user ID"""
 62        self.assertEqual(EntraIDOAuthCallback().get_user_id(EID_USER), EID_USER["id"])
 63
 64
 65class TestEntraIDClient(TestCase):
 66    """Entra ID group pagination"""
 67
 68    def setUp(self):
 69        self.source = OAuthSource(
 70            provider_type="entraid",
 71            additional_scopes="https://graph.microsoft.com/GroupMember.Read.All",
 72        )
 73        self.oauth_client = EntraIDClient(self.source, RequestFactory().get("/"))
 74        self.token = {"token_type": "Bearer", "access_token": generate_id()}
 75        self.urls = [
 76            "https://graph.microsoft.com/v1.0/me/memberOf",
 77            "https://graph.microsoft.com/v1.0/me/memberOf?$skiptoken=Opaque%2BOne%3D",
 78            "https://graph.microsoft.com/v1.0/me/memberOf?$top=2&$skiptoken=Other%2FTwo%3D",
 79        ]
 80
 81    def test_group_pages(self):
 82        """Collect all pages, follow exact next links, and filter non-group objects."""
 83        for count in (1, 2, 3):
 84            with (
 85                self.subTest(pages=count),
 86                Mocker() as mocker,
 87                patch("httpx.AsyncHTTPTransport.handle_async_request") as graph_request,
 88            ):
 89                mocker.get(EntraIDType.profile_url, json=EID_USER)
 90                token = {"token_type": "Bearer", "access_token": generate_id()}
 91                pages = []
 92                for index in range(count):
 93                    page = {
 94                        "value": [
 95                            {
 96                                "@odata.type": "#microsoft.graph.group",
 97                                "id": str(index),
 98                                "displayName": f"Group {index}",
 99                                "extension_custom": "retained",
100                                "createdDateTime": "2026-01-01T00:00:00Z",
101                                "owners": [{"@odata.type": "#microsoft.graph.user", "id": "owner"}],
102                            },
103                            {"@odata.type": "#microsoft.graph.directoryRole", "id": "role"},
104                        ]
105                    }
106                    if index + 1 < count:
107                        page["@odata.nextLink"] = self.urls[index + 1]
108                    pages.append(Response(200, json=page))
109                graph_request.side_effect = pages
110
111                info = self.oauth_client.get_profile_info(token)
112                self.assertEqual(len(info["raw_groups"]["value"]), count * 2)
113                self.assertEqual(
114                    EntraIDType().get_base_user_properties(info)["groups"],
115                    [str(index) for index in range(count)],
116                )
117                self.assertEqual(
118                    EntraIDType().get_base_group_properties(self.source, "0", info=info),
119                    {"name": "Group 0"},
120                )
121                group = info["raw_groups"]["0"]
122                self.assertEqual(group["additional_data"]["extension_custom"], "retained")
123                self.assertEqual(group["created_date_time"], "2026-01-01T00:00:00Z")
124                self.assertEqual(group["owners"][0]["id"], "owner")
125                self.assertNotIn("backing_store", dumps(group))
126                requests = [call.args[0] for call in graph_request.call_args_list]
127                self.assertEqual([str(request.url) for request in requests], self.urls[:count])
128                for request in requests:
129                    self.assertEqual(
130                        request.headers["Authorization"], f"Bearer {token['access_token']}"
131                    )
132
133    def test_later_page_error(self):
134        """A failed continuation must not return a partial profile for synchronization."""
135        with (
136            Mocker() as mocker,
137            patch("httpx.AsyncHTTPTransport.handle_async_request") as graph_request,
138        ):
139            mocker.get(EntraIDType.profile_url, json=EID_USER)
140            graph_request.side_effect = [
141                Response(
142                    200,
143                    json={
144                        "value": [{"@odata.type": "#microsoft.graph.group", "id": "group"}],
145                        "@odata.nextLink": self.urls[1],
146                    },
147                ),
148                Response(403, json={"error": {"code": "Authorization_RequestDenied"}}),
149            ]
150            self.assertIsNone(self.oauth_client.get_profile_info(self.token))
151            self.assertEqual(graph_request.call_count, 2)
152
153    def test_without_group_scope(self):
154        """Only fetch the user profile when the group scope is absent."""
155        self.source.additional_scopes = "https://graph.microsoft.com/User.Read"
156        with (
157            Mocker() as mocker,
158            patch("httpx.AsyncHTTPTransport.handle_async_request") as graph_request,
159        ):
160            mocker.get(EntraIDType.profile_url, json=EID_USER)
161            self.assertEqual(self.oauth_client.get_profile_info(self.token), EID_USER)
162            self.assertEqual(mocker.call_count, 1)
163            graph_request.assert_not_called()
164
165    def test_national_clouds(self):
166        """Use the profile's Graph cloud for scopes and every membership page."""
167        for host in (
168            "graph.microsoft.com",
169            "graph.microsoft.us",
170            "dod-graph.microsoft.us",
171            "microsoftgraph.chinacloudapi.cn",
172        ):
173            for path in ("/v1.0/me", "/oidc/userinfo", "/v1.0/me?$select=id,displayName"):
174                with (
175                    self.subTest(host=host, path=path),
176                    Mocker() as mocker,
177                    patch("httpx.AsyncHTTPTransport.handle_async_request") as graph_request,
178                ):
179                    base_url = f"https://{host}"
180                    self.source.profile_url = base_url + path
181                    self.source.additional_scopes = (
182                        f"*openid {base_url}/User.Read {base_url}/GroupMember.Read.All"
183                    )
184                    self.assertEqual(
185                        EntraIDOAuthRedirect().get_additional_parameters(self.source),
186                        {"scope": ["openid", f"{base_url}/User.Read"]},
187                    )
188                    mocker.get(self.source.profile_url, json=EID_USER)
189                    next_url = f"{base_url}/v1.0/me/memberOf?$skiptoken=Opaque%2BOne%3D"
190                    graph_request.side_effect = [
191                        Response(
192                            200,
193                            json={
194                                "value": [{"@odata.type": "#microsoft.graph.group", "id": "first"}],
195                                "@odata.nextLink": next_url,
196                            },
197                        ),
198                        Response(
199                            200,
200                            json={
201                                "value": [
202                                    {"@odata.type": "#microsoft.graph.group", "id": "second"}
203                                ],
204                            },
205                        ),
206                    ]
207                    info = self.oauth_client.get_profile_info(self.token)
208                    self.assertEqual(
209                        EntraIDType().get_base_user_properties(info)["groups"],
210                        ["first", "second"],
211                    )
212                    requests = [call.args[0] for call in graph_request.call_args_list]
213                    self.assertEqual(
214                        [str(request.url) for request in requests],
215                        [f"{base_url}/v1.0/me/memberOf", next_url],
216                    )
217                    for request in requests:
218                        self.assertEqual(
219                            request.headers["Authorization"], f"Bearer {self.token['access_token']}"
220                        )
221
222    def test_default_profile_scope(self):
223        """Unset profile URLs retain the commercial default scope."""
224        for profile_url in (None, ""):
225            with self.subTest(profile_url=profile_url):
226                self.source.profile_url = profile_url
227                self.assertEqual(
228                    EntraIDOAuthRedirect().get_additional_parameters(self.source),
229                    {"scope": ["openid", "https://graph.microsoft.com/User.Read"]},
230                )
231
232    def test_group_scope_must_match(self):
233        """Do not fetch memberships for another cloud or a scope substring."""
234        self.source.profile_url = "https://graph.microsoft.us/v1.0/me"
235        for scope in (
236            "https://graph.microsoft.com/GroupMember.Read.All",
237            "https://graph.microsoft.us/GroupMember.Read.All.extra",
238        ):
239            with (
240                self.subTest(scope=scope),
241                Mocker() as mocker,
242                patch("httpx.AsyncHTTPTransport.handle_async_request") as graph_request,
243            ):
244                self.source.additional_scopes = scope
245                mocker.get(self.source.profile_url, json=EID_USER)
246                self.assertEqual(self.oauth_client.get_profile_info(self.token), EID_USER)
247                graph_request.assert_not_called()
248
249    def test_profile_error(self):
250        """A failed profile request must not trigger a membership request."""
251        with (
252            Mocker() as mocker,
253            patch("httpx.AsyncHTTPTransport.handle_async_request") as graph_request,
254        ):
255            mocker.get(EntraIDType.profile_url, status_code=403)
256            self.assertIsNone(self.oauth_client.get_profile_info(self.token))
257            graph_request.assert_not_called()
EID_USER = {'@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#users/$entity', '@odata.id': 'https://graph.microsoft.com/v2/7ce9b89e-646a-41d2-9fa6-8371c6a8423d/directoryObjects/018b0aff-8aff-473e-bf9c-b50e27f52208/Microsoft.DirectoryServices.User', 'businessPhones': [], 'displayName': 'foo bar', 'givenName': 'foo', 'jobTitle': None, 'mail': 'foo@goauthentik.io', 'mobilePhone': None, 'officeLocation': None, 'preferredLanguage': None, 'surname': 'bar', 'userPrincipalName': 'foo@goauthentik.io', 'id': '018b0aff-8aff-473e-bf9c-b50e27f52208'}
class TestTypeAzureAD(django.test.testcases.TestCase):
41class TestTypeAzureAD(TestCase):
42    """OAuth Source tests"""
43
44    def setUp(self):
45        self.source = OAuthSource.objects.create(
46            name="test",
47            slug="test",
48            provider_type="openidconnect",
49            authorization_url="",
50            profile_url="",
51            consumer_key="",
52        )
53
54    def test_enroll_context(self):
55        """Test azure_ad Enrollment context"""
56        ak_context = EntraIDType().get_base_user_properties(source=self.source, info=EID_USER)
57        self.assertEqual(ak_context["username"], EID_USER["userPrincipalName"])
58        self.assertEqual(ak_context["email"], EID_USER["mail"])
59        self.assertEqual(ak_context["name"], EID_USER["displayName"])
60
61    def test_user_id(self):
62        """Test Entra ID user ID"""
63        self.assertEqual(EntraIDOAuthCallback().get_user_id(EID_USER), EID_USER["id"])

OAuth Source tests

def setUp(self):
44    def setUp(self):
45        self.source = OAuthSource.objects.create(
46            name="test",
47            slug="test",
48            provider_type="openidconnect",
49            authorization_url="",
50            profile_url="",
51            consumer_key="",
52        )

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

def test_enroll_context(self):
54    def test_enroll_context(self):
55        """Test azure_ad Enrollment context"""
56        ak_context = EntraIDType().get_base_user_properties(source=self.source, info=EID_USER)
57        self.assertEqual(ak_context["username"], EID_USER["userPrincipalName"])
58        self.assertEqual(ak_context["email"], EID_USER["mail"])
59        self.assertEqual(ak_context["name"], EID_USER["displayName"])

Test azure_ad Enrollment context

def test_user_id(self):
61    def test_user_id(self):
62        """Test Entra ID user ID"""
63        self.assertEqual(EntraIDOAuthCallback().get_user_id(EID_USER), EID_USER["id"])

Test Entra ID user ID

class TestEntraIDClient(django.test.testcases.TestCase):
 66class TestEntraIDClient(TestCase):
 67    """Entra ID group pagination"""
 68
 69    def setUp(self):
 70        self.source = OAuthSource(
 71            provider_type="entraid",
 72            additional_scopes="https://graph.microsoft.com/GroupMember.Read.All",
 73        )
 74        self.oauth_client = EntraIDClient(self.source, RequestFactory().get("/"))
 75        self.token = {"token_type": "Bearer", "access_token": generate_id()}
 76        self.urls = [
 77            "https://graph.microsoft.com/v1.0/me/memberOf",
 78            "https://graph.microsoft.com/v1.0/me/memberOf?$skiptoken=Opaque%2BOne%3D",
 79            "https://graph.microsoft.com/v1.0/me/memberOf?$top=2&$skiptoken=Other%2FTwo%3D",
 80        ]
 81
 82    def test_group_pages(self):
 83        """Collect all pages, follow exact next links, and filter non-group objects."""
 84        for count in (1, 2, 3):
 85            with (
 86                self.subTest(pages=count),
 87                Mocker() as mocker,
 88                patch("httpx.AsyncHTTPTransport.handle_async_request") as graph_request,
 89            ):
 90                mocker.get(EntraIDType.profile_url, json=EID_USER)
 91                token = {"token_type": "Bearer", "access_token": generate_id()}
 92                pages = []
 93                for index in range(count):
 94                    page = {
 95                        "value": [
 96                            {
 97                                "@odata.type": "#microsoft.graph.group",
 98                                "id": str(index),
 99                                "displayName": f"Group {index}",
100                                "extension_custom": "retained",
101                                "createdDateTime": "2026-01-01T00:00:00Z",
102                                "owners": [{"@odata.type": "#microsoft.graph.user", "id": "owner"}],
103                            },
104                            {"@odata.type": "#microsoft.graph.directoryRole", "id": "role"},
105                        ]
106                    }
107                    if index + 1 < count:
108                        page["@odata.nextLink"] = self.urls[index + 1]
109                    pages.append(Response(200, json=page))
110                graph_request.side_effect = pages
111
112                info = self.oauth_client.get_profile_info(token)
113                self.assertEqual(len(info["raw_groups"]["value"]), count * 2)
114                self.assertEqual(
115                    EntraIDType().get_base_user_properties(info)["groups"],
116                    [str(index) for index in range(count)],
117                )
118                self.assertEqual(
119                    EntraIDType().get_base_group_properties(self.source, "0", info=info),
120                    {"name": "Group 0"},
121                )
122                group = info["raw_groups"]["0"]
123                self.assertEqual(group["additional_data"]["extension_custom"], "retained")
124                self.assertEqual(group["created_date_time"], "2026-01-01T00:00:00Z")
125                self.assertEqual(group["owners"][0]["id"], "owner")
126                self.assertNotIn("backing_store", dumps(group))
127                requests = [call.args[0] for call in graph_request.call_args_list]
128                self.assertEqual([str(request.url) for request in requests], self.urls[:count])
129                for request in requests:
130                    self.assertEqual(
131                        request.headers["Authorization"], f"Bearer {token['access_token']}"
132                    )
133
134    def test_later_page_error(self):
135        """A failed continuation must not return a partial profile for synchronization."""
136        with (
137            Mocker() as mocker,
138            patch("httpx.AsyncHTTPTransport.handle_async_request") as graph_request,
139        ):
140            mocker.get(EntraIDType.profile_url, json=EID_USER)
141            graph_request.side_effect = [
142                Response(
143                    200,
144                    json={
145                        "value": [{"@odata.type": "#microsoft.graph.group", "id": "group"}],
146                        "@odata.nextLink": self.urls[1],
147                    },
148                ),
149                Response(403, json={"error": {"code": "Authorization_RequestDenied"}}),
150            ]
151            self.assertIsNone(self.oauth_client.get_profile_info(self.token))
152            self.assertEqual(graph_request.call_count, 2)
153
154    def test_without_group_scope(self):
155        """Only fetch the user profile when the group scope is absent."""
156        self.source.additional_scopes = "https://graph.microsoft.com/User.Read"
157        with (
158            Mocker() as mocker,
159            patch("httpx.AsyncHTTPTransport.handle_async_request") as graph_request,
160        ):
161            mocker.get(EntraIDType.profile_url, json=EID_USER)
162            self.assertEqual(self.oauth_client.get_profile_info(self.token), EID_USER)
163            self.assertEqual(mocker.call_count, 1)
164            graph_request.assert_not_called()
165
166    def test_national_clouds(self):
167        """Use the profile's Graph cloud for scopes and every membership page."""
168        for host in (
169            "graph.microsoft.com",
170            "graph.microsoft.us",
171            "dod-graph.microsoft.us",
172            "microsoftgraph.chinacloudapi.cn",
173        ):
174            for path in ("/v1.0/me", "/oidc/userinfo", "/v1.0/me?$select=id,displayName"):
175                with (
176                    self.subTest(host=host, path=path),
177                    Mocker() as mocker,
178                    patch("httpx.AsyncHTTPTransport.handle_async_request") as graph_request,
179                ):
180                    base_url = f"https://{host}"
181                    self.source.profile_url = base_url + path
182                    self.source.additional_scopes = (
183                        f"*openid {base_url}/User.Read {base_url}/GroupMember.Read.All"
184                    )
185                    self.assertEqual(
186                        EntraIDOAuthRedirect().get_additional_parameters(self.source),
187                        {"scope": ["openid", f"{base_url}/User.Read"]},
188                    )
189                    mocker.get(self.source.profile_url, json=EID_USER)
190                    next_url = f"{base_url}/v1.0/me/memberOf?$skiptoken=Opaque%2BOne%3D"
191                    graph_request.side_effect = [
192                        Response(
193                            200,
194                            json={
195                                "value": [{"@odata.type": "#microsoft.graph.group", "id": "first"}],
196                                "@odata.nextLink": next_url,
197                            },
198                        ),
199                        Response(
200                            200,
201                            json={
202                                "value": [
203                                    {"@odata.type": "#microsoft.graph.group", "id": "second"}
204                                ],
205                            },
206                        ),
207                    ]
208                    info = self.oauth_client.get_profile_info(self.token)
209                    self.assertEqual(
210                        EntraIDType().get_base_user_properties(info)["groups"],
211                        ["first", "second"],
212                    )
213                    requests = [call.args[0] for call in graph_request.call_args_list]
214                    self.assertEqual(
215                        [str(request.url) for request in requests],
216                        [f"{base_url}/v1.0/me/memberOf", next_url],
217                    )
218                    for request in requests:
219                        self.assertEqual(
220                            request.headers["Authorization"], f"Bearer {self.token['access_token']}"
221                        )
222
223    def test_default_profile_scope(self):
224        """Unset profile URLs retain the commercial default scope."""
225        for profile_url in (None, ""):
226            with self.subTest(profile_url=profile_url):
227                self.source.profile_url = profile_url
228                self.assertEqual(
229                    EntraIDOAuthRedirect().get_additional_parameters(self.source),
230                    {"scope": ["openid", "https://graph.microsoft.com/User.Read"]},
231                )
232
233    def test_group_scope_must_match(self):
234        """Do not fetch memberships for another cloud or a scope substring."""
235        self.source.profile_url = "https://graph.microsoft.us/v1.0/me"
236        for scope in (
237            "https://graph.microsoft.com/GroupMember.Read.All",
238            "https://graph.microsoft.us/GroupMember.Read.All.extra",
239        ):
240            with (
241                self.subTest(scope=scope),
242                Mocker() as mocker,
243                patch("httpx.AsyncHTTPTransport.handle_async_request") as graph_request,
244            ):
245                self.source.additional_scopes = scope
246                mocker.get(self.source.profile_url, json=EID_USER)
247                self.assertEqual(self.oauth_client.get_profile_info(self.token), EID_USER)
248                graph_request.assert_not_called()
249
250    def test_profile_error(self):
251        """A failed profile request must not trigger a membership request."""
252        with (
253            Mocker() as mocker,
254            patch("httpx.AsyncHTTPTransport.handle_async_request") as graph_request,
255        ):
256            mocker.get(EntraIDType.profile_url, status_code=403)
257            self.assertIsNone(self.oauth_client.get_profile_info(self.token))
258            graph_request.assert_not_called()

Entra ID group pagination

def setUp(self):
69    def setUp(self):
70        self.source = OAuthSource(
71            provider_type="entraid",
72            additional_scopes="https://graph.microsoft.com/GroupMember.Read.All",
73        )
74        self.oauth_client = EntraIDClient(self.source, RequestFactory().get("/"))
75        self.token = {"token_type": "Bearer", "access_token": generate_id()}
76        self.urls = [
77            "https://graph.microsoft.com/v1.0/me/memberOf",
78            "https://graph.microsoft.com/v1.0/me/memberOf?$skiptoken=Opaque%2BOne%3D",
79            "https://graph.microsoft.com/v1.0/me/memberOf?$top=2&$skiptoken=Other%2FTwo%3D",
80        ]

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

def test_group_pages(self):
 82    def test_group_pages(self):
 83        """Collect all pages, follow exact next links, and filter non-group objects."""
 84        for count in (1, 2, 3):
 85            with (
 86                self.subTest(pages=count),
 87                Mocker() as mocker,
 88                patch("httpx.AsyncHTTPTransport.handle_async_request") as graph_request,
 89            ):
 90                mocker.get(EntraIDType.profile_url, json=EID_USER)
 91                token = {"token_type": "Bearer", "access_token": generate_id()}
 92                pages = []
 93                for index in range(count):
 94                    page = {
 95                        "value": [
 96                            {
 97                                "@odata.type": "#microsoft.graph.group",
 98                                "id": str(index),
 99                                "displayName": f"Group {index}",
100                                "extension_custom": "retained",
101                                "createdDateTime": "2026-01-01T00:00:00Z",
102                                "owners": [{"@odata.type": "#microsoft.graph.user", "id": "owner"}],
103                            },
104                            {"@odata.type": "#microsoft.graph.directoryRole", "id": "role"},
105                        ]
106                    }
107                    if index + 1 < count:
108                        page["@odata.nextLink"] = self.urls[index + 1]
109                    pages.append(Response(200, json=page))
110                graph_request.side_effect = pages
111
112                info = self.oauth_client.get_profile_info(token)
113                self.assertEqual(len(info["raw_groups"]["value"]), count * 2)
114                self.assertEqual(
115                    EntraIDType().get_base_user_properties(info)["groups"],
116                    [str(index) for index in range(count)],
117                )
118                self.assertEqual(
119                    EntraIDType().get_base_group_properties(self.source, "0", info=info),
120                    {"name": "Group 0"},
121                )
122                group = info["raw_groups"]["0"]
123                self.assertEqual(group["additional_data"]["extension_custom"], "retained")
124                self.assertEqual(group["created_date_time"], "2026-01-01T00:00:00Z")
125                self.assertEqual(group["owners"][0]["id"], "owner")
126                self.assertNotIn("backing_store", dumps(group))
127                requests = [call.args[0] for call in graph_request.call_args_list]
128                self.assertEqual([str(request.url) for request in requests], self.urls[:count])
129                for request in requests:
130                    self.assertEqual(
131                        request.headers["Authorization"], f"Bearer {token['access_token']}"
132                    )

Collect all pages, follow exact next links, and filter non-group objects.

def test_later_page_error(self):
134    def test_later_page_error(self):
135        """A failed continuation must not return a partial profile for synchronization."""
136        with (
137            Mocker() as mocker,
138            patch("httpx.AsyncHTTPTransport.handle_async_request") as graph_request,
139        ):
140            mocker.get(EntraIDType.profile_url, json=EID_USER)
141            graph_request.side_effect = [
142                Response(
143                    200,
144                    json={
145                        "value": [{"@odata.type": "#microsoft.graph.group", "id": "group"}],
146                        "@odata.nextLink": self.urls[1],
147                    },
148                ),
149                Response(403, json={"error": {"code": "Authorization_RequestDenied"}}),
150            ]
151            self.assertIsNone(self.oauth_client.get_profile_info(self.token))
152            self.assertEqual(graph_request.call_count, 2)

A failed continuation must not return a partial profile for synchronization.

def test_without_group_scope(self):
154    def test_without_group_scope(self):
155        """Only fetch the user profile when the group scope is absent."""
156        self.source.additional_scopes = "https://graph.microsoft.com/User.Read"
157        with (
158            Mocker() as mocker,
159            patch("httpx.AsyncHTTPTransport.handle_async_request") as graph_request,
160        ):
161            mocker.get(EntraIDType.profile_url, json=EID_USER)
162            self.assertEqual(self.oauth_client.get_profile_info(self.token), EID_USER)
163            self.assertEqual(mocker.call_count, 1)
164            graph_request.assert_not_called()

Only fetch the user profile when the group scope is absent.

def test_national_clouds(self):
166    def test_national_clouds(self):
167        """Use the profile's Graph cloud for scopes and every membership page."""
168        for host in (
169            "graph.microsoft.com",
170            "graph.microsoft.us",
171            "dod-graph.microsoft.us",
172            "microsoftgraph.chinacloudapi.cn",
173        ):
174            for path in ("/v1.0/me", "/oidc/userinfo", "/v1.0/me?$select=id,displayName"):
175                with (
176                    self.subTest(host=host, path=path),
177                    Mocker() as mocker,
178                    patch("httpx.AsyncHTTPTransport.handle_async_request") as graph_request,
179                ):
180                    base_url = f"https://{host}"
181                    self.source.profile_url = base_url + path
182                    self.source.additional_scopes = (
183                        f"*openid {base_url}/User.Read {base_url}/GroupMember.Read.All"
184                    )
185                    self.assertEqual(
186                        EntraIDOAuthRedirect().get_additional_parameters(self.source),
187                        {"scope": ["openid", f"{base_url}/User.Read"]},
188                    )
189                    mocker.get(self.source.profile_url, json=EID_USER)
190                    next_url = f"{base_url}/v1.0/me/memberOf?$skiptoken=Opaque%2BOne%3D"
191                    graph_request.side_effect = [
192                        Response(
193                            200,
194                            json={
195                                "value": [{"@odata.type": "#microsoft.graph.group", "id": "first"}],
196                                "@odata.nextLink": next_url,
197                            },
198                        ),
199                        Response(
200                            200,
201                            json={
202                                "value": [
203                                    {"@odata.type": "#microsoft.graph.group", "id": "second"}
204                                ],
205                            },
206                        ),
207                    ]
208                    info = self.oauth_client.get_profile_info(self.token)
209                    self.assertEqual(
210                        EntraIDType().get_base_user_properties(info)["groups"],
211                        ["first", "second"],
212                    )
213                    requests = [call.args[0] for call in graph_request.call_args_list]
214                    self.assertEqual(
215                        [str(request.url) for request in requests],
216                        [f"{base_url}/v1.0/me/memberOf", next_url],
217                    )
218                    for request in requests:
219                        self.assertEqual(
220                            request.headers["Authorization"], f"Bearer {self.token['access_token']}"
221                        )

Use the profile's Graph cloud for scopes and every membership page.

def test_default_profile_scope(self):
223    def test_default_profile_scope(self):
224        """Unset profile URLs retain the commercial default scope."""
225        for profile_url in (None, ""):
226            with self.subTest(profile_url=profile_url):
227                self.source.profile_url = profile_url
228                self.assertEqual(
229                    EntraIDOAuthRedirect().get_additional_parameters(self.source),
230                    {"scope": ["openid", "https://graph.microsoft.com/User.Read"]},
231                )

Unset profile URLs retain the commercial default scope.

def test_group_scope_must_match(self):
233    def test_group_scope_must_match(self):
234        """Do not fetch memberships for another cloud or a scope substring."""
235        self.source.profile_url = "https://graph.microsoft.us/v1.0/me"
236        for scope in (
237            "https://graph.microsoft.com/GroupMember.Read.All",
238            "https://graph.microsoft.us/GroupMember.Read.All.extra",
239        ):
240            with (
241                self.subTest(scope=scope),
242                Mocker() as mocker,
243                patch("httpx.AsyncHTTPTransport.handle_async_request") as graph_request,
244            ):
245                self.source.additional_scopes = scope
246                mocker.get(self.source.profile_url, json=EID_USER)
247                self.assertEqual(self.oauth_client.get_profile_info(self.token), EID_USER)
248                graph_request.assert_not_called()

Do not fetch memberships for another cloud or a scope substring.

def test_profile_error(self):
250    def test_profile_error(self):
251        """A failed profile request must not trigger a membership request."""
252        with (
253            Mocker() as mocker,
254            patch("httpx.AsyncHTTPTransport.handle_async_request") as graph_request,
255        ):
256            mocker.get(EntraIDType.profile_url, status_code=403)
257            self.assertIsNone(self.oauth_client.get_profile_info(self.token))
258            graph_request.assert_not_called()

A failed profile request must not trigger a membership request.