ci: expand CI checks and make consumer sync opt-in

- Add Go, npm, Python, and Java validation to CI
- Run Go tests against PostgreSQL
- Record performance fixes in the report
This commit is contained in:
Gabriel20xx committed 2026-10-19 21:14:31 +00:00
1 parent 199a5efaef
commit 22887fef03
100 files changed
+9740 -429

No files matched your search

@@ -49,15 +49,26 @@ concrete Response object and knows how to attach headers to it.
from __future__ import annotations
import asyncio
import contextlib
import contextvars
import hashlib
import ipaddress
import json
import threading
import time
import urllib.error
import urllib.request
from collections.abc import Iterator
from dataclasses import dataclass, field
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.
VALIDATION_CACHE_TTL = 2.0
MAX_VALIDATION_CACHE_ENTRIES = 10000
_BEARER_PREFIX = "Bearer "
@@ -66,6 +77,34 @@ _BEARER_PREFIX = "Bearer "
# so it can enforce per-user project-access restriction (see AuthGuard's
# project-scope admin UI). Mirrors Go's authclient.ProjectKeyHeader.
PROJECT_KEY_HEADER = "X-Project-Key"
# Carries the end user's address on every AuthGuard call made inside a `forwarded_client_ip`
# block, so AuthGuard's per-address limits see the end user instead of this service. AuthGuard
# reads the header only when the calling service's own address is in its TRUSTED_PROXIES, so
# sending it changes nothing for a deployment that has not opted in.
FORWARDED_FOR_HEADER = "X-Forwarded-For"
_forwarded_client_ip: contextvars.ContextVar[str | None] = contextvars.ContextVar(
"authclient_forwarded_client_ip", default=None
)
@contextlib.contextmanager
def forwarded_client_ip(ip: str | None) -> Iterator[None]:
"""Makes AuthClient calls awaited inside the block send `ip` as X-Forwarded-For. Pass an
address the caller has already verified (see shared_backend.clientip.client_address), never a
raw request header. Anything that is not an IP address is ignored."""
token = _forwarded_client_ip.set(ip)
try:
yield
finally:
_forwarded_client_ip.reset(token)
def _valid_ip(value: str | None) -> str:
"""The canonical form of an IP address, or "" for anything else (no header injection)."""
try:
return str(ipaddress.ip_address((value or "").strip()))
except ValueError:
return ""
def _normalize_base_url(base_url: str) -> str:
@@ -233,6 +272,43 @@ class AuthClient:
# restriction. Normally a project's own lowercase identifier,
# matching the key ProjectConfigurator registers it under.
self.project_key = (project_key or "").strip().lower()
self._validation_lock = threading.Lock()
self._validation_cache: dict[str, tuple[float, AuthGuardUser | None]] = {}
@staticmethod
def _validation_key(token: str) -> str:
return hashlib.sha256(token.encode("utf-8")).hexdigest()
def _cached_validation(self, token: str) -> tuple[bool, AuthGuardUser | None]:
"""Returns (hit, user); user is None for a cached invalid session."""
key = self._validation_key(token)
with self._validation_lock:
entry = self._validation_cache.get(key)
if entry is None:
return False, None
expires, user = entry
if time.monotonic() >= expires:
del self._validation_cache[key]
return False, None
return True, user
def _cache_validation(self, token: str, user: AuthGuardUser | None) -> None:
with self._validation_lock:
if len(self._validation_cache) >= MAX_VALIDATION_CACHE_ENTRIES:
now = time.monotonic()
for key in [k for k, entry in self._validation_cache.items() if now >= entry[0]]:
del self._validation_cache[key]
if len(self._validation_cache) >= MAX_VALIDATION_CACHE_ENTRIES:
# dicts keep insertion order, so this drops the oldest entry.
del self._validation_cache[next(iter(self._validation_cache))]
self._validation_cache[self._validation_key(token)] = (
time.monotonic() + VALIDATION_CACHE_TTL,
user,
)
def _forget_validation(self, token: str) -> None:
with self._validation_lock:
self._validation_cache.pop(self._validation_key(token), None)
def set_base_url(self, base_url: str) -> None:
"""Atomically replaces the AuthGuard base URL this client calls,
@@ -248,6 +324,8 @@ class AuthClient:
normalized = _normalize_base_url(base_url)
if normalized:
self.base_url = normalized
with self._validation_lock:
self._validation_cache.clear()
# --- session validation (the original, minimal surface) ----------------
@@ -262,6 +340,11 @@ class AuthClient:
trimmed = (token or "").strip()
if not trimmed:
raise InvalidSessionError()
hit, cached = self._cached_validation(trimmed)
if hit:
if cached is None:
raise InvalidSessionError()
return cached
return await asyncio.to_thread(self._validate_sync, trimmed)
def _validate_sync(self, token: str) -> AuthGuardUser:
@@ -293,17 +376,23 @@ class AuthClient:
raise TypeError(f"expected a JSON object, got {type(payload).__name__}")
except (ValueError, TypeError, UnicodeDecodeError) as exc:
if status == 401:
self._cache_validation(token, None)
raise InvalidSessionError() from exc
raise AuthClientError(f"authclient: decode AuthGuard response: {exc}") from exc
if status != 200 or not payload.get("valid"):
if status == 401 or (status == 200 and not payload.get("valid")):
self._cache_validation(token, None)
raise InvalidSessionError()
if status != 200:
raise InvalidSessionError()
return AuthGuardUser(
user = AuthGuardUser(
id=int(payload.get("user_id") or 0),
username=str(payload.get("username") or ""),
role=str(payload.get("role") or ""),
)
self._cache_validation(token, user)
return user
# --- shared request/response plumbing for everything below -------------
@@ -333,6 +422,11 @@ class AuthClient:
headers: dict[str, str] = {}
if self.project_key:
headers[PROJECT_KEY_HEADER] = self.project_key
# asyncio.to_thread runs this in a copy of the caller's context, so the address set by
# forwarded_client_ip is visible here.
address = _valid_ip(_forwarded_client_ip.get())
if address:
headers[FORWARDED_FOR_HEADER] = address
if body is not None:
data = json.dumps(body).encode()
headers["Content-Type"] = "application/json"
@@ -435,6 +529,7 @@ class AuthClient:
server-side. Returns the (cookie-clearing) Set-Cookie header
value(s) AuthGuard's response carried."""
_, cookies = await self._call("POST", "/api/logout", token=token)
self._forget_validation((token or "").strip())
return cookies
async def me(self, token: str) -> PublicUser: