Skip to content

The agent that grows with you

fix(webapp): look a file request's session up once

unsupportedpastelsdb37888d8d3d
diff --git a/hermes_cli/web_routers/files.py b/hermes_cli/web_routers/files.py
index 3ce6d8c854e..43a7660cbaa 100644
--- a/hermes_cli/web_routers/files.py
+++ b/hermes_cli/web_routers/files.py
@@ -779,17 +779,17 @@ async def issue_file_ticket(payload: FileTicketRequest, request: Request):
# may be outside that home, but the ticket must still die with its owner.
owner = await asyncio.to_thread(owner_home)
# Before the backend is chosen: an SSH profile's ticket checks its session too.
- await _fs_owned_session(payload.session_id, payload.profile)
+ session = await _fs_owned_session(payload.session_id, payload.profile)
if payload.route == "download":
authority = await _fs_download_authority(
- request, payload.path, payload.profile, payload.session_id, owner,
+ request, payload.path, payload.profile, payload.session_id, owner, session,
)
else:
# An SSH profile's clip is captured on its SSH machine; a host-staged file on this host.
authority = await _remote_file_authority(payload.path, payload.profile, owner, _remote_stream_target)
path = payload.path
if authority is None and (payload.session_id is not None or path.lower().startswith("file:")):
- path = str(await _fs_download_path(path, payload.profile, payload.session_id))
+ path = str(await _fs_download_path(path, payload.profile, payload.session_id, session=session))
if authority is None:
authority = await asyncio.to_thread(capture)
except FileNotFoundError as exc:
@@ -836,7 +836,7 @@ async def stream_managed_file(
ticket route does. An SSH profile's clip streams from its SSH machine
(``_remote_fs_backend``, the rule download uses), one Range at a time.
Every request checks its ``session_id`` first, a ticketed one included."""
- await _fs_owned_session(session_id, profile)
+ session = await _fs_owned_session(session_id, profile)
authority = getattr(request.state, "file_ticket_authority", None)
if authority is not None and authority.workspace is not None:
target, size = await _ticketed_remote_target(authority, _remote_stream_target)
@@ -847,7 +847,7 @@ async def stream_managed_file(
target, size = await asyncio.to_thread(_remote_stream_target, backend, path)
return remote_media_response(request, backend, target, size, _fs_mime_type(Path(target)))
if session_id is not None or path.lower().startswith("file:"):
- path = str(await _fs_download_path(path, profile, session_id))
+ path = str(await _fs_download_path(path, profile, session_id, session=session))
return await _managed_file_response(request, path, content_disposition_type="inline", media_only=True)
@@ -1019,7 +1019,7 @@ async def fs_list(path: str, request: Request, profile: Optional[str] = None):
async def fs_read_text(
path: str, request: Request = None, profile: Optional[str] = None, session_id: Optional[str] = None,
):
- await _fs_owned_session(session_id, profile)
+ session = await _fs_owned_session(session_id, profile)
# A staged paste or pick previews from this host, as read-data-url reads it back to send.
backend = await asyncio.to_thread(_remote_fs_backend, path, profile)
if backend is not None:
@@ -1044,7 +1044,7 @@ async def fs_read_text(
}
profile_home = _fs_profile_home(profile)
# A session's /workspace is its own sandbox, resolved as download resolves it.
- target = await _fs_download_path(path, profile, session_id)
+ target = await _fs_download_path(path, profile, session_id, session=session)
# The same staged-file exception read-data-url makes under a locked files root.
if not await asyncio.to_thread(_is_host_file, str(target), profile):
_hosted_fs_read_guard(target, request)
@@ -1078,7 +1078,7 @@ async def fs_write_text(payload: FsWriteText, profile: Optional[str] = None):
file saves to the same place it was read from.
"""
text = payload.content or ""
- await _fs_owned_session(payload.session_id, profile)
+ session = await _fs_owned_session(payload.session_id, profile)
# Save where read-text read: a staged paste or pick on this host, all else on the SSH machine.
backend = await asyncio.to_thread(_remote_fs_backend, payload.path, profile)
if backend is not None:
@@ -1094,7 +1094,7 @@ async def fs_write_text(payload: FsWriteText, profile: Optional[str] = None):
return {"ok": True, "path": target, "byteSize": byte_size}
target = await _fs_download_path(
- payload.path, profile, payload.session_id, decode_fallback=False, own_sandbox_only=True,
+ payload.path, profile, payload.session_id, session=session, decode_fallback=False, own_sandbox_only=True,
)
if len(text.encode("utf-8")) > _FS_TEXT_WRITE_MAX_BYTES:
raise HTTPException(status_code=413, detail="Content too large")
@@ -1129,18 +1129,21 @@ async def fs_write_text(payload: FsWriteText, profile: Optional[str] = None):
async def _fs_download_path(
- path: str, profile: Optional[str], session_id: Optional[str], *, decode_fallback: bool = True,
- own_sandbox_only: bool = False,
+ path: str, profile: Optional[str], session_id: Optional[str], *, session: Optional[dict] = None,
+ decode_fallback: bool = True, own_sandbox_only: bool = False,
) -> Path:
# Resolve container paths in the requested profile's sandbox, not the active one's.
# A write passes decode_fallback=False: it must never land on a decoded twin of its name.
# A session's write also passes own_sandbox_only: reads fall back to the shared sandbox
# when the session's own copy is gone, a Save must not (409 instead).
+ # *session* is the row the route's _fs_owned_session already returned for *session_id*;
+ # a caller that passes none gets the same lookup here.
profile_home = _fs_profile_home(profile)
if session_id is not None:
- session = await _fs_owned_session(session_id, profile) or {}
+ if session is None:
+ session = await _fs_owned_session(session_id, profile)
# Validate ownership even for absolute paths; never trust a client cwd.
- cwd = session.get("cwd") or ""
+ cwd = (session or {}).get("cwd") or ""
return _agent_fs_path(
path, cwd=cwd, profile_home=profile_home,
workspace_key=_session_workspace_key(session_id, cwd), decode_fallback=decode_fallback,
@@ -1180,7 +1183,7 @@ async def fs_read_data_url(
path: str, request: Request, profile: Optional[str] = None, session_id: Optional[str] = None,
):
from hermes_cli.web_server import _FS_DATA_URL_MAX_BYTES
- await _fs_owned_session(session_id, profile)
+ session = await _fs_owned_session(session_id, profile)
backend = await asyncio.to_thread(_remote_fs_backend, path, profile)
if backend is not None:
try:
@@ -1191,7 +1194,7 @@ async def fs_read_data_url(
_raise_fs_backend_error(exc)
encoded = base64.b64encode(data).decode("ascii")
return {"dataUrl": f"data:{_fs_mime_type(Path(target))};base64,{encoded}"}
- target = await _fs_download_path(path, profile, session_id)
+ target = await _fs_download_path(path, profile, session_id, session=session)
# A browser paste or pick reads back to be sent wherever a locked files root sits: the server
# wrote it into the profile's own image cache or staged uploads, outside the managed tree.
if not await asyncio.to_thread(_is_host_file, str(target), profile):
@@ -1270,6 +1273,7 @@ def _remote_download_response(request: Optional[Request], backend, target: str,
async def _fs_download_authority(
request: Request, path: str, profile: Optional[str], session_id: Optional[str], owner: Path,
+ session: Optional[dict] = None,
) -> file_tickets.FileAuthority:
"""The file ``/api/fs/download`` serves for this query, captured for a download ticket: on the
profile's SSH workspace when it has one, else on this host under the same read rules."""
@@ -1278,7 +1282,7 @@ async def _fs_download_authority(
remote = await _remote_file_authority(path, profile, owner, _remote_download_target)
if remote is not None:
return remote
- local = await _fs_download_path(path, profile, session_id)
+ local = await _fs_download_path(path, profile, session_id, session=session)
def capture():
_hosted_fs_read_guard(local, request)
@@ -1325,7 +1329,7 @@ async def fs_download(
):
"""A workspace file as an attachment: from the profile's SSH workspace when it has one, else
from this host. A browser download link authenticates with a path-bound ``?ticket=``."""
- await _fs_owned_session(session_id, profile)
+ session = await _fs_owned_session(session_id, profile)
authority = getattr(getattr(request, "state", None), "file_ticket_authority", None)
if authority is not None:
return await _ticketed_fs_download(request, authority, profile)
@@ -1333,7 +1337,7 @@ async def fs_download(
if backend is not None:
target, size = await asyncio.to_thread(_remote_download_target, backend, path)
return _remote_download_response(request, backend, target, size)
- target = await _fs_download_path(path, profile, session_id)
+ target = await _fs_download_path(path, profile, session_id, session=session)
_hosted_fs_read_guard(target, request)
target, _st = _fs_regular_file(target, _fs_profile_home(profile))
await asyncio.to_thread(_refuse_live_database, target)
diff --git a/tests/hermes_cli/test_web_server_fs_session_workspace.py b/tests/hermes_cli/test_web_server_fs_session_workspace.py
index 8ab0141965d..f8ab33dc464 100644
--- a/tests/hermes_cli/test_web_server_fs_session_workspace.py
+++ b/tests/hermes_cli/test_web_server_fs_session_workspace.py
@@ -71,15 +71,39 @@ def sandboxes(monkeypatch, tmp_path):
"sess-work": ("work", str(project)),
}
+ lookups = []
+
async def detail(session_id, profile=None):
# The real lookup reads only the requested profile's state.db.
+ lookups.append(session_id)
row = rows.get(session_id)
if row is None or row[0] != (profile or "default"):
raise HTTPException(status_code=404, detail="Session not found")
return {"cwd": row[1], "id": session_id}
monkeypatch.setattr("hermes_cli.web_routers.sessions.get_session_detail", detail)
- return {"own": own, "foreign": foreign, "shared": shared, "outside": outside}
+ return {"own": own, "foreign": foreign, "shared": shared, "outside": outside, "lookups": lookups}
+
+
+def test_each_file_route_looks_its_session_up_once(client, sandboxes, monkeypatch):
+ monkeypatch.setattr(web_server.app.state, "ui_surface", "webapp", raising=False)
+ clip = {"path": "file:///workspace/clip.mp4", "session_id": "sess-ws"}
+ note = {"path": "/workspace/note.txt", "session_id": "sess-ws"}
+ requests = [
+ lambda: client.get("/api/files/stream", params=clip),
+ lambda: client.post("/api/files/ticket", json={"route": "stream", **clip}),
+ lambda: client.post("/api/files/ticket", json={"route": "download", **note}),
+ lambda: client.get("/api/fs/read-text", params=note),
+ lambda: client.get("/api/fs/read-data-url", params=note),
+ lambda: client.get("/api/fs/download", params=note),
+ lambda: client.post("/api/fs/write-text", json={**note, "content": "edited"}),
+ ]
+
+ for send in requests:
+ sandboxes["lookups"].clear()
+ response = send()
+ assert response.status_code == 200, response.text
+ assert sandboxes["lookups"] == ["sess-ws"], response.request.url
# Part 1: media streams