Files
ai-agent/backend/test_plugins.py
gabrielvidalandClaude Opus 5.5 5a12241e82 fix(plugins): a guest's managed plugin skills reach their runs again
live_skill_dirs() named a guest's managed-plugin skills plugin:managed/<id>,
but the copies live in live-skills/owner/<id> and the sidecar reads the
folder straight from the ref — so no guest run ever got one: not
ask-approval, not movies, not new-frontend-project. Found by the approvals
end-to-end test: the guest's run had no shared:ask-approval.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 23:37:51 +01:00

322 lines
16 KiB
Python

"""Tests for the live user-plugins runtime (v1 + v2 + v3)."""
from __future__ import annotations
import asyncio
import json
import os
import pathlib
import tempfile
import unittest
from unittest.mock import patch
import httpx
import main
from plugins.egress import check_public_url, is_public_ip
from plugins.manifest import (
ManifestError,
capability_fingerprint,
capability_summary,
requires_operator,
validate_manifest,
)
from plugins.proxy import ProxyError, forward, run_inspect
from plugins.runner import run_script
from plugins.store import OWNER_UID, PluginStore
def _write_plugin(root: pathlib.Path, manifest: dict, *, files: dict[str, str] | None = None) -> pathlib.Path:
root.mkdir(parents=True, exist_ok=True)
(root / "plugin.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
for rel, content in (files or {}).items():
p = root / rel
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(content, encoding="utf-8")
return root
class TestPluginManifest(unittest.TestCase):
def test_valid_v1_v2_v3_manifest_and_fingerprint(self):
with tempfile.TemporaryDirectory() as td:
d = _write_plugin(pathlib.Path(td) / "meta", {
"schema": 1,
"id": "meta-test",
"name": "Meta Test",
"version": "1.0.0",
"skill": {"dir": "skill", "name": "meta-test"},
"secrets": [{"key": "token", "label": "Token"}],
"settings": {"subtitle": "Read-only", "fields": [{"key": "tz", "label": "TZ", "type": "text", "default": "UTC"}]},
"proxy": {
"baseUrl": "https://graph.facebook.com/v27.0",
"auth": {"in": "header", "name": "Authorization", "prefix": "Bearer ", "secret": "token"},
"allow": [{"method": "GET", "path": "^me$"}],
"inspect": {"method": "GET", "path": "me/permissions", "requireOnlyScopes": ["ads_read"]},
},
"schedules": [{"id": "daily", "cron": "0 7 * * *", "script": "jobs/snap.py"}],
"ui": {"settingsHtml": "ui/s.html", "pages": [{"id": "p", "label": "P", "nav": "dashboards", "html": "ui/p.html"}]},
"webhooks": [{"id": "in", "mode": "notify"}],
"actions": {"ping": {"script": "handlers/ping.py"}},
"resources": [{"id": "jira", "label": "Jira", "urlRegex": "https://x\\.atlassian\\.net/([A-Z]+-\\d+)"}],
}, files={
"skill/SKILL.md": "---\nname: meta-test\ndescription: test\n---\n",
"jobs/snap.py": "print('{}')\n",
"ui/s.html": "<div>settings</div>",
"ui/p.html": "<div>page</div>",
"handlers/ping.py": "print('{\"ok\":true}')\n",
})
mf = validate_manifest(d)
self.assertEqual(mf["id"], "meta-test")
self.assertFalse(requires_operator(mf))
fp1 = capability_fingerprint(mf)
caps = capability_summary(mf)
self.assertTrue(any(c["kind"] == "proxy" for c in caps))
self.assertTrue(any(c["kind"] == "skill" for c in caps))
# Cosmetic description/version change must NOT change fingerprint
mf["version"] = "1.0.1"
mf["description"] = "updated copy"
self.assertEqual(fp1, capability_fingerprint(mf))
# Widening proxy allowlist MUST change fingerprint
mf["proxy"]["allow"].append({"method": "POST", "path": "^me$"})
self.assertNotEqual(fp1, capability_fingerprint(mf))
def test_rejects_traversal_and_http_non_internal(self):
with tempfile.TemporaryDirectory() as td:
d = _write_plugin(pathlib.Path(td) / "bad", {
"schema": 1,
"id": "bad",
"name": "Bad",
"proxy": {"baseUrl": "http://example.com", "allow": [{"method": "GET", "path": "^a$"}]},
"actions": {"x": {"script": "../escape.py"}},
})
with self.assertRaises(ManifestError) as ctx:
validate_manifest(d)
msg = " ".join(ctx.exception.errors)
self.assertIn("https://", msg)
self.assertIn("..", msg)
class TestEgressAndProxy(unittest.TestCase):
def test_blocks_private_and_tailscale_ips(self):
self.assertFalse(is_public_ip("127.0.0.1"))
self.assertFalse(is_public_ip("10.0.0.5"))
self.assertFalse(is_public_ip("192.168.1.1"))
self.assertFalse(is_public_ip("100.93.171.39"))
self.assertFalse(is_public_ip("::1"))
self.assertTrue(is_public_ip("1.1.1.1"))
ok, _ = check_public_url("http://localhost:8080/x")
self.assertFalse(ok)
ok, _ = check_public_url("http://127.0.0.1:8096/api/users")
self.assertFalse(ok)
def test_proxy_injects_scrubs_and_inspects_scopes(self):
with tempfile.TemporaryDirectory() as td:
root = pathlib.Path(td)
pdir = _write_plugin(root / "src", {
"schema": 1,
"id": "demo",
"name": "Demo",
"secrets": [{"key": "token", "label": "Token"}],
"proxy": {
"baseUrl": "https://api.example.test/v1",
"auth": {"in": "header", "name": "Authorization", "prefix": "Bearer ", "secret": "token"},
"headers": {"X-Who": "guest-{{user.id}}"},
"allow": [
{"method": "GET", "path": "^me$"},
{"method": "GET", "path": "^me/permissions$"},
],
"denyParams": ["access_token"],
"inspect": {"method": "GET", "path": "me/permissions", "requireOnlyScopes": ["ads_read"]},
},
})
store = PluginStore(root / "data")
store.install("cel", str(pdir), is_owner=True, approve=True)
store.set_secret("cel", "demo", "token", "EAA_SUPER_SECRET_123456")
rec = store.get_raw("cel", "demo")
def handler(req: httpx.Request) -> httpx.Response:
if req.url.path == "/v1/me":
assert req.headers["authorization"] == "Bearer EAA_SUPER_SECRET_123456"
assert req.headers["x-who"] == "guest-cel"
return httpx.Response(200, json={"echo": "EAA_SUPER_SECRET_123456", "ok": True})
if req.url.path == "/v1/me/permissions":
if "WRITE_KEY" in req.headers["authorization"]:
return httpx.Response(200, json={"data": [{"permission": "ads_management", "status": "granted"}]})
return httpx.Response(200, json={"data": [{"permission": "ads_read", "status": "granted"}]})
return httpx.Response(404)
transport = httpx.MockTransport(handler)
deps = main.app.state.ai
async def run():
async with httpx.AsyncClient(transport=transport) as client:
with patch("plugins.proxy.check_public_url", return_value=(True, "")):
st, _, raw = await forward(client, deps, store, "cel", rec, method="GET", rel_path="me")
self.assertEqual(st, 200)
self.assertNotIn(b"EAA_SUPER_SECRET_123456", raw)
self.assertIn(b"***", raw)
# Forbidden method/path rejected
with self.assertRaises(ProxyError):
await forward(client, deps, store, "cel", rec, method="POST", rel_path="me")
with self.assertRaises(ProxyError):
await forward(client, deps, store, "cel", rec, method="GET", rel_path="me",
query_params=[("access_token", "x")])
# Inspect allows read-only token, rejects write scope
ok_ins = await run_inspect(client, deps, store, "cel", rec)
self.assertEqual(ok_ins["scopes"], ["ads_read"])
with self.assertRaises(ProxyError) as ctx:
await run_inspect(client, deps, store, "cel", rec, override_secret="WRITE_KEY_123456")
self.assertEqual(ctx.exception.kind, "forbidden_scopes")
asyncio.run(run())
class TestStoreAndSandboxedRunner(unittest.TestCase):
def test_install_reload_live_skill_and_stripped_env_action(self):
with tempfile.TemporaryDirectory() as td:
root = pathlib.Path(td)
pdir = _write_plugin(root / "p1", {
"schema": 1,
"id": "echoer",
"name": "Echoer",
"skill": {"dir": "skill", "name": "echoer"},
"actions": {"check": {"script": "handlers/check.py", "timeoutSec": 10}},
}, files={
"skill/SKILL.md": "---\nname: echoer\ndescription: hi\n---\n",
"handlers/check.py": (
"import json, os, sys\n"
"inp = json.loads(sys.stdin.read() or '{}')\n"
"print(json.dumps({'plugin': os.environ.get('AIA_PLUGIN_ID'), "
"'has_anthropic': 'ANTHROPIC_API_KEY' in os.environ, "
"'has_token': bool(os.environ.get('AIA_TOOLS_TOKEN')), 'in': inp}))\n"
),
})
store = PluginStore(root / "data")
store.install(OWNER_UID, str(pdir), is_owner=True, approve=True)
live = store.live_skill_dirs(OWNER_UID)
self.assertEqual(len(live), 1)
self.assertEqual(live[0]["ref"], "plugin:owner/echoer")
self.assertTrue((live[0]["dir"] / "SKILL.md").is_file())
rec = store.get_raw(OWNER_UID, "echoer")
with patch.dict(os.environ, {"ANTHROPIC_API_KEY": "sk-secret"}):
out = run_script(main.app.state.ai, store, OWNER_UID, rec,
"handlers/check.py", payload={"hello": 1})
self.assertEqual(out["plugin"], "echoer")
self.assertFalse(out["has_anthropic"])
self.assertTrue(out["has_token"])
self.assertEqual(out["in"], {"hello": 1})
# Widening capabilities on reload sets needsApproval=True
mf = json.loads((pdir / "plugin.json").read_text())
mf["capabilities"] = ["conversations.spawn"]
(pdir / "plugin.json").write_text(json.dumps(mf))
reloaded = store.reload(OWNER_UID, "echoer", is_owner=True, approve=False)
self.assertTrue(reloaded["needsApproval"])
self.assertEqual(store.live_skill_dirs(OWNER_UID), [])
approved = store.reload(OWNER_UID, "echoer", is_owner=True, approve=True)
self.assertFalse(approved["needsApproval"])
self.assertEqual(len(store.live_skill_dirs(OWNER_UID)), 1)
class TestManagedPluginsAndUpgrades(unittest.TestCase):
def test_strip_response_keys_and_worktree_path_mapping(self):
with tempfile.TemporaryDirectory() as td:
root = pathlib.Path(td)
wt_root = root / "wt"
pdir = _write_plugin(wt_root / "my-wt" / "plugins" / "meta", {
"schema": 1,
"id": "meta-strip",
"name": "Meta Strip",
"secrets": [{"key": "token", "label": "Token"}],
"proxy": {
"baseUrl": "https://graph.facebook.com/v27.0",
"auth": {"in": "header", "name": "Authorization", "prefix": "Bearer ", "secret": "token"},
"allow": [{"method": "GET", "path": "^me/accounts$"}],
"stripResponseKeys": ["access_token"],
},
})
store = PluginStore(root / "data")
with patch.dict(os.environ, {"WORKTREES_DIR": str(wt_root), "WORKTREES_HOST_DIR": "/host/wt"}):
resolved, _ = store.resolve_source("/host/wt/my-wt/plugins/meta", allow_any_path=True)
self.assertEqual(resolved, pdir.resolve())
store.install("cel", str(pdir), is_owner=True, approve=True)
store.set_secret("cel", "meta-strip", "token", "EAA_SYS_USER_TOKEN_123456")
rec = store.get_raw("cel", "meta-strip")
def handler(req: httpx.Request) -> httpx.Response:
return httpx.Response(200, json={
"data": [{"id": "123", "name": "Page", "access_token": "EAA_PAGE_SECRET_999"}]
})
transport = httpx.MockTransport(handler)
deps = main.app.state.ai
async def run():
async with httpx.AsyncClient(transport=transport) as client:
with patch("plugins.proxy.check_public_url", return_value=(True, "")):
st, _, raw = await forward(client, deps, store, "cel", rec, method="GET", rel_path="me/accounts")
self.assertEqual(st, 200)
body = json.loads(raw)
self.assertNotIn("access_token", body["data"][0])
self.assertEqual(body["data"][0]["name"], "Page")
asyncio.run(run())
def test_managed_grants_byok_and_live_skills(self):
with tempfile.TemporaryDirectory() as td:
root = pathlib.Path(td)
pdir = _write_plugin(root / "nb", {
"schema": 1,
"id": "nb-test",
"name": "Nano Banana",
"skill": {"dir": "skill", "name": "nb-test"},
"secrets": [{"key": "api_key", "label": "Gemini Key", "scope": "hub"}],
"managed": {
"defaultForGuests": False,
"allowUserSecretOverride": True,
"metered": True,
"grantFields": [{"key": "allowPro", "label": "Allow Pro", "type": "checkbox", "default": False}],
"limits": {"inFlight": 4, "defaultMonthlyBudgetUsd": 5.0},
},
}, files={"skill/SKILL.md": "---\nname: nb-test\ndescription: img\n---\n"})
store = PluginStore(root / "data")
store.install(OWNER_UID, str(pdir), is_owner=True, approve=True)
store.set_secret(OWNER_UID, "nb-test", "api_key", "HUB_GEMINI_KEY_123", scope="hub")
# Not granted to guest yet
rec, grant, is_m = store.resolve_active_for_caller("cel", "nb-test")
self.assertIsNone(rec)
self.assertEqual(store.live_skill_dirs("cel"), [])
# Grant to cel with allowPro=True and $10 budget
g = store.set_grant("cel", "nb-test", enabled=True, config={"allowPro": True}, monthly_budget_usd=10.0)
self.assertTrue(g["enabled"])
self.assertTrue(g["config"]["allowPro"])
self.assertEqual(g["monthlyBudgetUsd"], 10.0)
rec, grant, is_m = store.resolve_active_for_caller("cel", "nb-test")
self.assertIsNotNone(rec)
self.assertTrue(is_m)
live = store.live_skill_dirs("cel")
self.assertEqual(len(live), 1)
# the ref names the folder the sidecar reads (live-skills/<uid>/<id>)
uid, pid = live[0]["ref"].removeprefix("plugin:").split("/")
self.assertTrue((store.live_skills_dir / uid / pid / "SKILL.md").is_file(), live[0]["ref"])
self.assertEqual(live[0]["dir"], store.live_skills_dir / uid / pid)
# Secret resolves to hub key by default, then BYOK when cel sets her own key
val, own = store.get_secret_for_caller("cel", "nb-test", "api_key", rec["manifest"])
self.assertEqual(val, "HUB_GEMINI_KEY_123")
self.assertFalse(own)
store.set_secret("cel", "nb-test", "api_key", "CEL_OWN_GEMINI_KEY_999", scope="user")
val2, own2 = store.get_secret_for_caller("cel", "nb-test", "api_key", rec["manifest"])
self.assertEqual(val2, "CEL_OWN_GEMINI_KEY_999")
self.assertTrue(own2)
if __name__ == "__main__":
unittest.main()