Skip to content

The agent that grows with you

fix(webapp): two gateways' Webapps on one hostname keep their own sign-ins

emozilla42bde77c6877
diff --git a/apps/desktop/electron/connection-config.test.ts b/apps/desktop/electron/connection-config.test.ts
index ddb0ab32b13..882e16928ab 100644
--- a/apps/desktop/electron/connection-config.test.ts
+++ b/apps/desktop/electron/connection-config.test.ts
@@ -1282,6 +1282,18 @@ test('cookiesHaveSession handles non-arrays', () => {
assert.equal(cookiesHaveSession([]), false)
})
+test('a gateway Webapp signs in with cookies named for its gateway, and they count as a session', () => {
+ // Cookies are not scoped to a port, so the gateway's Webapp names its login cookies
+ // hermes_session_at_<gateway> and hermes_session_rt_<gateway>; the dashboard keeps the bare names.
+ const gateway = '0123456789abcdef'
+ assert.equal(cookiesHaveSession([{ name: `hermes_session_at_${gateway}`, value: 'x' }]), true)
+ assert.equal(cookiesHaveSession([{ name: `__Host-hermes_session_at_${gateway}`, value: 'x' }]), true)
+ assert.equal(cookiesHaveSession([{ name: `hermes_session_rt_${gateway}`, value: 'x' }]), false)
+ assert.equal(cookiesHaveLiveSession([{ name: `__Secure-hermes_session_rt_${gateway}`, value: 'x' }]), true)
+ assert.equal(cookiesHaveSession([{ name: 'hermes_session_at_other', value: 'x' }]), false)
+ assert.equal(cookiesHaveLiveSession([{ name: `hermes_webapp_signin_${gateway}`, value: 'x' }]), false)
+})
+
// --- cookiesHaveLiveSession (AT or RT — the connectivity check) ---
test('cookiesHaveLiveSession is true for a live access-token cookie', () => {
diff --git a/apps/desktop/electron/connection-config.ts b/apps/desktop/electron/connection-config.ts
index 45a0b4f3ebc..193447cb995 100644
--- a/apps/desktop/electron/connection-config.ts
+++ b/apps/desktop/electron/connection-config.ts
@@ -40,6 +40,13 @@ import { profileCollectionRoute, profileRouteSuffix } from './profile-routes'
const AT_COOKIE_VARIANTS = ['__Host-hermes_session_at', '__Secure-hermes_session_at', 'hermes_session_at']
const RT_COOKIE_VARIANTS = ['__Host-hermes_session_rt', '__Secure-hermes_session_rt', 'hermes_session_rt']
+// A gateway's Webapp follows each name with its gateway (`hermes_session_at_<16 hex digits>`), since
+// cookies are not scoped to a port; the dashboard keeps the bare names.
+const GATEWAY_COOKIE_SUFFIX = /_[0-9a-f]{16}$/
+
+function isCookieVariant(name: unknown, variants: string[]): boolean {
+ return typeof name === 'string' && (variants.includes(name) || variants.includes(name.replace(GATEWAY_COOKIE_SUFFIX, '')))
+}
// Keep this aligned with hermes_cli.profiles.validate_profile_name(). `default`
// is the built-in root alias; these names cannot be created as profiles.
@@ -1163,7 +1170,7 @@ function cookiesHaveSession(cookies) {
return false
}
- return cookies.some(c => c && AT_COOKIE_VARIANTS.includes(c.name) && c.value)
+ return cookies.some(c => c && isCookieVariant(c.name, AT_COOKIE_VARIANTS) && c.value)
}
/**
@@ -1184,7 +1191,9 @@ function cookiesHaveLiveSession(cookies) {
return false
}
- return cookies.some(c => c && c.value && (AT_COOKIE_VARIANTS.includes(c.name) || RT_COOKIE_VARIANTS.includes(c.name)))
+ return cookies.some(
+ c => c && c.value && (isCookieVariant(c.name, AT_COOKIE_VARIANTS) || isCookieVariant(c.name, RT_COOKIE_VARIANTS))
+ )
}
export {
diff --git a/hermes_cli/dashboard_auth/cookies.py b/hermes_cli/dashboard_auth/cookies.py
index 2993727de0b..d6e5bb54159 100644
--- a/hermes_cli/dashboard_auth/cookies.py
+++ b/hermes_cli/dashboard_auth/cookies.py
@@ -7,13 +7,17 @@ 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_<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).
+``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).
+Cookies are not scoped to a port, so on the gateway's Webapp every one of these names is followed by
+``_<gateway>`` (``hermes_session_at_<gateway>``, ``<gateway>`` from a digest of the gateway's home,
+``webapp_sign_in.cookie_gateway``): two gateways' Webapps on one hostname keep their own logins, and
+neither reads or clears the names the standalone dashboard uses.
``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
-resolve the name via :func:`_resolved_name` — a mismatch silently breaks sessions.
+resolve the name via :func:`_resolved_name` and :func:`gateway_cookie_name` — a mismatch silently
+breaks sessions.
"""
from __future__ import annotations
@@ -32,8 +36,7 @@ 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, its
-#: name followed by the gateway's own suffix (:func:`webapp_signin_cookie_name`).
+#: 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.
@@ -57,6 +60,11 @@ def _resolved_name(bare: str, *, use_https: bool, prefix: str) -> str:
return f"__Secure-{bare}" if prefix else f"__Host-{bare}"
+def gateway_cookie_name(bare: str, gateway: str = "") -> str:
+ """*bare* as the gateway named *gateway* names it; ``""`` (off the gateway's Webapp) keeps *bare*."""
+ return f"{bare}_{gateway}" if gateway else bare
+
+
def _cookie_path(prefix: str) -> str:
"""``Path=/hermes`` under a proxy prefix (no leak to sibling apps), else ``/``."""
return prefix if prefix else "/"
@@ -86,16 +94,16 @@ def _set(response: Response, bare: str, value: str, *, max_age: int,
def set_session_provider_cookie(
- response: Response, *, provider: str, use_https: bool, prefix: str = "") -> None:
+ response: Response, *, provider: str, use_https: bool, prefix: str = "", gateway: str = "") -> None:
"""Persist the non-secret provider routing hint for token refresh."""
if provider:
- _set(response, SESSION_PROVIDER_COOKIE, provider, max_age=_RT_MAX_AGE,
+ _set(response, gateway_cookie_name(SESSION_PROVIDER_COOKIE, gateway), provider, max_age=_RT_MAX_AGE,
use_https=use_https, prefix=prefix)
def set_session_cookies(
response: Response, *, access_token: str, refresh_token: str, access_token_expires_in: int,
- use_https: bool, prefix: str = "", provider: str = "") -> None:
+ use_https: bool, prefix: str = "", provider: str = "", gateway: str = "") -> None:
"""``access_token_expires_in`` is seconds (the provider's reported TTL). An empty
``refresh_token`` means "don't persist the RT cookie" — a literal empty cookie would be dead
state at best, attack surface at worst.
@@ -104,12 +112,12 @@ def set_session_cookies(
``Session.refresh_token == ""`` and we simply don't persist the RT cookie — the session then behaves as
access-token-only until the AT expires. No other branch changes between the two cases.
"""
- _set(response, SESSION_AT_COOKIE, access_token, max_age=access_token_expires_in,
- use_https=use_https, prefix=prefix)
+ _set(response, gateway_cookie_name(SESSION_AT_COOKIE, gateway), access_token,
+ max_age=access_token_expires_in, use_https=use_https, prefix=prefix)
if refresh_token:
- _set(response, SESSION_RT_COOKIE, refresh_token, max_age=_RT_MAX_AGE,
+ _set(response, gateway_cookie_name(SESSION_RT_COOKIE, gateway), refresh_token, max_age=_RT_MAX_AGE,
use_https=use_https, prefix=prefix)
- set_session_provider_cookie(response, provider=provider, use_https=use_https, prefix=prefix)
+ set_session_provider_cookie(response, provider=provider, use_https=use_https, prefix=prefix, gateway=gateway)
def _clear_cookie_variants(
@@ -126,12 +134,13 @@ def _clear_cookie_variants(
response.set_cookie(bare_name, "", max_age=0, **bare_attrs)
-def clear_session_cookies(response: Response, *, prefix: str = "") -> None:
+def clear_session_cookies(response: Response, *, prefix: str = "", gateway: str = "") -> None:
"""Delete the AT, RT and provider cookies (every name variant, active path)."""
bare_attrs = _common_attrs(use_https=False, prefix=prefix)
for name in (SESSION_AT_COOKIE, SESSION_RT_COOKIE, SESSION_PROVIDER_COOKIE):
_clear_cookie_variants(
- response, name, prefix=prefix, https_samesite="lax", bare_attrs=bare_attrs)
+ response, gateway_cookie_name(name, gateway), prefix=prefix, https_samesite="lax",
+ bare_attrs=bare_attrs)
def encode_pkce_payload(parts: dict[str, str]) -> str:
@@ -143,17 +152,17 @@ def encode_pkce_payload(parts: dict[str, str]) -> str:
return base64.urlsafe_b64encode(raw.encode("utf-8")).decode("ascii").rstrip("=")
-def set_pkce_cookie(
- response: Response, *, payload: dict[str, str], use_https: bool, prefix: str = "") -> None:
+def set_pkce_cookie(response: Response, *, payload: dict[str, str], use_https: bool, prefix: str = "",
+ gateway: str = "") -> None:
"""``payload`` is the segment dict; see module docstring for the SameSite=None rationale."""
- _set(response, PKCE_COOKIE, encode_pkce_payload(payload), max_age=_PKCE_MAX_AGE,
+ _set(response, gateway_cookie_name(PKCE_COOKIE, gateway), encode_pkce_payload(payload), max_age=_PKCE_MAX_AGE,
use_https=use_https, prefix=prefix, attrs=_pkce_attrs(use_https=use_https, prefix=prefix))
-def clear_pkce_cookie(response: Response, *, use_https: bool, prefix: str = "") -> None:
+def clear_pkce_cookie(response: Response, *, use_https: bool, prefix: str = "", gateway: str = "") -> None:
"""Delete every PKCE cookie variant (prefixed ones carry ``Secure; SameSite=None``)."""
_clear_cookie_variants(
- response, PKCE_COOKIE, prefix=prefix, https_samesite="none",
+ response, gateway_cookie_name(PKCE_COOKIE, gateway), prefix=prefix, https_samesite="none",
bare_attrs=_pkce_attrs(use_https=use_https, prefix=prefix))
@@ -163,38 +172,32 @@ def _read_with_fallback(request: Request, bare_name: str) -> Optional[str]:
if v is not None), None)
-def read_session_cookies(request: Request) -> tuple[Optional[str], Optional[str]]:
+def read_session_cookies(request: Request, gateway: str = "") -> tuple[Optional[str], Optional[str]]:
"""Returns (access_token, refresh_token), either may be None."""
return (
- _read_with_fallback(request, SESSION_AT_COOKIE),
- _read_with_fallback(request, SESSION_RT_COOKIE))
+ _read_with_fallback(request, gateway_cookie_name(SESSION_AT_COOKIE, gateway)),
+ _read_with_fallback(request, gateway_cookie_name(SESSION_RT_COOKIE, gateway)))
-def read_session_provider(request: Request) -> Optional[str]:
+def read_session_provider(request: Request, gateway: str = "") -> Optional[str]:
"""Return the provider routing hint associated with the session cookies."""
- return _read_with_fallback(request, SESSION_PROVIDER_COOKIE)
+ return _read_with_fallback(request, gateway_cookie_name(SESSION_PROVIDER_COOKIE, gateway))
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)
+ as long as a refresh token cookie lasts. *gateway* names the gateway it binds to."""
+ _set(response, gateway_cookie_name(WEBAPP_SIGNIN_COOKIE, gateway), value, max_age=_RT_MAX_AGE,
+ use_https=use_https, prefix=prefix)
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
+ return _read_with_fallback(request, gateway_cookie_name(WEBAPP_SIGNIN_COOKIE, gateway))
-def read_pkce_cookie(request: Request) -> Optional[str]:
- return _read_with_fallback(request, PKCE_COOKIE)
+def read_pkce_cookie(request: Request, gateway: str = "") -> Optional[str]:
+ return _read_with_fallback(request, gateway_cookie_name(PKCE_COOKIE, gateway))
def parse_pkce_payload(raw: str) -> dict[str, str]:
@@ -223,21 +226,21 @@ def parse_pkce_payload(raw: str) -> dict[str, str]:
return dict(seg.split("=", 1) for seg in flat.split(";") if "=" in seg)
-def set_sso_attempt_cookie(response: Response, *, use_https: bool, prefix: str = "") -> None:
+def set_sso_attempt_cookie(response: Response, *, use_https: bool, prefix: str = "", gateway: str = "") -> None:
"""Set the auto-SSO loop-guard marker; only its presence matters."""
- _set(response, SSO_ATTEMPT_COOKIE, "1", max_age=_SSO_ATTEMPT_MAX_AGE,
+ _set(response, gateway_cookie_name(SSO_ATTEMPT_COOKIE, gateway), "1", max_age=_SSO_ATTEMPT_MAX_AGE,
use_https=use_https, prefix=prefix)
-def read_sso_attempt_cookie(request: Request) -> Optional[str]:
+def read_sso_attempt_cookie(request: Request, gateway: str = "") -> Optional[str]:
"""Return the auto-SSO marker value if present (any variant), else None."""
- return _read_with_fallback(request, SSO_ATTEMPT_COOKIE)
+ return _read_with_fallback(request, gateway_cookie_name(SSO_ATTEMPT_COOKIE, gateway))
-def clear_sso_attempt_cookie(response: Response, *, prefix: str = "") -> None:
+def clear_sso_attempt_cookie(response: Response, *, prefix: str = "", gateway: str = "") -> None:
"""Delete the auto-SSO marker (every variant) so it never suppresses a later silent attempt."""
_clear_cookie_variants(
- response, SSO_ATTEMPT_COOKIE, prefix=prefix, https_samesite="lax",
+ response, gateway_cookie_name(SSO_ATTEMPT_COOKIE, gateway), prefix=prefix, https_samesite="lax",
bare_attrs=_common_attrs(use_https=False, prefix=prefix))
diff --git a/hermes_cli/dashboard_auth/middleware.py b/hermes_cli/dashboard_auth/middleware.py
index f1f53d60d5f..e45c9865f4a 100644
--- a/hermes_cli/dashboard_auth/middleware.py
+++ b/hermes_cli/dashboard_auth/middleware.py
@@ -110,9 +110,10 @@ def _auto_sso_response(request: Request) -> Response | None:
"""
if request.url.path.startswith("/api/"):
return None
- if read_sso_attempt_cookie(request):
+ gateway = webapp_sign_in.cookie_gateway(request)
+ if read_sso_attempt_cookie(request, gateway):
resp = _unauth_response(request, reason="no_cookie")
- clear_sso_attempt_cookie(resp, prefix=prefix_from_request(request))
+ clear_sso_attempt_cookie(resp, prefix=prefix_from_request(request), gateway=gateway)
return resp
providers = list_session_providers()
if len(providers) != 1 or getattr(providers[0], "supports_password", False):
@@ -124,7 +125,7 @@ def _auto_sso_response(request: Request) -> Response | None:
if next_param:
auth_login = f"{auth_login}&next={next_param}"
resp = RedirectResponse(url=auth_login, status_code=302)
- set_sso_attempt_cookie(resp, use_https=detect_https(request), prefix=prefix)
+ set_sso_attempt_cookie(resp, use_https=detect_https(request), prefix=prefix, gateway=gateway)
audit_log(AuditEvent.LOGIN_START, provider=provider.name, reason="auto_sso",
ip=_client_ip(request))
return resp
@@ -154,7 +155,8 @@ async def _serve_refreshed(request: Request, call_next, new_session, provider: s
set_session_cookies(
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)
+ prefix=prefix_from_request(request), provider=provider,
+ gateway=webapp_sign_in.cookie_gateway(request))
webapp_sign_in.renew(response, request)
audit_log(AuditEvent.REFRESH_SUCCESS, provider=provider, user_id=new_session.user_id,
ip=_client_ip(request))
@@ -167,7 +169,8 @@ def _session_expired_response(request: Request) -> Response:
audit_log(AuditEvent.SESSION_VERIFY_FAILURE, reason="no_provider_recognises",
ip=_client_ip(request))
response = _unauth_response(request, reason="invalid_or_expired_session")
- clear_session_cookies(response, prefix=prefix_from_request(request))
+ clear_session_cookies(response, prefix=prefix_from_request(request),
+ gateway=webapp_sign_in.cookie_gateway(request))
return response
@@ -206,8 +209,9 @@ async def gated_auth_middleware(
return await call_next(request)
return _unauth_response(request, reason="invalid_or_expired_session")
- at, _rt = read_session_cookies(request)
- provider_hint = read_session_provider(request)
+ gateway = webapp_sign_in.cookie_gateway(request)
+ at, _rt = read_session_cookies(request, gateway)
+ provider_hint = read_session_provider(request, gateway)
if (at or _rt) and request.method not in {"GET", "HEAD", "OPTIONS", "TRACE"} and not cookie_origin_is_allowed(request):
return JSONResponse(status_code=403, content={"detail": _cross_origin_write_detail(request.app.state)})
if cookie_logout:
@@ -218,7 +222,7 @@ async def gated_auth_middleware(
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.
+ # in use; signing out replaced it. The cookies stay and open nothing until it signs in again.
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.
@@ -246,7 +250,7 @@ async def gated_auth_middleware(
if not provider_hint and session.provider:
set_session_provider_cookie(
response, provider=session.provider, use_https=detect_https(request),
- prefix=prefix_from_request(request))
+ prefix=prefix_from_request(request), gateway=gateway)
return response
diff --git a/hermes_cli/dashboard_auth/routes.py b/hermes_cli/dashboard_auth/routes.py
index 2a15800f7c6..dedc0b38598 100644
--- a/hermes_cli/dashboard_auth/routes.py
+++ b/hermes_cli/dashboard_auth/routes.py
@@ -99,14 +99,20 @@ def _validate_post_login_target(raw: str) -> str:
def _set_pkce(resp, request: Request, payload: dict[str, str]) -> None:
- set_pkce_cookie(resp, payload=payload, use_https=detect_https(request), prefix=_prefix(request))
+ set_pkce_cookie(resp, payload=payload, use_https=detect_https(request), prefix=_prefix(request),
+ gateway=webapp_sign_in.cookie_gateway(request))
+
+
+def _clear_pkce(resp, request: Request) -> None:
+ clear_pkce_cookie(resp, use_https=detect_https(request), prefix=_prefix(request),
+ gateway=webapp_sign_in.cookie_gateway(request))
def _set_session(resp, request: Request, session: Session) -> None:
set_session_cookies(
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)
+ prefix=_prefix(request), provider=session.provider, gateway=webapp_sign_in.cookie_gateway(request))
webapp_sign_in.bind(resp, request)
@@ -341,7 +347,7 @@ async def auth_native_authorize(
async def auth_callback(
request: Request, code: str = "", state: str = "", error: str = "",
error_description: str = ""):
- pkce_raw = read_pkce_cookie(request)
+ pkce_raw = read_pkce_cookie(request, webapp_sign_in.cookie_gateway(request))
if not pkce_raw:
_audit(request, AuditEvent.LOGIN_FAILURE, reason="missing_pkce_cookie")
raise _http(400, "Missing PKCE state cookie")
@@ -374,10 +380,9 @@ async def auth_callback(
resp = RedirectResponse(url=target, status_code=302)
if not native:
_set_session(resp, request, session)
- prefix = _prefix(request)
- clear_pkce_cookie(resp, use_https=detect_https(request), prefix=prefix)
+ _clear_pkce(resp, request)
# Clear the one-shot auto-SSO loop-guard so it never suppresses a future silent attempt.
- clear_sso_attempt_cookie(resp, prefix=prefix)
+ clear_sso_attempt_cookie(resp, prefix=_prefix(request), gateway=webapp_sign_in.cookie_gateway(request))
return resp
@@ -466,7 +471,7 @@ async def auth_password_login(request: Request, body: _PasswordLoginBody):
# The native broker handle also records WHICH provider the flow was started for. Enforce
# equality BEFORE verifying credentials so a flow started for provider A cannot be completed
# with provider B's credentials.
- pkce_raw = read_pkce_cookie(request)
+ pkce_raw = read_pkce_cookie(request, webapp_sign_in.cookie_gateway(request))
pkce_parts = parse_pkce_payload(pkce_raw) if pkce_raw else {}
broker_state = pkce_parts.get("broker", "")
if broker_state and pkce_parts.get("provider", "") != body.provider:
@@ -489,7 +494,7 @@ async def auth_password_login(request: Request, body: _PasswordLoginBody):
request, body.provider, session, broker_state=broker_state, next_raw=body.next)
resp = JSONResponse({"ok": True, "next": target})
if native:
- clear_pkce_cookie(resp, use_https=detect_https(request), prefix=_prefix(request))
+ _clear_pkce(resp, request)
else:
_set_session(resp, request, session)
return resp
@@ -497,7 +502,7 @@ async def auth_password_login(request: Request, body: _PasswordLoginBody):
@router.post("/auth/logout", name="auth_logout")
async def auth_logout(request: Request):
- _at, rt = read_session_cookies(request)
+ _at, rt = read_session_cookies(request, webapp_sign_in.cookie_gateway(request))
# Best-effort revoke on every provider; failures logged, never raised.
for provider in list_providers() if rt else ():
try:
@@ -509,8 +514,8 @@ async def auth_logout(request: Request):
user_id=(sess.user_id if sess else ""))
prefix = _prefix(request)
resp = RedirectResponse(url=f"{prefix}/login", status_code=302)
- clear_session_cookies(resp, prefix=prefix)
- clear_pkce_cookie(resp, use_https=detect_https(request), prefix=prefix)
+ clear_session_cookies(resp, prefix=prefix, gateway=webapp_sign_in.cookie_gateway(request))
+ _clear_pkce(resp, request)
return resp
diff --git a/hermes_cli/webapp_sign_in.py b/hermes_cli/webapp_sign_in.py
index 0f18f7bb4d3..0b3259a6e98 100644
--- a/hermes_cli/webapp_sign_in.py
+++ b/hermes_cli/webapp_sign_in.py
@@ -2,13 +2,13 @@
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 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
+``hermes_webapp_signin_<gateway>``: 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.
+out, whichever provider it signed in with. ``<gateway>`` comes from a digest of the gateway's home
+(:func:`cookie_gateway`), and the Webapp's listener names every sign-in cookie it sets that way, so two
+gateways' Webapps on one hostname keep their own logins and leave the standalone dashboard's alone.
A request that passes records the generation of the credential it was checked against
(``hermes_cli.browser_credential``) on ``request.state.webapp_sign_in``; the socket tickets it mints
@@ -150,6 +150,13 @@ def _home(request: Request) -> Optional[Path]:
return Path(home) if home is not None else None
+def cookie_gateway(request: Request) -> str:
+ """The suffix the gateway's Webapp gives every sign-in cookie it sets (``hermes_session_at_<it>``
+ and the rest, ``hermes_cli.dashboard_auth.cookies``): cookies are not scoped to a port. ``""`` off
+ the Webapp, where the standalone dashboard keeps main's names."""
+ return _gateway(request) if getattr(request.app.state, "ui_surface", None) == "webapp" else ""
+
+
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."""
diff --git a/tests/gateway/fixtures/webapp_gated_sign_out_peer.py b/tests/gateway/fixtures/webapp_gated_sign_out_peer.py
index 79b7a81212d..bd8747575c0 100644
--- a/tests/gateway/fixtures/webapp_gated_sign_out_peer.py
+++ b/tests/gateway/fixtures/webapp_gated_sign_out_peer.py
@@ -133,7 +133,9 @@ async def across_sign_out(runner, origin, ask):
async with httpx.AsyncClient(base_url=origin, timeout=20, cookies=stolen) as replay:
report["replayed_cookies_after"] = _refusal(await replay.get("/api/sessions"))
# The provider tokens those cookies held, presented on their own as a native app would.
- access, refresh = (stolen[name].strip('"') for name in ("hermes_session_at", "hermes_session_rt"))
+ # The Webapp's listener names its cookies for the gateway (``hermes_session_at_<gateway>``).
+ access, refresh = (next(value for key, value in stolen.items() if key.startswith(f"{name}_")).strip('"')
+ for name in ("hermes_session_at", "hermes_session_rt"))
async with httpx.AsyncClient(base_url=origin, timeout=20) as thief:
report["stolen_access_token_after"] = _refusal(
await thief.get("/api/sessions", headers={"Authorization": "Bearer " + access}))
diff --git a/tests/hermes_cli/test_webapp_gated_sign_out.py b/tests/hermes_cli/test_webapp_gated_sign_out.py
index f361024477d..a1a71736d7c 100644
--- a/tests/hermes_cli/test_webapp_gated_sign_out.py
+++ b/tests/hermes_cli/test_webapp_gated_sign_out.py
@@ -215,6 +215,63 @@ def test_two_gateways_on_one_hostname_keep_their_own_sign_ins(gated, monkeypatch
assert browser.get(at(9120, "/api/auth/me")).status_code == 200
+def test_two_gateways_with_their_own_sign_in_on_one_hostname_keep_their_logins_apart(gated, monkeypatch, tmp_path):
+ """The Webapp's listener names every sign-in cookie it sets for its gateway (the login's access and
+ refresh token, its provider hint and binding, the OAuth state and the auto sign-in marker), so two
+ gateways on one hostname whose sign-in providers differ (two users' or two profiles' gateways, each
+ with its own provider secret) keep their own logins in one browser: signing in to one leaves the
+ other signed in, and signing out of one in the browser leaves the other."""
+ from hermes_cli.dashboard_auth import clear_providers, register_provider
+ from plugins.dashboard_auth.basic import BasicAuthProvider, hash_password
+
+ state = gated.server.app.state
+ providers = {port: BasicAuthProvider(username=USER, password_hash=hash_password(PASSWORD), secret=secret * 32)
+ for port, secret in ((9120, b"1"), (9121, b"2"))}
+ 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)
+ clear_providers()
+ register_provider(providers[port])
+ 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
+ first = browser.get(at(9120, "/api/auth/me"))
+ assert first.status_code == 200, f"signing in to the second gateway signed the first out: {first.text}"
+ assert browser.post(at(9121, "/auth/logout"), headers={"Origin": "http://hermes.lan:9121"},
+ follow_redirects=False).status_code == 302
+ _signed_out(browser.get(at(9121, "/api/auth/me")))
+ assert browser.get(at(9120, "/api/auth/me")).status_code == 200
+
+
+def test_the_webapp_leaves_cookies_named_for_no_gateway_to_the_dashboard(gated, monkeypatch):
+ """The standalone dashboard on the same hostname keeps main's cookie names, as did earlier builds
+ of the Webapp. The Webapp's listener neither reads nor clears them: a browser holding only such a
+ login gets the sign-in view there, and the dashboard keeps it."""
+ monkeypatch.setattr(gated.server.app.state, "ui_surface", "dashboard")
+ browser = gated.browser()
+ _sign_in_with_password(browser)
+ names = set(browser.cookies.keys())
+ assert {"hermes_session_at", "hermes_session_rt", "hermes_session_provider"} <= names
+ monkeypatch.setattr(gated.server.app.state, "ui_surface", "webapp")
+ on_webapp = browser.get("/api/auth/me")
+ _signed_out(on_webapp)
+ assert "hermes_session_at=" not in on_webapp.headers.get("set-cookie", "")
+ signed_out = browser.post("/auth/logout", headers={"Origin": WEBAPP}, follow_redirects=False)
+ assert signed_out.status_code == 302
+ assert "hermes_session_at=" not in signed_out.headers.get("set-cookie", "")
+ monkeypatch.setattr(gated.server.app.state, "ui_surface", "dashboard")
+ assert browser.get("/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
@@ -236,10 +293,17 @@ def clock(monkeypatch):
return advance
+def _cookie(client, bare):
+ """The name of *client*'s cookie *bare*: on the Webapp's listener followed by its gateway, elsewhere
+ as on main."""
+ return next(name for name in client.cookies.keys() if name == bare or name.startswith(f"{bare}_"))
+
+
def _tokens(client):
"""The access and refresh token the cookie login on *client* holds, as a copy taken out of the
browser would present them (the cookie keeps them in quotes)."""
- return tuple(client.cookies.get(name).strip('"') for name in ("hermes_session_at", "hermes_session_rt"))
+ return tuple(client.cookies.get(_cookie(client, name)).strip('"')
+ for name in ("hermes_session_at", "hermes_session_rt"))
def _bearer(token):
@@ -293,7 +357,8 @@ def test_a_logins_tokens_work_only_as_its_cookies(gated, sign_in):
assert browser.get("/api/auth/me").status_code == 200
access, refresh = _tokens(browser)
_refused_alone(gated, access, refresh)
- stored = browser.cookies.get("hermes_session_at"), browser.cookies.get("hermes_session_rt")
+ stored = (browser.cookies.get(_cookie(browser, "hermes_session_at")),
+ browser.cookies.get(_cookie(browser, "hermes_session_rt")))
_refused_alone(gated, *stored)
@@ -303,7 +368,7 @@ def test_a_pair_renewed_before_sign_out_is_refused_after_it(gated, sign_out, clo
first = _tokens(browser)
# The gate renews the browser's pair once its access token lapses.
clock()
- browser.cookies.delete("hermes_session_at")
+ browser.cookies.delete(_cookie(browser, "hermes_session_at"))
assert browser.get("/api/auth/me").status_code == 200
renewed = _tokens(browser)
assert renewed[0] != first[0]
diff --git a/website/docs/developer-guide/gateway-local-sessions.md b/website/docs/developer-guide/gateway-local-sessions.md
index 9ec7b0e350c..f8e0fd810cb 100644
--- a/website/docs/developer-guide/gateway-local-sessions.md
+++ b/website/docs/developer-guide/gateway-local-sessions.md
@@ -53,9 +53,11 @@ The server issues `session:operator` only at these existing trusted boundaries:
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_<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
+ `webapp-sign-in` keyed with the token), so replacing it ends those logins too; sign-out closes
+ every socket the token or a bound login opened, Bot Desktop viewers included. The Webapp's listener
+ names every sign-in cookie it sets that way (`hermes_session_at_<gateway>` and the rest; `<gateway>`
+ comes from a digest of the gateway home), so two gateways' Webapps on one hostname keep their own
+ logins, whatever their sign-in providers, and leave the standalone dashboard's cookies alone. The provider tokens
such a login keeps in its cookies never work there on their own: the Webapp's listener accepts a
bearer token or a socket's `?token=`, and renews a refresh token, only when it gave that token to a
native app's RFC 8252 sign-in (digests kept in `webapp/native-sign-in-tokens.json` in the gateway home until they