The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(dashboard): confine fs preview and git diff reads to the managed root
Adolaniumb9d9aeeb58c2
diff --git a/hermes_cli/web_git.py b/hermes_cli/web_git.pyindex bec611c7563..afd2f6f720d 100644--- a/hermes_cli/web_git.py+++ b/hermes_cli/web_git.py@@ -14,6 +14,7 @@ import osimport reimport shutilimport subprocess+from collections.abc import Callablefrom pathlib import Pathfrom hermes_cli._subprocess_compat import harden_git_argv, noninteractive_git_env@@ -285,20 +286,35 @@ def review_list(cwd: str, scope: str, base_ref: str | None) -> dict:def _all_add_diff(cwd: str, file_path: str) -> str:"""Synthesized all-add diff for an untracked file (``--no-index`` exits non-zero by design)."""+ if not (Path(cwd) / file_path).is_file():+ return ""return _git(cwd, ["diff", "--no-index", "--", os.devnull, file_path])[1]+def _single_file_diff(cwd: str, args: list[str], file_path: str) -> str:+ """Literal Git pathspecs still expand directories, including deleted ones."""+ literal = f":(literal){file_path}"+ names = _git_out(cwd, ["diff", *args, "--no-renames", "--name-only", "-z", "--", literal])+ if not names:+ return ""+ root = Path(_git_line(cwd, ["rev-parse", "--show-toplevel"]))+ target = (Path(cwd) / file_path).resolve()+ if any((root / name).resolve() != target for name in names.split("\0") if name):+ raise RuntimeError("Expected a single file, not a directory")+ return _git_out(cwd, ["diff", *args, "--no-renames", "--", literal])++def review_diff(cwd: str, file_path: str, scope: str, base_ref: str | None, staged: bool) -> str:if not _is_dir(cwd):return ""if scope == "branch":base = _branch_base(cwd)- return _git_out(cwd, ["diff", f"{base}...HEAD", "--", file_path]) if base else ""+ return _single_file_diff(cwd, [f"{base}...HEAD"], file_path) if base else ""if scope == "lastTurn":- return _git_out(cwd, ["diff", base_ref, "--", file_path]) if base_ref else ""+ return _single_file_diff(cwd, [base_ref], file_path) if base_ref else ""if staged:- return _git_out(cwd, ["diff", "--cached", "--", file_path])- worktree = _git_out(cwd, ["diff", "--", file_path])+ return _single_file_diff(cwd, ["--cached"], file_path)+ worktree = _single_file_diff(cwd, [], file_path)return worktree if worktree.strip() else _all_add_diff(cwd, file_path)@@ -307,10 +323,11 @@ def file_diff_vs_head(cwd: str, file_path: str) -> str:review_diff, never all-adds a clean tracked file; only a genuinely untracked one."""if not _is_dir(cwd):return ""- head = _git_out(cwd, ["diff", "HEAD", "--", file_path])+ literal = f":(literal){file_path}"+ head = _single_file_diff(cwd, ["HEAD"], file_path)if head.strip():return head- status = _git_out(cwd, ["status", "--porcelain", "--", file_path])+ status = _git_out(cwd, ["status", "--porcelain", "--", literal])return _all_add_diff(cwd, file_path) if status.strip().startswith("??") else ""@@ -364,13 +381,25 @@ def review_push(cwd: str) -> dict:return {"ok": True}-def review_commit_context(cwd: str) -> dict:+def review_commit_context(cwd: str, path_allowed: Callable[[Path], bool] | None = None) -> dict:"""Diff of what WILL commit + recent subjects, for drafting a commit message."""code, raw = _status_z(cwd) if _is_dir(cwd) else (1, "")if code != 0:return {"diff": "", "recent": ""}entries = list(_walk_entries(raw))- diff = _git_out(cwd, ["diff", "--cached"] if _has_staged(raw) else ["diff", "HEAD"])+ args = ["diff", "--cached"] if _has_staged(raw) else ["diff", "HEAD"]+ if path_allowed is None:+ diff = _git_out(cwd, args)+ else:+ # Disable rename pairing so an allowed destination cannot include the+ # old contents of a credential path excluded from the diff.+ repo = _git_line(cwd, ["rev-parse", "--show-toplevel"])+ if not repo:+ return {"diff": "", "recent": ""}+ names = _git_out(repo, [*args, "--no-renames", "--name-only", "-z"]).split("\0")+ allowed = [f":(literal){name}" for name in names if name and path_allowed(Path(repo) / name)]+ diff = _git_out(repo, [*args, "--no-renames", "--", *allowed]) if allowed else ""+ entries = [entry for entry in entries if path_allowed(Path(repo) / entry[2])]if len(diff) > _COMMIT_CONTEXT_DIFF_MAX_CHARS:omitted = len(diff) - _COMMIT_CONTEXT_DIFF_MAX_CHARSdiff = f"{diff[:_COMMIT_CONTEXT_DIFF_MAX_CHARS]}\n# diff truncated: {omitted} chars omitted\n"diff --git a/hermes_cli/web_routers/files.py b/hermes_cli/web_routers/files.pyindex 09373e4c8b6..8d16f4f4fe4 100644--- a/hermes_cli/web_routers/files.py+++ b/hermes_cli/web_routers/files.py@@ -29,7 +29,7 @@ from hermes_cli._subprocess_compat import windows_hide_flagsfrom hermes_cli.sqlite_safe_read import LiveConnectionError, offline_file_accessfrom hermes_cli.web_deps import latefrom hermes_cli.web_server_files import (- _fs_path, _managed_file_entry, _managed_response_meta, _resolve_managed_path,+ _fs_path, _hosted_fs_read_guard, _managed_file_entry, _managed_response_meta, _resolve_managed_path,)from hermes_cli.web_models import (ChatImageUpload, FsWriteText, ManagedDirectoryCreate, ManagedFileDelete, ManagedFileUpload,@@ -757,7 +757,7 @@ _FS_LIST_ERRNO = (@router.get("/api/fs/list")-async def fs_list(path: str, profile: Optional[str] = None):+async def fs_list(path: str, request: Request, profile: Optional[str] = None):backend = await asyncio.to_thread(_fs_backend, profile)if backend is not None:try:@@ -765,6 +765,7 @@ async def fs_list(path: str, profile: Optional[str] = None):except Exception as exc:_raise_fs_backend_error(exc)target = _fs_path(path)+ _hosted_fs_read_guard(target, request)try:entries = []with os.scandir(target) as scan:@@ -786,7 +787,7 @@ async def fs_list(path: str, profile: Optional[str] = None):@router.get("/api/fs/read-text")-async def fs_read_text(path: str, profile: Optional[str] = None):+async def fs_read_text(path: str, request: Request, profile: Optional[str] = None):backend = await asyncio.to_thread(_fs_backend, profile)if backend is not None:try:@@ -808,7 +809,9 @@ async def fs_read_text(path: str, profile: Optional[str] = None):"text": data.decode("utf-8", errors="replace"),"truncated": size > _FS_TEXT_PREVIEW_MAX_BYTES,}- target, st = _fs_regular_file(_fs_path(path))+ target = _fs_path(path)+ _hosted_fs_read_guard(target, request)+ target, st = _fs_regular_file(target)if st.st_size > _FS_TEXT_SOURCE_MAX_BYTES:raise HTTPException(status_code=413, detail="File too large")data = await asyncio.to_thread(@@ -900,7 +903,7 @@ async def _fs_download_path(path: str, profile: Optional[str], session_id: Optio@router.get("/api/fs/read-data-url")async def fs_read_data_url(- path: str, profile: Optional[str] = None, session_id: Optional[str] = None,+ path: str, request: Request, profile: Optional[str] = None, session_id: Optional[str] = None,):from hermes_cli.web_server import _FS_DATA_URL_MAX_BYTESbackend = await asyncio.to_thread(_fs_backend, profile)@@ -913,7 +916,9 @@ 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, st = _fs_regular_file(await _fs_download_path(path, profile, session_id))+ target = await _fs_download_path(path, profile, session_id)+ _hosted_fs_read_guard(target, request)+ target, st = _fs_regular_file(target)if st.st_size > _FS_DATA_URL_MAX_BYTES:raise HTTPException(status_code=413, detail="File too large")encoded = await asyncio.to_thread(@@ -924,7 +929,7 @@ async def fs_read_data_url(@router.get("/api/fs/download")async def fs_download(- path: str, profile: Optional[str] = None, session_id: Optional[str] = None,+ path: str, request: Request, profile: Optional[str] = None, session_id: Optional[str] = None,):backend = await asyncio.to_thread(_fs_backend, profile)if backend is not None:@@ -941,7 +946,9 @@ async def fs_download(media_type=_fs_mime_type(target_path),headers={"Content-Disposition": f"attachment; filename*=UTF-8''{filename}"},)- target, _st = _fs_regular_file(await _fs_download_path(path, profile, session_id))+ target = await _fs_download_path(path, profile, session_id)+ _hosted_fs_read_guard(target, request)+ target, _st = _fs_regular_file(target)await asyncio.to_thread(_refuse_live_database, target)return FileResponse(path=str(target),diff --git a/hermes_cli/web_routers/git.py b/hermes_cli/web_routers/git.pyindex 64ae36cf59e..560eab3419c 100644--- a/hermes_cli/web_routers/git.py+++ b/hermes_cli/web_routers/git.py@@ -9,14 +9,16 @@ wrappers (git/gh can block).import asyncioimport shutilimport time+from functools import partial+from pathlib import Pathfrom typing import Optional-from fastapi import APIRouter, HTTPException+from fastapi import APIRouter, HTTPException, Requestfrom hermes_cli import web_git as _web_gitfrom hermes_cli._subprocess_compat import bounded_probe_runfrom hermes_cli.web_deps import late-from hermes_cli.web_server_files import _fs_path+from hermes_cli.web_server_files import _fs_path, _hosted_fs_path_allowed, _hosted_fs_read_guardfrom hermes_cli.web_models import (GitBranchSwitchBody,GitCommitBody,@@ -127,19 +129,29 @@ async def git_review_list_route(path: str, scope: str = "uncommitted", base: Opt@router.get("/api/git/review/diff")async def git_review_diff_route(- path: str, file: str, scope: str = "uncommitted", base: Optional[str] = None, staged: bool = False+ path: str, file: str, request: Request,+ scope: str = "uncommitted", base: Optional[str] = None, staged: bool = False):- return {"diff": await _git_op(_web_git.review_diff, _git_path(path), file, scope, base, staged)}+ cwd = _git_path(path)+ target = _fs_path(file, cwd=cwd)+ _hosted_fs_read_guard(target, request)+ return {"diff": await _git_op(_web_git.review_diff, cwd, str(target), scope, base, staged)}@router.get("/api/git/file-diff")-async def git_file_diff_route(path: str, file: str):- return {"diff": await _git_op(_web_git.file_diff_vs_head, _git_path(path), file)}+async def git_file_diff_route(path: str, file: str, request: Request):+ cwd = _git_path(path)+ target = _fs_path(file, cwd=cwd)+ _hosted_fs_read_guard(target, request)+ return {"diff": await _git_op(_web_git.file_diff_vs_head, cwd, str(target))}@router.get("/api/git/review/commit-context")-async def git_commit_context_route(path: str):- return await _git_op(_web_git.review_commit_context, _git_path(path))+async def git_commit_context_route(path: str, request: Request):+ cwd = _git_path(path)+ root = _hosted_fs_read_guard(Path(cwd), request)+ allowed = partial(_hosted_fs_path_allowed, root) if root is not None else None+ return await _git_op(_web_git.review_commit_context, cwd, allowed)@router.get("/api/git/review/rev-parse")diff --git a/hermes_cli/web_server_files.py b/hermes_cli/web_server_files.pyindex 2268db3602a..b44f49f48ec 100644--- a/hermes_cli/web_server_files.py+++ b/hermes_cli/web_server_files.py@@ -197,6 +197,22 @@ def _managed_response_meta(policy: ManagedFilesPolicy) -> Dict[str, Any]:return {"root": locked_root, "locked_root": locked_root, "can_change_path": policy.can_change_path}+def _hosted_fs_path_allowed(root: Path, target: Path) -> bool:+ from hermes_cli.web_routers.files import _is_sensitive_path++ resolved = _canonical_path(target)+ return (_path_is_under(root, resolved)+ and not _is_sensitive_path(target) and not _is_sensitive_path(resolved))+++def _hosted_fs_read_guard(target: Path, request: Request) -> Path | None:+ """Preview and Git reads share managed-file restrictions on locked deployments."""+ root = _managed_files_policy(request, create_root=False).locked_root+ if root is not None and not _hosted_fs_path_allowed(root, target):+ raise HTTPException(status_code=403, detail="Path is outside the managed read boundary")+ return root++def _managed_file_entry(policy: ManagedFilesPolicy, target: Path) -> Dict[str, Any]:try:resolved = target.resolve()diff --git a/tests/hermes_cli/test_web_read_confinement.py b/tests/hermes_cli/test_web_read_confinement.pynew file mode 100644index 00000000000..4e2e81c002b--- /dev/null+++ b/tests/hermes_cli/test_web_read_confinement.py@@ -0,0 +1,98 @@+"""Locked preview and review routes share the managed-file read boundary."""++import subprocess++import pytest+from starlette.testclient import TestClient++from hermes_cli import web_server+++def client(monkeypatch):+ monkeypatch.setattr(web_server.app.state, "auth_required", False, raising=False)+ with TestClient(web_server.app) as client:+ client.headers[web_server._SESSION_HEADER_NAME] = web_server._SESSION_TOKEN+ yield client++[email protected]("locked", [True, False])+def test_preview_respects_locked_root_and_sensitive_paths(client, monkeypatch, tmp_path, locked):+ root = tmp_path / "root"+ root.mkdir()+ if locked:+ monkeypatch.setenv("HERMES_DASHBOARD_FILES_ROOT", str(root))+ else:+ monkeypatch.delenv("HERMES_DASHBOARD_FILES_ROOT", raising=False)+ safe = root / "safe.txt"+ secret = root / "auth.json"+ outside = tmp_path / "outside.txt"+ for path in (safe, secret, outside):+ path.write_text("example", encoding="utf-8")+ for endpoint in ("read-text", "read-data-url", "download"):+ for path in (safe, secret, outside):+ response = client.get(f"/api/fs/{endpoint}", params={"path": str(path)})+ denied = path == secret or (locked and path == outside)+ assert response.status_code == (403 if denied else 200)+ response = client.get("/api/fs/list", params={"path": str(root)})+ names = {entry["name"] for entry in response.json()["entries"]}+ assert "safe.txt" in names+ assert "auth.json" not in names+ assert client.get("/api/fs/list", params={"path": str(tmp_path)}).status_code == (403 if locked else 200)++[email protected]("locked", [True, False])[email protected]("change", ["staged", "unstaged", "deleted", "renamed"])+def test_git_reads_filter_credentials_without_losing_safe_diffs(+ client, monkeypatch, tmp_path, locked, change+):+ root = tmp_path / "repo"+ root.mkdir()++ def git(*args):+ subprocess.run(["git", *args], cwd=root, check=True, capture_output=True)++ git("init", "-q")+ git("config", "user.email", "[email protected]")+ git("config", "user.name", "Test")+ secret = root / ".env"+ secret.write_text("PRIVATE_EXAMPLE=old\n", encoding="utf-8")+ archive = root / "archive"+ archive.mkdir()+ (archive / "auth.json").write_text("PRIVATE_EXAMPLE=archived\n", encoding="utf-8")+ (root / "safe.txt").write_text("old\n", encoding="utf-8")+ git("add", "-A")+ git("commit", "-qm", "initial")+ (archive / "auth.json").unlink()+ archive.rmdir()+ (root / "safe.txt").write_text("SAFE_CHANGE\n", encoding="utf-8")+ if change == "deleted":+ secret.unlink()+ elif change == "renamed":+ git("mv", ".env", "auth.json")+ (root / "auth.json").write_text("PRIVATE_EXAMPLE=new\n", encoding="utf-8")+ else:+ secret.write_text("PRIVATE_EXAMPLE=new\n", encoding="utf-8")+ if change != "unstaged":+ git("add", "-A")+ if locked:+ monkeypatch.setenv("HERMES_DASHBOARD_FILES_ROOT", str(root))+ else:+ monkeypatch.delenv("HERMES_DASHBOARD_FILES_ROOT", raising=False)++ response = client.get("/api/git/review/commit-context", params={"path": str(root)})+ assert response.status_code == 200+ diff = response.json()["diff"]+ assert "SAFE_CHANGE" in diff+ assert ("PRIVATE_EXAMPLE" in diff) is not locked+ for endpoint in ("/api/git/file-diff", "/api/git/review/diff"):+ response = client.get(endpoint, params={"path": str(root), "file": ".env", "staged": change != "unstaged"})+ assert response.status_code == (403 if locked else 200)+ # A pathspec is not a file name and must not expand into credential files.+ for file in (":(top)*", ".", "archive"):+ response = client.get(endpoint, params={"path": str(root), "file": file, "staged": change != "unstaged"})+ assert "PRIVATE_EXAMPLE" not in response.text++ monkeypatch.setenv("HERMES_DASHBOARD_FILES_ROOT", str(tmp_path / "other"))+ response = client.get("/api/git/review/commit-context", params={"path": str(root)})+ assert response.status_code == 403