Skip to content

The agent that grows with you

refactor(webapp): one module owns the browser credential and ends every grant at sign-out

emozilla0a4b903c52d2
diff --git a/gateway/webapp_listener.py b/gateway/webapp_listener.py
index 686d1c8b46e..de42576ec3f 100644
--- a/gateway/webapp_listener.py
+++ b/gateway/webapp_listener.py
@@ -346,23 +346,22 @@ def register_control_verbs(runner, home) -> None:
"expires_in_seconds": LAUNCH_TICKET_TTL_SECONDS}
def webapp_sign_out(_params, _peer):
- from hermes_cli import web_server_file_tickets, web_session_sockets
+ from hermes_cli import browser_credential
if runner.webapp_status["state"] != "serving":
# No browser reaches this gateway's Webapp and it holds no browser credential: replacing
# the stored one is the whole sign-out, and the next start serves the new one.
browser_session_token(home, rotate=True)
return {"signed_out": True, "serving": False, "sign_in_gate": False, "connections_closed": 0}
_, 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. 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()
+ # Every tab loses access at once: every grant made under the old credential ends, and the
+ # sockets and media links it opened end 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.
+ ended = browser_credential.rotate(browser_session_token(home, rotate=True))
return {"signed_out": True, "serving": True,
"sign_in_gate": bool(getattr(web.app.state, "auth_required", False)),
- "connections_closed": closed}
+ "connections_closed": ended.get("sockets", 0)}
server.private_handlers.update({
"webapp-status": webapp_status, "webapp-launch": webapp_launch, "webapp-sign-out": webapp_sign_out})
diff --git a/hermes_cli/browser_credential.py b/hermes_cli/browser_credential.py
new file mode 100644
index 00000000000..70abaa0178b
--- /dev/null
+++ b/hermes_cli/browser_credential.py
@@ -0,0 +1,67 @@
+"""The browser credential, and how every grant made under it ends when it is replaced.
+
+The browser credential is the dashboard session token (``hermes_cli.web_server._SESSION_TOKEN``). A
+loopback Webapp tab holds it; behind the sign-in gate each Webapp login is bound to it
+(``hermes_cli.webapp_sign_in``). The gateway keeps the Webapp's credential in its home
+(``gateway.webapp_listener.browser_session_token``) and sets it when its listener starts.
+
+Every grant a browser gets under the credential records the credential's generation, a SHA-256 digest
+of it, when the grant is made, and is honoured only while :func:`is_current` says that generation is
+still the one in use: window and launch tickets (``web_routers.webapp``), socket tickets
+(``web_session_sockets.ticket_refusal``), Bot Desktop viewer tickets (``web_routers.display``), file
+tickets (``web_server_file_tickets``), open sockets (``web_session_sockets.track``) and a cookie
+login's binding (``webapp_sign_in.check``). Stores keep the generation, never the credential.
+
+:func:`rotate` (``hermes webapp --sign-out``) replaces the credential, then runs every revoker
+registered with :func:`on_rotate`: grants that stay in use without being presented again (open
+sockets) end at once, and stores drop what can no longer be redeemed.
+"""
+from __future__ import annotations
+
+import hashlib
+import hmac
+import threading
+from typing import Callable, Optional
+
+_lock = threading.Lock()
+#: Revoker name -> callable that ends the grants made under a replaced credential and returns how
+#: many it ended.
+_revokers: dict[str, Callable[[], int]] = {}
+
+
+def current() -> str:
+ """The browser credential in use now."""
+ from hermes_cli import web_server
+ return web_server._SESSION_TOKEN
+
+
+def generation_of(credential: str) -> str:
+ """The generation a grant made under *credential* records."""
+ return hashlib.sha256(credential.encode()).hexdigest()
+
+
+def generation() -> str:
+ """The generation of the credential in use now."""
+ return generation_of(current())
+
+
+def is_current(recorded: Optional[str]) -> bool:
+ """Whether a grant that recorded generation *recorded* was made under the credential in use now."""
+ return recorded is not None and hmac.compare_digest(recorded, generation())
+
+
+def on_rotate(name: str, revoker: Callable[[], int]) -> None:
+ """Run *revoker* each time the credential is replaced; registering a name again replaces it."""
+ with _lock:
+ _revokers[name] = revoker
+
+
+def rotate(credential: str) -> dict[str, int]:
+ """Make *credential* the browser credential and end every grant made under the one it replaces.
+ Returns how many grants each registered revoker ended, by name. Safe from any thread."""
+ from hermes_cli import web_server
+
+ web_server._SESSION_TOKEN = credential
+ with _lock:
+ revokers = dict(_revokers)
+ return {name: revoker() for name, revoker in revokers.items()}
diff --git a/hermes_cli/web_routers/display.py b/hermes_cli/web_routers/display.py
index 9d29cfffbcd..054fa77347e 100644
--- a/hermes_cli/web_routers/display.py
+++ b/hermes_cli/web_routers/display.py
@@ -95,16 +95,16 @@ async def display_ws(ws: WebSocket) -> None:
def _signed_out(ws: WebSocket, info: dict) -> bool:
- """True when the browser tab that asked for this viewer has signed out since; otherwise the
- viewer is tracked with that tab's sockets, so signing out closes it too. A ticket a native
- client minted carries no browser credential and is left alone."""
- import hmac
-
- from hermes_cli.web_session_sockets import current_digest, track
+ """True when the browser tab that asked for this viewer has signed out since (the ticket's
+ browser credential generation is no longer current); otherwise the viewer is tracked with that
+ tab's sockets, so signing out closes it too. A ticket a native client minted carries no browser
+ credential and is left alone."""
+ from hermes_cli.browser_credential import is_current
+ from hermes_cli.web_session_sockets import track
admitted = info.get("admitted_with")
if admitted is None:
return False
- if not hmac.compare_digest(admitted, current_digest()):
+ if not is_current(admitted):
return True
track(ws, admitted)
return False
diff --git a/hermes_cli/web_routers/webapp.py b/hermes_cli/web_routers/webapp.py
index 6a16110afaf..52e63115624 100644
--- a/hermes_cli/web_routers/webapp.py
+++ b/hermes_cli/web_routers/webapp.py
@@ -179,16 +179,17 @@ def mint_socket_ticket(identity: dict, socket: str, *, session_token: str | None
sign_in: str | None = None, profile_home: str | None = None) -> str:
"""A one-use ticket that opens only *socket* (``web_session_sockets.GATEWAY_SOCKET``,
``HOST_TERMINAL_SOCKET`` or one of ``AUDIO_SOCKETS``) 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. With *profile_home* the
- socket it opens answers for that profile (``chat_ws.gateway_ws``)."""
+ *session_token*, or by a login whose sign-in binding was checked against the browser credential
+ of generation *sign_in* (``hermes_cli.webapp_sign_in``), it records that credential's generation
+ (``hermes_cli.browser_credential``): it opens nothing once that credential is replaced, and the
+ socket it opens closes when the browser signs out. With *profile_home* the socket it opens answers
+ for that profile (``chat_ws.gateway_ws``)."""
+ from hermes_cli.browser_credential import generation_of
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)
+ extra["session_token"] = generation_of(session_token)
if sign_in is not None:
extra["sign_in"] = sign_in
if profile_home is not None:
diff --git a/hermes_cli/web_server_chat.py b/hermes_cli/web_server_chat.py
index 04e81b109ea..a81db2c5f6e 100644
--- a/hermes_cli/web_server_chat.py
+++ b/hermes_cli/web_server_chat.py
@@ -235,7 +235,8 @@ def _ws_auth_reason(ws: WebSocket, *, allow_internal: bool = False,
"""
from hermes_cli.dashboard_auth.native_http import HEADER, authenticate_native_ws
from hermes_cli.web_server import _SESSION_TOKEN, app
- from hermes_cli.web_session_sockets import OWN_TICKET_SOCKETS, token_digest, track
+ from hermes_cli.browser_credential import generation_of
+ from hermes_cli.web_session_sockets import OWN_TICKET_SOCKETS, track
auth_required = bool(getattr(app.state, "auth_required", False))
if socket in OWN_TICKET_SOCKETS:
# No standing credential (the session token, a native grant, a login's access token) opens it.
@@ -345,7 +346,7 @@ def _ws_auth_reason(ws: WebSocket, *, allow_internal: bool = False,
if not token:
return "no_credential", "none"
if hmac.compare_digest(token.encode(), _SESSION_TOKEN.encode()):
- track(ws, token_digest(token))
+ track(ws, generation_of(token))
return None, "token"
return "token_mismatch", "token"
diff --git a/hermes_cli/web_server_file_tickets.py b/hermes_cli/web_server_file_tickets.py
index ad6183f5c6b..f9613b890e5 100644
--- a/hermes_cli/web_server_file_tickets.py
+++ b/hermes_cli/web_server_file_tickets.py
@@ -18,7 +18,6 @@ process, like the token.
"""
from __future__ import annotations
-import hmac
import secrets
import threading
import time
@@ -26,6 +25,8 @@ from dataclasses import dataclass
from pathlib import Path, PurePath
from typing import TYPE_CHECKING, Any, Iterable, Mapping
+from hermes_cli import browser_credential
+
if TYPE_CHECKING:
from starlette.requests import Request
@@ -96,9 +97,8 @@ def session_token_of(request: Request) -> str | None:
def mint(route: str, query: Mapping[str, str], *, authority: FileAuthority,
session_token: str | None = None) -> str:
"""Ticket for GET/HEAD of ``ROUTES[route]`` with exactly ``query`` (plus ``ticket``); minted for
- a request admitted with *session_token*, it redeems only while that token is current."""
- from hermes_cli.web_session_sockets import token_digest
-
+ a request admitted with *session_token*, it records that browser credential's generation and
+ redeems only while it is current."""
route_path = ROUTES[route]
single_use = route == "download"
now = time.monotonic()
@@ -108,7 +108,7 @@ def mint(route: str, query: Mapping[str, str], *, authority: FileAuthority,
expires_at=now + (DOWNLOAD_TTL_SECONDS if single_use else STREAM_TTL_SECONDS),
single_use=single_use,
authority=authority,
- session_token=None if session_token is None else token_digest(session_token),
+ session_token=None if session_token is None else browser_credential.generation_of(session_token),
)
with _lock:
for stale in [key for key, value in _tickets.items() if value.expires_at <= now]:
@@ -119,17 +119,18 @@ def mint(route: str, query: Mapping[str, str], *, authority: FileAuthority,
return ticket
-def revoke_all() -> None:
- """Drop every ticket: the session token that authorized them was replaced (sign-out)."""
+def revoke_all() -> int:
+ """Drop every ticket: the session token that authorized them was replaced (sign-out). Returns
+ how many were dropped."""
with _lock:
+ dropped = len(_tickets)
_tickets.clear()
+ return dropped
def redeem(request: Request) -> bool:
"""True when ``?ticket=`` authorizes this exact request; consumes a download ticket. A ticket
minted with a session token that has since been replaced is dropped instead."""
- from hermes_cli.web_session_sockets import current_digest
-
ticket = request.query_params.get("ticket", "")
if not ticket or request.method not in ("GET", "HEAD"):
return False
@@ -138,7 +139,7 @@ def redeem(request: Request) -> bool:
entry = _tickets.get(ticket)
if entry is None or entry.scope != scope or entry.expires_at <= time.monotonic():
return False
- if entry.session_token is not None and not hmac.compare_digest(entry.session_token, current_digest()):
+ if entry.session_token is not None and not browser_credential.is_current(entry.session_token):
del _tickets[ticket]
return False
if entry.single_use:
@@ -147,3 +148,6 @@ def redeem(request: Request) -> bool:
# A middleware-only check would race deletion before FileResponse opens it.
request.state.file_ticket_authority = entry.authority
return True
+
+
+browser_credential.on_rotate("file tickets", revoke_all)
diff --git a/hermes_cli/web_session_sockets.py b/hermes_cli/web_session_sockets.py
index 5370904e55c..84555cc4256 100644
--- a/hermes_cli/web_session_sockets.py
+++ b/hermes_cli/web_session_sockets.py
@@ -4,24 +4,23 @@ A browser on the loopback Webapp never puts the session token in a socket URL. A
request mints a one-use ticket for one socket instead: ``GATEWAY_SOCKET`` (``/api/ws``),
``HOST_TERMINAL_SOCKET`` (``/api/host-terminal``) or one of ``AUDIO_SOCKETS`` (the voice streams). A
ticket named for one socket opens no other, and 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 native client's grant, a dashboard login off the
-Webapp, a provider token presented directly) are never tracked.
+ticket minted with the session token records that browser credential's generation
+(``hermes_cli.browser_credential``) as ``session_token`` and opens nothing once the credential is
+replaced, nor behind the sign-in gate.
+
+Behind the sign-in gate the Webapp's browsers sign in instead, and each login is bound to the browser
+credential (``hermes_cli.webapp_sign_in``): a ticket such a login mints records the credential's
+generation as ``sign_in`` and likewise opens nothing once it is replaced.
+
+Every socket the browser credential admits, directly or through such a ticket, is tracked here under
+that generation until it ends; ``close_all``, which ``browser_credential.rotate`` runs when ``hermes
+webapp --sign-out`` replaces the credential, closes them all at once. Sockets admitted on any other
+credential (a native client's grant or sign-in, a dashboard login off the Webapp) are never tracked.
"""
from __future__ import annotations
import asyncio
import contextlib
-import hashlib
-import hmac
import logging
import threading
import weakref
@@ -29,6 +28,8 @@ from typing import Any, Optional
from starlette.websockets import WebSocketDisconnect
+from hermes_cli import browser_credential
+
_log = logging.getLogger(__name__)
GATEWAY_SOCKET = "gateway"
@@ -46,47 +47,36 @@ _lock = threading.Lock()
_live: dict[int, tuple[weakref.ref, asyncio.AbstractEventLoop, str]] = {}
-def token_digest(token: str) -> str:
- return hashlib.sha256(token.encode()).hexdigest()
-
-
-def current_digest() -> str:
- """Digest of the browser session token in use now."""
- from hermes_cli.web_server import _SESSION_TOKEN
- return token_digest(_SESSION_TOKEN)
-
-
def ticket_refusal(info: dict[str, Any], socket: Optional[str], *, auth_required: bool) -> Optional[str]:
"""Why a redeemed ticket may not open *socket*, or None when it may.
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; one minted by a Webapp login opens nothing
- once the token that login was bound to is replaced.
+ one that takes only its own ticket. A ticket minted under the browser credential (with the
+ session token, or by a Webapp login bound to it) opens nothing once that credential is replaced,
+ and one minted with the session token opens nothing behind the sign-in gate.
"""
named = info.get("socket")
if named != socket and (named is not None or socket in OWN_TICKET_SOCKETS):
return f"ticket for {named or 'any socket'} presented to {socket or 'an unnamed socket'}"
- 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"
+ granted = admitted_with(info)
+ if granted is not None and not browser_credential.is_current(granted):
+ return "ticket minted under a browser credential that has since been replaced"
+ if auth_required and info.get("session_token") is not None:
+ return "ticket minted with the session token, which opens nothing behind the sign-in gate"
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."""
+ """The browser credential generation a redeemed ticket was minted under, which its socket is
+ tracked under; 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.
+ """Keep *ws*, admitted under the browser credential generation *admitted_with*, until it ends.
- A socket admitted while that token was being replaced closes at once, so ``close_all`` never
- misses one.
+ A socket admitted while that credential was being replaced closes at once, so ``close_all``
+ never misses one.
"""
try:
loop = asyncio.get_running_loop()
@@ -98,13 +88,14 @@ def track(ws, admitted_with: str) -> None:
for key in [key for key, (ref, *_rest) in _live.items() if ref() is None]:
del _live[key]
_live[id(ws)] = (weakref.ref(ws), loop, admitted_with)
- if not hmac.compare_digest(admitted_with, current_digest()):
+ if not browser_credential.is_current(admitted_with):
_close_on(ws, loop)
def admission_of(ws) -> Optional[str]:
- """The digest live socket *ws* was tracked under, or None when signing out does not close it.
- A socket it opens on the browser's behalf (a screen viewer) is tracked under the same one."""
+ """The browser credential generation live socket *ws* was tracked under, or None when signing
+ out does not close it. A socket it opens on the browser's behalf (a screen viewer) records the
+ same one."""
with _lock:
entry = _live.get(id(ws))
return entry[2] if entry is not None and entry[0]() is ws else None
@@ -124,12 +115,15 @@ def _close_on(ws, loop: asyncio.AbstractEventLoop) -> bool:
def close_all() -> int:
- """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."""
+ """Close every live socket the browser credential 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()
closing = sum(_close_on(ws, loop) for ref, loop, _digest in live if (ws := ref()) is not None)
- _log.info("Closing %d browser sockets opened with the replaced session token", closing)
+ _log.info("Closing %d browser sockets opened with the replaced browser credential", closing)
return closing
+
+
+browser_credential.on_rotate("sockets", close_all)
diff --git a/hermes_cli/webapp_sign_in.py b/hermes_cli/webapp_sign_in.py
index 27d4648b6c0..236ad42e287 100644
--- a/hermes_cli/webapp_sign_in.py
+++ b/hermes_cli/webapp_sign_in.py
@@ -10,10 +10,11 @@ a cookie session without a matching value as signed out. Replacing that token (`
--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.
+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
+carry that generation, 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``, a socket's ``?token=``, ``/auth/native/refresh``) they would skip the
@@ -39,6 +40,8 @@ from typing import Optional
from fastapi import Request
from fastapi.responses import Response
+from hermes_cli import browser_credential
+
_MESSAGE = b"webapp-sign-in"
_log = logging.getLogger(__name__)
@@ -65,28 +68,22 @@ def applies(request: Request) -> bool:
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``."""
+ is, records that credential's generation 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()
+ token = browser_credential.current()
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)
+ request.state.webapp_sign_in = browser_credential.generation_of(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)."""
+ """The browser credential generation *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)
@@ -101,17 +98,17 @@ def _set(response: Response, request: Request, token: str) -> None:
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())
+ _set(response, request, browser_credential.current())
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
-
+ # One read of the credential: binding the login to a second read could bind it to a credential
+ # that replaced the one it was checked against.
+ token = browser_credential.current()
signed_in = sign_in_of(request)
- token = _current_token()
- if signed_in is not None and hmac.compare_digest(signed_in, token_digest(token)):
+ if signed_in is not None and hmac.compare_digest(signed_in, browser_credential.generation_of(token)):
_set(response, request, token)
diff --git a/tests/hermes_cli/test_browser_credential.py b/tests/hermes_cli/test_browser_credential.py
new file mode 100644
index 00000000000..8520876d0c0
--- /dev/null
+++ b/tests/hermes_cli/test_browser_credential.py
@@ -0,0 +1,39 @@
+"""The browser credential has one generation check and one rotation that ends every grant.
+
+Every grant made under the Webapp's browser credential records the credential's generation and is
+honoured only while ``is_current`` says it is the one in use; ``rotate`` (``hermes webapp
+--sign-out``) replaces the credential and runs every revoker registered with ``on_rotate``. The
+grant kinds themselves are pinned in test_webapp_sign_out_sockets.py and test_webapp_gated_sign_out.py.
+"""
+from hermes_cli import browser_credential, web_server
+
+
+def test_a_generation_is_current_only_while_its_credential_is_in_use(monkeypatch):
+ monkeypatch.setattr(web_server, "_SESSION_TOKEN", "a" * 43)
+ recorded = browser_credential.generation()
+ assert recorded == browser_credential.generation_of("a" * 43) != "a" * 43
+ assert browser_credential.is_current(recorded)
+ assert not browser_credential.is_current(None)
+ monkeypatch.setattr(web_server, "_SESSION_TOKEN", "b" * 43)
+ assert not browser_credential.is_current(recorded)
+
+
+def test_rotate_replaces_the_credential_then_runs_every_revoker(monkeypatch):
+ """Each revoker runs after the replacement, so it sees the old generation as no longer current,
+ and the rotation reports how many grants each one ended."""
+ monkeypatch.setattr(web_server, "_SESSION_TOKEN", "a" * 43)
+ monkeypatch.setattr(browser_credential, "_revokers", {})
+ old = browser_credential.generation()
+ seen = []
+
+ def revoker(count):
+ def run():
+ seen.append(browser_credential.is_current(old))
+ return count
+ return run
+
+ browser_credential.on_rotate("sockets", revoker(2))
+ browser_credential.on_rotate("file tickets", revoker(0))
+ assert browser_credential.rotate("b" * 43) == {"sockets": 2, "file tickets": 0}
+ assert web_server._SESSION_TOKEN == browser_credential.current() == "b" * 43
+ assert seen == [False, False]
diff --git a/tests/hermes_cli/test_display_ws_ticket.py b/tests/hermes_cli/test_display_ws_ticket.py
index e055b7ef5b9..6e4662fe47f 100644
--- a/tests/hermes_cli/test_display_ws_ticket.py
+++ b/tests/hermes_cli/test_display_ws_ticket.py
@@ -92,12 +92,12 @@ def test_signing_out_closes_a_screen_viewer_a_browser_tab_opened(monkeypatch):
"""A viewer opened from a signed-in tab watches, and while it holds the lease drives, the agent's
screen: it closes with the tab's other sockets when the browser signs out. A viewer a native
client opened (no browser credential on its ticket) stays."""
- from hermes_cli import web_server, web_session_sockets
+ from hermes_cli import browser_credential, web_server, web_session_sockets
from tests.hermes_cli.test_webapp_sign_out_sockets import _close_code
ws_tickets._reset_for_tests()
client = _viewer_app(monkeypatch)
- tab = _viewer_ticket(admitted_with=web_session_sockets.token_digest("a" * 43))
+ tab = _viewer_ticket(admitted_with=browser_credential.generation_of("a" * 43))
native = _viewer_ticket()
with client.websocket_connect(f"/api/display/ws?display_ticket={tab}") as from_tab, \
client.websocket_connect(f"/api/display/ws?display_ticket={native}") as from_native:
@@ -109,12 +109,12 @@ def test_signing_out_closes_a_screen_viewer_a_browser_tab_opened(monkeypatch):
def test_a_screen_viewer_ticket_from_a_signed_out_tab_opens_nothing(monkeypatch):
- from hermes_cli import web_server, web_session_sockets
+ from hermes_cli import browser_credential, web_server
from tests.hermes_cli.test_webapp_sign_out_sockets import _close_code
ws_tickets._reset_for_tests()
client = _viewer_app(monkeypatch)
- stale = _viewer_ticket(admitted_with=web_session_sockets.token_digest("a" * 43))
+ stale = _viewer_ticket(admitted_with=browser_credential.generation_of("a" * 43))
monkeypatch.setattr(web_server, "_SESSION_TOKEN", "b" * 43)
with client.websocket_connect(f"/api/display/ws?display_ticket={stale}") as conn:
assert _close_code(conn, 2.0) == 4401
diff --git a/tests/hermes_cli/test_webapp_sign_out_sockets.py b/tests/hermes_cli/test_webapp_sign_out_sockets.py
index de64215f883..9baee53e8dd 100644
--- a/tests/hermes_cli/test_webapp_sign_out_sockets.py
+++ b/tests/hermes_cli/test_webapp_sign_out_sockets.py
@@ -132,7 +132,7 @@ def test_a_socket_admitted_while_the_token_is_replaced_closes_at_once(monkeypatc
before this one was tracked: tracking it closes it."""
import asyncio
- from hermes_cli import web_server, web_session_sockets
+ from hermes_cli import browser_credential, web_server, web_session_sockets
closed = []
@@ -146,7 +146,7 @@ def test_a_socket_admitted_while_the_token_is_replaced_closes_at_once(monkeypatc
async def admit():
socket = Socket()
- web_session_sockets.track(socket, web_session_sockets.token_digest(_TOKEN))
+ web_session_sockets.track(socket, browser_credential.generation_of(_TOKEN))
await asyncio.wait_for(socket.ended.wait(), timeout=5)
monkeypatch.setattr(web_server, "_SESSION_TOKEN", "b" * 43)
diff --git a/tests/tui_gateway/test_display_methods.py b/tests/tui_gateway/test_display_methods.py
index 467327e6f25..b64ebca4a2a 100644
--- a/tests/tui_gateway/test_display_methods.py
+++ b/tests/tui_gateway/test_display_methods.py
@@ -90,13 +90,13 @@ def test_a_viewer_opened_from_a_browser_tab_signs_out_with_that_tab(monkeypatch,
so /api/display/ws closes the viewer when that browser signs out; a native client's carries none."""
import asyncio
- from hermes_cli import web_server, web_session_sockets
+ from hermes_cli import browser_credential, web_server, web_session_sockets
from tools.bot_desktop import runtime
from tui_gateway import server
monkeypatch.setattr(runtime, "rfb_socket_path", lambda: tmp_path / "rfb.sock")
monkeypatch.setattr(web_server, "_SESSION_TOKEN", "a" * 43)
- signed_in = web_session_sockets.token_digest("a" * 43)
+ signed_in = browser_credential.generation_of("a" * 43)
class _Socket:
async def close(self, code=1000, reason=""):