Debian Codegraph @

allauth/idp/oidc/internal/private_keys.py

raw
1 from __future__ import annotations
2
3 import math
4 from typing import TYPE_CHECKING, Literal
5
6 from django.utils import timezone
7
8
9 if TYPE_CHECKING:
10 from allauth.idp.oidc.models import PrivateKey
11
12
13 def filter_keys(
14 keys: list[PrivateKey],
15 *,
16 did_activate: Literal[True] | None = None,
17 is_active: Literal[True] | None = None,
18 ) -> list[PrivateKey]:
19 now = timezone.now()
20 return [
21 key
22 for key in keys
23 # Activated
24 if (not did_activate or key.not_before is None or key.not_before <= now)
25 # Not expired
26 and (not is_active or key.expires_at is None or key.expires_at > now)
27 ]
28
29
30 def pick_signing_key(keys: list[PrivateKey]) -> PrivateKey | None:
31 """
32 Returns the key that should sign new tokens: the most recently issued one.
33 Introducing a newer key is therefore what rotates signing away from older
34 keys. A key without an ``issued_at`` (e.g. the legacy
35 ``IDP_OIDC_PRIVATE_KEY``) is treated as oldest, so any dated key takes
36 precedence.
37 """
38 if not keys:
39 return None
40 return max(keys, key=_signing_priority)
41
42
43 def _signing_priority(key: PrivateKey) -> float:
44 ts = key.issued_at or key.not_before
45 return ts.timestamp() if ts is not None else -math.inf