Files

359 lines
14 KiB
Python

"""Sandboxed subprocess runner for plugin scheduled jobs (v1) and backend
actions (v3).
Plugin scripts run in a strictly stripped environment:
* NO host secrets (``ANTHROPIC_API_KEY``, ``SIDECAR_TOKEN``, ``INTERNAL_API_TOKEN``,
``GEMINI_API_KEY``, ``SEERR_API_KEY``, ``MATOMO_TOKEN``… are all absent).
* NO raw user secrets — the script calls ``AIA_TOOLS_URL/plugins/<id>/proxy/…``
with a short-lived ``AIA_TOOLS_TOKEN`` minted for that user.
* Read-only user context (``AIA_USER_CONTEXT``: ``{uid, isOwner, domains,
name, lang, sessionId, grant?}``), non-secret config (``AIA_PLUGIN_CONFIG``),
a writable per-user data dir (``AIA_PLUGIN_DATA_DIR``) and the plugin's
hub-scoped dir shared by every user's runs (``AIA_PLUGIN_SHARED_DIR``).
* ``AIA_TOOLS_TOKEN`` is a *handler token* (``aiah1``): it names the user and
this plugin, reaches only this plugin's routes, and is what handler-only
proxy rules require — the guest's own run token can't pass for it.
* A handler may answer an error with a status of its own:
``{"_error": {"status": 404, "kind": "...", "message": "..."}}`` on stdout.
"""
from __future__ import annotations
import json
import os
import pathlib
import subprocess
import sys
import threading
from typing import Any
from plugins.store import OWNER_UID, PluginStore
_SAFE_ENV_KEYS = ("PATH", "LANG", "LC_ALL", "TZ", "HOME", "TMPDIR", "PYTHONUNBUFFERED")
_ORIG_SUBPROCESS_MOD = subprocess
_ORIG_SUBPROCESS_RUN = subprocess.run
class ActionError(Exception):
def __init__(self, status: int, message: str, kind: str = "action_failed"):
super().__init__(message)
self.status = status
self.message = message
self.kind = kind
def _tools_url_local() -> str:
port = os.environ.get("PORT", "8080")
return f"http://127.0.0.1:{port}/proxy/tools"
def _user_domains(deps, uid: str) -> str:
if uid == OWNER_UID:
return ""
try:
from users import domains as user_domains
u = deps.users.get(uid) or {"id": uid}
bucket, domain = user_domains.address_of(u, user_domains.default_domain(deps))
return user_domains.base_of(bucket, domain)
except Exception:
return ""
def _user_email(deps, uid: str) -> str:
"""A guest's account email (``""`` for the owner, or when unknown)."""
if uid == OWNER_UID:
return ""
try:
return str((deps.users.get(uid) or {}).get("email") or "")
except Exception:
return ""
def _active_plugin_ids(store: PluginStore, uid: str) -> list[str]:
"""Every enabled, approved plugin id active for ``uid`` (own + managed)."""
out: set[str] = set()
try:
out.update(store.active_ids(uid))
if uid != OWNER_UID:
for rec in store.managed_plugins():
pid = rec["id"]
if store.effective_grant(uid, pid, rec["manifest"]).get("enabled"):
out.add(pid)
except Exception:
pass
return sorted(out)
def _user_name_lang(deps, uid: str) -> tuple[str, str]:
if uid == OWNER_UID:
from users.caller import OWNER
return OWNER.name, "en"
try:
from users.caller import guest_from_record
u = deps.users.get(uid) or {"id": uid}
c = guest_from_record({"id": uid, **u})
return c.name, c.lang or "en"
except Exception:
return uid, "en"
def requester_context(deps, uid: str, grant: dict[str, Any] | None = None,
session_id: str | None = None) -> dict[str, Any]:
"""Who started a guest's ``runAs: "owner"`` action — handed to the
handler as ``AIA_USER_CONTEXT.requester`` (``uid``, ``isOwner``, ``name``,
``lang``, ``domains``, ``email``, ``sessionId``, ``grant``) while it runs with the
owner's hub context. A plugin checks ``requester`` before ``uid``."""
r_name, r_lang = _user_name_lang(deps, uid)
ctx: dict[str, Any] = {
"uid": uid,
"isOwner": uid == OWNER_UID,
"name": r_name,
"lang": r_lang,
"domains": _user_domains(deps, uid),
"email": _user_email(deps, uid),
"sessionId": session_id,
}
if grant is not None:
ctx["grant"] = dict(grant.get("config") or {})
return ctx
def _structured_error(stdout: str) -> ActionError | None:
"""A handler's own ``{"_error": {status, kind, message}}``."""
try:
parsed = json.loads(stdout) if stdout else None
except ValueError:
return None
err = parsed.get("_error") if isinstance(parsed, dict) else None
if not isinstance(err, dict):
return None
try:
status = int(err.get("status") or 422)
except (TypeError, ValueError):
status = 422
status = min(599, max(400, status))
e = ActionError(status, str(err.get("message") or f"plugin error {status}")[:1000])
e.kind = str(err.get("kind") or "action_failed")[:40]
return e
def _script_cmd(path: pathlib.Path) -> list[str]:
if path.suffix == ".py":
return [sys.executable, str(path)]
if os.access(path, os.X_OK):
return [str(path)]
if path.suffix == ".sh":
return ["/bin/sh", str(path)]
return [sys.executable, str(path)]
# A request's plugin scripts hold one of the app's 40 worker threads each
# while they run, and many call back into this hub (the bridges), which takes
# another. 2026-11-27: an SSE storm made every tab ask for /api/inbox/waiting
# twice a second; the scripts behind it filled the pool and every request in
# the app waited 30 s. So a request may run at most REQUEST_SCRIPT_SLOTS
# top-level scripts at once; past that it waits REQUEST_SCRIPT_WAIT_SECS, then
# gets a 503. Background threads (cron, schedules) and a script's nested
# calls (call_depth > 0, which would otherwise deadlock on their parent's
# slot) are not counted.
REQUEST_SCRIPT_SLOTS = 12
REQUEST_SCRIPT_WAIT_SECS = 5.0
_request_slots = threading.BoundedSemaphore(REQUEST_SCRIPT_SLOTS)
def _in_request_thread() -> bool:
# Starlette runs sync routes in anyio's worker threads.
return threading.current_thread().name.startswith("AnyIO worker thread")
def run_script(*args, **kwargs) -> dict[str, Any]:
"""See :func:`_run_script`; a request's top-level runs share
:data:`REQUEST_SCRIPT_SLOTS` slots."""
if kwargs.get("call_depth") or not _in_request_thread():
return _run_script(*args, **kwargs)
if not _request_slots.acquire(timeout=REQUEST_SCRIPT_WAIT_SECS):
raise ActionError(503, "the hub is busy: too many plugin scripts running, try again")
try:
return _run_script(*args, **kwargs)
finally:
_request_slots.release()
def _hub_langs() -> tuple[str, ...]:
try:
from core.i18n import langs
return langs()
except Exception: # noqa: BLE001 — a handler still runs, in English
return ("en",)
def _run_script(
deps,
store: PluginStore,
uid: str,
rec: dict[str, Any],
rel_script: str,
*,
payload: dict[str, Any] | None = None,
timeout_sec: int = 30,
grant: dict[str, Any] | None = None,
using_own_secret: bool = False,
session_id: str | None = None,
call_depth: int = 0,
caller_plugin: str | None = None,
requester: dict[str, Any] | None = None,
candidate_secret: str | None = None,
context: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Run ``rel_script`` inside ``rec['dir']`` with a stripped environment and
JSON stdin/stdout contract. ``candidate_secret``: this run's proxy calls
use it instead of the stored secret (a key checked before it is saved).
``context``: more ``AIA_USER_CONTEXT`` keys the host vouches for
(plugins/launch.py); never ``uid`` / ``isOwner``."""
mf = rec.get("manifest") or {}
pid = mf["id"]
plugin_root = pathlib.Path(rec["dir"]).resolve()
script_path = (plugin_root / rel_script).resolve()
try:
script_path.relative_to(plugin_root)
except ValueError:
raise ActionError(400, "script escapes plugin directory") from None
if not script_path.is_file():
raise ActionError(404, f"plugin script not found: {rel_script}")
from toolproxy import access
token = access.mint_handler(uid, pid, ttl=max(timeout_sec + 60, 300))
data_dir = store.user_data_dir(uid, pid)
shared_dir = store.shared_data_dir(pid)
name, lang = _user_name_lang(deps, uid)
user_ctx: dict[str, Any] = {
"uid": uid,
"isOwner": uid == OWNER_UID,
"domains": _user_domains(deps, uid),
"name": name,
"lang": lang,
"email": _user_email(deps, uid),
"sessionId": session_id,
}
if caller_plugin:
user_ctx["callerPlugin"] = caller_plugin
if requester is not None:
user_ctx["requester"] = requester
for k, v in (context or {}).items():
if k not in user_ctx and v is not None:
user_ctx[k] = v
if grant is not None:
user_ctx["grant"] = {
**dict(grant.get("config") or {}),
"monthlyBudgetUsd": grant.get("monthlyBudgetUsd"),
"usingOwnSecret": bool(using_own_secret),
}
env = {k: os.environ[k] for k in _SAFE_ENV_KEYS if k in os.environ}
env.update({
"AIA_TOOLS_URL": _tools_url_local(),
"AIA_TOOLS_TOKEN": token,
"AIA_PLUGIN_ID": pid,
"AIA_PLUGIN_DIR": str(plugin_root),
"AIA_PLUGIN_DATA_DIR": str(data_dir),
"AIA_PLUGIN_SHARED_DIR": str(shared_dir),
"AIA_PLUGIN_CONFIG": json.dumps(rec.get("config") or {}),
"AIA_USER_CONTEXT": json.dumps(user_ctx),
"AIA_PLUGIN_CALL_DEPTH": str(int(call_depth)),
# the languages the hub speaks (English + every enabled translation):
# a handler wording a notice for several readers makes one variant each
"AIA_LANGS": json.dumps(list(_hub_langs())),
"AIA_ACTIVE_PLUGINS": json.dumps(_active_plugin_ids(
store, (requester or {}).get("uid") or uid)),
})
caps = set(mf.get("capabilities") or [])
# ``services.read``: the host's services dir (the Services catalogue
# plugin reads its compose / Traefik files) — the owner's runs only.
if uid == OWNER_UID and "services.read" in caps:
from servicesdir import SERVICES_DIR
if SERVICES_DIR.is_dir():
env["AIA_SERVICES_DIR"] = str(SERVICES_DIR)
# ``plans.read`` / ``plans.write``: the host's data/plans dir (owner only).
if uid == OWNER_UID and ("plans.read" in caps or "plans.write" in caps):
plans_dir = pathlib.Path(os.environ.get("PLANS_DIR", "/workspace/data/plans")).resolve()
env["AIA_PLANS_DIR"] = str(plans_dir)
# Batch 1 owner-only host dirs — same rule as services/plans: the owner's
# runs only. A guest's own run never sees them; a guest's call to a
# managed ``runAs: "owner"`` action runs as the owner and does, so such a
# plugin must check ``AIA_USER_CONTEXT.requester`` before touching them.
if uid == OWNER_UID and "templates.read" in caps:
env["AIA_TEMPLATES_DIR"] = str(pathlib.Path(
os.environ.get("TEMPLATES_DIR", "/workspace/projects/templates")).resolve())
if uid == OWNER_UID and "memories.read" in caps:
env["AIA_MEMORIES_DIR"] = str(pathlib.Path(
os.environ.get("MEMORIES_DIR", "/memories")).resolve())
if uid == OWNER_UID and "projects.env" in caps:
from projects.catalog import PROJECTS_DIR
env["AIA_PROJECTS_DIR"] = str(PROJECTS_DIR)
# ``hub.api``: the `ai-agent` CLI as a library — what drives that bridge
# (plugins/hubapi.py). On no sys.path by itself: the handler appends it.
if uid == OWNER_UID and "hub.api" in caps:
from plugins.hubapi import CLI_DIR
if CLI_DIR is not None:
env["AIA_CLI_DIR"] = str(CLI_DIR)
# A plugin answering HTTP on the hub's address knows that address — the
# configured one, never a request's Host (plugins/endpoints.py).
if mf.get("endpoints"):
from plugins.endpoints import hub_urls
env["AIA_HUB_URLS"] = json.dumps(hub_urls())
stdin_bytes = json.dumps(payload if payload is not None else {}).encode("utf-8")
if candidate_secret:
from plugins.proxy import register_candidate
register_candidate(token, candidate_secret)
try:
p = None
if (
script_path.suffix == ".py"
and subprocess is _ORIG_SUBPROCESS_MOD
and subprocess.run is _ORIG_SUBPROCESS_RUN
):
from plugins import zygote
p = zygote.run_python(
script_path,
stdin_bytes=stdin_bytes,
env=env,
cwd=str(plugin_root),
timeout_sec=timeout_sec,
)
if p is None:
p = subprocess.run(
_script_cmd(script_path),
input=stdin_bytes,
capture_output=True,
env=env,
cwd=str(plugin_root),
timeout=timeout_sec,
)
except subprocess.TimeoutExpired:
raise ActionError(504, f"plugin script timed out after {timeout_sec}s") from None
except OSError as e:
raise ActionError(500, f"failed to run plugin script: {e}") from None
finally:
if candidate_secret:
from plugins.proxy import drop_candidate
drop_candidate(token)
stdout = (p.stdout or b"").decode("utf-8", "replace").strip()
stderr = (p.stderr or b"").decode("utf-8", "replace").strip()
se = _structured_error(stdout)
if se is not None:
raise se
if p.returncode != 0:
msg = stderr.splitlines()[-1] if stderr else (stdout[:300] or f"exit {p.returncode}")
raise ActionError(422 if p.returncode in (1, 2) else 500, msg)
if not stdout:
return {"ok": True}
try:
parsed = json.loads(stdout)
return parsed if isinstance(parsed, dict) else {"ok": True, "result": parsed}
except ValueError:
return {"ok": True, "output": stdout[:16384]}