Skip to content

The agent that grows with you

fix(dashboard): respect X-Forwarded-Prefix in server-rendered login page

liuhao1024324fb9fdd017
diff --git a/hermes_cli/dashboard_auth/login_page.py b/hermes_cli/dashboard_auth/login_page.py
index 8acdd200d78..b06bfe30651 100644
--- a/hermes_cli/dashboard_auth/login_page.py
+++ b/hermes_cli/dashboard_auth/login_page.py
@@ -393,9 +393,16 @@ an SSH tunnel or Tailscale.</p>
# login pages stay script-free. Plain string (not ``str.format``): braces are
# literal. One delegated submit handler covers every form; the provider name
# comes from the form's ``data-provider`` attribute.
+#
+# Reverse-proxy prefix support: the script reads ``data-prefix`` from the
+# ``<main>`` element (set by :func:`render_login_html`) and prepends it
+# to the POST target and the post-login landing path so the login flow
+# works behind ``X-Forwarded-Prefix`` proxies.
_PASSWORD_FORM_SCRIPT = """\
<script>
(function () {
+ var mainEl = document.querySelector('main');
+ var prefix = (mainEl && mainEl.getAttribute('data-prefix')) || '';
function handle(form) {
form.addEventListener('submit', function (ev) {
ev.preventDefault();
@@ -409,7 +416,7 @@ _PASSWORD_FORM_SCRIPT = """\
password: (form.querySelector('input[name=password]') || {}).value || '',
next: (form.querySelector('input[name=next]') || {}).value || ''
};
- fetch('/auth/password-login', {
+ fetch(prefix + '/auth/password-login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
@@ -417,7 +424,7 @@ _PASSWORD_FORM_SCRIPT = """\
}).then(function (resp) {
if (resp.ok) {
return resp.json().then(function (data) {
- window.location.assign((data && data.next) || '/');
+ window.location.assign((data && data.next) || (prefix + '/'));
});
}
var msg = resp.status === 429
@@ -439,12 +446,18 @@ _PASSWORD_FORM_SCRIPT = """\
"""
-def render_login_html(*, next_path: str = "") -> str:
+def render_login_html(*, next_path: str = "", prefix: str = "") -> str:
"""Return the full HTML for ``GET /login``.
``next_path`` is threaded into each provider button/form so the OAuth round
trip carries it end-to-end. The caller validates it same-origin; it is
HTML-escaped here as defence in depth.
+
+ ``prefix`` — when set, the path prefix from ``X-Forwarded-Prefix``
+ (e.g. ``"/hermes"``). Prepended to all auth URLs so the login page
+ works behind a reverse proxy that mounts the dashboard at a
+ sub-path. Empty string (default) means no prefix — bare-root
+ deploys are unaffected.
"""
providers = list_session_providers()
if not providers:
@@ -453,17 +466,25 @@ def render_login_html(*, next_path: str = "") -> str:
# shape so a round-tripped value is byte-identical.
next_qs = f"&next={html.escape(quote(next_path, safe=''), quote=True)}" if next_path else ""
buttons = [
- _render_password_form(p, next_path) if getattr(p, "supports_password", False) else
+ _render_password_form(p, next_path, prefix=prefix)
+ if getattr(p, "supports_password", False) else
f' <a class="provider-btn" '
- f'href="/auth/login?provider={html.escape(p.name, quote=True)}{next_qs}">'
+ f'href="{prefix}/auth/login?provider={html.escape(p.name, quote=True)}{next_qs}">'
f'Sign in with {html.escape(p.display_name)}</a>'
for p in providers
]
needs_password_script = any(getattr(p, "supports_password", False) for p in providers)
- return _LOGIN_HTML_TEMPLATE.format(
+ html_out = _LOGIN_HTML_TEMPLATE.format(
provider_buttons="\n".join(buttons),
password_script=_PASSWORD_FORM_SCRIPT if needs_password_script else "",
)
+ # Inject the reverse-proxy prefix so the password-login JS can read
+ # it from the <main> element's data attribute. ``str.replace``
+ # after ``str.format`` avoids interfering with the CSS ``{{ }}``
+ # doubling in the template.
+ if prefix:
+ html_out = html_out.replace("<main>", f'<main data-prefix="{prefix}">', 1)
+ return html_out
def render_native_provider_choice_html(
@@ -487,12 +508,16 @@ def render_native_provider_choice_html(
return _LOGIN_HTML_TEMPLATE.format(provider_buttons="\n".join(buttons), password_script="")
-def _render_password_form(provider, next_path: str) -> str:
+def _render_password_form(provider, next_path: str, *, prefix: str = "") -> str:
"""Username/password form for a ``supports_password`` provider.
``next_path`` rides in a hidden field (already validated by the caller,
HTML-escaped here). The provider name is a ``data-`` attribute so the
script does not depend on field ordering.
+
+ ``prefix`` — reverse-proxy path prefix (e.g. ``"/hermes"``); kept for
+ interface parity with the other renderers (the submit handler reads
+ the prefix from ``<main data-prefix>``).
"""
pname = html.escape(provider.name, quote=True)
plabel = html.escape(provider.display_name)
diff --git a/hermes_cli/dashboard_auth/routes.py b/hermes_cli/dashboard_auth/routes.py
index 1aace007a43..e047cecd3d4 100644
--- a/hermes_cli/dashboard_auth/routes.py
+++ b/hermes_cli/dashboard_auth/routes.py
@@ -177,7 +177,8 @@ def _start_upstream_login(request: Request, p, *, audit_failure: bool, extra_pkc
async def login_page(request: Request) -> HTMLResponse:
# ``next=`` is set by the gate's redirect but /login is reachable directly.
next_path = _validate_post_login_target(request.query_params.get("next", ""))
- return HTMLResponse(render_login_html(next_path=next_path), headers=_NO_STORE)
+ return HTMLResponse(
+ render_login_html(next_path=next_path, prefix=_prefix(request)), headers=_NO_STORE)
@router.get("/api/auth/providers", name="auth_providers")
diff --git a/tests/hermes_cli/test_dashboard_auth_401_reauth.py b/tests/hermes_cli/test_dashboard_auth_401_reauth.py
index 49a1d72dcaa..40476efdb0e 100644
--- a/tests/hermes_cli/test_dashboard_auth_401_reauth.py
+++ b/tests/hermes_cli/test_dashboard_auth_401_reauth.py
@@ -282,6 +282,7 @@ class TestHtmlRedirectNext:
assert r.status_code == 200
+
# ---------------------------------------------------------------------------
# Gate middleware: auto-SSO redirect + one-shot loop guard (Phase 1)
# ---------------------------------------------------------------------------
@@ -346,6 +347,27 @@ class TestAutoSsoRedirect:
assert "/auth/login" not in second.headers["location"]
+ def test_login_page_prefixed_urls_behind_proxy(self, gated_app):
+ """When X-Forwarded-Prefix is set, the login page must render
+ all auth URLs with the prefix so the flow works behind a
+ reverse proxy that mounts the dashboard at a sub-path."""
+ r = gated_app.get(
+ "/login",
+ headers={"X-Forwarded-Prefix": "/hermes"},
+ )
+ assert r.status_code == 200
+ html = r.text
+ assert 'href="/hermes/auth/login?provider=' in html
+ assert 'data-prefix="/hermes"' in html
+
+ def test_login_page_bare_urls_without_proxy_header(self, gated_app):
+ """Without X-Forwarded-Prefix the login page must use
+ root-relative URLs (no prefix injection)."""
+ r = gated_app.get("/login")
+ assert r.status_code == 200
+ html = r.text
+ assert 'href="/auth/login?provider=' in html
+ assert "data-prefix" not in html
# ---------------------------------------------------------------------------
@@ -614,6 +636,38 @@ class TestRenderLoginHtmlNext:
assert '"injected' not in html_out
assert "%22injected" in html_out
+ def test_prefix_prepended_to_provider_button_href(self):
+ from hermes_cli.dashboard_auth.login_page import render_login_html
+ html_out = render_login_html(prefix="/hermes")
+ assert 'href="/hermes/auth/login?provider=stub"' in html_out
+
+ def test_prefix_with_next_threaded(self):
+ from hermes_cli.dashboard_auth.login_page import render_login_html
+ html_out = render_login_html(next_path="/sessions", prefix="/hermes")
+ assert 'href="/hermes/auth/login?provider=stub' in html_out
+ assert "next=" in html_out
+
+ def test_empty_prefix_produces_bare_root_urls(self):
+ """Explicitly passing prefix='' (the default) must NOT inject a
+ ``data-prefix`` attribute or alter the hrefs."""
+ from hermes_cli.dashboard_auth.login_page import render_login_html
+ html_out = render_login_html(prefix="")
+ assert 'href="/auth/login?provider=stub"' in html_out
+ assert "data-prefix" not in html_out
+
+ def test_prefix_injected_as_data_attribute(self):
+ """The <main> element must carry data-prefix so the password-login
+ JS can read it."""
+ from hermes_cli.dashboard_auth.login_page import render_login_html
+ html_out = render_login_html(prefix="/hermes")
+ assert 'data-prefix="/hermes"' in html_out
+
+ def test_prefix_does_not_appear_without_explicit_prefix(self):
+ from hermes_cli.dashboard_auth.login_page import render_login_html
+ html_out = render_login_html()
+ assert "<main>" in html_out
+ assert "data-prefix" not in html_out
+
# ---------------------------------------------------------------------------
# Unit-level coverage: /auth/login persists next= into the PKCE cookie