Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions hermes_cli/dashboard_auth/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,19 @@
)


def _request_path(request: Request) -> str:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please make this the shared path source for the current sibling authorization checks as well: hermes_cli/dashboard_auth/token_auth.py:162 selects exact bearer-token routes from request.url.path, and hermes_cli/web_server.py:505 selects the runtime disabled-plugin gate from it. Both make authorization decisions from the same divergent value this helper is intended to avoid.

"""Return the ASGI-dispatched path for auth decisions.

``request.url.path`` is reconstructed from URL components and is not the
routing source of truth. Keep path-based gates tied to ``scope["path"]`` so
host/header parsing quirks cannot desync auth checks from dispatch.
"""
path = request.scope.get("path") if hasattr(request, "scope") else None
if isinstance(path, str) and path:
return path
return request.url.path


def _path_is_public(path: str) -> bool:
"""True if ``path`` bypasses the OAuth auth gate.

Expand Down Expand Up @@ -101,7 +114,7 @@ def _unauth_response(request: Request, *, reason: str) -> Response:
"""
from hermes_cli.dashboard_auth.prefix import prefix_from_request

path = request.url.path
path = _request_path(request)
next_param = _safe_next_target(request)
prefix = prefix_from_request(request)
login_url = (
Expand Down Expand Up @@ -139,7 +152,7 @@ def _safe_next_target(request: Request) -> str:
string return means the caller produces a bare ``/login`` URL — fine,
user lands at the dashboard root after re-auth.
"""
path = request.url.path
path = _request_path(request)
# Reject anything that doesn't start with "/" or starts with "//"
# (protocol-relative URL — would open-redirect to an attacker host).
if not path or not path.startswith("/") or path.startswith("//"):
Expand Down Expand Up @@ -170,7 +183,7 @@ async def gated_auth_middleware(
if not getattr(request.app.state, "auth_required", False):
return await call_next(request)

path = request.url.path
path = _request_path(request)
if _path_is_public(path):
return await call_next(request)

Expand Down
4 changes: 3 additions & 1 deletion hermes_cli/web_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,9 @@ async def auth_middleware(request: Request, call_next):
# and is skipped here so the gate's session attachment isn't overridden.
if getattr(request.app.state, "auth_required", False):
return await call_next(request)
path = request.url.path
from hermes_cli.dashboard_auth.middleware import _request_path

path = _request_path(request)
if path.startswith("/api/") and path not in _PUBLIC_API_PATHS:
if not _has_valid_session_token(request):
return JSONResponse(
Expand Down
75 changes: 75 additions & 0 deletions tests/hermes_cli/test_dashboard_auth_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
# files that gate the app.
pytestmark = pytest.mark.xdist_group("dashboard_auth_app_state")
from fastapi.testclient import TestClient
from fastapi.responses import Response

from hermes_cli import web_server
from hermes_cli.dashboard_auth import clear_providers, register_provider
Expand Down Expand Up @@ -144,6 +145,80 @@ def test_gated_static_asset_path_is_public(gated_app):
assert r.status_code == 404


@pytest.mark.asyncio
async def test_gate_uses_scope_path_for_auth_decision():
"""Path auth gates must follow ASGI dispatch, not URL reconstruction."""
from hermes_cli.dashboard_auth.middleware import gated_auth_middleware

class FakeState:
auth_required = True

class FakeApp:
state = FakeState()

class FakeURL:
# A vulnerable implementation that trusts request.url.path would
# treat this as public and skip the gate.
path = "/login"
query = ""

class FakeClient:
host = "203.0.113.10"

class FakeRequest:
app = FakeApp()
url = FakeURL()
scope = {"path": "/api/sessions"}
headers = {}
cookies = {}
client = FakeClient()

called = False

async def call_next(_request):
nonlocal called
called = True
return Response("bypassed")

response = await gated_auth_middleware(FakeRequest(), call_next)

assert response.status_code == 401
assert called is False


@pytest.mark.asyncio
async def test_legacy_token_gate_uses_scope_path_for_api_decision():
"""Loopback token gate must also use the ASGI-dispatched path."""

class FakeState:
auth_required = False

class FakeApp:
state = FakeState()

class FakeURL:
path = "/"
query = ""

class FakeRequest:
app = FakeApp()
url = FakeURL()
scope = {"path": "/api/sessions"}
headers = {}

called = False

async def call_next(_request):
nonlocal called
called = True
return Response("bypassed")

response = await web_server.auth_middleware(FakeRequest(), call_next)

assert response.status_code == 401
assert called is False


# ---------------------------------------------------------------------------
# OAuth round trip
# ---------------------------------------------------------------------------
Expand Down
Loading