stormedo 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- stormedo/__init__.py +74 -0
- stormedo/_json.py +25 -0
- stormedo/_jwks.py +377 -0
- stormedo/client.py +1224 -0
- stormedo/errors.py +80 -0
- stormedo/py.typed +0 -0
- stormedo/types.py +269 -0
- stormedo/verifier.py +347 -0
- stormedo-0.1.0.dist-info/METADATA +220 -0
- stormedo-0.1.0.dist-info/RECORD +12 -0
- stormedo-0.1.0.dist-info/WHEEL +4 -0
- stormedo-0.1.0.dist-info/licenses/LICENSE +21 -0
stormedo/__init__.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
from .client import AsyncStormedo, Stormedo
|
|
2
|
+
from .errors import (
|
|
3
|
+
DeliveryVerificationError,
|
|
4
|
+
DeliveryVerificationErrorCode,
|
|
5
|
+
StormedoError,
|
|
6
|
+
)
|
|
7
|
+
from .types import (
|
|
8
|
+
AuthenticatedDelivery,
|
|
9
|
+
BatchRequest,
|
|
10
|
+
CronTiming,
|
|
11
|
+
EnqueuedRequest,
|
|
12
|
+
IntervalTiming,
|
|
13
|
+
JsonValue,
|
|
14
|
+
RequestAttempt,
|
|
15
|
+
RequestCancellation,
|
|
16
|
+
RequestDetail,
|
|
17
|
+
RequestListPage,
|
|
18
|
+
RequestMethod,
|
|
19
|
+
RequestRetryDecision,
|
|
20
|
+
RequestSource,
|
|
21
|
+
RequestStatus,
|
|
22
|
+
RequestSummary,
|
|
23
|
+
ScheduleDetail,
|
|
24
|
+
ScheduleRequest,
|
|
25
|
+
ScheduleRequestDefinition,
|
|
26
|
+
ScheduleRunOutcome,
|
|
27
|
+
ScheduleStatus,
|
|
28
|
+
ScheduleSummary,
|
|
29
|
+
ScheduleTiming,
|
|
30
|
+
ScheduleTimingDefinition,
|
|
31
|
+
VerifiedDelivery,
|
|
32
|
+
cron_timing,
|
|
33
|
+
interval_timing,
|
|
34
|
+
)
|
|
35
|
+
from .verifier import (
|
|
36
|
+
AsyncDeliveryVerifier,
|
|
37
|
+
DeliveryVerifier,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
__all__ = [
|
|
41
|
+
"AsyncDeliveryVerifier",
|
|
42
|
+
"AsyncStormedo",
|
|
43
|
+
"AuthenticatedDelivery",
|
|
44
|
+
"BatchRequest",
|
|
45
|
+
"CronTiming",
|
|
46
|
+
"DeliveryVerificationError",
|
|
47
|
+
"DeliveryVerificationErrorCode",
|
|
48
|
+
"DeliveryVerifier",
|
|
49
|
+
"EnqueuedRequest",
|
|
50
|
+
"IntervalTiming",
|
|
51
|
+
"JsonValue",
|
|
52
|
+
"RequestAttempt",
|
|
53
|
+
"RequestCancellation",
|
|
54
|
+
"RequestDetail",
|
|
55
|
+
"RequestListPage",
|
|
56
|
+
"RequestMethod",
|
|
57
|
+
"RequestRetryDecision",
|
|
58
|
+
"RequestSource",
|
|
59
|
+
"RequestStatus",
|
|
60
|
+
"RequestSummary",
|
|
61
|
+
"ScheduleDetail",
|
|
62
|
+
"ScheduleRequest",
|
|
63
|
+
"ScheduleRequestDefinition",
|
|
64
|
+
"ScheduleRunOutcome",
|
|
65
|
+
"ScheduleStatus",
|
|
66
|
+
"ScheduleSummary",
|
|
67
|
+
"ScheduleTiming",
|
|
68
|
+
"ScheduleTimingDefinition",
|
|
69
|
+
"Stormedo",
|
|
70
|
+
"StormedoError",
|
|
71
|
+
"VerifiedDelivery",
|
|
72
|
+
"cron_timing",
|
|
73
|
+
"interval_timing",
|
|
74
|
+
]
|
stormedo/_json.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
|
|
5
|
+
from .errors import verification_error
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def parse_token_json(value: bytes) -> dict[str, object]:
|
|
9
|
+
try:
|
|
10
|
+
source = value.decode("utf-8", errors="strict")
|
|
11
|
+
parsed = json.loads(source, object_pairs_hook=_unique_object)
|
|
12
|
+
except (UnicodeDecodeError, ValueError, RecursionError) as error:
|
|
13
|
+
raise verification_error("malformed_token") from error
|
|
14
|
+
if not isinstance(parsed, dict):
|
|
15
|
+
raise verification_error("malformed_token")
|
|
16
|
+
return parsed
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _unique_object(pairs: list[tuple[str, object]]) -> dict[str, object]:
|
|
20
|
+
result: dict[str, object] = {}
|
|
21
|
+
for key, value in pairs:
|
|
22
|
+
if key in result:
|
|
23
|
+
raise ValueError("duplicate JSON key")
|
|
24
|
+
result[key] = value
|
|
25
|
+
return result
|
stormedo/_jwks.py
ADDED
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import base64
|
|
5
|
+
import binascii
|
|
6
|
+
import ipaddress
|
|
7
|
+
import json
|
|
8
|
+
import re
|
|
9
|
+
import threading
|
|
10
|
+
import time
|
|
11
|
+
import weakref
|
|
12
|
+
from collections import OrderedDict
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from urllib.parse import urlsplit
|
|
15
|
+
|
|
16
|
+
import httpx
|
|
17
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
|
|
18
|
+
|
|
19
|
+
from .errors import DeliveryVerificationError, verification_error
|
|
20
|
+
|
|
21
|
+
_MAX_JWKS_BYTES = 64 * 1024
|
|
22
|
+
_MAX_JWKS_KEYS = 8
|
|
23
|
+
_JWKS_TIMEOUT_SECONDS = 5.0
|
|
24
|
+
_JWKS_REFRESH_COOLDOWN_SECONDS = 30.0
|
|
25
|
+
_MAX_SHARED_JWKS_CACHES = 128
|
|
26
|
+
_BASE64URL = re.compile(r"^[A-Za-z0-9_-]+$")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _monotonic_time() -> float:
|
|
30
|
+
return time.monotonic()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True, slots=True)
|
|
34
|
+
class _CachedKeySet:
|
|
35
|
+
keys: dict[str, Ed25519PublicKey]
|
|
36
|
+
expires_at: float
|
|
37
|
+
generation: int
|
|
38
|
+
etag: str | None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class ProjectJwksCache:
|
|
42
|
+
def __init__(self, url: str) -> None:
|
|
43
|
+
self._url = validate_jwks_url(url)
|
|
44
|
+
self._cached: _CachedKeySet | None = None
|
|
45
|
+
self._generation = 0
|
|
46
|
+
self._lock = threading.Lock()
|
|
47
|
+
self._last_refresh_attempt_at = float("-inf")
|
|
48
|
+
|
|
49
|
+
def get_key(self, kid: str) -> Ed25519PublicKey:
|
|
50
|
+
with self._lock:
|
|
51
|
+
key_set = self._current()
|
|
52
|
+
key = key_set.keys.get(kid)
|
|
53
|
+
if key is not None:
|
|
54
|
+
return key
|
|
55
|
+
if (
|
|
56
|
+
_monotonic_time() - self._last_refresh_attempt_at
|
|
57
|
+
< _JWKS_REFRESH_COOLDOWN_SECONDS
|
|
58
|
+
):
|
|
59
|
+
raise verification_error("unknown_signing_key")
|
|
60
|
+
key_set = self._refresh(force=True, previous_generation=key_set.generation)
|
|
61
|
+
key = key_set.keys.get(kid)
|
|
62
|
+
if key is None:
|
|
63
|
+
raise verification_error("unknown_signing_key")
|
|
64
|
+
return key
|
|
65
|
+
|
|
66
|
+
def _current(self) -> _CachedKeySet:
|
|
67
|
+
if self._cached is not None and _monotonic_time() < self._cached.expires_at:
|
|
68
|
+
return self._cached
|
|
69
|
+
return self._refresh(force=False, previous_generation=0)
|
|
70
|
+
|
|
71
|
+
def _refresh(self, *, force: bool, previous_generation: int) -> _CachedKeySet:
|
|
72
|
+
if (
|
|
73
|
+
force
|
|
74
|
+
and self._cached is not None
|
|
75
|
+
and self._cached.generation > previous_generation
|
|
76
|
+
):
|
|
77
|
+
return self._cached
|
|
78
|
+
if (
|
|
79
|
+
not force
|
|
80
|
+
and self._cached is not None
|
|
81
|
+
and _monotonic_time() < self._cached.expires_at
|
|
82
|
+
):
|
|
83
|
+
return self._cached
|
|
84
|
+
self._last_refresh_attempt_at = _monotonic_time()
|
|
85
|
+
self._cached = _fetch_key_set(self._url, self._cached, self._next_generation())
|
|
86
|
+
return self._cached
|
|
87
|
+
|
|
88
|
+
def _next_generation(self) -> int:
|
|
89
|
+
self._generation += 1
|
|
90
|
+
return self._generation
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class AsyncProjectJwksCache:
|
|
94
|
+
def __init__(self, url: str) -> None:
|
|
95
|
+
self._url = validate_jwks_url(url)
|
|
96
|
+
self._cached: _CachedKeySet | None = None
|
|
97
|
+
self._generation = 0
|
|
98
|
+
self._lock = asyncio.Lock()
|
|
99
|
+
self._last_refresh_attempt_at = float("-inf")
|
|
100
|
+
|
|
101
|
+
async def get_key(self, kid: str) -> Ed25519PublicKey:
|
|
102
|
+
async with self._lock:
|
|
103
|
+
key_set = await self._current()
|
|
104
|
+
key = key_set.keys.get(kid)
|
|
105
|
+
if key is not None:
|
|
106
|
+
return key
|
|
107
|
+
if (
|
|
108
|
+
_monotonic_time() - self._last_refresh_attempt_at
|
|
109
|
+
< _JWKS_REFRESH_COOLDOWN_SECONDS
|
|
110
|
+
):
|
|
111
|
+
raise verification_error("unknown_signing_key")
|
|
112
|
+
key_set = await self._refresh(
|
|
113
|
+
force=True, previous_generation=key_set.generation
|
|
114
|
+
)
|
|
115
|
+
key = key_set.keys.get(kid)
|
|
116
|
+
if key is None:
|
|
117
|
+
raise verification_error("unknown_signing_key")
|
|
118
|
+
return key
|
|
119
|
+
|
|
120
|
+
async def _current(self) -> _CachedKeySet:
|
|
121
|
+
if self._cached is not None and _monotonic_time() < self._cached.expires_at:
|
|
122
|
+
return self._cached
|
|
123
|
+
return await self._refresh(force=False, previous_generation=0)
|
|
124
|
+
|
|
125
|
+
async def _refresh(
|
|
126
|
+
self, *, force: bool, previous_generation: int
|
|
127
|
+
) -> _CachedKeySet:
|
|
128
|
+
if (
|
|
129
|
+
force
|
|
130
|
+
and self._cached is not None
|
|
131
|
+
and self._cached.generation > previous_generation
|
|
132
|
+
):
|
|
133
|
+
return self._cached
|
|
134
|
+
if (
|
|
135
|
+
not force
|
|
136
|
+
and self._cached is not None
|
|
137
|
+
and _monotonic_time() < self._cached.expires_at
|
|
138
|
+
):
|
|
139
|
+
return self._cached
|
|
140
|
+
self._last_refresh_attempt_at = _monotonic_time()
|
|
141
|
+
self._cached = await _fetch_key_set_async(
|
|
142
|
+
self._url, self._cached, self._next_generation()
|
|
143
|
+
)
|
|
144
|
+
return self._cached
|
|
145
|
+
|
|
146
|
+
def _next_generation(self) -> int:
|
|
147
|
+
self._generation += 1
|
|
148
|
+
return self._generation
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
_shared_sync_caches: OrderedDict[str, ProjectJwksCache] = OrderedDict()
|
|
152
|
+
_shared_sync_caches_lock = threading.Lock()
|
|
153
|
+
_shared_async_caches: weakref.WeakKeyDictionary[
|
|
154
|
+
asyncio.AbstractEventLoop, OrderedDict[str, AsyncProjectJwksCache]
|
|
155
|
+
] = weakref.WeakKeyDictionary()
|
|
156
|
+
_shared_async_caches_lock = threading.Lock()
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def get_project_jwks_cache(url: str) -> ProjectJwksCache:
|
|
160
|
+
validated_url = validate_jwks_url(url)
|
|
161
|
+
with _shared_sync_caches_lock:
|
|
162
|
+
cache = _shared_sync_caches.pop(validated_url, None)
|
|
163
|
+
if cache is None:
|
|
164
|
+
cache = ProjectJwksCache(validated_url)
|
|
165
|
+
_shared_sync_caches[validated_url] = cache
|
|
166
|
+
if len(_shared_sync_caches) > _MAX_SHARED_JWKS_CACHES:
|
|
167
|
+
_shared_sync_caches.popitem(last=False)
|
|
168
|
+
return cache
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def get_async_project_jwks_cache(url: str) -> AsyncProjectJwksCache:
|
|
172
|
+
validated_url = validate_jwks_url(url)
|
|
173
|
+
loop = asyncio.get_running_loop()
|
|
174
|
+
with _shared_async_caches_lock:
|
|
175
|
+
loop_caches = _shared_async_caches.setdefault(loop, OrderedDict())
|
|
176
|
+
cache = loop_caches.pop(validated_url, None)
|
|
177
|
+
if cache is None:
|
|
178
|
+
cache = AsyncProjectJwksCache(validated_url)
|
|
179
|
+
loop_caches[validated_url] = cache
|
|
180
|
+
if len(loop_caches) > _MAX_SHARED_JWKS_CACHES:
|
|
181
|
+
loop_caches.popitem(last=False)
|
|
182
|
+
return cache
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def validate_jwks_url(value: str) -> str:
|
|
186
|
+
if not isinstance(value, str) or not value:
|
|
187
|
+
raise TypeError("jwks_url must be an absolute URL")
|
|
188
|
+
try:
|
|
189
|
+
parsed = urlsplit(value)
|
|
190
|
+
except ValueError as error:
|
|
191
|
+
raise TypeError("jwks_url must be an absolute URL") from error
|
|
192
|
+
if (
|
|
193
|
+
not parsed.hostname
|
|
194
|
+
or parsed.query
|
|
195
|
+
or parsed.fragment
|
|
196
|
+
or parsed.username
|
|
197
|
+
or parsed.password
|
|
198
|
+
):
|
|
199
|
+
raise TypeError(
|
|
200
|
+
"jwks_url must not include credentials, a query, or a fragment"
|
|
201
|
+
)
|
|
202
|
+
if parsed.scheme == "https":
|
|
203
|
+
return value
|
|
204
|
+
if parsed.scheme == "http" and _is_loopback(parsed.hostname):
|
|
205
|
+
return value
|
|
206
|
+
raise TypeError("jwks_url must use HTTPS except for loopback development")
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _fetch_key_set(
|
|
210
|
+
url: str, cached: _CachedKeySet | None, generation: int
|
|
211
|
+
) -> _CachedKeySet:
|
|
212
|
+
headers = {"Accept": "application/json"}
|
|
213
|
+
if cached is not None and cached.etag is not None:
|
|
214
|
+
headers["If-None-Match"] = cached.etag
|
|
215
|
+
try:
|
|
216
|
+
with httpx.Client(
|
|
217
|
+
timeout=_JWKS_TIMEOUT_SECONDS, follow_redirects=False
|
|
218
|
+
) as client:
|
|
219
|
+
with client.stream("GET", url, headers=headers) as response:
|
|
220
|
+
return _read_response(response, cached, generation)
|
|
221
|
+
except DeliveryVerificationError:
|
|
222
|
+
raise
|
|
223
|
+
except httpx.HTTPError as error:
|
|
224
|
+
raise verification_error("jwks_unavailable") from error
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
async def _fetch_key_set_async(
|
|
228
|
+
url: str, cached: _CachedKeySet | None, generation: int
|
|
229
|
+
) -> _CachedKeySet:
|
|
230
|
+
headers = {"Accept": "application/json"}
|
|
231
|
+
if cached is not None and cached.etag is not None:
|
|
232
|
+
headers["If-None-Match"] = cached.etag
|
|
233
|
+
try:
|
|
234
|
+
async with httpx.AsyncClient(
|
|
235
|
+
timeout=_JWKS_TIMEOUT_SECONDS, follow_redirects=False
|
|
236
|
+
) as client:
|
|
237
|
+
async with client.stream("GET", url, headers=headers) as response:
|
|
238
|
+
return await _read_response_async(response, cached, generation)
|
|
239
|
+
except DeliveryVerificationError:
|
|
240
|
+
raise
|
|
241
|
+
except httpx.HTTPError as error:
|
|
242
|
+
raise verification_error("jwks_unavailable") from error
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _read_response(
|
|
246
|
+
response: httpx.Response, cached: _CachedKeySet | None, generation: int
|
|
247
|
+
) -> _CachedKeySet:
|
|
248
|
+
expires_at = _cache_expiry(response.headers.get("cache-control"))
|
|
249
|
+
if response.status_code == 304:
|
|
250
|
+
return _not_modified(cached, expires_at, generation)
|
|
251
|
+
if not response.is_success:
|
|
252
|
+
raise verification_error("jwks_unavailable")
|
|
253
|
+
_validate_content_length(response.headers.get("content-length"))
|
|
254
|
+
body = bytearray()
|
|
255
|
+
for chunk in response.iter_bytes():
|
|
256
|
+
body.extend(chunk)
|
|
257
|
+
if len(body) > _MAX_JWKS_BYTES:
|
|
258
|
+
raise verification_error("invalid_jwks")
|
|
259
|
+
return _new_key_set(bytes(body), response, expires_at, generation)
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
async def _read_response_async(
|
|
263
|
+
response: httpx.Response, cached: _CachedKeySet | None, generation: int
|
|
264
|
+
) -> _CachedKeySet:
|
|
265
|
+
expires_at = _cache_expiry(response.headers.get("cache-control"))
|
|
266
|
+
if response.status_code == 304:
|
|
267
|
+
return _not_modified(cached, expires_at, generation)
|
|
268
|
+
if not response.is_success:
|
|
269
|
+
raise verification_error("jwks_unavailable")
|
|
270
|
+
_validate_content_length(response.headers.get("content-length"))
|
|
271
|
+
body = bytearray()
|
|
272
|
+
async for chunk in response.aiter_bytes():
|
|
273
|
+
body.extend(chunk)
|
|
274
|
+
if len(body) > _MAX_JWKS_BYTES:
|
|
275
|
+
raise verification_error("invalid_jwks")
|
|
276
|
+
return _new_key_set(bytes(body), response, expires_at, generation)
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _new_key_set(
|
|
280
|
+
body: bytes, response: httpx.Response, expires_at: float, generation: int
|
|
281
|
+
) -> _CachedKeySet:
|
|
282
|
+
return _CachedKeySet(
|
|
283
|
+
keys=_parse_key_set(body),
|
|
284
|
+
expires_at=expires_at,
|
|
285
|
+
generation=generation,
|
|
286
|
+
etag=response.headers.get("etag"),
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _not_modified(
|
|
291
|
+
cached: _CachedKeySet | None, expires_at: float, generation: int
|
|
292
|
+
) -> _CachedKeySet:
|
|
293
|
+
if cached is None:
|
|
294
|
+
raise verification_error("invalid_jwks")
|
|
295
|
+
return _CachedKeySet(cached.keys, expires_at, generation, cached.etag)
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _parse_key_set(body: bytes) -> dict[str, Ed25519PublicKey]:
|
|
299
|
+
try:
|
|
300
|
+
decoded = json.loads(body.decode("utf-8", errors="strict"))
|
|
301
|
+
except (UnicodeDecodeError, json.JSONDecodeError) as error:
|
|
302
|
+
raise verification_error("invalid_jwks") from error
|
|
303
|
+
if not isinstance(decoded, dict) or not isinstance(decoded.get("keys"), list):
|
|
304
|
+
raise verification_error("invalid_jwks")
|
|
305
|
+
candidates = decoded["keys"]
|
|
306
|
+
if len(candidates) > _MAX_JWKS_KEYS:
|
|
307
|
+
raise verification_error("invalid_jwks")
|
|
308
|
+
keys: dict[str, Ed25519PublicKey] = {}
|
|
309
|
+
for candidate in candidates:
|
|
310
|
+
kid, key = _parse_public_key(candidate)
|
|
311
|
+
if kid in keys:
|
|
312
|
+
raise verification_error("invalid_jwks")
|
|
313
|
+
keys[kid] = key
|
|
314
|
+
return keys
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _parse_public_key(value: object) -> tuple[str, Ed25519PublicKey]:
|
|
318
|
+
if (
|
|
319
|
+
not isinstance(value, dict)
|
|
320
|
+
or value.get("kty") != "OKP"
|
|
321
|
+
or value.get("crv") != "Ed25519"
|
|
322
|
+
or value.get("alg") != "EdDSA"
|
|
323
|
+
or value.get("use") != "sig"
|
|
324
|
+
or not isinstance(value.get("kid"), str)
|
|
325
|
+
or not value["kid"]
|
|
326
|
+
or not isinstance(value.get("x"), str)
|
|
327
|
+
or not _BASE64URL.fullmatch(value["x"])
|
|
328
|
+
or "d" in value
|
|
329
|
+
):
|
|
330
|
+
raise verification_error("invalid_jwks")
|
|
331
|
+
try:
|
|
332
|
+
public_bytes = _decode_base64url(value["x"])
|
|
333
|
+
if len(public_bytes) != 32:
|
|
334
|
+
raise ValueError
|
|
335
|
+
key = Ed25519PublicKey.from_public_bytes(public_bytes)
|
|
336
|
+
except ValueError as error:
|
|
337
|
+
raise verification_error("invalid_jwks") from error
|
|
338
|
+
return value["kid"], key
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def _validate_content_length(value: str | None) -> None:
|
|
342
|
+
if value is None:
|
|
343
|
+
return
|
|
344
|
+
try:
|
|
345
|
+
length = int(value)
|
|
346
|
+
except ValueError as error:
|
|
347
|
+
raise verification_error("invalid_jwks") from error
|
|
348
|
+
if length < 0 or length > _MAX_JWKS_BYTES:
|
|
349
|
+
raise verification_error("invalid_jwks")
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def _cache_expiry(value: str | None) -> float:
|
|
353
|
+
now = _monotonic_time()
|
|
354
|
+
if value is None or re.search(r"(?:^|,)\s*(?:no-store|no-cache)\b", value, re.I):
|
|
355
|
+
return now
|
|
356
|
+
match = re.search(r'(?:^|,)\s*max-age\s*=\s*"?(\d+)"?', value, re.I)
|
|
357
|
+
return now if match is None else now + int(match.group(1))
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _decode_base64url(value: str) -> bytes:
|
|
361
|
+
padding = "=" * (-len(value) % 4)
|
|
362
|
+
try:
|
|
363
|
+
decoded = base64.urlsafe_b64decode(value + padding)
|
|
364
|
+
except (ValueError, binascii.Error) as error:
|
|
365
|
+
raise ValueError("invalid base64url") from error
|
|
366
|
+
if base64.urlsafe_b64encode(decoded).rstrip(b"=").decode("ascii") != value:
|
|
367
|
+
raise ValueError("non-canonical base64url")
|
|
368
|
+
return decoded
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def _is_loopback(hostname: str) -> bool:
|
|
372
|
+
if hostname == "localhost":
|
|
373
|
+
return True
|
|
374
|
+
try:
|
|
375
|
+
return ipaddress.ip_address(hostname).is_loopback
|
|
376
|
+
except ValueError:
|
|
377
|
+
return False
|