| 1 |
import base64 |
| 2 |
import hashlib |
| 3 |
import json |
| 4 |
import random |
| 5 |
import requests |
| 6 |
import uuid |
| 7 |
import warnings |
| 8 |
from http import HTTPStatus |
| 9 |
from urllib.parse import parse_qs, urlparse |
| 10 |
|
| 11 |
from django.conf import settings |
| 12 |
from django.contrib.auth import get_user_model |
| 13 |
from django.test import RequestFactory, TestCase |
| 14 |
from django.test.utils import override_settings |
| 15 |
from django.urls import reverse |
| 16 |
from django.utils.http import urlencode |
| 17 |
|
| 18 |
import jwt |
| 19 |
|
| 20 |
import allauth.app_settings |
| 21 |
from allauth.account.models import EmailAddress |
| 22 |
from allauth.account.utils import user_email, user_username |
| 23 |
from allauth.socialaccount import app_settings |
| 24 |
from allauth.socialaccount.adapter import get_adapter |
| 25 |
from allauth.socialaccount.models import SocialAccount, SocialApp |
| 26 |
from tests.mocking import MockedResponse, mocked_response |
| 27 |
|
| 28 |
|
| 29 |
def setup_app(provider_id): |
| 30 |
request = RequestFactory().get("/") |
| 31 |
apps = get_adapter().list_apps(request, provider_id) |
| 32 |
if apps: |
| 33 |
return apps[0] |
| 34 |
|
| 35 |
app = SocialApp.objects.create( |
| 36 |
provider=provider_id, |
| 37 |
name=provider_id, |
| 38 |
client_id="app123id", |
| 39 |
key=provider_id, |
| 40 |
secret="dummy", |
| 41 |
) |
| 42 |
if allauth.app_settings.SITES_ENABLED: |
| 43 |
from django.contrib.sites.models import Site |
| 44 |
|
| 45 |
app.sites.add(Site.objects.get_current()) |
| 46 |
return app |
| 47 |
|
| 48 |
|
| 49 |
class OAuthTestsMixin: |
| 50 |
provider_id: str |
| 51 |
|
| 52 |
def get_mocked_response(self): |
| 53 |
pass |
| 54 |
|
| 55 |
def get_expected_to_str(self): |
| 56 |
raise NotImplementedError |
| 57 |
|
| 58 |
def setUp(self): |
| 59 |
super().setUp() |
| 60 |
self.app = setup_app(self.provider_id) |
| 61 |
request = RequestFactory().get("/") |
| 62 |
self.provider = self.app.get_provider(request) |
| 63 |
|
| 64 |
@override_settings(SOCIALACCOUNT_AUTO_SIGNUP=False) |
| 65 |
def test_login(self): |
| 66 |
resp_mocks = self.get_mocked_response() |
| 67 |
if resp_mocks is None: |
| 68 |
warnings.warn(f"Cannot test provider {self.provider.id}, no oauth mock") |
| 69 |
return |
| 70 |
resp = self.login(resp_mocks) |
| 71 |
self.assertRedirects(resp, reverse("socialaccount_signup")) |
| 72 |
resp = self.client.get(reverse("socialaccount_signup")) |
| 73 |
sociallogin = resp.context["form"].sociallogin |
| 74 |
data = dict( |
| 75 |
email=user_email(sociallogin.user), |
| 76 |
username=str(random.randrange(1000, 10000000)), |
| 77 |
) |
| 78 |
resp = self.client.post(reverse("socialaccount_signup"), data=data) |
| 79 |
self.assertRedirects(resp, "/accounts/profile/", fetch_redirect_response=False) |
| 80 |
user = resp.context["user"] |
| 81 |
self.assertFalse(user.has_usable_password()) |
| 82 |
account = SocialAccount.objects.get(user=user, provider=self.provider.id) |
| 83 |
provider_account = account.get_provider_account() |
| 84 |
self.assertEqual(provider_account.to_str(), self.get_expected_to_str()) |
| 85 |
# The following lines don't actually test that much, but at least |
| 86 |
# we make sure that the code is hit. |
| 87 |
provider_account.get_avatar_url() |
| 88 |
provider_account.get_profile_url() |
| 89 |
provider_account.get_brand() |
| 90 |
|
| 91 |
@override_settings( |
| 92 |
SOCIALACCOUNT_AUTO_SIGNUP=True, |
| 93 |
SOCIALACCOUNT_EMAIL_REQUIRED=False, |
| 94 |
ACCOUNT_EMAIL_REQUIRED=False, |
| 95 |
) |
| 96 |
def test_auto_signup(self): |
| 97 |
resp_mocks = self.get_mocked_response() |
| 98 |
if not resp_mocks: |
| 99 |
warnings.warn(f"Cannot test provider {self.provider.id}, no oauth mock") |
| 100 |
return |
| 101 |
resp = self.login(resp_mocks) |
| 102 |
self.assertRedirects(resp, "/accounts/profile/", fetch_redirect_response=False) |
| 103 |
self.assertFalse(resp.context["user"].has_usable_password()) |
| 104 |
|
| 105 |
def login(self, resp_mocks, process="login"): |
| 106 |
with mocked_response( |
| 107 |
MockedResponse( |
| 108 |
HTTPStatus.OK, |
| 109 |
"oauth_token=token&oauth_token_secret=psst", |
| 110 |
{"content-type": "text/html"}, |
| 111 |
) |
| 112 |
): |
| 113 |
resp = self.client.post( |
| 114 |
reverse(f"{self.provider.id}_login") |
| 115 |
+ "?" |
| 116 |
+ urlencode(dict(process=process)) |
| 117 |
) |
| 118 |
p = urlparse(resp["location"]) |
| 119 |
q = parse_qs(p.query) |
| 120 |
complete_url = reverse(f"{self.provider.id}_callback") |
| 121 |
self.assertGreater(q["oauth_callback"][0].find(complete_url), 0) |
| 122 |
with mocked_response(self.get_access_token_response(), *resp_mocks): |
| 123 |
resp = self.client.get(complete_url) |
| 124 |
return resp |
| 125 |
|
| 126 |
def get_access_token_response(self): |
| 127 |
return MockedResponse( |
| 128 |
HTTPStatus.OK, |
| 129 |
"oauth_token=token&oauth_token_secret=psst", |
| 130 |
{"content-type": "text/html"}, |
| 131 |
) |
| 132 |
|
| 133 |
def test_authentication_error(self): |
| 134 |
resp = self.client.get(reverse(f"{self.provider.id}_callback")) |
| 135 |
assert resp.status_code == HTTPStatus.UNAUTHORIZED |
| 136 |
template_ext = getattr(settings, "ACCOUNT_TEMPLATE_EXTENSION", "html") |
| 137 |
self.assertTemplateUsed( |
| 138 |
resp, f"socialaccount/authentication_error.{template_ext}" |
| 139 |
) |
| 140 |
|
| 141 |
|
| 142 |
# For backward-compatibility with third-party provider tests that call |
| 143 |
# create_oauth_tests() rather than using the mixin directly. |
| 144 |
def create_oauth_tests(provider): |
| 145 |
class Class(OAuthTestsMixin, TestCase): |
| 146 |
provider_id = provider.id |
| 147 |
|
| 148 |
Class.__name__ = f"OAuthTests_{provider.id}" |
| 149 |
return Class |
| 150 |
|
| 151 |
|
| 152 |
class OAuth2TestsMixin: |
| 153 |
provider_id: str |
| 154 |
|
| 155 |
def get_mocked_response(self): |
| 156 |
pass |
| 157 |
|
| 158 |
def get_expected_to_str(self): |
| 159 |
raise NotImplementedError |
| 160 |
|
| 161 |
def get_access_token(self) -> str: |
| 162 |
return "testac" |
| 163 |
|
| 164 |
def get_refresh_token(self) -> str: |
| 165 |
return "testrf" |
| 166 |
|
| 167 |
def get_login_response_json(self, with_refresh_token=True): |
| 168 |
response = { |
| 169 |
"uid": uuid.uuid4().hex, |
| 170 |
"access_token": self.get_access_token(), |
| 171 |
} |
| 172 |
if with_refresh_token: |
| 173 |
response["refresh_token"] = self.get_refresh_token() |
| 174 |
return json.dumps(response) |
| 175 |
|
| 176 |
def mocked_response(self, *responses): |
| 177 |
return mocked_response(*responses) |
| 178 |
|
| 179 |
def setUp(self): |
| 180 |
super().setUp() |
| 181 |
self.setup_provider() |
| 182 |
|
| 183 |
def setup_provider(self): |
| 184 |
self.app = setup_app(self.provider_id) |
| 185 |
self.request = RequestFactory().get("/") |
| 186 |
self.provider = self.app.get_provider(self.request) |
| 187 |
|
| 188 |
def test_provider_has_no_pkce_params(self): |
| 189 |
provider_settings = app_settings.PROVIDERS.get(self.app.provider, {}) |
| 190 |
provider_settings_with_pkce_set = provider_settings.copy() |
| 191 |
provider_settings_with_pkce_set["OAUTH_PKCE_ENABLED"] = False |
| 192 |
|
| 193 |
with self.settings( |
| 194 |
SOCIALACCOUNT_PROVIDERS={self.app.provider: provider_settings_with_pkce_set} |
| 195 |
): |
| 196 |
self.assertEqual(self.provider.get_pkce_params(), {}) |
| 197 |
|
| 198 |
def test_provider_has_pkce_params(self): |
| 199 |
provider_settings = app_settings.PROVIDERS.get(self.app.provider, {}) |
| 200 |
provider_settings_with_pkce_set = provider_settings.copy() |
| 201 |
provider_settings_with_pkce_set["OAUTH_PKCE_ENABLED"] = True |
| 202 |
|
| 203 |
with self.settings( |
| 204 |
SOCIALACCOUNT_PROVIDERS={self.app.provider: provider_settings_with_pkce_set} |
| 205 |
): |
| 206 |
pkce_params = self.provider.get_pkce_params() |
| 207 |
self.assertEqual( |
| 208 |
set(pkce_params.keys()), |
| 209 |
{"code_challenge", "code_challenge_method", "code_verifier"}, |
| 210 |
) |
| 211 |
hashed_verifier = hashlib.sha256( |
| 212 |
pkce_params["code_verifier"].encode("ascii") |
| 213 |
) |
| 214 |
code_challenge = base64.urlsafe_b64encode(hashed_verifier.digest()) |
| 215 |
code_challenge_without_padding = code_challenge.rstrip(b"=") |
| 216 |
assert pkce_params["code_challenge"] == code_challenge_without_padding |
| 217 |
|
| 218 |
@override_settings(SOCIALACCOUNT_AUTO_SIGNUP=False) |
| 219 |
def test_login(self): |
| 220 |
resp_mock = self.get_mocked_response() |
| 221 |
if not resp_mock: |
| 222 |
warnings.warn(f"Cannot test provider {self.provider.id}, no oauth mock") |
| 223 |
return |
| 224 |
resp = self.login( |
| 225 |
resp_mock, |
| 226 |
) |
| 227 |
self.assertRedirects(resp, reverse("socialaccount_signup")) |
| 228 |
|
| 229 |
@override_settings(SOCIALACCOUNT_AUTO_SIGNUP=False) |
| 230 |
def test_login_with_pkce_disabled(self): |
| 231 |
provider_settings = app_settings.PROVIDERS.get(self.app.provider, {}) |
| 232 |
provider_settings_with_pkce_disabled = provider_settings.copy() |
| 233 |
provider_settings_with_pkce_disabled["OAUTH_PKCE_ENABLED"] = False |
| 234 |
|
| 235 |
with self.settings( |
| 236 |
SOCIALACCOUNT_PROVIDERS={ |
| 237 |
self.app.provider: provider_settings_with_pkce_disabled |
| 238 |
} |
| 239 |
): |
| 240 |
resp_mock = self.get_mocked_response() |
| 241 |
if not resp_mock: |
| 242 |
warnings.warn(f"Cannot test provider {self.provider.id}, no oauth mock") |
| 243 |
return |
| 244 |
resp = self.login( |
| 245 |
resp_mock, |
| 246 |
) |
| 247 |
self.assertRedirects(resp, reverse("socialaccount_signup")) |
| 248 |
|
| 249 |
@override_settings(SOCIALACCOUNT_AUTO_SIGNUP=False) |
| 250 |
def test_login_with_pkce_enabled(self): |
| 251 |
provider_settings = app_settings.PROVIDERS.get(self.app.provider, {}) |
| 252 |
provider_settings_with_pkce_enabled = provider_settings.copy() |
| 253 |
provider_settings_with_pkce_enabled["OAUTH_PKCE_ENABLED"] = True |
| 254 |
with self.settings( |
| 255 |
SOCIALACCOUNT_PROVIDERS={ |
| 256 |
self.app.provider: provider_settings_with_pkce_enabled |
| 257 |
} |
| 258 |
): |
| 259 |
resp_mock = self.get_mocked_response() |
| 260 |
if not resp_mock: |
| 261 |
warnings.warn(f"Cannot test provider {self.provider.id}, no oauth mock") |
| 262 |
return |
| 263 |
|
| 264 |
resp = self.login( |
| 265 |
resp_mock, |
| 266 |
) |
| 267 |
self.assertRedirects(resp, reverse("socialaccount_signup")) |
| 268 |
|
| 269 |
@override_settings(SOCIALACCOUNT_STORE_TOKENS=True) |
| 270 |
def test_account_tokens(self, multiple_login=False): |
| 271 |
email = "[email protected]" |
| 272 |
user = get_user_model()(is_active=True) |
| 273 |
user_email(user, email) |
| 274 |
user_username(user, "user") |
| 275 |
user.set_password("test") |
| 276 |
user.save() |
| 277 |
EmailAddress.objects.create(user=user, email=email, primary=True, verified=True) |
| 278 |
self.client.login(username=user.username, password="test") |
| 279 |
self.login(self.get_mocked_response(), process="connect") |
| 280 |
if multiple_login: |
| 281 |
self.login( |
| 282 |
self.get_mocked_response(), |
| 283 |
with_refresh_token=False, |
| 284 |
process="connect", |
| 285 |
) |
| 286 |
# get account |
| 287 |
sa = SocialAccount.objects.filter( |
| 288 |
user=user, provider=self.provider.app.provider_id or self.provider.id |
| 289 |
).get() |
| 290 |
provider_account = sa.get_provider_account() |
| 291 |
self.assertEqual(provider_account.to_str(), self.get_expected_to_str()) |
| 292 |
# The following lines don't actually test that much, but at least |
| 293 |
# we make sure that the code is hit. |
| 294 |
provider_account.get_avatar_url() |
| 295 |
provider_account.get_profile_url() |
| 296 |
provider_account.get_brand() |
| 297 |
# get token |
| 298 |
if self.app: |
| 299 |
t = sa.socialtoken_set.get() |
| 300 |
# verify access_token and refresh_token |
| 301 |
self.assertEqual(self.get_access_token(), t.token) |
| 302 |
resp = json.loads(self.get_login_response_json(with_refresh_token=True)) |
| 303 |
if "refresh_token" in resp: |
| 304 |
refresh_token = resp.get("refresh_token") |
| 305 |
elif "refreshToken" in resp: |
| 306 |
refresh_token = resp.get("refreshToken") |
| 307 |
else: |
| 308 |
refresh_token = "" |
| 309 |
self.assertEqual(t.token_secret, refresh_token) |
| 310 |
|
| 311 |
@override_settings(SOCIALACCOUNT_STORE_TOKENS=True) |
| 312 |
def test_account_refresh_token_saved_next_login(self): |
| 313 |
""" |
| 314 |
fails if a login missing a refresh token, deletes the previously |
| 315 |
saved refresh token. Systems such as google's oauth only send |
| 316 |
a refresh token on first login. |
| 317 |
""" |
| 318 |
self.test_account_tokens(multiple_login=True) |
| 319 |
|
| 320 |
def login(self, resp_mock=None, process="login", with_refresh_token=True): |
| 321 |
with self.mocked_response(): |
| 322 |
resp = self.client.post( |
| 323 |
self.provider.get_login_url(self.request, process=process) |
| 324 |
) |
| 325 |
p = urlparse(resp["location"]) |
| 326 |
q = parse_qs(p.query) |
| 327 |
|
| 328 |
pkce_enabled = app_settings.PROVIDERS.get(self.app.provider, {}).get( |
| 329 |
"OAUTH_PKCE_ENABLED", self.provider.pkce_enabled_default |
| 330 |
) |
| 331 |
|
| 332 |
self.assertEqual("code_challenge" in q, pkce_enabled) |
| 333 |
self.assertEqual("code_challenge_method" in q, pkce_enabled) |
| 334 |
if pkce_enabled: |
| 335 |
code_challenge = q["code_challenge"][0] |
| 336 |
self.assertEqual(q["code_challenge_method"][0], "S256") |
| 337 |
|
| 338 |
complete_url = self.provider.get_callback_url() |
| 339 |
self.assertGreater(q["redirect_uri"][0].find(complete_url), 0) |
| 340 |
response_json = self.get_login_response_json( |
| 341 |
with_refresh_token=with_refresh_token |
| 342 |
) |
| 343 |
|
| 344 |
if isinstance(resp_mock, list): |
| 345 |
resp_mocks = resp_mock |
| 346 |
elif resp_mock is None: |
| 347 |
resp_mocks = [] |
| 348 |
else: |
| 349 |
resp_mocks = [resp_mock] |
| 350 |
|
| 351 |
with self.mocked_response( |
| 352 |
MockedResponse( |
| 353 |
HTTPStatus.OK, response_json, {"content-type": "application/json"} |
| 354 |
), |
| 355 |
*resp_mocks, |
| 356 |
): |
| 357 |
resp = self.client.get(complete_url, self.get_complete_parameters(q)) |
| 358 |
|
| 359 |
# Find the access token POST request, and assert that it contains |
| 360 |
# the correct code_verifier if and only if PKCE is enabled |
| 361 |
request_calls = requests.Session.request.call_args_list |
| 362 |
for args, kwargs in request_calls: |
| 363 |
data = kwargs.get("data", {}) |
| 364 |
if ( |
| 365 |
args[0] == "POST" |
| 366 |
and isinstance(data, dict) |
| 367 |
and data.get("redirect_uri", "").endswith(complete_url) |
| 368 |
): |
| 369 |
self.assertEqual("code_verifier" in data, pkce_enabled) |
| 370 |
|
| 371 |
if pkce_enabled: |
| 372 |
hashed_code_verifier = hashlib.sha256( |
| 373 |
data["code_verifier"].encode("ascii") |
| 374 |
) |
| 375 |
expected_code_challenge = ( |
| 376 |
base64.urlsafe_b64encode(hashed_code_verifier.digest()) |
| 377 |
.rstrip(b"=") |
| 378 |
.decode() |
| 379 |
) |
| 380 |
self.assertEqual(code_challenge, expected_code_challenge) |
| 381 |
|
| 382 |
return resp |
| 383 |
|
| 384 |
def get_complete_parameters(self, q): |
| 385 |
return {"code": "test", "state": q["state"][0]} |
| 386 |
|
| 387 |
def test_authentication_error(self): |
| 388 |
resp = self.client.get(self.provider.get_callback_url()) |
| 389 |
template_ext = getattr(settings, "ACCOUNT_TEMPLATE_EXTENSION", "html") |
| 390 |
self.assertTemplateUsed( |
| 391 |
resp, f"socialaccount/authentication_error.{template_ext}" |
| 392 |
) |
| 393 |
|
| 394 |
|
| 395 |
class OpenIDConnectTests(OAuth2TestsMixin): |
| 396 |
oidc_info_content = { |
| 397 |
"authorization_endpoint": "/login", |
| 398 |
"userinfo_endpoint": "/userinfo", |
| 399 |
"token_endpoint": "/token", |
| 400 |
"jwks_uri": "/jwks", |
| 401 |
"issuer": "https://issuer.example.com", |
| 402 |
} |
| 403 |
userinfo_content = { |
| 404 |
"picture": "https://secure.gravatar.com/avatar/123", |
| 405 |
"email": "[email protected]", |
| 406 |
"sub": 2187, |
| 407 |
"identities": [], |
| 408 |
"name": "Ness", |
| 409 |
} |
| 410 |
id_token = { |
| 411 |
"email": "[email protected]", |
| 412 |
"sub": 2187, |
| 413 |
"preferred_username": "wizard", |
| 414 |
"iss": "https://issuer.example.com", |
| 415 |
"aud": "app123id", |
| 416 |
} |
| 417 |
|
| 418 |
def get_id_token(self) -> dict: |
| 419 |
return self.id_token |
| 420 |
|
| 421 |
def get_login_response_json(self, with_refresh_token=True) -> str: |
| 422 |
data = json.loads( |
| 423 |
super().get_login_response_json(with_refresh_token=with_refresh_token) |
| 424 |
) |
| 425 |
data["id_token"] = jwt.encode(self.get_id_token(), "secret") |
| 426 |
return json.dumps(data) |
| 427 |
|
| 428 |
def mocked_response(self, *responses): |
| 429 |
return mocked_response(*responses, callback=self._mocked_responses) |
| 430 |
|
| 431 |
def get_expected_to_str(self): |
| 432 |
return "[email protected]" |
| 433 |
|
| 434 |
def setup_provider(self): |
| 435 |
self.app = setup_app(self.provider_id) |
| 436 |
self.app.provider_id = self.provider_id |
| 437 |
self.app.provider = "openid_connect" |
| 438 |
self.app.settings = { |
| 439 |
"server_url": "https://unittest.example.com", |
| 440 |
} |
| 441 |
self.app.save() |
| 442 |
self.request = RequestFactory().get("/") |
| 443 |
self.provider = self.app.get_provider(self.request) |
| 444 |
|
| 445 |
def get_mocked_response(self): |
| 446 |
# Enable test_login in OAuth2TestsMixin, but this response mock is unused |
| 447 |
return True |
| 448 |
|
| 449 |
def _mocked_responses(self, url, *args, **kwargs): |
| 450 |
if url.endswith("/.well-known/openid-configuration"): |
| 451 |
return MockedResponse(HTTPStatus.OK, json.dumps(self.oidc_info_content)) |
| 452 |
elif url.endswith("/userinfo"): |
| 453 |
return MockedResponse(HTTPStatus.OK, json.dumps(self.userinfo_content)) |
| 454 |
|
| 455 |
@override_settings(SOCIALACCOUNT_AUTO_SIGNUP=True) |
| 456 |
def test_login_auto_signup(self): |
| 457 |
resp = self.login() |
| 458 |
self.assertRedirects(resp, "/accounts/profile/", fetch_redirect_response=False) |
| 459 |
sa = SocialAccount.objects.get(provider=self.app.provider_id) |
| 460 |
expected_data = {"id_token": self.id_token} |
| 461 |
if self.app.settings.get("fetch_userinfo", True): |
| 462 |
expected_data["userinfo"] = self.userinfo_content |
| 463 |
self.assertDictEqual(sa.extra_data, expected_data) |
| 464 |
|
| 465 |
def test_404_on_unknown_provider_id(self): |
| 466 |
""" |
| 467 |
Make sure that OIDC endpoints hit with an invalid provider_id |
| 468 |
not corresponding to any configured social "apps" returns a 404 |
| 469 |
instead of an unhandled SocialApp.DoesNotExist. |
| 470 |
""" |
| 471 |
|
| 472 |
# we can't use self.provider.get_login_url as we intentionally |
| 473 |
# do not want to use the configured provider's ID, so let's inline |
| 474 |
# OpenIDConnectProvider.get_login_url |
| 475 |
login_url = reverse( |
| 476 |
f"{self.app.provider}_login", |
| 477 |
kwargs={ |
| 478 |
# intentionally invalidate the ID |
| 479 |
"provider_id": f"{self.app.provider_id}-invalid" |
| 480 |
}, |
| 481 |
) |
| 482 |
|
| 483 |
resp = self.client.post(login_url) |
| 484 |
|
| 485 |
self.assertEqual(resp.status_code, HTTPStatus.NOT_FOUND) |
| 486 |
|
| 487 |
# same with the callback endpoint - inlining OpenIDConnectProvider.get_callback_url |
| 488 |
callback_url = reverse( |
| 489 |
f"{self.app.provider}_callback", |
| 490 |
kwargs={ |
| 491 |
# intentionally invalidate the ID |
| 492 |
"provider_id": f"{self.app.provider_id}-invalid" |
| 493 |
}, |
| 494 |
) |
| 495 |
|
| 496 |
# note: callback is a GET endpoint |
| 497 |
resp = self.client.get(callback_url) |
| 498 |
|
| 499 |
self.assertEqual(resp.status_code, HTTPStatus.NOT_FOUND) |