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>
247 lines
13 KiB
Python
247 lines
13 KiB
Python
"""The hub bridges behind the ``file-explorer`` and ``context-editor`` live
|
|
plugins: ``hostfiles.read`` (caller-scoped), ``context.read`` (owner-only),
|
|
``context.write`` (owner-only, handler-only), and manifest capability checks."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
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 / "ws", "REPO_DIR": TMP / "ws", "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",
|
|
"ROLES_PATH": TMP / "roles.json", "ASKFORM_PATH": TMP / "af.db",
|
|
"PLUGINS_DIR": TMP / "plugins", "PROJECTS_DIR": TMP / "projects",
|
|
"SERVICES_DIR": TMP / "services", "WORKTREES_DIR": TMP / "worktrees",
|
|
"HOMELAB_DIR": TMP / "homelab", "INTERNAL_API_TOKEN": "tok",
|
|
"SIDECAR_TOKEN": "", "PI_TRANSCRIPTS_DIR": "",
|
|
}.items():
|
|
os.environ.setdefault(k, str(v))
|
|
|
|
WS = pathlib.Path(os.environ["WORKSPACE"])
|
|
PROJ = pathlib.Path(os.environ["PROJECTS_DIR"])
|
|
HL = pathlib.Path(os.environ["HOMELAB_DIR"])
|
|
(WS / ".claude" / "skills" / "demo").mkdir(parents=True, exist_ok=True)
|
|
(WS / "data" / "notes").mkdir(parents=True, exist_ok=True)
|
|
(WS / "CLAUDE.md").write_text("# Root instructions\n\nHello.\n", encoding="utf-8")
|
|
(WS / ".claude" / "skills" / "demo" / "SKILL.md").write_text("# Demo skill\n", encoding="utf-8")
|
|
(WS / "data" / "notes" / "log.md").write_text("# Read only log\n", encoding="utf-8")
|
|
(WS / "secret.txt").write_text("not a context file\n", encoding="utf-8")
|
|
|
|
(PROJ / "film" / "notes").mkdir(parents=True, exist_ok=True)
|
|
(PROJ / "film" / "notes" / "report.md").write_text("# Film report\n", encoding="utf-8")
|
|
(PROJ / "film" / ".env").write_text("SECRET=1\n", encoding="utf-8")
|
|
(PROJ / "other").mkdir(parents=True, exist_ok=True)
|
|
(PROJ / "other" / "plan.md").write_text("# Private\n", encoding="utf-8")
|
|
(HL / "scripts").mkdir(parents=True, exist_ok=True)
|
|
(HL / "scripts" / "deploy.sh").write_text("#!/bin/sh\n", encoding="utf-8")
|
|
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
|
|
import main # noqa: E402
|
|
from plugins.manifest import capability_summary, requires_operator, validate_manifest # noqa: E402
|
|
from plugins.store import OWNER_UID # noqa: E402
|
|
from toolproxy import access # noqa: E402
|
|
|
|
DEPS = main.app.state.ai
|
|
|
|
|
|
def _make_plugin(root: pathlib.Path, pid: str, caps: list[str], *, managed: bool = False) -> pathlib.Path:
|
|
d = root / pid
|
|
d.mkdir(parents=True, exist_ok=True)
|
|
mf: dict = {
|
|
"schema": 1, "id": pid, "name": pid, "version": "1.0.0",
|
|
"description": "test plugin", "capabilities": caps,
|
|
"actions": {"noop": {"script": "noop.py", "readOnly": True}},
|
|
}
|
|
if managed:
|
|
mf["managed"] = {"defaultForGuests": True}
|
|
(d / "plugin.json").write_text(json.dumps(mf), encoding="utf-8")
|
|
(d / "noop.py").write_text("import json; print(json.dumps({'ok': True}))\n", encoding="utf-8")
|
|
return d
|
|
|
|
|
|
class FilesPluginBridgeTests(unittest.TestCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls.client = TestClient(main.app)
|
|
DEPS.indexer.scan_files(force_walk=True)
|
|
cls.pdir = TMP / "src-plugins"
|
|
cls.fe_dir = _make_plugin(cls.pdir, "file-explorer", ["hostfiles.read"], managed=True)
|
|
cls.ce_dir = _make_plugin(cls.pdir, "context-editor", ["context.read", "context.write"])
|
|
cls.bare_dir = _make_plugin(cls.pdir, "bare-files", [])
|
|
for d in (cls.fe_dir, cls.ce_dir, cls.bare_dir):
|
|
DEPS.plugin_store.install(OWNER_UID, str(d), is_owner=True, approve=True)
|
|
cls.guest = DEPS.users.create("dom@example.com", "Dom", projects={"film": "view"})
|
|
|
|
def _hdr(self, uid: str, pid: str, *, handler: bool = True) -> dict[str, str]:
|
|
tok = access.mint_handler(uid, pid, ttl=300) if handler else access.mint(uid, ttl=300)
|
|
return {"Authorization": f"Bearer {tok}"}
|
|
|
|
# ── manifest checks ──────────────────────────────────────────────────────
|
|
def test_manifest_operator_requirements_and_summary(self):
|
|
fe_plain = validate_manifest(_make_plugin(self.pdir, "fe-plain", ["hostfiles.read"]))
|
|
ce = validate_manifest(self.ce_dir)
|
|
self.assertTrue(requires_operator(fe_plain)) # ~/homelab for the owner: operator only
|
|
self.assertTrue(requires_operator(ce))
|
|
fe_labels = " ".join(c["label"] for c in capability_summary(fe_plain))
|
|
ce_labels = " ".join(c["label"] for c in capability_summary(ce))
|
|
self.assertIn("projects", fe_labels)
|
|
self.assertIn("CLAUDE.md", ce_labels)
|
|
|
|
# ── hostfiles.read ───────────────────────────────────────────────────────
|
|
def test_hostfiles_guest_scope_and_secrets(self):
|
|
h = self._hdr(self.guest["id"], "file-explorer")
|
|
r = self.client.get("/proxy/tools/plugins/file-explorer/hub/host-file",
|
|
params={"path": "~/projects/film/notes/report.md"}, headers=h)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(r.json()["content"], "# Film report\n")
|
|
|
|
# Listing hides .env and returns folders first
|
|
r = self.client.get("/proxy/tools/plugins/file-explorer/hub/host-files",
|
|
params={"path": "~/projects/film"}, headers=h)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
names = [e["name"] for e in r.json()["entries"]]
|
|
self.assertEqual(names, ["notes"])
|
|
|
|
# Recent docs for granted project work; ungranted 404s
|
|
r = self.client.get("/proxy/tools/plugins/file-explorer/hub/host-files/recent",
|
|
params={"project": "film"}, headers=h)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual([e["name"] for e in r.json()["entries"]], ["report.md"])
|
|
r = self.client.get("/proxy/tools/plugins/file-explorer/hub/host-files/recent",
|
|
params={"project": "other"}, headers=h)
|
|
self.assertEqual(r.status_code, 404)
|
|
|
|
# Denied paths & secrets always 404
|
|
for p in ("~/projects/film/.env", "~/projects/other/plan.md", "~/homelab/scripts/deploy.sh"):
|
|
r = self.client.get("/proxy/tools/plugins/file-explorer/hub/host-file",
|
|
params={"path": p}, headers=h)
|
|
self.assertEqual(r.status_code, 404, p)
|
|
|
|
def test_roots_are_the_callers_own(self):
|
|
gh = self._hdr(self.guest["id"], "file-explorer")
|
|
r = self.client.get("/proxy/tools/plugins/file-explorer/hub/host-files/roots", headers=gh)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual([x["path"] for x in r.json()["roots"]], ["~/projects/film"])
|
|
oh = self._hdr(OWNER_UID, "file-explorer")
|
|
paths = [x["path"] for x in self.client.get(
|
|
"/proxy/tools/plugins/file-explorer/hub/host-files/roots", headers=oh).json()["roots"]]
|
|
self.assertIn("~/projects/other", paths)
|
|
self.assertIn("~/homelab", paths)
|
|
|
|
def test_a_run_token_reads_like_its_person(self):
|
|
"""The plugin's skill/CLI (a run token, not a handler) reads with the
|
|
same reach as the person — a guest's never widens."""
|
|
h = self._hdr(self.guest["id"], "file-explorer", handler=False)
|
|
ok = self.client.get("/proxy/tools/plugins/file-explorer/hub/host-file",
|
|
params={"path": "~/projects/film/notes/report.md"}, headers=h)
|
|
self.assertEqual(ok.status_code, 200, ok.text)
|
|
no = self.client.get("/proxy/tools/plugins/file-explorer/hub/host-file",
|
|
params={"path": "~/projects/other/plan.md"}, headers=h)
|
|
self.assertEqual(no.status_code, 404)
|
|
|
|
def test_a_machine_token_reads_nothing(self):
|
|
"""A paired machine's proxy token is the owner (or a guest computer's
|
|
guest) on the tool-proxy door — never a reader of host or context
|
|
files, which /api/host-file and /api/bundle never answered either."""
|
|
DEPS.worker_store.put({"id": "mac", "name": "mac", "url": "http://x", "token": "t",
|
|
"proxyToken": "m" * 43})
|
|
DEPS.worker_store.put({"id": "gpc", "name": "pc", "url": "http://x", "token": "t",
|
|
"owner": self.guest["id"], "proxyToken": "g" * 43})
|
|
try:
|
|
for tok in ("m" * 43, "g" * 43):
|
|
h = {"Authorization": f"Bearer {tok}"}
|
|
r = self.client.get("/proxy/tools/plugins/file-explorer/hub/host-file",
|
|
params={"path": "~/projects/film/notes/report.md"}, headers=h)
|
|
self.assertEqual(r.status_code, 403, r.text)
|
|
r = self.client.get("/proxy/tools/plugins/file-explorer/hub/host-files/roots", headers=h)
|
|
self.assertEqual(r.status_code, 403, r.text)
|
|
h = {"Authorization": "Bearer " + "m" * 43}
|
|
r = self.client.get("/proxy/tools/plugins/context-editor/hub/context/bundle", headers=h)
|
|
self.assertEqual(r.status_code, 403, r.text)
|
|
r = self.client.get("/proxy/tools/plugins/context-editor/hub/context/file",
|
|
params={"path": "CLAUDE.md"}, headers=h)
|
|
self.assertEqual(r.status_code, 403, r.text)
|
|
finally:
|
|
DEPS.worker_store.delete("mac")
|
|
DEPS.worker_store.delete("gpc")
|
|
|
|
def test_no_token_no_read(self):
|
|
r = self.client.get("/proxy/tools/plugins/file-explorer/hub/host-file",
|
|
params={"path": "~/projects/film/notes/report.md"})
|
|
self.assertIn(r.status_code, (401, 403))
|
|
|
|
def test_hostfiles_owner_reaches_homelab_and_missing_cap_refused(self):
|
|
h = self._hdr(OWNER_UID, "file-explorer")
|
|
r = self.client.get("/proxy/tools/plugins/file-explorer/hub/host-file",
|
|
params={"path": "~/homelab/scripts/deploy.sh"}, headers=h)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(r.json()["kind"], "text")
|
|
|
|
# Plugin without hostfiles.read gets 403
|
|
hb = self._hdr(OWNER_UID, "bare-files")
|
|
r = self.client.get("/proxy/tools/plugins/bare-files/hub/host-file",
|
|
params={"path": "~/projects/film/notes/report.md"}, headers=hb)
|
|
self.assertEqual(r.status_code, 403)
|
|
|
|
# ── context.read & context.write ─────────────────────────────────────────
|
|
def test_context_read_owner_only(self):
|
|
h = self._hdr(OWNER_UID, "context-editor")
|
|
r = self.client.get("/proxy/tools/plugins/context-editor/hub/context/bundle", headers=h)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
paths = {f["path"] for f in r.json()["files"]}
|
|
self.assertIn("CLAUDE.md", paths)
|
|
self.assertIn(".claude/skills/demo/SKILL.md", paths)
|
|
self.assertIn("data/notes/log.md", paths)
|
|
self.assertNotIn("secret.txt", paths)
|
|
|
|
r = self.client.get("/proxy/tools/plugins/context-editor/hub/context/file",
|
|
params={"path": "CLAUDE.md"}, headers=h)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertIn("Root instructions", r.json()["content"])
|
|
self.assertTrue(r.json()["editable"])
|
|
|
|
# Non-context file refused
|
|
r = self.client.get("/proxy/tools/plugins/context-editor/hub/context/file",
|
|
params={"path": "secret.txt"}, headers=h)
|
|
self.assertEqual(r.status_code, 403)
|
|
|
|
# Guest refused
|
|
gh = self._hdr(self.guest["id"], "context-editor")
|
|
r = self.client.get("/proxy/tools/plugins/context-editor/hub/context/bundle", headers=gh)
|
|
self.assertEqual(r.status_code, 403)
|
|
|
|
def test_context_write_handler_only_and_editable_check(self):
|
|
h = self._hdr(OWNER_UID, "context-editor", handler=True)
|
|
r = self.client.put("/proxy/tools/plugins/context-editor/hub/context/file",
|
|
json={"path": "CLAUDE.md", "content": "# Updated\n"}, headers=h)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(r.json()["content"], "# Updated\n")
|
|
self.assertEqual((WS / "CLAUDE.md").read_text(encoding="utf-8"), "# Updated\n")
|
|
|
|
# Read-only data/ file cannot be written
|
|
r = self.client.put("/proxy/tools/plugins/context-editor/hub/context/file",
|
|
json={"path": "data/notes/log.md", "content": "hacked"}, headers=h)
|
|
self.assertEqual(r.status_code, 403)
|
|
|
|
# Non-handler (skill/run) token refused
|
|
nh = self._hdr(OWNER_UID, "context-editor", handler=False)
|
|
r = self.client.put("/proxy/tools/plugins/context-editor/hub/context/file",
|
|
json={"path": "CLAUDE.md", "content": "nope"}, headers=nh)
|
|
self.assertEqual(r.status_code, 403)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|