| 1 |
import json |
| 2 |
import requests |
| 3 |
from http import HTTPStatus |
| 4 |
from unittest.mock import patch |
| 5 |
from urllib.parse import urlparse |
| 6 |
|
| 7 |
from django.core.cache import cache |
| 8 |
from django.core.exceptions import ValidationError |
| 9 |
|
| 10 |
import pytest |
| 11 |
|
| 12 |
from allauth.idp.oidc.adapter import DefaultOIDCAdapter |
| 13 |
from allauth.idp.oidc.internal import cimd |
| 14 |
from allauth.idp.oidc.internal.clientkit import lookup_client |
| 15 |
from allauth.idp.oidc.models import Client |
| 16 |
|
| 17 |
|
| 18 |
CIMD_CLIENT_ID = "https://app.example.com/client-metadata" |
| 19 |
|
| 20 |
|
| 21 |
class CIMDTestAdapter(DefaultOIDCAdapter): |
| 22 |
def is_cimd_url_allowed(self, url: str) -> bool: |
| 23 |
return "disallowed" not in url |
| 24 |
|
| 25 |
|
| 26 |
@pytest.fixture |
| 27 |
def cimd_enabled(settings): |
| 28 |
settings.IDP_OIDC_CIMD_ENABLED = True |
| 29 |
settings.IDP_OIDC_ADAPTER = "tests.apps.idp.oidc.test_cimd.CIMDTestAdapter" |
| 30 |
|
| 31 |
|
| 32 |
@pytest.fixture |
| 33 |
def requests_get_mock(): |
| 34 |
with patch("allauth.idp.oidc.internal.cimd.requests.get") as mock_get: |
| 35 |
yield mock_get |
| 36 |
|
| 37 |
|
| 38 |
@pytest.fixture |
| 39 |
def response_mock(requests_get_mock): |
| 40 |
mock_resp = requests_get_mock.return_value |
| 41 |
mock_resp.status_code = HTTPStatus.OK |
| 42 |
mock_resp.headers = {} |
| 43 |
yield mock_resp |
| 44 |
|
| 45 |
|
| 46 |
def _validate_metadata(metadata, client_id=CIMD_CLIENT_ID): |
| 47 |
parsed = urlparse(client_id) |
| 48 |
return cimd.validate_metadata(client_id, parsed, metadata) |
| 49 |
|
| 50 |
|
| 51 |
def _metadata_factory(**overrides): |
| 52 |
metadata = { |
| 53 |
"client_id": CIMD_CLIENT_ID, |
| 54 |
"redirect_uris": ["https://app.example.com/callback"], |
| 55 |
"client_name": "Example App", |
| 56 |
"scope": "openid profile", |
| 57 |
"grant_types": ["authorization_code"], |
| 58 |
"response_types": ["code"], |
| 59 |
"post_logout_redirect_uris": ["https://app.example.com/logout"], |
| 60 |
} |
| 61 |
for k, v in overrides.items(): |
| 62 |
if v is NotImplemented: |
| 63 |
metadata.pop(k, None) |
| 64 |
else: |
| 65 |
metadata[k] = v |
| 66 |
return metadata |
| 67 |
|
| 68 |
|
| 69 |
@pytest.mark.parametrize( |
| 70 |
"client_id,expected", |
| 71 |
[ |
| 72 |
("https://example.com/app", True), |
| 73 |
("http://example.com/app", False), |
| 74 |
("HTTPS://example.com/app", False), |
| 75 |
("my-client-id", False), |
| 76 |
], |
| 77 |
) |
| 78 |
def test_is_cimd_url(client_id, expected): |
| 79 |
assert cimd.is_cimd_url(client_id) is expected |
| 80 |
|
| 81 |
|
| 82 |
@pytest.mark.parametrize( |
| 83 |
"client_id,error_match", |
| 84 |
[ |
| 85 |
(CIMD_CLIENT_ID, None), |
| 86 |
(f"{CIMD_CLIENT_ID}/okay", None), |
| 87 |
(f"{CIMD_CLIENT_ID}/disallowed", "not permitted"), |
| 88 |
("https://example.com", "path"), |
| 89 |
("https://example.com/", "path"), |
| 90 |
("https://example.com/app?foo=bar", "query"), |
| 91 |
("https://example.com/app#frag", "fragment"), |
| 92 |
("https://user:[email protected]/app", "credentials"), |
| 93 |
("https://Example.COM/app", "lowercase"), |
| 94 |
("https://example.com/a/../b", "normalized"), |
| 95 |
("https://example.com" + "/a" * 200, "maximum length"), |
| 96 |
], |
| 97 |
) |
| 98 |
def test_validate_client_id(cimd_enabled, db, client_id, error_match): |
| 99 |
if error_match is None: |
| 100 |
parsed = cimd.validate_client_id(client_id) |
| 101 |
assert parsed.hostname == "app.example.com" |
| 102 |
else: |
| 103 |
with pytest.raises(ValidationError, match=error_match): |
| 104 |
cimd.validate_client_id(client_id) |
| 105 |
|
| 106 |
|
| 107 |
def test_validate_metadata(db): |
| 108 |
client = _validate_metadata(_metadata_factory()) |
| 109 |
assert client.id == CIMD_CLIENT_ID |
| 110 |
assert client.name == "Example App" |
| 111 |
assert client.type == Client.Type.PUBLIC |
| 112 |
assert client.get_scopes() == ["openid", "profile"] |
| 113 |
assert client.get_redirect_uris() == ["https://app.example.com/callback"] |
| 114 |
assert client.get_post_logout_redirect_uris() == ["https://app.example.com/logout"] |
| 115 |
assert client.get_grant_types() == ["authorization_code"] |
| 116 |
assert client.get_response_types() == ["code"] |
| 117 |
assert client.data["cimd"] is True |
| 118 |
|
| 119 |
|
| 120 |
def test_validate_metadata_defaults(db): |
| 121 |
metadata = { |
| 122 |
"client_id": CIMD_CLIENT_ID, |
| 123 |
"redirect_uris": ["https://app.example.com/callback"], |
| 124 |
} |
| 125 |
client = _validate_metadata(metadata) |
| 126 |
assert client.get_scopes() == ["openid"] |
| 127 |
assert client.get_grant_types() == ["authorization_code"] |
| 128 |
assert client.get_response_types() == ["code"] |
| 129 |
assert client.name == "app.example.com" |
| 130 |
# post_logout_redirect_uris is optional; when omitted, there are none. |
| 131 |
assert client.get_post_logout_redirect_uris() == [] |
| 132 |
|
| 133 |
|
| 134 |
@pytest.mark.parametrize( |
| 135 |
"metadata,error_match", |
| 136 |
[ |
| 137 |
([1, 2, 3], "JSON object"), |
| 138 |
(_metadata_factory(client_id="https://other.com/app"), "does not match"), |
| 139 |
(_metadata_factory(scope=["openid"]), "scope"), |
| 140 |
(_metadata_factory(redirect_uris=[123]), "redirect_uris"), |
| 141 |
(_metadata_factory(redirect_uris=NotImplemented), "redirect_uris"), |
| 142 |
( |
| 143 |
_metadata_factory(post_logout_redirect_uris=[123]), |
| 144 |
"post_logout_redirect_uris", |
| 145 |
), |
| 146 |
( |
| 147 |
_metadata_factory( |
| 148 |
post_logout_redirect_uris="https://app.example.com/logout" |
| 149 |
), |
| 150 |
"post_logout_redirect_uris", |
| 151 |
), |
| 152 |
( |
| 153 |
_metadata_factory(post_logout_redirect_uris=[]), |
| 154 |
"post_logout_redirect_uris", |
| 155 |
), |
| 156 |
], |
| 157 |
) |
| 158 |
def test_validate_metadata_invalid(db, metadata, error_match): |
| 159 |
with pytest.raises(ValidationError, match=error_match): |
| 160 |
_validate_metadata(metadata) |
| 161 |
|
| 162 |
|
| 163 |
def test_fetch_success(response_mock, requests_get_mock): |
| 164 |
metadata = _metadata_factory() |
| 165 |
response_mock.iter_content.return_value = iter([json.dumps(metadata).encode()]) |
| 166 |
result = cimd.fetch_metadata(CIMD_CLIENT_ID) |
| 167 |
assert result == metadata |
| 168 |
requests_get_mock.assert_called_once_with( |
| 169 |
CIMD_CLIENT_ID, |
| 170 |
timeout=cimd.FETCH_TIMEOUT, |
| 171 |
headers={"Accept": "application/json"}, |
| 172 |
stream=True, |
| 173 |
allow_redirects=False, |
| 174 |
) |
| 175 |
|
| 176 |
|
| 177 |
def test_fetch_non_200(response_mock): |
| 178 |
response_mock.status_code = HTTPStatus.NOT_FOUND |
| 179 |
with pytest.raises(ValidationError, match="404"): |
| 180 |
cimd.fetch_metadata(CIMD_CLIENT_ID) |
| 181 |
|
| 182 |
|
| 183 |
def test_fetch_too_large_content_length(response_mock): |
| 184 |
response_mock.headers = {"Content-Length": "999999"} |
| 185 |
with pytest.raises(ValidationError, match="too large"): |
| 186 |
cimd.fetch_metadata(CIMD_CLIENT_ID) |
| 187 |
|
| 188 |
|
| 189 |
@pytest.mark.parametrize( |
| 190 |
"body,error_match", |
| 191 |
[ |
| 192 |
(b"x" * (cimd.MAX_RESPONSE_SIZE + 1), "too large"), |
| 193 |
(b"not json", "not valid JSON"), |
| 194 |
], |
| 195 |
) |
| 196 |
def test_fetch_invalid_body(response_mock, body, error_match): |
| 197 |
response_mock.iter_content.return_value = iter([body]) |
| 198 |
with pytest.raises(ValidationError, match=error_match): |
| 199 |
cimd.fetch_metadata(CIMD_CLIENT_ID) |
| 200 |
|
| 201 |
|
| 202 |
def test_rate_limited(enable_cache, settings, request_context): |
| 203 |
settings.IDP_OIDC_RATE_LIMITS = {"cimd_fetch": "0/s/ip"} |
| 204 |
with pytest.raises(ValidationError, match="rate limited"): |
| 205 |
cimd.fetch_metadata_safely(CIMD_CLIENT_ID) |
| 206 |
|
| 207 |
|
| 208 |
def test_thundering_herd_lock(enable_cache, request_context): |
| 209 |
lock_key = f"allauth.cimd.fetch:{CIMD_CLIENT_ID}" |
| 210 |
cache.add(lock_key, True, timeout=10) |
| 211 |
with pytest.raises(ValidationError, match="already in progress"): |
| 212 |
cimd.fetch_metadata_safely(CIMD_CLIENT_ID) |
| 213 |
|
| 214 |
|
| 215 |
def test_lookup_non_cimd_returns_db_client(cimd_enabled, db): |
| 216 |
result = lookup_client("regular-client-id") |
| 217 |
assert result is None |
| 218 |
|
| 219 |
|
| 220 |
def test_lookup_cimd_disabled(db, settings): |
| 221 |
settings.IDP_OIDC_CIMD_ENABLED = False |
| 222 |
result = lookup_client(CIMD_CLIENT_ID) |
| 223 |
assert result is None |
| 224 |
|
| 225 |
|
| 226 |
def _mock_fetch(metadata=None): |
| 227 |
if metadata is None: |
| 228 |
metadata = _metadata_factory() |
| 229 |
return patch( |
| 230 |
"allauth.idp.oidc.internal.cimd.fetch_metadata_safely", |
| 231 |
return_value=metadata, |
| 232 |
) |
| 233 |
|
| 234 |
|
| 235 |
def test_lookup_fresh_fetch(cimd_enabled, db, enable_cache, settings, request_context): |
| 236 |
with _mock_fetch(): |
| 237 |
client = lookup_client(CIMD_CLIENT_ID) |
| 238 |
assert client is not None |
| 239 |
assert client.id == CIMD_CLIENT_ID |
| 240 |
assert client.type == Client.Type.PUBLIC |
| 241 |
assert Client.objects.filter(id=CIMD_CLIENT_ID).exists() |
| 242 |
|
| 243 |
|
| 244 |
def test_lookup_cached_not_outdated(cimd_enabled, db, enable_cache, request_context): |
| 245 |
with _mock_fetch(): |
| 246 |
client1 = lookup_client(CIMD_CLIENT_ID) |
| 247 |
|
| 248 |
with _mock_fetch() as mock_fetch: |
| 249 |
client2 = lookup_client(CIMD_CLIENT_ID) |
| 250 |
mock_fetch.assert_not_called() |
| 251 |
assert client2.id == client1.id |
| 252 |
|
| 253 |
|
| 254 |
def test_lookup_outdated_refetches( |
| 255 |
cimd_enabled, db, enable_cache, settings, request_context |
| 256 |
): |
| 257 |
settings.IDP_OIDC_CIMD_CACHE_TIMEOUT = 0 |
| 258 |
with _mock_fetch(): |
| 259 |
lookup_client(CIMD_CLIENT_ID) |
| 260 |
|
| 261 |
updated_metadata = _metadata_factory(client_name="Updated App") |
| 262 |
with _mock_fetch(updated_metadata): |
| 263 |
client = lookup_client(CIMD_CLIENT_ID) |
| 264 |
assert client.name == "Updated App" |
| 265 |
|
| 266 |
|
| 267 |
def test_lookup_fetch_failure_returns_stale( |
| 268 |
cimd_enabled, db, enable_cache, settings, request_context |
| 269 |
): |
| 270 |
with _mock_fetch(): |
| 271 |
lookup_client(CIMD_CLIENT_ID) |
| 272 |
|
| 273 |
settings.IDP_OIDC_CIMD_CACHE_TIMEOUT = 0 |
| 274 |
with patch( |
| 275 |
"allauth.idp.oidc.internal.cimd.fetch_metadata_safely", |
| 276 |
side_effect=requests.ConnectionError(), |
| 277 |
): |
| 278 |
client = lookup_client(CIMD_CLIENT_ID) |
| 279 |
assert client is not None |
| 280 |
assert client.name == "Example App" |
| 281 |
|
| 282 |
|
| 283 |
def test_lookup_fetch_failure_no_existing( |
| 284 |
cimd_enabled, db, enable_cache, request_context |
| 285 |
): |
| 286 |
with patch( |
| 287 |
"allauth.idp.oidc.internal.cimd.fetch_metadata_safely", |
| 288 |
side_effect=ValidationError("fail"), |
| 289 |
): |
| 290 |
client = lookup_client(CIMD_CLIENT_ID) |
| 291 |
assert client is None |