docs: record auth hash alignment and validation results

This commit is contained in:
Gabriel20xx committed 2026-10-20 15:26:58 +00:00
1 parent 22887fef03
commit f7819904b9
51 files changed
+1792 -542

No files matched your search

@@ -64,11 +64,14 @@ from typing import Any, Mapping
DEFAULT_COOKIE_NAME = "auth_session"
DEFAULT_TIMEOUT = 5.0
# validate() results, positive and negative, are reused for this many seconds so a burst of
# requests with one token costs one AuthGuard call. Revocation through this client (logout)
# clears the entry at once; revocation elsewhere is seen within the TTL. Mirrors the Go client.
# validate() results (positive and negative) and /api/me profiles are reused for this many
# seconds so a burst of requests with one token costs one AuthGuard call. Revocation through
# this client (logout) and token-authenticated writes clear both entries at once; changes made
# directly in AuthGuard may take up to two seconds to reach consumers.
VALIDATION_CACHE_TTL = 2.0
MAX_VALIDATION_CACHE_ENTRIES = 10000
PROFILE_CACHE_TTL = VALIDATION_CACHE_TTL
MAX_PROFILE_CACHE_ENTRIES = MAX_VALIDATION_CACHE_ENTRIES
_BEARER_PREFIX = "Bearer "
@@ -274,6 +277,7 @@ class AuthClient:
self.project_key = (project_key or "").strip().lower()
self._validation_lock = threading.Lock()
self._validation_cache: dict[str, tuple[float, AuthGuardUser | None]] = {}
self._profile_cache: dict[str, tuple[float, PublicUser]] = {}
@staticmethod
def _validation_key(token: str) -> str:
@@ -307,8 +311,36 @@ class AuthClient:
)
def _forget_validation(self, token: str) -> None:
"""Clears cached validation and /api/me data for this token."""
with self._validation_lock:
self._validation_cache.pop(self._validation_key(token), None)
key = self._validation_key(token)
self._validation_cache.pop(key, None)
self._profile_cache.pop(key, None)
def _cached_profile(self, token: str) -> tuple[bool, PublicUser | None]:
key = self._validation_key(token)
with self._validation_lock:
entry = self._profile_cache.get(key)
if entry is None:
return False, None
expires, profile = entry
if time.monotonic() >= expires:
del self._profile_cache[key]
return False, None
return True, profile
def _cache_profile(self, token: str, profile: PublicUser) -> None:
with self._validation_lock:
if len(self._profile_cache) >= MAX_PROFILE_CACHE_ENTRIES:
now = time.monotonic()
for key in [k for k, entry in self._profile_cache.items() if now >= entry[0]]:
del self._profile_cache[key]
if len(self._profile_cache) >= MAX_PROFILE_CACHE_ENTRIES:
del self._profile_cache[next(iter(self._profile_cache))]
self._profile_cache[self._validation_key(token)] = (
time.monotonic() + PROFILE_CACHE_TTL,
profile,
)
def set_base_url(self, base_url: str) -> None:
"""Atomically replaces the AuthGuard base URL this client calls,
@@ -326,6 +358,7 @@ class AuthClient:
self.base_url = normalized
with self._validation_lock:
self._validation_cache.clear()
self._profile_cache.clear()
# --- session validation (the original, minimal surface) ----------------
@@ -465,6 +498,9 @@ class AuthClient:
message = str(payload.get("error") or f"request failed ({status})")
raise APIError(status, message, totp_required=bool(payload.get("totp_required")))
if token and method.upper() not in {"GET", "HEAD"}:
self._forget_validation(token)
return payload, list(cookies)
@staticmethod
@@ -533,9 +569,26 @@ class AuthClient:
return cookies
async def me(self, token: str) -> PublicUser:
"""Calls GET /api/me, resolving token to its account."""
payload, _ = await self._call("GET", "/api/me", token=token)
return self._public_user(payload)
"""Calls GET /api/me, resolving token to its account.
Successful profiles are cached by the SHA-256 token digest for the
same short window as validate(). This keeps protected API calls from
blocking on one AuthGuard round trip each while bounding how long an
external profile change or session revocation can remain stale.
"""
if not self.base_url:
raise AuthClientError("authclient: client has no base URL")
trimmed = (token or "").strip()
if trimmed:
hit, cached = self._cached_profile(trimmed)
if hit:
assert cached is not None
return cached
payload, _ = await self._call("GET", "/api/me", token=trimmed)
profile = self._public_user(payload)
if trimmed:
self._cache_profile(trimmed, profile)
return profile
# --- TOTP ------------------------------------------------------------------