161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259 | async def verify( # type: ignore[override]
self,
token: str,
*,
issuer: Optional[str] = None,
audience: Optional[str | list[str]] = None,
leeway_s: int = -1,
) -> Dict[str, Any]:
"""
POST token to the introspection endpoint, validate standard fields, and return claims.
Raises ValueError on inactive/invalid tokens, or httpx.HTTPError on transport errors.
"""
if not isinstance(token, str) or not token:
raise ValueError("token must be a non-empty string")
# Cache lookup
now = time.time()
entry = self._cache.get(token)
if entry and entry.expires_at > now:
if not entry.ok:
raise ValueError("inactive_token (cached)")
claims = dict(entry.claims)
self._validate_claims(
claims, issuer=issuer, audience=audience, leeway_s=leeway_s
)
return claims
# Build request
form: Dict[str, Any] = {"token": token}
if self._hint:
form["token_type_hint"] = self._hint
headers = {}
if self._client_auth == "client_secret_basic":
headers["Authorization"] = "Basic " + _b64(
f"{self._client_id}:{self._client_secret}"
)
elif self._client_auth == "bearer":
headers["Authorization"] = f"Bearer {self._authorization}"
elif self._client_auth == "client_secret_post":
form["client_id"] = self._client_id
form["client_secret"] = self._client_secret
# Call endpoint
client = await self._get_client()
resp = await client.post(self._endpoint, data=form, headers=headers)
# Accept 200 only; some AS return 400 for malformed tokens (treat as inactive w/ negative cache)
if resp.status_code == 401 or resp.status_code == 403:
# Auth to introspection endpoint failed → configuration error
resp.raise_for_status()
if resp.status_code >= 500:
resp.raise_for_status()
if resp.status_code not in (200, 400):
resp.raise_for_status()
# Parse JSON
try:
data = resp.json()
except json.JSONDecodeError:
raise ValueError("introspection_response_not_json")
# RFC 7662: must include "active" boolean
active = bool(data.get("active", False))
if not active:
# Negative cache
if self._neg_ttl:
self._cache[token] = _CacheEntry(
ok=False, claims={}, expires_at=now + self._neg_ttl
)
raise ValueError("inactive_token")
# Normalize claims (copy)
claims: Dict[str, Any] = dict(data)
# Standardize time fields to int if present
for k in ("exp", "iat", "nbf"):
if k in claims:
try:
claims[k] = int(claims[k])
except Exception:
raise ValueError(f"invalid_{k}_claim")
# Optionally enforce iss/aud, exp/nbf/iat
self._validate_claims(
claims, issuer=issuer, audience=audience, leeway_s=leeway_s
)
# Cache positive results
ttl = self._cache_ttl
# If exp present, restrict TTL so we never cache past expiry
if "exp" in claims:
eff_leeway = self._leeway if leeway_s < 0 else int(leeway_s)
ttl = min(ttl, max(0, claims["exp"] - int(now) + eff_leeway))
if ttl > 0:
self._cache[token] = _CacheEntry(
ok=True, claims=claims, expires_at=now + ttl
)
return claims
|