Coverage for downtify/oidc.py: 90%
176 statements
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-21 22:18 +0000
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-21 22:18 +0000
1"""OpenID Connect authorization-code login with PKCE."""
3from __future__ import annotations
5import base64
6import hashlib
7import hmac
8import os
9import re
10import secrets
11import threading
12import time
13from dataclasses import dataclass
14from typing import Any, Mapping, Optional
15from urllib.parse import urlencode
17import httpx
18from joserfc import jwt
19from joserfc.jwk import KeySet
20from joserfc.jwt import JWTClaimsRegistry
23class OIDCError(ValueError):
24 """An OIDC response or identity could not be trusted."""
27@dataclass(frozen=True)
28class OIDCConfig:
29 issuer: str
30 client_id: str
31 client_secret: str
32 scopes: str = 'openid profile email'
33 redirect_uri: str = ''
34 username_claim: str = 'preferred_username'
35 groups_claim: str = 'groups'
36 allowed_groups: tuple[str, ...] = ()
37 admin_groups: tuple[str, ...] = ()
39 @classmethod
40 def from_env(
41 cls, environ: Optional[Mapping[str, str]] = None
42 ) -> Optional[OIDCConfig]:
43 values = os.environ if environ is None else environ
44 issuer = values.get('DOWNTIFY_OIDC_ISSUER', '').strip()
45 client_id = values.get('DOWNTIFY_OIDC_CLIENT_ID', '').strip()
46 client_secret = values.get('DOWNTIFY_OIDC_CLIENT_SECRET', '').strip()
47 if not any((issuer, client_id, client_secret)):
48 return None
49 if not all((issuer, client_id, client_secret)):
50 raise ValueError(
51 'DOWNTIFY_OIDC_ISSUER, DOWNTIFY_OIDC_CLIENT_ID and '
52 'DOWNTIFY_OIDC_CLIENT_SECRET must all be set'
53 )
54 if not issuer.startswith(('https://', 'http://')):
55 raise ValueError('DOWNTIFY_OIDC_ISSUER must be an HTTP(S) URL')
57 def values_for(name: str) -> tuple[str, ...]:
58 return tuple(
59 item.strip()
60 for item in values.get(name, '').split(',')
61 if item.strip()
62 )
64 return cls(
65 issuer=issuer,
66 client_id=client_id,
67 client_secret=client_secret,
68 scopes=values.get(
69 'DOWNTIFY_OIDC_SCOPES', 'openid profile email'
70 ).strip(),
71 redirect_uri=values.get('DOWNTIFY_OIDC_REDIRECT_URI', '').strip(),
72 username_claim=values.get(
73 'DOWNTIFY_OIDC_USERNAME_CLAIM', 'preferred_username'
74 ).strip(),
75 groups_claim=values.get(
76 'DOWNTIFY_OIDC_GROUPS_CLAIM', 'groups'
77 ).strip(),
78 allowed_groups=values_for('DOWNTIFY_OIDC_ALLOWED_GROUPS'),
79 admin_groups=values_for('DOWNTIFY_OIDC_ADMIN_GROUPS'),
80 )
83class OIDCTransactions:
84 """Short-lived, single-use OIDC transactions held in process memory."""
86 def __init__(self, ttl_seconds: int = 600) -> None:
87 self._ttl = ttl_seconds
88 self._lock = threading.Lock()
89 self._pending: dict[str, tuple[float, str, str]] = {}
91 def create(self) -> tuple[str, str, str]:
92 state = secrets.token_urlsafe(32)
93 nonce = secrets.token_urlsafe(32)
94 verifier = secrets.token_urlsafe(64)
95 with self._lock:
96 now = time.monotonic()
97 self._pending = {
98 key: value
99 for key, value in self._pending.items()
100 if value[0] >= now
101 }
102 self._pending[state] = (now + self._ttl, nonce, verifier)
103 return state, nonce, verifier
105 def consume(self, state: str) -> Optional[tuple[str, str]]:
106 with self._lock:
107 entry = self._pending.pop(state, None)
108 if entry is None or entry[0] < time.monotonic():
109 return None
110 return entry[1], entry[2]
113def create_authorization_url(
114 config: OIDCConfig,
115 metadata: Mapping[str, Any],
116 callback_uri: str,
117 transactions: OIDCTransactions,
118) -> tuple[str, str]:
119 endpoint = metadata.get('authorization_endpoint')
120 if not isinstance(endpoint, str) or not endpoint.startswith((
121 'https://',
122 'http://',
123 )):
124 raise OIDCError('The provider has no valid authorization endpoint')
125 state, nonce, verifier = transactions.create()
126 challenge = (
127 base64
128 .urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest())
129 .rstrip(b'=')
130 .decode()
131 )
132 query = urlencode({
133 'client_id': config.client_id,
134 'redirect_uri': callback_uri,
135 'response_type': 'code',
136 'scope': config.scopes,
137 'state': state,
138 'nonce': nonce,
139 'code_challenge': challenge,
140 'code_challenge_method': 'S256',
141 })
142 separator = '&' if '?' in endpoint else '?'
143 return f'{endpoint}{separator}{query}', state
146_ALLOWED_ALGORITHMS = (
147 'RS256',
148 'RS384',
149 'RS512',
150 'PS256',
151 'PS384',
152 'PS512',
153 'ES256',
154 'ES384',
155 'ES512',
156 'EdDSA',
157)
160def verify_id_token(
161 encoded: str,
162 jwks: Mapping[str, Any],
163 config: OIDCConfig,
164 expected_nonce: str,
165) -> dict[str, Any]:
166 """Verify the ID token signature, standard claims, audience and nonce."""
168 try:
169 token = jwt.decode(
170 encoded,
171 KeySet.import_key_set(jwks),
172 algorithms=_ALLOWED_ALGORITHMS,
173 )
174 claims = dict(token.claims)
175 JWTClaimsRegistry(
176 leeway=60,
177 iss={'essential': True, 'value': config.issuer},
178 sub={'essential': True},
179 exp={'essential': True},
180 iat={'essential': True},
181 ).validate(claims)
182 except Exception as exc:
183 raise OIDCError('The provider returned an invalid ID token') from exc
185 audience = claims.get('aud')
186 audiences = [audience] if isinstance(audience, str) else audience
187 if not isinstance(audiences, list) or config.client_id not in audiences:
188 raise OIDCError('The ID token was issued for a different client')
189 authorized_party = claims.get('azp')
190 if len(audiences) > 1 and authorized_party != config.client_id:
191 raise OIDCError('The ID token has an invalid authorized party')
192 if authorized_party is not None and authorized_party != config.client_id:
193 raise OIDCError('The ID token has an invalid authorized party')
194 nonce = claims.get('nonce')
195 if not isinstance(nonce, str) or not hmac.compare_digest(
196 nonce, expected_nonce
197 ):
198 raise OIDCError('The ID token nonce does not match')
199 return claims
202def claim_value(claims: Mapping[str, Any], path: str) -> Any:
203 value: Any = claims
204 for part in path.split('.'):
205 if not isinstance(value, Mapping):
206 return None
207 value = value.get(part)
208 return value
211def authorize_claims(
212 claims: Mapping[str, Any], config: OIDCConfig
213) -> tuple[str, str]:
214 """Return the provider username and mapped Downtify role."""
216 group_value = claim_value(claims, config.groups_claim)
217 if isinstance(group_value, str):
218 groups = {group_value}
219 elif isinstance(group_value, list):
220 groups = {value for value in group_value if isinstance(value, str)}
221 else:
222 groups = set()
224 if config.allowed_groups and not groups.intersection(
225 config.allowed_groups
226 ):
227 raise OIDCError('Your identity is not in an allowed group')
229 role = 'admin' if groups.intersection(config.admin_groups) else 'user'
230 username = claim_value(claims, config.username_claim)
231 if not isinstance(username, str) or not username.strip():
232 username = claims.get('email')
233 if not isinstance(username, str) or not username.strip():
234 username = claims.get('sub')
235 if not isinstance(username, str) or not username.strip():
236 raise OIDCError('The provider did not return a usable identity')
237 return username.strip(), role
240def clean_oidc_username(value: str, issuer: str, subject: str) -> str:
241 name = re.sub(r'[^A-Za-z0-9._-]+', '_', value).strip('._-')[:32]
242 if len(name) < 3:
243 suffix = hashlib.sha256(f'{issuer}\0{subject}'.encode()).hexdigest()
244 name = f'oidc_{suffix[:12]}'
245 return name
248def local_login_enabled_from_env(
249 environ: Optional[Mapping[str, str]] = None,
250) -> bool:
251 values = os.environ if environ is None else environ
252 return values.get(
253 'DOWNTIFY_DISABLE_LOCAL_LOGIN', ''
254 ).strip().lower() not in {
255 '1',
256 'true',
257 'yes',
258 'on',
259 }
262class OIDCProvider:
263 """Discover an OIDC provider and complete its authorization flow."""
265 def __init__(
266 self,
267 config: OIDCConfig,
268 transactions: Optional[OIDCTransactions] = None,
269 transport: Optional[httpx.AsyncBaseTransport] = None,
270 ) -> None:
271 self.config = config
272 self.transactions = transactions or OIDCTransactions()
273 self._transport = transport
274 self._metadata: Optional[dict[str, Any]] = None
275 self._jwks: Optional[dict[str, Any]] = None
277 async def _get_json(self, url: str) -> dict[str, Any]:
278 async with httpx.AsyncClient(
279 timeout=10, transport=self._transport
280 ) as client:
281 response = await client.get(url)
282 response.raise_for_status()
283 value = response.json()
284 if not isinstance(value, dict):
285 raise OIDCError('The provider returned invalid JSON')
286 return value
288 async def metadata(self) -> dict[str, Any]:
289 if self._metadata is None:
290 discovery_url = (
291 self.config.issuer.rstrip('/')
292 + '/.well-known/openid-configuration'
293 )
294 metadata = await self._get_json(discovery_url)
295 if metadata.get('issuer') != self.config.issuer:
296 raise OIDCError('The provider issuer does not match')
297 for name in (
298 'authorization_endpoint',
299 'token_endpoint',
300 'jwks_uri',
301 ):
302 endpoint = metadata.get(name)
303 if not isinstance(endpoint, str) or not endpoint.startswith((
304 'https://',
305 'http://',
306 )):
307 raise OIDCError(f'The provider is missing {name}')
308 self._metadata = metadata
309 return self._metadata
311 async def begin(self, callback_uri: str) -> tuple[str, str]:
312 metadata = await self.metadata()
313 return create_authorization_url(
314 self.config, metadata, callback_uri, self.transactions
315 )
317 async def authenticate(
318 self,
319 *,
320 code: str,
321 state: str,
322 cookie_state: str,
323 callback_uri: str,
324 ) -> tuple[dict[str, Any], str, str]:
325 if (
326 not state
327 or not cookie_state
328 or not hmac.compare_digest(state, cookie_state)
329 ):
330 raise OIDCError('The sign-in state does not match')
331 transaction = self.transactions.consume(state)
332 if transaction is None:
333 raise OIDCError(
334 'The sign-in state has expired or was already used'
335 )
336 nonce, verifier = transaction
337 metadata = await self.metadata()
338 async with httpx.AsyncClient(
339 timeout=10, transport=self._transport
340 ) as client:
341 response = await client.post(
342 metadata['token_endpoint'],
343 data={
344 'grant_type': 'authorization_code',
345 'code': code,
346 'redirect_uri': callback_uri,
347 'code_verifier': verifier,
348 },
349 auth=httpx.BasicAuth(
350 self.config.client_id, self.config.client_secret
351 ),
352 headers={'Accept': 'application/json'},
353 )
354 response.raise_for_status()
355 token_response = response.json()
356 if not isinstance(token_response, dict) or not isinstance(
357 token_response.get('id_token'), str
358 ):
359 raise OIDCError('The provider did not return an ID token')
360 if self._jwks is None:
361 self._jwks = await self._get_json(metadata['jwks_uri'])
362 claims = verify_id_token(
363 token_response['id_token'], self._jwks, self.config, nonce
364 )
365 username, role = authorize_claims(claims, self.config)
366 return claims, username, role