Files
ai-agent/backend/test_tool_proxy_meta.py
gabrielvidalandClaude Opus 5.5 74dbc55d03 feat(plugins): Settings → API keys folds into the plugin's Hub key section
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>
2026-11-26 11:33:41 +01:00

441 lines
23 KiB
Python

"""The tool proxy's Meta Business group (toolproxy/meta.py → the Graph API):
a guest connects their own key on their page — refused when it may write or
reaches nothing, never shown again —; their runs read it through the proxy
with GETs on an allowlist of paths only, the key scrubbed out of every answer
(paging links, a Page's own token); a guest never reads someone else's; the
owner reads a guest's with ``as``; per-day ads / Instagram / Page bundles, a
retired metric dropped with a note; the daily snapshot on disk and ``history``;
a dead key marks the connection and pushes once.
``python -m pytest test_tool_proxy_meta.py`` from ``backend/``."""
import asyncio
import datetime as dt
import json
import os
import pathlib
import stat
import tempfile
import unittest
from urllib.parse import parse_qs
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_META_PATH": TMP / "tools-meta.json", "META_SNAPSHOT_DIR": TMP / "snaps",
"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, meta, metaroutes, routes, snapshots # noqa: E402
from toolproxy.ledger import LEDGER # noqa: E402
from users.caller import SESSION_COOKIE # noqa: E402
DEPS = main.app.state.ai
SID = "0190e0a1-0000-7000-8000-0000000000bb"
GOOD = "EAA" + "g" * 80
WRITE = "EAA" + "w" * 80
DEAD = "EAA" + "d" * 80
EMPTY = "EAA" + "e" * 80
PAGE_TOK = "EAApage" + "p" * 70
READ = ["ads_read", "read_insights", "pages_show_list", "pages_read_engagement",
"instagram_basic", "instagram_manage_insights"]
class FakeGraph:
"""Just enough of the Graph API: the key's identity and permissions, one
ad account, one Page with its Instagram account, insights per day."""
def __init__(self):
self.seen: list[httpx.Request] = []
self.dead: set[str] = {DEAD}
self.no_combined = False # refuse breakdown=age,gender together
@staticmethod
def err(code, msg, status=400):
return httpx.Response(status, json={"error": {"message": msg, "type": "OAuthException",
"code": code}})
def __call__(self, req: httpx.Request) -> httpx.Response:
self.seen.append(req)
q = {k: v[0] for k, v in parse_qs(req.url.query.decode()).items()}
tok = q.get("access_token", "")
path = req.url.path.split("/v27.0/", 1)[-1]
if tok in self.dead:
return self.err(190, "Error validating access token: Session has expired")
if tok not in (GOOD, WRITE, EMPTY, PAGE_TOK):
return self.err(190, "Invalid OAuth access token")
if path == "me":
return httpx.Response(200, json={"id": "9001", "name": "calamite-reader"})
if path == "me/permissions":
perms = READ + (["ads_management"] if tok == WRITE else [])
return httpx.Response(200, json={"data": [{"permission": p, "status": "granted"}
for p in perms]})
if path == "me/adaccounts":
data = [] if tok == EMPTY else [{"id": "act_111", "account_id": "111",
"name": "CALAMITE", "currency": "EUR",
"timezone_name": "Europe/Berlin",
"account_status": 1}]
return httpx.Response(200, json={"data": data})
if path == "me/accounts":
data = [] if tok == EMPTY else [{
"id": "222", "name": "CALAMITE Page", "access_token": PAGE_TOK,
"instagram_business_account": {"id": "333", "username": "calamite.band",
"followers_count": 1186}}]
return httpx.Response(200, json={"data": data})
if path == "act_111/insights":
tr = json.loads(q.get("time_range") or "{}")
days = []
d = dt.date.fromisoformat(tr["since"]) if tr else dt.date(2026, 11, 20)
while tr and d <= dt.date.fromisoformat(tr["until"]):
days.append(d.isoformat())
d += dt.timedelta(days=1)
rows = [{"date_start": day, "date_stop": day, "ad_name": f"Reel {g}",
"adset_name": "A", "age": "25-34", "gender": g, "spend": "1.50",
"impressions": "300",
"actions": [{"action_type": "video_view", "value": "40"}]}
for day in days for g in ("female", "male")]
if q.get("after") == "c1":
return httpx.Response(200, json={"data": rows[1:]})
return httpx.Response(200, json={
"data": rows[:1],
"paging": {"cursors": {"before": "c0", "after": "c1"},
"next": f"https://graph.facebook.com/v27.0/act_111/insights?"
f"access_token={tok}&after=c1"}})
if path == "act_111/campaigns":
return httpx.Response(200, json={"data": [{"id": "5", "name": "Single",
"status": "ACTIVE"}],
"paging": {"cursors": {"after": "z"},
"next": f"https://x/?access_token={tok}"}})
if path == "333/insights":
metrics = q.get("metric", "").split(",")
if q.get("metric_type") == "total_value":
if "profile_views" in metrics:
return self.err(100, "(#100) metric[11] must be one of the following values")
if q.get("breakdown") == "follow_type":
return httpx.Response(200, json={"data": [{"name": "follows_and_unfollows",
"total_value": {"breakdowns": [{"results": [
{"dimension_values": ["FOLLOWER"], "value": 9},
{"dimension_values": ["NON_FOLLOWER"], "value": 1}]}]}}]})
if q.get("breakdown") == "age,gender" and self.no_combined:
return self.err(100, "(#100) Incompatible breakdowns")
if q.get("breakdown"):
return httpx.Response(200, json={"data": [{"name": "follower_demographics",
"total_value": {"breakdowns": [{"results": [
{"dimension_values": ["25-34", "F"], "value": 120}]}]}}]})
return httpx.Response(200, json={"data": [{"name": m, "total_value": {"value": 5}}
for m in metrics]})
# follower_count: a series, end_time = the end of the day counted.
since = int(q["since"])
until = int(q["until"])
vals = []
t = since
while t < until:
end = dt.datetime.fromtimestamp(t, meta.TZ).date() + dt.timedelta(days=1)
vals.append({"value": 7, "end_time": f"{end.isoformat()}T08:00:00+0000"})
t += 86400
return httpx.Response(200, json={"data": [{"name": "follower_count", "values": vals}]})
if path == "222/insights":
if tok != PAGE_TOK:
return self.err(210, "A page access token is required to request this resource")
metrics = q["metric"].split(",")
if "page_impressions_unique" in metrics:
return self.err(100, "(#100) The value must be a valid insights metric")
s, u = dt.date.fromisoformat(q["since"]), dt.date.fromisoformat(q["until"])
vals = [{"value": 3, "end_time": (s + dt.timedelta(days=i + 1)).isoformat()
+ "T08:00:00+0000"} for i in range((u - s).days)]
return httpx.Response(200, json={"data": [{"name": m, "values": vals}
for m in metrics]})
if path == "333/media":
ts = (dt.datetime.now(dt.timezone.utc) - dt.timedelta(days=2)).strftime(
"%Y-%m-%dT%H:%M:%S+0000")
return httpx.Response(200, json={"data": [
{"id": "777", "media_product_type": "REELS", "timestamp": ts,
"caption": "Bout de fi", "like_count": 50},
{"id": "778", "media_product_type": "FEED", "timestamp": "2025-01-01T10:00:00+0000"}]})
if path == "777/insights":
return httpx.Response(200, json={"data": [{"name": m, "values": [{"value": 11}]}
for m in q["metric"].split(",")]})
if path == "333":
return httpx.Response(200, json={"username": "calamite.band", "followers_count": 1190,
"follows_count": 80, "media_count": 40})
return self.err(100, f"Unknown path {path}")
class MetaToolTest(unittest.TestCase):
def setUp(self):
meta.STORE.path.unlink(missing_ok=True)
meta._BAD.clear()
self.uid = self._guest("cel@example.test", "Cel", {"groups": ["meta"]})
self.other = self._guest("bo@example.test", "Bo", {"groups": ["meta"]})
self.off = self._guest("di@example.test", "Di", {"groups": ["3d"]})
self.graph = FakeGraph()
routes._client = httpx.AsyncClient(transport=httpx.MockTransport(self.graph))
self.client = TestClient(main.app)
self.backfills: list[str] = []
self._backfill = metaroutes.backfill
metaroutes.backfill = self.backfills.append
def tearDown(self):
metaroutes.backfill = self._backfill
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"}})
return u["id"]
def web(self, method, path, uid=None, **kw):
if uid is None:
return self.client.request(method, path, headers={"X-Internal-Auth": "tok"}, **kw)
c = TestClient(main.app, base_url="https://claude.example.test")
c.cookies.set(SESSION_COOKIE, DEPS.auth.open_session(uid))
return c.request(method, path, **kw)
def connect(self, uid=None, token=GOOD):
return self.web("PUT", "/api/me/meta", uid=uid or self.uid, json={"token": token})
def op(self, name, body=None, uid=None, owner=False):
h = ({"Authorization": "Bearer tok"} if owner
else {"Authorization": f"Bearer {access.mint(uid or self.uid)}",
"X-Claude-Code-Session-Id": SID})
return self.client.post(f"/proxy/tools/meta/{name}", json=body or {}, headers=h)
def assertNoKey(self, text):
for k in (GOOD, PAGE_TOK, WRITE):
self.assertNotIn(k, text)
# ── connecting ───────────────────────────────────────────────────────────
def test_connect_checks_the_key_and_never_shows_it_again(self):
r = self.connect()
self.assertEqual(r.status_code, 200, r.text)
d = r.json()
c = d["connection"]
self.assertTrue(d["enabled"])
self.assertEqual(d["scopesAsked"], READ)
self.assertEqual(c["user"], {"id": "9001", "name": "calamite-reader"})
self.assertEqual([a["id"] for a in c["adAccounts"]], ["act_111"])
self.assertEqual(c["instagram"][0]["username"], "calamite.band")
self.assertEqual(c["sees"], {"ads": True, "instagram": True, "page": True})
self.assertNoKey(r.text)
self.assertNoKey(self.web("GET", "/api/me/meta", uid=self.uid).text)
self.assertNoKey(self.web("GET", f"/api/users/{self.uid}/meta").text)
self.assertEqual(self.backfills, [self.uid])
# Kept 0600, with the Page's own key beside it.
self.assertEqual(stat.S_IMODE(meta.STORE.path.stat().st_mode), 0o600)
self.assertEqual(meta.STORE.get(self.uid)["pageTokens"], {"222": PAGE_TOK})
def test_a_key_that_may_write_or_reaches_nothing_is_refused(self):
r = self.connect(token=WRITE)
self.assertEqual(r.status_code, 400)
self.assertIn("ads_management", r.text)
self.assertIn("more than read", r.text)
self.assertEqual(self.connect(token=EMPTY).status_code, 400)
self.assertEqual(self.connect(token="hello").status_code, 400)
r = self.connect(token=DEAD)
self.assertEqual(r.status_code, 400)
self.assertIn("doesn't accept this key", r.text)
self.assertFalse(meta.STORE.get(self.uid))
def test_only_a_guest_with_the_switch_connects(self):
self.assertEqual(self.connect(uid=self.off).status_code, 403)
self.assertEqual(self.web("PUT", "/api/me/meta", json={"token": GOOD}).status_code, 403)
def test_disconnect_forgets_the_key(self):
self.connect()
r = self.web("DELETE", "/api/me/meta", uid=self.uid)
self.assertFalse(r.json()["connection"]["connected"])
self.assertFalse(meta.STORE.get(self.uid))
self.connect()
self.assertFalse(self.web("DELETE", f"/api/users/{self.uid}/meta")
.json()["connection"]["connected"])
# ── reading through the proxy ────────────────────────────────────────────
def test_the_group_and_a_connection_are_needed(self):
r = self.op("status", uid=self.off)
self.assertEqual((r.status_code, r.json()["error"]["kind"]), (403, "group"))
r = self.op("days")
self.assertEqual((r.status_code, r.json()["error"]["kind"]), (404, "not-connected"))
def test_get_reads_only_allowlisted_paths_and_scrubs_the_key(self):
self.connect()
r = self.op("get", {"path": "act_111/campaigns", "params": {"fields": "name,status"}})
self.assertEqual(r.status_code, 200, r.text)
self.assertNoKey(r.text)
self.assertEqual(r.json()["paging"], {"cursors": {"after": "z"}, "more": True})
# ``all`` follows the cursors itself.
r = self.op("get", {"path": "act_111/insights", "all": True,
"params": {"time_range": {"since": "2026-11-20", "until": "2026-11-21"}}})
self.assertEqual(len(r.json()["data"]), 4)
self.assertNoKey(r.text)
# me/accounts carries a Page's key: dropped.
r = self.op("get", {"path": "me/accounts"})
self.assertNoKey(r.text)
self.assertNotIn("access_token", r.text)
for path in ("oauth/access_token", "222/feed", "act_111/adsets/../x", "debug_token",
"333/subscribed_apps", "act_111/customaudiences", "", "v27.0/me/feed"):
self.assertEqual(self.op("get", {"path": path}).status_code, 403, path)
for bad in ({"method": "post"}, {"access_token": "x"}, {"batch": "[]"},
{"Method": "POST"}, {"a b": 1}):
self.assertEqual(self.op("get", {"path": "me", "params": bad}).status_code, 400, bad)
# Someone else's ad account, by id: not this connection's.
self.assertEqual(self.op("get", {"path": "act_999/insights"}).status_code, 404)
# Only ever a GET.
self.assertEqual({q.method for q in self.graph.seen}, {"GET"})
line = LEDGER.summary("who", self.uid)["byTool"]["meta"]
self.assertEqual(line["usd"], 0)
self.assertGreater(line["units"]["calls"], 0)
def test_days_bundles_ads_instagram_and_the_page(self):
self.connect()
y = meta.today() - dt.timedelta(days=1)
since = (y - dt.timedelta(days=1)).isoformat()
r = self.op("days", {"since": since, "until": y.isoformat()})
self.assertEqual(r.status_code, 200, r.text)
d = r.json()
self.assertEqual(sorted(d["days"]), [since, y.isoformat()])
day = d["days"][y.isoformat()]
self.assertEqual([x["gender"] for x in day["ads"]["act_111"]], ["female", "male"])
ig = day["instagram"]["333"]
self.assertEqual((ig["follower_count"], ig["follows"], ig["unfollows"], ig["reach"]),
(7, 9, 1, 5))
self.assertNotIn("profile_views", ig)
# The Page answered with its own key; a retired metric dropped, with a note.
self.assertEqual(day["page"]["222"]["page_follows"], 3)
self.assertNotIn("page_impressions_unique", day["page"]["222"])
noted = {e.get("metric") for e in d["errors"]}
self.assertTrue({"profile_views", "page_impressions_unique"} <= noted)
self.assertNoKey(r.text)
# Not today, not the future, not too many days.
self.assertEqual(self.op("days", {"since": "2026-01-01", "until": "2026-12-31"})
.status_code, 400)
self.assertEqual(self.op("days", {"since": "nope"}).status_code, 400)
def test_media_and_audience(self):
self.connect()
d = self.op("media").json()
reels = d["media"]["333"]
self.assertEqual([m["id"] for m in reels], ["777"]) # 778 is too old
self.assertEqual(reels[0]["insights"]["ig_reels_avg_watch_time"], 11)
a = self.op("audience").json()["instagram"]["333"]
self.assertEqual(a["profile"]["followers_count"], 1190)
self.assertEqual(a["age_gender"], [{"key": ["25-34", "F"], "value": 120}])
def test_audience_asks_age_and_gender_apart_when_refused_together(self):
self.connect()
self.graph.no_combined = True
a = self.op("audience").json()
ig = a["instagram"]["333"]
self.assertNotIn("age_gender", ig)
self.assertIn("age", ig)
self.assertIn("gender", ig)
self.assertEqual(a["errors"], [])
def test_a_guest_never_reads_another_guests_connection(self):
self.connect()
r = self.op("status", uid=self.other)
self.assertEqual(r.json()["error"]["kind"], "not-connected")
# ``as`` is the owner's only.
r = self.op("status", {"as": self.uid}, uid=self.other)
self.assertEqual(r.status_code, 404)
def test_the_owner_reads_a_guests_connection(self):
self.assertEqual(self.op("status", owner=True).status_code, 404)
self.connect()
r = self.op("status", owner=True)
self.assertEqual((r.status_code, r.json()["as"]), (200, self.uid), r.text)
self.connect(uid=self.other)
self.assertEqual(self.op("status", owner=True).status_code, 400)
self.assertEqual(self.op("status", {"as": self.other}, owner=True).json()["as"],
self.other)
def test_a_dead_key_marks_the_connection_and_pushes_once(self):
self.connect()
self.graph.dead.add(GOOD)
sent = []
from users import deliver
real = deliver.to_guests
deliver.to_guests = lambda deps, uids, *a, **k: sent.append(uids)
try:
r = self.op("get", {"path": "me"})
self.assertEqual((r.status_code, r.json()["error"]["kind"]), (403, "meta-token"))
self.op("get", {"path": "me"})
finally:
deliver.to_guests = real
# The guest once (the owner hears it on his own channel), however many calls fail.
self.assertEqual(sent.count([self.uid]), 1)
err = self.web("GET", "/api/me/meta", uid=self.uid).json()["connection"]["error"]
self.assertEqual(err["kind"], "meta-token")
self.assertFalse(snapshots.due(DEPS, self.uid))
# A new key clears it.
self.graph.dead.discard(GOOD)
self.assertIsNone(self.connect().json()["connection"]["error"])
# ── the daily snapshot ───────────────────────────────────────────────────
def test_the_snapshot_saves_each_day_and_history_reads_them(self):
self.connect()
client = httpx.AsyncClient(transport=httpx.MockTransport(self.graph))
out = asyncio.run(meta.snapshot(client, self.uid))
self.assertTrue(out["ok"])
self.assertEqual(out["days"], meta.REFRESH_DAYS)
y = (meta.today() - dt.timedelta(days=1)).isoformat()
f = json.loads((TMP / "snaps" / self.uid / f"{y}.json").read_text())
self.assertIn("media", f)
self.assertIn("audience", f)
self.assertNoKey(json.dumps(f))
st = self.web("GET", "/api/me/meta", uid=self.uid).json()["connection"]["snapshot"]
self.assertEqual((st["ok"], st["day"], st["days"]),
(True, y, meta.REFRESH_DAYS))
self.assertFalse(snapshots.due(DEPS, self.uid))
h = self.op("history", {"since": (meta.today() - dt.timedelta(days=30)).isoformat(),
"parts": "instagram"}).json()
self.assertEqual(len(h["days"]), meta.REFRESH_DAYS)
self.assertEqual(set(h["days"][y]), {"instagram", "date", "takenAt"})
def test_due_waits_for_the_morning_and_the_switch(self):
self.connect()
morning = dt.datetime.now(meta.TZ).replace(hour=8)
self.assertTrue(snapshots.due(DEPS, self.uid, morning))
self.assertFalse(snapshots.due(DEPS, self.uid, morning.replace(hour=3)))
DEPS.users.update(self.uid, {"tools": {"groups": []}})
self.assertFalse(snapshots.due(DEPS, self.uid, morning))
# ── the pieces ───────────────────────────────────────────────────────────
def test_scrub_and_paths(self):
out = meta.scrub({"a": f"x access_token={GOOD}&b=1", "access_token": GOOD,
"paging": {"next": "u", "cursors": {"after": "c"}},
"l": [GOOD]}, (GOOD,))
self.assertEqual(out, {"a": "x access_token=***&b=1",
"paging": {"cursors": {"after": "c"}, "more": True},
"l": ["***"]})
self.assertTrue(meta.path_ok("act_1/insights"))
self.assertTrue(meta.path_ok("17841400000000000/media"))
self.assertTrue(meta.path_ok("222_333/insights"))
self.assertFalse(meta.path_ok("act_1/adsets/copies"))
self.assertFalse(meta.path_ok("me/feed"))
if __name__ == "__main__":
unittest.main()