Files
ai-agent/backend/toolproxy/access.py
gabrielvidalandClaude Opus 5.5 112f386682 feat(plugins): close the managed-plugin gaps — handler tokens, handler-only rules, forced params, ownership, stream limits
- Handler subprocesses get an aiah1 token (uid + plugin), honoured only on
  that plugin's routes and never on the guest host; per-rule / proxy-wide
  handlerOnly refuses a guest's run token (the raw-proxy bypass).
- Rules: first-match with optional query, forcedParams ({{user.tag}}),
  noAuth, units, creates (jobsPerDay), owned (named group in a _private/
  index only handlers write).
- Streams enforce proxy.maxBytes both ways.
- Handler calls to their own proxy skip limits, in-flight and the $0 row.
- Runner: AIA_PLUGIN_SHARED_DIR, user context name/lang/sessionId,
  structured _error status, action timeout up to 900 s.
- hub/notify: session + i18n, and 'to' really reaches that user (it went
  to the owner); webhook notify mode the same; internalOnly webhooks.
- UI bridge: window.aiAgentPlugin.navigate(path).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 14:41:35 +01:00

313 lines
12 KiB
Python

"""
Who is calling the tool proxy, and whether they may make this call now.
Two kinds of bearer, both answered on any host (the proxy is outside ``/api``:
no Authelia, no trusted-caller gate — the token is the whole auth):
* a **run token** (``aiat1.<uid>.<exp>.<sig>``) — minted for a guest's run on
the lab (``users/runs.scope_for`` → the run's ``AIA_TOOLS_TOKEN``), an HMAC
with a key only the hub holds; it names the guest, and expires;
* a **worker's proxy token** — the one its Claude proxy already uses
(``claudeproxy.service``), shipped to the machine with the hub editions of
the skills (``workers/labsync``): a guest's computer is that guest, an owner's
worker is the owner.
The owner is never refused. A guest is refused when disabled, when guests are
locked, when the group isn't switched on for them, a Pro model without the
Pro switch, a paid call past their tools budget, too many calls in flight or
in the last minute.
"""
from __future__ import annotations
import base64
import dataclasses
import hashlib
import hmac
import os
import pathlib
import re
import secrets
import threading
import time
from . import catalog
from .ledger import LEDGER
KEY_PATH = pathlib.Path(os.environ.get("TOOLS_TOKEN_KEY", "/data/tools-token.key"))
TOKEN_TTL_S = int(os.environ.get("TOOLS_TOKEN_TTL_S", str(3 * 86400)))
PREFIX = "aiat1"
# A plugin handler's own token (``plugins/runner.py``): names the user AND the
# plugin, so ``/proxy/tools/plugins/<pid>/…`` can tell the plugin's code from
# the guest's run calling the same door (handler-only proxy rules).
HANDLER_PREFIX = "aiah1"
_PID_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,63}$")
_UID_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")
_key_lock = threading.Lock()
_key: bytes | None = None
# Calls in flight per guest and tool, and per guest a minute (all tools).
IN_FLIGHT = {"nanobanana": 4, "video-extract": 2, "3d-gen": 6, "3d-render": 2, "matomo": 4,
"movies": 4, "meta": 3}
PER_MINUTE = int(os.environ.get("TOOLS_PER_MINUTE", "120"))
# A job tool's creations a day per guest (EVOX2 time is free but not endless).
JOBS_PER_DAY = {"video-extract": 30, "3d-gen": 40}
def _secret() -> bytes:
global _key
if _key is not None:
return _key
with _key_lock:
if _key is None:
try:
k = KEY_PATH.read_bytes().strip()
except OSError:
k = b""
if len(k) < 32:
k = base64.urlsafe_b64encode(secrets.token_bytes(32))
try:
KEY_PATH.parent.mkdir(parents=True, exist_ok=True)
fd = os.open(KEY_PATH, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "wb") as f:
f.write(k)
except OSError:
pass
_key = k
return _key
def _sig(payload: str) -> str:
d = hmac.new(_secret(), payload.encode(), hashlib.sha256).digest()
return base64.urlsafe_b64encode(d).decode().rstrip("=")
def mint(uid: str, ttl: int = TOKEN_TTL_S, now: float | None = None) -> str:
exp = int((now if now is not None else time.time()) + ttl)
payload = f"{PREFIX}.{uid}.{exp}"
return f"{payload}.{_sig(payload)}"
def verify(token: str, now: float | None = None) -> str | None:
"""The guest a run token names, when it is ours and still good."""
parts = (token or "").split(".")
if len(parts) != 4 or parts[0] != PREFIX or not _UID_RE.match(parts[1]):
return None
try:
exp = int(parts[2])
except ValueError:
return None
if exp < (now if now is not None else time.time()):
return None
if not hmac.compare_digest(_sig(".".join(parts[:3])), parts[3]):
return None
return parts[1]
def mint_handler(uid: str, pid: str, ttl: int, now: float | None = None) -> str:
"""A token for one plugin handler run: ``aiah1.<uid>.<pid>.<exp>.<sig>``."""
exp = int((now if now is not None else time.time()) + ttl)
payload = f"{HANDLER_PREFIX}.{uid}.{pid}.{exp}"
return f"{payload}.{_sig(payload)}"
def verify_handler(token: str, now: float | None = None) -> tuple[str, str] | None:
"""``(uid, pid)`` a handler token names, when it is ours and still good."""
parts = (token or "").split(".")
if (len(parts) != 5 or parts[0] != HANDLER_PREFIX or not _UID_RE.match(parts[1])
or not _PID_RE.match(parts[2])):
return None
try:
exp = int(parts[3])
except ValueError:
return None
if exp < (now if now is not None else time.time()):
return None
if not hmac.compare_digest(_sig(".".join(parts[:4])), parts[4]):
return None
return parts[1], parts[2]
@dataclasses.dataclass
class Who:
uid: str | None # the guest; None = the owner
worker: dict | None = None
via: str = "run" # "run" | "worker" | "lab" | "handler"
handler: str | None = None # the plugin id a handler token is for
@property
def is_owner(self) -> bool:
return self.uid is None
@property
def key(self) -> str:
return self.uid or "owner"
def row(self) -> dict:
"""The ledger fields naming the caller."""
out: dict = {"who": self.key, "via": self.via}
if self.uid:
out["guest"] = self.uid
if self.worker:
out["worker"] = self.worker["id"]
return out
def resolve(deps, token: str, *, guest_surface: bool,
allow_handler: bool = False) -> Who | None:
"""The caller a bearer names (None: no one). A plugin handler's token is
only honoured where the caller asks for it (the plugin routes), and never
out on the public guest host — handlers call the hub over loopback."""
if (token or "").startswith(HANDLER_PREFIX + "."):
if not allow_handler or guest_surface:
return None
got = verify_handler(token)
if not got:
return None
uid, pid = got
return Who(None if uid == "owner" else uid, None, "handler", pid)
if (token or "").startswith(PREFIX + "."):
uid = verify(token)
if not uid:
return None
if uid == "owner":
return None if guest_surface else Who(None, None, "run")
return Who(uid, None, "run")
# The lab's own skills (``nanobanana`` in ~/homelab) hold the hub's
# internal token from the root .env: the owner, on the lab — never on the
# public guest host.
from core.auth import INTERNAL_API_TOKEN
if (INTERNAL_API_TOKEN and token and not guest_surface
and hmac.compare_digest(token, INTERNAL_API_TOKEN)):
return Who(None, None, "lab")
from claudeproxy import service
from workers import guests
w = service.worker_for_token(deps.worker_store, token)
if not w:
return None
if guest_surface and not guests.is_guest(w):
# The owner's workers reach the hub over the tailnet; out on the public
# guest host their tokens are no one's.
return None
return Who(guests.owner_of(w), w, "worker")
# ── the user's switches ──────────────────────────────────────────────────────
def config(deps, who: Who) -> dict:
"""The caller's tools config (``users/store.clean_tools``); the owner
has every group and Pro, no budget."""
from users.store import clean_tools
if who.is_owner:
return {"groups": list(catalog.GROUPS), "pro": True, "budgetUsd": None}
u = deps.users.get(who.uid) or {}
return clean_tools(u.get("tools"))
# ── in flight / rate ─────────────────────────────────────────────────────────
_flight_lock = threading.Lock()
_flight: dict[tuple[str, str], int] = {}
_minute: dict[str, list[float]] = {}
_days: dict[tuple[str, str, str], int] = {}
def enter(who: Who, tool: str) -> None:
with _flight_lock:
k = (who.key, tool)
_flight[k] = _flight.get(k, 0) + 1
def leave(who: Who, tool: str) -> None:
with _flight_lock:
k = (who.key, tool)
n = _flight.get(k, 0) - 1
if n > 0:
_flight[k] = n
else:
_flight.pop(k, None)
def _take_minute(key: str, now: float) -> bool:
with _flight_lock:
hits = [t for t in _minute.get(key, []) if now - t < 60]
if len(hits) >= PER_MINUTE:
_minute[key] = hits
return False
hits.append(now)
_minute[key] = hits
return True
def count_job(who: Who, tool: str) -> None:
day = time.strftime("%Y-%m-%d", time.gmtime())
with _flight_lock:
_days[(who.key, tool, day)] = _days.get((who.key, tool, day), 0) + 1
def refusal(deps, who: Who, tool: str, *, model: str | None = None,
paid: bool = False, creates: bool = False) -> tuple[int, str, str] | None:
"""``(status, message, kind)`` when ``who`` may not make this call now.
``paid``: it costs money (checked against the tools budget); ``creates``:
it starts a job (the day's job cap)."""
group = catalog.GROUP_OF.get(tool)
if group is None:
return 404, f"unknown tool {tool!r}", "tool"
if who.is_owner:
return None
u = deps.users.active(who.uid)
if not u:
return 403, "your guest account is disabled", "disabled"
if deps.security_state.guests_locked():
return 403, "guest access is paused for now", "locked"
if who.worker and who.worker.get("paused"):
return 403, ("this computer is paused — switch it back on in your portal "
"(Settings → My computers)"), "paused"
cfg = config(deps, who)
if group not in cfg["groups"]:
return 403, (f"{catalog.GROUP_LABELS[group]} isn't switched on for you — ask the "
"hub's owner"), "group"
if model is not None:
hit = catalog.nb_model(model)
if not hit:
return 400, (f"unknown image model {model!r} — use one of "
f"{', '.join(m for m, p in catalog.NB_MODELS.items() if cfg['pro'] or not p['pro'])}"), "model"
if hit[1]["pro"] and not cfg["pro"]:
return 403, (f"{hit[1]['label']} isn't switched on for you — use "
f"{catalog.NB_DEFAULT} or gemini-3.1-flash-image"), "pro"
if paid and cfg["budgetUsd"] is not None:
spent = LEDGER.spent(who.key)
if spent >= cfg["budgetUsd"]:
return 429, (f"your monthly tools budget is spent (${spent:.2f} of "
f"${cfg['budgetUsd']:.0f}) — it resets on the 1st"), "budget"
with _flight_lock:
busy = _flight.get((who.key, tool), 0)
day = _days.get((who.key, tool, time.strftime("%Y-%m-%d", time.gmtime())), 0)
if busy >= IN_FLIGHT.get(tool, 4):
return 429, (f"{IN_FLIGHT.get(tool, 4)} {tool} calls are already running for you — "
"wait for one to finish"), "inflight"
if creates and tool in JOBS_PER_DAY and day >= JOBS_PER_DAY[tool]:
return 429, (f"{JOBS_PER_DAY[tool]} {tool} jobs today is the daily limit — "
"it resets at midnight UTC"), "daily"
if not _take_minute(who.key, time.time()):
return 429, f"more than {PER_MINUTE} tool calls in a minute — slow down", "rate"
return None
# ── which conversation ───────────────────────────────────────────────────────
_SID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
def session_of(deps, who: Who, raw: str | None) -> str | None:
"""The conversation a call came from (its Claude Code session id,
``X-Claude-Code-Session-Id``), kept only when it is the caller's: a
guest's own conversation — never one that is someone else's."""
sid = (raw or "").strip().lower()
if not _SID_RE.match(sid):
return None
if who.is_owner:
return sid
try:
meta = deps.meta_store.peek(sid) or {}
except Exception:
return None
return sid if meta.get("owner") == who.uid else None