ci: expand CI checks and make consumer sync opt-in
- Add Go, npm, Python, and Java validation to CI - Run Go tests against PostgreSQL - Record performance fixes in the report
This commit is contained in:
1 parent
199a5efaef
commit
22887fef03
100 files changed
+9740
-429
No files matched your search
@@ -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}}
|
||||
|
||||
Reference in new issue
Block a user