The core speaks English only; every other language is a kind: "translation" plugin
(translation-<lang>; the French one is translation-fr in ai-agent-plugins, seeded once at start).
- plugins: kind translation (typed_manifest.parse_translation: lang, name, englishName, flag,
locale, promptLine, ui/backend JSON dictionaries — strict, operator-only, in the fingerprint);
a top-level "languages" field on any plugin (default ["en"]) shown on its page; seeding takes
translation-*; plugins/translations.py reads the enabled ones (first by id wins a code).
- core/i18n: tr / langs / localized / clean_pref / effective_lang read the installed
translations; a pick whose translation is gone reads English and is kept; browserLang records
any base code. core/i18n_fr.py and FRENCH_LINE are gone (language_line = the plugin's promptLine).
- The owner picks a language too (users.json ownerLang, PUT /api/me {lang}; English by default).
- Public GET /api/i18n/languages and /api/i18n/{lang} (ETag/304), guest host and sign-in included.
- Coverage: backend/core/i18n_keys/{ui,backend}.json (kept by the two i18n tests,
UPDATE_I18N_KEYS=1); a translation's page shows translated / missing / stale / placeholder
mismatches.
- Frontend: frontend/src/i18n/fr removed; the dictionary comes from the hub, cached in
localStorage and revalidated in the background (first boot in a language waits <= 4 s, any
failure is English); Lang is a string; number/currency style from the translation's locale;
LanguageSelect lists English + installed translations (hidden when none); Settings → Plugins
has a Translations kind (tab, catalog filter, group) and a Translation section with the
missing-strings count; mock is English only.
- Tests: test_i18n.py rewritten on a made-up translation; i18n_testkit.speaking() for the
tests that need a second language. authz golden, openapi.json + src/generated regenerated;
docs/plugins.md (Translations), CLAUDE.md, i18n README, docs/settings.md.
Changelog
- Added: languages are plugins — Settings → Plugins → Translations; the owner can pick a language.
- Changed: French moved to the translation-fr plugin (seeded at start: nothing changes for guests).
- Removed: the core's built-in French dictionaries.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
320 lines
15 KiB
Python
320 lines
15 KiB
Python
"""The managed-plugin gaps closed on 2026-11-25: handler tokens, handler-only
|
|
proxy rules, forced params, ownership, noAuth/query rules, units/creates,
|
|
stream byte limits, `_private/` data, structured handler errors, the shared
|
|
dir + user context, hub/notify targeting, internal-only webhooks."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import json
|
|
import pathlib
|
|
import tempfile
|
|
import unittest
|
|
from unittest.mock import patch
|
|
|
|
import httpx
|
|
from fastapi.testclient import TestClient
|
|
|
|
import main
|
|
from plugins import metering, proxy as plugin_proxy
|
|
from plugins.manifest import ManifestError, capability_fingerprint, validate_manifest
|
|
from plugins.runner import ActionError, run_script
|
|
from plugins.store import OWNER_UID, PluginStore
|
|
from toolproxy import access
|
|
from toolproxy.ledger import LEDGER
|
|
|
|
|
|
def _write(root: pathlib.Path, manifest: dict, files: dict[str, str] | None = None) -> 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 or {}).items():
|
|
p = root / rel
|
|
p.parent.mkdir(parents=True, exist_ok=True)
|
|
p.write_text(content, encoding="utf-8")
|
|
return root
|
|
|
|
|
|
MANIFEST = {
|
|
"schema": 1, "id": "gx", "name": "Gaps",
|
|
"secrets": [{"key": "token", "label": "Token"}],
|
|
"proxy": {
|
|
"baseUrl": "http://up.internal:9",
|
|
"internal": True,
|
|
"handlerOnly": True,
|
|
"auth": {"in": "query", "name": "token_auth", "secret": "token"},
|
|
"allow": [
|
|
{"method": "POST", "path": "^index\\.php$", "noAuth": True,
|
|
"query": {"method": "^Users\\.mint$"}},
|
|
{"method": "POST", "path": "^index\\.php$"},
|
|
{"method": "GET", "path": "^files$", "handlerOnly": False,
|
|
"forcedParams": {"library": "{{user.tag}}"}, "units": {"files": 1}},
|
|
{"method": "GET", "path": "^models/(?P<folder>[a-z0-9]+)/(?P<name>[a-z.]+)$",
|
|
"handlerOnly": False,
|
|
"owned": {"group": "folder", "file": "_private/owned.json", "key": "folders"}},
|
|
{"method": "POST", "path": "^jobs$", "handlerOnly": False, "creates": True},
|
|
],
|
|
},
|
|
"actions": {
|
|
"boom": {"script": "handlers/boom.py"},
|
|
"ctx": {"script": "handlers/ctx.py"},
|
|
},
|
|
"webhooks": [{"id": "in", "mode": "notify", "internalOnly": True}],
|
|
}
|
|
FILES = {
|
|
"handlers/boom.py": "import json,sys\nprint(json.dumps({'_error': {'status': 404, 'kind': 'nope', 'message': 'no such job'}}))\nsys.exit(1)\n",
|
|
"handlers/ctx.py": "import json,os\nprint(json.dumps({'ctx': json.loads(os.environ['AIA_USER_CONTEXT']), 'shared': os.environ['AIA_PLUGIN_SHARED_DIR'], 'tok': os.environ['AIA_TOOLS_TOKEN'][:6]}))\n",
|
|
}
|
|
|
|
|
|
class TestHandlerToken(unittest.TestCase):
|
|
def test_mint_verify_and_resolve(self):
|
|
t = access.mint_handler("cel", "gx", ttl=60)
|
|
self.assertTrue(t.startswith("aiah1.cel.gx."))
|
|
self.assertEqual(access.verify_handler(t), ("cel", "gx"))
|
|
self.assertIsNone(access.verify_handler(t[:-2] + "xx"))
|
|
self.assertIsNone(access.verify_handler(access.mint_handler("cel", "gx", ttl=-10)))
|
|
deps = main.app.state.ai
|
|
# Only where asked for, and never on the guest host.
|
|
self.assertIsNone(access.resolve(deps, t, guest_surface=False))
|
|
self.assertIsNone(access.resolve(deps, t, guest_surface=True, allow_handler=True))
|
|
who = access.resolve(deps, t, guest_surface=False, allow_handler=True)
|
|
self.assertEqual((who.uid, who.handler, who.via), ("cel", "gx", "handler"))
|
|
own = access.resolve(deps, access.mint_handler(OWNER_UID, "gx", 60), guest_surface=False,
|
|
allow_handler=True)
|
|
self.assertTrue(own.is_owner)
|
|
|
|
|
|
class TestManifestRules(unittest.TestCase):
|
|
def test_rule_fields_kept_and_fingerprinted(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
mf = validate_manifest(_write(pathlib.Path(td) / "gx", MANIFEST, FILES))
|
|
rules = mf["proxy"]["allow"]
|
|
self.assertTrue(mf["proxy"]["handlerOnly"])
|
|
self.assertTrue(rules[0]["noAuth"])
|
|
self.assertEqual(rules[0]["query"], {"method": "^Users\\.mint$"})
|
|
self.assertEqual(rules[2]["forcedParams"], {"library": "{{user.tag}}"})
|
|
self.assertEqual(rules[3]["owned"]["group"], "folder")
|
|
self.assertTrue(rules[4]["creates"])
|
|
self.assertTrue(mf["webhooks"][0]["internalOnly"])
|
|
fp = capability_fingerprint(mf)
|
|
mf["proxy"]["allow"][2]["handlerOnly"] = True
|
|
self.assertNotEqual(fp, capability_fingerprint(mf))
|
|
|
|
def test_owned_needs_a_named_group_and_timeout_cap(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
bad = json.loads(json.dumps(MANIFEST))
|
|
bad["proxy"]["allow"][3]["owned"]["group"] = "nope"
|
|
with self.assertRaises(ManifestError):
|
|
validate_manifest(_write(pathlib.Path(td) / "a", bad, FILES))
|
|
ok = json.loads(json.dumps(MANIFEST))
|
|
ok["actions"]["boom"]["timeoutSec"] = 900
|
|
self.assertEqual(validate_manifest(_write(pathlib.Path(td) / "b", ok, FILES))
|
|
["actions"]["boom"]["timeoutSec"], 900)
|
|
|
|
def test_first_matching_rule_with_query(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
pr = validate_manifest(_write(pathlib.Path(td) / "gx", MANIFEST, FILES))["proxy"]
|
|
r = plugin_proxy.match_rule(pr, "POST", "index.php", {"method": "Users.mint"})
|
|
self.assertTrue(r.get("noAuth"))
|
|
r = plugin_proxy.match_rule(pr, "POST", "index.php", {"method": "SitesManager.deleteSite"})
|
|
self.assertFalse(r.get("noAuth"))
|
|
|
|
|
|
class _Env:
|
|
"""A temp plugin store on the live app + a mock upstream."""
|
|
|
|
def __init__(self, td: str, *, uid: str = "cel"):
|
|
self.root = pathlib.Path(td)
|
|
self.deps = main.app.state.ai
|
|
self.store = PluginStore(self.root / "data")
|
|
pdir = _write(self.root / "src", MANIFEST, FILES)
|
|
self.store.install(uid, str(pdir), is_owner=True, approve=True)
|
|
self.store.set_secret(uid, "gx", "token", "ADMIN_TOKEN_123456")
|
|
self.uid = uid
|
|
self.seen: list[httpx.Request] = []
|
|
self.bodies: list[bytes] = []
|
|
|
|
def handler(req: httpx.Request) -> httpx.Response:
|
|
self.seen.append(req)
|
|
self.bodies.append(req.read())
|
|
if req.url.path == "/models/f1/big.glb":
|
|
return httpx.Response(200, content=b"x" * 5000)
|
|
return httpx.Response(200, json={"ok": True, "q": dict(req.url.params)})
|
|
|
|
self.client = httpx.AsyncClient(transport=httpx.MockTransport(handler))
|
|
|
|
def __enter__(self):
|
|
self._patches = [
|
|
patch.object(self.deps, "plugin_store", self.store),
|
|
patch("plugins.proxyroutes._http", lambda: self.client),
|
|
patch("plugins.proxy.check_public_url", return_value=(True, "")),
|
|
]
|
|
for p in self._patches:
|
|
p.start()
|
|
return self
|
|
|
|
def __exit__(self, *a):
|
|
for p in self._patches:
|
|
p.stop()
|
|
asyncio.run(self.client.aclose())
|
|
|
|
|
|
def _auth(t: str) -> dict:
|
|
return {"Authorization": f"Bearer {t}"}
|
|
|
|
|
|
class TestProxyRoutes(unittest.TestCase):
|
|
def setUp(self):
|
|
self.tc = TestClient(main.app)
|
|
self.run_tok = access.mint("cel", ttl=600)
|
|
self.h_tok = access.mint_handler("cel", "gx", ttl=600)
|
|
|
|
def test_handler_only_refuses_the_run_token(self):
|
|
with tempfile.TemporaryDirectory() as td, _Env(td) as env:
|
|
r = self.tc.post("/proxy/tools/plugins/gx/proxy/index.php", headers=_auth(self.run_tok),
|
|
data={"method": "SitesManager.deleteSite"})
|
|
self.assertEqual(r.status_code, 403)
|
|
self.assertEqual(r.json()["error"]["kind"], "handler_only")
|
|
self.assertEqual(env.seen, [])
|
|
r = self.tc.post("/proxy/tools/plugins/gx/proxy/index.php", headers=_auth(self.h_tok),
|
|
data={"method": "SitesManager.getSites"})
|
|
self.assertEqual(r.status_code, 200)
|
|
self.assertEqual(env.seen[-1].url.params.get("token_auth"), "ADMIN_TOKEN_123456")
|
|
|
|
def test_handler_token_of_another_plugin_is_refused(self):
|
|
with tempfile.TemporaryDirectory() as td, _Env(td):
|
|
other = access.mint_handler("cel", "nanobanana", ttl=600)
|
|
r = self.tc.post("/proxy/tools/plugins/gx/proxy/index.php", headers=_auth(other))
|
|
self.assertEqual(r.status_code, 403)
|
|
|
|
def test_no_auth_rule_skips_the_secret(self):
|
|
with tempfile.TemporaryDirectory() as td, _Env(td) as env:
|
|
r = self.tc.post("/proxy/tools/plugins/gx/proxy/index.php", headers=_auth(self.h_tok),
|
|
data={"method": "Users.mint"})
|
|
self.assertEqual(r.status_code, 200)
|
|
self.assertNotIn("token_auth", env.seen[-1].url.params)
|
|
|
|
def test_forced_params_override_the_caller(self):
|
|
with tempfile.TemporaryDirectory() as td, _Env(td) as env:
|
|
r = self.tc.get("/proxy/tools/plugins/gx/proxy/files?library=owner&x=1",
|
|
headers=_auth(self.run_tok))
|
|
self.assertEqual(r.status_code, 200)
|
|
self.assertEqual(env.seen[-1].url.params.get_list("library"), ["guest-cel"])
|
|
self.assertEqual(env.seen[-1].url.params.get("x"), "1")
|
|
# The plugin's own handler is trusted with its params.
|
|
self.tc.get("/proxy/tools/plugins/gx/proxy/files?library=guest-cel",
|
|
headers=_auth(self.h_tok))
|
|
self.assertEqual(env.seen[-1].url.params.get_list("library"), ["guest-cel"])
|
|
|
|
def test_owned_rule_and_private_data(self):
|
|
with tempfile.TemporaryDirectory() as td, _Env(td) as env:
|
|
url = "/proxy/tools/plugins/gx/proxy/models/f1/big.glb"
|
|
self.assertEqual(self.tc.get(url, headers=_auth(self.run_tok)).status_code, 404)
|
|
# The guest can't write their own ownership index…
|
|
r = self.tc.put("/proxy/tools/plugins/gx/data/_private/owned.json",
|
|
headers=_auth(self.run_tok), content=b'{"folders": {"f1": {}}}')
|
|
self.assertEqual(r.status_code, 403)
|
|
r = self.tc.put("/proxy/tools/plugins/gx/data/notes.txt",
|
|
headers=_auth(self.run_tok), content=b"hi")
|
|
self.assertEqual(r.status_code, 200)
|
|
# …the plugin's handler can.
|
|
r = self.tc.put("/proxy/tools/plugins/gx/data/_private/owned.json",
|
|
headers=_auth(self.h_tok), content=b'{"folders": {"f1": {}}}')
|
|
self.assertEqual(r.status_code, 200)
|
|
self.assertEqual(self.tc.get(url, headers=_auth(self.run_tok)).status_code, 200)
|
|
self.assertEqual(
|
|
self.tc.get("/proxy/tools/plugins/gx/proxy/models/f2/big.glb",
|
|
headers=_auth(self.run_tok)).status_code, 404)
|
|
self.assertEqual(len(env.seen), 1)
|
|
|
|
def test_handler_calls_skip_ledger_and_in_flight(self):
|
|
with tempfile.TemporaryDirectory() as td, _Env(td):
|
|
rows = []
|
|
with patch.object(LEDGER, "record", side_effect=rows.append), \
|
|
patch.object(metering, "enter") as enter:
|
|
self.tc.get("/proxy/tools/plugins/gx/proxy/files", headers=_auth(self.h_tok))
|
|
self.assertEqual(rows, [])
|
|
enter.assert_not_called()
|
|
self.tc.get("/proxy/tools/plugins/gx/proxy/files", headers=_auth(self.run_tok))
|
|
self.assertEqual(rows[-1]["units"], {"files": 1})
|
|
|
|
|
|
class TestStreams(unittest.TestCase):
|
|
def test_limited_upload_and_download(self):
|
|
async def gen(n):
|
|
for _ in range(n):
|
|
yield b"x" * 100
|
|
|
|
async def collect(it):
|
|
return b"".join([c async for c in it])
|
|
|
|
self.assertEqual(len(asyncio.run(collect(plugin_proxy.limited(gen(5), 250)))), 200)
|
|
with self.assertRaises(plugin_proxy.UploadTooLarge):
|
|
asyncio.run(collect(plugin_proxy.limited(gen(5), 250, upload=True)))
|
|
self.assertEqual(len(asyncio.run(collect(plugin_proxy.limited(gen(2), 250, upload=True)))), 200)
|
|
|
|
|
|
class TestRunner(unittest.TestCase):
|
|
def test_structured_error_context_and_shared_dir(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
store = PluginStore(pathlib.Path(td) / "data")
|
|
store.install("cel", str(_write(pathlib.Path(td) / "src", MANIFEST, FILES)),
|
|
is_owner=True, approve=True)
|
|
rec = store.get_raw("cel", "gx")
|
|
deps = main.app.state.ai
|
|
with self.assertRaises(ActionError) as ctx:
|
|
run_script(deps, store, "cel", rec, "handlers/boom.py")
|
|
self.assertEqual((ctx.exception.status, ctx.exception.kind), (404, "nope"))
|
|
out = run_script(deps, store, "cel", rec, "handlers/ctx.py", session_id="abc")
|
|
self.assertEqual(out["tok"], "aiah1.")
|
|
self.assertEqual(out["ctx"]["sessionId"], "abc")
|
|
self.assertIn(out["ctx"]["lang"], ("en", "fr"))
|
|
self.assertIn("name", out["ctx"])
|
|
self.assertTrue(out["shared"].endswith("/_hub/gx"))
|
|
self.assertTrue(pathlib.Path(out["shared"]).is_dir())
|
|
|
|
|
|
class TestNotifyAndWebhooks(unittest.TestCase):
|
|
def setUp(self):
|
|
self.tc = TestClient(main.app)
|
|
|
|
def test_notify_reaches_the_named_user_and_checks_session(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
m = json.loads(json.dumps(MANIFEST))
|
|
m["capabilities"] = ["notify.send"]
|
|
store = PluginStore(pathlib.Path(td) / "data")
|
|
store.install("cel", str(_write(pathlib.Path(td) / "src", m, FILES)),
|
|
is_owner=True, approve=True)
|
|
deps = main.app.state.ai
|
|
got = []
|
|
from i18n_testkit import speaking
|
|
with patch.object(deps, "plugin_store", store), speaking("fr"), \
|
|
patch("notifications.routes._create_notify", side_effect=lambda d, x: got.append(x)):
|
|
tok = access.mint("cel", ttl=600)
|
|
r = self.tc.post("/proxy/tools/plugins/gx/hub/notify", headers=_auth(tok),
|
|
json={"title": "Ready", "to": "cel",
|
|
"i18n": {"fr": {"title": "Prêt", "message": "ok"}}})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(got[-1]["recipients"], ["cel"])
|
|
self.assertEqual(got[-1]["i18n"]["fr"]["title"], "Prêt")
|
|
r = self.tc.post("/proxy/tools/plugins/gx/hub/notify", headers=_auth(tok),
|
|
json={"title": "x", "session": "0f0f0f0f-0000-4000-8000-000000000000"})
|
|
self.assertEqual(r.status_code, 403)
|
|
|
|
def test_internal_only_webhook_hidden_on_guest_host(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
store = PluginStore(pathlib.Path(td) / "data")
|
|
store.install(OWNER_UID, str(_write(pathlib.Path(td) / "src", MANIFEST, FILES)),
|
|
is_owner=True, approve=True)
|
|
deps = main.app.state.ai
|
|
with patch.object(deps, "plugin_store", store), \
|
|
patch.object(store, "find_by_webhook_token",
|
|
return_value=(OWNER_UID, store.get_raw(OWNER_UID, "gx"))), \
|
|
patch("plugins.proxyroutes.on_public_surface", return_value=True):
|
|
r = self.tc.post("/proxy/tools/plugins/gx/webhook/in?token=t", json={})
|
|
self.assertEqual(r.status_code, 404)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|