Files
ai-agent/backend/test_batch1_platform.py
gabrielvidalandClaude Opus 5.5 5670313285 feat(cron): cron jobs leave the core for the cron-jobs plugin
Owner jobs and guests' own scheduled jobs are the cron-jobs live plugin's
(forms move-ai-agent-cron-jobs-into-a-plugin_u0wa6b,
cron-scheduled-in-the-cli-and-mcp_x4nk83). Gone: backend/cron/,
schemas/cron.py, /api/cron*, /api/me/cron*, the cron scheduler thread,
Settings → Cron and the guests' Tâches planifiées pages, `ai-agent cron`
(now a pointer), MCP run_cron_job / set_cron_job / browse cron, the
scheduled-jobs core skill, guestDefaults.cronLimits.

The core keeps thin contracts:
- runs.guest bridge (runs/guestjob.py): a guest's job run as that guest,
  confined by the core from their record; the plugin only names it.
- runs.start's cron stamp → meta.cron.
- delivery of a guest job's result (push, mail, mailHtml) off the stamp.
- « Discuter »: POST /api/cron-runs/discuss.
- runs.cron provider readers (plugins/cron_bridge.py): budget,
  auto-archive, agents catalog, the agents page's Schedule.
- core/cronexpr.py, agents/runconfig.py; context.write create for a new
  agent definition; ui.pages[].unless; setRoute keeps a Settings page
  under /settings/p/.
- carryover.cron_jobs: /data/cron-jobs.json → the plugin's jobs.json,
  cronLimits → limits.json, guests' qwen jobs → sonnet (PR #23's
  decision, superseded).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 17:57:41 +01:00

504 lines
26 KiB
Python

"""Batch 1 platform hooks (2026-11-26) — what the templates, memories,
desk-phone, activity, project-env, ship and blue-green-deploy plugins build on:
the owner-only capabilities and their host dirs, the new ``provides`` keys and
the active ones on ``/api/plugins``, the memories / app.banner bridges, the
activity and ship hub bridges, ``hub/conversations?memories=1&memory=…``, the
inline scaffold template list and ``/api/usage/daily``."""
from __future__ import annotations
import json
import os
import pathlib
import tempfile
import unittest
from types import SimpleNamespace
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 import HTTPException # noqa: E402
from fastapi.testclient import TestClient # noqa: E402
import main # noqa: E402
from plugins import banner, memories_bridge # noqa: E402
from plugins.manifest import (ManifestError, capability_summary, requires_operator, # noqa: E402
validate_manifest)
from plugins.runner import requester_context, run_script # noqa: E402
from plugins.store import OWNER_UID, PluginStore # noqa: E402
from toolproxy import access # noqa: E402
from users.caller import guest_from_record # noqa: E402
OWNER_H = {"X-Internal-Auth": os.environ["INTERNAL_API_TOKEN"]}
NEW_CAPS = ("templates.read", "memories.read", "projects.env", "activity.read", "ship.run")
ENV = r'''
import json, os, sys
sys.stdin.read()
print(json.dumps({k: os.environ.get(k) for k in
("AIA_TEMPLATES_DIR", "AIA_MEMORIES_DIR", "AIA_PROJECTS_DIR")}))
'''
ECHO = r'''
import json, os, sys
p = json.load(sys.stdin)
print(json.dumps({"payload": p, "ctx": json.loads(os.environ["AIA_USER_CONTEXT"])}))
'''
INDEX = r'''
import json
print(json.dumps({"memories": [{"slug": "m1", "name": "One", "links": ["m2"]}, {"name": "no slug"}]}))
'''
GET = r'''
import json, sys
p = json.load(sys.stdin)
print(json.dumps({"slug": "m1", "body": "hi"} if p.get("slug") == "m1"
else {"_error": {"status": 404, "message": "nope"}}))
'''
BANNER = r'''
import json, os, sys
sys.stdin.read()
n = int(open(os.path.join(os.environ["AIA_PLUGIN_SHARED_DIR"], "n")).read()) if os.path.exists(
os.path.join(os.environ["AIA_PLUGIN_SHARED_DIR"], "n")) else 0
print(json.dumps({"active": True, "title": "Deploy", "label": "batch1", "status": "running",
"phaseNum": 2, "totalPhases": 3, "phase": "waiting", "n": n,
"steps": [{"n": 1, "label": "build"}, {"n": 2, "label": "wait"}, {"n": 3, "label": "swap"}]}))
'''
HOOK = r'''
import json, os, sys
p = json.load(sys.stdin)
d = os.environ["AIA_PLUGIN_SHARED_DIR"]
os.makedirs(d, exist_ok=True)
open(os.path.join(d, "n"), "w").write("7")
print(json.dumps({"got": p}))
'''
def _write(root: pathlib.Path, manifest: dict, files: dict[str, str]) -> pathlib.Path:
root.mkdir(parents=True, exist_ok=True)
(root / "plugin.json").write_text(json.dumps(manifest), encoding="utf-8")
for rel, body in files.items():
(root / rel).parent.mkdir(parents=True, exist_ok=True)
(root / rel).write_text(body, encoding="utf-8")
return root
def _install(td, manifest, files, uid=OWNER_UID) -> PluginStore:
store = PluginStore(pathlib.Path(td) / "data")
store.install(uid, str(_write(pathlib.Path(td) / "src", manifest, files)), is_owner=True, approve=True)
return store
class ManifestCaps(unittest.TestCase):
def test_new_capabilities_are_operator_only_and_labelled(self):
with tempfile.TemporaryDirectory() as td:
for cap in NEW_CAPS:
mf = validate_manifest(_write(pathlib.Path(td) / cap, {
"schema": 1, "id": "x", "name": "X", "capabilities": [cap]}, {}))
self.assertTrue(requires_operator(mf), cap)
item = next(c for c in capability_summary(mf) if c["kind"] == "capability")
self.assertTrue(item["privileged"], cap)
self.assertNotIn("Hub capability:", item["label"], cap)
def test_old_operator_rules_hold(self):
with tempfile.TemporaryDirectory() as td:
spawn = validate_manifest(_write(pathlib.Path(td) / "s", {
"schema": 1, "id": "s", "name": "S", "capabilities": ["conversations.spawn"]}, {}))
models = validate_manifest(_write(pathlib.Path(td) / "m", {
"schema": 1, "id": "m", "name": "M", "capabilities": ["models.read"]}, {}))
self.assertFalse(requires_operator(spawn))
self.assertTrue(next(c for c in capability_summary(spawn) if c["kind"] == "capability")["privileged"])
self.assertTrue(requires_operator(models))
self.assertFalse(next(c for c in capability_summary(models) if c["kind"] == "capability")["privileged"])
def test_new_provides_keys(self):
with tempfile.TemporaryDirectory() as td:
for key in ("memories.index", "notify.audio", "app.banner"):
mf = validate_manifest(_write(pathlib.Path(td) / key, {
"schema": 1, "id": "p", "name": "P", "actions": {"a": {"script": "a.py"}},
"provides": {key: "a"}}, {"a.py": "print('{}')"}))
self.assertEqual(mf["provides"], {key: "a"})
with self.assertRaises(ManifestError):
validate_manifest(_write(pathlib.Path(td) / "bad", {
"schema": 1, "id": "p", "name": "P", "actions": {"a": {"script": "a.py"}},
"provides": {"app.toast": "a"}}, {"a.py": ""}))
class RunnerDirs(unittest.TestCase):
def test_dirs_only_for_the_owner(self):
deps = SimpleNamespace(users=SimpleNamespace(get=lambda u: None))
with tempfile.TemporaryDirectory() as td:
store = _install(td, {"schema": 1, "id": "e", "name": "E", "capabilities": list(NEW_CAPS[:3]),
"actions": {"env": {"script": "env.py"}}}, {"env.py": ENV})
rec = store.get_raw(OWNER_UID, "e")
with patch.dict(os.environ, {"TEMPLATES_DIR": f"{td}/tpl", "MEMORIES_DIR": f"{td}/mem"}):
own = run_script(deps, store, OWNER_UID, rec, "env.py")
guest = run_script(deps, store, "dom", rec, "env.py")
self.assertEqual(own["AIA_TEMPLATES_DIR"], str(pathlib.Path(td, "tpl").resolve()))
self.assertEqual(own["AIA_MEMORIES_DIR"], str(pathlib.Path(td, "mem").resolve()))
from projects.catalog import PROJECTS_DIR
self.assertEqual(own["AIA_PROJECTS_DIR"], str(PROJECTS_DIR))
self.assertEqual(guest, {"AIA_TEMPLATES_DIR": None, "AIA_MEMORIES_DIR": None, "AIA_PROJECTS_DIR": None})
def test_no_capability_no_dir(self):
deps = SimpleNamespace(users=SimpleNamespace(get=lambda u: None))
with tempfile.TemporaryDirectory() as td:
store = _install(td, {"schema": 1, "id": "e", "name": "E",
"actions": {"env": {"script": "env.py"}}}, {"env.py": ENV})
out = run_script(deps, store, OWNER_UID, store.get_raw(OWNER_UID, "e"), "env.py")
self.assertEqual(set(out.values()), {None})
def test_requester_context_carries_the_session(self):
deps = SimpleNamespace(users=SimpleNamespace(get=lambda u: {"id": u, "name": "Dom", "lang": "fr"}))
ctx = requester_context(deps, "dom", {"config": {"x": 1}}, "sess-1")
self.assertEqual((ctx["uid"], ctx["isOwner"], ctx["sessionId"], ctx["grant"]),
("dom", False, "sess-1", {"x": 1}))
self.assertIn("name", ctx)
self.assertIn("lang", ctx)
class ProvidesList(unittest.TestCase):
MF = {"schema": 1, "id": "pv", "name": "Pv",
"actions": {"b": {"script": "b.py"}, "a": {"script": "b.py"}},
"provides": {"notify.audio": "a", "app.banner": "b"}}
def test_active_provides_on_the_list(self):
deps = main.app.state.ai
with tempfile.TemporaryDirectory() as td:
store = _install(td, self.MF, {"b.py": "print('{}')"})
with patch.object(deps, "plugin_store", store):
out = TestClient(main.app, headers=OWNER_H).get("/api/plugins").json()
store.update(OWNER_UID, "pv", enabled=False)
off = TestClient(main.app, headers=OWNER_H).get("/api/plugins").json()
self.assertEqual(out["provides"], ["app.banner", "notify.audio"])
self.assertEqual(out["ui"]["provides"], ["app.banner", "notify.audio"])
self.assertEqual(off["provides"], [])
def test_a_guest_never_sees_app_banner(self):
from plugins.routes import _ui_descriptors
deps = main.app.state.ai
g = guest_from_record({"id": "dom", "name": "Dom", "projects": {}})
rows = [{"id": "pv", "name": "Pv", "enabled": True, "manifest": self.MF}]
self.assertEqual(_ui_descriptors(deps, g, rows)["provides"], ["notify.audio"])
class MemoriesBridge(unittest.TestCase):
MF = {"schema": 1, "id": "memories", "name": "Memories", "capabilities": ["memories.read"],
"actions": {"index": {"script": "i.py"}, "get": {"script": "g.py"}},
"provides": {"memories.index": "index"}}
def test_no_plugin(self):
deps = main.app.state.ai
with tempfile.TemporaryDirectory() as td, \
patch.object(deps, "plugin_store", PluginStore(pathlib.Path(td))):
self.assertFalse(memories_bridge.has_provider(deps))
self.assertEqual(memories_bridge.list_memories(deps), [])
self.assertIsNone(memories_bridge.get_memory(deps, "m1"))
def test_through_the_plugin_and_into_the_graph(self):
deps = main.app.state.ai
with tempfile.TemporaryDirectory() as td:
store = _install(td, self.MF, {"i.py": INDEX, "g.py": GET})
with patch.object(deps, "plugin_store", store):
self.assertTrue(memories_bridge.has_provider(deps))
self.assertEqual([m["slug"] for m in memories_bridge.list_memories(deps)], ["m1"])
self.assertEqual(memories_bridge.get_memory(deps, "m1")["body"], "hi")
self.assertIsNone(memories_bridge.get_memory(deps, "zz"))
from plugins import graphdata
g = graphdata.build(deps)
self.assertEqual([m["slug"] for m in g["memories"]], ["m1"])
self.assertEqual(g["memories"][0]["links"], ["m2"])
def test_graph_without_the_plugin_has_no_memories(self):
"""backend/memories/ left the core (2026-11-26): no core fallback."""
deps = main.app.state.ai
from plugins import graphdata
self.assertFalse(hasattr(graphdata, "_legacy_memories"))
with tempfile.TemporaryDirectory() as td, \
patch.object(deps, "plugin_store", PluginStore(pathlib.Path(td))):
g = graphdata.build(deps)
self.assertEqual(g["memories"], [])
class AppBanner(unittest.TestCase):
MF = {"schema": 1, "id": "bg", "name": "Blue-green",
"actions": {"status": {"script": "s.py"}, "hook": {"script": "h.py"}},
"provides": {"app.banner": "status"},
"webhooks": [{"id": "phase", "mode": "action", "action": "hook", "internalOnly": True}]}
def setUp(self):
banner.invalidate()
def tearDown(self):
banner.invalidate()
def test_normalize(self):
self.assertIsNone(banner.normalize(None))
self.assertIsNone(banner.normalize({}))
b = banner.normalize({"status": "failed", "phaseNum": 2,
"steps": [{"n": 1, "label": "a"}, {"n": 2, "label": "b"}, {"n": 3, "label": "c"}]})
self.assertEqual([s["state"] for s in b["steps"]], ["done", "failed", "pending"])
self.assertTrue(b["active"])
self.assertEqual(banner.normalize({"active": False, "status": "weird"})["status"], "info")
def test_owner_route_cache_webhook_and_maintenance(self):
deps = main.app.state.ai
tc = TestClient(main.app, headers=OWNER_H)
published = []
with tempfile.TemporaryDirectory() as td:
store = _install(td, self.MF, {"s.py": BANNER, "h.py": HOOK})
with patch.object(deps, "plugin_store", store), \
patch.object(deps.hub, "publish", side_effect=published.append):
r = tc.get("/api/app-banner")
self.assertEqual(r.status_code, 200, r.text)
b = r.json()
self.assertEqual((b["title"], b["label"], b["status"]), ("Deploy", "batch1", "running"))
self.assertNotIn("n", b) # only the BannerStatus fields reach the app
self.assertEqual([s["state"] for s in b["steps"]], ["done", "active", "pending"])
self.assertTrue(banner.is_maintenance(deps))
# The webhook runs its action with the payload on stdin, then
# drops the cache and pings the app.
tok = store.get_raw(OWNER_UID, "bg")
with patch.object(store, "find_by_webhook_token", return_value=(OWNER_UID, tok)):
w = tc.post("/proxy/tools/plugins/bg/webhook/phase?token=t", json={"phase": 3})
self.assertEqual(w.status_code, 200, w.text)
self.assertEqual(w.json()["result"]["got"],
{"trigger": "webhook", "hookId": "phase", "body": {"phase": 3}})
self.assertIn({"type": "banner"}, published)
self.assertIsNone(banner._cache)
def test_never_a_guests(self):
from plugins.routes import app_banner
g = guest_from_record({"id": "dom", "name": "Dom", "projects": {}})
with self.assertRaises(HTTPException) as e:
app_banner(main.app.state.ai, g)
self.assertEqual(e.exception.status_code, 403)
def test_no_provider_no_banner_no_maintenance(self):
deps = main.app.state.ai
with tempfile.TemporaryDirectory() as td, \
patch.object(deps, "plugin_store", PluginStore(pathlib.Path(td))):
self.assertIsNone(TestClient(main.app, headers=OWNER_H).get("/api/app-banner").json())
self.assertFalse(banner.is_maintenance(deps))
def test_guest_job_delivery_waits_out_maintenance(self):
from runs import guestjob as guests
with patch("plugins.banner.is_maintenance", return_value=True), \
patch.object(guests, "due_deliveries") as due:
self.assertEqual(guests.deliver_sweep(main.app.state.ai), 0)
due.assert_not_called()
class _Summaries:
def __init__(self, rows):
self.rows = rows
def all_summaries(self):
return list(self.rows)
class _Meta:
def peek(self, sid):
return {}
class HubConversationsMemories(unittest.TestCase):
def test_memories_columns_and_memory_filter(self):
deps = main.app.state.ai
rows = [
("/a/old.jsonl", {"sessionId": "s-old", "endedAt": "2020-01-01T00:00:00Z", "memoriesRead": ["m1"],
"models": ["claude-opus-5-5"]}),
("/a/new.jsonl", {"sessionId": "s-new", "endedAt": "2099-01-01T00:00:00Z", "memoriesRead": ["m2"]}),
]
tc = TestClient(main.app)
with tempfile.TemporaryDirectory() as td:
store = _install(td, {"schema": 1, "id": "cr", "name": "R", "capabilities": ["conversations.read"]}, {})
tok = access.mint_handler(OWNER_UID, "cr", ttl=600)
h = {"Authorization": f"Bearer {tok}"}
with patch.object(deps, "plugin_store", store), patch.object(deps, "store", _Summaries(rows)), \
patch.object(deps, "meta_store", _Meta()):
plain = tc.get("/proxy/tools/plugins/cr/hub/conversations", headers=h).json()["conversations"]
mem = tc.get("/proxy/tools/plugins/cr/hub/conversations?memories=1", headers=h).json()["conversations"]
one = tc.get("/proxy/tools/plugins/cr/hub/conversations?memory=m1", headers=h).json()["conversations"]
self.assertEqual([c["sessionId"] for c in plain], ["s-new"])
self.assertNotIn("memoriesRead", plain[0])
self.assertEqual(mem[0]["memoriesRead"], ["m2"])
self.assertIn("model", mem[0])
# The whole archive, not the 30-day window.
self.assertEqual([(c["sessionId"], c["model"], c["memoriesRead"]) for c in one],
[("s-old", "claude-opus-5-5", ["m1"])])
class ActivityBridge(unittest.TestCase):
MF = {"schema": 1, "id": "act", "name": "Activity", "capabilities": ["activity.read"]}
def test_owner_reads_it_a_guest_never(self):
deps = main.app.state.ai
tc = TestClient(main.app)
with tempfile.TemporaryDirectory() as td:
store = _install(td, self.MF, {})
with patch.object(deps, "plugin_store", store), \
patch("plugins.activitydata.build", return_value={"days": []}) as b:
r = tc.get("/proxy/tools/plugins/act/hub/activity?account=all&tzOffset=99999",
headers={"Authorization": f"Bearer {access.mint_handler(OWNER_UID, 'act', ttl=600)}"})
g = tc.get("/proxy/tools/plugins/act/hub/activity",
headers={"Authorization": f"Bearer {access.mint('cel', ttl=600)}"})
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(b.call_args.args[1:], ("all", 960))
self.assertEqual(g.status_code, 403)
def test_payload_shape(self):
from plugins import activitydata
deps = main.app.state.ai
b0 = 1795168800 // 300
rows = [("/x.jsonl", {"sessionId": "s", "messages": 3, "startedAt": "2026-11-20T10:00:00Z",
"tokens": 100, "cost": 1.5, "models": ["claude-opus-5-5"],
"activeBins": {"claude-opus-5-5": [b0, b0 + 1]}})]
with patch("conversations.cards._summaries_for", return_value=rows):
out = activitydata._build_activity_bridge(deps, 0, "all")
for k in ("days", "binsByDay", "models", "totals", "profiles", "byAccount"):
self.assertIn(k, out)
self.assertEqual(out["days"][0]["date"], "2026-11-20")
self.assertEqual(out["totals"]["cost"], 1.5)
self.assertEqual(out["binsByDay"]["2026-11-20"], [[120, 0, 1], [121, 0, 1]])
def test_timebins_and_no_core_dashboard(self):
import importlib.util
from dashboards import timebins
# the core dashboard is gone: the activity plugin reads the bridge
self.assertIsNone(importlib.util.find_spec("dashboards.activity"))
self.assertNotIn("/api/activity", {getattr(r, "path", "") for r in main.app.routes})
self.assertEqual(timebins._local_day_and_slot(1795168800 // 300, 0), ("2026-11-20", 120))
self.assertEqual(timebins._local_date("2026-11-20T23:30:00Z", 60 * 60_000), "2026-11-21")
class DailyUsage(unittest.TestCase):
def test_days_zero_filled_and_scoped(self):
import datetime as dt
from usage.routes import daily_usage
today = dt.datetime.now(dt.timezone.utc).date()
iso = lambda d: f"{d.isoformat()}T12:00:00Z" # noqa: E731
rows = [
("/a.jsonl", {"messages": 2, "startedAt": iso(today), "cost": 1.0, "tokens": 10}),
("/a/sub.jsonl", {"messages": 2, "startedAt": iso(today), "cost": 0.5, "tokens": 5, "isSidechain": True}),
("/b.jsonl", {"messages": 2, "startedAt": iso(today - dt.timedelta(days=2)), "cost": 2.0, "tokens": 20}),
("/old.jsonl", {"messages": 2, "startedAt": iso(today - dt.timedelta(days=30)), "cost": 9.0}),
("/empty.jsonl", {"startedAt": iso(today), "cost": 9.0}),
]
with patch("conversations.cards._summaries_for", return_value=rows) as sf:
out = daily_usage(main.app.state.ai, 7, 0, "profile:personal")
many = daily_usage(main.app.state.ai, 1000, 0, None)
self.assertEqual(sf.call_args_list[0].args[1], "profile:personal")
days = out["days"]
self.assertEqual(len(days), 7)
self.assertEqual(days[-1], {"date": today.isoformat(), "cost": 1.5, "tokens": 15, "conversations": 1})
self.assertEqual(days[-3]["cost"], 2.0)
self.assertEqual(days[0]["cost"], 0.0)
self.assertEqual(len(many["days"]), 90)
def test_route_is_gone_the_bridge_reads_it(self):
# Home's usage card is the activity plugin's: its bridge calls
# daily_usage, the core route is gone
self.assertNotIn("/api/usage/daily", main.app.openapi()["paths"])
from authz.routes import TABLE
self.assertNotIn(("GET", "/api/usage/daily"), TABLE)
self.assertEqual(TABLE[("GET", "/api/app-banner")], "lab.read")
class ShipBridge(unittest.TestCase):
MF = {"schema": 1, "id": "ship", "name": "Ship", "capabilities": ["ship.run"],
"actions": {"a": {"script": "a.py", "runAs": "owner"}}}
def setUp(self):
self.td = tempfile.TemporaryDirectory()
root = pathlib.Path(self.td.name)
self.projects = root / "projects"
site = self.projects / "site"
(site / "scripts").mkdir(parents=True)
(site / "package.json").write_text(json.dumps({"zipgo": {"deploy": {"site.dom.gabvdl.xyz": "dist/web"}}}))
(site / "scripts" / "deploy.sh").write_text('HOST="other.dom.gabvdl.xyz"\nzipgo -d also.example.com\n')
self.store = _install(root, self.MF, {"a.py": ECHO})
self.deps = main.app.state.ai
self.patches = [patch.object(self.deps, "plugin_store", self.store),
patch("projects.catalog.PROJECTS_DIR", self.projects.resolve())]
for p in self.patches:
p.start()
self.tc = TestClient(main.app)
self.h = {"Authorization": f"Bearer {access.mint_handler(OWNER_UID, 'ship', ttl=600)}"}
def tearDown(self):
for p in self.patches:
p.stop()
self.td.cleanup()
def test_scan(self):
r = self.tc.get("/proxy/tools/plugins/ship/hub/ship/scan?project=site", headers=self.h)
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(r.json()["hosts"], ["also.example.com", "other.dom.gabvdl.xyz", "site.dom.gabvdl.xyz"])
self.assertEqual(r.json()["buildDirs"], {"site.dom.gabvdl.xyz": "dist/web"})
self.assertEqual(self.tc.get("/proxy/tools/plugins/ship/hub/ship/scan?project=../etc",
headers=self.h).status_code, 404)
def test_deploy_records_and_calls_the_sidecar(self):
calls, events = [], []
with patch("runs.sidecar_client._sidecar_call",
side_effect=lambda d, path, body, timeout: calls.append((path, body, timeout)) or {"output": "ok"}), \
patch("security.service.record", side_effect=lambda d, kind, **kw: events.append((kind, kw))):
r = self.tc.post("/proxy/tools/plugins/ship/hub/ship/deploy", headers=self.h,
json={"project": "site", "host": "site.dom.gabvdl.xyz", "actor": "dom"})
bad = self.tc.post("/proxy/tools/plugins/ship/hub/ship/deploy", headers=self.h,
json={"project": "site", "host": "x.example.com", "dir": "../up"})
nohost = self.tc.post("/proxy/tools/plugins/ship/hub/ship/deploy", headers=self.h,
json={"project": "site", "host": "not a host"})
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(calls, [("/ship/deploy", {"project": "site", "host": "site.dom.gabvdl.xyz",
"dir": "dist/web"}, 280)])
self.assertEqual(r.json()["url"], "https://site.dom.gabvdl.xyz")
self.assertEqual(events[0][0], "ship_deploy")
self.assertEqual(events[0][1]["who"], "dom")
self.assertEqual((bad.status_code, nohost.status_code), (400, 400))
def test_audit(self):
events = []
with patch("security.service.record", side_effect=lambda d, kind, **kw: events.append((kind, kw))):
ok = self.tc.post("/proxy/tools/plugins/ship/hub/ship/audit", headers=self.h,
json={"kind": "guard_block", "actor": "dom", "project": "site", "host": "evil.com"})
bad = self.tc.post("/proxy/tools/plugins/ship/hub/ship/audit", headers=self.h,
json={"kind": "sandbox_denial", "actor": "dom"})
self.assertEqual(ok.status_code, 200, ok.text)
self.assertEqual(bad.status_code, 400)
self.assertEqual(events[0][0], "guard_block")
self.assertIn("evil.com", events[0][1]["detail"])
def test_handler_only(self):
# A guest's run token, not the plugin's own handler: refused.
r = self.tc.get("/proxy/tools/plugins/ship/hub/ship/scan?project=site",
headers={"Authorization": f"Bearer {access.mint('cel', ttl=600)}"})
self.assertEqual(r.status_code, 403)
class ScaffoldTemplates(unittest.TestCase):
def test_inline_list(self):
from plugins.hubbridge import _app_templates
with tempfile.TemporaryDirectory() as td:
root = pathlib.Path(td)
(root / "vite-site").mkdir()
(root / "vite-site" / "package.json").write_text(json.dumps({"description": "A site"}))
(root / "datakit").mkdir()
(root / "datakit" / "pyproject.toml").write_text("")
(root / "datakit" / "README.md").write_text("# Datakit\n\n@@DESC@@\nPython kit.\n")
(root / "homelab-service-x").mkdir()
(root / "homelab-service-x" / "package.json").write_text("{}")
(root / "notes").mkdir()
with patch.dict(os.environ, {"TEMPLATES_DIR": str(root)}):
out = _app_templates()
self.assertEqual(out, {"templates": [{"name": "datakit", "description": "Python kit."},
{"name": "vite-site", "description": "A site"}]})
if __name__ == "__main__":
unittest.main()