docs: record auth hash alignment and validation results

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

No files matched your search

@@ -28,12 +28,12 @@ from .authclient import (
token_from_request,
)
from .config import DatabaseConfig, database_url_from_env
from .coreconfig import MIN_INTERNAL_SECRET_LENGTH, internal_secret_matches, internal_secret_usable
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
from .totp import generate_totp_secret, totp_provisioning_uri, verify_totp, verify_totp_step
__all__ = [
"AuthStore",
@@ -47,6 +47,8 @@ __all__ = [
"CoreConfigInfo",
"CoreConfigStore",
"internal_secret_matches",
"internal_secret_usable",
"MIN_INTERNAL_SECRET_LENGTH",
"ROLE_ADMIN",
"ROLE_SUPERADMIN",
"ROLE_USER",
@@ -70,4 +72,5 @@ __all__ = [
"verify_password",
"verify_password_async",
"verify_totp",
"verify_totp_step",
]
@@ -3,6 +3,9 @@
from __future__ import annotations
import asyncio
import hashlib
import hmac
import re
import secrets
import threading
from dataclasses import dataclass
@@ -12,6 +15,7 @@ import asyncpg
import bcrypt
from .postgres import Database
from .totp import verify_totp_step
_SCHEMA = """
CREATE TABLE IF NOT EXISTS auth_users (
@@ -22,6 +26,7 @@ CREATE TABLE IF NOT EXISTS auth_users (
role TEXT NOT NULL DEFAULT 'user',
totp_secret TEXT NOT NULL DEFAULT '',
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
last_used_step BIGINT NOT NULL DEFAULT -1,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
@@ -29,6 +34,7 @@ ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user';
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT '';
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 last_used_step BIGINT NOT NULL DEFAULT -1;
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();
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx
@@ -179,7 +185,12 @@ def _validate_credentials(username: str | None, password_hash: str | None) -> No
# 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$"
_BCRYPT_SHA256_SCHEME = "bcrypt-sha256$"
_LEGACY_BCRYPT_PREFIXES = ("$2a$", "$2b$", "$2y$")
_PBKDF2_SCHEME = "pbkdf2-sha256"
BCRYPT_MAX_PASSWORD_BYTES = 72
_LEGACY_PBKDF2_ITERATIONS = 100_000
_MAX_PBKDF2_ITERATIONS = 10_000_000
BCRYPT_ROUNDS = 12
@@ -188,9 +199,9 @@ def _new_bcrypt_hash(password: str) -> str:
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
# bcrypt reads only the first 72 bytes, so new passwords are refused above this limit. Legacy
# PBKDF2 passwords over the limit are migrated with an explicitly marked SHA-256 pre-hash.
MAX_PASSWORD_BYTES = BCRYPT_MAX_PASSWORD_BYTES
def hash_password(password: str) -> str:
@@ -209,24 +220,75 @@ def _bcrypt_string_of(stored_hash: str) -> str | None:
return None
def _bcrypt_hash_info(stored_hash: str) -> tuple[str, bool, bool] | None:
if stored_hash.startswith(_BCRYPT_SHA256_SCHEME):
return stored_hash[len(_BCRYPT_SHA256_SCHEME) :], True, False
if stored_hash.startswith(_BCRYPT_SCHEME):
return stored_hash[len(_BCRYPT_SCHEME) :], False, False
if stored_hash.startswith(_LEGACY_BCRYPT_PREFIXES):
return stored_hash, False, True
return None
def _pbkdf2_hash_info(stored_hash: str) -> tuple[int, str, str] | None:
if stored_hash.startswith(f"{_PBKDF2_SCHEME}$"):
parts = stored_hash.split("$")
if len(parts) != 4:
return None
_, raw_iterations, salt, expected = parts
try:
iterations = int(raw_iterations)
except ValueError:
return None
elif re.fullmatch(r"[0-9a-f]+:[0-9a-f]+", stored_hash):
salt, expected = stored_hash.split(":", 1)
iterations = _LEGACY_PBKDF2_ITERATIONS
else:
return None
if len(salt) != 32 or len(expected) != 64 or not (1 <= iterations <= _MAX_PBKDF2_ITERATIONS):
return None
return iterations, salt, expected
def _new_bcrypt_sha256_hash(password: str) -> str:
digest = hashlib.sha256(password.encode("utf-8")).hexdigest()
hashed = bcrypt.hashpw(digest.encode("ascii"), bcrypt.gensalt(rounds=BCRYPT_ROUNDS))
return _BCRYPT_SHA256_SCHEME + hashed.decode("utf-8")
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"), bcrypt_hash.encode("utf-8"))
except (ValueError, TypeError):
bcrypt_info = _bcrypt_hash_info(stored_hash)
if bcrypt_info is not None:
bcrypt_hash, prehashed, _ = bcrypt_info
raw_password = password.encode("utf-8")
if prehashed:
raw_password = hashlib.sha256(raw_password).hexdigest().encode("ascii")
elif len(raw_password) > BCRYPT_MAX_PASSWORD_BYTES:
return False
try:
return bcrypt.checkpw(raw_password, bcrypt_hash.encode("utf-8"))
except (ValueError, TypeError):
return False
parsed = _pbkdf2_hash_info(stored_hash)
if parsed is None:
return False
iterations, salt, expected = parsed
actual = hashlib.pbkdf2_hmac(
"sha256", password.encode("utf-8"), salt.encode("ascii"), iterations
)
return hmac.compare_digest(actual.hex(), expected)
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):
"""True for legacy PBKDF2/bcrypt formats or a bcrypt cost below policy."""
bcrypt_info = _bcrypt_hash_info(stored_hash)
if bcrypt_info is None:
return True
# The bcrypt string after the prefix is "$2b$<cost>$<salt+hash>".
parts = stored_hash[len(_BCRYPT_SCHEME) :].split("$")
bcrypt_hash, _, legacy = bcrypt_info
parts = bcrypt_hash.split("$")
try:
return int(parts[2]) < BCRYPT_ROUNDS
return legacy or int(parts[2]) < BCRYPT_ROUNDS
except (IndexError, ValueError):
return True
@@ -243,6 +305,8 @@ def verify_and_upgrade_password(password: str, stored_hash: str) -> tuple[bool,
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.
if len(password.encode("utf-8")) > BCRYPT_MAX_PASSWORD_BYTES:
return True, _new_bcrypt_sha256_hash(password)
return True, _new_bcrypt_hash(password)
@@ -431,18 +495,19 @@ class AuthStore:
async def get_totp_state(self, user_id: int) -> dict[str, object]:
row = await self.database.fetchrow(
"SELECT COALESCE(totp_secret, '') AS secret, COALESCE(totp_enabled, false) AS enabled "
"SELECT COALESCE(totp_secret, '') AS secret, COALESCE(totp_enabled, false) AS enabled, "
"COALESCE(last_used_step, -1) AS last_used_step "
"FROM auth_users WHERE id = $1",
user_id,
)
return dict(row) if row else {"secret": "", "enabled": False}
return dict(row) if row else {"secret": "", "enabled": False, "last_used_step": -1}
async def set_totp_secret(self, user_id: int, secret: str) -> None:
"""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, "
"UPDATE auth_users SET totp_secret = $1, totp_enabled = false, last_used_step = -1, "
"updated_at = now() WHERE id = $2 AND NOT totp_enabled",
secret,
user_id,
@@ -450,16 +515,41 @@ class AuthStore:
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(
"UPDATE auth_users SET totp_enabled = true, updated_at = now() "
"WHERE id = $1 AND totp_secret <> ''",
async def enable_totp(self, user_id: int, token: str, now: float | None = None) -> bool:
state = await self.get_totp_state(user_id)
if not state["secret"] or state["enabled"]:
return False
step = verify_totp_step(str(state["secret"]), token, now)
if step is None:
return False
status = await self.database.execute(
"UPDATE auth_users SET totp_enabled = true, last_used_step = $1, updated_at = now() "
"WHERE id = $2 AND totp_secret = $3 AND NOT totp_enabled AND last_used_step < $1",
step,
user_id,
state["secret"],
)
return status == "UPDATE 1"
async def consume_totp_code(self, user_id: int, token: str, now: float | None = None) -> bool:
state = await self.get_totp_state(user_id)
if not state["secret"] or not state["enabled"]:
return False
step = verify_totp_step(str(state["secret"]), token, now)
if step is None:
return False
status = await self.database.execute(
"UPDATE auth_users SET last_used_step = $1, updated_at = now() "
"WHERE id = $2 AND totp_enabled AND totp_secret = $3 AND last_used_step < $1",
step,
user_id,
state["secret"],
)
return status == "UPDATE 1"
async def disable_totp(self, user_id: int) -> None:
await self.database.execute(
"UPDATE auth_users SET totp_secret = '', totp_enabled = false, "
"UPDATE auth_users SET totp_secret = '', totp_enabled = false, last_used_step = -1, "
"updated_at = now() WHERE id = $1",
user_id,
)
@@ -64,11 +64,14 @@ from typing import Any, Mapping
DEFAULT_COOKIE_NAME = "auth_session"
DEFAULT_TIMEOUT = 5.0
# validate() results, positive and negative, are reused for this many seconds so a burst of
# requests with one token costs one AuthGuard call. Revocation through this client (logout)
# clears the entry at once; revocation elsewhere is seen within the TTL. Mirrors the Go client.
# validate() results (positive and negative) and /api/me profiles are reused for this many
# seconds so a burst of requests with one token costs one AuthGuard call. Revocation through
# this client (logout) and token-authenticated writes clear both entries at once; changes made
# directly in AuthGuard may take up to two seconds to reach consumers.
VALIDATION_CACHE_TTL = 2.0
MAX_VALIDATION_CACHE_ENTRIES = 10000
PROFILE_CACHE_TTL = VALIDATION_CACHE_TTL
MAX_PROFILE_CACHE_ENTRIES = MAX_VALIDATION_CACHE_ENTRIES
_BEARER_PREFIX = "Bearer "
@@ -274,6 +277,7 @@ class AuthClient:
self.project_key = (project_key or "").strip().lower()
self._validation_lock = threading.Lock()
self._validation_cache: dict[str, tuple[float, AuthGuardUser | None]] = {}
self._profile_cache: dict[str, tuple[float, PublicUser]] = {}
@staticmethod
def _validation_key(token: str) -> str:
@@ -307,8 +311,36 @@ class AuthClient:
)
def _forget_validation(self, token: str) -> None:
"""Clears cached validation and /api/me data for this token."""
with self._validation_lock:
self._validation_cache.pop(self._validation_key(token), None)
key = self._validation_key(token)
self._validation_cache.pop(key, None)
self._profile_cache.pop(key, None)
def _cached_profile(self, token: str) -> tuple[bool, PublicUser | None]:
key = self._validation_key(token)
with self._validation_lock:
entry = self._profile_cache.get(key)
if entry is None:
return False, None
expires, profile = entry
if time.monotonic() >= expires:
del self._profile_cache[key]
return False, None
return True, profile
def _cache_profile(self, token: str, profile: PublicUser) -> None:
with self._validation_lock:
if len(self._profile_cache) >= MAX_PROFILE_CACHE_ENTRIES:
now = time.monotonic()
for key in [k for k, entry in self._profile_cache.items() if now >= entry[0]]:
del self._profile_cache[key]
if len(self._profile_cache) >= MAX_PROFILE_CACHE_ENTRIES:
del self._profile_cache[next(iter(self._profile_cache))]
self._profile_cache[self._validation_key(token)] = (
time.monotonic() + PROFILE_CACHE_TTL,
profile,
)
def set_base_url(self, base_url: str) -> None:
"""Atomically replaces the AuthGuard base URL this client calls,
@@ -326,6 +358,7 @@ class AuthClient:
self.base_url = normalized
with self._validation_lock:
self._validation_cache.clear()
self._profile_cache.clear()
# --- session validation (the original, minimal surface) ----------------
@@ -465,6 +498,9 @@ class AuthClient:
message = str(payload.get("error") or f"request failed ({status})")
raise APIError(status, message, totp_required=bool(payload.get("totp_required")))
if token and method.upper() not in {"GET", "HEAD"}:
self._forget_validation(token)
return payload, list(cookies)
@staticmethod
@@ -533,9 +569,26 @@ class AuthClient:
return cookies
async def me(self, token: str) -> PublicUser:
"""Calls GET /api/me, resolving token to its account."""
payload, _ = await self._call("GET", "/api/me", token=token)
return self._public_user(payload)
"""Calls GET /api/me, resolving token to its account.
Successful profiles are cached by the SHA-256 token digest for the
same short window as validate(). This keeps protected API calls from
blocking on one AuthGuard round trip each while bounding how long an
external profile change or session revocation can remain stale.
"""
if not self.base_url:
raise AuthClientError("authclient: client has no base URL")
trimmed = (token or "").strip()
if trimmed:
hit, cached = self._cached_profile(trimmed)
if hit:
assert cached is not None
return cached
payload, _ = await self._call("GET", "/api/me", token=trimmed)
profile = self._public_user(payload)
if trimmed:
self._cache_profile(trimmed, profile)
return profile
# --- TOTP ------------------------------------------------------------------
@@ -56,6 +56,7 @@ from __future__ import annotations
import abc
import os
from http.cookies import CookieError, SimpleCookie
from typing import Any, Callable, Optional
from fastapi import APIRouter, Depends, HTTPException, Request, Response
@@ -72,6 +73,7 @@ from .authclient import (
forwarded_client_ip,
)
from .clientip import client_address, parse_trusted_proxies, trusted_proxies_from_env
from .coreconfig import MIN_INTERNAL_SECRET_LENGTH, internal_secret_matches
from .ratelimit import AttemptLimiter
__all__ = ["ProxyStore", "build_auth_router"]
@@ -104,7 +106,10 @@ ERR_FEATURE_REQUIRES_AUTHGUARD = "This feature requires AUTHGUARD_URL to be conf
# 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_SECRET_NOT_SET = (
"SECRET environment variable is unset, shorter than "
f"{MIN_INTERNAL_SECRET_LENGTH} characters, or an example placeholder."
)
ERR_ADMIN_REQUIRED = "Administrator access required."
# _LOCAL_PROFILE is the fixed placeholder identity every handler reports when
@@ -175,6 +180,8 @@ class UpdateMeRequest(BaseModel):
email: str = ""
username: str = ""
password: str = ""
currentPassword: str = ""
totpToken: str = ""
class UpdateAccessRequest(BaseModel):
@@ -333,8 +340,30 @@ def build_auth_router(
)
def _forward_cookies(response: Response, cookies: list[str]) -> None:
for cookie in cookies:
response.headers.append("set-cookie", cookie)
for header in cookies:
parsed = SimpleCookie()
try:
parsed.load(header)
except CookieError:
continue
for morsel in parsed.values():
morsel["httponly"] = True
morsel["samesite"] = "lax"
if secure_cookie:
morsel["secure"] = True
response.headers.append("set-cookie", morsel.OutputString())
def _temporary_session_token(cookies: list[str]) -> str:
for header in cookies:
parsed = SimpleCookie()
try:
parsed.load(header)
except CookieError:
continue
morsel = parsed.get(cookie_name)
if morsel is not None and morsel.value:
return morsel.value
return ""
async def _current_profile(
request: Request, client: AuthClient
@@ -610,14 +639,42 @@ def build_auth_router(
email = _normalize_email(req.email)
username = _normalize_username(req.username)
password = None
temporary_token = ""
if req.password:
_validate_password(req.password)
if not req.currentPassword:
raise HTTPException(
status_code=400,
detail="Current password is required to change the password.",
)
if current.totp_enabled and not req.totpToken.strip():
raise HTTPException(
status_code=400,
detail="A current authenticator code is required to change the password.",
)
try:
reauthenticated = await client.login(
current.username,
req.currentPassword,
req.totpToken,
)
except AuthClientError as exc:
_raise_authguard_error(exc, "Current credentials could not be verified.")
raise # unreachable
temporary_token = _temporary_session_token(reauthenticated.cookies)
password = req.password
try:
await client.update_managed_user(
token, current.id, username=username, email=email, password=password
)
try:
await client.update_managed_user(
token, current.id, username=username, email=email, password=password
)
finally:
if password is not None and temporary_token:
try:
await client.logout(temporary_token)
except AuthClientError:
pass
except AuthClientError as exc:
_raise_authguard_error(exc, "Profile could not be updated.")
raise # unreachable
@@ -651,9 +708,8 @@ def build_auth_router(
request: Request,
store: ProxyStore = Depends(get_store), # noqa: B008
) -> dict[str, bool]:
if (
not configured_internal_secret
or request.headers.get("X-Internal-Auth") != configured_internal_secret
if not internal_secret_matches(
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)
@@ -25,13 +25,29 @@ from dataclasses import dataclass, field
from typing import Callable, Optional
from urllib.parse import urlsplit
MIN_INTERNAL_SECRET_LENGTH = 16
"""Shortest SECRET a service accepts for its internal routes."""
EXAMPLE_INTERNAL_SECRETS = frozenset({"SECRET", "change-me-to-a-long-random-value"})
"""Placeholders from .env.example files and the bare variable name. They are
public, so they never gate a route."""
def internal_secret_usable(secret: Optional[str]) -> bool:
"""True when the configured secret is strong enough to gate an internal
route: at least MIN_INTERNAL_SECRET_LENGTH characters and not an example
placeholder. A route whose secret is not usable rejects every caller."""
value = secret or ""
return len(value) >= MIN_INTERNAL_SECRET_LENGTH and value not in EXAMPLE_INTERNAL_SECRETS
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:
"""True when the X-Internal-Auth value equals the configured secret. A
secret that is not usable (see internal_secret_usable) never matches, and
the comparison is constant-time."""
if not internal_secret_usable(secret):
return False
expected = (secret or "").encode("utf-8")
return hmac.compare_digest(expected, (provided or "").encode("utf-8"))
@@ -36,19 +36,24 @@ def totp_provisioning_uri(issuer: str, account: str, secret: str) -> str:
def verify_totp(secret: str, token: str, now: float | None = None) -> bool:
return verify_totp_step(secret, token, now) is not None
def verify_totp_step(secret: str, token: str, now: float | None = None) -> int | None:
normalized_secret = _normalize_secret(secret)
normalized_token = _normalize_token(token)
if not normalized_secret or len(normalized_token) != TOTP_DIGITS:
return False
return None
try:
key = base64.b32decode(normalized_secret + "=" * ((8 - len(normalized_secret) % 8) % 8))
except (ValueError, binascii.Error):
return False
return None
if not key:
return False
return None
period = int((time.time() if now is None else now) // TOTP_PERIOD_SECONDS)
for offset in range(-TOTP_WINDOW, TOTP_WINDOW + 1):
# Prefer the current step if a six-digit collision occurs in the window.
for offset in (0, -1, 1):
counter = period + offset
if counter < 0:
continue
@@ -62,8 +67,8 @@ def verify_totp(secret: str, token: str, now: float | None = None) -> bool:
)
candidate = f"{value % 1_000_000:06d}"
if hmac.compare_digest(candidate, normalized_token):
return True
return False
return counter
return None
def _normalize_secret(value: str) -> str: