Skip to content

The agent that grows with you

fix(webapp): keep the sign-ins of two gateways' Webapps on one hostname apart

emozilla030661475836
diff --git a/hermes_cli/dashboard_auth/cookies.py b/hermes_cli/dashboard_auth/cookies.py
index 5b1b6ae28c7..2993727de0b 100644
--- a/hermes_cli/dashboard_auth/cookies.py
+++ b/hermes_cli/dashboard_auth/cookies.py
@@ -7,8 +7,9 @@ when the provider returned one, always cleared on logout/expiry), ``hermes_sessi
(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),
-``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).
+``hermes_webapp_signin_<gateway>`` (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, named for the gateway's home so two
+gateways' Webapps on one hostname keep their own).
``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
@@ -31,7 +32,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.
+#: The Webapp's sign-in binding (``hermes_cli.webapp_sign_in``); set beside the session cookies, its
+#: name followed by the gateway's own suffix (:func:`webapp_signin_cookie_name`).
WEBAPP_SIGNIN_COOKIE = "hermes_webapp_signin"
# Name variants a reader may have to try; most strict first.
@@ -173,14 +175,22 @@ 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 set_webapp_signin_cookie(response: Response, *, value: str, use_https: bool, prefix: str = "",
+ gateway: str = "") -> None:
+ """Set the Webapp's sign-in binding with the session cookies' Path, SameSite and Secure policy, for
+ as long as a refresh token cookie lasts. *gateway* names the gateway it binds to: cookies are not
+ scoped to a port, and two gateways' Webapps on one hostname must not replace each other's."""
+ _set(response, webapp_signin_cookie_name(gateway), 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_webapp_signin_cookie(request: Request, gateway: str = "") -> Optional[str]:
+ return _read_with_fallback(request, webapp_signin_cookie_name(gateway))
+
+
+def webapp_signin_cookie_name(gateway: str) -> str:
+ """The bare name of the sign-in binding for the gateway named *gateway* (``""`` for none)."""
+ return f"{WEBAPP_SIGNIN_COOKIE}_{gateway}" if gateway else WEBAPP_SIGNIN_COOKIE
def read_pkce_cookie(request: Request) -> Optional[str]:
diff --git a/hermes_cli/webapp_sign_in.py b/hermes_cli/webapp_sign_in.py
index 22d007d5d36..ce55d4ad493 100644
--- a/hermes_cli/webapp_sign_in.py
+++ b/hermes_cli/webapp_sign_in.py
@@ -1,7 +1,9 @@
"""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
+successful cookie login (a password login or an OAuth callback) also sets the cookie
+``hermes_webapp_signin_<gateway>`` (``<gateway>`` from a digest of the gateway's home, so two gateways'
+Webapps on one hostname keep their own): 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
@@ -75,7 +77,7 @@ def check(request: Request) -> bool:
from hermes_cli.web_session_sockets import token_digest
token = _current_token()
- presented = read_webapp_signin_cookie(request) or ""
+ presented = read_webapp_signin_cookie(request, _gateway(request)) or ""
if not hmac.compare_digest(presented.encode(), binding(token).encode()):
return False
request.state.webapp_sign_in = token_digest(token)
@@ -93,7 +95,7 @@ def _set(response: Response, request: Request, token: str) -> None:
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))
+ prefix=prefix_from_request(request), gateway=_gateway(request))
def bind(response: Response, request: Request) -> None:
@@ -153,6 +155,13 @@ def _home(request: Request) -> Optional[Path]:
return Path(home) if home is not None else None
+def _gateway(request: Request) -> str:
+ """This gateway's name in its sign-in cookie: a digest of its home, the same across restarts and
+ different for every gateway on one machine (each home has its own); ``""`` without a home."""
+ home = _home(request)
+ return "" if home is None else hashlib.sha256(str(home.absolute()).encode()).hexdigest()[:16]
+
+
def _loaded(home: Optional[Path]) -> dict[str, int]:
"""*home*'s record, read from its file on first use (call with ``_records_lock`` held). Without a
home it lives in memory only."""
diff --git a/tests/hermes_cli/test_webapp_gated_sign_out.py b/tests/hermes_cli/test_webapp_gated_sign_out.py
index d390a5ad72a..3231d3794a2 100644
--- a/tests/hermes_cli/test_webapp_gated_sign_out.py
+++ b/tests/hermes_cli/test_webapp_gated_sign_out.py
@@ -183,11 +183,37 @@ 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())
+ assert not any("hermes_webapp_signin" in name for name in browser.cookies.keys())
monkeypatch.setattr(gated.server, "_SESSION_TOKEN", "n" * 43)
assert browser.get("/api/auth/me").status_code == 200
+def test_two_gateways_on_one_hostname_keep_their_own_sign_ins(gated, monkeypatch, tmp_path):
+ """Cookies are not scoped to a port, so one browser sends the Webapps of two gateways on one host
+ the same cookies. Signing in to one leaves the other signed in (here both accept the same account
+ tokens, as two gateways sharing a sign-in provider do), and signing one out leaves the other."""
+ state = gated.server.app.state
+ gateways = {9120: (tmp_path / ".hermes", _TOKEN), 9121: (tmp_path / "other-home", "o" * 43)}
+ browser = gated.browser() # one cookie jar for both
+
+ def at(port, path):
+ home, token = gateways[port]
+ monkeypatch.setattr(state, "webapp_home", home)
+ monkeypatch.setattr(state, "bound_port", port)
+ monkeypatch.setattr(gated.server, "_SESSION_TOKEN", token)
+ return f"http://hermes.lan:{port}{path}"
+
+ for port in (9120, 9121):
+ signed_in = browser.post(at(port, "/auth/password-login"),
+ json={"provider": "basic", "username": USER, "password": PASSWORD})
+ assert signed_in.status_code == 200
+ assert browser.get(at(9121, "/api/auth/me")).status_code == 200
+ assert browser.get(at(9120, "/api/auth/me")).status_code == 200
+ gateways[9121] = (gateways[9121][0], "r" * 43) # the second gateway signs its browsers out
+ _signed_out(browser.get(at(9121, "/api/auth/me")))
+ assert browser.get(at(9120, "/api/auth/me")).status_code == 200
+
+
# A browser's login keeps the sign-in provider's access and refresh token in its cookies. Copied out of
# them they are the kind of token a native app presents as ``Authorization: Bearer`` and renews on
# ``/auth/native/refresh``. On the Webapp's listener they work only as that login's cookies, so signing
diff --git a/website/docs/developer-guide/gateway-local-sessions.md b/website/docs/developer-guide/gateway-local-sessions.md
index 1bf29c31a14..f287493e8e2 100644
--- a/website/docs/developer-guide/gateway-local-sessions.md
+++ b/website/docs/developer-guide/gateway-local-sessions.md
@@ -52,8 +52,9 @@ The server issues `session:operator` only at these existing trusted boundaries:
Webapp tabs survive a restart, hands it out only through a one-use link minted for a same-user
control-socket peer, and replaces it on `hermes webapp --sign-out` and whenever the Webapp's
listener fails to start, since its port then belongs to someone else. Behind the sign-in gate a
- Webapp login is bound to that token by the `hermes_webapp_signin` cookie (HMAC-SHA256 of
- `webapp-sign-in` keyed with the token), so replacing it ends those logins too; sign-out closes
+ Webapp login is bound to that token by the `hermes_webapp_signin_<gateway>` cookie (HMAC-SHA256 of
+ `webapp-sign-in` keyed with the token; `<gateway>` comes from a digest of the gateway home, so two
+ gateways' Webapps on one hostname keep their own), so replacing it ends those logins too; sign-out closes
every socket the token or a bound login opened, Bot Desktop viewers included. The provider tokens
such a login keeps in its cookies never work there on their own: the Webapp's listener accepts a
bearer token, and renews a refresh token, only when it gave that token to a native app's RFC 8252