Skip to content

The agent that grows with you

fix(webapp): end the account tokens of a signed-out browser login on the Webapp too

emozilla9538b1b04069
diff --git a/gateway/run_api.py b/gateway/run_api.py
index ea96dacb586..20e36a834d2 100644
--- a/gateway/run_api.py
+++ b/gateway/run_api.py
@@ -94,6 +94,7 @@ class GatewayDashboardMount:
from gateway.webapp_listener import browser_session_token
web.app.state.ui_surface = "webapp"
web.app.state.web_dist = webapp.dist
+ web.app.state.webapp_home = webapp.home
self._replaced_session_token = web._SESSION_TOKEN
web._SESSION_TOKEN = browser_session_token(webapp.home)
@@ -106,8 +107,8 @@ class GatewayDashboardMount:
delattr(self.web.app.state, "listener_public_url")
if self._replaced_session_token is not None:
# Removed, not cleared: a listener mounted next (the private one the gateway falls back
- # to) must find the app as main's listener does, with no surface and no bundle set.
- for name in ("ui_surface", "web_dist"):
+ # to) must find the app as main's listener does, with no surface, bundle or home set.
+ for name in ("ui_surface", "web_dist", "webapp_home"):
if hasattr(self.web.app.state, name):
delattr(self.web.app.state, name)
self.web._SESSION_TOKEN, self._replaced_session_token = self._replaced_session_token, None
diff --git a/hermes_cli/dashboard_auth/middleware.py b/hermes_cli/dashboard_auth/middleware.py
index 9c600743110..f1f53d60d5f 100644
--- a/hermes_cli/dashboard_auth/middleware.py
+++ b/hermes_cli/dashboard_auth/middleware.py
@@ -189,11 +189,14 @@ async def gated_auth_middleware(
# RFC 8252 native-app bearer path: the same provider-minted access token the cookie flow
# stores, verified with the same provider stack, no cookie read or set. A presented-but-
# invalid bearer gets the structured 401 so the desktop refreshes/re-logs instead of
- # following a cookie redirect.
+ # following a cookie redirect. On the gateway's Webapp only tokens it gave a native app's
+ # sign-in work here: a browser login's tokens work only as its cookies, which sign-out ends.
bearer = _extract_bearer(request)
if bearer:
if cookie_logout:
return await call_next(request)
+ if not webapp_sign_in.token_works_alone(request, bearer):
+ return _unauth_response(request, reason="invalid_or_expired_session")
try:
bearer_session = _verify_access_token(request, access_token=bearer, audit=False)
except ProviderError as e:
diff --git a/hermes_cli/dashboard_auth/routes.py b/hermes_cli/dashboard_auth/routes.py
index 1846ca60ecb..2a15800f7c6 100644
--- a/hermes_cli/dashboard_auth/routes.py
+++ b/hermes_cli/dashboard_auth/routes.py
@@ -587,6 +587,7 @@ async def auth_native_token(request: Request, body: _NativeTokenBody):
except native_flow.CodeInvalid:
_audit(request, AuditEvent.NATIVE_TOKEN_FAILURE, reason="invalid_code_or_pkce")
raise _http(400, "Invalid or expired authorization code.")
+ webapp_sign_in.gave_native_app(request, session)
_audit(request, AuditEvent.NATIVE_TOKEN_SUCCESS, provider=session.provider,
user_id=session.user_id)
return _bearer_payload(session)
@@ -601,9 +602,15 @@ class _NativeRefreshBody(BaseModel):
async def auth_native_refresh(request: Request, body: _NativeRefreshBody):
"""Rotate a desktop-held refresh token (mirrors the gate's ``_attempt_refresh``): every
provider rejecting the RT -> 401 ``session_expired`` (desktop re-logs); none rotated and one
- unreachable -> 503."""
+ unreachable -> 503. On the gateway's Webapp behind the gate it renews only refresh tokens
+ this listener gave a native app's sign-in (``webapp_sign_in.token_works_alone``)."""
if not body.refresh_token:
raise _http(400, "refresh_token required")
+ if not webapp_sign_in.token_works_alone(request, body.refresh_token):
+ _audit(request, AuditEvent.REFRESH_FAILURE, reason="not_a_native_sign_in")
+ return JSONResponse(
+ {"error": "session_expired",
+ "detail": "Refresh token expired or invalid; start a new sign-in."}, status_code=401)
try:
# Off the event loop: the provider call is synchronous network I/O and a slow IdP
# otherwise wedges every public endpoint (/api/status) behind it.
@@ -614,6 +621,7 @@ async def auth_native_refresh(request: Request, body: _NativeRefreshBody):
raise _http(503, f"Auth provider {str(e)!r} unreachable")
if refreshed is not None:
session = refreshed[0]
+ webapp_sign_in.gave_native_app(request, session)
_audit(request, AuditEvent.REFRESH_SUCCESS, provider=session.provider,
user_id=session.user_id)
return _bearer_payload(session)
diff --git a/hermes_cli/webapp_launcher.py b/hermes_cli/webapp_launcher.py
index 368b0ecfb7f..78544e5a02e 100644
--- a/hermes_cli/webapp_launcher.py
+++ b/hermes_cli/webapp_launcher.py
@@ -149,7 +149,9 @@ def _signed_out_summary(result: dict) -> str:
closed = result["connections_closed"]
connections = f"closed {closed} browser connection{'' if closed == 1 else 's'}"
if result.get("sign_in_gate"):
- return f"Signed out every browser: {connections}. Browsers behind sign-in must sign in again."
+ return (f"Signed out every browser: {connections}. Every browser login behind sign-in has ended, "
+ "and the account tokens it held no longer work here: browsers must sign in again. Native apps "
+ "signed in to this gateway with their own sign-in stay signed in.")
return f"Signed out of every Webapp tab: {connections}. Run hermes webapp to open it again."
diff --git a/hermes_cli/webapp_sign_in.py b/hermes_cli/webapp_sign_in.py
index c009e91eb8a..22d007d5d36 100644
--- a/hermes_cli/webapp_sign_in.py
+++ b/hermes_cli/webapp_sign_in.py
@@ -12,17 +12,44 @@ 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.
+
+Such a login's cookies also hold the sign-in provider's access and refresh token. Presented on their own
+(``Authorization: Bearer``, ``/auth/native/refresh``) they would skip the binding, and a list of tokens
+to refuse cannot catch them: a provider may accept many spellings of one token (the bundled password
+provider decodes base64 leniently, so the quoted cookie value verifies too). So on the gateway's Webapp
+behind the gate a provider token works on its own only when this listener gave it to a native app's
+sign-in (RFC 8252: ``/auth/native/token``, then ``/auth/native/refresh``). The listener keeps a digest of
+each such token until it expires, in ``RECORD_PATH`` under the gateway home (``app.state.webapp_home``),
+so native apps stay signed in across a restart and a sign-out. A browser login's tokens therefore work
+only as that login's cookies and end with it.
"""
from __future__ import annotations
import hashlib
import hmac
+import json
+import logging
+import threading
+import time
+from pathlib import Path
from typing import Optional
from fastapi import Request
from fastapi.responses import Response
_MESSAGE = b"webapp-sign-in"
+_log = logging.getLogger(__name__)
+
+#: Where the gateway home keeps the digests of the provider tokens its listener gave native apps.
+RECORD_PATH = Path("webapp") / "native-sign-in-tokens.json"
+#: How long a refresh token stays recorded. Providers do not say when theirs expire; this is the longest
+#: the bundled providers issue (the password provider's 30 days) and how long a browser keeps one.
+REFRESH_TOKEN_LIFETIME = 30 * 24 * 60 * 60
+
+_records_lock = threading.Lock()
+#: Per gateway home: token digest -> expiry in Unix seconds. Read from the home's file once per
+#: process; this process is its only writer.
+_records: dict[Optional[Path], dict[str, int]] = {}
def binding(token: str) -> str:
@@ -84,3 +111,78 @@ def renew(response: Response, request: Request) -> None:
token = _current_token()
if signed_in is not None and hmac.compare_digest(signed_in, token_digest(token)):
_set(response, request, token)
+
+
+def token_works_alone(request: Request, token: str) -> bool:
+ """Whether provider token *token* may be used on its own (a bearer header, the refresh route) on
+ *request*'s listener: anywhere but the gateway's Webapp behind the gate, as on main; there, only
+ when this listener gave it to a native app's sign-in and it has not expired."""
+ if not applies(request):
+ return True
+ with _records_lock:
+ expires = _loaded(_home(request)).get(_digest(token))
+ return expires is not None and expires > time.time()
+
+
+def gave_native_app(request: Request, session) -> None:
+ """Record that this listener just gave *session*'s tokens to a native app's sign-in, so they work
+ on their own on the gateway's Webapp behind the gate (:func:`token_works_alone`)."""
+ if not applies(request):
+ return
+ now = int(time.time())
+ given = ((session.access_token, int(session.expires_at or 0) or now + REFRESH_TOKEN_LIFETIME),
+ (session.refresh_token, now + REFRESH_TOKEN_LIFETIME))
+ home = _home(request)
+ with _records_lock:
+ records = _loaded(home)
+ for token, expires in given:
+ if token:
+ records[_digest(token)] = expires
+ for key in [key for key, expires in records.items() if expires <= now]:
+ del records[key]
+ if home is not None:
+ _write(home / RECORD_PATH, records)
+
+
+def _digest(token: str) -> str:
+ return hashlib.sha256(token.encode()).hexdigest()
+
+
+def _home(request: Request) -> Optional[Path]:
+ home = getattr(request.app.state, "webapp_home", None)
+ return Path(home) if home is not None else None
+
+
+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."""
+ if home in _records:
+ return _records[home]
+ stored: object = {}
+ if home is not None:
+ try:
+ stored = json.loads((home / RECORD_PATH).read_text(encoding="utf-8-sig"))
+ except FileNotFoundError:
+ pass
+ except (OSError, ValueError) as exc: # native apps sign in again
+ _log.warning("Could not read the Webapp's record of native sign-ins: %s", exc)
+ records = ({key: value for key, value in stored.items() if isinstance(value, int)}
+ if isinstance(stored, dict) else {})
+ _records[home] = records
+ return records
+
+
+def _write(path: Path, records: dict[str, int]) -> None:
+ from utils import atomic_write_text
+
+ try:
+ path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
+ atomic_write_text(path, json.dumps(records, separators=(",", ":")) + "\n", mode=0o600)
+ except OSError as exc: # this process still accepts them; after a restart native apps sign in again
+ _log.warning("Could not save the Webapp's record of native sign-ins: %s", exc)
+
+
+def _reset_for_tests() -> None:
+ """Forget every loaded record, as a new process starts with only the files."""
+ with _records_lock:
+ _records.clear()
diff --git a/tests/gateway/fixtures/webapp_gated_sign_out_peer.py b/tests/gateway/fixtures/webapp_gated_sign_out_peer.py
index dcc74454fba..441bd94799e 100644
--- a/tests/gateway/fixtures/webapp_gated_sign_out_peer.py
+++ b/tests/gateway/fixtures/webapp_gated_sign_out_peer.py
@@ -131,6 +131,13 @@ async def across_sign_out(runner, origin, ask):
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"))
+ # 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"))
+ 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}))
+ report["stolen_refresh_token_after"] = _refusal(
+ await thief.post("/auth/native/refresh", json={"refresh_token": refresh}))
report["sign_in_again_status"] = await sign_in(browser)
report["sessions_after_sign_in_again"] = (await browser.get("/api/sessions")).status_code
return report
diff --git a/tests/gateway/test_webapp_cookie_writes.py b/tests/gateway/test_webapp_cookie_writes.py
index be58f5657db..14289843450 100644
--- a/tests/gateway/test_webapp_cookie_writes.py
+++ b/tests/gateway/test_webapp_cookie_writes.py
@@ -3,11 +3,14 @@
``webapp.host: 0.0.0.0`` gates the gateway's dashboard mount behind dashboard sign-in, and the browser
keeps that sign-in in a cookie. A page on another site, or on another port of the same host, that makes
the browser POST, PUT or DELETE with the cookie is refused before any route runs. The Webapp's own page
-writes normally, and native clients keep working: a bearer token, or Electron's cookie requests, which
-carry no Origin.
+writes normally, and native clients keep working: a bearer token from their own sign-in, or Electron's
+cookie requests, which carry no Origin.
"""
import asyncio
+import base64
+import hashlib
import types
+from urllib.parse import parse_qs, urlsplit
import httpx
@@ -33,11 +36,24 @@ async def _write_statuses(client: httpx.AsyncClient, headers: dict) -> tuple[int
return ticket.status_code, config.status_code, job.status_code
+async def _native_app_token(client: httpx.AsyncClient) -> str:
+ """The access token a native app gets from its own sign-in (RFC 8252) on the Webapp's listener."""
+ verifier = "native-app-verifier-" + "v" * 40
+ challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()
+ started = await client.get("/auth/native/authorize", params={
+ "provider": "stub", "code_challenge": challenge, "code_challenge_method": "S256",
+ "redirect_uri": "http://127.0.0.1:53999/cb", "state": "desk"})
+ callback = parse_qs(urlsplit(started.headers["location"]).query)
+ landed = await client.get("/auth/callback", params={"code": callback["code"][0], "state": callback["state"][0]})
+ code = parse_qs(urlsplit(landed.headers["location"]).query)["code"][0]
+ tokens = await client.post("/auth/native/token", json={"code": code, "code_verifier": verifier})
+ return tokens.json()["access_token"]
+
+
def test_a_wildcard_webapp_takes_cookie_writes_only_from_its_own_page(tmp_path, monkeypatch):
from hermes_cli import web_server
from hermes_cli.config import read_raw_config
from hermes_cli.dashboard_auth import clear_providers, register_provider
- from hermes_cli.dashboard_auth.cookies import SESSION_AT_COOKIE
from hermes_constants import get_hermes_home
from tests.hermes_cli.conftest_dashboard_auth import StubAuthProvider
@@ -59,7 +75,6 @@ def test_a_wildcard_webapp_takes_cookie_writes_only_from_its_own_page(tmp_path,
transport = httpx.ASGITransport(app=mount)
async with httpx.AsyncClient(transport=transport, base_url=WEBAPP) as browser:
await browser.get("/auth/login?provider=stub", follow_redirects=True)
- token = next(v for k, v in browser.cookies.items() if k.endswith(SESSION_AT_COOKIE))
for page in FOREIGN_PAGES:
assert await _write_statuses(browser, page) == (403, 403, 403), page
assert read_raw_config().get("display", {}).get("skin") != "mono"
@@ -73,7 +88,7 @@ def test_a_wildcard_webapp_takes_cookie_writes_only_from_its_own_page(tmp_path,
native_ticket = await browser.post("/api/webapp/gateway-ticket", headers=native)
assert native_ticket.status_code == 200, native_ticket.text
async with httpx.AsyncClient(transport=transport, base_url=WEBAPP) as native_app:
- bearer = {"Authorization": f"Bearer {token}", "Origin": "null"}
+ bearer = {"Authorization": f"Bearer {await _native_app_token(native_app)}", "Origin": "null"}
ticket, config, job = await _write_statuses(native_app, bearer)
assert (ticket, config) == (200, 200)
assert job not in {401, 403}
diff --git a/tests/gateway/test_webapp_gated_sign_out.py b/tests/gateway/test_webapp_gated_sign_out.py
index e6737e1f58a..167a2e31ce9 100644
--- a/tests/gateway/test_webapp_gated_sign_out.py
+++ b/tests/gateway/test_webapp_gated_sign_out.py
@@ -4,8 +4,9 @@ The gateway binds its Webapp on loopback with a public URL, which puts it behind
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.
+in, tickets it minted open nothing, and its cookies replayed elsewhere get nothing, nor do the provider
+tokens they held, presented on their own. The native client stays connected, and the browser can sign
+in again.
"""
import json
from pathlib import Path
@@ -70,5 +71,10 @@ def test_after_sign_out_the_browser_must_sign_in_again(signed_out):
assert signed_out["old_terminal_ticket_after"] == 403
+def test_after_sign_out_the_tokens_the_browsers_cookies_held_work_nowhere(signed_out):
+ assert signed_out["stolen_access_token_after"][:2] == [401, "session_expired"]
+ assert signed_out["stolen_refresh_token_after"][:2] == [401, "session_expired"]
+
+
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
index eb67b236c8c..d390a5ad72a 100644
--- a/tests/hermes_cli/test_webapp_gated_sign_out.py
+++ b/tests/hermes_cli/test_webapp_gated_sign_out.py
@@ -4,8 +4,11 @@ On a LAN or own-URL Webapp a browser signs in with the dashboard's sign-in (a pa
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.
+4401, tickets it minted open nothing, and its cookies replayed from anywhere get nothing. The provider
+tokens those cookies hold work only as those cookies: the Webapp's listener refuses them as a bearer
+token and on the refresh route, before and after sign-out and across a restart. Signing in again works,
+and a native app's own sign-in on the same listener stays signed in. The standalone dashboard has no
+browser credential and keeps its logins as on main.
"""
import json
from types import SimpleNamespace
@@ -25,6 +28,7 @@ USER, PASSWORD = "owner", "throwaway-test-password"
@pytest.fixture
def gated(tmp_path, monkeypatch):
"""The Webapp behind the sign-in gate with a password and an OAuth provider registered."""
+ from hermes_cli import webapp_sign_in
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
@@ -36,7 +40,9 @@ def gated(tmp_path, monkeypatch):
monkeypatch.setattr(state, "bound_host", "hermes.lan")
monkeypatch.setattr(state, "bound_port", 9120, raising=False)
monkeypatch.setattr(state, "auth_required", True)
+ monkeypatch.setattr(state, "webapp_home", tmp_path / ".hermes", raising=False)
_reset_for_tests()
+ webapp_sign_in._reset_for_tests()
_reset_password_rate_limit()
clear_providers()
register_provider(BasicAuthProvider(username=USER, password_hash=hash_password(PASSWORD), secret=b"k" * 32))
@@ -47,6 +53,7 @@ def gated(tmp_path, monkeypatch):
finally:
clear_providers()
_reset_for_tests()
+ webapp_sign_in._reset_for_tests()
_reset_password_rate_limit()
@@ -179,3 +186,193 @@ def test_the_standalone_dashboard_keeps_its_logins_as_on_main(gated, monkeypatch
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
+
+
+# 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
+# out ends them everywhere there; a native app's own sign-in on the same listener stays signed in.
+
+def clock(monkeypatch):
+ """Moves the password provider's clock forward. It signs each token's expiry in whole seconds, so
+ without this a renewal or a second login in the same second gets byte-identical tokens."""
+ import time
+
+ from plugins.dashboard_auth import basic
+
+ offset = [0]
+ monkeypatch.setattr(basic, "time", SimpleNamespace(time=lambda: time.time() + offset[0]))
+
+ def advance(seconds=5):
+ offset[0] += seconds
+ return advance
+
+
+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"))
+
+
+def _bearer(token):
+ return {"Authorization": "Bearer " + token}
+
+
+def _renew(gated, refresh_token):
+ """``/auth/native/refresh`` from a client holding nothing but *refresh_token*."""
+ return gated.browser().post("/auth/native/refresh", json={"refresh_token": refresh_token})
+
+
+def _refused(response):
+ assert (response.status_code, response.json().get("error")) == (401, "session_expired")
+
+
+def _refused_alone(gated, access, refresh):
+ """Neither token works on its own: the access token as a bearer, the refresh token on the
+ refresh route."""
+ stolen = gated.browser()
+ _refused(stolen.get("/api/auth/me", headers=_bearer(access)))
+ _refused(stolen.post("/api/webapp/terminal-ticket", headers=_bearer(access)))
+ _refused(stolen.post("/api/auth/ws-ticket", headers=_bearer(access)))
+ _refused(_renew(gated, refresh))
+
+
+def _restart(gated, monkeypatch, *, token=None):
+ """What a new gateway process starts from: nothing in memory but the files in its home, and the
+ browser credential stored there (*token* when the CLI replaced it while no gateway ran)."""
+ from hermes_cli import webapp_sign_in
+
+ webapp_sign_in._reset_for_tests()
+ if token is not None:
+ monkeypatch.setattr(gated.server, "_SESSION_TOKEN", token)
+
+
[email protected]("sign_in", SIGN_INS)
+def test_after_sign_out_a_logins_tokens_work_nowhere_on_the_webapp(gated, sign_out, sign_in):
+ browser = gated.browser()
+ SIGN_INS[sign_in](browser)
+ access, refresh = _tokens(browser)
+ sign_out()
+ _refused_alone(gated, access, refresh)
+
+
[email protected]("sign_in", SIGN_INS)
+def test_a_logins_tokens_work_only_as_its_cookies(gated, sign_in):
+ """Before any sign-out too: the tokens a browser login holds open nothing without its cookies, in
+ the spelling a copy would take from the browser or from the cookie as stored."""
+ browser = gated.browser()
+ SIGN_INS[sign_in](browser)
+ 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")
+ _refused_alone(gated, *stored)
+
+
+def test_a_pair_renewed_before_sign_out_is_refused_after_it(gated, sign_out, clock):
+ browser = gated.browser()
+ _sign_in_with_password(browser)
+ first = _tokens(browser)
+ # The gate renews the browser's pair once its access token lapses.
+ clock()
+ browser.cookies.delete("hermes_session_at")
+ assert browser.get("/api/auth/me").status_code == 200
+ renewed = _tokens(browser)
+ assert renewed[0] != first[0]
+ # The refresh route renews nothing from a browser login, before sign-out either.
+ _refused(_renew(gated, first[1]))
+ sign_out()
+ _refused_alone(gated, *renewed)
+
+
+def test_the_refusal_survives_a_gateway_restart(gated, sign_out, monkeypatch):
+ browser = gated.browser()
+ _sign_in_with_password(browser)
+ access, refresh = _tokens(browser)
+ sign_out()
+ _restart(gated, monkeypatch)
+ _refused_alone(gated, access, refresh)
+
+
+def test_a_credential_replaced_while_the_gateway_was_down_ends_its_logins_tokens(gated, monkeypatch, tmp_path):
+ from gateway.webapp_listener import browser_session_token
+
+ browser = gated.browser()
+ _sign_in_with_password(browser)
+ access, refresh = _tokens(browser)
+ # The gateway stops, hermes webapp --sign-out replaces the stored credential, a gateway starts.
+ _restart(gated, monkeypatch, token=browser_session_token(tmp_path / ".hermes", rotate=True))
+ _signed_out(browser.get("/api/auth/me"))
+ _refused_alone(gated, access, refresh)
+
+
+def test_a_login_after_sign_out_works(gated, sign_out, clock):
+ browser = gated.browser()
+ _sign_in_with_password(browser)
+ sign_out()
+ clock()
+ _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 _native_app_sign_in(gated):
+ """An RFC 8252 sign-in (the native Desktop's) on the Webapp's listener: authorize in the system
+ browser, then redeem the loopback code for bearer tokens. No cookie login takes part."""
+ import base64
+ import hashlib
+ from urllib.parse import parse_qs, urlsplit
+
+ verifier = "native-app-verifier-" + "v" * 40
+ challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()
+ system_browser = gated.browser()
+ started = system_browser.get("/auth/native/authorize", follow_redirects=False, params={
+ "provider": "stub", "code_challenge": challenge, "code_challenge_method": "S256",
+ "redirect_uri": "http://127.0.0.1:53999/cb", "state": "desk"})
+ callback = parse_qs(urlsplit(started.headers["location"]).query)
+ landed = system_browser.get("/auth/callback", follow_redirects=False,
+ params={"code": callback["code"][0], "state": callback["state"][0]})
+ code = parse_qs(urlsplit(landed.headers["location"]).query)["code"][0]
+ tokens = gated.browser().post("/auth/native/token", json={"code": code, "code_verifier": verifier})
+ assert tokens.status_code == 200
+ return tokens.json()["access_token"], tokens.json()["refresh_token"]
+
+
+def test_a_native_app_signed_in_on_the_webapps_listener_stays_signed_in(gated, sign_out, monkeypatch):
+ """Signing the browsers out leaves a native app's own sign-in alone, across a restart too, and the
+ pair it renews keeps working."""
+ access, refresh = _native_app_sign_in(gated)
+ sign_out()
+ _restart(gated, monkeypatch)
+ assert gated.browser().get("/api/auth/me", headers=_bearer(access)).status_code == 200
+ renewed = _renew(gated, refresh)
+ assert renewed.status_code == 200
+ assert gated.browser().get("/api/auth/me", headers=_bearer(renewed.json()["access_token"])).status_code == 200
+ assert _renew(gated, renewed.json()["refresh_token"]).status_code == 200
+
+
+def test_only_the_spelling_given_to_a_native_app_works(gated):
+ """The providers accept other spellings of a token (the password provider and the test provider
+ decode base64 leniently); the listener takes only the one it gave out."""
+ access, refresh = _native_app_sign_in(gated)
+ _refused_alone(gated, f'"{access}"', f'"{refresh}"')
+
+
+def test_off_the_webapp_any_provider_token_works_on_its_own_as_on_main(gated, monkeypatch):
+ monkeypatch.setattr(gated.server.app.state, "ui_surface", "dashboard")
+ browser = gated.browser()
+ _sign_in_with_password(browser)
+ access, refresh = _tokens(browser)
+ assert gated.browser().get("/api/auth/me", headers=_bearer(access)).status_code == 200
+ assert _renew(gated, refresh).status_code == 200
+
+
+def test_the_record_of_native_sign_ins_is_user_only(gated, tmp_path):
+ from hermes_cli.webapp_sign_in import RECORD_PATH
+
+ _native_app_sign_in(gated)
+ record = tmp_path / ".hermes" / RECORD_PATH
+ assert record.stat().st_mode & 0o777 == 0o600
+ assert record.parent.stat().st_mode & 0o777 == 0o700
diff --git a/tests/hermes_cli/test_webapp_launcher.py b/tests/hermes_cli/test_webapp_launcher.py
index cc1994657ec..476f1ef30bb 100644
--- a/tests/hermes_cli/test_webapp_launcher.py
+++ b/tests/hermes_cli/test_webapp_launcher.py
@@ -199,11 +199,14 @@ def test_sign_out_replaces_the_browser_credential_on_the_running_gateway(world,
def test_sign_out_behind_the_sign_in_gate_says_browsers_must_sign_in_again(world, capsys):
+ """It says exactly what ended: every browser login and the account tokens it held, which work on
+ the Webapp only as that login. Native apps' own sign-ins stay."""
world["answers"]["webapp-sign-out"]["result"] = {
"signed_out": True, "serving": True, "sign_in_gate": True, "connections_closed": 1}
assert launcher.cmd_webapp(_args(sign_out=True)) == 0
out = capsys.readouterr().out
assert "closed 1 browser connection." in out and "must sign in again" in out
+ assert "tokens" in out and "Native apps" in out and "stay signed in" in out
def test_sign_out_on_a_gateway_not_serving_the_webapp_says_no_browser_was_connected(world, capsys):
diff --git a/website/docs/developer-guide/gateway-local-sessions.md b/website/docs/developer-guide/gateway-local-sessions.md
index 4d58a83bb17..1bf29c31a14 100644
--- a/website/docs/developer-guide/gateway-local-sessions.md
+++ b/website/docs/developer-guide/gateway-local-sessions.md
@@ -54,7 +54,11 @@ The server issues `session:operator` only at these existing trusted boundaries:
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
- every socket the token or a bound login opened, Bot Desktop viewers included.
+ 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
+ sign-in (digests kept in `webapp/native-sign-in-tokens.json` in the gateway home until they
+ expire), so native apps stay signed in across a sign-out and a restart.
- The HTTP mutation gate, after a verified dashboard Session, native HTTP owner grant,
or permitted legacy session token has been accepted.
diff --git a/website/docs/reference/cli-commands.md b/website/docs/reference/cli-commands.md
index 99e2ac9cda4..01f103f4416 100644
--- a/website/docs/reference/cli-commands.md
+++ b/website/docs/reference/cli-commands.md
@@ -1958,7 +1958,7 @@ exception: this command builds it, and the running gateway serves it at once.
| `--force-build` | Rebuild the bundle even when its build receipt is current |
| `--build-only` | Build the bundle and stop |
| `--status` | Show whether the running gateway serves the Webapp, and at which address |
-| `--sign-out` | Sign out every browser: tabs a link signed in need a new link, and behind the sign-in gate every login must sign in again. Their connections close and the command reports how many. Waits for a gateway that is still starting; with none running, replaces the stored credential |
+| `--sign-out` | Sign out every browser: tabs a link signed in need a new link, and behind the sign-in gate every login must sign in again; the account tokens those logins held stop working on the Webapp too. Native apps that signed in on their own stay signed in. Their connections close and the command reports how many. Waits for a gateway that is still starting; with none running, replaces the stored credential |
```bash
# Turn it on once, then open it
diff --git a/website/docs/user-guide/desktop.md b/website/docs/user-guide/desktop.md
index 5c0cf3b4028..8b602f383f2 100644
--- a/website/docs/user-guide/desktop.md
+++ b/website/docs/user-guide/desktop.md
@@ -57,7 +57,9 @@ macOS and the BSDs the command prints the gateway's private link instead, for yo
browser in as you until you sign out, so keep it private. `hermes webapp --sign-out` signs out every
tab at once: their open connections close, Bot Desktop viewers included, and each shows the sign-in
instructions. Behind the sign-in gate (below) it also signs out every browser that signed in with a
-dashboard account; each must sign in again.
+dashboard account; each must sign in again. The account tokens such a login keeps in its cookies work
+on the Webapp only as that login (the gateway refuses them as a bearer token and on its token refresh),
+so they end with it. A native Hermes app that signed in to the gateway on its own stays signed in.
For a named profile, `hermes -p work webapp` opens the Webapp on `work`. Profiles the default gateway
serves share its Webapp; a standalone profile's own gateway serves its own when its config turns it on.