Files
ai-agent/backend/test_hostfiles.py
gabrielvidalandClaude Opus 5.5 b7427475be feat(plugins): move the file explorer/viewer and the context editor into live plugins
The host file browser + viewer (/file/*, HostFilePage, the project Files
card) and the context tree + editor (/_/*, Editor, the FilesPanel tree) are
the file-explorer and context-editor plugins' now.

- bridges (plugins/hubfiles.py): hostfiles.read (as the caller; operator-
  approved; machine tokens refused), context.read / context.write (owner)
- /api/bundle, /api/file, /api/host-file, /api/host-files[/recent] retired;
  /api/host-file/raw stays for media and downloads
- pages that route themselves: aiAgentPlugin.setRoute / onRoute; download,
  back; plugin pages pad above the phone composer
- /file/* and /_/* redirect through opens (host-file, context-file)
- mock: filesPlugins.ts; docs and CLAUDE.md updated

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 13:44:41 +01:00

246 lines
13 KiB
Python

"""Host files a message names (files/hostfiles.py + files/browse.py): which
paths resolve for whom, the secrets and noise nobody reads, symlinks out of a
root, and the file-explorer plugin's bridge and the raw route through the gate for a guest and the owner.
Imports ``main`` against throwaway paths (no startup event → no threads)."""
import os
import pathlib
import tempfile
import unittest
TMP = pathlib.Path(tempfile.mkdtemp())
for k, v in {"DB_PATH": TMP / "x.db", "TRANSCRIPTS_DIR": TMP / "t",
"WORKSPACE": TMP, "REPO_DIR": TMP, "ARCHIVE_DIR": TMP / "arch",
"META_PATH": TMP / "meta.json", "WORKERS_PATH": TMP / "w.json",
"PROFILES_PATH": TMP / "profiles.json",
"WORKERS_TRANSCRIPTS_DIR": TMP / "mirror",
"CRON_PATH": TMP / "cron.json", "NOTIFY_PATH": TMP / "n.json",
"FORMS_PATH": TMP / "f.json", "UI_STATE_PATH": TMP / "ui.json",
"NOTIF_READ_PATH": TMP / "nr.json",
"MAIL_TRIGGER_SENDERS_PATH": TMP / "mt.json",
"USERS_PATH": TMP / "users.json", "AUTH_PATH": TMP / "auth.json",
"PROJECTS_DIR": TMP / "projects", "SERVICES_DIR": TMP / "services",
"WORKTREES_DIR": TMP / "worktrees", "HOMELAB_DIR": TMP / "homelab",
"INTERNAL_API_TOKEN": "tok", "PLUGINS_DIR": TMP / "plugins", "GUEST_HOSTS": "claude.example.test",
"SIDECAR_TOKEN": "", "PI_TRANSCRIPTS_DIR": ""}.items():
os.environ[k] = str(v)
FILM = TMP / "projects" / "film"
(FILM / "notes").mkdir(parents=True)
(FILM / "node_modules" / "x").mkdir(parents=True)
(FILM / "notes" / "report.md").write_text("# Report\n\nok\n")
(FILM / "notes" / "data.csv").write_text("a,b\n1,2\n")
(FILM / "notes" / "blob.bin").write_bytes(b"\x00\x01\x02")
(FILM / ".env").write_text("SECRET=1\n")
(FILM / ".env.example").write_text("SECRET=\n")
(FILM / "deploy.pem").write_text("-----BEGIN-----\n")
(FILM / "node_modules" / "x" / "index.js").write_text("x\n")
(TMP / "projects" / "other").mkdir(parents=True)
(TMP / "projects" / "other" / "plan.md").write_text("# other\n")
(TMP / "outside.md").write_text("# outside\n")
(FILM / "escape.md").symlink_to(TMP / "outside.md")
(FILM / "notes" / "innocent.txt").symlink_to(FILM / ".env") # a secret behind a plain name
(FILM / "notes" / "alias.cfg").symlink_to(FILM / "notes" / "report.md") # a harmless link
LAB = TMP / "homelab"
(LAB / "services" / "mail" / "data").mkdir(parents=True)
(LAB / "services" / "mail" / "docker-compose.yml").write_text("services: {}\n")
(LAB / "services" / "mail" / "data" / "inbox.mbox").write_text("From: x\n")
(LAB / "services" / "traefik" / "config").mkdir(parents=True)
(LAB / "services" / "traefik" / "config" / "acme.json").write_text("{}\n")
(LAB / "data" / "tmp").mkdir(parents=True)
(LAB / "data" / "tmp" / "token.txt").write_text("x\n")
(LAB / "data" / "log").mkdir(parents=True)
(LAB / "data" / "log" / "2026-11-02-x.md").write_text("# log\n")
(LAB / "scripts").mkdir(parents=True)
(LAB / "scripts" / "deploy.sh").write_text("#!/bin/sh\n")
(TMP / "services" / "traefik").mkdir(parents=True)
(TMP / "services" / "traefik" / "traefik.yml").write_text("http: {}\n")
from fastapi.testclient import TestClient # noqa: E402
import main # noqa: E402
from files import hostfiles # noqa: E402
from users.caller import OWNER, SESSION_COOKIE # noqa: E402
DEPS = main.app.state.ai
OWNER_H = {"X-Internal-Auth": "tok"}
class HostFiles(unittest.TestCase):
def setUp(self):
for u in DEPS.users.all():
DEPS.users.delete(u["id"])
self.dom = DEPS.users.create("dom@example.com", "Dom", projects={"film": "view"})
self.cookie = DEPS.auth.open_session(self.dom["id"])
self.owner = TestClient(main.app)
def guest(self):
c = TestClient(main.app, base_url="https://claude.example.test")
c.cookies.set(SESSION_COOKIE, self.cookie)
return c
def guest_caller(self):
from users.caller import guest_from_record
return guest_from_record(DEPS.users.get(self.dom["id"]))
# ── resolve ──────────────────────────────────────────────────────────────
def test_spellings_of_a_project_path(self):
for p in ("/home/gabrielvidal/projects/film/notes/report.md",
"~/projects/film/notes/report.md",
"$HOME/projects/film/notes/report.md"):
r = hostfiles.resolve(OWNER, p)
self.assertIsNotNone(r, p)
self.assertEqual(r.host, "~/projects/film/notes/report.md")
self.assertEqual((r.project, r.rel), ("film", "notes/report.md"))
def test_relative_and_climbing_paths_do_not_resolve(self):
for p in ("projects/film/notes/report.md", "notes/report.md",
"~/projects/film/../other/plan.md", "/etc/passwd", ""):
self.assertIsNone(hostfiles.resolve(OWNER, p), p)
def test_secrets_and_noise_never_resolve(self):
for p in ("~/projects/film/.env", "~/projects/film/deploy.pem",
"~/projects/film/node_modules/x/index.js",
"~/projects/film/.git/config"):
self.assertIsNone(hostfiles.resolve(OWNER, p), p)
self.assertIsNotNone(hostfiles.resolve(OWNER, "~/projects/film/.env.example"))
def test_a_symlink_out_of_the_root_does_not_resolve(self):
self.assertIsNone(hostfiles.resolve(OWNER, "~/projects/film/escape.md"))
def test_a_symlink_to_a_secret_inside_the_root_does_not_resolve(self):
"""The secret filter looks at what a path *is*, not only at what it
is called: `notes/innocent.txt → .env` reads the .env."""
self.assertIsNone(hostfiles.resolve(OWNER, "~/projects/film/notes/innocent.txt"))
guest = self.guest_caller()
self.assertIsNone(hostfiles.resolve(guest, "~/projects/film/notes/innocent.txt"))
self.assertEqual(self.guest().get("/api/host-file/raw", params={
"path": "~/projects/film/notes/innocent.txt"}).status_code, 404)
self.assertIsNotNone(hostfiles.resolve(guest, "~/projects/film/notes/alias.cfg"))
names = [e["name"] for e in hostfiles.list_dir(
hostfiles.resolve(guest, "~/projects/film/notes"))["entries"]]
self.assertIn("alias.cfg", names)
self.assertNotIn("innocent.txt", names)
def test_a_guest_reaches_only_granted_projects(self):
g = self.guest_caller()
self.assertIsNotNone(hostfiles.resolve(g, "~/projects/film/notes/report.md"))
self.assertIsNone(hostfiles.resolve(g, "~/projects/other/plan.md"))
self.assertIsNone(hostfiles.resolve(g, "~/homelab/scripts/deploy.sh"))
def test_kinds(self):
self.assertEqual(hostfiles.kind_of("a.md"), "markdown")
self.assertEqual(hostfiles.kind_of("a.tsv"), "csv")
self.assertEqual(hostfiles.kind_of("a.webp"), "image")
self.assertEqual(hostfiles.kind_of("a.pdf"), "pdf")
self.assertEqual(hostfiles.kind_of("a.xlsx"), "binary")
# ── through the file-explorer bridge + the raw route ─────────────────────
# The JSON routes (/api/host-file, /api/host-files, /api/host-files/recent)
# are the file-explorer plugin's ``hostfiles.read`` bridge now; every
# confinement the routes had is asserted on the bridge, over HTTP.
BRIDGE = "/proxy/tools/plugins/fx/hub"
@classmethod
def setUpClass(cls):
import json as _json
from plugins.store import OWNER_UID
d = TMP / "src-plugins" / "fx"
d.mkdir(parents=True, exist_ok=True)
(d / "plugin.json").write_text(_json.dumps({
"schema": 1, "id": "fx", "name": "fx", "version": "1.0.0", "description": "t",
"capabilities": ["hostfiles.read"], "managed": {"defaultForGuests": True},
"actions": {"noop": {"script": "noop.py", "readOnly": True}}}))
(d / "noop.py").write_text("print('{}')\n")
DEPS.plugin_store.install(OWNER_UID, str(d), is_owner=True, approve=True)
def bridge(self, who: str, route: str, **params):
from plugins.store import OWNER_UID
from toolproxy import access
uid = OWNER_UID if who == "owner" else self.dom["id"]
tok = access.mint_handler(uid, "fx", ttl=300)
return self.owner.get(f"{self.BRIDGE}/{route}", params=params,
headers={"Authorization": f"Bearer {tok}"})
def test_guest_reads_a_report(self):
r = self.bridge("guest", "host-file", path="/home/x/projects/film/notes/report.md")
self.assertEqual(r.status_code, 200, r.text)
j = r.json()
self.assertEqual(j["kind"], "markdown")
self.assertEqual(j["content"], "# Report\n\nok\n")
self.assertEqual(j["dir"], "~/projects/film/notes")
self.assertEqual(j["project"], "film")
def test_guest_gets_404_outside_their_projects_and_on_secrets(self):
g = self.guest()
for p in ("~/projects/other/plan.md", "~/projects/film/.env",
"~/homelab/services/traefik/traefik.yml", "~/projects/film/nope.md",
"~/projects/film/notes/innocent.txt", "~/projects/film/escape.md",
"~/projects/film/deploy.pem", "~/projects/film/node_modules/x/index.js"):
self.assertEqual(self.bridge("guest", "host-file", path=p).status_code, 404, p)
self.assertEqual(g.get("/api/host-file/raw", params={"path": p}).status_code, 404, p)
for p in ("~/projects/other", "~/homelab", "~/worktrees/x", "~/projects/film/node_modules"):
self.assertEqual(self.bridge("guest", "host-files", path=p).status_code, 404, p)
def test_binary_has_no_content_and_raw_is_a_download(self):
j = self.bridge("guest", "host-file", path="~/projects/film/notes/blob.bin").json()
self.assertEqual((j["kind"], j["content"]), ("binary", None))
r = self.guest().get("/api/host-file/raw", params={"path": "~/projects/film/notes/report.md"})
self.assertEqual(r.status_code, 200)
self.assertIn("attachment", r.headers.get("content-disposition", ""))
self.assertEqual(r.headers.get("x-content-type-options"), "nosniff")
def test_listing_hides_secrets_and_noise(self):
j = self.bridge("guest", "host-files", path="~/projects/film").json()
names = [e["name"] for e in j["entries"]]
self.assertEqual(names[0], "notes") # folders first
self.assertIn(".env.example", names)
for n in (".env", "deploy.pem", "node_modules"):
self.assertNotIn(n, names)
self.assertNotIn("escape.md", names)
self.assertIsNone(j["parent"])
sub = self.bridge("guest", "host-files", path="~/projects/film/notes").json()
self.assertEqual(sub["parent"], "~/projects/film")
self.assertNotIn("innocent.txt", [e["name"] for e in sub["entries"]])
def test_recent_documents(self):
j = self.bridge("guest", "host-files/recent", project="film").json()
names = {e["name"] for e in j["entries"]}
self.assertEqual(names, {"report.md", "data.csv"})
self.assertEqual(self.bridge("guest", "host-files/recent", project="other").status_code, 404)
def test_roots(self):
g = [x["path"] for x in self.bridge("guest", "host-files/roots").json()["roots"]]
self.assertEqual(g, ["~/projects/film"])
o = [x["path"] for x in self.bridge("owner", "host-files/roots").json()["roots"]]
self.assertIn("~/projects/other", o)
self.assertIn("~/homelab", o)
def test_owner_reaches_the_whole_homelab_but_its_runtime_state(self):
for p in ("~/homelab/scripts/deploy.sh", "~/homelab/data/log/2026-11-02-x.md",
"/home/u/homelab/services/mail/docker-compose.yml"):
self.assertIsNotNone(hostfiles.resolve(OWNER, p), p)
for p in ("~/homelab/services/mail/data/inbox.mbox", "~/homelab/data/tmp/token.txt",
"~/homelab/services/traefik/config/acme.json", "~/homelab/.env"):
self.assertIsNone(hostfiles.resolve(OWNER, p), p)
self.assertEqual(self.bridge("owner", "host-file", path=p).status_code, 404, p)
j = self.bridge("owner", "host-files", path="~/homelab/services/mail").json()
self.assertEqual([e["name"] for e in j["entries"]], ["docker-compose.yml"])
self.assertIsNone(hostfiles.resolve(self.guest_caller(), "~/homelab/scripts/deploy.sh"))
def test_owner_reaches_services(self):
r = self.bridge("owner", "host-file", path="~/homelab/scripts/deploy.sh")
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(r.json()["kind"], "text")
def test_legacy_json_routes_are_retired(self):
paths = set(main.app.openapi()["paths"])
for p in ("/api/host-file", "/api/host-files", "/api/host-files/recent",
"/api/bundle", "/api/file"):
self.assertNotIn(p, paths, p)
self.assertIn("/api/host-file/raw", paths)
if __name__ == "__main__":
unittest.main()