The core API keys page (backend/apikeys/, business/apiKeys/) and the host
sidecar's /homelab-env writer are retired: a managed plugin that declares
managed.keyHealth gets the same page on its Settings page, generic.
Manifest
- settings.links[]: {label, url} https:// links with {{config.<field>}}
placeholders (URL-quoted; a link whose field is empty is left out).
- managed.keyHealth: alertLimit + currency (alertLimitEur still reads),
secretKey (default: the first hub secret), legacyLedgerTool (a core ledger
tool whose rows count as the plugin's spend: nanobanana → plugin:nanobanana).
Store / metering
- set_secret keeps a non-secret last-4 hint (installed.json → secretHints);
secrets stored before hints get theirs on first read.
- Runtime key settings per plugin (alertLimit, currency, pushAtPct,
pushOnBreak) over the manifest defaults.
- Key health: ok / broken states set the state, other failures are listed
only; a break pushes once (type error), the recovery once ("✅ <Plugin> key
works again", type success); the month pushes at pushAtPct and at 100 %,
each once per month; spend merges the legacy ledger tool.
Routes
- GET /api/plugins/{pid}/spend (plugins.manage): health + hint, settings,
month, byCaller, byModel, 30 days with failures, recent successes +
failures with session links, the links filled in (plugins/keyspend.py).
- PUT /api/plugins/{pid}/key-settings (plugins.manage).
- POST /api/plugins/{pid}/test records the testAction's verdict (its _meter
billed as via "test", or a structured _error whose kind is a key state).
- PUT /api/plugins/{pid}/secrets/{key} on the watched hub key: checked with
testAction before saving — the run's handler token carries the candidate in
memory (plugins.proxy.register_candidate) so its proxy calls use it;
invalid / denied → 400, no-credit / capped → saved, anything else → 502.
- /proxy/tools/nanobanana/<model> (the cli hub edition) reads the plugin's hub
key and feeds its health; Gemini's classify moves to toolproxy/catalog.
Frontend
- PluginKeyHealthSection (status + hint + Test / Replace + links, month with
progress, threshold marker and the limit / currency / alerts form, by caller
/ model + 30-day bars with failure dots, recent calls) on PluginSettingsPage
for the owner; /settings/api-keys redirects to /settings/plugin/nanobanana;
the settings entry, mock, lazy page and unused French strings go.
openapi.json is not re-dumped here (the coordinator does it after Batch 2).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
478 lines
27 KiB
Python
478 lines
27 KiB
Python
"""The tool proxy (toolproxy/): who may call it (a guest's run token, a
|
||
worker's proxy token), what a guest is refused (a group not switched on, Pro
|
||
without the switch, the tools budget spent), Nano Banana priced into the
|
||
tool ledger apart from the Claude budget, 3d-gen jobs and models private to
|
||
the guest who made them, the run scope and the workers' lab sync carrying
|
||
the hub editions. ``python -m pytest test_tool_proxy.py`` from ``backend/``."""
|
||
|
||
import json
|
||
import os
|
||
import pathlib
|
||
import tempfile
|
||
import time
|
||
import unittest
|
||
from unittest import mock
|
||
|
||
TMP = pathlib.Path(tempfile.mkdtemp())
|
||
for k, v in {"DB_PATH": TMP / "x.db", "TRANSCRIPTS_DIR": TMP / "t",
|
||
"WORKSPACE": TMP, "REPO_DIR": TMP, "ARCHIVE_DIR": TMP / "arch",
|
||
"META_PATH": TMP / "meta.json", "WORKERS_PATH": TMP / "w.json",
|
||
"PROFILES_PATH": TMP / "profiles.json",
|
||
"WORKERS_TRANSCRIPTS_DIR": TMP / "mirror",
|
||
"CRON_PATH": TMP / "cron.json", "NOTIFY_PATH": TMP / "n.json",
|
||
"FORMS_PATH": TMP / "f.json", "UI_STATE_PATH": TMP / "ui.json",
|
||
"NOTIF_READ_PATH": TMP / "nr.json",
|
||
"MAIL_TRIGGER_SENDERS_PATH": TMP / "mt.json",
|
||
"USERS_PATH": TMP / "users.json", "AUTH_PATH": TMP / "auth.json",
|
||
"PROJECTS_DIR": TMP / "projects", "PROXY_LEDGER_DIR": TMP / "ledger",
|
||
"WORKER_ENROLL_PATH": TMP / "enroll.json",
|
||
"SECURITY_LOG_PATH": TMP / "sec.jsonl",
|
||
"TOOLS_TOKEN_KEY": TMP / "tools.key", "TOOLS_OWNED_PATH": TMP / "owned.json",
|
||
"TOOLS_MATOMO_PATH": TMP / "matomo.json", "MATOMO_URL": "http://matomo.test",
|
||
"MATOMO_TOKEN": "super-token", "MATOMO_ADMIN_PASSWORD": "admin-pw",
|
||
"THREEDGEN_URL": "http://3d-gen.test",
|
||
"INTERNAL_API_TOKEN": "tok", "GUEST_HOSTS": "claude.example.test",
|
||
"GUEST_PUBLIC_URL": "https://claude.example.test",
|
||
"SIDECAR_TOKEN": "", "PI_TRANSCRIPTS_DIR": "",
|
||
"PLUGINS_DIR": TMP / "plugins"}.items():
|
||
os.environ[k] = str(v)
|
||
(TMP / "projects" / "film").mkdir(parents=True)
|
||
|
||
import httpx # noqa: E402
|
||
from fastapi.testclient import TestClient # noqa: E402
|
||
|
||
import main # noqa: E402
|
||
from toolproxy import access, catalog, matomo, routes # noqa: E402
|
||
from toolproxy.ledger import LEDGER, ToolLedger # noqa: E402
|
||
from toolproxy.owned import OWNED # noqa: E402
|
||
from users.caller import guest_from_record # noqa: E402
|
||
from users.runs import scope_for, tool_scope # noqa: E402
|
||
from users.store import clean_tools # noqa: E402
|
||
from workers import labsync # noqa: E402
|
||
|
||
DEPS = main.app.state.ai
|
||
REPO = pathlib.Path(__file__).resolve().parent.parent
|
||
SID = "0190e0a1-0000-7000-8000-000000000001"
|
||
|
||
|
||
def _gemini_reply(images=1):
|
||
return {"candidates": [{"content": {"parts": [
|
||
{"text": "here"}, *({"inlineData": {"mimeType": "image/png", "data": "iVBORw0K"}}
|
||
for _ in range(images))]}}],
|
||
"usageMetadata": {"promptTokenCount": 10, "candidatesTokenCount": 1300,
|
||
"candidatesTokensDetails": [{"modality": "IMAGE", "tokenCount": 1290},
|
||
{"modality": "TEXT", "tokenCount": 10}]}}
|
||
|
||
|
||
class ToolProxyTest(unittest.TestCase):
|
||
def setUp(self):
|
||
for u in list(DEPS.users.all()):
|
||
DEPS.users.delete(u["id"]) if hasattr(DEPS.users, "delete") else None
|
||
self.uid = self._guest("ana@example.test", "Ana", {"groups": ["images", "3d"]})
|
||
self.other = self._guest("bo@example.test", "Bo", {"groups": ["3d"]})
|
||
self.seen: list[httpx.Request] = []
|
||
self.jobs: dict[str, dict] = {}
|
||
# The Gemini key is the Nano Banana plugin's hub secret.
|
||
store = DEPS.plugin_store
|
||
real_get_raw = store.get_raw
|
||
nb = {"id": "nanobanana", "dir": str(TMP), "config": {},
|
||
"manifest": {"id": "nanobanana", "name": "Nano Banana",
|
||
"secrets": [{"key": "api_key", "scope": "hub"}],
|
||
"managed": {"keyHealth": {"alertLimit": 20.0, "currency": "EUR",
|
||
"pushAtPct": 80, "pushOnBreak": True,
|
||
"secretKey": "api_key",
|
||
"legacyLedgerTool": "nanobanana"}}}}
|
||
get_raw = mock.patch.object(
|
||
store, "get_raw",
|
||
side_effect=lambda uid, pid: nb if pid == "nanobanana" else real_get_raw(uid, pid))
|
||
get_raw.start()
|
||
self.addCleanup(get_raw.stop)
|
||
store.set_secret(None, "nanobanana", "api_key", "AIza-secret", scope="hub")
|
||
|
||
self.mt = {"sites": {1: ["https://gabvdl.xyz", "https://www.gabvdl.xyz"],
|
||
10: ["https://ouliapo.ana.example.test"],
|
||
11: ["https://mix.ana.example.test", "https://gabvdl.xyz"]},
|
||
"users": {}, "access": {}, "tokens": {}, "calls": []}
|
||
|
||
def fake_matomo(req: httpx.Request) -> httpx.Response:
|
||
from urllib.parse import parse_qs
|
||
f = {k: v[0] for k, v in parse_qs(req.content.decode()).items()}
|
||
self.mt["calls"].append(f)
|
||
m, mt = f["method"], self.mt
|
||
if f.get("token_auth") != "super-token" and m != "UsersManager.createAppSpecificTokenAuth":
|
||
return httpx.Response(200, json={"result": "error", "message": "no access"})
|
||
if m == "SitesManager.getAllSites":
|
||
return httpx.Response(200, json={str(i): {"idsite": str(i), "name": f"s{i}",
|
||
"main_url": u[0]}
|
||
for i, u in mt["sites"].items()})
|
||
if m == "SitesManager.getSiteUrlsFromId":
|
||
return httpx.Response(200, json=mt["sites"][int(f["idSite"])])
|
||
if m == "SitesManager.addSite":
|
||
i = max(mt["sites"]) + 1
|
||
mt["sites"][i] = [f["urls[0]"]]
|
||
return httpx.Response(200, json={"value": i})
|
||
if m == "UsersManager.addUser":
|
||
if f["userLogin"] in mt["users"]:
|
||
return httpx.Response(200, json={"result": "error", "message": "exists"})
|
||
mt["users"][f["userLogin"]] = f["password"]
|
||
return httpx.Response(200, json={"result": "success"})
|
||
if m == "UsersManager.deleteUser":
|
||
mt["users"].pop(f["userLogin"], None)
|
||
mt["access"].pop(f["userLogin"], None)
|
||
mt["tokens"] = {t: u for t, u in mt["tokens"].items() if u != f["userLogin"]}
|
||
return httpx.Response(200, json={"result": "success"})
|
||
if m == "UsersManager.setUserAccess":
|
||
mt["access"].setdefault(f["userLogin"], set()).update(
|
||
int(x) for x in f["idSites"].split(","))
|
||
return httpx.Response(200, json={"result": "success"})
|
||
if m == "UsersManager.createAppSpecificTokenAuth":
|
||
if "token_auth" in f or mt["users"].get(f["userLogin"]) != f["passwordConfirmation"]:
|
||
return httpx.Response(200, json={"result": "error", "message": "bad pw"})
|
||
mt["n"] = mt.get("n", 0) + 1
|
||
t = f"tok{mt['n']}"
|
||
mt["tokens"][t] = f["userLogin"]
|
||
return httpx.Response(200, json={"value": t})
|
||
if m == "VisitsSummary.get":
|
||
return httpx.Response(200, json={"nb_visits": 7, "idSite": f["idSite"],
|
||
"period": f.get("period")})
|
||
return httpx.Response(200, json={"result": "error", "message": f"unknown {m}"})
|
||
|
||
def upstream(req: httpx.Request) -> httpx.Response:
|
||
self.seen.append(req)
|
||
if req.url.host == "matomo.test":
|
||
return fake_matomo(req)
|
||
if req.url.host == "generativelanguage.googleapis.com":
|
||
return httpx.Response(200, json=_gemini_reply())
|
||
if req.url.host == "3d-gen.test":
|
||
path = req.url.path
|
||
if req.method == "POST" and path == "/api/jobs":
|
||
jid = f"{len(self.jobs) + 1:012x}"
|
||
self.jobs[jid] = {"id": jid, "status": "queued", "folder": None,
|
||
"user": req.headers.get("remote-user")}
|
||
return httpx.Response(200, json={"id": jid, "status": "queued"})
|
||
if req.method == "GET" and path.startswith("/api/jobs/"):
|
||
j = self.jobs.get(path.rsplit("/", 1)[-1])
|
||
return httpx.Response(200, json=j) if j else httpx.Response(404)
|
||
if req.method == "GET" and path.startswith("/api/models/"):
|
||
# A stream, as the real reply is.
|
||
return httpx.Response(200, stream=httpx.ByteStream(b"glTF-bytes"),
|
||
headers={"content-type": "model/gltf-binary"})
|
||
return httpx.Response(404)
|
||
|
||
routes._client = httpx.AsyncClient(transport=httpx.MockTransport(upstream))
|
||
self.client = TestClient(main.app)
|
||
|
||
def _guest(self, email, name, tools):
|
||
try:
|
||
u = DEPS.users.create(email, name)
|
||
except ValueError:
|
||
u = DEPS.users.by_email(email)
|
||
DEPS.users.update(u["id"], {"tools": tools, "projects": {"film": "chat"},
|
||
"domain": f"{name.lower()}.example.test"})
|
||
return u["id"]
|
||
|
||
def h(self, uid=None, sid=None):
|
||
out = {"Authorization": f"Bearer {access.mint(uid or self.uid)}"}
|
||
if sid:
|
||
out["X-Claude-Code-Session-Id"] = sid
|
||
return out
|
||
|
||
# ── tokens ───────────────────────────────────────────────────────────────
|
||
def test_run_token_names_the_guest_until_it_expires(self):
|
||
tok = access.mint("ana")
|
||
self.assertEqual(access.verify(tok), "ana")
|
||
self.assertIsNone(access.verify(tok[:-2] + "xx"))
|
||
self.assertIsNone(access.verify(tok.replace(".ana.", ".bob.")))
|
||
self.assertIsNone(access.verify(access.mint("ana", ttl=-5)))
|
||
self.assertIsNone(access.verify("nope"))
|
||
|
||
def test_an_unknown_token_is_refused(self):
|
||
r = self.client.get("/proxy/tools/whoami", headers={"Authorization": "Bearer junk"})
|
||
self.assertEqual(r.status_code, 401)
|
||
|
||
def test_whoami_says_what_is_switched_on(self):
|
||
r = self.client.get("/proxy/tools/whoami", headers=self.h())
|
||
self.assertEqual(r.status_code, 200, r.text)
|
||
d = r.json()
|
||
self.assertEqual(d["who"], self.uid)
|
||
self.assertEqual(sorted(d["tools"]), ["3d-gen", "3d-render", "nanobanana"])
|
||
self.assertNotIn("gemini-3-pro-image", d["models"])
|
||
|
||
# ── the user's switches ──────────────────────────────────────────────────
|
||
def test_clean_tools(self):
|
||
self.assertEqual(clean_tools(None), {"groups": ["media"], "pro": False, "budgetUsd": 10.0})
|
||
self.assertEqual(clean_tools({"groups": ["3d", "nope", "images"], "budgetUsd": "5"}),
|
||
{"groups": ["images", "3d"], "pro": False, "budgetUsd": 5.0})
|
||
base = clean_tools({"groups": ["video"], "pro": True, "budgetUsd": 20})
|
||
self.assertEqual(clean_tools({"budgetUsd": 3}, base),
|
||
{"groups": ["video"], "pro": True, "budgetUsd": 3.0})
|
||
|
||
def test_a_partial_update_keeps_the_rest(self):
|
||
DEPS.users.update(self.uid, {"tools": {"pro": True}})
|
||
t = DEPS.users.get(self.uid)["tools"]
|
||
self.assertEqual(t["groups"], ["images", "3d"])
|
||
self.assertTrue(t["pro"])
|
||
DEPS.users.update(self.uid, {"tools": {"pro": False}})
|
||
|
||
# ── Nano Banana ──────────────────────────────────────────────────────────
|
||
def test_prices(self):
|
||
self.assertEqual(catalog.nb_model("gemini-3-pro-image-preview")[0], "gemini-3-pro-image")
|
||
self.assertIsNone(catalog.nb_model("gpt-image-1"))
|
||
usd = catalog.nb_cost("gemini-2.5-flash-image", _gemini_reply()["usageMetadata"])
|
||
# 10 prompt × $0.30 + 1290 image × $30 + 10 text × $2.50, per 1M
|
||
self.assertAlmostEqual(usd, (10 * 0.30 + 1290 * 30 + 10 * 2.5) / 1e6, places=7)
|
||
|
||
def test_nanobanana_goes_up_with_the_hub_key_and_lands_in_the_ledger(self):
|
||
before = LEDGER.spent(self.uid)
|
||
r = self.client.post("/proxy/tools/nanobanana/gemini-2.5-flash-image",
|
||
headers=self.h(), json={"contents": [{"parts": [{"text": "fox"}]}]})
|
||
self.assertEqual(r.status_code, 200, r.text)
|
||
up = self.seen[-1]
|
||
self.assertEqual(up.url.params["key"], "AIza-secret")
|
||
self.assertNotIn("authorization", {k.lower() for k in up.headers})
|
||
self.assertNotIn("AIza-secret", r.text)
|
||
self.assertGreater(LEDGER.spent(self.uid), before)
|
||
line = LEDGER.summary("who", self.uid)["byTool"]["nanobanana"]
|
||
self.assertGreaterEqual(line["units"]["images"], 1)
|
||
|
||
def test_nanobanana_without_the_plugin_key_is_refused(self):
|
||
DEPS.plugin_store.delete_secret(None, "nanobanana", "api_key", scope="hub")
|
||
r = self.client.post("/proxy/tools/nanobanana/gemini-2.5-flash-image",
|
||
headers=self.h(), json={"contents": [{"parts": [{"text": "x"}]}]})
|
||
self.assertEqual((r.status_code, r.json()["error"]["kind"]), (503, "config"))
|
||
|
||
def test_nanobanana_replies_move_the_plugin_key_health(self):
|
||
self.client.post("/proxy/tools/nanobanana/gemini-2.5-flash-image",
|
||
headers=self.h(), json={"contents": [{"parts": [{"text": "fox"}]}]})
|
||
self.assertEqual(DEPS.plugin_store.get_key_health("nanobanana")["status"], "ok")
|
||
|
||
def test_nanobanana_refusals(self):
|
||
body = {"contents": [{"parts": [{"text": "x"}]}]}
|
||
r = self.client.post("/proxy/tools/nanobanana/gemini-2.5-flash-image",
|
||
headers=self.h(self.other), json=body)
|
||
self.assertEqual((r.status_code, r.json()["error"]["kind"]), (403, "group"))
|
||
r = self.client.post("/proxy/tools/nanobanana/gemini-3-pro-image-preview",
|
||
headers=self.h(), json=body)
|
||
self.assertEqual((r.status_code, r.json()["error"]["kind"]), (403, "pro"))
|
||
r = self.client.post("/proxy/tools/nanobanana/not-a-model", headers=self.h(), json=body)
|
||
self.assertEqual(r.status_code, 400)
|
||
DEPS.users.update(self.uid, {"tools": {"budgetUsd": 0}})
|
||
try:
|
||
r = self.client.post("/proxy/tools/nanobanana/gemini-2.5-flash-image",
|
||
headers=self.h(), json=body)
|
||
self.assertEqual((r.status_code, r.json()["error"]["kind"]), (429, "budget"))
|
||
finally:
|
||
DEPS.users.update(self.uid, {"tools": {"budgetUsd": 10}})
|
||
|
||
def test_tool_spend_stays_out_of_the_claude_budget(self):
|
||
from claudeproxy import limits
|
||
self.client.post("/proxy/tools/nanobanana/gemini-2.5-flash-image", headers=self.h(),
|
||
json={"contents": [{"parts": [{"text": "fox"}]}]})
|
||
self.assertEqual(limits.LEDGER.spent("guest", self.uid), 0.0)
|
||
|
||
def test_the_conversation_gets_its_tools_chip_only_when_it_is_theirs(self):
|
||
DEPS.meta_store.update(SID, {"owner": self.uid})
|
||
self.client.post("/proxy/tools/nanobanana/gemini-2.5-flash-image",
|
||
headers=self.h(sid=SID), json={"contents": [{"parts": [{"text": "a"}]}]})
|
||
tools = DEPS.meta_store.peek(SID).get("tools")
|
||
self.assertTrue(tools and tools["usd"] > 0 and tools["tools"]["nanobanana"] >= 1)
|
||
self.assertIsNone(access.session_of(DEPS, access.Who(self.other), SID))
|
||
self.assertEqual(access.session_of(DEPS, access.Who(None), SID), SID)
|
||
|
||
# ── 3d-gen ───────────────────────────────────────────────────────────────
|
||
def test_3d_jobs_are_private_to_their_guest(self):
|
||
r = self.client.post("/proxy/tools/3d-gen/api/jobs", headers=self.h(),
|
||
files={"images": ("a.png", b"png", "image/png")},
|
||
data={"fast": "true"})
|
||
self.assertEqual(r.status_code, 200, r.text)
|
||
jid = r.json()["id"]
|
||
self.assertEqual(self.jobs[jid]["user"], f"guest-{self.uid}")
|
||
self.assertEqual(OWNED.job_of(jid), self.uid)
|
||
self.jobs[jid].update(status="done", folder="fox-1a2b")
|
||
r = self.client.get(f"/proxy/tools/3d-gen/api/jobs/{jid}", headers=self.h())
|
||
self.assertEqual(r.json()["folder"], "fox-1a2b")
|
||
r = self.client.get("/proxy/tools/3d-gen/api/models/fox-1a2b/model.glb", headers=self.h())
|
||
self.assertEqual((r.status_code, r.content), (200, b"glTF-bytes"))
|
||
# Another guest: neither the job nor the model.
|
||
self.assertEqual(self.client.get(f"/proxy/tools/3d-gen/api/jobs/{jid}",
|
||
headers=self.h(self.other)).status_code, 404)
|
||
self.assertEqual(self.client.get("/proxy/tools/3d-gen/api/models/fox-1a2b/model.glb",
|
||
headers=self.h(self.other)).status_code, 404)
|
||
mine = self.client.get("/proxy/tools/3d-gen/api/jobs", headers=self.h()).json()["jobs"]
|
||
self.assertIn(jid, [j["id"] for j in mine])
|
||
theirs = self.client.get("/proxy/tools/3d-gen/api/jobs",
|
||
headers=self.h(self.other)).json()["jobs"]
|
||
self.assertNotIn(jid, [j["id"] for j in theirs])
|
||
# Free but counted.
|
||
line = LEDGER.summary("who", self.uid)["byTool"]["3d-gen"]
|
||
self.assertEqual(line["usd"], 0)
|
||
self.assertGreaterEqual(line["units"]["jobs"], 1)
|
||
|
||
def test_3d_paths_outside_the_allowlist_are_refused(self):
|
||
for method, path in (("POST", "api/models/x/publish"), ("GET", "api/published"),
|
||
("POST", "api/retopo/bulk"), ("GET", "internal/viewer/x"),
|
||
("POST", "api/jobs/retry-all")):
|
||
r = self.client.request(method, f"/proxy/tools/3d-gen/{path}", headers=self.h())
|
||
self.assertEqual(r.status_code, 404, path)
|
||
|
||
# ── a guest's run ────────────────────────────────────────────────────────
|
||
def test_the_run_scope_carries_the_tools_and_their_skills(self):
|
||
u = DEPS.users.get(self.uid)
|
||
scope = scope_for(guest_from_record(u), "film", "chat", ["video-dl", "screenshot"])
|
||
self.assertEqual(scope["tools"]["url"], "https://claude.example.test/proxy/tools")
|
||
self.assertEqual(access.verify(scope["tools"]["token"]), self.uid)
|
||
sk = scope["skills"]
|
||
# The hub editions, ahead of the owner's shared skills (the plugin
|
||
# keeps the first of a name).
|
||
self.assertEqual([s for s in sk if s in ("@nanobanana", "@3d-gen", "@3d-render")],
|
||
["@nanobanana", "@3d-gen", "@3d-render"])
|
||
self.assertLess(sk.index("@nanobanana"), sk.index("screenshot"))
|
||
self.assertIn("Paid tools", scope["systemPrompt"])
|
||
# A live plugin with the same skill name replaces the hub edition.
|
||
from unittest.mock import MagicMock
|
||
fake = MagicMock()
|
||
fake.plugin_store.live_skill_dirs.return_value = [{"name": "nanobanana", "ref": "@plugin:nb"}]
|
||
swapped = tool_scope(guest_from_record(u), fake)["skills"]
|
||
self.assertNotIn("@nanobanana", swapped)
|
||
self.assertIn("@plugin:nb", swapped)
|
||
self.assertIn("@3d-gen", swapped)
|
||
none = guest_from_record({**u, "tools": {"groups": []}})
|
||
self.assertIsNone(tool_scope(none))
|
||
self.assertNotIn("tools", scope_for(none, "film", "chat", []))
|
||
|
||
# ── Matomo (analytics) ───────────────────────────────────────────────────
|
||
def _mt(self, op, body=None, uid=None):
|
||
return self.client.post(f"/proxy/tools/matomo/{op}", json=body or {},
|
||
headers=self.h(uid))
|
||
|
||
def test_matomo_needs_the_analytics_switch(self):
|
||
r = self._mt("sites")
|
||
self.assertEqual(r.status_code, 403, r.text)
|
||
self.assertEqual(r.json()["error"]["kind"], "group")
|
||
|
||
def test_a_guest_sees_only_the_sites_all_on_their_address(self):
|
||
DEPS.users.update(self.uid, {"tools": {"groups": ["analytics"]}})
|
||
d = self._mt("sites").json()
|
||
self.assertEqual([s["id"] for s in d["sites"]], [10])
|
||
self.assertEqual(d["base"], "ana.example.test")
|
||
# Reading: forced onto that one site; someone else's site is a 404.
|
||
r = self._mt("report", {"site": 10, "method": "VisitsSummary.get",
|
||
"params": {"period": "month", "idSite": "1", "token_auth": "x"}})
|
||
self.assertEqual(r.status_code, 200, r.text)
|
||
self.assertEqual(r.json(), {"nb_visits": 7, "idSite": "10", "period": "month"})
|
||
for site in (1, 11, "all", "1,10"):
|
||
r = self._mt("report", {"site": site, "method": "VisitsSummary.get"})
|
||
self.assertIn(r.status_code, (400, 404), site)
|
||
# Only the report modules' get* methods.
|
||
for method in ("UsersManager.getUsers", "SitesManager.getAllSites",
|
||
"MultiSites.getAll", "API.getBulkRequest", "VisitsSummary.delete",
|
||
"Annotations.add"):
|
||
r = self._mt("report", {"site": 10, "method": method})
|
||
self.assertEqual(r.status_code, 403, method)
|
||
line = LEDGER.summary("who", self.uid)["byTool"]["matomo"]
|
||
self.assertEqual(line["usd"], 0)
|
||
|
||
def test_a_guest_adds_sites_only_on_their_address(self):
|
||
DEPS.users.update(self.uid, {"tools": {"groups": ["analytics"]}})
|
||
r = self._mt("add-site", {"url": "https://jeu.ana.example.test/x"})
|
||
self.assertEqual(r.status_code, 200, r.text)
|
||
d = r.json()
|
||
self.assertTrue(d["created"])
|
||
self.assertIn(f"'setSiteId', '{d['site']['id']}'", d["tracking"])
|
||
add = [c for c in self.mt["calls"] if c["method"] == "SitesManager.addSite"][-1]
|
||
self.assertEqual((add["excludedUserAgents"], add["timezone"]),
|
||
("HeadlessChrome", "Europe/Paris"))
|
||
again = self._mt("add-site", {"url": "jeu.ana.example.test"}).json()
|
||
self.assertEqual((again["created"], again["site"]["id"]), (False, d["site"]["id"]))
|
||
for url in ("https://gabvdl.xyz", "https://evil-ana.example.test",
|
||
"https://ana.example.test.evil.xyz", "javascript:alert(1)"):
|
||
self.assertIn(self._mt("add-site", {"url": url}).status_code, (400, 403), url)
|
||
# A host already on someone else's site.
|
||
self.assertEqual(self._mt("add-site", {"url": "https://mix.ana.example.test"})
|
||
.status_code, 409)
|
||
|
||
def test_a_guest_view_only_key_covers_their_sites_and_rotates(self):
|
||
DEPS.users.update(self.uid, {"tools": {"groups": ["analytics"]}})
|
||
d = self._mt("token").json()
|
||
login = f"guest-{self.uid}-viewer"
|
||
self.assertEqual((d["login"], d["sites"], d["rotated"]), (login, [10], False))
|
||
self.assertEqual(self.mt["access"][login], {10})
|
||
self.assertEqual(self.mt["tokens"][d["token"]], login)
|
||
# The same key on the next call; a site added later joins its access.
|
||
self.assertEqual(self._mt("token").json()["token"], d["token"])
|
||
self._mt("add-site", {"url": "https://autre.ana.example.test"})
|
||
self.assertEqual(self.mt["access"][login], {10, 12})
|
||
r = self._mt("token", {"rotate": True}).json()
|
||
self.assertTrue(r["rotated"])
|
||
self.assertNotEqual(r["token"], d["token"])
|
||
self.assertNotIn(d["token"], self.mt["tokens"])
|
||
self.assertEqual(self.mt["access"][login], {10, 12})
|
||
# The viewer's password never leaves the hub.
|
||
self.assertNotIn("password", r)
|
||
|
||
def test_a_guest_without_sites_gets_no_key(self):
|
||
DEPS.users.update(self.other, {"tools": {"groups": ["analytics"]}})
|
||
self.assertEqual(self._mt("token", uid=self.other).status_code, 404)
|
||
|
||
def test_matomo_unknown_op(self):
|
||
DEPS.users.update(self.uid, {"tools": {"groups": ["analytics"]}})
|
||
self.assertEqual(self._mt("delete-site", {"site": 10}).status_code, 404)
|
||
|
||
def test_matomo_ownership_rules(self):
|
||
self.assertTrue(matomo.method_ok("Events.getCategory"))
|
||
self.assertTrue(matomo.method_ok("API.get"))
|
||
self.assertFalse(matomo.method_ok("Events.deleteAll"))
|
||
self.assertFalse(matomo.method_ok("UsersManager.getUser"))
|
||
site = {"main_url": "https://a.dom.xyz", "alias_urls": ["http://b.a.dom.xyz"]}
|
||
self.assertTrue(matomo.is_theirs(site, "dom.xyz"))
|
||
self.assertFalse(matomo.is_theirs({**site, "alias_urls": ["https://xdom.xyz"]}, "dom.xyz"))
|
||
self.assertFalse(matomo.is_theirs(site, ""))
|
||
|
||
# ── the workers' lab sync ────────────────────────────────────────────────
|
||
def test_a_guest_computer_gets_the_hub_editions_with_its_token(self):
|
||
DEPS.worker_store.put({"id": "gpc", "name": "pc", "url": "http://x", "token": "t",
|
||
"owner": self.uid, "proxyToken": "p" * 43})
|
||
try:
|
||
b = labsync.for_worker(DEPS.worker_store.get("gpc"))
|
||
self.assertEqual(sorted(b["skills"]), ["3d-gen", "3d-render", "nanobanana"])
|
||
import base64
|
||
hub = json.loads(base64.b64decode(b["skills"]["nanobanana"]["hub.json"]))
|
||
self.assertEqual(hub, {"url": "https://claude.example.test/proxy/tools",
|
||
"token": "p" * 43})
|
||
DEPS.worker_store.patch("gpc", {"proxyToken": "q" * 43})
|
||
self.assertNotEqual(labsync.for_worker(DEPS.worker_store.get("gpc"))["hash"],
|
||
b["hash"])
|
||
finally:
|
||
DEPS.worker_store.delete("gpc")
|
||
|
||
def test_an_owner_worker_is_offered_the_hub_editions(self):
|
||
names = {i["name"] for i in labsync.all_items() if i.get("hub")}
|
||
self.assertEqual(names, set(catalog.HUB_SKILLS))
|
||
self.assertIsNotNone(access.resolve(DEPS, "x", guest_surface=False) or True)
|
||
|
||
def test_the_hub_editions_share_one_client(self):
|
||
copies = sorted((REPO / "cli" / "skills").glob("*/scripts/hubclient.py"))
|
||
self.assertEqual(len(copies), len(catalog.HUB_SKILLS))
|
||
self.assertEqual(len({c.read_text() for c in copies}), 1)
|
||
for name in catalog.HUB_SKILLS:
|
||
script = REPO / "cli" / "skills" / name / "scripts" / name
|
||
self.assertTrue(script.is_file() and os.access(script, os.X_OK), name)
|
||
|
||
|
||
class LedgerTest(unittest.TestCase):
|
||
def test_sums_per_caller_tool_and_session(self):
|
||
led = ToolLedger(TMP / "ledger-unit")
|
||
led.record({"tool": "nanobanana", "who": "ana", "guest": "ana", "usd": 0.04,
|
||
"units": {"images": 1}, "session": SID})
|
||
led.record({"tool": "3d-gen", "who": "ana", "guest": "ana", "usd": 0,
|
||
"units": {"jobs": 1}, "session": SID})
|
||
self.assertAlmostEqual(led.spent("ana"), 0.04)
|
||
again = ToolLedger(TMP / "ledger-unit") # rebuilt from the file
|
||
s = again.summary("who", "ana")
|
||
self.assertEqual((s["calls"], s["byTool"]["3d-gen"]["units"]["jobs"]), (2, 1))
|
||
self.assertEqual(again.session(SID)["tools"], {"nanobanana": 1, "3d-gen": 1})
|
||
|
||
|
||
if __name__ == "__main__":
|
||
unittest.main()
|