Skip to content

The agent that grows with you

fix(webapp): a media or download link minted during sign-out ends with the old credential

emozilla94fdb3402b45
diff --git a/hermes_cli/web_routers/files.py b/hermes_cli/web_routers/files.py
index cff600c4992..e77999243b6 100644
--- a/hermes_cli/web_routers/files.py
+++ b/hermes_cli/web_routers/files.py
@@ -733,6 +733,7 @@ async def issue_file_ticket(payload: FileTicketRequest, request: Request):
query = {"path": payload.path, "profile": payload.profile, "session_id": payload.session_id}
ticket = file_tickets.mint(
payload.route, {key: value for key, value in query.items() if value is not None}, authority=authority,
+ session_token=file_tickets.session_token_of(request),
)
return JSONResponse({"ticket": ticket}, headers={"Cache-Control": "no-store"})
diff --git a/hermes_cli/web_server_file_tickets.py b/hermes_cli/web_server_file_tickets.py
index 31d39abae27..874ab71ccb6 100644
--- a/hermes_cli/web_server_file_tickets.py
+++ b/hermes_cli/web_server_file_tickets.py
@@ -9,11 +9,15 @@ else. A download is one request, so its ticket is single-use; a media element
issues many Range requests for one source, so a stream ticket is reusable until
it expires. Each ticket captures the resolved file and the named profile homes it
belongs to; the resource opener refuses it once one of those homes is missing or
-deleted (``hermes_constants.assert_named_profile_home_live``). In-memory only:
-tickets die with the process, like the token.
+deleted (``hermes_constants.assert_named_profile_home_live``). A ticket minted for
+a request that presented the browser session token redeems only while that token
+is current, like a socket ticket, so signing out ends it even when the sign-out
+lands while the ticket is being minted. In-memory only: tickets die with the
+process, like the token.
"""
from __future__ import annotations
+import hmac
import secrets
import threading
import time
@@ -56,6 +60,10 @@ class _Ticket:
expires_at: float
single_use: bool
authority: FileAuthority
+ #: Digest of the browser session token the minting request presented (None for any other
+ #: credential): the ticket redeems only while that token is current, so a sign-out that lands
+ #: between the request's admission and the mint still ends it.
+ session_token: str | None = None
_lock = threading.Lock()
@@ -66,8 +74,25 @@ def _scope(route_path: str, query: Iterable[tuple[str, str]]) -> _Scope:
return route_path, tuple(sorted(query))
-def mint(route: str, query: Mapping[str, str], *, authority: FileAuthority) -> str:
- """Ticket for GET/HEAD of ``ROUTES[route]`` with exactly ``query`` (plus ``ticket``)."""
+def session_token_of(request: Request) -> str | None:
+ """The browser session token *request* was admitted with on the loopback gate, or None when it
+ came with any other credential (a sign-in, a native client's grant, a service token)."""
+ from hermes_cli.web_server import _SESSION_HEADER_NAME
+
+ if (getattr(request.app.state, "auth_required", False)
+ or getattr(request.state, "native_http_principal", None)
+ or getattr(request.state, "token_authenticated", False)):
+ return None
+ return (request.headers.get(_SESSION_HEADER_NAME)
+ or request.headers.get("authorization", "").removeprefix("Bearer ") or 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
+
route_path = ROUTES[route]
single_use = route == "download"
now = time.monotonic()
@@ -77,6 +102,7 @@ def mint(route: str, query: Mapping[str, str], *, authority: FileAuthority) -> s
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),
)
with _lock:
for stale in [key for key, value in _tickets.items() if value.expires_at <= now]:
@@ -94,7 +120,10 @@ def revoke_all() -> None:
def redeem(request: Request) -> bool:
- """True when ``?ticket=`` authorizes this exact request; consumes a download ticket."""
+ """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
@@ -103,6 +132,9 @@ 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()):
+ del _tickets[ticket]
+ return False
if entry.single_use:
del _tickets[ticket]
# Carry the captured authority through middleware to the resource opener.
diff --git a/hermes_cli/web_session_sockets.py b/hermes_cli/web_session_sockets.py
index dbd0249042f..80b5fa4680a 100644
--- a/hermes_cli/web_session_sockets.py
+++ b/hermes_cli/web_session_sockets.py
@@ -41,7 +41,8 @@ def token_digest(token: str) -> str:
return hashlib.sha256(token.encode()).hexdigest()
-def _current_digest() -> str:
+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)
@@ -57,7 +58,7 @@ def ticket_refusal(info: dict[str, Any], socket: Optional[str], *, auth_required
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())):
+ 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"
return None
@@ -78,7 +79,7 @@ def track(ws, admitted_with: str) -> None:
for key in [key for key, (ref, _loop) in _live.items() if ref() is None]:
del _live[key]
_live[id(ws)] = (weakref.ref(ws), loop)
- if not hmac.compare_digest(admitted_with, _current_digest()):
+ if not hmac.compare_digest(admitted_with, current_digest()):
_close_on(ws, loop)
diff --git a/tests/hermes_cli/test_webapp_sign_out_sockets.py b/tests/hermes_cli/test_webapp_sign_out_sockets.py
index 8b7cdc11995..8b9711ab84a 100644
--- a/tests/hermes_cli/test_webapp_sign_out_sockets.py
+++ b/tests/hermes_cli/test_webapp_sign_out_sockets.py
@@ -103,6 +103,30 @@ def test_signing_out_ends_the_media_links_the_session_token_minted(webapp, sign_
assert client.get("/api/files/stream", params=stream).status_code == 401
+def test_a_media_link_minted_while_signing_out_streams_nothing(webapp, sign_out, tmp_path, monkeypatch):
+ """The request asking for the link was admitted with the old credential, and the sign-out
+ finished before the link was stored: the link ends with the credential that asked for it."""
+ from hermes_cli import web_server_file_tickets
+
+ client = webapp.client
+ root = tmp_path / "files"
+ root.mkdir()
+ (root / "clip.mp4").write_bytes(b"hello")
+ monkeypatch.setenv("HERMES_DASHBOARD_FILES_ROOT", str(root))
+ mint = web_server_file_tickets.mint
+
+ def mint_after_sign_out(*args, **kwargs):
+ sign_out()
+ return mint(*args, **kwargs)
+
+ monkeypatch.setattr(web_server_file_tickets, "mint", mint_after_sign_out)
+ minted = client.post("/api/files/ticket", json={"route": "stream", "path": str(root / "clip.mp4")},
+ headers={"X-Hermes-Session-Token": _TOKEN})
+ assert minted.status_code == 200, minted.text
+ stream = {"path": str(root / "clip.mp4"), "ticket": minted.json()["ticket"]}
+ assert client.get("/api/files/stream", params=stream).status_code == 401
+
+
def test_a_socket_admitted_while_the_token_is_replaced_closes_at_once(monkeypatch):
"""The gate checked the old token, then sign-out replaced it and closed the sockets it knew of
before this one was tracked: tracking it closes it."""