Files
ai-agent/backend/test_plugin_catalog_bridge.py
gabrielvidalandClaude Opus 5.5 34a8e4a8eb feat(plugins): an install bridge for the plugin-catalog plugin
A sandboxed frame may now ask the host to install or uninstall a plugin of
the public catalog — never do it itself (form
plugin-catalog-and-public-plugins-repo_al2ibd):

- New operator-only capability `plugins.manage` (in the approval
  fingerprint). aiAgentPlugin.plugins.list() / .install({source}) /
  .uninstall({id}) answer only the operator, and only a plugin of theirs that
  holds it (enabled, approved); anyone else gets a refusal.
- An install source must be `<catalogRepo>#plugins/<id>`; the host validates
  it (refreshed clone), checks the folder holds that id and draws the
  confirmation — name, version, source, every capability, what an update
  replaces — before its own POST /api/plugins/install. An uninstall asks keep
  or delete data and secrets each time. A plugin can't uninstall itself.
- PLUGIN_CATALOG_REPO (plugins/catalog_repo.py, default the public mirror
  gabrielvidal/ai-agent-plugins-public.git), served as `catalogRepo` on
  GET /api/plugins to the operator only.
- Settings → Plugins (operator): All / Installed / Available gives way to
  *Browse the catalog* (the page that opens `plugin-catalog`); promoted hub
  catalog entries wear *For guests*; old ?show=available / ?tab=catalog&kind=
  links redirect to the plugin's page on that shelf; with the plugin off, a
  note offers to install it again. Guests' page unchanged.

Tests: test_plugin_catalog_bridge.py (capability, repo rule, guest kept out),
catalogBridge.test.tsx (refusals, confirm-then-install, cancel, keep/delete).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 20:07:05 +01:00

147 lines
7.4 KiB
Python

"""The plugin catalog's install bridge (since 2026-11-28): the
``plugins.manage`` capability (operator-only, in the approval fingerprint),
the catalog repository a frame may install from (``plugins/catalog_repo.py``,
``catalogRepo`` on ``GET /api/plugins`` — the owner's only), and a guest kept
out of all of it."""
from __future__ import annotations
import json
import os
import pathlib
import tempfile
import unittest
from unittest.mock import patch
TMP = pathlib.Path(tempfile.mkdtemp())
for k, v in {"DB_PATH": TMP / "x.db", "TRANSCRIPTS_DIR": TMP / "t", "WORKSPACE": TMP, "REPO_DIR": TMP,
"META_PATH": TMP / "meta.json", "USERS_PATH": TMP / "users.json", "AUTH_PATH": TMP / "auth.json",
"PROJECTS_DIR": TMP / "projects", "INTERNAL_API_TOKEN": "tok",
"GUEST_HOSTS": "claude.example.test",
"SIDECAR_TOKEN": "", "PI_TRANSCRIPTS_DIR": ""}.items():
os.environ.setdefault(k, str(v))
from fastapi.testclient import TestClient # noqa: E402
import main # noqa: E402
from plugins import catalog_repo # noqa: E402
from plugins.manifest import ( # noqa: E402
ManifestError, capability_fingerprint, capability_summary, requires_operator, validate_manifest,
)
from plugins.store import OWNER_UID, PluginStore # noqa: E402
from users.caller import SESSION_COOKIE # noqa: E402
DEPS = main.app.state.ai
OWNER_H = {"X-Internal-Auth": "tok"}
REPO = catalog_repo.DEFAULT_REPO
BASE = {
"schema": 1, "id": "plugin-catalog", "name": "Plugin catalog", "version": "1.0.0",
"description": "Browse and install plugins", "category": "agents",
"capabilities": ["plugins.manage"],
"actions": {"catalog": {"script": "handlers/catalog.py", "readOnly": True, "ownerOnly": True}},
"ui": {"pages": [{"id": "catalog", "label": "Plugin catalog", "nav": "settings", "group": "tools",
"after": "plugins", "html": "ui/catalog.html", "perm": "plugins.manage",
"opens": ["plugin-catalog"]}]},
}
def _write(root: pathlib.Path, manifest: dict) -> pathlib.Path:
(root / "handlers").mkdir(parents=True, exist_ok=True)
(root / "ui").mkdir(parents=True, exist_ok=True)
(root / "handlers" / "catalog.py").write_text("print('{}')\n", encoding="utf-8")
(root / "ui" / "catalog.html").write_text("<div></div>\n", encoding="utf-8")
(root / "plugin.json").write_text(json.dumps(manifest), encoding="utf-8")
return root
class Capability(unittest.TestCase):
def test_known_operator_only_and_fingerprinted(self):
with tempfile.TemporaryDirectory() as td:
mf = validate_manifest(_write(pathlib.Path(td) / "a", BASE))
self.assertEqual(mf["capabilities"], ["plugins.manage"])
self.assertTrue(requires_operator(mf))
labels = " ".join(c["label"] for c in capability_summary(mf))
self.assertIn("install or uninstall plugins", labels)
bare = validate_manifest(_write(pathlib.Path(td) / "b", {**BASE, "capabilities": []}))
self.assertFalse(requires_operator(bare))
# widening to it asks for approval again
self.assertNotEqual(capability_fingerprint(mf), capability_fingerprint(bare))
def test_a_typo_is_refused(self):
with tempfile.TemporaryDirectory() as td:
with self.assertRaises(ManifestError):
validate_manifest(_write(pathlib.Path(td) / "a", {**BASE, "capabilities": ["plugin.manage"]}))
class Repo(unittest.TestCase):
def test_default_and_override(self):
with patch.dict(os.environ, {"PLUGIN_CATALOG_REPO": ""}):
self.assertEqual(catalog_repo.repo(), REPO)
with patch.dict(os.environ, {"PLUGIN_CATALOG_REPO": "https://git.example.com/a/b.git"}):
self.assertEqual(catalog_repo.repo(), "https://git.example.com/a/b.git")
for bad in ("http://git.example.com/a/b.git", "https://git.example.com/a/b", "file:///x.git",
"https://git.example.com/a/b.git#plugins/x", "https://h/a b.git"):
with patch.dict(os.environ, {"PLUGIN_CATALOG_REPO": bad}):
self.assertIsNone(catalog_repo.repo(), bad)
def test_sources_of_the_catalog_only(self):
ok = catalog_repo.plugin_id_of
self.assertEqual(ok(f"{REPO}#plugins/charts", REPO), "charts")
for bad in (f"{REPO}#plugins/../x", f"{REPO}#plugins/a/b", f"{REPO}#plugins/", f"{REPO}#other/x",
f"{REPO}", "https://evil.example/x.git#plugins/charts", "/home/x/plugins/charts",
f"{REPO}x#plugins/charts", f"{REPO}#plugins/Charts", None):
self.assertIsNone(ok(bad, REPO), bad)
class Api(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={})
self.cookie = DEPS.auth.open_session(self.dom["id"])
def guest(self):
c = TestClient(main.app, base_url="https://claude.example.test")
c.cookies.set(SESSION_COOKIE, self.cookie)
return c
def test_owner_gets_the_repo_a_guest_doesnt(self):
with tempfile.TemporaryDirectory() as td:
store = PluginStore(pathlib.Path(td) / "data")
store.install(OWNER_UID, str(_write(pathlib.Path(td) / "p", BASE)), is_owner=True, approve=True)
with patch.object(DEPS, "plugin_store", store):
owner = TestClient(main.app, headers=OWNER_H).get("/api/plugins").json()
self.assertEqual(owner["catalogRepo"], catalog_repo.repo())
page = [p for p in owner["ui"]["pages"] if p["pluginId"] == "plugin-catalog"]
self.assertEqual(page[0]["opens"], ["plugin-catalog"])
r = self.guest().get("/api/plugins")
self.assertEqual(r.status_code, 200, r.text)
g = r.json()
self.assertIsNone(g["catalogRepo"])
self.assertFalse([p for p in g["ui"]["pages"] if p["pluginId"] == "plugin-catalog"])
self.assertFalse([p for p in g["installed"] if p["id"] == "plugin-catalog"])
# the app-wide UI list: no page for the guest either
r = self.guest().get("/api/plugins/ui")
self.assertEqual(r.status_code, 200, r.text)
self.assertFalse([p for p in r.json()["ui"]["pages"] if p["pluginId"] == "plugin-catalog"])
def test_a_guest_can_neither_install_it_nor_run_its_actions(self):
with tempfile.TemporaryDirectory() as td:
store = PluginStore(pathlib.Path(td) / "data")
src = _write(pathlib.Path(td) / "p", BASE)
# the store itself: an operator-only capability is the operator's
with self.assertRaises(ManifestError):
store.install(self.dom["id"], str(src), is_owner=False, approve=True)
store.install(OWNER_UID, str(src), is_owner=True, approve=True)
with patch.object(DEPS, "plugin_store", store):
r = self.guest().post("/api/plugins/install", json={"source": str(src), "approve": True})
self.assertIn(r.status_code, (400, 403), r.text)
r = self.guest().post("/api/plugins/plugin-catalog/actions/catalog", json={})
self.assertIn(r.status_code, (403, 404), r.text)
r = self.guest().get("/api/plugins/plugin-catalog/ui/page/catalog")
self.assertIn(r.status_code, (403, 404), r.text)
if __name__ == "__main__":
unittest.main()