Skip to content

The agent that grows with you

fix(webapp): let a download retry redeem its ticket again

Adolaniuma3848f78e8dc
diff --git a/hermes_cli/web_server_file_tickets.py b/hermes_cli/web_server_file_tickets.py
index b1dea079937..52f85e0daea 100644
--- a/hermes_cli/web_server_file_tickets.py
+++ b/hermes_cli/web_server_file_tickets.py
@@ -5,11 +5,14 @@ header, and the session token grants host shells and file access, so it must
never appear in a URL the browser records (download history, "Copy video
address"). An authenticated ``POST /api/files/ticket`` mints a ticket that lets
the loopback token gate admit GET/HEAD of exactly one route + query and nothing
-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 (on the profile's SSH workspace
-when it has one, as for native Desktop's download) and the named profile homes it
-belongs to; the resource opener refuses it once one of those homes is missing or
+else. A browser retries a failed or cancelled download by requesting that same
+URL again, so a download ticket allows a few redemptions of that exact request
+and then dies, still inside its short TTL. It is not a reusable credential. 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 (on the
+profile's SSH workspace when it has one, as for native Desktop's download) 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``). A ticket minted for
a request that presented the browser session token records that credential's
generation (``hermes_cli.browser_credential``) and redeems only while it is
@@ -23,7 +26,7 @@ from __future__ import annotations
import secrets
import threading
import time
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
from pathlib import Path, PurePath
from typing import TYPE_CHECKING, Any, Iterable, Mapping
@@ -33,6 +36,10 @@ if TYPE_CHECKING:
from starlette.requests import Request
DOWNLOAD_TTL_SECONDS = 60
+#: The original GET, the browser's restart after it cancels that request, and
+#: one retry of a failed or cancelled download. Past this the ticket is spent
+#: even though the download TTL has not elapsed.
+DOWNLOAD_MAX_REDEMPTIONS = 3
#: A transcript video may be played long after it mounted; seeking past the
#: buffered range needs the ticket again.
STREAM_TTL_SECONDS = 60 * 60
@@ -74,6 +81,8 @@ class _Ticket:
#: while it is current, so a sign-out that lands between the request's admission and the mint
#: still ends it.
generation: str | None = None
+ #: Download tickets only. Stream tickets stay until expiry and ignore this.
+ uses_remaining: int = 0
_lock = threading.Lock()
@@ -112,6 +121,7 @@ def mint(route: str, query: Mapping[str, str], *, authority: FileAuthority,
single_use=single_use,
authority=authority,
generation=None if session_token is None else browser_credential.generation_of(session_token),
+ uses_remaining=DOWNLOAD_MAX_REDEMPTIONS if single_use else 0,
)
with _lock:
for stale in [key for key, value in _tickets.items() if value.expires_at <= now]:
@@ -133,9 +143,21 @@ def revoke_replaced() -> int:
return len(replaced)
+def _spend_download(ticket: str, entry: _Ticket) -> None:
+ """Count one same-URL redemption. Caller holds ``_lock``. Stream tickets are not spent."""
+ if not entry.single_use:
+ return
+ remaining = entry.uses_remaining - 1
+ if remaining > 0:
+ _tickets[ticket] = replace(entry, uses_remaining=remaining)
+ else:
+ del _tickets[ticket]
+
+
def redeem(request: Request) -> bool:
- """True when ``?ticket=`` authorizes this exact request; consumes a download ticket. A ticket
- minted under a browser credential that has since been replaced is dropped instead."""
+ """True when ``?ticket=`` authorizes this exact request. A download ticket grants only a few
+ redemptions of that same URL; a stream ticket lasts until it expires. A ticket minted under a
+ browser credential that has since been replaced is dropped instead."""
ticket = request.query_params.get("ticket", "")
if not ticket or request.method not in ("GET", "HEAD"):
return False
@@ -147,8 +169,7 @@ def redeem(request: Request) -> bool:
if entry.generation is not None and not browser_credential.is_current(entry.generation):
del _tickets[ticket]
return False
- if entry.single_use:
- del _tickets[ticket]
+ _spend_download(ticket, entry)
# Carry the captured authority through middleware to the resource opener.
# A middleware-only check would race deletion before FileResponse opens it.
request.state.file_ticket_authority = entry.authority
diff --git a/tests/hermes_cli/test_web_server_file_ticket_generations.py b/tests/hermes_cli/test_web_server_file_ticket_generations.py
index 439be7e4404..16a4de53945 100644
--- a/tests/hermes_cli/test_web_server_file_ticket_generations.py
+++ b/tests/hermes_cli/test_web_server_file_ticket_generations.py
@@ -125,6 +125,10 @@ def test_http_tickets_die_with_their_profile_or_session_owner(file_server, scope
assert (response.status_code, response.content) == (206, b"old")
assert response.headers["content-range"] == "bytes 0-2/14"
if route == "download":
+ for _ in range(web_server_file_tickets.DOWNLOAD_MAX_REDEMPTIONS - 1):
+ again = client.get(endpoint, params=params)
+ assert again.status_code == 200, again.text
+ assert again.content == b"old-generation"
assert client.get(endpoint, params=params).status_code == 401
params = _ticket(client, route, query)
else:
diff --git a/tests/hermes_cli/test_web_server_file_ticket_retries.py b/tests/hermes_cli/test_web_server_file_ticket_retries.py
new file mode 100644
index 00000000000..d488a448017
--- /dev/null
+++ b/tests/hermes_cli/test_web_server_file_ticket_retries.py
@@ -0,0 +1,119 @@
+"""A browser retry of the same download URL redeems that ticket again, a few times.
+
+The download is fetched once, and the browser repeats that exact URL when the
+download fails or is cancelled. Those retries succeed inside the download TTL.
+The ticket is not a reusable credential: a different path, query, or method is
+refused without spending a retry, an expired ticket is refused, and signing out
+drops one minted under the replaced browser credential. Stream tickets stay
+reusable until they expire.
+"""
+
+import time
+
+import pytest
+from starlette.testclient import TestClient
+
+from hermes_cli import browser_credential, web_server, web_server_file_tickets
+
+
+def browser_download(monkeypatch, tmp_path):
+ root = tmp_path / "files"
+ root.mkdir()
+ clip = root / "clip.mp4"
+ clip.write_bytes(b"hello")
+ monkeypatch.setenv("HERMES_DASHBOARD_FILES_ROOT", str(root))
+ for key, value in (
+ ("auth_required", False),
+ ("bound_host", None),
+ ("ui_surface", "webapp"),
+ ):
+ monkeypatch.setattr(web_server.app.state, key, value, raising=False)
+ client = TestClient(web_server.app)
+ client.headers[web_server._SESSION_HEADER_NAME] = web_server._SESSION_TOKEN
+ browser = TestClient(web_server.app)
+ try:
+ yield client, browser, clip
+ finally:
+ browser.close()
+ client.close()
+
+
+def _mint(client, route, **query):
+ minted = client.post("/api/files/ticket", json={"route": route, **query})
+ assert minted.status_code == 200, minted.text
+ return {**query, "ticket": minted.json()["ticket"]}
+
+
+def test_the_same_download_url_can_be_retried_a_few_times_then_dies(browser_download):
+ client, browser, clip = browser_download
+ route = web_server_file_tickets.ROUTES["download"]
+ params = _mint(client, "download", path=str(clip))
+ # A handful of browser retries, not a credential that lasts for the TTL.
+ assert 1 < web_server_file_tickets.DOWNLOAD_MAX_REDEMPTIONS <= 5
+
+ assert browser.get(route, params=params).content == b"hello"
+ assert (
+ browser.get(route, params={**params, "path": str(clip) + ".other"}).status_code
+ == 401
+ )
+ assert browser.get(route, params={**params, "profile": "other"}).status_code == 401
+ assert browser.post(route, params=params).status_code == 401
+ assert (
+ browser.get(web_server_file_tickets.ROUTES["stream"], params=params).status_code
+ == 401
+ )
+ for _ in range(web_server_file_tickets.DOWNLOAD_MAX_REDEMPTIONS - 1):
+ assert browser.get(route, params=params).content == b"hello"
+ assert browser.get(route, params=params).status_code == 401
+
+ stream = _mint(client, "stream", path=str(clip))
+ for _ in range(web_server_file_tickets.DOWNLOAD_MAX_REDEMPTIONS + 1):
+ partial = browser.get(
+ web_server_file_tickets.ROUTES["stream"],
+ params=stream,
+ headers={"Range": "bytes=1-3"},
+ )
+ assert (partial.status_code, partial.content) == (206, b"ell")
+
+
+def test_an_expired_download_ticket_is_refused_while_retries_remain(
+ browser_download, monkeypatch
+):
+ client, browser, clip = browser_download
+ route = web_server_file_tickets.ROUTES["download"]
+ real = time.monotonic
+ offset = {"seconds": 0.0}
+ monkeypatch.setattr(
+ web_server_file_tickets.time, "monotonic", lambda: real() + offset["seconds"]
+ )
+
+ fresh = _mint(client, "download", path=str(clip))
+ assert browser.get(route, params=fresh).content == b"hello"
+ offset["seconds"] = web_server_file_tickets.DOWNLOAD_TTL_SECONDS + 1
+ assert browser.get(route, params=fresh).status_code == 401
+
+ monkeypatch.setattr(web_server_file_tickets, "DOWNLOAD_TTL_SECONDS", 0)
+ expired = _mint(client, "download", path=str(clip))
+ assert browser.get(route, params=expired).status_code == 401
+
+
+def test_sign_out_drops_a_download_ticket_minted_under_the_browser_credential(
+ browser_download, monkeypatch
+):
+ client, browser, clip = browser_download
+ route = web_server_file_tickets.ROUTES["download"]
+ params = _mint(client, "download", path=str(clip))
+ assert browser.get(route, params=params).content == b"hello"
+ other = web_server_file_tickets.mint(
+ "download",
+ {"path": str(clip)},
+ authority=web_server_file_tickets.FileAuthority(clip, ()),
+ session_token=None,
+ )
+ monkeypatch.setattr(web_server, "_SESSION_TOKEN", web_server._SESSION_TOKEN)
+ browser_credential.rotate("b" * 43)
+
+ assert browser.get(route, params=params).status_code == 401
+ kept = browser.get(route, params={"path": str(clip), "ticket": other})
+ assert kept.content == b"hello"
diff --git a/tests/hermes_cli/test_web_server_files.py b/tests/hermes_cli/test_web_server_files.py
index 92a93647881..ca41e0f8494 100644
--- a/tests/hermes_cli/test_web_server_files.py
+++ b/tests/hermes_cli/test_web_server_files.py
@@ -245,7 +245,7 @@ def test_browser_file_urls_authenticate_only_with_route_and_path_bound_tickets(
forced_files_client, monkeypatch,
):
"""A ticket admits exactly the URL it was minted for: reusable for media
- Range requests, single-use for a download, useless for any other file."""
+ Range requests, a few retries of that same download, useless for any other file."""
from hermes_cli import web_server_file_tickets
client, root = forced_files_client
@@ -284,7 +284,8 @@ def test_browser_file_urls_authenticate_only_with_route_and_path_bound_tickets(
once = {"path": str(video), "ticket": download}
assert client.get("/api/files/stream", params=once).status_code == 401
- assert client.get(download_route, params=once).content == b"hello"
+ for _ in range(web_server_file_tickets.DOWNLOAD_MAX_REDEMPTIONS):
+ assert client.get(download_route, params=once).content == b"hello"
assert client.get(download_route, params=once).status_code == 401
diff --git a/tests/hermes_cli/test_web_server_fs.py b/tests/hermes_cli/test_web_server_fs.py
index 45d74c302f1..59fe0b1a37c 100644
--- a/tests/hermes_cli/test_web_server_fs.py
+++ b/tests/hermes_cli/test_web_server_fs.py
@@ -259,8 +259,8 @@ def test_a_browser_download_reads_the_ssh_workspace_file_it_listed(client, monke
"""The browser lists an SSH workspace through ``/api/fs/list``. Its Download checks the file
with a HEAD, then hands the browser the URL a download ticket authorizes (an anchor cannot send
the session header). Both read the file on the SSH machine, as native Desktop's download does,
- never a file at the same path on the gateway's own disk. The ticket is single-use and dies
- with its profile."""
+ never a file at the same path on the gateway's own disk. The ticket allows a few retries of
+ that exact URL, then dies with its profile."""
from hermes_cli import web_server_file_tickets as file_tickets
from hermes_constants import mark_named_profile_deleted
@@ -302,16 +302,22 @@ def test_a_browser_download_reads_the_ssh_workspace_file_it_listed(client, monke
checked = client.head(route, params=query)
assert (checked.status_code, checked.content) == (200, b""), (path, checked.text)
params = ticketed(query)
- saved = anchor.get(route, params=params)
- assert (saved.status_code, saved.content) == (200, b"remote copy"), path
+ saved = None
+ for _ in range(file_tickets.DOWNLOAD_MAX_REDEMPTIONS):
+ saved = anchor.get(route, params=params)
+ assert (saved.status_code, saved.content) == (200, b"remote copy"), path
assert saved.headers["content-disposition"].startswith("attachment;")
assert anchor.get(route, params=params).status_code == 401
- assert streamed == [str(same_path), remote_only] # the HEAD checks read nothing
+ expected = (
+ [str(same_path)] * file_tickets.DOWNLOAD_MAX_REDEMPTIONS
+ + [remote_only] * file_tickets.DOWNLOAD_MAX_REDEMPTIONS
+ )
+ assert streamed == expected # the HEAD checks read nothing
params = ticketed({"path": remote_only, "profile": "remote-dev"})
mark_named_profile_deleted(profile)
assert anchor.get(route, params=params).status_code in (401, 403, 404)
- assert streamed == [str(same_path), remote_only]
+ assert streamed == expected
finally:
anchor.close()