Debian Codegraph @

allauth/idp/oidc/app_settings.py

raw
1 from __future__ import annotations
2
3 from datetime import datetime, timezone as dt_timezone
4 from typing import TYPE_CHECKING, Any, TypeVar
5
6 from django.core.exceptions import ImproperlyConfigured
7
8 from allauth import app_settings as allauth_settings
9 from allauth.core.internal.cryptokit import UserCodeFormat
10
11
12 if TYPE_CHECKING:
13 from allauth.idp.oidc.models import PrivateKey
14
15 _T = TypeVar("_T")
16
17
18 class AppSettings:
19 def __init__(self, prefix: str) -> None:
20 self.prefix = prefix
21
22 def _setting(self, name: str, dflt: _T) -> _T:
23 from allauth.utils import get_setting
24
25 return get_setting(f"{self.prefix}{name}", dflt)
26
27 @property
28 def ADAPTER(self) -> str:
29 return self._setting(
30 "ADAPTER",
31 "allauth.idp.oidc.adapter.DefaultOIDCAdapter",
32 )
33
34 @property
35 def ID_TOKEN_EXPIRES_IN(self) -> int:
36 return self._setting("ID_TOKEN_EXPIRES_IN", 5 * 60)
37
38 @property
39 def PRIVATE_KEY(self) -> str:
40 return self._setting("PRIVATE_KEY", "")
41
42 @property
43 def PRIVATE_KEYS(self) -> list[PrivateKey]:
44 from allauth.idp.oidc.models import PrivateKey
45
46 ret: list[PrivateKey] = []
47 keys: Any = self._setting("PRIVATE_KEYS", [])
48 if not isinstance(keys, (list, tuple)):
49 raise ImproperlyConfigured("IDP_OIDC_PRIVATE_KEYS: must be a list")
50 pem1 = self._setting("PRIVATE_KEY", "")
51 seen_pems: set[str] = set()
52 for key in keys:
53 if not isinstance(key, dict):
54 raise ImproperlyConfigured(
55 "IDP_OIDC_PRIVATE_KEYS: each entry must be a dict"
56 )
57 pem = key.get("pem")
58 if not isinstance(pem, str):
59 raise ImproperlyConfigured(
60 "IDP_OIDC_PRIVATE_KEYS: 'pem' must be a string"
61 )
62 if pem in seen_pems:
63 raise ImproperlyConfigured("IDP_OIDC_PRIVATE_KEYS: duplicate 'pem'")
64 seen_pems.add(pem)
65 ret.append(
66 PrivateKey(
67 pem=pem,
68 not_before=self._parse_datetime(
69 "not_before", key.get("not_before")
70 ),
71 expires_at=self._parse_datetime(
72 "expires_at", key.get("expires_at")
73 ),
74 issued_at=self._parse_datetime("issued_at", key.get("issued_at")),
75 )
76 )
77 if pem1 and pem1 not in seen_pems:
78 ret.append(PrivateKey(pem=pem1))
79 return ret
80
81 @property
82 def JWKS_CACHE_CONTROL(self) -> int:
83 return self._setting("JWKS_CACHE_CONTROL", 60 * 60)
84
85 @property
86 def ACCESS_TOKEN_EXPIRES_IN(self) -> int:
87 return self._setting("ACCESS_TOKEN_EXPIRES_IN", 3600)
88
89 @property
90 def ACCESS_TOKEN_FORMAT(self) -> str:
91 return self._setting("ACCESS_TOKEN_FORMAT", "opaque")
92
93 @property
94 def AUTH_METHODS(self) -> tuple[str, ...]:
95 return tuple(
96 self._setting(
97 "AUTH_METHODS",
98 ["client_secret_basic", "client_secret_post", "none"],
99 )
100 )
101
102 @property
103 def INTROSPECTION_ENABLED(self) -> bool:
104 return self._setting("INTROSPECTION_ENABLED", False)
105
106 @property
107 def INTROSPECTION_AUTH_METHODS(self) -> tuple[str, ...]:
108 return tuple(
109 self._setting(
110 "INTROSPECTION_AUTH_METHODS",
111 ["client_secret_basic", "client_secret_post"],
112 )
113 )
114
115 @property
116 def INTROSPECTION_CROSS_CLIENT_ALLOWED(self) -> bool:
117 return self._setting("INTROSPECTION_CROSS_CLIENT_ALLOWED", False)
118
119 @property
120 def AUTHORIZATION_CODE_EXPIRES_IN(self) -> int:
121 return self._setting("AUTHORIZATION_CODE_EXPIRES_IN", 60)
122
123 @property
124 def ROTATE_REFRESH_TOKEN(self) -> bool:
125 return self._setting("ROTATE_REFRESH_TOKEN", True)
126
127 @property
128 def REFRESH_TOKEN_EXPIRES_IN(self) -> int | None:
129 return self._setting("REFRESH_TOKEN_EXPIRES_IN", None)
130
131 @property
132 def DEVICE_CODE_EXPIRES_IN(self) -> int:
133 return self._setting("DEVICE_CODE_EXPIRES_IN", 300)
134
135 @property
136 def DEVICE_CODE_INTERVAL(self) -> int:
137 return self._setting("DEVICE_CODE_INTERVAL", 5)
138
139 @property
140 def USER_CODE_FORMAT(self) -> UserCodeFormat:
141 return self._setting("USER_CODE_FORMAT", allauth_settings.USER_CODE_FORMAT)
142
143 @property
144 def RATE_LIMITS(self) -> dict:
145 rls: dict = self._setting("RATE_LIMITS", {})
146 if rls is False:
147 return {}
148 ret = {
149 # OIDC device user code checks
150 "device_user_code": "5/m/ip",
151 # DCR
152 "client_registration": "3/m/ip",
153 # CIMD fetches
154 "cimd_fetch": "3/m/ip",
155 # token introspection, throttled per source IP (before client
156 # authentication) and per authenticated client (after).
157 "introspect_ip": "30/m/ip",
158 "introspect_client": "60/m/key",
159 }
160 ret.update(rls)
161 return ret
162
163 @property
164 def RP_INITIATED_LOGOUT_ASKS_FOR_OP_LOGOUT(self) -> bool:
165 """
166 At https://openid.net/specs/openid-connect-rpinitiated-1_0.html
167
168 > 2. RP-Initiated Logout':
169 > At the Logout Endpoint, the OP SHOULD ask the End-User whether to
170 > log out of the OP as well.
171
172 This setting controls whether the OP always asks.
173 """
174 return self._setting("RP_INITIATED_LOGOUT_ASKS_FOR_OP_LOGOUT", True)
175
176 @property
177 def USERINFO_ENDPOINT(self) -> str | None:
178 """
179 This setting can be used to point the ``userinfo_endpoint`` value as
180 returned in the ".well-known/openid-configuration" to a custom URL.
181 Setting this disables the built-in userinfo endpoint.
182 """
183 return self._setting("USERINFO_ENDPOINT", None)
184
185 @property
186 def DCR_ENABLED(self) -> bool:
187 """
188 Controls whether Dynamic Client Registration (RFC 7591) is enabled.
189 """
190 return self._setting("DCR_ENABLED", False)
191
192 @property
193 def DCR_REQUIRES_INITIAL_ACCESS_TOKEN(self) -> bool:
194 """
195 Controls whether or not an initial access token is required to
196 perform Dynamic Client Registration.
197 """
198 return self._setting("DCR_REQUIRES_INITIAL_ACCESS_TOKEN", True)
199
200 @property
201 def CIMD_ENABLED(self) -> bool:
202 """
203 Whether or not CIMD is enabled.
204
205 https://datatracker.ietf.org/doc/draft-ietf-oauth-client-id-metadata-document/
206 https://client.dev/
207 """
208 return self._setting("CIMD_ENABLED", False)
209
210 @property
211 def CIMD_CACHE_TIMEOUT(self) -> int:
212 """
213 CIMD cache duration, in seconds.
214 """
215 return self._setting("CIMD_CACHE_TIMEOUT", 60 * 60)
216
217 @staticmethod
218 def _parse_datetime(field: str, value: Any) -> datetime | None:
219 if value is None:
220 return None
221 dt: datetime | None = None
222 if isinstance(value, str):
223 try:
224 dt = datetime.fromisoformat(value)
225 except ValueError:
226 pass
227 elif isinstance(value, datetime):
228 dt = value
229 if dt is None:
230 raise ImproperlyConfigured(
231 f"IDP_OIDC_PRIVATE_KEYS: {field!r} is not a valid datetime: {value!r}"
232 )
233 if dt.tzinfo is None:
234 return dt.replace(tzinfo=dt_timezone.utc)
235 return dt.astimezone(dt_timezone.utc)
236
237
238 _app_settings = AppSettings("IDP_OIDC_")
239
240
241 def __getattr__(name):
242 # See https://peps.python.org/pep-0562/
243 return getattr(_app_settings, name)