Fix #34: Replace setup redirect allowlist prefix matching with explicit allowlist
- Replace fragile startswith() matching with explicit path matching - Split allowlist into _EXACT_ALLOWED (exact paths) and _PREFIX_ALLOWED (prefixes) - Prefix paths MUST end with '/' to prevent matching unintended paths like /api/setup-debug - Paths correctly matched: /api/setup, /api/health, /api/docs, /api/redoc, /api/openapi.json, /api/setup/timezone - Paths correctly blocked: /api/setup-debug, /api/setup123, /api/jails - Add comprehensive Setup Guard Route Policy documentation to Backend-Development.md - Update line numbers in documentation to reflect current implementation This prevents future route additions from accidentally bypassing the setup guard. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
@@ -41,6 +41,7 @@ from app.exceptions import (
|
||||
ServiceUnavailableError,
|
||||
)
|
||||
from app.middleware.csrf import CsrfMiddleware
|
||||
from app.models.response import ErrorResponse
|
||||
from app.routers import (
|
||||
auth,
|
||||
bans,
|
||||
@@ -56,7 +57,6 @@ from app.routers import (
|
||||
setup,
|
||||
)
|
||||
from app.startup import startup_shared_resources
|
||||
from app.models.response import ErrorResponse
|
||||
from app.utils.rate_limiter import RateLimiter
|
||||
from app.utils.runtime_state import ApplicationState, RuntimeState
|
||||
from app.utils.session_cache import InMemorySessionCache, NoOpSessionCache
|
||||
@@ -180,7 +180,7 @@ def _get_error_code(exc: Exception) -> str:
|
||||
"""
|
||||
if hasattr(exc, "error_code"):
|
||||
return exc.error_code
|
||||
|
||||
|
||||
exc_name = exc.__class__.__name__
|
||||
import re
|
||||
snake_case = re.sub(r"(?<!^)(?=[A-Z])", "_", exc_name).lower()
|
||||
@@ -546,7 +546,7 @@ async def _http_exception_handler(
|
||||
status_code=exc.status_code,
|
||||
error=exc.detail,
|
||||
)
|
||||
|
||||
|
||||
error_code_map = {
|
||||
status.HTTP_400_BAD_REQUEST: "invalid_input",
|
||||
status.HTTP_401_UNAUTHORIZED: "authentication_required",
|
||||
@@ -558,14 +558,14 @@ async def _http_exception_handler(
|
||||
status.HTTP_500_INTERNAL_SERVER_ERROR: "internal_error",
|
||||
status.HTTP_503_SERVICE_UNAVAILABLE: "service_unavailable",
|
||||
}
|
||||
|
||||
|
||||
error_code = error_code_map.get(exc.status_code, "internal_error")
|
||||
error_response = ErrorResponse(
|
||||
code=error_code,
|
||||
detail=exc.detail,
|
||||
metadata={},
|
||||
)
|
||||
|
||||
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content=error_response.model_dump(),
|
||||
@@ -577,18 +577,42 @@ async def _http_exception_handler(
|
||||
# Setup-redirect middleware
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# Paths that are always reachable, even before setup is complete.
|
||||
_ALWAYS_ALLOWED: frozenset[str] = frozenset(
|
||||
{"/api/setup", "/api/health", "/api/docs", "/api/redoc", "/api/openapi.json"},
|
||||
# Exact paths that are always reachable, even before setup is complete.
|
||||
# Using exact matching prevents fragile prefix-based allowlists. For example,
|
||||
# if we used startswith(), a future route like /api/setup-debug would bypass
|
||||
# the guard without being explicitly allowed.
|
||||
_EXACT_ALLOWED: frozenset[str] = frozenset(
|
||||
{
|
||||
"/api/setup", # GET/POST /api/setup
|
||||
"/api/health", # Health check endpoint
|
||||
"/api/docs", # Swagger UI
|
||||
"/api/redoc", # ReDoc
|
||||
"/api/openapi.json", # OpenAPI schema
|
||||
},
|
||||
)
|
||||
|
||||
# Prefix paths that are always reachable. These MUST end with "/" to prevent
|
||||
# matching paths like "/api/setup-debug" while still matching nested routes
|
||||
# like "/api/setup/timezone".
|
||||
_PREFIX_ALLOWED: frozenset[str] = frozenset(
|
||||
{
|
||||
"/api/setup/", # Nested setup routes (e.g., /api/setup/timezone)
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class SetupRedirectMiddleware(BaseHTTPMiddleware):
|
||||
"""Redirect all API requests to ``/api/setup`` until setup is done.
|
||||
|
||||
Once setup is complete this middleware is a no-op. Paths listed in
|
||||
:data:`_ALWAYS_ALLOWED` are exempt so the setup endpoint itself is
|
||||
always reachable.
|
||||
Once setup is complete this middleware is a no-op. Paths listed in
|
||||
:data:`_EXACT_ALLOWED` and :data:`_PREFIX_ALLOWED` are exempt so the
|
||||
setup endpoint and dependencies (health, docs, openapi schema) are always
|
||||
reachable.
|
||||
|
||||
This middleware uses explicit path matching rather than prefix-based rules
|
||||
to prevent fragile allowlists. For example, using startswith() could
|
||||
accidentally allow paths like /api/setup-debug that shouldn't bypass
|
||||
the setup guard.
|
||||
"""
|
||||
|
||||
async def dispatch(
|
||||
@@ -606,12 +630,23 @@ class SetupRedirectMiddleware(BaseHTTPMiddleware):
|
||||
Either a ``307 Temporary Redirect`` to ``/api/setup`` or the
|
||||
normal router response.
|
||||
"""
|
||||
# Remove trailing slash for consistent path comparison.
|
||||
# Note: request.url.path does not include query parameters, so those
|
||||
# don't need special handling.
|
||||
path: str = request.url.path.rstrip("/") or "/"
|
||||
|
||||
# Allow requests that don't need setup guard.
|
||||
if any(path.startswith(allowed) for allowed in _ALWAYS_ALLOWED):
|
||||
# Check if path is in the explicit allowlist (exact match).
|
||||
if path in _EXACT_ALLOWED:
|
||||
return await call_next(request)
|
||||
|
||||
# Check if path matches any allowed prefix. Prefixes in _PREFIX_ALLOWED
|
||||
# end with "/" to prevent accidental matches. For example:
|
||||
# - "/api/setup/" matches "/api/setup/timezone" (prefix match)
|
||||
# - "/api/setup/" does NOT match "/api/setup-debug" (exact prefix without /)
|
||||
for prefix in _PREFIX_ALLOWED:
|
||||
if path == prefix.rstrip("/") or path.startswith(prefix):
|
||||
return await call_next(request)
|
||||
|
||||
# If setup is not complete, block all other API requests.
|
||||
# The setup completion state is resolved at startup and stored in
|
||||
# ``app.state.setup_complete_cached`` so this middleware does not
|
||||
|
||||
Reference in New Issue
Block a user