Skip to content

The agent that grows with you

fix(webapp): signing out behind the sign-in gate signs every browser out

emozilla4e2b34118778
diff --git a/gateway/webapp_listener.py b/gateway/webapp_listener.py
index e817d9ed5ec..32e850424d0 100644
--- a/gateway/webapp_listener.py
+++ b/gateway/webapp_listener.py
@@ -250,7 +250,8 @@ def register_control_verbs(runner, home) -> None:
reaches them. ``webapp-launch`` returns a one-use launch link, so the credential crosses neither
the socket nor a browser's argv; where such a link cannot be redeemed (macOS) it returns the
private credential link instead, for the user to open by hand. ``webapp-sign-out`` replaces the
- browser credential and closes the browser sockets it opened."""
+ browser credential, which also ends every login bound to it behind the sign-in gate, closes the
+ browser sockets those opened, and reports how many it closed."""
server = getattr(runner, "session_control_server", None)
if server is None:
return
@@ -303,10 +304,13 @@ def register_control_verbs(runner, home) -> None:
_, web = serving()
web._SESSION_TOKEN = browser_session_token(home, rotate=True)
# Every tab loses access at once: the sockets and media links the old credential opened end
- # now, not when each tab next reconnects. Native clients never held it and stay connected.
- web_session_sockets.close_all()
+ # now, not when each tab next reconnects. Behind the sign-in gate every login is bound to the
+ # credential (hermes_cli.webapp_sign_in), so those browsers are signed out and their sockets
+ # close too. Native clients never held it and stay connected.
+ closed = web_session_sockets.close_all()
web_server_file_tickets.revoke_all()
- return {"signed_out": True}
+ return {"signed_out": True, "sign_in_gate": bool(getattr(web.app.state, "auth_required", False)),
+ "connections_closed": closed}
server.private_handlers.update({
"webapp-status": webapp_status, "webapp-launch": webapp_launch, "webapp-sign-out": webapp_sign_out})
diff --git a/hermes_cli/dashboard_auth/cookies.py b/hermes_cli/dashboard_auth/cookies.py
index 1a52c8b16db..5b1b6ae28c7 100644
--- a/hermes_cli/dashboard_auth/cookies.py
+++ b/hermes_cli/dashboard_auth/cookies.py
@@ -6,7 +6,9 @@ when the provider returned one, always cleared on logout/expiry), ``hermes_sessi
(non-secret routing hint so an RT is not handed to the wrong provider), ``hermes_session_pkce``
(PKCE state + CSRF nonce + provider hint, 10 min; ``SameSite=None; Secure`` over HTTPS because it
is set on the /auth/login 302 and must survive the cross-site redirect chain — Chromium drops Lax
-cookies set on such a 302, crbug 40508226), ``hermes_sso_attempt`` (auto-SSO loop guard, 60 s).
+cookies set on such a 302, crbug 40508226), ``hermes_sso_attempt`` (auto-SSO loop guard, 60 s),
+``hermes_webapp_signin`` (the gateway Webapp's sign-in binding, ``hermes_cli.webapp_sign_in``; set
+only by a login on the Webapp, Max-Age as the refresh token's).
``Secure`` only when ``request.url.scheme`` is https. Cookie-prefix hardening per
draft-west-cookie-prefixes: bare name over HTTP; ``__Host-`` on gated HTTPS with Path=/;
``__Secure-`` behind a proxy prefix (``__Host-`` forbids Path != /). Setters and readers BOTH
@@ -29,6 +31,8 @@ SESSION_RT_COOKIE = "hermes_session_rt"
SESSION_PROVIDER_COOKIE = "hermes_session_provider"
PKCE_COOKIE = "hermes_session_pkce"
SSO_ATTEMPT_COOKIE = "hermes_sso_attempt"
+#: The Webapp's sign-in binding (``hermes_cli.webapp_sign_in``); set beside the session cookies.
+WEBAPP_SIGNIN_COOKIE = "hermes_webapp_signin"
# Name variants a reader may have to try; most strict first.
_NAME_VARIANTS = ("__Host-", "__Secure-", "")
@@ -169,6 +173,16 @@ def read_session_provider(request: Request) -> Optional[str]:
return _read_with_fallback(request, SESSION_PROVIDER_COOKIE)
+def set_webapp_signin_cookie(response: Response, *, value: str, use_https: bool, prefix: str = "") -> None:
+ """Set the Webapp's sign-in binding with the session cookies' name, Path, SameSite and Secure
+ policy, for as long as a refresh token cookie lasts."""
+ _set(response, WEBAPP_SIGNIN_COOKIE, value, max_age=_RT_MAX_AGE, use_https=use_https, prefix=prefix)
+
+
+def read_webapp_signin_cookie(request: Request) -> Optional[str]:
+ return _read_with_fallback(request, WEBAPP_SIGNIN_COOKIE)
+
+
def read_pkce_cookie(request: Request) -> Optional[str]:
return _read_with_fallback(request, PKCE_COOKIE)
diff --git a/hermes_cli/dashboard_auth/middleware.py b/hermes_cli/dashboard_auth/middleware.py
index db4df8538eb..9c600743110 100644
--- a/hermes_cli/dashboard_auth/middleware.py
+++ b/hermes_cli/dashboard_auth/middleware.py
@@ -4,7 +4,9 @@ Engaged when ``app.state.auth_required is True``; a no-op otherwise (loopback
mode is handled by the legacy ``_SESSION_TOKEN`` ``auth_middleware``). Allows
the auth-bootstrap routes and static assets through unauthenticated; for
everything else demands a bearer token or a valid session cookie and attaches
-the verified :class:`Session` to ``request.state.session``. HTML routes are
+the verified :class:`Session` to ``request.state.session``. On the gateway's
+Webapp a cookie session also needs its sign-in binding to the browser credential
+(``hermes_cli.webapp_sign_in``). HTML routes are
redirected to ``/login``; ``/api/*`` routes get a 401 JSON envelope.
"""
from __future__ import annotations
@@ -17,6 +19,7 @@ from fastapi import Request
from fastapi.responses import JSONResponse, RedirectResponse, Response
from starlette.concurrency import run_in_threadpool
+from hermes_cli import webapp_sign_in
from hermes_cli.dashboard_auth import list_session_providers
from hermes_cli.dashboard_auth.audit import AuditEvent, audit_log
from hermes_cli.dashboard_auth.base import ProviderError
@@ -152,6 +155,7 @@ async def _serve_refreshed(request: Request, call_next, new_session, provider: s
response, access_token=new_session.access_token, refresh_token=new_session.refresh_token,
access_token_expires_in=_expires_in_seconds(new_session), use_https=detect_https(request),
prefix=prefix_from_request(request), provider=provider)
+ webapp_sign_in.renew(response, request)
audit_log(AuditEvent.REFRESH_SUCCESS, provider=provider, user_id=new_session.user_id,
ip=_client_ip(request))
return response
@@ -209,6 +213,10 @@ async def gated_auth_middleware(
# No session at all: try the silent portal bounce before /login.
auto = _auto_sso_response(request)
return auto if auto is not None else _unauth_response(request, reason="no_cookie")
+ if webapp_sign_in.applies(request) and not webapp_sign_in.check(request):
+ # A login on the gateway's Webapp holds only while the browser credential it was bound to is
+ # in use; signing out replaced it. The cookies stay: another surface on this host may use them.
+ return _unauth_response(request, reason="signed_out")
# An absent AT with a present RT is the COMMON expiry case (the AT cookie's Max-Age tracks
# the token TTL, so the browser evicts it first) — skip straight to refresh.
session = None
diff --git a/hermes_cli/dashboard_auth/routes.py b/hermes_cli/dashboard_auth/routes.py
index 942d093bdfd..1846ca60ecb 100644
--- a/hermes_cli/dashboard_auth/routes.py
+++ b/hermes_cli/dashboard_auth/routes.py
@@ -30,6 +30,7 @@ from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
from pydantic import BaseModel, Field
from starlette.concurrency import run_in_threadpool
+from hermes_cli import webapp_sign_in
from hermes_cli.dashboard_auth import (
get_provider, list_providers, list_session_providers, native_flow)
from hermes_cli.dashboard_auth import prefix as _prefix_mod
@@ -106,6 +107,7 @@ def _set_session(resp, request: Request, session: Session) -> None:
resp, access_token=session.access_token, refresh_token=session.refresh_token,
access_token_expires_in=access_token_max_age(session), use_https=detect_https(request),
prefix=_prefix(request), provider=session.provider)
+ webapp_sign_in.bind(resp, request)
def _bearer_payload(session: Session) -> dict[str, Any]:
@@ -559,7 +561,11 @@ async def api_auth_ws_ticket(request: Request):
``Authorization`` on the upgrade); one ticket per WS."""
sess = _require_session(request)
from hermes_cli.dashboard_auth.ws_tickets import TTL_SECONDS, mint_ticket
- ticket = mint_ticket(user_id=sess.user_id, provider=sess.provider, issuer=sess.issuer)
+ # On the gateway's Webapp the ticket carries the login's sign-in binding, so the socket it opens
+ # closes at sign-out (``hermes_cli.webapp_sign_in``).
+ signed_in = webapp_sign_in.sign_in_of(request)
+ ticket = mint_ticket(user_id=sess.user_id, provider=sess.provider, issuer=sess.issuer,
+ extra={"sign_in": signed_in} if signed_in else None)
_audit(request, AuditEvent.WS_TICKET_MINTED, provider=sess.provider, user_id=sess.user_id)
return {"ticket": ticket, "ttl_seconds": TTL_SECONDS}
diff --git a/hermes_cli/web_routers/webapp.py b/hermes_cli/web_routers/webapp.py
index 7f653ad289a..a70443f16b1 100644
--- a/hermes_cli/web_routers/webapp.py
+++ b/hermes_cli/web_routers/webapp.py
@@ -165,24 +165,30 @@ def _ticket_principal(request: Request) -> tuple[dict, str | None]:
raise HTTPException(status_code=401, detail="Unauthorized")
-def mint_socket_ticket(identity: dict, socket: str, *, session_token: str | None = None) -> str:
+def mint_socket_ticket(identity: dict, socket: str, *, session_token: str | None = None,
+ sign_in: str | None = None) -> str:
"""A one-use ticket that opens only *socket* (``web_session_sockets.GATEWAY_SOCKET`` or
- ``HOST_TERMINAL_SOCKET``) as *identity*. Minted with *session_token*, it opens nothing once that
- token is replaced, and the socket it opens closes when the browser signs out."""
+ ``HOST_TERMINAL_SOCKET``) as *identity*. Minted with *session_token*, or by a login whose
+ sign-in binding was checked against the credential with digest *sign_in*
+ (``hermes_cli.webapp_sign_in``), it opens nothing once that credential is replaced, and the
+ socket it opens closes when the browser signs out."""
from hermes_cli.dashboard_auth.ws_tickets import mint_ticket
from hermes_cli.web_session_sockets import token_digest
extra = {"socket": socket}
if session_token is not None:
extra["session_token"] = token_digest(session_token)
+ if sign_in is not None:
+ extra["sign_in"] = sign_in
return mint_ticket(user_id=identity["user_id"], provider=identity["provider"],
issuer=identity.get("issuer", ""), extra=extra)
-def _socket_ticket_response(identity: dict, socket: str, session_token: str | None) -> JSONResponse:
+def _socket_ticket_response(request: Request, identity: dict, socket: str, session_token: str | None) -> JSONResponse:
from hermes_cli.dashboard_auth.ws_tickets import TTL_SECONDS
+ from hermes_cli.webapp_sign_in import sign_in_of
- ticket = mint_socket_ticket(identity, socket, session_token=session_token)
+ ticket = mint_socket_ticket(identity, socket, session_token=session_token, sign_in=sign_in_of(request))
return JSONResponse({"ticket": ticket, "ttl_seconds": TTL_SECONDS}, headers={"Cache-Control": "no-store"})
@@ -200,7 +206,7 @@ async def issue_gateway_ticket(request: Request, profile: str | None = None):
raise HTTPException(404, "Webapp gateway tickets are unavailable on this surface")
identity, session_token = _ticket_principal(request)
_cron_profile_home(profile)
- return _socket_ticket_response(identity, GATEWAY_SOCKET, session_token)
+ return _socket_ticket_response(request, identity, GATEWAY_SOCKET, session_token)
@router.post("/api/webapp/terminal-ticket")
@@ -210,7 +216,7 @@ async def issue_terminal_ticket(request: Request):
if not policy(request.app.state).host_terminal:
raise HTTPException(404, "The host terminal is unavailable on this surface")
identity, session_token = _ticket_principal(request)
- return _socket_ticket_response(identity, HOST_TERMINAL_SOCKET, session_token)
+ return _socket_ticket_response(request, identity, HOST_TERMINAL_SOCKET, session_token)
@router.post("/webapp/window-session")
diff --git a/hermes_cli/web_server_chat.py b/hermes_cli/web_server_chat.py
index 2e7e3684ac7..923676e8f2a 100644
--- a/hermes_cli/web_server_chat.py
+++ b/hermes_cli/web_server_chat.py
@@ -355,9 +355,9 @@ def _consume_ws_ticket(ws: WebSocket, reject, socket: Optional[str] = None, *,
``(reason, credential)`` once judged, or None when the upgrade presents none. An accepted ticket
stamps the server-minted identity onto the socket; the client never supplies it through RPC
params. *socket* is the route's socket (``web_session_sockets.ticket_refusal``); a socket a
- session-token ticket opens is tracked so signing out closes it."""
+ session-token ticket, or a Webapp login's ticket, opens is tracked so signing out closes it."""
from hermes_cli.dashboard_auth.ws_tickets import TicketInvalid, consume_ticket
- from hermes_cli.web_session_sockets import ticket_refusal, track
+ from hermes_cli.web_session_sockets import admitted_with, ticket_refusal, track
protocol_ticket, protocol_reason = _gateway_ws_ticket_from_subprotocol(ws)
if protocol_reason == "invalid":
return "ticket_invalid", "ticket-subprotocol"
@@ -382,8 +382,8 @@ def _consume_ws_ticket(ws: WebSocket, reject, socket: Optional[str] = None, *,
ws._hermes_auth_identity = {"user_id": info.get("user_id"), "provider": info.get("provider")}
if info.get("issuer"):
ws._hermes_auth_identity["issuer"] = info["issuer"]
- if "session_token" in info:
- track(ws, info["session_token"])
+ if (admitted := admitted_with(info)) is not None:
+ track(ws, admitted)
if not protocol_ticket:
return None, "ticket"
# Select only the stable public protocol during accept. The ticket-bearing protocol is a
diff --git a/hermes_cli/web_session_sockets.py b/hermes_cli/web_session_sockets.py
index 80b5fa4680a..fb6f397b6c7 100644
--- a/hermes_cli/web_session_sockets.py
+++ b/hermes_cli/web_session_sockets.py
@@ -6,10 +6,14 @@ request mints a one-use ticket for one socket instead: ``GATEWAY_SOCKET`` (``/ap
the host terminal opens only with its own ticket. A ticket minted with the session token records that
token's digest and opens nothing once the token is replaced.
+Behind the sign-in gate the Webapp's browsers sign in instead, and each login is bound to the session
+token (``hermes_cli.webapp_sign_in``): a ticket such a login mints records the token's digest as
+``sign_in`` and likewise opens nothing once the token is replaced.
+
Every socket the session token admits, directly or through such a ticket, is tracked here until it
ends, so ``close_all`` (run when ``hermes webapp --sign-out`` replaces the token) closes them all at
-once. Sockets admitted on any other credential (a signed-in login, a native client's grant) are never
-tracked.
+once. Sockets admitted on any other credential (a native client's grant, a dashboard login off the
+Webapp, a provider token presented directly) are never tracked.
"""
from __future__ import annotations
@@ -52,7 +56,8 @@ def ticket_refusal(info: dict[str, Any], socket: Optional[str], *, auth_required
A ticket named for a socket opens only that socket; an unnamed ticket opens any socket except
one that takes only its own ticket. A ticket minted with the session token opens nothing behind
- the sign-in gate, nor once that token is replaced.
+ the sign-in gate, nor once that token is replaced; one minted by a Webapp login opens nothing
+ once the token that login was bound to is replaced.
"""
named = info.get("socket")
if named != socket and (named is not None or socket in OWN_TICKET_SOCKETS):
@@ -60,9 +65,18 @@ def ticket_refusal(info: dict[str, Any], socket: Optional[str], *, auth_required
minted_with = info.get("session_token")
if minted_with is not None and (auth_required or not hmac.compare_digest(minted_with, current_digest())):
return "ticket minted with a replaced session token"
+ signed_in = info.get("sign_in")
+ if signed_in is not None and not hmac.compare_digest(signed_in, current_digest()):
+ return "ticket minted by a login that has since been signed out"
return None
+def admitted_with(info: dict[str, Any]) -> Optional[str]:
+ """The session token digest a redeemed ticket's socket is tracked under, or None when it was
+ minted with another credential."""
+ return info.get("session_token") or info.get("sign_in")
+
+
def track(ws, admitted_with: str) -> None:
"""Keep *ws*, admitted on the session token whose digest is *admitted_with*, until it ends.
@@ -97,8 +111,9 @@ def _close_on(ws, loop: asyncio.AbstractEventLoop) -> bool:
def close_all() -> int:
- """Close every live socket the session token admitted, each on its own event loop. Safe from any
- thread; returns how many were asked to close."""
+ """Close every live socket the session token admitted, directly, through a ticket or through a
+ login bound to it, each on its own event loop. Safe from any thread; returns how many were asked
+ to close."""
with _lock:
live = list(_live.values())
_live.clear()
diff --git a/hermes_cli/webapp_sign_in.py b/hermes_cli/webapp_sign_in.py
new file mode 100644
index 00000000000..c009e91eb8a
--- /dev/null
+++ b/hermes_cli/webapp_sign_in.py
@@ -0,0 +1,86 @@
+"""Behind the sign-in gate, a Webapp login lasts only while the browser credential it is bound to does.
+
+On the gateway's Webapp (``app.state.ui_surface == "webapp"``) with the sign-in gate engaged, every
+successful cookie login (a password login or an OAuth callback) also sets ``hermes_webapp_signin``: the
+hex HMAC-SHA256 of ``"webapp-sign-in"`` keyed with the browser session token the gateway serves
+(``web_server._SESSION_TOKEN``, kept in the gateway home by ``gateway.webapp_listener``). The gate treats
+a cookie session without a matching value as signed out. Replacing that token (``hermes webapp
+--sign-out``, or the CLI replacing the stored token while no gateway runs) therefore signs every browser
+out, whichever provider it signed in with.
+
+A request that passes records the digest of the token it was checked against on
+``request.state.webapp_sign_in``; the socket tickets it mints carry that digest, so the sockets they open
+are tracked (``web_session_sockets.track``) and close at sign-out, and a ticket minted before a sign-out
+opens nothing after it. The standalone dashboard never sets or checks the binding.
+"""
+from __future__ import annotations
+
+import hashlib
+import hmac
+from typing import Optional
+
+from fastapi import Request
+from fastapi.responses import Response
+
+_MESSAGE = b"webapp-sign-in"
+
+
+def binding(token: str) -> str:
+ """The ``hermes_webapp_signin`` value for browser session token *token*."""
+ return hmac.new(token.encode(), _MESSAGE, hashlib.sha256).hexdigest()
+
+
+def applies(request: Request) -> bool:
+ """Whether *request* reaches the gateway's Webapp behind the sign-in gate."""
+ state = request.app.state
+ return getattr(state, "ui_surface", None) == "webapp" and bool(getattr(state, "auth_required", False))
+
+
+def _current_token() -> str:
+ from hermes_cli.web_server import _SESSION_TOKEN
+ return _SESSION_TOKEN
+
+
+def check(request: Request) -> bool:
+ """Whether the cookie login on *request* is bound to the browser credential in use now. When it
+ is, records that credential's digest on ``request.state.webapp_sign_in``."""
+ from hermes_cli.dashboard_auth.cookies import read_webapp_signin_cookie
+ from hermes_cli.web_session_sockets import token_digest
+
+ token = _current_token()
+ presented = read_webapp_signin_cookie(request) or ""
+ if not hmac.compare_digest(presented.encode(), binding(token).encode()):
+ return False
+ request.state.webapp_sign_in = token_digest(token)
+ return True
+
+
+def sign_in_of(request: Request) -> Optional[str]:
+ """The browser credential digest *request*'s login was checked against, or None off the Webapp's
+ gate (the socket tickets it mints then carry no binding)."""
+ return getattr(request.state, "webapp_sign_in", None)
+
+
+def _set(response: Response, request: Request, token: str) -> None:
+ from hermes_cli.dashboard_auth.cookies import detect_https, set_webapp_signin_cookie
+ from hermes_cli.dashboard_auth.prefix import prefix_from_request
+
+ set_webapp_signin_cookie(response, value=binding(token), use_https=detect_https(request),
+ prefix=prefix_from_request(request))
+
+
+def bind(response: Response, request: Request) -> None:
+ """Bind the login *request* just completed to the browser credential in use now."""
+ if applies(request):
+ _set(response, request, _current_token())
+
+
+def renew(response: Response, request: Request) -> None:
+ """Keep the binding as long-lived as the session cookies a refresh just rotated, unless the
+ credential it was checked against was replaced while the request ran."""
+ from hermes_cli.web_session_sockets import token_digest
+
+ signed_in = sign_in_of(request)
+ token = _current_token()
+ if signed_in is not None and hmac.compare_digest(signed_in, token_digest(token)):
+ _set(response, request, token)
diff --git a/tests/gateway/fixtures/webapp_gated_sign_out_peer.py b/tests/gateway/fixtures/webapp_gated_sign_out_peer.py
new file mode 100644
index 00000000000..dcc74454fba
--- /dev/null
+++ b/tests/gateway/fixtures/webapp_gated_sign_out_peer.py
@@ -0,0 +1,191 @@
+"""A real gateway serving the Webapp behind the sign-in gate; a browser signs in, then the owner signs out.
+
+Run as ``python webapp_gated_sign_out_peer.py <port>`` with an isolated ``HERMES_HOME``. The listener binds
+loopback only; a public URL engages the sign-in gate (``engage_sign_in_gate``), and the bundled password
+provider (``plugins/dashboard_auth/basic``) is configured with a throwaway password. Writes ``receipt.json``
+there (the gateway redirects stdout). No external inference: the model points at a closed port.
+"""
+import asyncio
+import json
+import os
+from pathlib import Path
+import secrets
+import sys
+import traceback
+
+USER = "owner"
+PASSWORD = "throwaway-" + secrets.token_urlsafe(12)
+
+
+def engage_sign_in_gate(config: dict, public_url: str) -> None:
+ """The setting that puts the gateway's loopback Webapp behind the sign-in gate: the URL browsers
+ reach it at. The one place this test names that setting."""
+ config.setdefault("webapp", {})["public_url"] = public_url
+
+
+def write_config(home: Path, port: int) -> None:
+ from plugins.dashboard_auth.basic import hash_password
+
+ config = {
+ "gateway": {"multiplex_profiles": False},
+ "model": {"provider": "custom", "default": "no-inference", "base_url": "http://127.0.0.1:1/v1"},
+ "auxiliary": {"title_generation": {"enabled": False}},
+ "webapp": {"enabled": True, "port": port},
+ "dashboard": {"basic_auth": {"username": USER, "password_hash": hash_password(PASSWORD),
+ "secret": secrets.token_hex(32)}},
+ }
+ engage_sign_in_gate(config, f"http://hermes-webapp.test:{port}")
+ (home / "config.yaml").write_text(json.dumps(config), encoding="utf-8") # JSON is YAML
+
+
+async def _close_code(ws, seconds=10):
+ """The code the server closed *ws* with, reading past any frames it sends first."""
+ from websockets.exceptions import ConnectionClosed
+
+ try:
+ async with asyncio.timeout(seconds):
+ while True:
+ await ws.recv()
+ except ConnectionClosed as exc:
+ return exc.rcvd.code if exc.rcvd else None
+ except TimeoutError:
+ return "open"
+
+
+async def _upgrade(url, **kwargs):
+ """``"accepted"``, or the HTTP status of a refused upgrade."""
+ from websockets.asyncio.client import connect
+ from websockets.exceptions import InvalidStatus
+
+ try:
+ async with connect(url, **kwargs):
+ return "accepted"
+ except InvalidStatus as exc:
+ return exc.response.status_code
+
+
+def _refusal(response):
+ """Status and error kind of a refused request, so the report never carries a credential."""
+ try:
+ error = response.json().get("error")
+ except ValueError:
+ error = None
+ return [response.status_code, error, response.headers.get("location", "").split("?", 1)[0]]
+
+
+async def across_sign_out(runner, origin, ask):
+ import httpx
+ from websockets.asyncio.client import connect
+
+ from gateway.runtime_bootstrap import TicketStore
+ from hermes_cli import web_host_terminal
+ from tests.gateway.fixtures.local_recovery_probe import rpc
+
+ # A harmless program stands in for the user's login shell.
+ web_host_terminal.shell_spec = lambda: ([sys.executable, "-c", "import time; time.sleep(120)"], "python")
+ sockets = origin.replace("http:", "ws:")
+ page = {"Origin": origin, "Sec-Fetch-Site": "same-origin"} # the Webapp's own page
+ report = {}
+
+ def chat_protocols(value):
+ return ["hermes-gateway-v1", f"hermes-gateway-ticket.{value}"]
+
+ async def sign_in(browser):
+ signed_in = await browser.post("/auth/password-login", headers=page,
+ json={"provider": "basic", "username": USER, "password": PASSWORD})
+ return signed_in.status_code
+
+ async def ticket(browser, kind):
+ minted = await browser.post(f"/api/webapp/{kind}-ticket", headers=page)
+ return minted.json()["ticket"] if minted.status_code == 200 else None
+
+ authority = runner.session_authority
+ runner.session_ticket_store = TicketStore("webapp-gated", frozenset({authority.profile_id}))
+ native_ticket = runner.session_ticket_store.mint(
+ profile_id=authority.profile_id, subject="fixture-same-user", purpose="interactive")
+ async with httpx.AsyncClient(base_url=origin, timeout=20) as browser:
+ report["before_sign_in"] = _refusal(await browser.get("/api/sessions"))
+ report["sign_in_status"] = await sign_in(browser)
+ report["sessions_before"] = (await browser.get("/api/sessions")).status_code
+ report["me_before"] = (await browser.get("/api/auth/me")).status_code
+ stolen = dict(browser.cookies.items())
+ unused_terminal_ticket = await ticket(browser, "terminal")
+ async with connect(f"{sockets}/api/ws?native_dial=browser", origin=origin,
+ subprotocols=chat_protocols(await ticket(browser, "gateway"))) as chat, \
+ connect(f"{sockets}/api/host-terminal?ticket={await ticket(browser, 'terminal')}",
+ origin=origin) as terminal, \
+ connect(f"{sockets}/api/ws", subprotocols=chat_protocols(native_ticket)) as native:
+ report["terminal_open"] = (await terminal.recv()).startswith(web_host_terminal.META_PREFIX)
+ report["chat_open"] = "result" in await rpc(chat, "session.list")
+ answer = ask("webapp-sign-out")
+ report["sign_out_ok"] = answer["ok"]
+ report["sign_out_result"] = answer.get("result")
+ report["chat_close"] = await _close_code(chat)
+ report["terminal_close"] = await _close_code(terminal)
+ report["native_answers"] = "result" in await rpc(native, "session.list")
+ report["sessions_after"] = _refusal(await browser.get("/api/sessions"))
+ report["me_after"] = _refusal(await browser.get("/api/auth/me"))
+ report["page_after"] = _refusal(await browser.get("/", follow_redirects=False))
+ report["terminal_ticket_after"] = _refusal(await browser.post("/api/webapp/terminal-ticket", headers=page))
+ report["old_terminal_ticket_after"] = await _upgrade(
+ f"{sockets}/api/host-terminal?ticket={unused_terminal_ticket}", origin=origin)
+ async with httpx.AsyncClient(base_url=origin, timeout=20, cookies=stolen) as replay:
+ report["replayed_cookies_after"] = _refusal(await replay.get("/api/sessions"))
+ report["sign_in_again_status"] = await sign_in(browser)
+ report["sessions_after_sign_in_again"] = (await browser.get("/api/sessions")).status_code
+ return report
+
+
+async def probe(port):
+ from gateway.control_socket import GatewayControlServer
+ from gateway.run import GatewayRunner
+ from gateway.run_api import stop_gateway_api
+ from gateway.run_runtime import start_gateway_runtime_api
+ from gateway.session_authority import initialize_session_authority
+ from hermes_cli.dashboard_auth import list_providers
+ from hermes_cli.plugins import discover_plugins
+ import hermes_cli.webapp
+
+ home = Path(os.environ["HERMES_HOME"])
+ write_config(home, port)
+ dist = home / "dist-webapp"
+ dist.mkdir()
+ (dist / "index.html").write_text("<!doctype html><html><body>WEBAPP_BUNDLE</body></html>", encoding="utf-8")
+ hermes_cli.webapp.webapp_dist_dir = lambda _root: dist # the built bundle, without a build
+ discover_plugins() # the gateway loads the bundled sign-in providers at startup
+ runner = GatewayRunner()
+ runner.session_control_server = GatewayControlServer(home) # verbs only; not listening
+ # Set by the gateway bootstrap, which this fixture skips; the gateway is up.
+ runner.session_runtime_descriptor = {"runtime_protocol": 1, "state": "ready", "capabilities": [],
+ "served_profiles": []}
+ await initialize_session_authority(runner, profile_id=str(home), instance_id="webapp-gated")
+ await start_gateway_runtime_api(runner)
+ api = runner.session_api
+ from hermes_cli import web_server
+
+ def ask(verb):
+ raw = json.dumps({"protocol": 1, "verb": verb, "id": 1, "params": {}}).encode()
+ return json.loads(runner.session_control_server.handle_request_line(raw, "fixture-same-user"))
+
+ report = {"api_origin": api.api_origin, "status": ask("webapp-status").get("result"),
+ "providers": sorted(p.name for p in list_providers()),
+ "gate_engaged": bool(getattr(web_server.app.state, "auth_required", False)),
+ "surface": getattr(web_server.app.state, "ui_surface", None)}
+ try:
+ report.update(await across_sign_out(runner, api.api_origin, ask))
+ finally:
+ await stop_gateway_api(api)
+ return report
+
+
+def main():
+ receipt = Path(os.environ["HERMES_HOME"]) / "receipt.json"
+ try:
+ receipt.write_text(json.dumps(asyncio.run(probe(int(sys.argv[1])))))
+ except BaseException:
+ receipt.write_text(json.dumps({"error": traceback.format_exc()}))
+ raise SystemExit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/gateway/test_webapp_gated_sign_out.py b/tests/gateway/test_webapp_gated_sign_out.py
new file mode 100644
index 00000000000..e6737e1f58a
--- /dev/null
+++ b/tests/gateway/test_webapp_gated_sign_out.py
@@ -0,0 +1,74 @@
+"""Signing out of a gateway's Webapp behind the sign-in gate signs the browsers out (a real gateway).
+
+The gateway binds its Webapp on loopback with a public URL, which puts it behind the sign-in gate, and
+the bundled password provider. A browser signs in, opens its chat socket and a host terminal, and a
+native client is attached. ``webapp-sign-out`` (what ``hermes webapp --sign-out`` asks for) then ends
+the browser's login: its sockets close with 4401, its requests get 401 and the page sends it to sign
+in, tickets it minted open nothing, and its cookies replayed elsewhere get nothing. The native client
+stays connected, and the browser can sign in again.
+"""
+import json
+from pathlib import Path
+import socket
+import subprocess
+import sys
+
+import pytest
+
+from tests.gateway.fixtures.local_recovery_probe import child_env
+
+
+def _free_port() -> int:
+ with socket.socket() as probe:
+ probe.bind(("127.0.0.1", 0))
+ return probe.getsockname()[1]
+
+
[email protected](scope="module")
+def signed_out(tmp_path_factory):
+ root = Path(__file__).resolve().parents[2]
+ tmp = tmp_path_factory.mktemp("webapp-gated")
+ home, user = tmp / "state", tmp / "user"
+ for path in (home, user):
+ path.mkdir()
+ env = child_env()
+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),
+ PYTHONUNBUFFERED="1")
+ result = subprocess.run(
+ [sys.executable, str(root / "tests/gateway/fixtures/webapp_gated_sign_out_peer.py"), str(_free_port())],
+ cwd=root, env=env, capture_output=True, text=True, timeout=180, check=False)
+ receipt = home / "receipt.json"
+ assert result.returncode == 0, result.stdout + result.stderr + (receipt.read_text() if receipt.exists() else "")
+ return json.loads(receipt.read_text())
+
+
+def test_the_webapp_is_behind_the_sign_in_gate(signed_out):
+ assert signed_out["gate_engaged"] is True and signed_out["surface"] == "webapp"
+ assert "basic" in signed_out["providers"]
+ assert signed_out["status"]["state"] == "serving"
+ assert signed_out["before_sign_in"][0] == 401
+
+
+def test_a_signed_in_browser_works_before_sign_out(signed_out):
+ assert (signed_out["sign_in_status"], signed_out["sessions_before"], signed_out["me_before"]) == (200, 200, 200)
+ assert signed_out["chat_open"] is True and signed_out["terminal_open"] is True
+
+
+def test_signing_out_closes_the_browsers_sockets_and_keeps_native_clients(signed_out):
+ assert signed_out["sign_out_ok"] is True
+ assert signed_out["chat_close"] == 4401
+ assert signed_out["terminal_close"] == 4401
+ assert signed_out["native_answers"] is True
+ assert signed_out["sign_out_result"]["sign_in_gate"] is True
+ assert signed_out["sign_out_result"]["connections_closed"] == 2
+
+
+def test_after_sign_out_the_browser_must_sign_in_again(signed_out):
+ for probe in ("sessions_after", "me_after", "terminal_ticket_after", "replayed_cookies_after"):
+ assert signed_out[probe][:2] in ([401, "unauthenticated"], [401, "session_expired"]), probe
+ assert signed_out["page_after"][0] == 302 and signed_out["page_after"][2] == "/login"
+ assert signed_out["old_terminal_ticket_after"] == 403
+
+
+def test_the_browser_can_sign_in_again(signed_out):
+ assert (signed_out["sign_in_again_status"], signed_out["sessions_after_sign_in_again"]) == (200, 200)
diff --git a/tests/hermes_cli/test_webapp_gated_sign_out.py b/tests/hermes_cli/test_webapp_gated_sign_out.py
new file mode 100644
index 00000000000..eb67b236c8c
--- /dev/null
+++ b/tests/hermes_cli/test_webapp_gated_sign_out.py
@@ -0,0 +1,181 @@
+"""Behind the sign-in gate, signing the Webapp out signs every browser out.
+
+On a LAN or own-URL Webapp a browser signs in with the dashboard's sign-in (a password, or an OAuth
+provider) and keeps that login in cookies. Each login on the Webapp is bound to the gateway's browser
+credential, so ``hermes webapp --sign-out``, which replaces that credential, ends every one of them:
+the login's requests get 401 and the sign-in view, the sockets and host terminals it opened close with
+4401, tickets it minted open nothing, and its cookies replayed from anywhere get nothing. Signing in
+again works. The standalone dashboard has no browser credential and keeps its logins as on main.
+"""
+import json
+from types import SimpleNamespace
+
+import pytest
+from starlette.testclient import TestClient
+from starlette.websockets import WebSocketDisconnect
+
+from tests.hermes_cli.test_web_host_terminal_persistence import metadata
+from tests.hermes_cli.test_webapp_sign_out_sockets import _close_code
+from tests.hermes_cli.test_webapp_socket_tickets import _TOKEN, serve_webapp
+
+WEBAPP = "http://hermes.lan:9120"
+USER, PASSWORD = "owner", "throwaway-test-password"
+
+
+def gated(tmp_path, monkeypatch):
+ """The Webapp behind the sign-in gate with a password and an OAuth provider registered."""
+ from hermes_cli.dashboard_auth import clear_providers, register_provider
+ from hermes_cli.dashboard_auth.routes import _reset_password_rate_limit
+ from hermes_cli.dashboard_auth.ws_tickets import _reset_for_tests
+ from plugins.dashboard_auth.basic import BasicAuthProvider, hash_password
+ from tests.hermes_cli.conftest_dashboard_auth import StubAuthProvider
+
+ webapp = serve_webapp(tmp_path, monkeypatch)
+ state = webapp.server.app.state
+ monkeypatch.setattr(state, "bound_host", "hermes.lan")
+ monkeypatch.setattr(state, "bound_port", 9120, raising=False)
+ monkeypatch.setattr(state, "auth_required", True)
+ _reset_for_tests()
+ _reset_password_rate_limit()
+ clear_providers()
+ register_provider(BasicAuthProvider(username=USER, password_hash=hash_password(PASSWORD), secret=b"k" * 32))
+ register_provider(StubAuthProvider())
+ webapp.browser = lambda: TestClient(webapp.server.app, base_url=WEBAPP)
+ try:
+ yield webapp
+ finally:
+ clear_providers()
+ _reset_for_tests()
+ _reset_password_rate_limit()
+
+
+def _sign_in_with_password(client):
+ signed_in = client.post("/auth/password-login", json={"provider": "basic", "username": USER, "password": PASSWORD})
+ assert signed_in.status_code == 200, signed_in.text
+
+
+def _sign_in_with_oauth(client):
+ started = client.get("/auth/login?provider=stub", follow_redirects=False)
+ state = started.headers["location"].split("state=")[1]
+ assert client.get(f"/auth/callback?code=stub_code&state={state}", follow_redirects=False).status_code == 302
+
+
+SIGN_INS = {"password": _sign_in_with_password, "oauth": _sign_in_with_oauth}
+
+
+def sign_out(gated, tmp_path):
+ """Ask the gateway serving *gated* for ``webapp-sign-out`` over its control socket."""
+ from gateway.control_socket import GatewayControlServer
+ from gateway.webapp_listener import register_control_verbs
+
+ home = tmp_path / ".hermes"
+ runner = SimpleNamespace(
+ session_control_server=GatewayControlServer(home),
+ webapp_status={"state": "serving", "url": WEBAPP, "reason": None},
+ session_api=SimpleNamespace(app=SimpleNamespace(web=gated.server)))
+ register_control_verbs(runner, home)
+
+ def ask():
+ raw = json.dumps({"protocol": 1, "verb": "webapp-sign-out", "id": 1, "params": {}}).encode()
+ answer = json.loads(runner.session_control_server.handle_request_line(raw, "same-user"))
+ assert answer["ok"], answer
+ assert gated.server._SESSION_TOKEN != _TOKEN
+ return answer["result"]
+ return ask
+
+
+def _signed_out(response):
+ assert response.status_code == 401, response.text
+ body = response.json()
+ assert body["error"] in {"unauthenticated", "session_expired"} and body["login_url"].startswith("/login")
+
+
[email protected]("sign_in", SIGN_INS)
+def test_signing_out_ends_every_login_behind_the_gate(gated, sign_out, sign_in):
+ browser = gated.browser()
+ SIGN_INS[sign_in](browser)
+ assert browser.get("/api/auth/me").status_code == 200
+ sign_out()
+ _signed_out(browser.get("/api/auth/me"))
+ _signed_out(browser.post("/api/webapp/terminal-ticket"))
+ _signed_out(browser.post("/api/auth/ws-ticket"))
+ page = browser.get("/", follow_redirects=False)
+ assert page.status_code == 302 and page.headers["location"].startswith("/login")
+
+
+def test_old_login_cookies_replayed_after_sign_out_get_nothing(gated, sign_out):
+ browser = gated.browser()
+ _sign_in_with_password(browser)
+ stolen = dict(browser.cookies.items())
+ sign_out()
+ replay = gated.browser()
+ replay.cookies.update(stolen)
+ _signed_out(replay.get("/api/auth/me"))
+
+
+def test_signing_in_again_after_sign_out_works(gated, sign_out):
+ browser = gated.browser()
+ _sign_in_with_password(browser)
+ sign_out()
+ _signed_out(browser.get("/api/auth/me"))
+ _sign_in_with_password(browser)
+ assert browser.get("/api/auth/me").status_code == 200
+ assert browser.post("/api/webapp/terminal-ticket").status_code == 200
+
+
+def test_a_credential_replaced_while_the_gateway_was_down_signs_logins_out(gated, monkeypatch):
+ """The CLI replaces the stored credential when no gateway is running; the next gateway serves
+ the new one, and logins bound to the old one are signed out."""
+ browser = gated.browser()
+ _sign_in_with_password(browser)
+ monkeypatch.setattr(gated.server, "_SESSION_TOKEN", "n" * 43)
+ _signed_out(browser.get("/api/auth/me"))
+
+
+def test_signing_out_closes_the_sockets_and_host_terminal_a_login_opened(gated, sign_out):
+ from hermes_cli.dashboard_auth.ws_tickets import mint_ticket
+
+ browser = gated.browser()
+ _sign_in_with_password(browser)
+ terminal = browser.post("/api/webapp/terminal-ticket").json()["ticket"]
+ events = browser.post("/api/auth/ws-ticket").json()["ticket"]
+ other = mint_ticket(user_id="someone-else", provider="stub")
+ with TestClient(gated.host, base_url=WEBAPP) as shells, \
+ shells.websocket_connect(f"ws://hermes.lan:9120/api/host-terminal?ticket={terminal}") as shell, \
+ browser.websocket_connect(f"ws://hermes.lan:9120/api/events?channel=tab-1&ticket={events}") as stream, \
+ browser.websocket_connect(f"ws://hermes.lan:9120/api/events?channel=kept&ticket={other}") as kept:
+ metadata(shell)
+ assert _close_code(shell, 0.2) is None and _close_code(stream, 0.2) is None
+ result = sign_out()
+ assert _close_code(shell) == 4401
+ assert _close_code(stream) == 4401
+ assert _close_code(kept, 0.5) is None
+ assert result["connections_closed"] == 2
+ assert result["sign_in_gate"] is True
+
+
+def test_tickets_a_login_minted_before_sign_out_open_nothing_after(gated, sign_out):
+ browser = gated.browser()
+ _sign_in_with_password(browser)
+ terminal = browser.post("/api/webapp/terminal-ticket").json()["ticket"]
+ events = browser.post("/api/auth/ws-ticket").json()["ticket"]
+ sign_out()
+ with TestClient(gated.host, base_url=WEBAPP) as shells:
+ for client, url in ((shells, f"ws://hermes.lan:9120/api/host-terminal?ticket={terminal}"),
+ (browser, f"ws://hermes.lan:9120/api/events?channel=tab-1&ticket={events}")):
+ with pytest.raises(WebSocketDisconnect) as closed:
+ with client.websocket_connect(url) as ws:
+ ws.receive_text()
+ assert closed.value.code == 4401
+ assert gated.shells == []
+
+
+def test_the_standalone_dashboard_keeps_its_logins_as_on_main(gated, monkeypatch):
+ monkeypatch.setattr(gated.server.app.state, "ui_surface", "dashboard")
+ browser = gated.browser()
+ _sign_in_with_password(browser)
+ assert not any(name.endswith("hermes_webapp_signin") for name in browser.cookies.keys())
+ monkeypatch.setattr(gated.server, "_SESSION_TOKEN", "n" * 43)
+ assert browser.get("/api/auth/me").status_code == 200
diff --git a/tests/hermes_cli/test_webapp_sign_out_sockets.py b/tests/hermes_cli/test_webapp_sign_out_sockets.py
index 8b9711ab84a..f911a98a69d 100644
--- a/tests/hermes_cli/test_webapp_sign_out_sockets.py
+++ b/tests/hermes_cli/test_webapp_sign_out_sockets.py
@@ -73,7 +73,7 @@ def test_signing_out_closes_the_terminal_and_streams_the_session_token_opened(we
client.websocket_connect(f"ws://localhost/api/events?channel=kept&ticket={other}") as kept:
metadata(shell)
assert _close_code(shell, 0.2) is None and _close_code(events, 0.2) is None
- assert sign_out() == {"signed_out": True}
+ assert sign_out() == {"signed_out": True, "sign_in_gate": False, "connections_closed": 2}
assert _close_code(shell) == 4401
assert _close_code(events) == 4401
assert _close_code(kept, 0.5) is None
@@ -83,7 +83,7 @@ def test_signing_out_closes_the_terminal_and_streams_the_session_token_opened(we
def test_signing_out_with_no_open_tabs_still_replaces_the_credential(webapp, sign_out):
client = webapp.client
- assert sign_out() == {"signed_out": True}
+ assert sign_out() == {"signed_out": True, "sign_in_gate": False, "connections_closed": 0}
assert client.post("/api/webapp/gateway-ticket", headers={"X-Hermes-Session-Token": _TOKEN}).status_code == 401