Add shared_backend.authproxy: FastAPI AuthGuard-proxy engine

Extracted from three near-identical bespoke implementations (Heretic,
HordeWorker, InfiniteVideo), each ~800-1000 lines hand-rolling the same
status/setup/login/logout/TOTP/admin-user-CRUD proxy around AuthClient.
build_auth_router(get_client, get_store) returns a ready-to-mount
APIRouter matching shared/backend/auth (Go)'s Service response shapes.
Gated behind an optional `fastapi` extra so the rest of this
framework-agnostic package is unaffected. 18 new tests, including a
regression test for a real bug this had (request models nested inside
build_auth_router silently broke under `from __future__ import
annotations`, misrouting every JSON body as a missing query param).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Gabriel20xxandClaude Sonnet 5 committed 2026-09-13 21:27:54 +02:00
1 parent f58579290d
commit c09957189f
5 files changed
+995 -1

No files matched your search

+1 -1
View File
@@ -78,6 +78,6 @@ jobs:
with: with:
python-version: '3.12' python-version: '3.12'
- name: Install package - name: Install package
run: python -m pip install --upgrade pip -e packages/python-backend run: python -m pip install --upgrade pip -e "packages/python-backend[fastapi]"
- name: Run Python tests - name: Run Python tests
run: python -m unittest discover -s packages/python-backend/tests -p 'test_*.py' run: python -m unittest discover -s packages/python-backend/tests -p 'test_*.py'
+50
View File
@@ -68,3 +68,53 @@ async def require_session(request: Request):
@app.get("/me", dependencies=[Depends(require_session)]) @app.get("/me", dependencies=[Depends(require_session)])
... ...
``` ```
## `authproxy`: a ready-to-mount FastAPI router (optional)
Wiring up `authclient` still leaves each service reimplementing the same
~800-1000 lines of status/setup/login/logout/TOTP/admin-user-CRUD
boilerplate around it — three projects in this workspace independently did
exactly that before `shared_backend.authproxy` was extracted from them.
Unlike the rest of this package, `authproxy` is a deliberate, narrow
exception to "HTTP framework adapters stay in each service": it hard-depends
on FastAPI and Pydantic, and is only pulled in if you install the optional
`fastapi` extra:
```bash
pip install "gabriel20xx-shared-backend[fastapi]"
```
A service implements a small `ProxyStore` (two independent, genuinely
local concerns: a one-time "has this deployment's setup screen been
completed" claim flag, and optionally a "require login" toggle) and calls
`build_auth_router` once to get a fully-formed `APIRouter`:
```python
from shared_backend.authclient import AuthClient
from shared_backend.authproxy import ProxyStore, build_auth_router
class MyStore(ProxyStore):
async def login_required(self) -> bool: return True
async def set_login_required(self, required: bool) -> None: pass
async def is_setup_claimed(self) -> bool: ... # your own table
async def try_claim_setup(self) -> bool: ... # your own table
async def unclaim_setup(self) -> None: ... # your own table
def get_client(request):
return request.app.state.auth_client # AuthClient | None, or None in auth-disabled mode
def get_store(request):
return request.app.state.auth_store
app.include_router(
build_auth_router(get_client, get_store, legacy_cookie_name="myproject_session"),
prefix="/api/auth",
)
```
This mounts `/status`, `/me` (GET/PUT), `/admin-needed`, `/setup`, `/login`,
`/logout`, `/access` (GET/PUT, the login-required toggle), `/users`
(GET/POST), `/users/{id}` (PUT/PATCH/DELETE), and `/totp/status|initiate|verify|disable`
— the same URL paths and JSON response shapes as `shared/backend/auth`
(Go)'s `Service`, so a project migrating onto this module gets the same
standardized wire format that Go consumers of that engine already have.
+9
View File
@@ -14,6 +14,15 @@ dependencies = [
"bcrypt>=4.2", "bcrypt>=4.2",
] ]
# Optional: only shared_backend.authproxy needs these (a FastAPI-specific
# AuthGuard-proxy router builder). The rest of this package stays
# framework-agnostic by design - see authclient.py's module docstring.
# Install with `pip install gabriel20xx-shared-backend[fastapi]`; a consumer
# that already depends on FastAPI directly (as every current authproxy
# consumer does) satisfies this from its own requirements regardless.
[project.optional-dependencies]
fastapi = ["fastapi>=0.100", "pydantic>=2"]
[tool.setuptools.packages.find] [tool.setuptools.packages.find]
where = ["src"] where = ["src"]
@@ -0,0 +1,700 @@
"""shared_backend.authproxy: the Python equivalent of shared/backend/auth's
Service/New/NewWithStore (Go) - the ONE shared AuthGuard-proxy engine for
every FastAPI-based project in this workspace that centralizes identity
through AuthGuard, instead of each project hand-rolling its own
status/setup/login/logout/TOTP/admin-user-CRUD proxy around AuthClient.
Extracted 2026-09-13 from three near-identical ~800-1000 line
implementations (Heretic, HordeWorker, InfiniteVideo), each explicitly
documented as mirroring the others and, ultimately, the reference Go
implementation (Original/GameStream/backend/cmd/gamestreamd/auth.go before
its own migration onto shared/backend/auth). Read any of those three
projects' pre-migration auth.py (or their own project's post-migration
git history) for the fuller narrative rationale behind each design choice
below - it is intentionally not repeated at length here.
Usage
-----
A project builds a `ProxyStore` implementation over whatever local
persistence it already has for two small, genuinely independent concerns:
a one-time "has this deployment's setup screen been completed" claim flag,
and (optionally) a "require login" toggle. It then calls `build_auth_router`
once, passing:
- `get_client(request) -> AuthClient | None`: resolve this request's
AuthClient from wherever the project stores it (typically
`request.app.state.auth_client`); `None` means AUTHGUARD_URL was unset
(auth-disabled mode - see `_LOCAL_PROFILE`'s doc comment below).
- `get_store(request) -> ProxyStore`: resolve this request's ProxyStore
the same way.
- `project_key`: this project's own lowercase identifier, passed to
`AuthClient(..., project_key=...)` by the project itself when
constructing its client - NOT re-passed here; this module never
constructs an AuthClient itself. Mentioned here only so a project
wiring this up remembers to set it.
- `legacy_cookie_name`: the project's own pre-migration session cookie
name, if any, cleared alongside AuthGuard's on logout for browsers that
still hold one.
- `secure_cookie`: whether cookies this router sets/clears should carry
the `Secure` attribute (mirror the project's own COOKIE_SECURE-style
setting).
and mounts the resulting `APIRouter` at `/api/auth` (the prefix every
existing consumer already uses - this module's own routes are declared
without a prefix, so a project could choose a different one, but doing so
would be a project-specific behavior change, not part of this migration).
Response shapes deliberately match shared/backend/auth (Go)'s: a nested
`user` object rather than flat fields, TOTP payloads nested under `data`,
etc. - the same standardization already applied when GameStream, OmniLogger,
and several other Go projects were migrated onto that engine. A project
adopting this module updates its own frontend to match; this is intentional,
not a bug.
"""
from __future__ import annotations
import abc
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 .authclient import (
DEFAULT_COOKIE_NAME,
APIError,
AuthClient,
AuthClientError,
ManagedUser,
PublicUser,
)
__all__ = ["ProxyStore", "build_auth_router"]
MIN_PASSWORD_LEN = 8
MAX_USERNAME_LEN = 64
MAX_EMAIL_LEN = 254
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_SELF_SERVICE_PROFILE = (
"Self-service profile editing is only available to administrator accounts; "
"ask an administrator to update this account."
)
# Returned by handlers that need a real backing identity (not just an access
# gate) when AUTHGUARD_URL is unset; see _LOCAL_PROFILE's doc comment.
ERR_FEATURE_REQUIRES_AUTHGUARD = "This feature requires AUTHGUARD_URL to be configured."
# Raised whenever AuthGuard could not be reached or gave an unusable response
# - a real "invalid or expired session" always resolves to None instead,
# 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."
# _LOCAL_PROFILE is the fixed placeholder identity every handler reports when
# auth is disabled (get_client(request) returns None, i.e. AUTHGUARD_URL was
# never configured). Role is superadmin so can_manage_users reports true,
# consistent with "nothing gated": the frontend's own admin-only UI sections
# become visible too, even though the underlying admin endpoints have
# nothing to manage.
_LOCAL_PROFILE = PublicUser(
id=0, username="local", email="", role=ROLE_SUPERADMIN, totp_enabled=False
)
class ProxyStore(abc.ABC):
"""The small piece of local, project-owned persistence build_auth_router
needs beyond AuthGuard itself: the independent "require login" toggle
and the one-time "has this deployment's setup screen been completed"
claim flag. Mirrors Go's sharedauth.ProxyStore exactly (same five
operations); a project with no "require login" concept of its own can
make login_required always return True and set_login_required a no-op.
"""
@abc.abstractmethod
async def login_required(self) -> bool: ...
@abc.abstractmethod
async def set_login_required(self, required: bool) -> None: ...
@abc.abstractmethod
async def is_setup_claimed(self) -> bool: ...
@abc.abstractmethod
async def try_claim_setup(self) -> bool: ...
@abc.abstractmethod
async def unclaim_setup(self) -> None: ...
ClientGetter = Callable[[Request], Optional[AuthClient]]
StoreGetter = Callable[[Request], ProxyStore]
# Request/response models are declared at module level (not inside
# build_auth_router) deliberately: this file uses `from __future__ import
# annotations` (PEP 563), which turns every annotation into a string
# resolved later via the function's *module* globals - a class nested
# inside build_auth_router's local scope is invisible to that resolution,
# which silently breaks FastAPI's body-vs-query-param detection (a
# nested-class version of this router mistook every JSON body for a
# missing query parameter). Keeping these as plain module-level classes
# avoids that trap entirely.
class SetupRequest(BaseModel):
username: str
email: str
password: str
class LoginRequest(BaseModel):
identifier: Optional[str] = None
username: Optional[str] = None
email: Optional[str] = None
password: str
totpToken: str = ""
class UpdateMeRequest(BaseModel):
email: str = ""
username: str = ""
password: str = ""
class UpdateAccessRequest(BaseModel):
loginRequired: bool
class ManagedUserRequest(BaseModel):
username: str = ""
email: str = ""
password: str = ""
role: Optional[str] = None
class TotpTokenRequest(BaseModel):
token: str = ""
totpToken: str = ""
def _normalize_username(username: str) -> str:
username = (username or "").strip()
if not username or len(username) > MAX_USERNAME_LEN:
raise HTTPException(status_code=400, detail="Username is required.")
return username
def _normalize_email(email: str) -> str:
email = (email or "").strip().lower()
if not email or len(email) > MAX_EMAIL_LEN or email.count("@") != 1:
raise HTTPException(status_code=400, detail="Email is required and must be valid.")
local, domain = email.split("@", 1)
if not local or not domain or "." not in domain:
raise HTTPException(status_code=400, detail="Email is required and must be valid.")
return email
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.")
def _raise_authguard_error(err: Exception, fallback: str) -> None:
"""Translates an authclient error into a FastAPI HTTPException. AuthGuard's
own httpapi handlers were built from this workspace's various original
local implementations, so their status codes and messages already match
closely - AuthGuard's APIError is forwarded close to verbatim rather than
re-mapped by hand. A non-APIError (a transport failure actually reaching
AuthGuard) falls back to a generic 500 with `fallback`."""
if isinstance(err, APIError):
raise HTTPException(status_code=err.status_code, detail=err.message) from err
raise HTTPException(status_code=500, detail=fallback) from err
def _user_payload(user: PublicUser) -> dict[str, Any]:
return {
"id": user.id,
"username": user.username,
"email": user.email,
"role": normalize_role(user.role),
"canManageUsers": can_manage_users(user.role),
"mfaEnabled": user.totp_enabled,
}
def _managed_user_payload(user: ManagedUser) -> dict[str, Any]:
return {
"id": user.id,
"username": user.username,
"email": user.email,
"role": normalize_role(user.role),
"createdAt": user.created_at,
}
def build_auth_router(
get_client: ClientGetter,
get_store: StoreGetter,
*,
legacy_cookie_name: str = "",
secure_cookie: bool = False,
cookie_name: str = DEFAULT_COOKIE_NAME,
) -> 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."""
router = APIRouter()
def _enabled(client: Optional[AuthClient]) -> bool:
return client is not None
def _session_token(request: Request) -> str:
return request.cookies.get(cookie_name, "") or ""
def _clear_session_cookies(response: Response) -> None:
names = [cookie_name]
if legacy_cookie_name and legacy_cookie_name != cookie_name:
names.append(legacy_cookie_name)
for name in names:
response.delete_cookie(
key=name, path="/", secure=secure_cookie, httponly=True, samesite="lax"
)
def _forward_cookies(response: Response, cookies: list[str]) -> None:
for cookie in cookies:
response.headers.append("set-cookie", cookie)
async def _current_profile(
request: Request, client: AuthClient
) -> tuple[Optional[PublicUser], str]:
token = _session_token(request)
if not token:
return None, ""
try:
user = await client.me(token)
except APIError as exc:
if exc.status_code == 401:
return None, ""
raise
return user, token
async def _current_profile_or_401(
request: Request, client: AuthClient
) -> tuple[PublicUser, str]:
try:
profile, token = await _current_profile(request, client)
except AuthClientError as exc:
raise HTTPException(status_code=500, detail=ERR_AUTHGUARD_UNAVAILABLE) from exc
if profile is None:
raise HTTPException(status_code=401, detail=ERR_AUTH_REQUIRED)
return profile, token
async def require_session(
request: Request,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> PublicUser:
"""FastAPI dependency gating a route behind a valid session."""
if not _enabled(client):
return _LOCAL_PROFILE
assert client is not None
profile, _ = await _current_profile_or_401(request, client)
return profile
async def _require_user_manager(
request: Request,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> str:
"""Returns the caller's session token, or "" in auth-disabled mode
(each handler decides its own auth-disabled response). Authorization
(can_manage_users, "protect the superadmin") is enforced by
AuthGuard itself from the forwarded token."""
if not _enabled(client):
return ""
token = _session_token(request)
if not token:
raise HTTPException(status_code=401, detail=ERR_AUTH_REQUIRED)
return token
# --- status / me -------------------------------------------------------
@router.get("/me")
async def get_me(
request: Request,
store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> dict[str, Any]:
login_required = await store.login_required()
if not _enabled(client):
return {"user": _user_payload(_LOCAL_PROFILE), "authRequired": login_required}
assert client is not None
try:
profile, _ = await _current_profile(request, client)
except AuthClientError as exc:
raise HTTPException(status_code=500, detail=ERR_AUTHGUARD_UNAVAILABLE) from exc
return {
"user": _user_payload(profile) if profile else None,
"authRequired": login_required,
}
@router.get("/admin-needed")
async def get_admin_needed(
store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> dict[str, bool]:
if not _enabled(client):
return {"adminNeeded": False}
assert client is not None
if await store.is_setup_claimed():
return {"adminNeeded": False}
try:
setup_required = await client.setup_status()
except AuthClientError as exc:
raise HTTPException(status_code=500, detail=ERR_AUTHGUARD_UNAVAILABLE) from exc
return {"adminNeeded": setup_required}
@router.get("/status")
async def get_status(
request: Request,
store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
return {
"setupRequired": False,
"authenticated": True,
"authRequired": True,
"user": _user_payload(_LOCAL_PROFILE),
}
assert client is not None
claimed = await store.is_setup_claimed()
setup_required = False
if not claimed:
try:
setup_required = await client.setup_status()
except AuthClientError as exc:
raise HTTPException(status_code=500, detail=ERR_AUTHGUARD_UNAVAILABLE) from exc
try:
profile, _ = await _current_profile(request, client)
except AuthClientError as exc:
raise HTTPException(status_code=500, detail=ERR_AUTHGUARD_UNAVAILABLE) from exc
login_required = await store.login_required()
return {
"setupRequired": setup_required,
"authenticated": profile is not None,
"authRequired": login_required,
"user": _user_payload(profile) if profile else None,
}
# --- setup / login / logout ---------------------------------------------
@router.post("/setup", status_code=201)
async def setup(
req: SetupRequest,
response: Response,
store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
return {"user": _user_payload(_LOCAL_PROFILE)}
assert client is not None
username = _normalize_username(req.username)
email = _normalize_email(req.email)
_validate_password(req.password)
if not await store.try_claim_setup():
raise HTTPException(status_code=409, detail=ERR_SETUP_COMPLETE)
try:
setup_required = await client.setup_status()
except AuthClientError as exc:
await store.unclaim_setup()
raise HTTPException(status_code=500, detail=ERR_AUTHGUARD_UNAVAILABLE) from exc
if not setup_required:
await store.unclaim_setup()
raise HTTPException(status_code=409, detail=ERR_SETUP_COMPLETE)
try:
result = await client.register(username, email, req.password)
except AuthClientError as exc:
await store.unclaim_setup()
_raise_authguard_error(exc, "Could not create account.")
raise # unreachable
_forward_cookies(response, result.cookies)
return {"user": _user_payload(result.user)}
@router.post("/login")
async def login(
req: LoginRequest,
response: Response,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
return {"user": _user_payload(_LOCAL_PROFILE)}
assert client is not None
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)
try:
result = await client.login(identifier, req.password, req.totpToken)
except APIError as exc:
if exc.totp_required:
raise HTTPException(
status_code=401,
detail={
"error": "Two-factor authentication code required.",
"mfaRequired": True,
},
) from exc
if exc.status_code == 401:
raise HTTPException(status_code=401, detail=ERR_INVALID_CREDENTIALS) from exc
_raise_authguard_error(exc, "Could not authenticate.")
raise # unreachable
except AuthClientError as exc:
raise HTTPException(status_code=500, detail=ERR_AUTHGUARD_UNAVAILABLE) from exc
_forward_cookies(response, result.cookies)
return {"user": _user_payload(result.user)}
@router.post("/logout")
async def logout(
request: Request,
response: Response,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> dict[str, bool]:
if _enabled(client):
assert client is not None
token = _session_token(request)
if token:
try:
cookies = await client.logout(token)
except APIError:
cookies = []
except AuthClientError as exc:
raise HTTPException(status_code=500, detail="Internal error.") from exc
else:
_forward_cookies(response, cookies)
_clear_session_cookies(response)
return {"ok": True}
# --- self-service profile editing ---------------------------------------
@router.put("/me")
@router.post("/me")
async def update_me(
req: UpdateMeRequest,
request: Request,
client: Optional[AuthClient] = Depends(get_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
current, token = await _current_profile_or_401(request, client)
if not can_manage_users(current.role):
raise HTTPException(status_code=403, detail=ERR_SELF_SERVICE_PROFILE)
email = _normalize_email(req.email)
username = _normalize_username(req.username)
password = None
if req.password:
_validate_password(req.password)
password = req.password
try:
await client.update_managed_user(
token, current.id, username=username, email=email, password=password
)
except AuthClientError as exc:
_raise_authguard_error(exc, "Profile could not be updated.")
raise # unreachable
try:
updated = await client.me(token)
except AuthClientError as exc:
raise HTTPException(status_code=500, detail="Profile could not be loaded.") from exc
return {"user": _user_payload(updated)}
# --- login-required toggle (only meaningful for a project that already
# has this concept locally; ProxyStore.login_required/set_login_required
# stub to (True, no-op) otherwise) --------------------------------------
@router.get("/access")
async def access_settings(store: ProxyStore = Depends(get_store)) -> dict[str, bool]: # noqa: B008
return {"loginRequired": await store.login_required()}
@router.put("/access")
async def update_access_settings(
req: UpdateAccessRequest,
store: ProxyStore = Depends(get_store), # noqa: B008
) -> dict[str, bool]:
await store.set_login_required(req.loginRequired)
return {"loginRequired": req.loginRequired}
# --- admin user management ----------------------------------------------
@router.get("/users")
async def list_users(
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
token: str = Depends(_require_user_manager), # noqa: B008
) -> list[dict[str, Any]]:
if not _enabled(client):
return []
assert client is not None
try:
users = await client.list_managed_users(token)
except AuthClientError as exc:
_raise_authguard_error(exc, "Users unavailable.")
raise # unreachable
return [_managed_user_payload(u) for u in users]
@router.post("/users", status_code=201)
async def create_managed_user(
req: ManagedUserRequest,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
token: str = Depends(_require_user_manager), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD)
assert client is not None
try:
created = await client.create_managed_user(
token, username=req.username, email=req.email, password=req.password, role=req.role
)
except AuthClientError as exc:
_raise_authguard_error(exc, "User could not be created.")
raise # unreachable
return _managed_user_payload(created)
@router.put("/users/{user_id}")
@router.patch("/users/{user_id}")
async def update_managed_user(
user_id: int,
req: ManagedUserRequest,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
token: str = Depends(_require_user_manager), # noqa: B008
) -> dict[str, Any]:
if not _enabled(client):
raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD)
assert client is not None
try:
await client.update_managed_user(
token,
user_id,
username=req.username or None,
email=req.email or None,
password=req.password or None,
role=req.role,
)
except AuthClientError as exc:
_raise_authguard_error(exc, "User could not be updated.")
raise # unreachable
try:
users = await client.list_managed_users(token)
except AuthClientError as exc:
_raise_authguard_error(exc, "User could not be loaded.")
raise # unreachable
updated = next((u for u in users if u.id == user_id), None)
if updated is None:
raise HTTPException(status_code=404, detail="User not found.")
return _managed_user_payload(updated)
@router.delete("/users/{user_id}")
async def delete_managed_user(
user_id: int,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
token: str = Depends(_require_user_manager), # noqa: B008
) -> dict[str, bool]:
if not _enabled(client):
raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD)
assert client is not None
try:
await client.delete_managed_user(token, user_id)
except AuthClientError as exc:
_raise_authguard_error(exc, "User could not be deleted.")
raise # unreachable
return {"ok": True}
# --- TOTP ----------------------------------------------------------------
@router.get("/totp/status")
async def get_totp_status(
request: Request,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> dict[str, bool]:
if not _enabled(client):
return {"enabled": False, "mfaEnabled": False}
assert client is not None
profile, _ = await _current_profile_or_401(request, client)
return {"enabled": bool(profile.totp_enabled), "mfaEnabled": bool(profile.totp_enabled)}
@router.post("/totp/initiate")
async def initiate_totp(
request: Request,
client: Optional[AuthClient] = Depends(get_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
profile, token = await _current_profile_or_401(request, client)
if profile.totp_enabled:
raise HTTPException(
status_code=409, detail="Two-factor authentication is already enabled."
)
try:
result = await client.totp_enable(token)
except AuthClientError as exc:
_raise_authguard_error(exc, "Could not create authenticator secret.")
raise # unreachable
return {
"data": {
"secret": result.secret,
"otpauth": result.otpauth_url,
"otpauthUrl": result.otpauth_url,
"enabled": result.enabled,
}
}
@router.post("/totp/verify")
async def verify_totp(
req: TotpTokenRequest,
request: Request,
client: Optional[AuthClient] = Depends(get_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)
code = req.totpToken or req.token
try:
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": []}}
@router.post("/totp/disable")
async def disable_totp(
req: TotpTokenRequest,
request: Request,
client: Optional[AuthClient] = Depends(get_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)
code = req.totpToken or req.token
try:
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}}
# Expose the session dependency for the project's own non-auth routes to
# reuse (mirrors Go's Service.Require/RequireAdmin being usable as
# middleware on any route, not just this router's own).
router.require_session = require_session # type: ignore[attr-defined]
return router
@@ -0,0 +1,235 @@
import unittest
from fastapi import FastAPI, Request
from fastapi.testclient import TestClient
from shared_backend import authproxy as ap
from shared_backend.authclient import APIError, AuthClient, PublicUser, SessionResult
class _FakeStore(ap.ProxyStore):
"""In-memory ProxyStore covering both flags build_auth_router needs."""
def __init__(self, *, claimed: bool = False, login_required: bool = True) -> None:
self.claimed = claimed
self._login_required = login_required
async def login_required(self) -> bool:
return self._login_required
async def set_login_required(self, required: bool) -> None:
self._login_required = required
async def is_setup_claimed(self) -> bool:
return self.claimed
async def try_claim_setup(self) -> bool:
if self.claimed:
return False
self.claimed = True
return True
async def unclaim_setup(self) -> None:
self.claimed = False
def _build_app(store: ap.ProxyStore, client: AuthClient | None = None) -> FastAPI:
def get_client(request: Request) -> AuthClient | None:
return client
def get_store(request: Request) -> ap.ProxyStore:
return store
app = FastAPI()
app.include_router(ap.build_auth_router(get_client, get_store), 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
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
missing query parameter (all these POST/PUT calls would 422 on that
bug)."""
def setUp(self) -> None:
self.client = TestClient(_build_app(_FakeStore()))
def test_status_reports_local_superadmin(self) -> None:
response = self.client.get("/api/auth/status")
self.assertEqual(response.status_code, 200)
body = response.json()
self.assertTrue(body["authenticated"])
self.assertFalse(body["setupRequired"])
self.assertEqual(body["user"]["role"], "superadmin")
self.assertTrue(body["user"]["canManageUsers"])
def test_me_reports_local_superadmin(self) -> None:
body = self.client.get("/api/auth/me").json()
self.assertEqual(body["user"]["username"], "local")
def test_setup_succeeds_as_a_no_op(self) -> None:
response = self.client.post(
"/api/auth/setup",
json={"username": "a", "email": "a@b.com", "password": "password123"},
)
self.assertEqual(response.status_code, 201)
self.assertEqual(response.json()["user"]["role"], "superadmin")
def test_login_succeeds_as_a_no_op(self) -> None:
response = self.client.post(
"/api/auth/login", json={"identifier": "anyone", "password": "whatever"}
)
self.assertEqual(response.status_code, 200)
def test_logout_always_ok(self) -> None:
self.assertEqual(self.client.post("/api/auth/logout").json(), {"ok": True})
def test_list_users_returns_empty_list_not_an_error(self) -> None:
self.assertEqual(self.client.get("/api/auth/users").json(), [])
def test_mutating_admin_routes_require_authguard(self) -> None:
response = self.client.post(
"/api/auth/users",
json={"username": "b", "email": "b@c.com", "password": "password123"},
)
self.assertEqual(response.status_code, 409)
def test_totp_initiate_requires_authguard(self) -> None:
self.assertEqual(self.client.post("/api/auth/totp/initiate").status_code, 409)
def test_update_me_requires_authguard(self) -> None:
self.assertEqual(self.client.put("/api/auth/me", json={}).status_code, 409)
class AccessSettingsTests(unittest.TestCase):
def test_get_and_put_round_trip_through_the_store(self) -> None:
store = _FakeStore(login_required=True)
client = TestClient(_build_app(store))
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
response = client.put("/api/auth/access", json={"loginRequired": False})
self.assertEqual(response.json(), {"loginRequired": False})
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": False})
class _FakeClient(AuthClient):
"""Overrides just the methods build_auth_router calls, bypassing real
HTTP entirely - AuthClient.__init__ never needs a reachable base_url for
these tests since nothing here calls the real _call/_validate_sync."""
def __init__(self, *, setup_required: bool = True) -> None:
super().__init__("http://authguard.test")
self.setup_required = setup_required
self.registered: list[tuple[str, str, str]] = []
self.logged_out: list[str] = []
async def setup_status(self) -> bool:
return self.setup_required
async def register(self, username: str, email: str, password: str) -> SessionResult:
self.registered.append((username, email, password))
self.setup_required = False
return SessionResult(
user=PublicUser(id=1, username=username, email=email, role="superadmin"),
cookies=["auth_session=tok1; Path=/"],
)
async def login(self, username_or_email: str, password: str, totp_token: str = ""):
if password == "wrong":
raise APIError(401, "invalid credentials")
return SessionResult(
user=PublicUser(id=1, username=username_or_email, email="a@b.com", role="user"),
cookies=["auth_session=tok1; Path=/"],
)
async def me(self, token: str) -> PublicUser:
if not token:
raise APIError(401, "unauthenticated")
return PublicUser(id=1, username="a", email="a@b.com", role="user")
async def logout(self, token: str) -> list[str]:
self.logged_out.append(token)
return ["auth_session=; Path=/; Max-Age=0"]
class EnabledModeSetupAndLoginTests(unittest.TestCase):
"""Exercises the real (client is not None) path, including the
setup-claim flag's interaction with the store."""
def test_setup_claims_the_flag_and_registers_against_authguard(self) -> None:
store = _FakeStore(claimed=False)
fake_client = _FakeClient(setup_required=True)
client = TestClient(_build_app(store, fake_client))
response = client.post(
"/api/auth/setup",
json={"username": "admin", "email": "admin@example.com", "password": "password123"},
)
self.assertEqual(response.status_code, 201)
self.assertTrue(store.claimed)
self.assertEqual(fake_client.registered, [("admin", "admin@example.com", "password123")])
self.assertIn("set-cookie", response.headers)
def test_setup_refuses_a_second_claim(self) -> None:
store = _FakeStore(claimed=True)
client = TestClient(_build_app(store, _FakeClient()))
response = client.post(
"/api/auth/setup",
json={"username": "admin", "email": "admin@example.com", "password": "password123"},
)
self.assertEqual(response.status_code, 409)
def test_setup_unclaims_when_authguard_already_has_an_account(self) -> None:
# claimed=False locally, but AuthGuard itself reports no setup is
# needed (e.g. another project already created the first account) -
# the local claim slot must be released again, not left stuck.
store = _FakeStore(claimed=False)
client = TestClient(_build_app(store, _FakeClient(setup_required=False)))
response = client.post(
"/api/auth/setup",
json={"username": "admin", "email": "admin@example.com", "password": "password123"},
)
self.assertEqual(response.status_code, 409)
self.assertFalse(store.claimed)
def test_login_success_forwards_cookies(self) -> None:
client = TestClient(_build_app(_FakeStore(), _FakeClient()))
response = client.post(
"/api/auth/login", json={"identifier": "a@b.com", "password": "correct"}
)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json()["user"]["username"], "a@b.com")
def test_login_invalid_credentials_surfaces_401(self) -> None:
client = TestClient(_build_app(_FakeStore(), _FakeClient()))
response = client.post(
"/api/auth/login", json={"identifier": "a@b.com", "password": "wrong"}
)
self.assertEqual(response.status_code, 401)
def test_me_without_session_cookie_reports_no_user(self) -> None:
client = TestClient(_build_app(_FakeStore(), _FakeClient()))
body = client.get("/api/auth/me").json()
self.assertIsNone(body["user"])
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()))
def test_setup_rejects_missing_fields_with_422_not_500(self) -> None:
response = self.client.post("/api/auth/setup", json={})
self.assertEqual(response.status_code, 422)
def test_login_rejects_missing_password_with_422_not_500(self) -> None:
response = self.client.post("/api/auth/login", json={"identifier": "a"})
self.assertEqual(response.status_code, 422)
if __name__ == "__main__":
unittest.main()