Files
ai-agent/backend/test_plugin_grants_bridge.py

216 lines
10 KiB
Python

"""The ``hub/grants`` bridge (a managed plugin's own per-guest grants, read and
written by its owner handlers) and ``AIA_USER_CONTEXT.email``."""
from __future__ import annotations
import json
import os
import pathlib
import sys
import tempfile
import unittest
BACKEND = pathlib.Path(__file__).resolve().parent
sys.path.insert(0, str(BACKEND))
_TMP = tempfile.TemporaryDirectory()
_DATA = pathlib.Path(_TMP.name)
os.environ.setdefault("DB_PATH", str(_DATA / "ai-agent.db"))
os.environ.setdefault("META_PATH", str(_DATA / "meta.json"))
os.environ.setdefault("TRANSCRIPTS_DIR", str(_DATA / "transcripts"))
os.environ.setdefault("WORKSPACE", str(_DATA / "workspace"))
os.environ.setdefault("REPO_DIR", str(_DATA / "workspace"))
os.environ.setdefault("PLUGINS_DIR", str(_DATA / "plugins"))
os.environ.setdefault("UI_STATE_PATH", str(_DATA / "ui-state.json"))
os.environ.setdefault("USERS_PATH", str(_DATA / "users.json"))
os.environ.setdefault("AUTH_PATH", str(_DATA / "auth.json"))
os.environ.setdefault("TOOLS_TOKEN_KEY", str(_DATA / "tools.key"))
os.environ.setdefault("CRON_PATH", str(_DATA / "cron.json"))
os.environ.setdefault("SECURITY_PATH", str(_DATA / "security.json"))
os.environ.setdefault("WORKERS_PATH", str(_DATA / "workers.json"))
os.environ.setdefault("PROFILES_PATH", str(_DATA / "profiles.json"))
os.environ.setdefault("PUSH_PATH", str(_DATA / "push.json"))
os.environ.setdefault("NOTIFY_PATH", str(_DATA / "notify.json"))
os.environ.setdefault("MCP_PATH", str(_DATA / "mcp.json"))
os.environ.setdefault("ASKFORM_PATH", str(_DATA / "askform.json"))
os.environ.setdefault("DRAFTS_PATH", str(_DATA / "drafts.json"))
os.environ.setdefault("TOOL_LEDGER_PATH", str(_DATA / "ledger.jsonl"))
from fastapi import FastAPI # noqa: E402
from fastapi.testclient import TestClient # noqa: E402
import core.auth as auth_mod # noqa: E402
import plugins.hubbridge as hubbridge # noqa: E402
import plugins.proxyroutes as proxyroutes # noqa: E402
import plugins.routes as plugin_routes # noqa: E402
from core.state import build_state # noqa: E402
from plugins import runner # noqa: E402
from plugins.store import OWNER_UID, PluginStore # noqa: E402
from toolproxy import access as tp_access # noqa: E402
CTX_SCRIPT = (
"import json, os\n"
"print(json.dumps(json.loads(os.environ['AIA_USER_CONTEXT'])))\n"
)
GRANT_FIELDS = [
{"key": "fromName", "label": "From name", "type": "text", "default": ""},
{"key": "perDay", "label": "Per day", "type": "number", "default": 10},
{"key": "mode", "label": "Mode", "type": "select", "options": ["a", "b"], "default": "a"},
]
def _make_plugin(root: pathlib.Path, pid: str, manifest: dict) -> pathlib.Path:
d = root / pid
d.mkdir(parents=True, exist_ok=True)
(d / "ctx.py").write_text(CTX_SCRIPT, encoding="utf-8")
(d / "plugin.json").write_text(json.dumps({
"schema": 1, "id": pid, "name": pid.title(),
"actions": {"ctx": {"script": "ctx.py"}}, **manifest,
}), encoding="utf-8")
return d
class GrantsBridgeTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.root = pathlib.Path(self.tmp.name)
self.deps = build_state()
self.deps.plugin_store = PluginStore(self.root / "plugins")
if not self.deps.users.get("gina"):
self.deps.users.create("gina@example.com", "Gina")
self.events = []
orig = self.deps.hub.publish
self.deps.hub.publish = lambda ev: (self.events.append(ev), orig(ev))[1]
self.addCleanup(setattr, self.deps.hub, "publish", orig)
self.app = FastAPI()
auth_mod.install(self.app)
self.app.state.ai = self.deps
self.app.include_router(plugin_routes.router)
self.app.include_router(proxyroutes.router)
self.app.include_router(hubbridge.router)
self.client = TestClient(self.app)
def tearDown(self):
self.tmp.cleanup()
def _install(self, pid: str, *, managed=True, caps=("users.read",)):
mf: dict = {"capabilities": list(caps)}
if managed:
mf["managed"] = {"defaultForGuests": True, "grantFields": GRANT_FIELDS}
d = _make_plugin(self.root, pid, mf)
self.deps.plugin_store.install(OWNER_UID, str(d), is_owner=True, approve=True)
def _hdr(self, uid: str, pid: str) -> dict:
return {"Authorization": f"Bearer {tp_access.mint_handler(uid, pid, ttl=300)}"}
# ── AIA_USER_CONTEXT.email ──────────────────────────────────────────────
def test_user_context_email(self):
self._install("mailer")
rec = self.deps.plugin_store.get_raw(OWNER_UID, "mailer")
out = runner.run_script(self.deps, self.deps.plugin_store, "gina", rec, "ctx.py")
self.assertEqual(out["email"], "gina@example.com")
req = runner.requester_context(self.deps, "gina")
self.assertEqual(req["email"], "gina@example.com")
out = runner.run_script(self.deps, self.deps.plugin_store, OWNER_UID, rec, "ctx.py",
requester=req)
self.assertEqual(out["email"], "")
self.assertEqual(out["requester"]["email"], "gina@example.com")
self.assertEqual(runner.requester_context(self.deps, OWNER_UID)["email"], "")
self.assertEqual(runner._user_email(self.deps, "nobody"), "")
# ── GET / PUT hub/grants ────────────────────────────────────────────────
def test_list_and_update(self):
self._install("mailer")
hdr = self._hdr(OWNER_UID, "mailer")
r = self.client.get("/proxy/tools/plugins/mailer/hub/grants", headers=hdr)
self.assertEqual(r.status_code, 200, r.text)
body = r.json()
self.assertEqual(body["managed"]["grantFields"][0]["key"], "fromName")
row = next(g for g in body["grants"] if g["uid"] == "gina")
self.assertEqual(row["email"], "gina@example.com")
self.assertEqual(row["name"], "Gina")
self.assertTrue(row["grant"]["enabled"])
self.assertIn("usage", row)
self.events.clear()
r = self.client.put("/proxy/tools/plugins/mailer/hub/grants/gina", headers=hdr,
json={"enabled": False, "config": {"perDay": 3, "bogus": 1},
"monthlyBudgetUsd": 2.5})
self.assertEqual(r.status_code, 200, r.text)
g = r.json()["grant"]
self.assertTrue(r.json()["ok"])
self.assertFalse(g["enabled"])
self.assertEqual(g["config"]["perDay"], 3)
self.assertNotIn("bogus", g["config"])
self.assertEqual(g["monthlyBudgetUsd"], 2.5)
types = [e.get("type") for e in self.events]
self.assertIn("plugins", types)
self.assertIn("users", types)
mf = self.deps.plugin_store.get_raw(OWNER_UID, "mailer")["manifest"]
eff = self.deps.plugin_store.effective_grant("gina", "mailer", mf)
self.assertEqual(eff["config"]["perDay"], 3)
# Same store as the Users page's route.
from users.caller import OWNER
listed = plugin_routes.list_user_managed_grants(self.deps, OWNER, "gina")
row = next(p for p in listed["plugins"] if p["id"] == "mailer")
self.assertEqual(row["grant"]["config"]["perDay"], 3)
# Config merges; an omitted budget is left alone; null clears it.
r = self.client.put("/proxy/tools/plugins/mailer/hub/grants/gina", headers=hdr,
json={"config": {"mode": "b"}})
g = r.json()["grant"]
self.assertEqual((g["config"]["perDay"], g["config"]["mode"]), (3, "b"))
self.assertEqual(g["monthlyBudgetUsd"], 2.5)
r = self.client.put("/proxy/tools/plugins/mailer/hub/grants/gina", headers=hdr,
json={"monthlyBudgetUsd": None})
self.assertIsNone(r.json()["grant"]["monthlyBudgetUsd"])
def test_refusals(self):
self._install("mailer")
self._install("plain", managed=False)
self._install("nocap", caps=())
self._install("other")
owner = self._hdr(OWNER_UID, "mailer")
url = "/proxy/tools/plugins/{}/hub/grants"
r = self.client.put(url.format("mailer") + "/ghost", headers=owner, json={"enabled": True})
self.assertEqual(r.status_code, 404)
r = self.client.put(url.format("mailer") + "/owner", headers=owner, json={"enabled": True})
self.assertEqual(r.status_code, 404)
r = self.client.get(url.format("plain"), headers=self._hdr(OWNER_UID, "plain"))
self.assertEqual(r.status_code, 400)
r = self.client.put(url.format("plain") + "/gina", headers=self._hdr(OWNER_UID, "plain"),
json={})
self.assertEqual(r.status_code, 400)
r = self.client.get(url.format("nocap"), headers=self._hdr(OWNER_UID, "nocap"))
self.assertEqual(r.status_code, 403)
# A guest's handler of the same plugin: owner-only.
r = self.client.get(url.format("mailer"), headers=self._hdr("gina", "mailer"))
self.assertEqual(r.status_code, 403)
r = self.client.put(url.format("mailer") + "/gina", headers=self._hdr("gina", "mailer"),
json={"enabled": False})
self.assertEqual(r.status_code, 403)
# Not a handler: a plain run token.
run = {"Authorization": f"Bearer {tp_access.mint(OWNER_UID)}"}
r = self.client.get(url.format("mailer"), headers=run)
self.assertEqual(r.status_code, 403)
# Another plugin's handler token can't read / write this plugin's grants.
other = self._hdr(OWNER_UID, "other")
r = self.client.get(url.format("mailer"), headers=other)
self.assertEqual(r.status_code, 403)
r = self.client.put(url.format("mailer") + "/gina", headers=other, json={"enabled": False})
self.assertEqual(r.status_code, 403)
mf = self.deps.plugin_store.get_raw(OWNER_UID, "mailer")["manifest"]
self.assertTrue(self.deps.plugin_store.effective_grant("gina", "mailer", mf)["enabled"])
if __name__ == "__main__":
unittest.main()