ci: expand shared package validation and test coverage
Lint / Lint (push) Successful in 32s
Docker / Docker Build & Push (push) Failing after 2m22s
Tests / Go backend (push) Failing after 1m2s
Tests / Dashboard checks (push) Failing after 35s

- Add lint, formatting, vet, and publish workflow checks
- Run Go database tests with PostgreSQL and add Java tests
- Make consumer sync opt-in; update docs and Go dependency
This commit is contained in:
Gabriel20xx committed 2026-10-19 21:46:52 +00:00
1 parent 937f51b4fb
commit 0ff94f9b10
107 files changed
+10124 -410

No files matched your search

+26 -5
View File
@@ -4,7 +4,7 @@ Shared Python backend infrastructure for services using `asyncpg`:
- validated `DATABASE_URL` and pool settings;
- one async pool owner with startup retry, ping, and graceful shutdown;
- bcrypt password and secure session-token helpers;
- bcrypt password helpers (`verify_and_upgrade_password_async` returns a current-scheme hash for a login to store) and secure session-token helpers;
- short-lived, one-time admin reset codes printed to the server console;
- common account/session persistence for the single-admin or optional multi-user model;
- an `authclient` module for services that adopt AuthGuard, the centralized
@@ -20,7 +20,25 @@ pip install "git+https://repos.gfranz.ch/Gabriel20xx/shared@v0.1.0#subdirectory=
```
Database startup uses `DB_INIT_RETRY_INTERVAL_MS` (default `5000`, minimum
`250`) and `DB_INIT_RETRY_MAX_ATTEMPTS` (default `0`, retry indefinitely).
`250`) and `DB_INIT_RETRY_MAX_ATTEMPTS` (default `0`, retry indefinitely). Only
transient connection errors are retried; bad credentials or a missing database
fail at once.
`authproxy.build_auth_router` limits login attempts (10 per account and 200 per
client address per 15 minutes) and TOTP verify/disable attempts (5 per user), in
process memory, and answers `429` beyond that. The client address is the TCP
peer; `X-Forwarded-For` is read only from peers inside `TRUSTED_PROXIES` (a
comma-separated list of CIDR ranges or IP addresses, empty by default; the
`trusted_proxies` argument overrides it, and an invalid list raises
`ValueError` at startup). The same address reaches AuthGuard as
`X-Forwarded-For` through `authclient.forwarded_client_ip`, which AuthGuard reads
only from peers in its own `TRUSTED_PROXIES`.
`AuthStore` refuses an empty password hash and a username containing `@`
(`EmptyPasswordHashError`, `InvalidUsernameError` in `shared_backend.auth`),
refuses `set_totp_secret` while TOTP is enabled (`TotpAlreadyEnabledError`), and
makes usernames unique ignoring case when no clashing pair already exists.
`hash_password` refuses a password longer than 72 bytes, the most bcrypt reads.
## `authclient`: adopting AuthGuard instead of local auth
@@ -92,7 +110,7 @@ give it, and updated live whenever ProjectConfigurator pushes a fresh
`PUT /api/core-services/internal`. A service wires the actual route itself:
```python
from shared_backend import AuthClient, CoreConfigInfo, CoreConfigStore
from shared_backend import AuthClient, CoreConfigInfo, CoreConfigStore, internal_secret_matches
auth_client = AuthClient("") # pending: no URL yet, still safe to use
core_config = CoreConfigStore(CoreConfigInfo(auth_guard_url=""))
@@ -101,10 +119,13 @@ core_config.on_update(lambda info: auth_client.set_base_url(info.auth_guard_url)
# in your framework's route for PUT /api/core-services/internal:
async def push_core_services(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.set(CoreConfigInfo.from_json(body))
try:
info = core_config.set(CoreConfigInfo.from_json(body))
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
return {"ok": True, "info": info.to_json()}
```
@@ -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 ""
@@ -0,0 +1,81 @@
import unittest
from shared_backend.clientip import client_address, parse_trusted_proxies
from shared_backend.ratelimit import MAX_TRACKED_ATTEMPT_KEYS, AttemptLimiter
class ParseTrustedProxiesTests(unittest.TestCase):
def test_accepts_cidrs_and_bare_addresses(self) -> None:
networks = parse_trusted_proxies(" 10.0.0.0/8, 192.168.1.5 ,fd00::/8,, ::1 ")
self.assertEqual(
[str(network) for network in networks],
["10.0.0.0/8", "192.168.1.5/32", "fd00::/8", "::1/128"],
)
def test_empty_trusts_no_proxy(self) -> None:
self.assertEqual(parse_trusted_proxies(" "), [])
self.assertEqual(parse_trusted_proxies(None), [])
def test_rejects_invalid_entries(self) -> None:
for value in ("not-an-ip", "10.0.0.0/33", "10.0.0.1, bogus"):
with self.assertRaises(ValueError, msg=value):
parse_trusted_proxies(value)
class ClientAddressTests(unittest.TestCase):
def test_forwarded_for_is_ignored_without_trusted_proxies(self) -> None:
self.assertEqual(client_address("203.0.113.7", ["198.51.100.1"], []), "203.0.113.7")
def test_forwarded_for_is_ignored_from_an_unknown_peer(self) -> None:
trusted = parse_trusted_proxies("10.0.0.0/8")
self.assertEqual(client_address("203.0.113.7", ["198.51.100.1"], trusted), "203.0.113.7")
def test_a_trusted_peer_has_its_header_honoured(self) -> None:
trusted = parse_trusted_proxies("10.0.0.0/8, 172.16.0.0/12")
cases = [
("single client", ["198.51.100.9"], "198.51.100.9"),
("second trusted hop", ["198.51.100.9, 172.16.4.4"], "198.51.100.9"),
("spoofed left-most entry", ["6.6.6.6, 198.51.100.9, 172.16.4.4"], "198.51.100.9"),
("entries across header lines", ["6.6.6.6", "198.51.100.9"], "198.51.100.9"),
("malformed entry", ["198.51.100.9, not-an-ip"], "10.0.0.2"),
("no header", [], "10.0.0.2"),
("every hop trusted", ["10.1.1.1, 172.16.4.4"], "10.1.1.1"),
]
for name, forwarded, want in cases:
with self.subTest(name):
self.assertEqual(client_address("10.0.0.2", forwarded, trusted), want)
def test_an_ipv4_mapped_peer_matches_an_ipv4_range(self) -> None:
trusted = parse_trusted_proxies("10.0.0.0/8")
self.assertEqual(
client_address("::ffff:10.0.0.2", ["198.51.100.9"], trusted), "198.51.100.9"
)
def test_a_non_ip_peer_is_returned_as_is(self) -> None:
self.assertEqual(client_address("testclient", ["198.51.100.9"], []), "testclient")
class AttemptLimiterTests(unittest.TestCase):
def test_window_and_limit(self) -> None:
now = [1000.0]
limiter = AttemptLimiter(60, 2, clock=lambda: now[0])
self.assertTrue(limiter.allow("k"))
self.assertTrue(limiter.allow("k"))
self.assertFalse(limiter.allow("k"))
self.assertTrue(limiter.allow("other"))
now[0] += 60
self.assertTrue(limiter.allow("k"))
def test_the_table_is_bounded(self) -> None:
now = [0.0]
limiter = AttemptLimiter(3600, 1, clock=lambda: now[0])
for i in range(MAX_TRACKED_ATTEMPT_KEYS):
limiter.allow(str(i))
self.assertFalse(limiter.allow("new-key"))
self.assertFalse(limiter.allow("0")) # a tracked key keeps its own count
now[0] += 3600 # every window has ended, so stale keys are dropped to make room
self.assertTrue(limiter.allow("new-key"))
if __name__ == "__main__":
unittest.main()
@@ -13,6 +13,7 @@ from shared_backend.authclient import (
InvalidSessionError,
ManagedUser,
PublicUser,
forwarded_client_ip,
resolve_user,
token_from_request,
)
@@ -49,6 +50,37 @@ def _fake_http_error(status: int, payload: dict) -> urllib.error.HTTPError:
)
class AuthClientForwardedClientIpTests(unittest.IsolatedAsyncioTestCase):
"""forwarded_client_ip makes credential calls carry the end user's address (S-009)."""
async def _login_request(self, address):
client = AuthClient("https://authguard.example")
payload = {"user": {"id": 1, "username": "a", "email": "", "role": "user"}}
with patch(
"shared_backend.authclient.urllib.request.urlopen",
return_value=_FakeResponse(200, payload),
) as urlopen:
if address is None:
await client.login("a", "secret-password")
else:
with forwarded_client_ip(address):
await client.login("a", "secret-password")
return urlopen.call_args.args[0]
async def test_the_address_is_sent_as_x_forwarded_for(self) -> None:
request = await self._login_request("203.0.113.9")
self.assertEqual(request.get_header("X-forwarded-for"), "203.0.113.9")
async def test_no_header_is_sent_outside_the_block(self) -> None:
request = await self._login_request(None)
self.assertIsNone(request.get_header("X-forwarded-for"))
async def test_a_value_that_is_not_an_ip_address_is_dropped(self) -> None:
for value in ("203.0.113.9\r\nX-Evil: 1", "not-an-ip", ""):
request = await self._login_request(value)
self.assertIsNone(request.get_header("X-forwarded-for"), repr(value))
class AuthClientBaseUrlTests(unittest.TestCase):
def test_bare_public_host_assumes_https(self) -> None:
self.assertEqual(AuthClient("auth.example.com").base_url, "https://auth.example.com")
@@ -155,6 +187,57 @@ class AuthClientValidateTests(unittest.IsolatedAsyncioTestCase):
await self.client.validate("a-token")
class AuthClientValidationCacheTests(unittest.IsolatedAsyncioTestCase):
def setUp(self) -> None:
self.client = AuthClient("https://authguard.example")
payload = {"valid": True, "user_id": 42, "username": "alice", "role": "admin"}
self.valid = _FakeResponse(200, payload)
async def test_repeated_validate_reuses_the_answer(self) -> None:
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=self.valid
) as urlopen:
first = await self.client.validate("a-token")
second = await self.client.validate("a-token")
self.assertEqual(first, second)
urlopen.assert_called_once()
async def test_invalid_session_is_cached_too(self) -> None:
with patch(
"shared_backend.authclient.urllib.request.urlopen",
return_value=_FakeResponse(401, {"valid": False}),
) as urlopen:
with self.assertRaises(InvalidSessionError):
await self.client.validate("bad-token")
with self.assertRaises(InvalidSessionError):
await self.client.validate("bad-token")
urlopen.assert_called_once()
async def test_logout_drops_the_cached_answer(self) -> None:
with patch(
"shared_backend.authclient.urllib.request.urlopen",
side_effect=[self.valid, _FakeResponse(200, {}), _FakeResponse(401, {"valid": False})],
) as urlopen:
await self.client.validate("a-token")
await self.client.logout("a-token")
with self.assertRaises(InvalidSessionError):
await self.client.validate("a-token")
self.assertEqual(urlopen.call_count, 3)
async def test_set_base_url_clears_the_cache(self) -> None:
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=self.valid
) as urlopen:
await self.client.validate("a-token")
self.client.set_base_url("https://authguard2.example")
await self.client.validate("a-token")
self.assertEqual(urlopen.call_count, 2)
class TokenFromRequestTests(unittest.TestCase):
def test_prefers_authorization_header_over_cookie(self) -> None:
headers = {"Authorization": "Bearer header-token"}
@@ -10,6 +10,7 @@ from shared_backend.authclient import (
AuthClient,
PublicUser,
SessionResult,
_forwarded_client_ip,
)
@@ -44,6 +45,8 @@ def _build_app(
client: AuthClient | None = None,
*,
internal_secret: str | None = None,
local_profile_without_authguard: bool = False,
trusted_proxies: str = "",
) -> FastAPI:
def get_client(request: Request) -> AuthClient | None:
return client
@@ -53,15 +56,23 @@ def _build_app(
app = FastAPI()
app.include_router(
ap.build_auth_router(get_client, get_store, internal_secret=internal_secret),
ap.build_auth_router(
get_client,
get_store,
internal_secret=internal_secret,
local_profile_without_authguard=local_profile_without_authguard,
trusted_proxies=trusted_proxies,
),
prefix="/api/auth",
)
return app
class AuthDisabledModeTests(unittest.TestCase):
"""client=None (AUTHGUARD_URL unset) - every route reports the fixed
placeholder superadmin identity and nothing is gated. This is also a
"""client=None (AUTHGUARD_URL unset) with the local-mode opt-in - every
route reports the fixed placeholder superadmin identity and nothing is
gated. Without the opt-in the same deployment fails closed; see
UnconfiguredAuthGuardTests. This is also a
regression test for a real bug this module had: request/response models
declared *inside* build_auth_router, combined with `from __future__
import annotations`, made FastAPI silently misparse every JSON body as a
@@ -69,7 +80,7 @@ class AuthDisabledModeTests(unittest.TestCase):
bug)."""
def setUp(self) -> None:
self.client = TestClient(_build_app(_FakeStore()))
self.client = TestClient(_build_app(_FakeStore(), local_profile_without_authguard=True))
def test_status_reports_local_superadmin(self) -> None:
response = self.client.get("/api/auth/status")
@@ -118,6 +129,25 @@ class AuthDisabledModeTests(unittest.TestCase):
self.assertEqual(self.client.put("/api/auth/me", json={}).status_code, 409)
class UnconfiguredAuthGuardTests(unittest.TestCase):
"""client=None without local_profile_without_authguard: a missing
AUTHGUARD_URL must not turn guarded routes into the local superadmin."""
def setUp(self) -> None:
self.client = TestClient(
_build_app(_FakeStore(login_required=True)), raise_server_exceptions=False
)
def test_guarded_routes_fail_closed(self) -> None:
self.assertEqual(self.client.get("/api/auth/status").status_code, 500)
self.assertEqual(self.client.get("/api/auth/me").status_code, 500)
self.assertEqual(self.client.get("/api/auth/users").status_code, 500)
self.assertEqual(self.client.post("/api/auth/logout").status_code, 500)
def test_login_flag_read_is_still_public(self) -> None:
self.assertEqual(self.client.get("/api/auth/access").json(), {"loginRequired": True})
class AccessSettingsTests(unittest.TestCase):
def test_get_is_public_and_put_requires_an_admin_session(self) -> None:
store = _FakeStore(login_required=True)
@@ -142,7 +172,7 @@ class AccessSettingsTests(unittest.TestCase):
store = _FakeStore(login_required=True)
client = TestClient(_build_app(store))
response = client.put("/api/auth/access", json={"loginRequired": False})
self.assertEqual(response.status_code, 401)
self.assertEqual(response.status_code, 500)
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
def test_internal_update_disables_login_and_uses_admin_identity(self) -> None:
@@ -275,12 +305,142 @@ class EnabledModeSetupAndLoginTests(unittest.TestCase):
self.assertIsNone(body["user"])
class _AddressRecordingClient(_RoleClient):
"""Records the address AuthClient would send as X-Forwarded-For for each credential call, and
counts the calls that reached AuthGuard."""
def __init__(self) -> None:
super().__init__()
self.forwarded: list[str | None] = []
self.login_calls = 0
self.totp_calls = 0
async def login(self, username_or_email: str, password: str, totp_token: str = ""):
self.login_calls += 1
self.forwarded.append(_forwarded_client_ip.get())
return await super().login(username_or_email, password, totp_token)
async def register(self, username: str, email: str, password: str) -> SessionResult:
self.forwarded.append(_forwarded_client_ip.get())
return await super().register(username, email, password)
async def totp_verify(self, token: str, code: str) -> None:
self.totp_calls += 1
self.forwarded.append(_forwarded_client_ip.get())
if code != "123456":
raise APIError(401, "bad code")
async def totp_disable(self, token: str, code: str) -> None:
self.totp_calls += 1
self.forwarded.append(_forwarded_client_ip.get())
raise APIError(401, "bad code")
class AttemptLimitTests(unittest.TestCase):
"""Login and the TOTP routes refuse further attempts with 429 (S-009)."""
def _login(self, client: TestClient, identifier: str = "Victim") -> int:
response = client.post(
"/api/auth/login", json={"identifier": identifier, "password": "wrong"}
)
return response.status_code
def test_login_is_limited_per_account_before_authguard_is_called(self) -> None:
fake = _AddressRecordingClient()
client = TestClient(_build_app(_FakeStore(), fake))
for attempt in range(ap.LOGIN_ACCOUNT_LIMIT):
self.assertEqual(self._login(client), 401, f"attempt {attempt + 1}")
self.assertEqual(self._login(client), 429)
self.assertEqual(self._login(client, "VICTIM"), 429) # the account key ignores case
self.assertEqual(fake.login_calls, ap.LOGIN_ACCOUNT_LIMIT)
self.assertEqual(self._login(client, "someone-else"), 401)
def test_login_is_limited_per_client_address(self) -> None:
fake = _AddressRecordingClient()
client = TestClient(_build_app(_FakeStore(), fake), client=("203.0.113.7", 40000))
statuses = [self._login(client, f"user{i}") for i in range(ap.LOGIN_CLIENT_LIMIT + 1)]
self.assertEqual(statuses[:-1], [401] * ap.LOGIN_CLIENT_LIMIT)
self.assertEqual(statuses[-1], 429)
def test_totp_verify_and_disable_share_a_per_user_limit(self) -> None:
fake = _AddressRecordingClient()
client = TestClient(_build_app(_FakeStore(), fake))
client.cookies.set(DEFAULT_COOKIE_NAME, "user-token")
for _ in range(ap.TOTP_ATTEMPT_LIMIT - 1):
response = client.post("/api/auth/totp/verify", json={"totpToken": "000000"})
self.assertEqual(response.status_code, 401)
self.assertEqual(
client.post("/api/auth/totp/disable", json={"totpToken": "000000"}).status_code, 401
)
self.assertEqual(
client.post("/api/auth/totp/verify", json={"totpToken": "123456"}).status_code, 429
)
self.assertEqual(
client.post("/api/auth/totp/disable", json={"totpToken": "000000"}).status_code, 429
)
self.assertEqual(fake.totp_calls, ap.TOTP_ATTEMPT_LIMIT)
class ClientAddressForwardingTests(unittest.TestCase):
"""The client address is the TCP peer unless the peer is a trusted proxy (decision 5), and it
reaches AuthGuard as X-Forwarded-For through forwarded_client_ip."""
def _login_address(self, *, peer: str, trusted: str, forwarded: str | None) -> str | None:
fake = _AddressRecordingClient()
client = TestClient(
_build_app(_FakeStore(), fake, trusted_proxies=trusted), client=(peer, 40000)
)
headers = {"X-Forwarded-For": forwarded} if forwarded is not None else {}
response = client.post(
"/api/auth/login",
json={"identifier": "a@b.com", "password": "correct"},
headers=headers,
)
self.assertEqual(response.status_code, 200)
return fake.forwarded[-1]
def test_the_tcp_peer_is_forwarded_without_trusted_proxies(self) -> None:
got = self._login_address(peer="203.0.113.7", trusted="", forwarded="6.6.6.6")
self.assertEqual(got, "203.0.113.7")
def test_a_spoofed_header_from_an_untrusted_peer_is_ignored(self) -> None:
got = self._login_address(peer="203.0.113.7", trusted="10.0.0.0/8", forwarded="6.6.6.6")
self.assertEqual(got, "203.0.113.7")
def test_a_trusted_peer_has_its_header_walked_right_to_left(self) -> None:
got = self._login_address(
peer="10.0.0.2", trusted="10.0.0.0/8", forwarded="6.6.6.6, 198.51.100.9, 10.0.0.1"
)
self.assertEqual(got, "198.51.100.9")
def test_setup_and_totp_forward_the_address_too(self) -> None:
fake = _AddressRecordingClient()
fake.setup_required = True
client = TestClient(_build_app(_FakeStore(), fake), client=("198.51.100.20", 40000))
client.post(
"/api/auth/setup",
json={"username": "admin", "email": "admin@example.com", "password": "password123"},
)
client.cookies.set(DEFAULT_COOKIE_NAME, "user-token")
client.post("/api/auth/totp/verify", json={"totpToken": "123456"})
client.post("/api/auth/totp/disable", json={"totpToken": "123456"})
self.assertEqual(fake.forwarded, ["198.51.100.20"] * 3)
def test_the_forwarded_address_does_not_leak_outside_the_call(self) -> None:
self._login_address(peer="203.0.113.7", trusted="", forwarded=None)
self.assertIsNone(_forwarded_client_ip.get())
def test_an_invalid_trusted_proxy_list_fails_at_startup(self) -> None:
with self.assertRaises(ValueError):
_build_app(_FakeStore(), trusted_proxies="10.0.0.0/8, not-an-ip")
class RequestValidationTests(unittest.TestCase):
"""Every JSON-body route must actually parse its body (see the docstring
on AuthDisabledModeTests for the regression this guards against)."""
def setUp(self) -> None:
self.client = TestClient(_build_app(_FakeStore()))
self.client = TestClient(_build_app(_FakeStore(), local_profile_without_authguard=True))
def test_setup_rejects_missing_fields_with_422_not_500(self) -> None:
response = self.client.post("/api/auth/setup", json={})
@@ -0,0 +1,77 @@
import json
import unittest
from pathlib import Path
from shared_backend.auth import (
hash_password,
password_hash_needs_upgrade,
verify_and_upgrade_password,
verify_password,
)
from shared_backend.clientip import client_address, parse_trusted_proxies
from shared_backend.totp import verify_totp
# The Go, Node and Python auth helpers load the same fixtures; see "description" in the file.
CONTRACT_PATH = Path(__file__).resolve().parents[3] / "contract" / "auth-contract.json"
@unittest.skipUnless(
CONTRACT_PATH.exists(), "contract/auth-contract.json is not part of this checkout"
)
class AuthContractTests(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
cls.contract = json.loads(CONTRACT_PATH.read_text(encoding="utf-8"))
def test_password_hashes_verify_as_the_contract_says_for_python(self) -> None:
password = self.contract["password"]
for entry in password["hashes"]:
with self.subTest(entry["name"]):
self.assertEqual(
verify_password(password["plaintext"], entry["hash"]),
entry["verifies"]["python"],
)
self.assertFalse(verify_password(password["wrongPassword"], entry["hash"]))
if "python" in entry.get("needsUpgrade", {}):
want = entry["needsUpgrade"]["python"]
self.assertEqual(password_hash_needs_upgrade(entry["hash"]), want)
valid, upgraded = verify_and_upgrade_password(
password["plaintext"], entry["hash"]
)
self.assertTrue(valid)
self.assertEqual(upgraded is not None, want)
if upgraded is not None:
self.assertTrue(upgraded.startswith("bcrypt$"))
self.assertTrue(verify_password(password["plaintext"], upgraded))
def test_the_password_length_contract_holds_for_python(self) -> None:
too_long = self.contract["password"]["tooLongToHash"]
try:
hash_password("a" * too_long["bytes"])
accepted = True
except ValueError:
accepted = False
self.assertEqual(accepted, too_long["accepted"]["python"])
def test_totp_verifies_as_the_contract_says(self) -> None:
totp = self.contract["totp"]
for entry in totp["cases"]:
with self.subTest(entry["name"]):
secret = entry.get("secret", totp["secret"])
self.assertEqual(verify_totp(secret, entry["code"], entry["unix"]), entry["valid"])
def test_client_address_follows_the_contract(self) -> None:
section = self.contract["clientAddress"]
for entry in section["cases"]:
with self.subTest(entry["name"]):
trusted = parse_trusted_proxies(entry["trusted"])
self.assertEqual(
client_address(entry["peer"], entry["forwarded"], trusted), entry["want"]
)
for value in section["invalidTrustedProxyLists"]:
with self.subTest(value), self.assertRaises(ValueError):
parse_trusted_proxies(value)
if __name__ == "__main__":
unittest.main()
@@ -1,9 +1,26 @@
import asyncio
import os
import unittest
from datetime import timedelta
from shared_backend.auth import ResetManager, hash_password, verify_password
import bcrypt
from shared_backend.auth import (
ResetManager,
hash_password,
hash_password_async,
password_hash_needs_upgrade,
verify_and_upgrade_password,
verify_and_upgrade_password_async,
verify_password,
verify_password_async,
)
from shared_backend.config import DatabaseConfig
from shared_backend.postgres import (
StartupRetryOptions,
is_transient_connection_error,
retry_startup,
)
from shared_backend.tokens import hash_token, new_session_token
from shared_backend.totp import totp_provisioning_uri, verify_totp
@@ -14,6 +31,95 @@ class SharedBackendTests(unittest.TestCase):
self.assertTrue(verify_password("correct horse battery staple", password_hash))
self.assertFalse(verify_password("wrong password", password_hash))
def test_async_password_helpers_match_the_sync_ones(self):
async def run():
password_hash = await hash_password_async("correct horse battery staple")
self.assertTrue(verify_password("correct horse battery staple", password_hash))
self.assertTrue(
await verify_password_async("correct horse battery staple", password_hash)
)
self.assertFalse(await verify_password_async("wrong password", password_hash))
asyncio.run(run())
def test_new_hashes_carry_the_scheme_prefix_and_the_current_cost(self):
password_hash = hash_password("correct horse battery staple")
self.assertTrue(password_hash.startswith("bcrypt$$2b$12$"))
self.assertFalse(password_hash_needs_upgrade(password_hash))
def test_unprefixed_legacy_bcrypt_hashes_still_verify_and_are_upgraded(self):
legacy = bcrypt.hashpw(
b"correct horse battery staple", bcrypt.gensalt(rounds=12)
).decode()
self.assertTrue(verify_password("correct horse battery staple", legacy))
self.assertFalse(verify_password("wrong password", legacy))
self.assertTrue(password_hash_needs_upgrade(legacy))
valid, upgraded = verify_and_upgrade_password("correct horse battery staple", legacy)
self.assertTrue(valid)
self.assertTrue(upgraded.startswith("bcrypt$$2b$12$"))
self.assertTrue(verify_password("correct horse battery staple", upgraded))
self.assertFalse(password_hash_needs_upgrade(upgraded))
def test_a_cost_below_the_current_policy_is_upgraded(self):
low_cost = "bcrypt$" + bcrypt.hashpw(
b"correct horse battery staple", bcrypt.gensalt(rounds=4)
).decode()
self.assertTrue(password_hash_needs_upgrade(low_cost))
valid, upgraded = verify_and_upgrade_password("correct horse battery staple", low_cost)
self.assertTrue(valid)
self.assertIsNotNone(upgraded)
def test_a_wrong_password_and_a_current_hash_are_not_rewritten(self):
current = hash_password("correct horse battery staple")
password = "correct horse battery staple"
self.assertEqual(verify_and_upgrade_password(password, current), (True, None))
self.assertEqual(verify_and_upgrade_password("wrong password", current), (False, None))
def test_unknown_formats_fail_closed(self):
unknown = [
"",
"bcrypt$",
"bcrypt$not-a-bcrypt-string",
"pbkdf2-sha256$600000$00$00",
"$1$abc",
]
for stored in unknown:
self.assertFalse(verify_password("correct horse battery staple", stored), stored)
def test_async_upgrade_matches_the_sync_one(self):
password = "correct horse battery staple"
legacy = bcrypt.hashpw(password.encode(), bcrypt.gensalt(rounds=12)).decode()
async def run():
valid, upgraded = await verify_and_upgrade_password_async(password, legacy)
self.assertTrue(valid)
self.assertTrue(await verify_password_async(password, upgraded))
asyncio.run(run())
def test_startup_retry_only_retries_transient_connection_errors(self):
import asyncpg
async def retry_with(error):
attempts = []
async def operation():
attempts.append(1)
raise error
policy = StartupRetryOptions(interval_seconds=0.001, max_attempts=3)
with self.assertRaises(type(error)):
await retry_startup(operation, policy)
return len(attempts)
self.assertTrue(is_transient_connection_error(ConnectionRefusedError()))
self.assertTrue(is_transient_connection_error(asyncpg.exceptions.ConnectionDoesNotExistError("closed")))
self.assertFalse(is_transient_connection_error(asyncpg.exceptions.InvalidPasswordError("bad")))
self.assertFalse(is_transient_connection_error(ValueError("bad")))
self.assertEqual(asyncio.run(retry_with(ValueError("bad"))), 1)
self.assertEqual(asyncio.run(retry_with(ConnectionRefusedError())), 3)
def test_session_token_hash(self):
token, token_hash = new_session_token()
self.assertNotEqual(token, token_hash)
@@ -1,6 +1,6 @@
import unittest
from shared_backend.coreconfig import Info, Store
from shared_backend.coreconfig import Info, Store, internal_secret_matches
class StoreDefaultsTests(unittest.TestCase):
@@ -62,5 +62,29 @@ class StoreSetTests(unittest.TestCase):
self.assertEqual(info.to_json()["carrierNodeUrl"], "http://carrier.example.com")
class InternalSecretTests(unittest.TestCase):
def test_unset_or_empty_secret_never_matches(self):
self.assertFalse(internal_secret_matches(None, None))
self.assertFalse(internal_secret_matches(None, ""))
self.assertFalse(internal_secret_matches("", ""))
self.assertFalse(internal_secret_matches("", None))
def test_compares_the_whole_secret(self):
self.assertTrue(internal_secret_matches("shared-secret", "shared-secret"))
self.assertFalse(internal_secret_matches("shared-secreT", "shared-secret"))
self.assertFalse(internal_secret_matches(None, "shared-secret"))
class UrlValidationTests(unittest.TestCase):
def test_rejects_urls_that_are_not_http_or_https_with_a_host(self):
store = Store(Info(auth_guard_url="http://auth.example.com"))
for bad in ["javascript:alert(1)", "auth.example.com", "ftp://carrier.example.com", "http://"]:
with self.subTest(url=bad), self.assertRaises(ValueError):
store.set(Info(auth_guard_url=bad))
with self.assertRaises(ValueError):
store.set(Info(carrier_node_urls=["http://carrier.example.com:99999"]))
self.assertEqual(store.auth_guard_url, "http://auth.example.com")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,120 @@
import unittest
from shared_backend.auth import (
AuthStore,
EmptyPasswordHashError,
InvalidUsernameError,
TotpAlreadyEnabledError,
hash_password,
)
class _FakeDatabase:
"""Records queries and answers them from canned results."""
def __init__(self) -> None:
self.executed: list[tuple[str, tuple]] = []
self.fetched: list[tuple[str, tuple]] = []
self.execute_status = "UPDATE 1"
self.totp_enabled = False
self.rows_by_condition: dict[str, dict] = {}
async def execute(self, query: str, *args) -> str:
self.executed.append((query, args))
return self.execute_status
async def fetchval(self, query: str, *args):
return False
async def fetchrow(self, query: str, *args):
self.fetched.append((query, args))
if "totp_enabled" in query:
return {"secret": "S", "enabled": self.totp_enabled}
for condition, row in self.rows_by_condition.items():
if condition in query:
return row
return None
def _user_row(username: str, email: str = "") -> dict:
return {
"id": 1,
"username": username,
"email": email,
"password_hash": "h",
"role": "user",
"created_at": None,
"updated_at": None,
}
class AuthStoreHardeningTests(unittest.IsolatedAsyncioTestCase):
def setUp(self) -> None:
self.db = _FakeDatabase()
self.store = AuthStore(self.db, single_user=False) # type: ignore[arg-type]
async def test_ensure_schema_requests_the_case_insensitive_username_index(self) -> None:
await self.store.ensure_schema()
statements = " ".join(query for query, _ in self.db.executed)
self.assertIn("auth_users_username_lower_idx", statements)
self.assertIn("lower(username)", statements)
# The index is created only while no clashing pair exists.
self.assertIn("HAVING count(*) > 1", statements)
async def test_set_totp_secret_refuses_while_enabled(self) -> None:
self.db.execute_status = "UPDATE 0"
self.db.totp_enabled = True
with self.assertRaises(TotpAlreadyEnabledError):
await self.store.set_totp_secret(1, "NEWSECRET")
self.assertIn("NOT totp_enabled", self.db.executed[0][0])
async def test_set_totp_secret_succeeds_while_disabled(self) -> None:
await self.store.set_totp_secret(1, "NEWSECRET")
self.db.execute_status = "UPDATE 0" # no such user: nothing to refuse
await self.store.set_totp_secret(2, "NEWSECRET")
async def test_credential_writes_refuse_an_empty_hash_and_an_at_username(self) -> None:
writes = [
lambda u, h: self.store.create_user(u, "", h),
lambda u, h: self.store.create_managed_user(u, "", h),
lambda u, h: self.store.update_credentials(1, u, "", h),
lambda u, h: self.store.update_user(1, username=u, password_hash=h),
]
for write in writes:
with self.assertRaises(EmptyPasswordHashError):
await write("alice", "")
with self.assertRaises(InvalidUsernameError):
await write("alice@example.com", "hash")
self.assertEqual(self.db.executed, [])
self.assertEqual(self.db.fetched, [])
async def test_update_user_leaves_unspecified_fields_alone(self) -> None:
await self.store.update_user(1, email="a@b.com")
await self.store.update_user(1, role="admin")
self.assertEqual(len(self.db.executed), 2)
async def test_find_by_identifier_tries_the_username_before_the_email(self) -> None:
self.db.rows_by_condition = {
"username = $1": _user_row("owner@example.com", "second@example.com"),
"lower(email) = lower($1)": _user_row("owner", "owner@example.com"),
}
found = await self.store.find_by_identifier("owner@example.com")
self.assertEqual(found.username, "owner@example.com")
self.assertEqual(len(self.db.fetched), 1)
del self.db.rows_by_condition["username = $1"]
found = await self.store.find_by_identifier("owner@example.com")
self.assertEqual(found.username, "owner")
class PasswordLengthTests(unittest.TestCase):
def test_hash_password_refuses_more_than_72_bytes(self) -> None:
with self.assertRaises(ValueError):
hash_password("a" * 73)
with self.assertRaises(ValueError):
hash_password("é" * 37) # 74 bytes
self.assertTrue(hash_password("a" * 72).startswith("bcrypt$"))
if __name__ == "__main__":
unittest.main()