Debian Codegraph @

tests/apps/socialaccount/providers/saml/tests.py

raw
1 from http import HTTPStatus
2 from unittest.mock import Mock, patch
3 from urllib.parse import parse_qs, urlparse
4
5 from django.conf import settings
6 from django.urls import reverse, reverse_lazy
7 from django.utils.http import urlencode
8
9 import pytest
10 from pytest_django.asserts import assertTemplateUsed
11
12 from allauth.account.models import EmailAddress
13 from allauth.socialaccount.adapter import get_adapter
14 from allauth.socialaccount.internal import statekit
15 from allauth.socialaccount.models import SocialAccount
16 from allauth.socialaccount.providers.base.constants import AuthProcess
17 from allauth.socialaccount.providers.saml.utils import build_saml_config
18
19
20 @pytest.mark.parametrize(
21 "idp_initiated,adv_settings,state_kwargs,relay_state, expected_url",
22 [
23 (False, {"strict": True}, {}, "/not/here", settings.LOGIN_REDIRECT_URL),
24 (False, {}, {"next": "/here"}, "/not/here", "/here"),
25 (
26 False,
27 {},
28 {"process": "connect"},
29 "/not/here",
30 reverse_lazy("socialaccount_connections"),
31 ),
32 (False, {}, {"process": "connect", "next": "/here"}, "/not/here", "/here"),
33 (True, {"reject_idp_initiated_sso": False}, {}, "/set-by-idp", "/set-by-idp"),
34 (
35 True,
36 {"reject_idp_initiated_sso": False},
37 {},
38 "not-a-url",
39 settings.LOGIN_REDIRECT_URL,
40 ),
41 (True, {}, {}, "/set-by-idp", "/set-by-idp"),
42 ],
43 )
44 def test_acs(
45 request,
46 idp_initiated,
47 db,
48 saml_settings,
49 acs_saml_response_factory,
50 mocked_signature_validation,
51 expected_url,
52 relay_state,
53 state_kwargs,
54 sociallogin_setup_state,
55 adv_settings,
56 settings,
57 ):
58 provider_settings = settings.SOCIALACCOUNT_PROVIDERS["saml"]["APPS"][0]["settings"]
59 advanced = dict(provider_settings["advanced"])
60 advanced.update(adv_settings)
61 provider_settings["advanced"] = advanced
62 process = state_kwargs.setdefault("process", AuthProcess.LOGIN)
63 is_connect = process == AuthProcess.CONNECT
64 if is_connect:
65 client = request.getfixturevalue("auth_client")
66 user = request.getfixturevalue("user")
67 else:
68 client = request.getfixturevalue("client")
69 user = None
70
71 state_id = None
72 if not idp_initiated:
73 state_id = sociallogin_setup_state(client, **state_kwargs)
74
75 data = {"SAMLResponse": acs_saml_response_factory(in_response_to=state_id)}
76 if relay_state is not None:
77 data["RelayState"] = relay_state
78 resp = client.post(
79 reverse("saml_acs", kwargs={"organization_slug": "org"}), data=data
80 )
81 finish_url = reverse("saml_finish_acs", kwargs={"organization_slug": "org"})
82 assert resp.status_code == HTTPStatus.FOUND
83 assert resp["location"] == finish_url
84 resp = client.get(finish_url)
85 if idp_initiated and advanced.get("reject_idp_initiated_sso", True):
86 assert "socialaccount/authentication_error.html" in (
87 t.name for t in resp.templates
88 )
89 else:
90 assert resp["location"] == expected_url
91 account = SocialAccount.objects.get(
92 provider="urn:dev-123.us.auth0.com", uid="dummysamluid"
93 )
94 assert account.extra_data["Role"] == ["view-profile", "manage-account-links"]
95 email = EmailAddress.objects.get(user=account.user)
96 assert email.email == (user.email if is_connect else "[email protected]")
97
98
99 def test_acs_error(client, db, saml_settings):
100 data = {"SAMLResponse": "bad-response"}
101 resp = client.post(
102 reverse("saml_acs", kwargs={"organization_slug": "org"}), data=data
103 )
104 assert resp.status_code == HTTPStatus.FOUND
105 resp = client.get(resp["location"])
106 assert "socialaccount/authentication_error.html" in (t.name for t in resp.templates)
107
108
109 def test_acs_get(client, db, saml_settings):
110 """WHile ACS expects POST, it always redirects and handles the request in
111 the FinishACSView.
112 """
113 resp = client.get(reverse("saml_acs", kwargs={"organization_slug": "org"}))
114 assert resp.status_code == HTTPStatus.FOUND
115 resp = client.get(resp["location"])
116 assert "socialaccount/authentication_error.html" in (t.name for t in resp.templates)
117
118
119 def test_sls_get(client, db, saml_settings):
120 """SLS expects POST"""
121 resp = client.get(reverse("saml_sls", kwargs={"organization_slug": "org"}))
122 assert resp.status_code == HTTPStatus.BAD_REQUEST
123
124
125 def test_login_on_get(client, db, saml_settings):
126 resp = client.get(reverse("saml_login", kwargs={"organization_slug": "org"}))
127 assert resp.status_code == HTTPStatus.OK
128 assertTemplateUsed(resp, "socialaccount/login.html")
129
130
131 def test_login(client, db, saml_settings):
132 resp = client.post(
133 reverse("saml_login", kwargs={"organization_slug": "org"})
134 + "?process=connect&next=/foo"
135 )
136 assert resp.status_code == HTTPStatus.FOUND
137 location = resp["location"]
138 assert location.startswith("https://dev-123.us.auth0.com/samlp/456?SAMLRequest=")
139 resp_query = parse_qs(urlparse(location).query)
140 # We're not using RelayState
141 assert resp_query.get("RelayState") is None
142 # We're using the request ID / InResponseTo for tracking state.
143 state_id = list(client.session[statekit.STATES_SESSION_KEY].keys())[0]
144 assert state_id.startswith("ONELOGIN_")
145 state = client.session[statekit.STATES_SESSION_KEY][state_id][0]
146 assert state == {"process": "connect", "data": None, "next": "/foo"}
147
148
149 def test_metadata(
150 client,
151 db,
152 saml_settings,
153 ):
154 resp = client.get(reverse("saml_metadata", kwargs={"organization_slug": "org"}))
155 assert resp.status_code == HTTPStatus.OK
156 assert resp.content.startswith(
157 b'<?xml version="1.0"?>\n<md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata'
158 )
159
160
161 def test_sls(auth_client, db, saml_settings, user_factory, sls_saml_request):
162 with patch("allauth.account.adapter.DefaultAccountAdapter.logout") as logout_mock:
163 resp = auth_client.get(
164 reverse("saml_sls", kwargs={"organization_slug": "org"})
165 + "?"
166 + urlencode({"SAMLRequest": sls_saml_request})
167 )
168 assert logout_mock.call_count == 1
169 assert resp.status_code == HTTPStatus.FOUND
170 assert resp["location"].startswith(
171 "https://dev-123.us.auth0.com/samlp/456?SAMLResponse="
172 )
173
174
175 @pytest.mark.parametrize(
176 "provider_config",
177 [
178 {
179 "idp": {
180 "entity_id": "dummy",
181 "sso_url": "https://idp.org/sso/",
182 "slo_url": "https://idp.saml.org/slo/",
183 "x509cert": "cert",
184 }
185 },
186 ],
187 )
188 def test_build_saml_config_without_metadata_url(rf, provider_config):
189 request = rf.get("/")
190 config = build_saml_config(request, provider_config, "org")
191 assert config["idp"]["entityId"] == "dummy"
192 assert config["idp"]["x509cert"] == "cert"
193 assert config["idp"]["singleSignOnService"] == {"url": "https://idp.org/sso/"}
194 assert config["idp"]["singleLogoutService"] == {"url": "https://idp.saml.org/slo/"}
195
196
197 @pytest.mark.parametrize(
198 "provider_config",
199 [
200 {
201 "idp": {
202 "entity_id": "dummy",
203 "metadata_url": "https://idp.org/sso/",
204 }
205 },
206 {
207 "idp": {
208 "entity_id": "dummy",
209 "metadata_url": "https://idp.org/sso/",
210 },
211 "sp": {"entity_id": "dummy-sp-entity-id"},
212 },
213 ],
214 )
215 def test_build_saml_config(rf, provider_config):
216 request = rf.get("/")
217 with patch(
218 "onelogin.saml2.idp_metadata_parser.OneLogin_Saml2_IdPMetadataParser.parse_remote"
219 ) as parse_mock:
220 parse_mock.return_value = {
221 "idp": {
222 "entityId": "dummy",
223 "singleSignOnService": {"url": "https://idp.org/sso/"},
224 "singleLogoutService": {"url": "https://idp.saml.org/slo/"},
225 "x509cert": "cert",
226 }
227 }
228 config = build_saml_config(request, provider_config, "org")
229
230 assert config["idp"]["entityId"] == "dummy"
231 assert config["idp"]["x509cert"] == "cert"
232 assert config["idp"]["singleSignOnService"] == {"url": "https://idp.org/sso/"}
233 assert config["idp"]["singleLogoutService"] == {"url": "https://idp.saml.org/slo/"}
234 metadata_url = request.build_absolute_uri(reverse("saml_metadata", args=["org"]))
235 sp_entity_id = provider_config.get("sp", {}).get("entity_id")
236 if sp_entity_id:
237 assert config["sp"]["entityId"] == sp_entity_id
238 else:
239 assert config["sp"]["entityId"] == metadata_url
240
241
242 @pytest.mark.parametrize(
243 "data, result, uid",
244 [
245 (
246 {"urn:oasis:names:tc:SAML:attribute:subject-id": ["123"]},
247 {"uid": "123", "email": "[email protected]"},
248 "123",
249 ),
250 ({}, {"email": "[email protected]"}, "[email protected]"),
251 ],
252 )
253 def test_extract_attributes(db, data, result, uid, settings):
254 settings.SOCIALACCOUNT_PROVIDERS = {
255 "saml": {
256 "APPS": [
257 {
258 "client_id": "org",
259 "provider_id": "urn:dev-123.us.auth0.com",
260 }
261 ]
262 }
263 }
264 provider = get_adapter().get_provider(request=None, provider="saml")
265 onelogin_data = Mock()
266 onelogin_data.get_attributes.return_value = data
267 onelogin_data.get_nameid.return_value = "[email protected]"
268 onelogin_data.get_nameid_format.return_value = (
269 "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"
270 )
271 assert provider._extract(onelogin_data) == result
272 assert provider.extract_uid(onelogin_data) == uid