| 1 |
import base64 |
| 2 |
from datetime import timedelta |
| 3 |
from http import HTTPStatus |
| 4 |
from unittest.mock import ANY, patch |
| 5 |
from urllib.parse import parse_qs, urlparse |
| 6 |
|
| 7 |
from django.urls import reverse |
| 8 |
from django.utils import timezone |
| 9 |
from django.utils.http import urlencode |
| 10 |
|
| 11 |
import jwt |
| 12 |
import pytest |
| 13 |
from pytest_django.asserts import assertTemplateUsed |
| 14 |
|
| 15 |
from allauth.account.models import EmailAddress |
| 16 |
from allauth.idp.oidc.adapter import get_adapter |
| 17 |
from allauth.idp.oidc.models import Token |
| 18 |
|
| 19 |
from .internal.test_tokens import PREVIOUS_PRIVATE_KEY |
| 20 |
|
| 21 |
|
| 22 |
@pytest.mark.parametrize( |
| 23 |
"scopes,has_secondary_email,choose_secondary_email", |
| 24 |
[ |
| 25 |
(("openid",), False, False), |
| 26 |
(("openid", "email"), False, False), |
| 27 |
(("openid", "email"), True, True), |
| 28 |
], |
| 29 |
) |
| 30 |
def test_userinfo( |
| 31 |
client, |
| 32 |
oidc_client, |
| 33 |
user, |
| 34 |
access_token_factory, |
| 35 |
scopes, |
| 36 |
has_secondary_email, |
| 37 |
choose_secondary_email, |
| 38 |
email_factory, |
| 39 |
): |
| 40 |
# Pass along ID token as hint |
| 41 |
token, token_instance = access_token_factory(oidc_client, user, scopes=scopes) |
| 42 |
if has_secondary_email: |
| 43 |
email = email_factory() |
| 44 |
EmailAddress.objects.create( |
| 45 |
user=user, email=email, verified=True, primary=False |
| 46 |
) |
| 47 |
token_instance.set_scope_email(email) |
| 48 |
token_instance.save() |
| 49 |
expected_email = email if choose_secondary_email else user.email |
| 50 |
else: |
| 51 |
expected_email = user.email |
| 52 |
resp = client.get( |
| 53 |
reverse("idp:oidc:userinfo"), |
| 54 |
HTTP_AUTHORIZATION=f"Bearer {token}", |
| 55 |
) |
| 56 |
assert resp.status_code == HTTPStatus.OK |
| 57 |
data = resp.json() |
| 58 |
assert data["sub"] == get_adapter().get_user_sub(oidc_client, user) |
| 59 |
if "email" in scopes: |
| 60 |
assert data["email"] == expected_email |
| 61 |
assert data["email_verified"] is True |
| 62 |
else: |
| 63 |
assert "email" not in data |
| 64 |
|
| 65 |
|
| 66 |
@pytest.mark.parametrize( |
| 67 |
"resources", |
| 68 |
[ |
| 69 |
[], |
| 70 |
["https://api.example.com/a"], |
| 71 |
["https://api.example.com/a", "https://api.example.com/b"], |
| 72 |
], |
| 73 |
) |
| 74 |
@pytest.mark.parametrize("access_token_format", ["jwt", "opaque"]) |
| 75 |
@pytest.mark.parametrize("basic_auth", (False, True)) |
| 76 |
def test_client_credentials( |
| 77 |
client, |
| 78 |
oidc_client, |
| 79 |
oidc_client_secret, |
| 80 |
access_token_format, |
| 81 |
settings, |
| 82 |
basic_auth, |
| 83 |
resources, |
| 84 |
): |
| 85 |
settings.IDP_OIDC_ACCESS_TOKEN_FORMAT = access_token_format |
| 86 |
data = { |
| 87 |
"scope": "profile email", |
| 88 |
"grant_type": "client_credentials", |
| 89 |
} |
| 90 |
if resources: |
| 91 |
data["resource"] = resources |
| 92 |
|
| 93 |
post_kwargs = {} |
| 94 |
if not basic_auth: |
| 95 |
data.update( |
| 96 |
{ |
| 97 |
"client_id": oidc_client.id, |
| 98 |
"client_secret": oidc_client_secret, |
| 99 |
} |
| 100 |
) |
| 101 |
else: |
| 102 |
credentials = base64.b64encode( |
| 103 |
f"{oidc_client.id}:{oidc_client_secret}".encode() |
| 104 |
).decode() |
| 105 |
post_kwargs = {"HTTP_AUTHORIZATION": f"Basic {credentials}"} |
| 106 |
|
| 107 |
resp = client.post(reverse("idp:oidc:token"), data=data, **post_kwargs) |
| 108 |
assert resp.status_code == HTTPStatus.OK |
| 109 |
data = resp.json() |
| 110 |
assert data == { |
| 111 |
"access_token": ANY, |
| 112 |
"expires_in": 3600, |
| 113 |
"scope": "profile email", |
| 114 |
"token_type": "Bearer", |
| 115 |
} |
| 116 |
token = Token.objects.lookup(Token.Type.ACCESS_TOKEN, data["access_token"]) |
| 117 |
assert token.client == oidc_client |
| 118 |
assert token.get_scopes() == ["profile", "email"] |
| 119 |
assert set(token.get_resources()) == set(resources) |
| 120 |
|
| 121 |
if access_token_format == "jwt": |
| 122 |
decoded = jwt.decode(data["access_token"], options={"verify_signature": False}) |
| 123 |
expected_decoded = { |
| 124 |
"client_id": oidc_client.id, |
| 125 |
"exp": ANY, |
| 126 |
"iat": ANY, |
| 127 |
"iss": "http://testserver", |
| 128 |
"jti": ANY, |
| 129 |
"scope": "profile email", |
| 130 |
"token_use": "access", |
| 131 |
} |
| 132 |
if resources: |
| 133 |
expected_decoded["aud"] = resources |
| 134 |
assert decoded == expected_decoded |
| 135 |
|
| 136 |
|
| 137 |
def test_client_secret_basic_invalid(client, oidc_client): |
| 138 |
credentials = base64.b64encode(f"{oidc_client.id}:wrong-secret".encode()).decode() |
| 139 |
resp = client.post( |
| 140 |
reverse("idp:oidc:token"), |
| 141 |
data={ |
| 142 |
"scope": "profile", |
| 143 |
"grant_type": "client_credentials", |
| 144 |
}, |
| 145 |
HTTP_AUTHORIZATION=f"Basic {credentials}", |
| 146 |
) |
| 147 |
assert resp.status_code == HTTPStatus.UNAUTHORIZED |
| 148 |
|
| 149 |
|
| 150 |
def test_password_grant_is_blocked( |
| 151 |
client, oidc_client, oidc_client_secret, user, user_password |
| 152 |
): |
| 153 |
resp = client.post( |
| 154 |
reverse("idp:oidc:token"), |
| 155 |
data={ |
| 156 |
"client_id": oidc_client.id, |
| 157 |
"client_secret": oidc_client_secret, |
| 158 |
# These are valid credentials. |
| 159 |
"username": user.username, |
| 160 |
"password": user_password, |
| 161 |
"scope": "profile email", |
| 162 |
"grant_type": "password", |
| 163 |
}, |
| 164 |
) |
| 165 |
# We don't crash, but also don't grant. |
| 166 |
assert resp.status_code == HTTPStatus.BAD_REQUEST |
| 167 |
assert resp.json() == { |
| 168 |
"error": "invalid_grant", |
| 169 |
"error_description": "Invalid credentials given.", |
| 170 |
} |
| 171 |
|
| 172 |
|
| 173 |
@pytest.mark.parametrize( |
| 174 |
"resources", |
| 175 |
[ |
| 176 |
[], |
| 177 |
["https://api.example.com/a"], |
| 178 |
["https://api.example.com/a", "https://api.example.com/b"], |
| 179 |
], |
| 180 |
) |
| 181 |
def test_implicit_grant_flow(auth_client, user, oidc_client, enable_cache, resources): |
| 182 |
redirect_uri = oidc_client.get_redirect_uris()[0] |
| 183 |
scopes = ["openid", "profile"] |
| 184 |
data = { |
| 185 |
"client_id": oidc_client.id, |
| 186 |
"response_type": "token", |
| 187 |
"scope": " ".join(scopes), |
| 188 |
"nonce": "some-nonce", |
| 189 |
"state": "some-state", |
| 190 |
"redirect_uri": redirect_uri, |
| 191 |
} |
| 192 |
if resources: |
| 193 |
data["resource"] = resources |
| 194 |
resp = auth_client.get( |
| 195 |
reverse("idp:oidc:authorization") + "?" + urlencode(data, doseq=True) |
| 196 |
) |
| 197 |
assert resp.status_code == HTTPStatus.OK |
| 198 |
assertTemplateUsed(resp, "idp/oidc/authorization_form.html") |
| 199 |
resp = auth_client.post( |
| 200 |
reverse("idp:oidc:authorization"), |
| 201 |
{ |
| 202 |
"scopes": scopes, |
| 203 |
"action": "grant", |
| 204 |
"request": resp.context["form"]["request"].value(), |
| 205 |
}, |
| 206 |
) |
| 207 |
# "https://client/callback#access_token=baI5uc9m5JWc6afKqaZ9eymeOrq1hz&expires_in=3600&token_type=Bearer&scope=openid+profile&state=some-state" |
| 208 |
assert resp.status_code == HTTPStatus.FOUND |
| 209 |
parts = urlparse(resp["location"]) |
| 210 |
data = parse_qs(parts.fragment) |
| 211 |
assert data == { |
| 212 |
"access_token": ANY, |
| 213 |
"expires_in": ["3600"], |
| 214 |
"scope": ["openid profile"], |
| 215 |
"token_type": ["Bearer"], |
| 216 |
"state": ["some-state"], |
| 217 |
} |
| 218 |
token = Token.objects.lookup(Token.Type.ACCESS_TOKEN, data["access_token"][0]) |
| 219 |
assert set(token.get_resources()) == set(resources) |
| 220 |
|
| 221 |
|
| 222 |
def test_userinfo_access_token_as_query( |
| 223 |
client, oidc_client, user, access_token_factory |
| 224 |
): |
| 225 |
# Pass along ID token as hint |
| 226 |
token, _ = access_token_factory(oidc_client, user, scopes=["openid"]) |
| 227 |
resp = client.get( |
| 228 |
f"{reverse('idp:oidc:userinfo')}?{urlencode({'access_token': token})}", |
| 229 |
) |
| 230 |
assert resp.status_code == HTTPStatus.UNAUTHORIZED |
| 231 |
|
| 232 |
|
| 233 |
def test_jwks_view(client, settings): |
| 234 |
settings.IDP_OIDC_JWKS_CACHE_CONTROL = 4711 |
| 235 |
resp = client.get(reverse("idp:oidc:jwks")) |
| 236 |
assert resp.status_code == HTTPStatus.OK |
| 237 |
assert resp.json() == { |
| 238 |
"keys": [{"e": ANY, "key_ops": ["verify"], "kid": ANY, "kty": "RSA", "n": ANY}] |
| 239 |
} |
| 240 |
assert resp["Cache-Control"] == "max-age=4711, must-revalidate" |
| 241 |
|
| 242 |
|
| 243 |
@pytest.mark.parametrize("expires_in,key_count", [(-60, 1), (60, 2)]) |
| 244 |
def test_jwks_view_skips_expired_keys(client, settings, key_count, expires_in): |
| 245 |
settings.USE_TZ = True |
| 246 |
settings.IDP_OIDC_PRIVATE_KEYS = [ |
| 247 |
{ |
| 248 |
"pem": PREVIOUS_PRIVATE_KEY, |
| 249 |
"expires_at": timezone.now() + timedelta(seconds=expires_in), |
| 250 |
} |
| 251 |
] |
| 252 |
resp = client.get(reverse("idp:oidc:jwks")) |
| 253 |
assert resp.status_code == HTTPStatus.OK |
| 254 |
assert resp.json() == { |
| 255 |
"keys": [{"e": ANY, "key_ops": ["verify"], "kid": ANY, "kty": "RSA", "n": ANY}] |
| 256 |
* key_count, |
| 257 |
} |
| 258 |
|
| 259 |
|
| 260 |
@pytest.mark.parametrize("expires_in,expected_max_age", [(90, 90), (10000, 4711)]) |
| 261 |
def test_jwks_view_clamps_cache_control(client, settings, expires_in, expected_max_age): |
| 262 |
settings.USE_TZ = True |
| 263 |
settings.IDP_OIDC_JWKS_CACHE_CONTROL = 4711 |
| 264 |
now = timezone.now() |
| 265 |
settings.IDP_OIDC_PRIVATE_KEYS = [ |
| 266 |
{ |
| 267 |
"pem": PREVIOUS_PRIVATE_KEY, |
| 268 |
"expires_at": now + timedelta(seconds=expires_in), |
| 269 |
} |
| 270 |
] |
| 271 |
# Pin the adapter's clock so the clamp is exact; an expiry sooner than the |
| 272 |
# configured max-age must shorten it, a later one must leave it untouched. |
| 273 |
with patch("allauth.idp.oidc.adapter.timezone.now", return_value=now): |
| 274 |
resp = client.get(reverse("idp:oidc:jwks")) |
| 275 |
assert resp.status_code == HTTPStatus.OK |
| 276 |
assert resp["Cache-Control"] == f"max-age={expected_max_age}, must-revalidate" |
| 277 |
|
| 278 |
|
| 279 |
@pytest.mark.parametrize("custom_userinfo_endpoint", [False, True]) |
| 280 |
def test_configuration_view( |
| 281 |
client, oidc_client, custom_userinfo_endpoint, settings_impacting_urls |
| 282 |
): |
| 283 |
with settings_impacting_urls( |
| 284 |
IDP_OIDC_INTROSPECTION_ENABLED=True, |
| 285 |
IDP_OIDC_USERINFO_ENDPOINT=( |
| 286 |
"https://remote/userinfo" if custom_userinfo_endpoint else None |
| 287 |
), |
| 288 |
): |
| 289 |
resp = client.get(reverse("idp:oidc:configuration")) |
| 290 |
assert resp.status_code == HTTPStatus.OK |
| 291 |
assert resp.json() == { |
| 292 |
"authorization_endpoint": "http://testserver/identity/o/authorize", |
| 293 |
"device_authorization_endpoint": "http://testserver/identity/o/api/device/code", |
| 294 |
"end_session_endpoint": "http://testserver/identity/o/logout", |
| 295 |
"id_token_signing_alg_values_supported": ["RS256"], |
| 296 |
"issuer": "http://testserver", |
| 297 |
"jwks_uri": "http://testserver/.well-known/jwks.json", |
| 298 |
"response_types_supported": [ |
| 299 |
"code", |
| 300 |
"code id_token", |
| 301 |
"code id_token token", |
| 302 |
"code token", |
| 303 |
"id_token", |
| 304 |
"id_token token", |
| 305 |
"none", |
| 306 |
"token", |
| 307 |
], |
| 308 |
"revocation_endpoint": "http://testserver/identity/o/api/revoke", |
| 309 |
"introspection_endpoint": "http://testserver/identity/o/api/introspect", |
| 310 |
"introspection_endpoint_auth_methods_supported": [ |
| 311 |
"client_secret_basic", |
| 312 |
"client_secret_post", |
| 313 |
], |
| 314 |
"subject_types_supported": ["public"], |
| 315 |
"token_endpoint": "http://testserver/identity/o/api/token", |
| 316 |
"token_endpoint_auth_methods_supported": [ |
| 317 |
"client_secret_basic", |
| 318 |
"client_secret_post", |
| 319 |
"none", |
| 320 |
], |
| 321 |
"scopes_supported": ["openid", "profile", "email"], |
| 322 |
"userinfo_endpoint": ( |
| 323 |
"https://remote/userinfo" |
| 324 |
if custom_userinfo_endpoint |
| 325 |
else "http://testserver/identity/o/api/userinfo" |
| 326 |
), |
| 327 |
"code_challenge_methods_supported": ["S256"], |
| 328 |
"grant_types_supported": [ |
| 329 |
"authorization_code", |
| 330 |
"client_credentials", |
| 331 |
"refresh_token", |
| 332 |
"urn:ietf:params:oauth:grant-type:device_code", |
| 333 |
], |
| 334 |
} |
| 335 |
|
| 336 |
|
| 337 |
def test_configuration_view_without_introspection( |
| 338 |
client, oidc_client, settings_impacting_urls |
| 339 |
): |
| 340 |
with settings_impacting_urls(IDP_OIDC_INTROSPECTION_ENABLED=False): |
| 341 |
resp = client.get(reverse("idp:oidc:configuration")) |
| 342 |
assert resp.status_code == HTTPStatus.OK |
| 343 |
data = resp.json() |
| 344 |
assert "introspection_endpoint" not in data |
| 345 |
assert "introspection_endpoint_auth_methods_supported" not in data |
| 346 |
|
| 347 |
|
| 348 |
def test_post_userinfo( |
| 349 |
client, |
| 350 |
oidc_client, |
| 351 |
user, |
| 352 |
access_token_factory, |
| 353 |
): |
| 354 |
# Pass along ID token as hint |
| 355 |
token, token_instance = access_token_factory(oidc_client, user) |
| 356 |
resp = client.post( |
| 357 |
reverse("idp:oidc:userinfo"), |
| 358 |
HTTP_AUTHORIZATION=f"Bearer {token}", |
| 359 |
) |
| 360 |
assert resp.status_code == HTTPStatus.OK |
| 361 |
data = resp.json() |
| 362 |
assert data["sub"] == get_adapter().get_user_sub(oidc_client, user) |