Skip to content

The agent that grows with you

fix(webapp): check a file request's session before choosing its SSH backend

unsupportedpastelscd322c2a0000
diff --git a/hermes_cli/web_routers/files.py b/hermes_cli/web_routers/files.py
index cf7a4ea3567..8feda942312 100644
--- a/hermes_cli/web_routers/files.py
+++ b/hermes_cli/web_routers/files.py
@@ -772,6 +772,8 @@ async def issue_file_ticket(payload: FileTicketRequest, request: Request):
# Capture the session/profile owner BEFORE looking up its cwd. The file
# 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)
if payload.route == "download":
authority = await _fs_download_authority(
request, payload.path, payload.profile, payload.session_id, owner,
@@ -826,7 +828,9 @@ async def stream_managed_file(
Same size cap, sensitive guard and MIME detection as download. A
``session_id`` resolves ``/workspace`` in that session's own sandbox, as the
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."""
+ (``_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)
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)
@@ -1009,6 +1013,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)
# 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:
@@ -1067,6 +1072,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)
# 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:
@@ -1121,11 +1127,7 @@ async def _fs_download_path(
# A write passes decode_fallback=False: it must never land on a decoded twin of its name.
profile_home = _fs_profile_home(profile)
if session_id is not None:
- from hermes_cli.web_routers.sessions import get_session_detail
-
- if not session_id.strip():
- raise HTTPException(status_code=404, detail="Session not found")
- session = await get_session_detail(session_id, profile)
+ session = await _fs_owned_session(session_id, profile) or {}
# Validate ownership even for absolute paths; never trust a client cwd.
cwd = session.get("cwd") or ""
return _agent_fs_path(
@@ -1135,6 +1137,20 @@ async def _fs_download_path(
return _agent_fs_path(path, profile_home=profile_home, decode_fallback=decode_fallback)
+async def _fs_owned_session(session_id: Optional[str], profile: Optional[str]) -> Optional[dict]:
+ """The session *session_id* names, looked up in *profile*'s own sessions, or None when the
+ request names none. A blank id, or one that profile does not own, is 404. A route that takes a
+ ``session_id`` calls this before it picks a backend, so an SSH profile refuses the same
+ sessions a host or Docker one does."""
+ if session_id is None:
+ return None
+ from hermes_cli.web_routers.sessions import get_session_detail
+
+ if not session_id.strip():
+ raise HTTPException(status_code=404, detail="Session not found")
+ return await get_session_detail(session_id, profile)
+
+
def _fs_profile_home(profile: Optional[str]) -> Optional[Path]:
"""HERMES_HOME of a requested profile (404/400 on an unknown one), None for the request's
own profile (omitted, ``""`` or ``current``, as ``_is_current_profile`` reads them)."""
@@ -1152,6 +1168,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)
backend = await asyncio.to_thread(_remote_fs_backend, path, profile)
if backend is not None:
try:
@@ -1296,6 +1313,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)
authority = getattr(getattr(request, "state", None), "file_ticket_authority", None)
if authority is not None:
return await _ticketed_fs_download(request, authority, profile)
diff --git a/tests/hermes_cli/test_web_server_ssh_media_stream.py b/tests/hermes_cli/test_web_server_ssh_media_stream.py
index 7f6e3a8b0c5..8668cdf30cb 100644
--- a/tests/hermes_cli/test_web_server_ssh_media_stream.py
+++ b/tests/hermes_cli/test_web_server_ssh_media_stream.py
@@ -24,6 +24,15 @@ class FakeSshWorkspace:
self.files = {CLIP: BYTES, "/srv/media/notes.txt": b"notes"}
self.links = {"/srv/media/linked.mp4": "/home/dev/.hermes/mcp-tokens/token.mp4"}
self.reads = []
+ self.writes = []
+
+ def read_bytes(self, path, max_bytes=None, read_limit=None):
+ data = self.files[path]
+ return data[:read_limit] if read_limit else data, len(data), path
+
+ def write_text(self, path, text, max_bytes=None):
+ self.writes.append((path, text))
+ return path, len(text.encode("utf-8"))
def inspect_file(self, path):
target = self.links.get(path, path)
@@ -213,6 +222,114 @@ def test_a_down_ssh_host_is_unavailable_to_the_stream(client, ssh, monkeypatch):
assert (minted.status_code, minted.json()) == UNAVAILABLE
+# A session_id is checked against the profile before the SSH backend is chosen.
+
+
+def sessions(monkeypatch):
+ """``ssh-sess`` belongs to the SSH profile, ``host-sess`` to the default one; the real lookup
+ reads only the requested profile's state.db."""
+ from fastapi import HTTPException
+
+ rows = {"ssh-sess": "remote-dev", "host-sess": "default"}
+
+ async def detail(session_id, profile=None):
+ if rows.get(session_id) != (profile or "default"):
+ raise HTTPException(status_code=404, detail="Session not found")
+ return {"cwd": "/srv", "id": session_id}
+
+ monkeypatch.setattr("hermes_cli.web_routers.sessions.get_session_detail", detail)
+ return rows
+
+
+NOT_OWNED = ["host-sess", "missing-session", " ", ""]
+
+
[email protected]("session_id", NOT_OWNED)
+def test_ssh_stream_and_tickets_refuse_a_session_the_profile_does_not_own(client, ssh, sessions, session_id):
+ _profile, workspace = ssh
+ query = {"path": CLIP, "profile": "remote-dev", "session_id": session_id}
+
+ direct = _stream(client, session_id=session_id, headers={"Range": "bytes=0-3"})
+ head = _stream(client, method="HEAD", session_id=session_id)
+ minted = client.post("/api/files/ticket", json={"route": "stream", **query})
+ download = client.post("/api/files/ticket", json={"route": "download", **query})
+
+ assert [r.status_code for r in (direct, head, minted, download)] == [404] * 4, minted.text
+ assert workspace.reads == []
+
+
[email protected]("session_id", NOT_OWNED)
+def test_an_ssh_stream_ticket_never_plays_for_a_session_the_profile_does_not_own(client, ssh, sessions, session_id):
+ _profile, workspace = ssh
+ query = {"path": CLIP, "profile": "remote-dev"}
+ player = TestClient(web_server.app) # a media element sends no session header
+ try:
+ minted = client.post("/api/files/ticket", json={"route": "stream", **query, "session_id": session_id})
+ assert minted.status_code == 404, minted.text
+ bare = client.post("/api/files/ticket", json={"route": "stream", **query})
+ assert bare.status_code == 200, bare.text
+
+ redeemed = player.get(
+ "/api/files/stream", params={**query, "session_id": session_id, "ticket": bare.json()["ticket"]},
+ )
+
+ assert redeemed.status_code in (401, 404), redeemed.text
+ assert workspace.reads == []
+ finally:
+ player.close()
+
+
+def test_an_ssh_stream_ticket_stops_playing_once_its_session_is_gone(client, ssh, sessions, monkeypatch):
+ _profile, workspace = ssh
+ query = {"path": CLIP, "profile": "remote-dev", "session_id": "ssh-sess"}
+ minted = client.post("/api/files/ticket", json={"route": "stream", **query})
+ assert minted.status_code == 200, minted.text
+ ticketed = {**query, "ticket": minted.json()["ticket"]}
+ player = TestClient(web_server.app)
+ try:
+ played = player.get("/api/files/stream", params=ticketed, headers={"Range": "bytes=0-3"})
+ assert (played.status_code, played.content) == (206, BYTES[:4])
+
+ monkeypatch.delitem(sessions, "ssh-sess")
+ gone = player.get("/api/files/stream", params=ticketed, headers={"Range": "bytes=0-3"})
+
+ assert gone.status_code == 404, gone.text
+ assert workspace.reads == [(CLIP, 0, 4)]
+ finally:
+ player.close()
+
+
+def test_an_ssh_profile_streams_reads_and_saves_for_its_own_session(client, ssh, sessions):
+ _profile, workspace = ssh
+
+ streamed = _stream(client, session_id="ssh-sess")
+ read = client.get("/api/fs/read-text", params={"path": "/srv/media/notes.txt", "profile": "remote-dev",
+ "session_id": "ssh-sess"})
+ saved = client.post("/api/fs/write-text", params={"profile": "remote-dev"},
+ json={"path": "/srv/media/notes.txt", "content": "edited", "session_id": "ssh-sess"})
+
+ assert (streamed.status_code, streamed.content) == (200, BYTES)
+ assert (read.status_code, read.json()["text"]) == (200, "notes")
+ assert saved.status_code == 200, saved.text
+ assert workspace.writes == [("/srv/media/notes.txt", "edited")]
+
+
[email protected]("session_id", NOT_OWNED)
+def test_ssh_reads_and_saves_refuse_a_session_the_profile_does_not_own(client, ssh, sessions, session_id):
+ _profile, workspace = ssh
+ note = {"path": "/srv/media/notes.txt", "profile": "remote-dev", "session_id": session_id}
+
+ read = client.get("/api/fs/read-text", params=note)
+ data_url = client.get("/api/fs/read-data-url", params=note)
+ download = client.get("/api/fs/download", params=note)
+ saved = client.post("/api/fs/write-text", params={"profile": "remote-dev"},
+ json={"path": note["path"], "content": "edited", "session_id": session_id})
+
+ assert [r.status_code for r in (read, data_url, download, saved)] == [404] * 4, read.text
+ assert workspace.writes == []
+
+
def test_the_adapter_reads_one_range_with_the_path_quoted(monkeypatch):
"""The SSH command reads exactly the asked bytes, and a hostile file name stays one word."""
launched = []