- plugin.json: `icon` may name an .svg; new `illustration`, `color` and
`readme`. icon.svg, illustration.{svg,webp,png,jpg} and README.md at
the plugin root are picked up without a declaration. `artVersion`
busts the asset URLs' cache.
- An SVG with scripts, event handlers, foreignObject, external or data:
references is refused at install, and again when served.
- GET /api/plugins/{id}/asset/{icon|illustration}: sandboxed (CSP
sandbox, nosniff), for an own install, a granted managed plugin or a
visible catalog entry. GET /api/plugins/{id}/info: README,
capabilities, schedules, webhooks, actions, pages, version, author,
source (the source only to its installer or the operator).
- Records, the catalog and the guests' managed view carry iconUrl,
illustrationUrl, color, author, hasReadme. A record installed before
art existed gets it once from its source — art keys only, so no
re-approval (art is not in the fingerprint).
- + New plugin scaffolds icon.svg + README.md and asks the build for art.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
169 lines
8.6 KiB
Python
169 lines
8.6 KiB
Python
"""Plugin art (SVG icon, illustration, colour, README) and the info page."""
|
|
|
|
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",
|
|
"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.manifest import ManifestError, capability_fingerprint, svg_problem, validate_manifest # noqa: E402
|
|
from plugins.store import OWNER_UID, PluginStore # noqa: E402
|
|
|
|
OWNER_H = {"X-Internal-Auth": os.environ["INTERNAL_API_TOKEN"]}
|
|
|
|
ICON = ('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" '
|
|
'stroke="currentColor"><path d="M4 4h16v16H4z"/><use href="#a"/></svg>')
|
|
BASE = {"schema": 1, "id": "artsy", "name": "Artsy", "version": "1.2.0",
|
|
"description": "Has art", "author": "someone",
|
|
"schedules": [{"id": "daily", "cron": "0 7 * * *", "script": "jobs/a.py", "description": "Daily"}],
|
|
"webhooks": [{"id": "in", "mode": "notify", "description": "Inbound"}]}
|
|
|
|
|
|
def _write(root: pathlib.Path, manifest: dict, files: dict[str, str | bytes]) -> pathlib.Path:
|
|
root.mkdir(parents=True, exist_ok=True)
|
|
(root / "plugin.json").write_text(json.dumps(manifest), encoding="utf-8")
|
|
for rel, content in files.items():
|
|
p = root / rel
|
|
p.parent.mkdir(parents=True, exist_ok=True)
|
|
if isinstance(content, bytes):
|
|
p.write_bytes(content)
|
|
else:
|
|
p.write_text(content, encoding="utf-8")
|
|
return root
|
|
|
|
|
|
FILES: dict[str, str | bytes] = {"jobs/a.py": "print('{}')\n", "icon.svg": ICON,
|
|
"illustration.webp": b"RIFF....WEBPVP8 fake",
|
|
"README.md": "# Artsy\n\nDoes art things.\n"}
|
|
|
|
|
|
class TestArtManifest(unittest.TestCase):
|
|
def test_files_by_name_are_picked_up(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
mf = validate_manifest(_write(pathlib.Path(td) / "p", BASE, FILES))
|
|
self.assertEqual(mf["icon"], "puzzle")
|
|
self.assertEqual(mf["iconSvg"], "icon.svg")
|
|
self.assertEqual(mf["illustration"], "illustration.webp")
|
|
self.assertEqual(mf["readme"], "README.md")
|
|
self.assertEqual(len(mf["artVersion"]), 12)
|
|
|
|
def test_declared_paths_colour_and_lucide_name(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
m = {**BASE, "icon": "art/i.svg", "illustration": "art/cover.svg", "color": "#3A2F7D"}
|
|
mf = validate_manifest(_write(pathlib.Path(td) / "p", m, {
|
|
"jobs/a.py": "x", "art/i.svg": ICON, "art/cover.svg": ICON}))
|
|
self.assertEqual((mf["iconSvg"], mf["illustration"], mf["color"]),
|
|
("art/i.svg", "art/cover.svg", "#3a2f7d"))
|
|
self.assertIsNone(mf["readme"])
|
|
plain = validate_manifest(_write(pathlib.Path(td) / "q", {**BASE, "icon": "clapperboard"},
|
|
{"jobs/a.py": "x"}))
|
|
self.assertEqual((plain["icon"], plain["iconSvg"], plain["illustration"]),
|
|
("clapperboard", None, None))
|
|
|
|
def test_refuses_active_svg_bad_colour_and_wrong_type(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
for i, (m, files) in enumerate([
|
|
(BASE, {"icon.svg": '<svg onload="alert(1)"/>'}),
|
|
(BASE, {"icon.svg": "<svg><script>x</script></svg>"}),
|
|
({**BASE, "illustration": "x.svg"}, {"x.svg": '<svg><image href="https://e.vil/a.png"/></svg>'}),
|
|
({**BASE, "illustration": "x.gif"}, {"x.gif": "GIF89a"}),
|
|
({**BASE, "color": "red"}, {}),
|
|
({**BASE, "icon": "../outside.svg"}, {}),
|
|
]):
|
|
with self.subTest(i=i), self.assertRaises(ManifestError):
|
|
validate_manifest(_write(pathlib.Path(td) / f"p{i}", m, {"jobs/a.py": "x", **files}))
|
|
self.assertIsNone(svg_problem(ICON.encode()))
|
|
|
|
def test_art_does_not_touch_the_approval_fingerprint(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
bare = validate_manifest(_write(pathlib.Path(td) / "a", BASE, {"jobs/a.py": "print('{}')\n"}))
|
|
arty = validate_manifest(_write(pathlib.Path(td) / "b", {**BASE, "color": "#123456"}, FILES))
|
|
self.assertEqual(capability_fingerprint(bare), capability_fingerprint(arty))
|
|
|
|
|
|
class TestArtRoutes(unittest.TestCase):
|
|
def setUp(self):
|
|
self.tc = TestClient(main.app, headers=OWNER_H)
|
|
|
|
def _store(self, td: str) -> PluginStore:
|
|
store = PluginStore(pathlib.Path(td) / "data")
|
|
src = _write(pathlib.Path(td) / "src", {**BASE, "color": "#123456"}, FILES)
|
|
store.install(OWNER_UID, str(src), is_owner=True, approve=True)
|
|
return store
|
|
|
|
def test_list_info_and_assets(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
store = self._store(td)
|
|
with patch.object(main.app.state.ai, "plugin_store", store):
|
|
rec = self.tc.get("/api/plugins").json()["installed"][0]
|
|
self.assertTrue(rec["iconUrl"].startswith("/api/plugins/artsy/asset/icon?v="))
|
|
self.assertTrue(rec["illustrationUrl"].startswith("/api/plugins/artsy/asset/illustration?v="))
|
|
self.assertEqual((rec["color"], rec["hasReadme"]), ("#123456", True))
|
|
|
|
r = self.tc.get(rec["iconUrl"])
|
|
self.assertEqual(r.status_code, 200)
|
|
self.assertEqual(r.headers["content-type"], "image/svg+xml")
|
|
self.assertIn("sandbox", r.headers["content-security-policy"])
|
|
self.assertEqual(r.headers["x-content-type-options"], "nosniff")
|
|
self.assertEqual(self.tc.get(rec["illustrationUrl"]).headers["content-type"], "image/webp")
|
|
self.assertEqual(self.tc.get("/api/plugins/artsy/asset/readme").status_code, 404)
|
|
self.assertEqual(self.tc.get("/api/plugins/nope/asset/icon").status_code, 404)
|
|
|
|
info = self.tc.get("/api/plugins/artsy/info").json()
|
|
self.assertEqual(info["how"], "installed")
|
|
self.assertIn("Does art things", info["readme"])
|
|
self.assertEqual(info["schedules"][0]["id"], "daily")
|
|
self.assertEqual(info["webhooks"], [{"id": "in", "mode": "notify", "description": "Inbound"}])
|
|
self.assertTrue(info["source"])
|
|
self.assertTrue(any(c["kind"] == "schedule" for c in info["capabilities"]))
|
|
|
|
def test_a_record_from_before_art_gets_it_once_without_reapproval(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
store = self._store(td)
|
|
with store._lock:
|
|
rec = store._state["users"][OWNER_UID]["artsy"]
|
|
for k in ("iconSvg", "illustration", "color", "readme", "artVersion"):
|
|
rec["manifest"].pop(k, None)
|
|
fp = rec["fingerprint"]
|
|
[pub] = store.list_for(OWNER_UID)
|
|
self.assertTrue(pub["iconUrl"])
|
|
self.assertEqual(pub["color"], "#123456")
|
|
self.assertFalse(pub["needsApproval"])
|
|
self.assertEqual(store.get_raw(OWNER_UID, "artsy")["fingerprint"], fp)
|
|
self.assertIn("artVersion", store.get_raw(OWNER_UID, "artsy")["manifest"])
|
|
|
|
def test_svg_changed_on_disk_after_install_is_refused(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
store = self._store(td)
|
|
(pathlib.Path(td) / "src" / "icon.svg").write_text("<svg onload='x'/>", encoding="utf-8")
|
|
with patch.object(main.app.state.ai, "plugin_store", store):
|
|
self.assertEqual(self.tc.get("/api/plugins/artsy/asset/icon").status_code, 404)
|
|
|
|
def test_catalog_entry_has_art_and_info(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
store = PluginStore(pathlib.Path(td) / "data")
|
|
src = _write(pathlib.Path(td) / "src", BASE, FILES)
|
|
store.promote_catalog(str(src))
|
|
with patch.object(main.app.state.ai, "plugin_store", store):
|
|
cat = self.tc.get("/api/plugins").json()["catalog"][0]
|
|
self.assertTrue(cat["iconUrl"])
|
|
self.assertEqual(self.tc.get(cat["iconUrl"]).status_code, 200)
|
|
self.assertEqual(self.tc.get("/api/plugins/artsy/info").json()["how"], "catalog")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|