Debian Codegraph @

allauth/idp/oidc/internal/cimd.py

raw
1 import json
2 import logging
3 import posixpath
4 import requests
5 import time
6 from http import HTTPStatus
7 from typing import Any
8 from urllib.parse import ParseResult, urlparse
9
10 from django.core.cache import cache
11 from django.core.exceptions import ValidationError
12
13 from allauth.core import context
14 from allauth.core.internal import ratelimit
15 from allauth.idp.oidc import app_settings
16 from allauth.idp.oidc.adapter import get_adapter
17 from allauth.idp.oidc.models import Client
18
19
20 logger = logging.getLogger(__name__)
21
22 FETCH_TIMEOUT = 1
23 MAX_RESPONSE_SIZE = 2 * 1024
24
25
26 def is_cimd_url(client_id: str) -> bool:
27 # Intentionally check for lower case, we don't want any '?client_id=HtTps://...' hacking
28 return client_id.startswith("https:")
29
30
31 def validate_client_id(client_id: str) -> ParseResult:
32 parsed = urlparse(client_id)
33 if parsed.scheme != "https":
34 raise ValidationError("client_id must use the https scheme.")
35 if not parsed.hostname:
36 raise ValidationError("client_id must contain a hostname.")
37 if parsed.netloc != parsed.netloc.lower():
38 raise ValidationError("client_id hostname must be lowercase.")
39 if not parsed.path or parsed.path == "/":
40 raise ValidationError("client_id must contain a path component.")
41 if posixpath.normpath(parsed.path) != parsed.path:
42 raise ValidationError("client_id path is not normalized.")
43 if parsed.query:
44 raise ValidationError("client_id must not contain a query component.")
45 if parsed.fragment:
46 raise ValidationError("client_id must not contain a fragment.")
47 if parsed.username or parsed.password:
48 raise ValidationError("client_id must not contain credentials.")
49 client_id_max_length = Client.id.field.max_length
50 assert client_id_max_length # nosec
51 if len(client_id) > client_id_max_length:
52 raise ValidationError(
53 f"client_id exceeds maximum length of {client_id_max_length}."
54 )
55 if not get_adapter().is_cimd_url_allowed(client_id):
56 raise ValidationError("This client_id URL is not permitted by the server.")
57 return parsed
58
59
60 def fetch_metadata_safely(client_id: str) -> Any:
61 if not ratelimit.consume(
62 context.request,
63 action="cimd_fetch",
64 config=app_settings.RATE_LIMITS,
65 limit_get=True,
66 ):
67 raise ValidationError("CIMD fetch rate limited.")
68 lock_key = f"allauth.cimd.fetch:{client_id}"
69 if not cache.add(lock_key, True, timeout=FETCH_TIMEOUT + 5):
70 raise ValidationError("CIMD fetch already in progress.")
71 try:
72 return fetch_metadata(client_id)
73 finally:
74 cache.delete(lock_key)
75
76
77 def fetch_metadata(client_id: str) -> Any:
78 resp = requests.get(
79 client_id,
80 timeout=FETCH_TIMEOUT,
81 headers={"Accept": "application/json"},
82 stream=True,
83 allow_redirects=False,
84 )
85
86 try:
87 if resp.status_code != HTTPStatus.OK:
88 raise ValidationError(f"CIMD fetch returned HTTP {resp.status_code}.")
89
90 content_length = resp.headers.get("Content-Length")
91 if (
92 content_length
93 and content_length.isdigit()
94 and int(content_length) > MAX_RESPONSE_SIZE
95 ):
96 raise ValidationError("CIMD response too large.")
97
98 body = next(resp.iter_content(chunk_size=MAX_RESPONSE_SIZE + 1), b"")
99 if len(body) > MAX_RESPONSE_SIZE:
100 raise ValidationError("CIMD response too large.")
101 finally:
102 resp.close()
103
104 try:
105 return json.loads(body)
106 except (ValueError, TypeError) as e:
107 raise ValidationError(f"CIMD response is not valid JSON: {e}") from e
108
109
110 def fetch_client(client_id: str) -> Client:
111 """
112 Fetch a Client ID Metadata Document (CIMD) and return a Client instance.
113
114 The ``client_id`` is expected to be an HTTPS URL pointing at a JSON metadata
115 document whose ``client_id`` field matches the URL.
116
117 Raises ``ValidationError`` for invalid client_id URLs or metadata, and
118 ``requests.RequestException`` if the HTTP fetch fails.
119 """
120 parsed = validate_client_id(client_id)
121 metadata = fetch_metadata_safely(client_id)
122 return validate_metadata(client_id, parsed, metadata)
123
124
125 def _get_list_of_str(
126 metadata: dict, field: str, dflt: list[str] | None = None
127 ) -> list[str]:
128 if field not in metadata and dflt is not None:
129 return dflt
130 value = metadata.get(field)
131 if (
132 not value
133 or not isinstance(value, list)
134 or not all(isinstance(item, str) for item in value)
135 ):
136 raise ValidationError(f"'{field}' must be a non-empty list of strings.")
137 return value
138
139
140 def validate_metadata(client_id: str, parsed: ParseResult, metadata: Any) -> Client:
141 if not isinstance(metadata, dict):
142 raise ValidationError("CIMD document must be a JSON object.")
143 if metadata.get("client_id") != client_id:
144 raise ValidationError("'client_id' in CIMD document does not match the URL.")
145
146 scope = metadata.get("scope", "openid")
147 if not isinstance(scope, str):
148 raise ValidationError("'scope' must be a string.")
149 scopes = scope.split()
150
151 name = metadata.get("client_name", parsed.hostname)
152 if not isinstance(name, str):
153 raise ValidationError("'client_name' must be a string.")
154 name = name[: Client.name.field.max_length]
155
156 grant_types = _get_list_of_str(metadata, "grant_types", ["authorization_code"])
157 redirect_uris = _get_list_of_str(metadata, "redirect_uris")
158 response_types = _get_list_of_str(metadata, "response_types", ["code"])
159 _get_list_of_str(metadata, "post_logout_redirect_uris", [])
160 client = Client(
161 id=client_id,
162 name=name,
163 type=Client.Type.PUBLIC,
164 )
165 client.set_grant_types(grant_types)
166 client.set_redirect_uris(redirect_uris)
167 client.set_scopes(scopes)
168 client.set_response_types(response_types)
169
170 client.data = {
171 "cimd": True,
172 "client_metadata": metadata,
173 "updated_at": int(time.time()),
174 }
175 return client
176
177
178 def is_outdated(client: Client) -> bool:
179 updated_at = (client.data or {}).get("updated_at", 0)
180 return time.time() - updated_at > app_settings.CIMD_CACHE_TIMEOUT
181
182
183 def lookup_client(client_id: str, client: Client | None) -> Client | None:
184 if not is_cimd_url(client_id):
185 return client
186 if client and not is_outdated(client):
187 return client
188 try:
189 updated_client = fetch_client(client_id)
190 except (ValidationError, requests.RequestException):
191 logger.warning("Failed to fetch CIMD for client_id: %s", client_id)
192 return client
193 updated_client._state.adding = client is None
194 updated_client.save()
195 return updated_client