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

@@ -11,8 +11,13 @@ from .auth import (
can_assign_role,
can_manage_users,
hash_password,
hash_password_async,
normalize_role,
password_hash_needs_upgrade,
verify_and_upgrade_password,
verify_and_upgrade_password_async,
verify_password,
verify_password_async,
)
from .authclient import (
AuthClient,
@@ -25,6 +30,7 @@ from .authclient import (
from .config import DatabaseConfig, database_url_from_env
from .coreconfig import Info as CoreConfigInfo
from .coreconfig import Store as CoreConfigStore
from .coreconfig import internal_secret_matches
from .postgres import Database
from .tokens import hash_token, new_session_token
from .totp import generate_totp_secret, totp_provisioning_uri, verify_totp
@@ -40,6 +46,7 @@ __all__ = [
"token_from_request",
"CoreConfigInfo",
"CoreConfigStore",
"internal_secret_matches",
"ROLE_ADMIN",
"ROLE_SUPERADMIN",
"ROLE_USER",
@@ -52,10 +59,15 @@ __all__ = [
"database_url_from_env",
"generate_totp_secret",
"hash_password",
"hash_password_async",
"hash_token",
"new_session_token",
"normalize_role",
"password_hash_needs_upgrade",
"totp_provisioning_uri",
"verify_and_upgrade_password",
"verify_and_upgrade_password_async",
"verify_password",
"verify_password_async",
"verify_totp",
]
@@ -2,6 +2,7 @@
from __future__ import annotations
import asyncio
import secrets
import threading
from dataclasses import dataclass
@@ -30,9 +31,6 @@ ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAUL
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now();
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
UPDATE auth_users SET role = 'superadmin'
WHERE id = (SELECT id FROM auth_users ORDER BY created_at, id LIMIT 1)
AND NOT EXISTS (SELECT 1 FROM auth_users WHERE role = 'superadmin');
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx
ON auth_users (lower(email)) WHERE email <> '';
CREATE TABLE IF NOT EXISTS auth_sessions (
@@ -46,6 +44,39 @@ CREATE INDEX IF NOT EXISTS auth_sessions_expiry_idx ON auth_sessions (expires_at
CREATE INDEX IF NOT EXISTS auth_sessions_user_idx ON auth_sessions (user_id);
"""
# Usernames are unique ignoring case ("Admin" and "admin" are one identity to a reader). The index
# is created only while no such pair exists, so a database that already holds one still starts and
# raises a warning; it is built on the first start after one account of each pair is renamed.
_USERNAME_CASE_INDEX = """
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM auth_users GROUP BY lower(username) HAVING count(*) > 1) THEN
RAISE WARNING 'auth_users holds usernames that differ only by case; '
'the case-insensitive username index was not created';
ELSE
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_username_lower_idx
ON auth_users (lower(username));
END IF;
EXCEPTION WHEN unique_violation THEN
RAISE WARNING 'the case-insensitive username index was not created: a clashing username was '
'just added';
END
$$
"""
_ROLE_COLUMN_MISSING = """
SELECT NOT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema = current_schema() AND table_name = 'auth_users' AND column_name = 'role'
)
"""
_PROMOTE_OLDEST_SUPERADMIN = """
UPDATE auth_users SET role = 'superadmin'
WHERE id = (SELECT id FROM auth_users ORDER BY created_at, id LIMIT 1)
AND NOT EXISTS (SELECT 1 FROM auth_users WHERE role = 'superadmin')
"""
RESET_CODE_TTL = timedelta(minutes=5)
ROLE_SUPERADMIN = "superadmin"
@@ -107,10 +138,12 @@ class ResetManager:
@dataclass(frozen=True, slots=True)
class AuthUser:
"""A stored account. Only the lookups that verify credentials fill password_hash."""
id: int
username: str
email: str
password_hash: str
password_hash: str = ""
role: str = ROLE_USER
created_at: datetime | None = None
updated_at: datetime | None = None
@@ -120,26 +153,129 @@ class UserExistsError(Exception):
"""Raised when a user violates a unique or single-user constraint."""
class TotpAlreadyEnabledError(Exception):
"""Raised by set_totp_secret while two-factor auth is enabled."""
class EmptyPasswordHashError(ValueError):
"""Raised when a credential write carries no password hash."""
class InvalidUsernameError(ValueError):
"""Raised for a username containing "@", which would be read as an email."""
def _validate_credentials(username: str | None, password_hash: str | None) -> None:
"""Refuse a write that would leave an account without a password hash, or store a username
that could be mistaken for another account's email. None means "leave unchanged"."""
if password_hash is not None and not password_hash:
raise EmptyPasswordHashError("password hash is required")
if username is not None and "@" in username:
raise InvalidUsernameError("username cannot contain @")
# Every hash this module writes starts with this scheme prefix, so verification
# picks the algorithm from the stored value. The bcrypt string follows unchanged,
# so a stored value reads "bcrypt$$2b$12$...". Unprefixed bcrypt hashes written
# before the prefix still verify and are rewritten on the next successful login.
_BCRYPT_SCHEME = "bcrypt$"
_LEGACY_BCRYPT_PREFIXES = ("$2a$", "$2b$", "$2y$")
BCRYPT_ROUNDS = 12
def _new_bcrypt_hash(password: str) -> str:
hashed = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt(rounds=BCRYPT_ROUNDS))
return _BCRYPT_SCHEME + hashed.decode("utf-8")
# bcrypt reads only the first 72 bytes. Older bcrypt releases drop the rest silently, so the limit
# is enforced here instead of depending on the installed version.
MAX_PASSWORD_BYTES = 72
def hash_password(password: str) -> str:
if len(password) < 8:
raise ValueError("Password must be at least 8 characters")
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
if len(password.encode("utf-8")) > MAX_PASSWORD_BYTES:
raise ValueError(f"Password must be at most {MAX_PASSWORD_BYTES} bytes")
return _new_bcrypt_hash(password)
def _bcrypt_string_of(stored_hash: str) -> str | None:
if stored_hash.startswith(_BCRYPT_SCHEME):
return stored_hash[len(_BCRYPT_SCHEME) :]
if stored_hash.startswith(_LEGACY_BCRYPT_PREFIXES):
return stored_hash
return None
def verify_password(password: str, stored_hash: str) -> bool:
bcrypt_hash = _bcrypt_string_of(stored_hash)
if bcrypt_hash is None:
return False
try:
return bcrypt.checkpw(password.encode("utf-8"), stored_hash.encode("utf-8"))
return bcrypt.checkpw(password.encode("utf-8"), bcrypt_hash.encode("utf-8"))
except (ValueError, TypeError):
return False
def password_hash_needs_upgrade(stored_hash: str) -> bool:
"""True for an unprefixed legacy hash, or a bcrypt cost below BCRYPT_ROUNDS."""
if not stored_hash.startswith(_BCRYPT_SCHEME):
return True
# The bcrypt string after the prefix is "$2b$<cost>$<salt+hash>".
parts = stored_hash[len(_BCRYPT_SCHEME) :].split("$")
try:
return int(parts[2]) < BCRYPT_ROUNDS
except (IndexError, ValueError):
return True
def verify_and_upgrade_password(password: str, stored_hash: str) -> tuple[bool, str | None]:
"""Check a password and, on a match against an older scheme, return a replacement hash.
Returns (valid, upgraded_hash). upgraded_hash is None when the password does not match or
the stored hash is already current. Store upgraded_hash, for example with
AuthStore.update_user(user_id, password_hash=...).
"""
if not verify_password(password, stored_hash):
return False, None
if not password_hash_needs_upgrade(stored_hash):
return True, None
# The length rule applies when a password is first set, not when an old hash is upgraded.
return True, _new_bcrypt_hash(password)
async def hash_password_async(password: str) -> str:
"""Non-blocking hash_password: bcrypt runs in a worker thread."""
return await asyncio.to_thread(hash_password, password)
async def verify_password_async(password: str, stored_hash: str) -> bool:
"""Non-blocking verify_password: bcrypt runs in a worker thread."""
return await asyncio.to_thread(verify_password, password, stored_hash)
async def verify_and_upgrade_password_async(
password: str, stored_hash: str
) -> tuple[bool, str | None]:
"""Non-blocking verify_and_upgrade_password: bcrypt runs in a worker thread."""
return await asyncio.to_thread(verify_and_upgrade_password, password, stored_hash)
class AuthStore:
def __init__(self, database: Database, *, single_user: bool = True) -> None:
self.database = database
self.single_user = single_user
async def ensure_schema(self) -> None:
# Only a table that predates the role column needs its oldest account promoted, so the
# promotion runs once, in the migration that adds the column.
role_column_missing = await self.database.fetchval(_ROLE_COLUMN_MISSING)
await self.database.execute(_SCHEMA)
await self.database.execute(_USERNAME_CASE_INDEX)
if role_column_missing:
await self.database.execute(_PROMOTE_OLDEST_SUPERADMIN)
if self.single_user:
await self.database.execute(
"CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true))"
@@ -151,6 +287,7 @@ class AuthStore:
return int(await self.database.fetchval("SELECT count(*) FROM auth_users"))
async def create_user(self, username: str, email: str, password_hash: str) -> AuthUser:
_validate_credentials(username, password_hash or "")
try:
row = await self.database.fetchrow(
"""
@@ -159,7 +296,7 @@ class AuthStore:
CASE WHEN EXISTS (SELECT 1 FROM auth_users) THEN 'user'
ELSE 'superadmin' END,
now())
RETURNING id, username, email, password_hash, role, created_at, updated_at
RETURNING id, username, email, role, created_at, updated_at
""",
username,
email,
@@ -171,19 +308,25 @@ class AuthStore:
return AuthUser(**dict(row))
async def find_by_identifier(self, identifier: str) -> AuthUser | None:
row = await self.database.fetchrow(
"""
SELECT id, username, email, password_hash, role, created_at, updated_at
FROM auth_users
WHERE username = $1 OR lower(email) = lower($1)
""",
identifier,
)
return AuthUser(**dict(row)) if row else None
# Usernames are tried before emails, so an identifier resolves to one account in a
# fixed order.
for condition in ("username = $1", "lower(email) = lower($1)"):
row = await self.database.fetchrow(
f"""
SELECT id, username, email, password_hash, role, created_at, updated_at
FROM auth_users
WHERE {condition}
""",
identifier,
)
if row:
return AuthUser(**dict(row))
return None
async def update_credentials(
self, user_id: int, username: str, email: str, password_hash: str
) -> None:
_validate_credentials(username, password_hash or "")
await self.database.execute(
"""
UPDATE auth_users
@@ -224,7 +367,7 @@ class AuthStore:
async def list_users(self) -> list[AuthUser]:
rows = await self.database.fetch(
"SELECT id, username, email, role, password_hash, created_at, updated_at "
"SELECT id, username, email, role, created_at, updated_at "
"FROM auth_users ORDER BY created_at, id"
)
return [AuthUser(**dict(row)) for row in rows]
@@ -232,12 +375,13 @@ class AuthStore:
async def create_managed_user(
self, username: str, email: str, password_hash: str, role: str = ROLE_USER
) -> AuthUser:
_validate_credentials(username, password_hash or "")
try:
row = await self.database.fetchrow(
"""
INSERT INTO auth_users (username, email, password_hash, role, updated_at)
VALUES ($1, $2, $3, $4, now())
RETURNING id, username, email, password_hash, role, created_at, updated_at
RETURNING id, username, email, role, created_at, updated_at
""",
username,
email,
@@ -258,6 +402,7 @@ class AuthStore:
password_hash: str | None = None,
role: str | None = None,
) -> None:
_validate_credentials(username, password_hash)
fields: list[str] = []
values: list[object] = []
for column, value in (
@@ -293,12 +438,17 @@ class AuthStore:
return dict(row) if row else {"secret": "", "enabled": False}
async def set_totp_secret(self, user_id: int, secret: str) -> None:
await self.database.execute(
"""Stores a pending secret without enabling two-factor auth. Raises
TotpAlreadyEnabledError while it is enabled, so a replaced secret cannot silently switch
the second factor off."""
status = await self.database.execute(
"UPDATE auth_users SET totp_secret = $1, totp_enabled = false, "
"updated_at = now() WHERE id = $2",
"updated_at = now() WHERE id = $2 AND NOT totp_enabled",
secret,
user_id,
)
if status == "UPDATE 0" and (await self.get_totp_state(user_id))["enabled"]:
raise TotpAlreadyEnabledError("TOTP is already enabled; disable it first")
async def enable_totp(self, user_id: int) -> None:
await self.database.execute(
@@ -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:
@@ -61,7 +61,7 @@ from typing import Any, Callable, Optional
from fastapi import APIRouter, Depends, HTTPException, Request, Response
from pydantic import BaseModel
from .auth import ROLE_SUPERADMIN, can_manage_users, normalize_role
from .auth import MAX_PASSWORD_BYTES, ROLE_SUPERADMIN, can_manage_users, normalize_role
from .authclient import (
DEFAULT_COOKIE_NAME,
APIError,
@@ -69,11 +69,20 @@ from .authclient import (
AuthClientError,
ManagedUser,
PublicUser,
forwarded_client_ip,
)
from .clientip import client_address, parse_trusted_proxies, trusted_proxies_from_env
from .ratelimit import AttemptLimiter
__all__ = ["ProxyStore", "build_auth_router"]
MIN_PASSWORD_LEN = 8
# Attempt limits for login and the TOTP verify/disable routes, the same numbers as the Go proxy
# (backend/auth/ratelimit.go): each key may make `limit` attempts per window.
ATTEMPT_WINDOW_SECONDS = 15 * 60
LOGIN_ACCOUNT_LIMIT = 10
LOGIN_CLIENT_LIMIT = 200
TOTP_ATTEMPT_LIMIT = 5
MAX_USERNAME_LEN = 64
MAX_EMAIL_LEN = 254
@@ -81,6 +90,7 @@ ERR_AUTH_REQUIRED = "Authentication required."
ERR_SETUP_COMPLETE = "Setup has already been completed."
ERR_INVALID_CREDENTIALS = "Invalid username or password."
ERR_INVALID_INPUT = "Invalid authentication input."
ERR_TOO_MANY_ATTEMPTS = "Too many attempts. Try again later."
ERR_SELF_SERVICE_PROFILE = (
"Self-service profile editing is only available to administrator accounts; "
"ask an administrator to update this account."
@@ -93,6 +103,7 @@ ERR_FEATURE_REQUIRES_AUTHGUARD = "This feature requires AUTHGUARD_URL to be conf
# never this error - so every caller can safely report this same message
# rather than a generic "internal error" indistinguishable from any other bug.
ERR_AUTHGUARD_UNAVAILABLE = "Unable to reach the authentication service. Please try again shortly."
ERR_AUTHGUARD_NOT_CONFIGURED = "AUTHGUARD_URL is not configured, so sessions cannot be verified."
ERR_SECRET_NOT_SET = "SECRET environment variable is not set."
ERR_ADMIN_REQUIRED = "Administrator access required."
@@ -202,6 +213,11 @@ def _normalize_email(email: str) -> str:
def _validate_password(password: str) -> None:
if len(password or "") < MIN_PASSWORD_LEN:
raise HTTPException(status_code=400, detail="Password must be at least 8 characters.")
# bcrypt reads only the first 72 bytes, so a longer password could not be stored faithfully.
if len(password.encode("utf-8")) > MAX_PASSWORD_BYTES:
raise HTTPException(
status_code=400, detail=f"Password must be at most {MAX_PASSWORD_BYTES} bytes."
)
def _raise_authguard_error(err: Exception, fallback: str) -> None:
@@ -246,14 +262,38 @@ def build_auth_router(
cookie_name: str = DEFAULT_COOKIE_NAME,
configuration_error: str | None = None,
internal_secret: str | None = None,
local_profile_without_authguard: bool = False,
trusted_proxies: str | None = None,
) -> APIRouter:
"""Builds a ready-to-mount APIRouter implementing the full standardized
AuthGuard-proxy surface (no prefix baked in - mount it at "/api/auth",
matching every existing consumer). See the module docstring for the
`get_client`/`get_store` contract."""
`get_client`/`get_store` contract.
When `get_client` returns None (AUTHGUARD_URL unset) the guarded routes
refuse requests with a 500 unless `local_profile_without_authguard` is
True. Pass True only for a deployment that is meant to run without
AuthGuard; otherwise a missing environment variable would silently make
every guarded route run as the local superadmin.
Login and the TOTP routes refuse further attempts with 429: per account and per client
address for login (10 and 200 per 15 minutes), per user for TOTP verify and disable (5 per 15
minutes). The counters live in this process. The client address is the TCP peer;
`trusted_proxies` (default: the TRUSTED_PROXIES environment variable, a comma-separated list
of CIDR ranges or IP addresses, empty by default) names the reverse proxies whose
X-Forwarded-For is believed. An invalid list raises ValueError here, at startup. The address
is also sent to AuthGuard as X-Forwarded-For, which AuthGuard reads only from peers in its own
TRUSTED_PROXIES."""
router = APIRouter()
login_required_override: bool | None = None
trusted_networks = (
trusted_proxies_from_env()
if trusted_proxies is None
else parse_trusted_proxies(trusted_proxies)
)
login_account_attempts = AttemptLimiter(ATTEMPT_WINDOW_SECONDS, LOGIN_ACCOUNT_LIMIT)
login_client_attempts = AttemptLimiter(ATTEMPT_WINDOW_SECONDS, LOGIN_CLIENT_LIMIT)
totp_attempts = AttemptLimiter(ATTEMPT_WINDOW_SECONDS, TOTP_ATTEMPT_LIMIT)
configured_internal_secret = (
os.environ.get("SECRET", "") if internal_secret is None else internal_secret
).strip()
@@ -265,6 +305,21 @@ def build_auth_router(
def _enabled(client: Optional[AuthClient]) -> bool:
return client is not None
def _configured_client(
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> Optional[AuthClient]:
"""Resolves the route's AuthClient. A missing client fails closed with a
500 unless running without AuthGuard was opted into."""
if client is None and not local_profile_without_authguard:
raise HTTPException(
status_code=500, detail=configuration_error or ERR_AUTHGUARD_NOT_CONFIGURED
)
return client
def _client_address(request: Request) -> str:
peer = request.client.host if request.client else ""
return client_address(peer, request.headers.getlist("x-forwarded-for"), trusted_networks)
def _session_token(request: Request) -> str:
return request.cookies.get(cookie_name, "") or ""
@@ -307,14 +362,12 @@ def build_auth_router(
return profile, token
async def _login_required(store: ProxyStore) -> bool:
if login_required_override is not None:
return login_required_override
return await store.login_required()
async def require_session(
request: Request,
store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> PublicUser:
"""FastAPI dependency gating a route behind a valid session."""
if not _enabled(client) or not await _login_required(store):
@@ -326,7 +379,7 @@ def build_auth_router(
async def _require_user_manager(
request: Request,
store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> str:
"""Returns the caller's session token, or "" in auth-disabled mode
(each handler decides its own auth-disabled response). Authorization
@@ -341,7 +394,7 @@ def build_auth_router(
async def require_admin(
request: Request,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> PublicUser:
"""FastAPI dependency gating a route behind an administrator session
(the Python counterpart of Go's RequireAdmin). Unlike require_session it
@@ -362,7 +415,7 @@ def build_auth_router(
async def get_me(
request: Request,
store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, Any]:
_ensure_configured()
login_required = await _login_required(store)
@@ -383,7 +436,7 @@ def build_auth_router(
@router.get("/admin-needed")
async def get_admin_needed(
store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, bool]:
if not _enabled(client):
return {"adminNeeded": False}
@@ -402,7 +455,7 @@ def build_auth_router(
async def get_status(
request: Request,
store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, Any]:
_ensure_configured()
if not _enabled(client):
@@ -444,9 +497,10 @@ def build_auth_router(
@router.post("/setup", status_code=201)
async def setup(
req: SetupRequest,
request: Request,
response: Response,
store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
return {"user": _user_payload(_LOCAL_PROFILE)}
@@ -468,7 +522,8 @@ def build_auth_router(
raise HTTPException(status_code=409, detail=ERR_SETUP_COMPLETE)
try:
result = await client.register(username, email, req.password)
with forwarded_client_ip(_client_address(request)):
result = await client.register(username, email, req.password)
except AuthClientError as exc:
await store.unclaim_setup()
_raise_authguard_error(exc, "Could not create account.")
@@ -480,8 +535,9 @@ def build_auth_router(
@router.post("/login")
async def login(
req: LoginRequest,
request: Request,
response: Response,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
return {"user": _user_payload(_LOCAL_PROFILE)}
@@ -489,8 +545,13 @@ def build_auth_router(
identifier = (req.identifier or req.username or req.email or "").strip()
if not identifier or len(identifier) > MAX_EMAIL_LEN:
raise HTTPException(status_code=401, detail=ERR_INVALID_CREDENTIALS)
address = _client_address(request)
account_ok = login_account_attempts.allow(identifier.lower())
if not (account_ok and login_client_attempts.allow(address)):
raise HTTPException(status_code=429, detail=ERR_TOO_MANY_ATTEMPTS)
try:
result = await client.login(identifier, req.password, req.totpToken)
with forwarded_client_ip(address):
result = await client.login(identifier, req.password, req.totpToken)
except APIError as exc:
if exc.totp_required:
raise HTTPException(
@@ -513,7 +574,7 @@ def build_auth_router(
async def logout(
request: Request,
response: Response,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, bool]:
if _enabled(client):
assert client is not None
@@ -537,7 +598,7 @@ def build_auth_router(
async def update_me(
req: UpdateMeRequest,
request: Request,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD)
@@ -581,9 +642,7 @@ def build_auth_router(
store: ProxyStore = Depends(get_store), # noqa: B008
_admin: PublicUser = Depends(require_admin), # noqa: B008
) -> dict[str, bool]:
nonlocal login_required_override
await store.set_login_required(req.loginRequired)
login_required_override = req.loginRequired
return {"loginRequired": req.loginRequired}
@router.put("/access/internal")
@@ -592,21 +651,19 @@ def build_auth_router(
request: Request,
store: ProxyStore = Depends(get_store), # noqa: B008
) -> dict[str, bool]:
nonlocal login_required_override
if (
not configured_internal_secret
or request.headers.get("X-Internal-Auth") != configured_internal_secret
):
raise HTTPException(status_code=401, detail="internal service authentication required")
await store.set_login_required(req.loginRequired)
login_required_override = req.loginRequired
return {"loginRequired": req.loginRequired}
# --- admin user management ----------------------------------------------
@router.get("/users")
async def list_users(
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
token: str = Depends(_require_user_manager), # noqa: B008
) -> list[dict[str, Any]]:
if not _enabled(client):
@@ -622,7 +679,7 @@ def build_auth_router(
@router.post("/users", status_code=201)
async def create_managed_user(
req: ManagedUserRequest,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
token: str = Depends(_require_user_manager), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
@@ -642,7 +699,7 @@ def build_auth_router(
async def update_managed_user(
user_id: int,
req: ManagedUserRequest,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
token: str = Depends(_require_user_manager), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
@@ -673,7 +730,7 @@ def build_auth_router(
@router.delete("/users/{user_id}")
async def delete_managed_user(
user_id: int,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
token: str = Depends(_require_user_manager), # noqa: B008
) -> dict[str, bool]:
if not _enabled(client):
@@ -691,7 +748,7 @@ def build_auth_router(
@router.get("/totp/status")
async def get_totp_status(
request: Request,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, bool]:
if not _enabled(client):
return {"enabled": False, "mfaEnabled": False}
@@ -702,7 +759,7 @@ def build_auth_router(
@router.post("/totp/initiate")
async def initiate_totp(
request: Request,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD)
@@ -730,15 +787,18 @@ def build_auth_router(
async def verify_totp(
req: TotpTokenRequest,
request: Request,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD)
assert client is not None
_, token = await _current_profile_or_401(request, client)
profile, token = await _current_profile_or_401(request, client)
if not totp_attempts.allow(str(profile.id)):
raise HTTPException(status_code=429, detail=ERR_TOO_MANY_ATTEMPTS)
code = req.totpToken or req.token
try:
await client.totp_verify(token, code)
with forwarded_client_ip(_client_address(request)):
await client.totp_verify(token, code)
except Exception as exc:
raise HTTPException(status_code=401, detail="Invalid authenticator code.") from exc
return {"data": {"mfaEnabled": True, "enabled": True, "backupCodes": []}}
@@ -747,15 +807,18 @@ def build_auth_router(
async def disable_totp(
req: TotpTokenRequest,
request: Request,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD)
assert client is not None
_, token = await _current_profile_or_401(request, client)
profile, token = await _current_profile_or_401(request, client)
if not totp_attempts.allow(str(profile.id)):
raise HTTPException(status_code=429, detail=ERR_TOO_MANY_ATTEMPTS)
code = req.totpToken or req.token
try:
await client.totp_disable(token, code)
with forwarded_client_ip(_client_address(request)):
await client.totp_disable(token, code)
except Exception as exc:
raise HTTPException(status_code=401, detail="Invalid authenticator code.") from exc
return {"data": {"mfaEnabled": False, "enabled": False}}
@@ -0,0 +1,76 @@
"""Trusted-proxy-aware client address, the Python counterpart of backend/auth/clientip.go.
The address used for attempt limits and forwarded to AuthGuard is the TCP peer. X-Forwarded-For is
read only when that peer is inside a configured trusted-proxy list (the TRUSTED_PROXIES setting),
and is then walked from the right to the first hop that is not itself a trusted proxy. The list is
empty by default, so a client can never choose its own address.
"""
from __future__ import annotations
import ipaddress
import os
from collections.abc import Iterable, Mapping, Sequence
__all__ = ["client_address", "parse_trusted_proxies", "trusted_proxies_from_env"]
IPNetwork = ipaddress.IPv4Network | ipaddress.IPv6Network
IPAddress = ipaddress.IPv4Address | ipaddress.IPv6Address
def parse_trusted_proxies(value: str | None) -> list[IPNetwork]:
"""Parses a comma-separated list of CIDR ranges or bare IP addresses. An empty value trusts no
proxy. Raises ValueError for an entry that is neither."""
networks: list[IPNetwork] = []
for entry in (value or "").split(","):
entry = entry.strip()
if not entry:
continue
try:
networks.append(ipaddress.ip_network(entry, strict=False))
except ValueError as exc:
raise ValueError(
f"trusted proxy {entry!r} is neither an IP address nor a CIDR range"
) from exc
return networks
def trusted_proxies_from_env(env: Mapping[str, str] | None = None) -> list[IPNetwork]:
"""Reads the TRUSTED_PROXIES setting."""
source = os.environ if env is None else env
return parse_trusted_proxies(source.get("TRUSTED_PROXIES", ""))
def _parse_ip(value: str) -> IPAddress | None:
try:
ip = ipaddress.ip_address(value)
except ValueError:
return None
if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:
return ip.ipv4_mapped
return ip
def _is_trusted(ip: IPAddress, trusted: Sequence[IPNetwork]) -> bool:
return any(ip.version == network.version and ip in network for network in trusted)
def client_address(peer: str, forwarded_for: Iterable[str], trusted: Sequence[IPNetwork]) -> str:
"""Returns the address a request is counted against. peer is the TCP peer's host and
forwarded_for the values of every X-Forwarded-For header line. A malformed entry makes the peer
the answer, so a bad header can never choose the key."""
peer_ip = _parse_ip(peer)
if peer_ip is None or not _is_trusted(peer_ip, trusted):
return peer
hops = [part.strip() for line in forwarded_for for part in line.split(",") if part.strip()]
if not hops:
return peer
for hop in reversed(hops):
ip = _parse_ip(hop)
if ip is None:
return peer
if not _is_trusted(ip, trusted):
return str(ip)
# Every hop is a trusted proxy, so the left-most one is closest to the client.
first = _parse_ip(hops[0])
return str(first) if first is not None else peer
@@ -19,9 +19,29 @@ for a minimal FastAPI example.
from __future__ import annotations
import hmac
import threading
from dataclasses import dataclass, field
from typing import Callable, Optional
from urllib.parse import urlsplit
def internal_secret_matches(provided: Optional[str], secret: Optional[str]) -> bool:
"""True when the X-Internal-Auth value equals the configured secret. An
unset or empty secret never matches, and the comparison is constant-time."""
expected = (secret or "").encode("utf-8")
if not expected:
return False
return hmac.compare_digest(expected, (provided or "").encode("utf-8"))
def _is_service_url(value: str) -> bool:
try:
parts = urlsplit(value)
parts.port # noqa: B018 - raises ValueError for an invalid port
except ValueError:
return False
return parts.scheme in ("http", "https") and bool(parts.hostname)
@dataclass
@@ -104,17 +124,26 @@ class Store:
"""Replaces the current Info, field by field, ignoring a
blank/empty field so a partial push (e.g. only carrierNodeUrl(s)
changed) never clobbers the other value. Returns the resulting
Info. Minimal FastAPI usage:
Info. Every URL must be an http or https URL with a host; otherwise
nothing is changed and ValueError is raised. Minimal FastAPI usage:
@app.put("/api/core-services/internal")
async def push_core_services(request: Request):
if request.headers.get("X-Internal-Auth") != SECRET:
if not internal_secret_matches(request.headers.get("X-Internal-Auth"), SECRET):
raise HTTPException(status_code=401)
body = await request.json()
info = core_config_store.set(Info.from_json(body))
try:
info = core_config_store.set(Info.from_json(body))
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
return {"ok": True, "info": info.to_json()}
"""
next_info = _normalize(next_info)
for url in [next_info.auth_guard_url, *next_info.carrier_node_urls]:
if url and not _is_service_url(url):
raise ValueError(
f"core service URL must be an http or https URL with a host: {url}"
)
with self._lock:
if next_info.auth_guard_url:
self._info.auth_guard_url = next_info.auth_guard_url
@@ -15,6 +15,24 @@ from .config import DatabaseConfig
_logger = logging.getLogger(__name__)
# The same connection failures that database.js treats as transient: refused,
# reset and broken sockets, an administrative shutdown, a dropped connection
# (SQLSTATE class 08) and a connect timeout. Other errors, such as bad
# credentials or a missing database, are raised at once instead of retried.
_TRANSIENT_CONNECTION_ERRORS = (
ConnectionRefusedError,
ConnectionResetError,
BrokenPipeError,
TimeoutError,
asyncpg.exceptions.AdminShutdownError,
asyncpg.exceptions.PostgresConnectionError,
)
def is_transient_connection_error(exc: BaseException) -> bool:
"""Return True for connection failures that a startup retry can recover from."""
return isinstance(exc, _TRANSIENT_CONNECTION_ERRORS)
@dataclass(frozen=True, slots=True)
class StartupRetryOptions:
@@ -50,7 +68,11 @@ async def retry_startup(
operation: Callable[[], Awaitable[Any]],
options: StartupRetryOptions | None = None,
) -> Any:
"""Retry a startup operation until it succeeds or the context is cancelled."""
"""Retry a startup operation on transient connection errors only.
Any other exception is raised immediately, so a wrong password or a missing
database does not spin until the process is stopped.
"""
policy = options or startup_retry_options_from_env()
attempt = 0
@@ -61,6 +83,8 @@ async def retry_startup(
except asyncio.CancelledError:
raise
except Exception as exc:
if not is_transient_connection_error(exc):
raise
if policy.max_attempts and attempt >= policy.max_attempts:
raise
_logger.warning(
@@ -0,0 +1,47 @@
"""Fixed-window attempt counters for credential endpoints, the Python counterpart of
backend/auth/ratelimit.go. Counters live in this process; AuthGuard's own limits apply on top."""
from __future__ import annotations
import threading
import time
from collections.abc import Callable
__all__ = ["AttemptLimiter"]
MAX_TRACKED_ATTEMPT_KEYS = 10000
class AttemptLimiter:
"""Each key may make `limit` attempts per `window` seconds; further attempts are refused until
the window ends. When the table is full of live keys a new key is refused rather than tracked,
so flooding distinct keys cannot grow memory without bound."""
def __init__(
self, window: float, limit: int, *, clock: Callable[[], float] = time.monotonic
) -> None:
self._window = window
self._limit = limit
self._clock = clock
self._lock = threading.Lock()
self._counts: dict[str, tuple[float, int]] = {}
def allow(self, key: str) -> bool:
"""Records one attempt for key and reports whether it is within the limit."""
now = self._clock()
with self._lock:
tracked = key in self._counts
if not tracked and len(self._counts) >= MAX_TRACKED_ATTEMPT_KEYS:
self._counts = {
existing: state
for existing, state in self._counts.items()
if now - state[0] < self._window
}
if len(self._counts) >= MAX_TRACKED_ATTEMPT_KEYS:
return False
start, count = self._counts.get(key, (now, 0))
if now - start >= self._window:
start, count = now, 0
count += 1
self._counts[key] = (start, count)
return count <= self._limit
@@ -72,4 +72,5 @@ def _normalize_secret(value: str) -> str:
def _normalize_token(value: str) -> str:
token = str(value or "").strip()
return token if len(token) == TOTP_DIGITS and token.isdigit() else ""
# str.isdigit() accepts other scripts' digits too, and hmac.compare_digest refuses those.
return token if len(token) == TOTP_DIGITS and token.isascii() and token.isdigit() else ""