oidcauthlib 3.0.27__tar.gz → 3.0.29__tar.gz

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.
Files changed (98) hide show
  1. {oidcauthlib-3.0.27/oidcauthlib.egg-info → oidcauthlib-3.0.29}/PKG-INFO +1 -1
  2. oidcauthlib-3.0.29/VERSION +1 -0
  3. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/auth_manager.py +5 -0
  4. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/token_reader.py +20 -4
  5. oidcauthlib-3.0.29/oidcauthlib/auth/well_known_configuration/well_known_configuration_cache.py +492 -0
  6. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/well_known_configuration/well_known_configuration_cache_result.py +5 -0
  7. oidcauthlib-3.0.29/oidcauthlib/auth/well_known_configuration/well_known_configuration_manager.py +125 -0
  8. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/utilities/environment/oidc_environment_variables.py +20 -0
  9. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29/oidcauthlib.egg-info}/PKG-INFO +1 -1
  10. oidcauthlib-3.0.27/VERSION +0 -1
  11. oidcauthlib-3.0.27/oidcauthlib/auth/well_known_configuration/well_known_configuration_cache.py +0 -468
  12. oidcauthlib-3.0.27/oidcauthlib/auth/well_known_configuration/well_known_configuration_manager.py +0 -118
  13. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/LICENSE +0 -0
  14. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/MANIFEST.in +0 -0
  15. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/README.md +0 -0
  16. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/__init__.py +0 -0
  17. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/__init__.py +0 -0
  18. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/auth_helper.py +0 -0
  19. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/cache/__init__.py +0 -0
  20. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/cache/oauth_cache.py +0 -0
  21. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/cache/oauth_memory_cache.py +0 -0
  22. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/cache/oauth_mongo_cache.py +0 -0
  23. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/config/__init__.py +0 -0
  24. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/config/auth_config.py +0 -0
  25. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/config/auth_config_reader.py +0 -0
  26. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/dcr/__init__.py +0 -0
  27. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/dcr/dcr_client.py +0 -0
  28. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/dcr/dcr_manager.py +0 -0
  29. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/dcr/dcr_registration.py +0 -0
  30. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/exceptions/__init__.py +0 -0
  31. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/exceptions/authorization_bearer_token_expired_exception.py +0 -0
  32. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/exceptions/authorization_bearer_token_invalid_exception.py +0 -0
  33. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/exceptions/authorization_bearer_token_missing_exception.py +0 -0
  34. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/exceptions/authorization_needed_exception.py +0 -0
  35. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/fastapi_auth_manager.py +0 -0
  36. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/middleware/__init__.py +0 -0
  37. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/middleware/request_scope_middleware.py +0 -0
  38. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/middleware/token_reader_middleware.py +0 -0
  39. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/models/__init__.py +0 -0
  40. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/models/auth.py +0 -0
  41. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/models/base_db_model.py +0 -0
  42. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/models/cache_item.py +0 -0
  43. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/models/client_key_set.py +0 -0
  44. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/models/token.py +0 -0
  45. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/repository/__init__.py +0 -0
  46. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/repository/base_repository.py +0 -0
  47. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/repository/memory/__init__.py +0 -0
  48. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/repository/memory/memory_repository.py +0 -0
  49. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/repository/mongo/__init__.py +0 -0
  50. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/repository/mongo/mongo_repository.py +0 -0
  51. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/repository/repository_factory.py +0 -0
  52. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/routers/__init__.py +0 -0
  53. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/routers/auth_router.py +0 -0
  54. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/userinfo/__init__.py +0 -0
  55. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/userinfo/oidc_userinfo_manager.py +0 -0
  56. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/well_known_configuration/__init__.py +0 -0
  57. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/well_known_configuration/auth_server_metadata.py +0 -0
  58. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/auth/well_known_configuration/auth_server_metadata_discovery.py +0 -0
  59. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/cache_gate/__init__.py +0 -0
  60. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/cache_gate/advisory_lock.py +0 -0
  61. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/cache_gate/version_gate.py +0 -0
  62. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/container/__init__.py +0 -0
  63. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/container/oidc_authlib_container_factory.py +0 -0
  64. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/open_telemetry/__init__.py +0 -0
  65. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/open_telemetry/attribute_names.py +0 -0
  66. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/open_telemetry/configurator.py +0 -0
  67. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/open_telemetry/filtering_sampler.py +0 -0
  68. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/open_telemetry/filtering_span_exporter.py +0 -0
  69. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/open_telemetry/filtering_span_processor.py +0 -0
  70. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/open_telemetry/otel_setup.py +0 -0
  71. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/open_telemetry/span_names.py +0 -0
  72. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/py.typed +0 -0
  73. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/storage/__init__.py +0 -0
  74. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/storage/cache_to_collection_mapper.py +0 -0
  75. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/storage/memory_storage_factory.py +0 -0
  76. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/storage/mongo_gridfs_db.py +0 -0
  77. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/storage/mongo_gridfs_exception.py +0 -0
  78. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/storage/mongo_storage_factory.py +0 -0
  79. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/storage/storage_factory.py +0 -0
  80. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/storage/storage_factory_creator.py +0 -0
  81. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/utilities/__init__.py +0 -0
  82. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/utilities/cached.py +0 -0
  83. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/utilities/environment/__init__.py +0 -0
  84. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/utilities/environment/abstract_environment_variables.py +0 -0
  85. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/utilities/logger/__init__.py +0 -0
  86. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/utilities/logger/log_levels.py +0 -0
  87. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/utilities/logger/logging_response.py +0 -0
  88. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/utilities/logger/logging_transport.py +0 -0
  89. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/utilities/mongo_url_utils.py +0 -0
  90. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib/utilities/url_validator.py +0 -0
  91. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib.egg-info/SOURCES.txt +0 -0
  92. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib.egg-info/dependency_links.txt +0 -0
  93. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib.egg-info/requires.txt +0 -0
  94. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/oidcauthlib.egg-info/top_level.txt +0 -0
  95. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/pyproject.toml +0 -0
  96. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/setup.cfg +0 -0
  97. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/tests/test_mongo_url_utils.py +0 -0
  98. {oidcauthlib-3.0.27 → oidcauthlib-3.0.29}/tests/test_simple.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: oidcauthlib
3
- Version: 3.0.27
3
+ Version: 3.0.29
4
4
  Summary: oidcauthlib
5
5
  Author-email: Imran Qureshi <imran.qureshi@bwell.com>
6
6
  License: Apache-2.0
@@ -0,0 +1 @@
1
+ 3.0.29
@@ -115,6 +115,11 @@ class AuthManager:
115
115
  async def ensure_initialized_async(self) -> None:
116
116
  auth_config: AuthConfig
117
117
  for auth_config in self.auth_configs:
118
+ if auth_config.auth_provider.lower() in self._registered_dynamic_providers:
119
+ # Already registered: discovery is read through the shared store, so re-reading it
120
+ # here on every login would add store reads and let another provider's issuer
121
+ # outage fail this login.
122
+ continue
118
123
  if auth_config.well_known_uri:
119
124
  await self.well_known_configuration_manager.get_async(auth_config=auth_config)
120
125
  await self.register_dynamic_provider(auth_config=auth_config)
@@ -113,6 +113,21 @@ class TokenReader:
113
113
 
114
114
  self.environment_variables: OidcEnvironmentVariables = environment_variables or OidcEnvironmentVariables()
115
115
 
116
+ @staticmethod
117
+ def _peek_issuer(*, token: str) -> str | None:
118
+ """Read ``iss`` from the UNVERIFIED payload, only to choose which provider keys to load.
119
+
120
+ Never used for the validation decision: the signature is verified and iss/aud are
121
+ checked against provider config afterwards, exactly as before.
122
+ """
123
+ try:
124
+ payload = json.loads(jws.extract_compact(token.encode()).payload)
125
+ except Exception as e:
126
+ logger.debug(f"Could not read iss from token payload ({type(e).__name__}); loading all providers")
127
+ return None
128
+ issuer = payload.get("iss") if isinstance(payload, dict) else None
129
+ return issuer if isinstance(issuer, str) else None
130
+
116
131
  @staticmethod
117
132
  def extract_token(*, authorization_header: str | None) -> Optional[str]:
118
133
  """
@@ -210,7 +225,8 @@ class TokenReader:
210
225
  # surfaces as a config error, not a per-request "invalid token" failure.
211
226
  leeway = self.environment_variables.jwt_clock_skew_leeway_seconds
212
227
 
213
- jwks: KeySet = await self._well_known_config_manager.get_jwks_async()
228
+ peeked_issuer = self._peek_issuer(token=token)
229
+ jwks: KeySet = await self._well_known_config_manager.get_jwks_for_issuer_async(issuer=peeked_issuer)
214
230
 
215
231
  # get kids from jwks for logging
216
232
  jwks_kids = [key.get("kid") for key in jwks.keys]
@@ -227,8 +243,8 @@ class TokenReader:
227
243
  verified = jwt.decode(token, jwks, algorithms=self.algorithms)
228
244
  except InvalidKeyIdError:
229
245
  logger.info("Unknown kid in token; refreshing JWKS from identity providers and retrying.")
230
- await self._well_known_config_manager.refresh_async()
231
- jwks = await self._well_known_config_manager.get_jwks_async()
246
+ await self._well_known_config_manager.refresh_for_issuer_async(issuer=peeked_issuer)
247
+ jwks = await self._well_known_config_manager.get_jwks_for_issuer_async(issuer=peeked_issuer)
232
248
  jwks_kids = [key.get("kid") for key in jwks.keys]
233
249
  verified = jwt.decode(token, jwks, algorithms=self.algorithms)
234
250
  issuer = verified.claims.get("iss")
@@ -362,8 +378,8 @@ class TokenReader:
362
378
  Call is_token_valid_async with an access token to get a boolean validity result.
363
379
  """
364
380
  assert access_token, "Access token must not be empty"
365
- jwks: KeySet = await self._well_known_config_manager.get_jwks_async()
366
381
  try:
382
+ jwks: KeySet = await self._well_known_config_manager.get_jwks_async()
367
383
  try:
368
384
  verified = jwt.decode(access_token, jwks, algorithms=self.algorithms)
369
385
  except InvalidKeyIdError:
@@ -0,0 +1,492 @@
1
+ import asyncio
2
+ import logging
3
+ import time
4
+ import warnings
5
+ from functools import partial
6
+ from typing import Awaitable, Callable, Dict, Any, TypeVar, cast
7
+
8
+ import httpx
9
+ from httpx import ConnectError
10
+ from joserfc.jwk import KeySet
11
+ from key_value.aio.stores.base import BaseStore
12
+ from key_value.aio.stores.memory import MemoryStore
13
+ from opentelemetry import trace
14
+ from pydantic import ValidationError
15
+
16
+ from oidcauthlib.auth.config.auth_config import AuthConfig
17
+ from oidcauthlib.auth.models.client_key_set import ClientKeySet
18
+ from oidcauthlib.auth.well_known_configuration.well_known_configuration_cache_result import (
19
+ WellKnownConfigurationCacheResult,
20
+ )
21
+ from oidcauthlib.open_telemetry.span_names import OidcOpenTelemetrySpanNames
22
+ from oidcauthlib.utilities.environment.oidc_environment_variables import (
23
+ OidcEnvironmentVariables,
24
+ )
25
+ from oidcauthlib.utilities.logger.log_levels import SRC_LOG_LEVELS
26
+ from oidcauthlib.open_telemetry.attribute_names import OidcOpenTelemetryAttributeNames
27
+ from oidcauthlib.utilities.url_validator import validate_url
28
+
29
+ logger = logging.getLogger(__name__)
30
+ logger.setLevel(SRC_LOG_LEVELS["AUTH"])
31
+
32
+ _T = TypeVar("_T")
33
+
34
+
35
+ class WellKnownConfigurationCache:
36
+ """Read-through accessor for OpenID Connect discovery documents and their JWKS.
37
+
38
+ Every read goes to the backing store (``well_known_store``; MongoDB in our services),
39
+ which is shared by all pods. This class keeps NO in-process copy of a discovery
40
+ document or of the JWKS, so a pod can never serve keys another pod has already
41
+ refreshed away. When no store is supplied (deprecated) a private ``MemoryStore`` is
42
+ used as the backing store, which keeps the old single-process behaviour.
43
+
44
+ Read path: store hit -> return. Store miss, expired row, bad row or stale schema ->
45
+ fetch from the issuer over HTTPS, upsert into the store with a TTL, return.
46
+
47
+ Single flight:
48
+ - Within a pod, concurrent callers for the same URI share one in-flight task and its
49
+ outcome, success or failure, so an unreachable issuer costs one timeout rather than one
50
+ per queued caller. The task is dropped as soon as it finishes; it never holds data. The
51
+ store is re-read inside the task so a row another pod just wrote is reused.
52
+ - Across pods, duplicate fetches are tolerated: the fetch is idempotent, the write is an
53
+ upsert, and the cost is at most one issuer fetch per pod per URI per TTL window. An
54
+ advisory lock is deliberately not used; a stuck lock would put a new failure mode on
55
+ the authentication path.
56
+
57
+ Expiry and key rotation:
58
+ - Rows are written with ``well_known_cache_ttl_seconds`` and carry ``fetched_at``; rows
59
+ older than the TTL are treated as misses even if the store did not expire them.
60
+ - ``refresh_async`` (called when a token's kid is unknown) refetches the issuer, but is
61
+ rate limited by the stored row's ``fetched_at`` (shared across pods), so a flood of
62
+ tokens with random kids cannot cause a refetch storm.
63
+
64
+ Failure behaviour (fail closed): store read/write errors and issuer errors propagate to
65
+ the caller. Nothing here ever skips signature validation or falls back to stale keys.
66
+
67
+ Public API:
68
+ - read_list_async(auth_configs): read-through for multiple configs.
69
+ - read_async(auth_config): read-through for one config.
70
+ - get_async(auth_config): read-through for one config (kept for compatibility).
71
+ - get_jwks_async(auth_configs): assemble a fresh KeySet from the store.
72
+ - refresh_async(auth_configs): rate-limited refetch for unknown-kid.
73
+ - get_client_key_set_for_kid_async(kid): look a kid up in the store.
74
+ - get_size_async(): number of readable rows for URIs this instance has seen.
75
+ - clear_async(): delete the rows for URIs this instance has seen.
76
+ """
77
+
78
+ def __init__(
79
+ self,
80
+ *,
81
+ well_known_store: BaseStore | None,
82
+ environment_variables: OidcEnvironmentVariables,
83
+ clock: Callable[[], float] = time.time,
84
+ ) -> None:
85
+ if well_known_store is not None and not isinstance(well_known_store, BaseStore):
86
+ raise TypeError(f"well_known_store must be an instance of BaseStore: {type(well_known_store)}")
87
+ self.environment_variables: OidcEnvironmentVariables = environment_variables
88
+ if not isinstance(environment_variables, OidcEnvironmentVariables):
89
+ raise TypeError(
90
+ f"environment_variables must be an instance of OidcEnvironmentVariables, got {type(environment_variables).__name__}"
91
+ )
92
+ self.well_known_store: BaseStore | None = well_known_store
93
+ if well_known_store is None:
94
+ message = (
95
+ "WellKnownConfigurationCache created without a well_known_store: discovery documents and JWKS "
96
+ "are held in this process only, so pods will not share or refresh them together. "
97
+ "Pass a shared BaseStore (e.g. MongoDB); store-less operation is deprecated."
98
+ )
99
+ logger.warning(message)
100
+ warnings.warn(message, DeprecationWarning, stacklevel=2)
101
+ self._store: BaseStore = well_known_store if well_known_store is not None else MemoryStore()
102
+ self._clock: Callable[[], float] = clock
103
+ # In-flight fetches within this process, keyed by (operation, URI). Entries exist only
104
+ # while the fetch runs and hold no cached data.
105
+ self._in_flight: Dict[tuple[str, str], asyncio.Future[Any]] = {}
106
+ # URIs this instance has been asked about (configuration, not cached data). The store
107
+ # has no key listing, so kid lookup and clear need to know which rows to consult.
108
+ self._known_uris: set[str] = set()
109
+
110
+ @property
111
+ def jwks(self) -> KeySet:
112
+ """Removed: the JWKS is no longer held in memory.
113
+
114
+ Raises:
115
+ RuntimeError: always. Use ``await get_jwks_async(auth_configs=...)``, which
116
+ assembles a KeySet from the backing store on every call.
117
+ """
118
+ raise RuntimeError(
119
+ "WellKnownConfigurationCache no longer holds a JWKS in memory; use get_jwks_async(auth_configs=...)"
120
+ )
121
+
122
+ async def read_list_async(self, *, auth_configs: list[AuthConfig]) -> None:
123
+ """Read (and fetch if missing or expired) discovery documents for multiple configs.
124
+
125
+ Configs without a ``well_known_uri`` are skipped.
126
+ """
127
+ tracer = trace.get_tracer(__name__)
128
+ with tracer.start_as_current_span(
129
+ OidcOpenTelemetrySpanNames.POPULATE_WELL_KNOWN_CONFIG_CACHE,
130
+ ):
131
+ await asyncio.gather(*[self.read_async(auth_config=c) for c in auth_configs if c.well_known_uri])
132
+ return None
133
+
134
+ async def get_jwks_async(self, *, auth_configs: list[AuthConfig]) -> KeySet:
135
+ """Assemble a KeySet from the backing store for the given configs.
136
+
137
+ The KeySet is built per call and not retained. Keys are de-duplicated by kid
138
+ (first provider wins), matching the previous behaviour.
139
+ """
140
+ results = await self._read_many_async(auth_configs=[c for c in auth_configs if c.well_known_uri])
141
+ keys: list[Dict[str, Any]] = []
142
+ seen_kids: set[Any] = set()
143
+ for result in results:
144
+ if result is None or result.client_key_set is None:
145
+ continue
146
+ for key in result.client_key_set.keys or []:
147
+ kid = key.get("kid")
148
+ if kid is not None and kid in seen_kids:
149
+ continue
150
+ seen_kids.add(kid)
151
+ keys.append(key)
152
+ if not keys:
153
+ return KeySet(keys=[])
154
+ return KeySet.import_key_set({"keys": keys})
155
+
156
+ async def _read_many_async(
157
+ self, *, auth_configs: list[AuthConfig]
158
+ ) -> list[WellKnownConfigurationCacheResult | None]:
159
+ """Read rows for several configs with ONE store round trip (get_many).
160
+
161
+ Configs whose row is missing, expired or unusable fall back to the single-config
162
+ read-through path (which fetches the issuer). A failing provider does not take down
163
+ the others: its error is logged and its keys are simply absent, so its own tokens
164
+ still fail closed. If no provider has a usable row and every fallback read fails, the first error is raised.
165
+ """
166
+ if not auth_configs:
167
+ return []
168
+ uris = [cast(str, c.well_known_uri) for c in auth_configs]
169
+ self._known_uris.update(uris)
170
+ rows = await self._store.get_many(keys=uris)
171
+ usable_rows = [self._parse_row(well_known_uri=uri, cached=row) for uri, row in zip(uris, rows)]
172
+ missing = [c for c, usable in zip(auth_configs, usable_rows) if usable is None]
173
+ fetched = iter(
174
+ self._tolerate_partial_failure(
175
+ outcomes=await asyncio.gather(
176
+ *[self.read_async(auth_config=c) for c in missing],
177
+ return_exceptions=True,
178
+ ),
179
+ uris=[cast(str, c.well_known_uri) for c in missing],
180
+ has_usable_rows=any(usable is not None for usable in usable_rows),
181
+ )
182
+ )
183
+ return [usable if usable is not None else next(fetched) for usable in usable_rows]
184
+
185
+ @staticmethod
186
+ def _tolerate_partial_failure(
187
+ *, outcomes: list[_T | BaseException], uris: list[str], has_usable_rows: bool
188
+ ) -> list[_T | None]:
189
+ """Turn per-provider failures into None unless every provider failed.
190
+
191
+ Isolates providers from each other's outages. Providers whose stored row was already
192
+ usable count as healthy: the error is raised only when no provider has a usable row and
193
+ every fetch failed, so there is nothing healthy to protect (fail closed, caller sees the cause).
194
+ """
195
+ failures = [o for o in outcomes if isinstance(o, BaseException)]
196
+ if outcomes and len(failures) == len(outcomes) and not has_usable_rows:
197
+ raise failures[0]
198
+ results: list[_T | None] = []
199
+ for uri, outcome in zip(uris, outcomes):
200
+ if isinstance(outcome, BaseException):
201
+ logger.error(f"Could not read OIDC configuration for {uri}; continuing without it: {outcome!r}")
202
+ results.append(None)
203
+ else:
204
+ results.append(outcome)
205
+ return results
206
+
207
+ def _is_fresh(self, *, result: WellKnownConfigurationCacheResult) -> bool:
208
+ if result.fetched_at is None:
209
+ # Row written before fetched_at existed: rely on the store's own TTL.
210
+ return True
211
+ age = self._clock() - result.fetched_at
212
+ return age <= self.environment_variables.well_known_cache_ttl_seconds
213
+
214
+ async def _read_stored_async(self, *, well_known_uri: str) -> WellKnownConfigurationCacheResult | None:
215
+ """Read one row from the store; None for a miss, unreadable, stale-schema, mismatched or expired row.
216
+
217
+ Store errors propagate (fail closed).
218
+ """
219
+ cached: dict[str, Any] | None = await self._store.get(key=well_known_uri)
220
+ return self._parse_row(well_known_uri=well_known_uri, cached=cached)
221
+
222
+ def _parse_row(
223
+ self, *, well_known_uri: str, cached: dict[str, Any] | None
224
+ ) -> WellKnownConfigurationCacheResult | None:
225
+ """Validate a raw stored row; None if absent, unreadable, stale-schema, mismatched or expired."""
226
+ if cached is None:
227
+ return None
228
+ try:
229
+ result = WellKnownConfigurationCacheResult.model_validate(cached)
230
+ except ValidationError as ve:
231
+ logger.info(
232
+ f"Stored data for {well_known_uri} failed validation ({ve.error_count()} error(s)); treating as miss"
233
+ )
234
+ return None
235
+ if not result.is_schema_current():
236
+ logger.info(
237
+ f"Stale schema version in store for {well_known_uri} "
238
+ f"(stored={result.schema_version}, current={WellKnownConfigurationCacheResult.SCHEMA_VERSION}); "
239
+ f"treating as miss"
240
+ )
241
+ return None
242
+ if result.well_known_uri != well_known_uri:
243
+ logger.warning(f"Stored row for {well_known_uri} names a different URI; treating as miss")
244
+ return None
245
+ if not self._is_fresh(result=result):
246
+ logger.info(f"Stored row for {well_known_uri} is older than the TTL; treating as miss")
247
+ return None
248
+ return result
249
+
250
+ def _discard_flight(self, key: tuple[str, str], flight: "asyncio.Future[Any]") -> None:
251
+ if self._in_flight.get(key) is flight:
252
+ del self._in_flight[key]
253
+
254
+ async def _single_flight_async(
255
+ self, *, operation: str, well_known_uri: str, work: Callable[[], Awaitable[_T]]
256
+ ) -> _T:
257
+ """Run ``work`` once per (operation, URI) at a time; concurrent callers share its outcome.
258
+
259
+ Success or failure is shared with everyone who arrived while it ran, so callers do not
260
+ queue up and repeat a timed-out fetch one after another. A caller arriving after it has
261
+ finished starts a new run. The entry is removed on completion and holds no data.
262
+ """
263
+ key = (operation, well_known_uri)
264
+ flight = self._in_flight.get(key)
265
+ if flight is None:
266
+ flight = asyncio.ensure_future(work())
267
+ self._in_flight[key] = flight
268
+ flight.add_done_callback(partial(self._discard_flight, key))
269
+ # shield: one waiter being cancelled must not cancel the fetch the others share
270
+ return cast(_T, await asyncio.shield(flight))
271
+
272
+ async def read_async(self, *, auth_config: AuthConfig) -> WellKnownConfigurationCacheResult | None:
273
+ """Return the discovery document for one config, reading the store on every call.
274
+
275
+ Args:
276
+ auth_config: OIDC authorization configuration providing well_known_uri.
277
+ Returns:
278
+ The result, or None if the config has no well_known_uri.
279
+ Raises:
280
+ ValueError: Missing required fields or non-2xx from the issuer.
281
+ ConnectionError: Network problems reaching the issuer.
282
+ Exception: Any store error (fail closed).
283
+ """
284
+ if auth_config is None:
285
+ raise ValueError("well_known_uri is not set")
286
+ well_known_uri: str | None = auth_config.well_known_uri
287
+ if not well_known_uri:
288
+ return None
289
+ self._known_uris.add(well_known_uri)
290
+
291
+ stored = await self._read_stored_async(well_known_uri=well_known_uri)
292
+ if stored is not None:
293
+ return stored
294
+
295
+ async def _read_or_fetch_async() -> WellKnownConfigurationCacheResult:
296
+ # Another pod may have filled the row since the read above.
297
+ stored = await self._read_stored_async(well_known_uri=well_known_uri)
298
+ if stored is not None:
299
+ return stored
300
+ logger.info(f"Store miss for {well_known_uri}; fetching from issuer")
301
+ return await self._fetch_and_store_async(auth_config=auth_config, well_known_uri=well_known_uri)
302
+
303
+ return await self._single_flight_async(
304
+ operation="read", well_known_uri=well_known_uri, work=_read_or_fetch_async
305
+ )
306
+
307
+ async def refresh_async(self, *, auth_configs: list[AuthConfig]) -> None:
308
+ """Refetch discovery documents and JWKS because a token presented an unknown kid.
309
+
310
+ Rate limited per URI: if the stored row was fetched less than
311
+ ``well_known_kid_miss_refetch_min_interval_seconds`` ago (by any pod), the refetch is
312
+ skipped and the caller's validation proceeds against the stored keys and fails closed.
313
+ The row is overwritten, never deleted first, so there is no window with no row.
314
+ One provider failing to refetch does not stop the others; if all fail the first error is raised.
315
+ """
316
+ targets = [c for c in auth_configs if c.well_known_uri]
317
+ self._tolerate_partial_failure(
318
+ outcomes=await asyncio.gather(
319
+ *[self._refresh_one_async(auth_config=c) for c in targets], return_exceptions=True
320
+ ),
321
+ uris=[cast(str, c.well_known_uri) for c in targets],
322
+ has_usable_rows=False,
323
+ )
324
+
325
+ async def _refresh_one_async(self, *, auth_config: AuthConfig) -> None:
326
+ well_known_uri = cast(str, auth_config.well_known_uri)
327
+ self._known_uris.add(well_known_uri)
328
+
329
+ async def _rate_limited_refetch_async() -> None:
330
+ stored = await self._read_stored_async(well_known_uri=well_known_uri)
331
+ if stored is not None and stored.fetched_at is not None:
332
+ age = self._clock() - stored.fetched_at
333
+ if age < self.environment_variables.well_known_kid_miss_refetch_min_interval_seconds:
334
+ logger.info(f"Skipping kid-miss refetch for {well_known_uri}: row is {age:.0f}s old (rate limited)")
335
+ return
336
+ await self._fetch_and_store_async(auth_config=auth_config, well_known_uri=well_known_uri)
337
+
338
+ await self._single_flight_async(
339
+ operation="refresh", well_known_uri=well_known_uri, work=_rate_limited_refetch_async
340
+ )
341
+
342
+ async def _fetch_and_store_async(
343
+ self, *, auth_config: AuthConfig, well_known_uri: str
344
+ ) -> WellKnownConfigurationCacheResult:
345
+ tracer = trace.get_tracer(__name__)
346
+ with tracer.start_as_current_span(
347
+ OidcOpenTelemetrySpanNames.READ_WELL_KNOWN_CONFIGURATION,
348
+ ) as span:
349
+ span.set_attribute(OidcOpenTelemetryAttributeNames.WELL_KNOWN_URI, well_known_uri)
350
+ validate_url(well_known_uri)
351
+ async with httpx.AsyncClient() as client:
352
+ try:
353
+ logger.info(f"Fetching OIDC discovery document from {well_known_uri}")
354
+ response = await client.get(
355
+ well_known_uri,
356
+ timeout=self.environment_variables.well_known_config_http_timeout_seconds,
357
+ )
358
+ response.raise_for_status()
359
+ config = cast(Dict[str, Any], response.json())
360
+ result = WellKnownConfigurationCacheResult(
361
+ schema_version=WellKnownConfigurationCacheResult.SCHEMA_VERSION,
362
+ well_known_uri=well_known_uri,
363
+ well_known_config=config,
364
+ client_key_set=await self._read_jwks_async(
365
+ auth_config=auth_config,
366
+ well_known_config=config,
367
+ ),
368
+ fetched_at=self._clock(),
369
+ )
370
+ except httpx.HTTPStatusError as e:
371
+ raise ValueError(
372
+ f"Failed to fetch OIDC discovery document from {well_known_uri} with status {e.response.status_code} : {e}"
373
+ )
374
+ except ConnectError as e:
375
+ raise ConnectionError(f"Failed to connect to OIDC discovery document: {well_known_uri}: {e}")
376
+ await self._store.put(
377
+ key=well_known_uri,
378
+ value=result.model_dump(),
379
+ ttl=self.environment_variables.well_known_cache_ttl_seconds,
380
+ )
381
+ logger.info(f"Stored OIDC discovery document for {well_known_uri}")
382
+ return result
383
+
384
+ @staticmethod
385
+ async def _read_jwks_uri_async(*, well_known_config: Dict[str, Any]) -> str | None:
386
+ """Extract the JWKS URI from the discovery document.
387
+
388
+ Args:
389
+ well_known_config: Parsed discovery document.
390
+ Returns:
391
+ JWKS URI string if present.
392
+ Raises:
393
+ ValueError: If jwks_uri or issuer is missing.
394
+ """
395
+ jwks_uri: str | None = well_known_config.get("jwks_uri")
396
+ issuer = well_known_config.get("issuer")
397
+ if not jwks_uri:
398
+ raise ValueError(f"jwks_uri not found in well-known configuration: {well_known_config}")
399
+ if not issuer:
400
+ raise ValueError(f"issuer not found in well-known configuration: {well_known_config}")
401
+ return jwks_uri
402
+
403
+ async def _read_jwks_async(
404
+ self, *, auth_config: AuthConfig, well_known_config: dict[str, Any]
405
+ ) -> ClientKeySet | None:
406
+ """Build a ClientKeySet by fetching keys from jwks_uri.
407
+
408
+ Args:
409
+ auth_config: The related OIDC config for context in ClientKeySet.
410
+ well_known_config: Discovery document containing jwks_uri.
411
+ Returns:
412
+ ClientKeySet with kids and keys, or None if jwks_uri missing or no keys.
413
+ """
414
+ jwks_uri = await self._read_jwks_uri_async(well_known_config=well_known_config)
415
+ if not jwks_uri:
416
+ logger.warning(f"AuthConfig {auth_config} does not have a JWKS URI, skipping JWKS fetch.")
417
+ return None
418
+
419
+ keys: list[Dict[str, Any]] = await self._read_jwks_from_uri_async(jwks_uri=jwks_uri)
420
+
421
+ if len(keys) > 0:
422
+ return ClientKeySet(
423
+ auth_config=auth_config,
424
+ well_known_config=well_known_config,
425
+ kids=[cast(str, key.get("kid")) for key in keys if key.get("kid") is not None],
426
+ keys=keys,
427
+ )
428
+ else:
429
+ return None
430
+
431
+ async def get_size_async(self) -> int:
432
+ """Return the number of readable rows for the URIs this instance has seen."""
433
+ results = await asyncio.gather(*[self._read_stored_async(well_known_uri=u) for u in set(self._known_uris)])
434
+ return sum(1 for r in results if r is not None)
435
+
436
+ async def clear_async(self) -> None:
437
+ """Delete the stored rows for the URIs this instance has seen.
438
+
439
+ In a shared store this removes the rows for every pod; the next read refetches.
440
+ """
441
+ if self._known_uris:
442
+ await self._store.delete_many(keys=list(self._known_uris))
443
+
444
+ async def get_client_key_set_for_kid_async(self, *, kid: str | None) -> ClientKeySet | None:
445
+ """Return the ClientKeySet containing the given kid, reading the store; None if absent."""
446
+ if kid is None:
447
+ return None
448
+ for well_known_uri in set(self._known_uris):
449
+ result = await self._read_stored_async(well_known_uri=well_known_uri)
450
+ client_key_set = result.client_key_set if result else None
451
+ if client_key_set and client_key_set.kids and kid in client_key_set.kids:
452
+ return client_key_set
453
+ return None
454
+
455
+ async def get_async(self, *, auth_config: AuthConfig) -> WellKnownConfigurationCacheResult | None:
456
+ """Return the discovery document for the config (read-through; fetches on miss)."""
457
+ return await self.read_async(auth_config=auth_config)
458
+
459
+ async def _read_jwks_from_uri_async(self, *, jwks_uri: str) -> list[Dict[str, Any]]:
460
+ """Fetch JWKS keys from the given JWKS URI.
461
+
462
+ Args:
463
+ jwks_uri: HTTPS URL to retrieve JWKS.
464
+ Returns:
465
+ A list of key dicts (deduplicated by kid) from the JWKS response.
466
+ Raises:
467
+ ValueError: Non-2xx HTTP status.
468
+ ConnectionError: When unable to reach the JWKS endpoint.
469
+ Security:
470
+ - Keys are not logged; only counts are logged to avoid PII/token leakage.
471
+ """
472
+ validate_url(jwks_uri)
473
+ async with httpx.AsyncClient() as client:
474
+ try:
475
+ logger.info(f"Fetching JWKS from {jwks_uri}")
476
+ response = await client.get(
477
+ jwks_uri,
478
+ timeout=self.environment_variables.well_known_config_http_timeout_seconds,
479
+ )
480
+ response.raise_for_status()
481
+ jwks_data: Dict[str, Any] = response.json()
482
+ keys: list[Dict[str, Any]] = []
483
+ for key in jwks_data.get("keys", []):
484
+ if not any([k.get("kid") == key.get("kid") for k in keys]):
485
+ keys.append(key)
486
+ logger.info(f"Successfully fetched JWKS from {jwks_uri}, keys= {len(keys)}")
487
+ return keys
488
+ except httpx.HTTPStatusError as e:
489
+ logger.exception(e)
490
+ raise ValueError(f"Failed to fetch JWKS from {jwks_uri} with status {e.response.status_code} : {e}")
491
+ except ConnectError as e:
492
+ raise ConnectionError(f"Failed to connect to JWKS URI: {jwks_uri}: {e}")
@@ -15,5 +15,10 @@ class WellKnownConfigurationCacheResult(BaseModel):
15
15
  well_known_config: dict[str, object] | None = Field(description="The OIDC well-known configuration document")
16
16
  client_key_set: ClientKeySet | None = Field(description="The client key set containing JWKS and related info")
17
17
 
18
+ fetched_at: float | None = Field(
19
+ default=None,
20
+ description="Epoch seconds when the issuer was fetched; lets readers enforce TTL and rate-limit refetches",
21
+ )
22
+
18
23
  def is_schema_current(self) -> bool:
19
24
  return self.schema_version == self.SCHEMA_VERSION