Files
ai-agent/backend/test_plugin_key_health.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

375 lines
19 KiB
Python

"""A managed plugin's hub key (``managed.keyHealth``) — what Settings → API
keys was before it folded into the plugin's page (2026-11-26): the manifest's
``settings.links`` / ``legacyLedgerTool`` / ``secretKey``, the last-4 hint, the
owner's runtime alert settings, break / recovery pushes and the 80 % + 100 %
spend pushes (each once), the spend view (legacy ledger rows merged), and the
routes: ``/spend``, ``/key-settings``, Test recording the key's health and a
new key checked before it is saved (refused when invalid / denied, kept when
the credit is out). ``python -m pytest test_plugin_key_health.py`` from
``backend/``."""
from __future__ import annotations
import json
import os
import pathlib
import tempfile
import time
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",
"PROXY_LEDGER_DIR": TMP / "ledger", "TOOLS_TOKEN_KEY": TMP / "tools.key",
"SIDECAR_TOKEN": "", "PI_TRANSCRIPTS_DIR": ""}.items():
os.environ.setdefault(k, str(v))
import httpx # noqa: E402
from fastapi.testclient import TestClient # noqa: E402
import main # noqa: E402
from plugins import keyspend, metering # noqa: E402
from plugins.manifest import ManifestError, validate_manifest # noqa: E402
from plugins.runner import ActionError # noqa: E402
from plugins.store import OWNER_UID, PluginStore # noqa: E402
from toolproxy import access, catalog # noqa: E402
from toolproxy.ledger import LEDGER, month_of # noqa: E402
OWNER_H = {"X-Internal-Auth": os.environ["INTERNAL_API_TOKEN"]}
KEY = "AIzaSyA-old-key-0000000000000000000wxyz"
NEW = "AIzaSyB-new-key-1111111111111111111abcd"
MANIFEST = {
"schema": 1, "id": "kh", "name": "Key Health",
"secrets": [{"key": "api_key", "label": "API key", "scope": "hub"}],
"settings": {
"fields": [{"key": "project", "label": "Project", "type": "text", "default": "proj-1"},
{"key": "billing", "label": "Billing", "type": "text", "default": ""}],
"links": [
{"label": "Console", "url": "https://console.example.test/creds?project={{config.project}}"},
{"label": "Billing", "url": "https://console.example.test/billing/{{config.billing}}"},
{"label": "Studio", "url": "https://studio.example.test/apikey"},
],
"testAction": "inspect",
},
"proxy": {
"baseUrl": "https://up.example.test/v1", "handlerOnly": True,
"auth": {"in": "query", "name": "key", "secret": "api_key"},
"allow": [{"method": "POST", "path": "^models/[a-z0-9.-]+:generateContent$"}],
},
"managed": {
"metered": True,
"keyHealth": {"alertLimit": 10, "currency": "USD", "pushAtPct": 80,
"legacyLedgerTool": "khlegacy"},
},
"actions": {"inspect": {"script": "handlers/inspect.py"}},
}
FILES = {"handlers/inspect.py": "print('{}')\n"}
def _write(root: pathlib.Path, manifest: dict) -> 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)
p.write_text(content, encoding="utf-8")
return root
class _Env:
"""The ``kh`` plugin installed for the owner in a temp store on the live app,
pushes captured."""
def __init__(self, td: str, manifest: dict | None = None):
self.root = pathlib.Path(td)
self.deps = main.app.state.ai
self.store = PluginStore(self.root / "data")
self.store.install(OWNER_UID, str(_write(self.root / "src", manifest or MANIFEST)),
is_owner=True, approve=True)
self.pushes: list[dict] = []
def __enter__(self):
self._p = [patch.object(self.deps, "plugin_store", self.store),
patch("notifications.routes._create_notify",
side_effect=lambda d, x: self.pushes.append(x))]
for p in self._p:
p.start()
return self
def __exit__(self, *a):
for p in reversed(self._p):
p.stop()
@property
def rec(self):
return self.store.get_raw(OWNER_UID, "kh")
@property
def mf(self):
return self.rec["manifest"]
class TestManifest(unittest.TestCase):
def test_key_health_and_links_are_kept(self):
with tempfile.TemporaryDirectory() as td:
mf = validate_manifest(_write(pathlib.Path(td) / "kh", MANIFEST))
kh = mf["managed"]["keyHealth"]
self.assertEqual((kh["alertLimit"], kh["currency"], kh["secretKey"], kh["legacyLedgerTool"]),
(10.0, "USD", "api_key", "khlegacy"))
self.assertEqual([ln["label"] for ln in mf["settings"]["links"]], ["Console", "Billing", "Studio"])
def test_the_older_alert_limit_eur_still_reads(self):
m = json.loads(json.dumps(MANIFEST))
m["managed"]["keyHealth"] = {"alertLimitEur": 20}
with tempfile.TemporaryDirectory() as td:
kh = validate_manifest(_write(pathlib.Path(td) / "kh", m))["managed"]["keyHealth"]
self.assertEqual((kh["alertLimit"], kh["currency"]), (20.0, "EUR"))
def test_bad_links_and_secret_keys_are_refused(self):
for patch_ in (
{"settings": {**MANIFEST["settings"], "links": [{"label": "x", "url": "http://plain.test"}]}},
{"settings": {**MANIFEST["settings"],
"links": [{"label": "x", "url": "https://a.test/{{config.nope}}"}]}},
{"managed": {"keyHealth": {"secretKey": "missing"}}},
{"managed": {"keyHealth": {"legacyLedgerTool": "plugin:kh"}}},
):
m = {**json.loads(json.dumps(MANIFEST)), **patch_}
with tempfile.TemporaryDirectory() as td, self.assertRaises(ManifestError):
validate_manifest(_write(pathlib.Path(td) / "kh", m))
class TestStore(unittest.TestCase):
def test_the_hint_is_the_last_four_and_never_the_key(self):
with tempfile.TemporaryDirectory() as td:
s = PluginStore(pathlib.Path(td))
s.set_secret(None, "kh", "api_key", KEY, scope="hub")
self.assertEqual(s.secret_hint(None, "kh", "api_key", scope="hub")["last4"], "wxyz")
index = (pathlib.Path(td) / "installed.json").read_text()
self.assertNotIn(KEY, index)
self.assertIn("wxyz", index)
s.delete_secret(None, "kh", "api_key", scope="hub")
self.assertIsNone(s.secret_hint(None, "kh", "api_key", scope="hub"))
def test_a_secret_from_before_hints_gets_one(self):
with tempfile.TemporaryDirectory() as td:
s = PluginStore(pathlib.Path(td))
s.set_secret(None, "kh", "api_key", KEY, scope="hub")
s._state["secretHints"] = {}
self.assertEqual(s.secret_hint(None, "kh", "api_key", scope="hub")["last4"], "wxyz")
def test_key_settings_override_the_manifest(self):
with tempfile.TemporaryDirectory() as td:
s = PluginStore(pathlib.Path(td))
mf = {"managed": {"keyHealth": {"alertLimit": 10, "currency": "USD", "pushAtPct": 80,
"pushOnBreak": True}}}
self.assertEqual(s.key_settings("kh", mf)["alertLimit"], 10)
out = s.update_key_settings("kh", mf, {"alertLimit": 25, "currency": "eur",
"pushAtPct": 150, "nope": 1})
self.assertEqual(out, {"alertLimit": 25.0, "currency": "EUR", "pushAtPct": 100,
"pushOnBreak": True})
with self.assertRaises(ValueError):
s.update_key_settings("kh", mf, {"currency": "GBP"})
# survives a restart
self.assertEqual(PluginStore(pathlib.Path(td)).key_settings("kh", mf)["currency"], "EUR")
class TestAlerts(unittest.TestCase):
def test_a_break_pushes_once_and_the_recovery_once(self):
with tempfile.TemporaryDirectory() as td, _Env(td) as env:
who = {"who": "owner", "via": "lab"}
for _ in range(2):
metering.observe_key_health(env.deps, "kh", env.mf, "no-credit", "credits are depleted",
who_row=who, http_status=402)
self.assertEqual([p["type"] for p in env.pushes], ["error"])
self.assertIn("stopped working", env.pushes[0]["title"])
# a transient error keeps the state, pushes nothing
metering.observe_key_health(env.deps, "kh", env.mf, "error", "HTTP 503", who_row=who)
self.assertEqual(env.store.get_key_health("kh")["status"], "no-credit")
for _ in range(2):
metering.observe_key_health(env.deps, "kh", env.mf, "ok", who_row=who)
self.assertEqual([p["type"] for p in env.pushes], ["error", "success"])
self.assertEqual(env.pushes[1]["title"], "✅ Key Health key works again")
def test_break_pushes_can_be_switched_off(self):
with tempfile.TemporaryDirectory() as td, _Env(td) as env:
env.store.update_key_settings("kh", env.mf, {"pushOnBreak": False})
metering.observe_key_health(env.deps, "kh", env.mf, "invalid", "bad key")
metering.observe_key_health(env.deps, "kh", env.mf, "ok")
self.assertEqual(env.pushes, [])
def test_spend_pushes_at_the_threshold_and_at_100_once_each(self):
with tempfile.TemporaryDirectory() as td, _Env(td) as env, \
patch.object(metering, "month_spent", side_effect=[8.5, 8.6, 10.2, 11.0]):
self.assertEqual(metering.check_spend(env.deps, "kh", env.mf), [80])
self.assertEqual(metering.check_spend(env.deps, "kh", env.mf), [])
self.assertEqual(metering.check_spend(env.deps, "kh", env.mf), [100])
self.assertEqual(metering.check_spend(env.deps, "kh", env.mf), [])
self.assertEqual([p["title"] for p in env.pushes],
["💸 Key Health: 80 % of the monthly limit",
"💸 Key Health: monthly limit reached"])
self.assertTrue(all(p["type"] == "warn" for p in env.pushes))
def test_the_legacy_tool_counts_in_the_month(self):
mf = {"managed": {"keyHealth": {"legacyLedgerTool": "khlegacy"}}}
self.assertEqual(metering.ledger_tools("kh", mf), ["plugin:kh", "khlegacy"])
with patch.object(LEDGER, "tool_spent", side_effect=lambda t, m: {"plugin:kh": 1.0,
"khlegacy": 2.5}[t]):
self.assertEqual(metering.month_spent("kh", mf), 3.5)
class TestSpendView(unittest.TestCase):
def test_build_merges_legacy_rows_failures_and_links(self):
now = time.time()
rows = {"plugin:kh": [{"t": now - 60, "tool": "plugin:kh", "who": "owner", "via": "lab",
"usd": 0.04, "units": {"images": 1}, "model": "m-1",
"session": "0190e0a1-0000-7000-8000-000000000001"}],
"khlegacy": [{"t": now - 120, "tool": "khlegacy", "who": "owner", "via": "test",
"usd": 0.0001, "units": {"tests": 1}, "model": "lite"}]}
with tempfile.TemporaryDirectory() as td, _Env(td) as env, \
patch.object(LEDGER, "rows", side_effect=lambda months, tool=None: rows.get(tool, [])):
env.store.set_secret(None, "kh", "api_key", KEY, scope="hub")
metering.observe_key_health(env.deps, "kh", env.mf, "denied", "nope",
who_row={"who": "owner", "via": "lab"}, http_status=403)
v = keyspend.build(env.deps, "kh", env.rec, now=now)
self.assertEqual(v["hint"], "…wxyz")
self.assertEqual(v["keyHealth"]["status"], "denied")
self.assertEqual(v["keyHealth"]["lastError"]["status"], 403)
self.assertEqual(v["month"]["month"], month_of(now))
self.assertAlmostEqual(v["month"]["usd"], 0.0401, places=4)
self.assertEqual(v["month"]["units"], {"images": 1, "tests": 1})
self.assertEqual(v["month"]["limitUsd"], 10.0)
self.assertEqual({c["label"] for c in v["byCaller"]}, {"You · lab", "Key test"})
self.assertIn("Key test", {m["label"] for m in v["byModel"]})
self.assertEqual(len(v["days"]), 30)
self.assertEqual(v["days"][-1]["failures"], 1)
self.assertEqual([c["ok"] for c in v["recent"]], [False, True, True])
self.assertEqual(v["recent"][1]["session"], "0190e0a1-0000-7000-8000-000000000001")
# {{config.billing}} has no value: that link is left out
self.assertEqual(v["links"], [
{"label": "Console", "url": "https://console.example.test/creds?project=proj-1"},
{"label": "Studio", "url": "https://studio.example.test/apikey"}])
def _ok(*_a, **kw):
return {"ok": True, "status": "ok", "message": "accepted",
"_meter": {"usd": 0.00001, "units": {"tests": 1}, "model": "lite",
"keyHealth": {"status": "ok", "message": ""}}}
def _fails(kind: str, status: int):
def run(*_a, **kw):
e = ActionError(status, f"{kind}: provider says no")
e.kind = kind
raise e
return run
class TestRoutes(unittest.TestCase):
def setUp(self):
self.tc = TestClient(main.app, headers=OWNER_H)
def test_spend_and_key_settings_are_the_owners(self):
with tempfile.TemporaryDirectory() as td, _Env(td):
r = self.tc.get("/api/plugins/kh/spend")
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(r.json()["settings"]["alertLimit"], 10.0)
r = self.tc.put("/api/plugins/kh/key-settings", json={"alertLimit": 30, "currency": "EUR"})
self.assertEqual((r.status_code, r.json()["settings"]["currency"]), (200, "EUR"))
self.assertEqual(self.tc.put("/api/plugins/kh/key-settings",
json={"currency": "GBP"}).status_code, 400)
self.assertEqual(self.tc.get("/api/plugins/nope/spend").status_code, 404)
def test_test_records_the_health_and_bills_the_call(self):
with tempfile.TemporaryDirectory() as td, _Env(td) as env:
env.store.set_secret(None, "kh", "api_key", KEY, scope="hub")
recorded = []
with patch("plugins.routes.run_script", side_effect=_fails("no-credit", 402)):
r = self.tc.post("/api/plugins/kh/test")
self.assertEqual(r.status_code, 402)
self.assertEqual(env.store.get_key_health("kh")["status"], "no-credit")
self.assertEqual([p["type"] for p in env.pushes], ["error"])
with patch("plugins.routes.run_script", side_effect=_ok), \
patch.object(LEDGER, "record", side_effect=recorded.append):
r = self.tc.post("/api/plugins/kh/test")
self.assertEqual(r.status_code, 200, r.text)
self.assertNotIn("_meter", r.json())
self.assertEqual(env.store.get_key_health("kh")["status"], "ok")
self.assertEqual([p["type"] for p in env.pushes], ["error", "success"])
self.assertEqual((recorded[-1]["tool"], recorded[-1]["via"]), ("plugin:kh", "test"))
def test_a_new_key_is_checked_before_it_is_saved(self):
with tempfile.TemporaryDirectory() as td, _Env(td) as env:
env.store.set_secret(None, "kh", "api_key", KEY, scope="hub")
seen = []
def refuse(*a, **kw):
seen.append(kw.get("candidate_secret"))
return _fails("invalid", 403)()
with patch("plugins.routes.run_script", side_effect=refuse):
r = self.tc.put("/api/plugins/kh/secrets/api_key", json={"value": NEW})
self.assertEqual(r.status_code, 400)
self.assertEqual(seen, [NEW])
self.assertEqual(env.store.get_secret(None, "kh", "api_key", scope="hub"), KEY)
# the same key again: nothing to do
self.assertEqual(self.tc.put("/api/plugins/kh/secrets/api_key",
json={"value": KEY}).status_code, 409)
# out of credit: the key is right, the billing isn't — kept
with patch("plugins.routes.run_script", side_effect=_fails("no-credit", 402)):
r = self.tc.put("/api/plugins/kh/secrets/api_key", json={"value": NEW})
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual((r.json()["check"]["kind"], r.json()["hint"]), ("no-credit", "…abcd"))
self.assertEqual(env.store.get_secret(None, "kh", "api_key", scope="hub"), NEW)
self.assertEqual(env.store.get_key_health("kh")["status"], "no-credit")
# the provider unreachable: not saved
with patch("plugins.routes.run_script", side_effect=_fails("error", 502)):
r = self.tc.put("/api/plugins/kh/secrets/api_key", json={"value": KEY})
self.assertEqual(r.status_code, 502)
self.assertEqual(env.store.get_secret(None, "kh", "api_key", scope="hub"), NEW)
class TestCandidateKey(unittest.TestCase):
def test_the_check_run_calls_the_provider_with_the_candidate(self):
seen: list[httpx.Request] = []
client = httpx.AsyncClient(transport=httpx.MockTransport(
lambda req: seen.append(req) or httpx.Response(200, json={"ok": True})))
tc = TestClient(main.app)
with tempfile.TemporaryDirectory() as td, _Env(td) as env, \
patch("plugins.proxyroutes._http", lambda: client), \
patch("plugins.proxy.check_public_url", return_value=(True, "")):
env.store.set_secret(None, "kh", "api_key", KEY, scope="hub")
tok = access.mint_handler(OWNER_UID, "kh", ttl=600)
url = "/proxy/tools/plugins/kh/proxy/models/lite:generateContent"
from plugins.proxy import drop_candidate, register_candidate
register_candidate(tok, NEW)
try:
r = tc.post(url, headers={"Authorization": f"Bearer {tok}"}, json={"contents": []})
finally:
drop_candidate(tok)
self.assertEqual(r.status_code, 200, r.text)
tc.post(url, headers={"Authorization": f"Bearer {tok}"}, json={"contents": []})
self.assertEqual([q.url.params["key"] for q in seen], [NEW, KEY])
class TestGeminiClassify(unittest.TestCase):
def test_replies_map_to_the_key_states(self):
c = catalog.nb_classify
self.assertEqual(c(200, {})[0], "ok")
self.assertEqual(c(402, {})[0], "no-credit")
self.assertEqual(c(429, {"error": {"message": "Your prepayment credits are depleted"}})[0],
"no-credit")
self.assertEqual(c(400, {"error": {"message": "API key not valid. Please pass a valid API key.",
"details": [{"reason": "API_KEY_INVALID"}]}})[0], "invalid")
self.assertEqual(c(429, {"error": {"message": "spend cap exceeded"}})[0], "capped")
self.assertEqual(c(403, {"error": {"message": "Permission denied"}})[0], "denied")
self.assertEqual(c(429, {"error": {"message": "slow down"}})[0], "rate-limited")
self.assertEqual(c(500, None)[0], "error")
if __name__ == "__main__":
unittest.main()