The hub as an MCP server (OAuth 2.1, the consent page, /mcp, Settings → AI
apps) is the `hub-mcp` live plugin now (ai-agent-plugins). Core keeps nothing
about MCP: four generic plugin contracts replace backend/mcpserver/.
Gabriel's picks: form move-the-hub-mcp-server-into-a-plugin_2od10i.
New contracts (docs/plugins.md → "HTTP endpoints, the hub's API and asks"):
- `endpoints[]` (plugins/endpoints.py): HTTP a plugin answers on the hub's own
address — under /x/<pluginId>/… or a protocol path (/mcp, /oauth/…,
/.well-known/…). The request goes to the endpoint's action with what the
host vouches for (client address, surface, and `caller`: who the browser is
signed in as, by the gate's own rules — core/auth.identify); the answer
comes back through header and type allowlists, and HTML never runs a script
(forced CSP). Body cap, per-address rate, 16 runs at once on their own
threads. An endpoint's action answers HTTP only: the action routes refuse it
and the manifest can't wire it to anything else — its payload is the host's
word on who is asking.
- `hub.api` (plugins/hubapi.py, plugins/actas.py): the hub's API for the
plugin's handlers, as the owner or — `X-AIA-As-User`, the `cli` scope — as a
guest the plugin is granted to. The CLI is its library (AIA_CLI_DIR; the
names a plugin leans on are pinned by cli/test_library_surface.py).
`hub/via` stamps meta.via = {kind: "plugin", …}: the "via Claude.ai" pill.
- `notify.ask` and `security.record` (plugins/hubsignals.py): a tappable
question to the owner and its answer; a `plugin_event` Security log line.
Removed: backend/mcpserver/, schemas/mcp.py, cli/mcp_tools.py + mcp_server.py,
the frontend's business/aiApps (Settings → AI apps, /connect/<id> — both old
addresses redirect), /api/mcp*, /api/me/ai-apps, the `mcp` SSE event, the
mcp.connect / mcp.manage permissions and the per-guest AI apps switch (the
plugin's managed grant). A retired permission still in a record reads without
it and is never refused (authz/catalog.RETIRED).
Carry-over (carryover.hub_mcp, at start and after the plugin's install):
/data/mcp.json → the plugin's store, same shape, so connected apps keep
working — minus the connections bound to a worker, which are dropped with
their tokens rather than left as plain owner connections; every guest who
held mcp.connect gets the grant; whoever was pushed about mcp_connected is
pushed about plugin events.
Workers: the `ai-agent` CLI switch gains Full — the lab's CLI as the owner
(every command but worktrees, any machine, the plugins' commands), what the
EVOX2's unbound MCP connection gave. The worker-side CLI no longer filters
commands: the hub's switch decides. "Acts as" is gone; workers/bound.py stays
as the CLI's narrowing.
Until the plugin is installed after a deploy, /mcp and /oauth/* answer 404.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
280 lines
12 KiB
Python
280 lines
12 KiB
Python
"""Recording security events, pushing the owner about the ones he picked, and
|
|
the two big switches: *Lock guests* and *Stop every run* (docs/security.md)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import threading
|
|
import time
|
|
|
|
from fastapi import Request
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
# kind → (icon, title of its push). Kinds not listed are logged, never pushed.
|
|
PUSHABLE = {
|
|
"guard_block": ("🛡️", "Guard blocked a guest run"),
|
|
"guard_owner": ("🛡️", "An agent tripped a guard rule"),
|
|
"new_device": ("👤", "Guest sign-in from a new device"),
|
|
"sandbox_burst": ("🧱", "Sandbox denials piling up"),
|
|
"edge_anonymous": ("🚪", "Anonymous request on the admin host"),
|
|
# What a plugin reported through the ``security.record`` bridge and asked
|
|
# to be pushed (plugins/hubsignals.py — hub-mcp: an AI app connected).
|
|
"plugin_event": ("🧩", "A plugin reported an event"),
|
|
"cross_site": ("🧨", "A page on another site tried to act as you"),
|
|
# Every sign-in on the internet address (remoteaccess/), new device or not.
|
|
"owner_login": ("🔑", "You signed in from the internet"),
|
|
"remote_passkey_added": ("🔑", "A passkey was added for internet access"),
|
|
"remote_passkey_invited": ("🔗", "A link to add a passkey was made"),
|
|
}
|
|
KINDS = (*PUSHABLE, "sandbox_denial", "guest_login", "link_request", "guest_run",
|
|
"ship_deploy", "guests_locked", "guests_unlocked", "runs_stopped",
|
|
"guest_worker_paired", "guest_worker_removed", "guest_proxy_refused",
|
|
# the MCP server's lines from before it was the hub-mcp plugin (old rows)
|
|
"worker_linked", "ip_locked", "mcp_connected", "mcp_revoked", "mcp_bound",
|
|
"guest_cron", "guest_tool_refused", "code_failed", "oidc_refused",
|
|
"perm_denied", "loopback_tokenless", "owner_login_refused", "remote_locked",
|
|
"remote_unlocked", "remote_signed_out", "remote_passkey_invited",
|
|
"remote_passkey_removed")
|
|
|
|
# Sandbox denials: this many within the window push once (per session per hour).
|
|
BURST_COUNT, BURST_WINDOW_S, BURST_QUIET_S = 3, 600, 3600
|
|
_bursts: dict[str, list[float]] = {}
|
|
_burst_pushed: dict[str, float] = {}
|
|
# The same anonymous edge probe is logged once per IP per quiet window.
|
|
_edge_seen: dict[str, float] = {}
|
|
_EDGE_QUIET_S = 600
|
|
# …and a refused cross-site request once per (origin, who) per quiet window.
|
|
_cross_seen: dict[tuple[str, str], float] = {}
|
|
# A permission refusal, once per (who, scope, route) per quiet window; a host
|
|
# call without the host token, once per (method, route, client, agent) an hour.
|
|
_denied_seen: dict[tuple, float] = {}
|
|
_loopback_seen: dict[tuple, float] = {}
|
|
_LOOPBACK_QUIET_S = 3600
|
|
_lock = threading.Lock()
|
|
|
|
|
|
def client_ip(request: Request) -> str:
|
|
"""The browser's address: Traefik's ``X-Real-Ip`` when Traefik is the
|
|
peer (the only one whose headers we believe), else the peer itself."""
|
|
from core.auth import via_edge
|
|
peer = request.client.host if request.client else ""
|
|
if via_edge(request):
|
|
return (request.headers.get("x-real-ip") or "").strip() or peer
|
|
return peer
|
|
|
|
|
|
def record(deps, kind: str, *, who: str | None = None, sid: str | None = None,
|
|
detail: str = "", data: dict | None = None,
|
|
request: Request | None = None, ip: str | None = None,
|
|
push: bool = True) -> dict | None:
|
|
"""Append one event (never raises) and push the owner when its kind is
|
|
one of his ``pushKinds`` (``push=False``: a line only). ``ip``: the
|
|
address, for an event recorded away from its request (a plugin's)."""
|
|
try:
|
|
ev = {"kind": kind, "who": who, "sid": sid or None, "detail": detail[:500]}
|
|
if request is not None:
|
|
ev["ip"] = client_ip(request)
|
|
ev["ua"] = (request.headers.get("user-agent") or "")[:200]
|
|
elif ip:
|
|
ev["ip"] = ip[:64]
|
|
if data:
|
|
ev["data"] = data
|
|
ev = deps.security_log.append({k: v for k, v in ev.items() if v is not None})
|
|
deps.hub.publish({"type": "security"})
|
|
if kind == "sandbox_denial" and sid:
|
|
_maybe_burst(deps, ev)
|
|
if push and kind in PUSHABLE and kind in deps.security_state.get()["pushKinds"]:
|
|
_push(deps, ev)
|
|
return ev
|
|
except Exception as exc: # the log must never break what it watches
|
|
log.warning("security event %s not recorded: %s", kind, exc)
|
|
return None
|
|
|
|
|
|
def record_plugin(deps, pid: str, name: str, event: str, detail: str, *,
|
|
who: str | None = None, ip: str | None = None,
|
|
push: bool = False) -> dict | None:
|
|
"""A plugin's own line (the ``security.record`` bridge): a
|
|
``plugin_event``, pushed only when the plugin asked for it *and* the
|
|
owner has that kind on."""
|
|
return record(deps, "plugin_event", who=who, ip=ip, push=push,
|
|
detail=f"{name}: {detail}" if detail else name,
|
|
data={"plugin": pid, "event": event})
|
|
|
|
|
|
def _maybe_burst(deps, ev: dict) -> None:
|
|
sid, now = ev["sid"], time.time()
|
|
with _lock:
|
|
hits = [t for t in _bursts.get(sid, []) if now - t < BURST_WINDOW_S] + [now]
|
|
_bursts[sid] = hits
|
|
if len(hits) < BURST_COUNT or now - _burst_pushed.get(sid, 0) < BURST_QUIET_S:
|
|
return
|
|
_burst_pushed[sid] = now
|
|
record(deps, "sandbox_burst", who=ev.get("who"), sid=sid,
|
|
detail=f"{len(hits)} sandbox denials in {BURST_WINDOW_S // 60} min — "
|
|
f"last: {ev.get('detail', '')[:200]}")
|
|
|
|
|
|
def edge_anonymous(deps, request: Request) -> None:
|
|
"""A request from Traefik with no Authelia user on a host that isn't the
|
|
guest one: before 2026-11-01 that was the owner. Logged once per IP per
|
|
``_EDGE_QUIET_S`` — a tripwire for whoever tries it now."""
|
|
from users.caller import request_host
|
|
ip = client_ip(request)
|
|
now = time.time()
|
|
with _lock:
|
|
if now - _edge_seen.get(ip, 0) < _EDGE_QUIET_S:
|
|
return
|
|
_edge_seen[ip] = now
|
|
record(deps, "edge_anonymous", request=request,
|
|
detail=f"{request.method} {request.scope.get('path')} "
|
|
f"on Host {request_host(request)!r}")
|
|
|
|
|
|
def cross_site_refused(deps, request: Request) -> None:
|
|
"""A state-changing request a browser sent from another origin (the gate
|
|
refused it): a page on some other site — a guest's, a compromised one —
|
|
tried to use the session of whoever was looking at it. Logged once per
|
|
origin per ``_EDGE_QUIET_S``, with whose session it was."""
|
|
from core.auth import _authelia_user, _guest_session
|
|
origin = (request.headers.get("origin")
|
|
or f"({request.headers.get('sec-fetch-site') or '?'})")[:200]
|
|
try:
|
|
guest = _guest_session(request)
|
|
except Exception:
|
|
guest = None
|
|
who = guest.id if guest else ("owner" if _authelia_user(request) else None)
|
|
now = time.time()
|
|
with _lock:
|
|
if now - _cross_seen.get((origin, who or ""), 0) < _EDGE_QUIET_S:
|
|
return
|
|
_cross_seen[(origin, who or "")] = now
|
|
record(deps, "cross_site", who=who, request=request,
|
|
detail=f"{request.method} {request.scope.get('path')} from {origin}")
|
|
|
|
|
|
def _once(seen: dict, key, quiet: float) -> bool:
|
|
"""True the first time ``key`` comes up in ``quiet`` seconds."""
|
|
now = time.time()
|
|
with _lock:
|
|
if now - seen.get(key, 0) < quiet:
|
|
return False
|
|
if len(seen) > 5000:
|
|
seen.clear()
|
|
seen[key] = now
|
|
return True
|
|
|
|
|
|
def perm_denied(deps, request: Request, caller, perm: str | None,
|
|
template: str | None) -> None:
|
|
"""The gate refused ``caller`` a route for lack of ``perm``
|
|
(authz/routes.py; None = a route no table entry covers)."""
|
|
who = getattr(caller, "id", None)
|
|
scope = getattr(caller, "scope", None)
|
|
route = template or request.scope.get("path") or ""
|
|
if not _once(_denied_seen, (who, scope, request.method, route), _EDGE_QUIET_S):
|
|
return
|
|
record(deps, "perm_denied", who=who, request=request,
|
|
detail=f"{request.method} {route} needs {perm or 'every permission'}"
|
|
+ (f" (through the {scope} scope)" if scope else ""),
|
|
data={"perm": perm, "scope": scope, "route": route})
|
|
|
|
|
|
def loopback_tokenless(deps, request: Request, template: str | None) -> None:
|
|
"""A host caller (loopback / the docker gateway) without the host token:
|
|
the owner still, this round — written down so the callers left can be
|
|
found and given the token before loopback stops being a credential
|
|
(docs/permissions.md)."""
|
|
route = template or request.scope.get("path") or ""
|
|
ua = (request.headers.get("user-agent") or "")[:80]
|
|
peer = request.client.host if request.client else ""
|
|
if not _once(_loopback_seen, (request.method, route, peer, ua), _LOOPBACK_QUIET_S):
|
|
return
|
|
record(deps, "loopback_tokenless", request=request,
|
|
detail=f"{request.method} {route} from {peer or '?'} ({ua or 'no user agent'})",
|
|
data={"route": route, "method": request.method})
|
|
|
|
|
|
def _push(deps, ev: dict) -> None:
|
|
from notifications.service import VIEW_URL, _create_notify
|
|
icon, title = PUSHABLE[ev["kind"]]
|
|
who = ev.get("who") or "?"
|
|
_create_notify(deps, {
|
|
"title": f"{icon} {title}",
|
|
"message": f"{who} · {ev.get('detail') or ''}"[:400],
|
|
"type": "auth", "url": f"{VIEW_URL}/settings/security",
|
|
# No session: a security push is the owner's alone, never the
|
|
# conversation's audience (the guest it is about).
|
|
"sessionId": ""})
|
|
|
|
|
|
def guest_live_runs(deps) -> list[str]:
|
|
"""Live lab runs launched for a guest (``meta.runAs`` ≠ owner)."""
|
|
from runs.sidecar_client import _sidecar_live_sids
|
|
from runs.service import OWNER_RUN
|
|
live = _sidecar_live_sids(deps) or set()
|
|
return sorted(s for s in live
|
|
if (deps.meta_store.peek(s) or {}).get("runAs") not in (None, OWNER_RUN))
|
|
|
|
|
|
def _interrupt(deps, sid: str, worker: str | None = None) -> bool:
|
|
from fastapi import HTTPException
|
|
from runs.sidecar_client import _sidecar_busy, _sidecar_call
|
|
_sidecar_busy.add(sid)
|
|
try:
|
|
_sidecar_call(deps, "/interrupt", {"sessionId": sid}, worker=worker)
|
|
deps.meta_store.update(sid, {"state": "interrupted"})
|
|
deps.hub.publish({"type": "meta", "id": sid})
|
|
return True
|
|
except HTTPException:
|
|
return False
|
|
finally:
|
|
_sidecar_busy.discard(sid)
|
|
|
|
|
|
def lock_guests(deps, locked: bool) -> dict:
|
|
"""*Lock guests*: every guest session is dropped, sign-in and links are
|
|
refused (the gate) and their live runs are interrupted. Unlocking only
|
|
lifts the refusal — they sign in again."""
|
|
state = deps.security_state.set_locked(locked)
|
|
stopped: list[str] = []
|
|
dropped = 0
|
|
if locked:
|
|
for u in deps.users.all():
|
|
dropped += deps.auth.revoke_user(u["id"]) or 0
|
|
stopped = [s for s in guest_live_runs(deps) if _interrupt(deps, s)]
|
|
record(deps, "guests_locked" if locked else "guests_unlocked", who="owner",
|
|
detail=(f"{dropped} sessions dropped, {len(stopped)} runs stopped"
|
|
if locked else "guests may sign in again"))
|
|
deps.hub.publish({"type": "users"})
|
|
return {**state, "sessionsDropped": dropped, "runsStopped": stopped}
|
|
|
|
|
|
def lock_remote(deps, locked: bool) -> dict:
|
|
"""*Internet access* off: every owner session on the internet address is
|
|
dropped and no sign-in is taken there until it is switched back on (from
|
|
the admin host or the internet address itself — off is one tap anywhere)."""
|
|
deps.security_state.set_remote_locked(locked)
|
|
dropped = deps.owner_sessions.close_all() if locked else 0
|
|
if locked:
|
|
deps.owner_passkeys.cancel_invites() # an open link dies with it
|
|
record(deps, "remote_locked" if locked else "remote_unlocked", who="owner",
|
|
detail=f"{dropped} sessions dropped" if locked else "sign-in allowed again")
|
|
return {**deps.security_state.get(), "sessionsDropped": dropped}
|
|
|
|
|
|
def stop_every_run(deps) -> dict:
|
|
"""*Stop every run*: interrupt every live run, on the lab sidecar and on
|
|
each online worker."""
|
|
from runs.sidecar_client import _sidecar_live_sids
|
|
stopped: list[str] = []
|
|
for worker in [None, *(w["id"] for w in deps.worker_store.list()
|
|
if deps.worker_store.online(w["id"]))]:
|
|
for sid in sorted(_sidecar_live_sids(deps, worker) or ()):
|
|
if _interrupt(deps, sid, worker):
|
|
stopped.append(sid)
|
|
record(deps, "runs_stopped", who="owner", detail=f"{len(stopped)} runs stopped",
|
|
data={"sessions": stopped})
|
|
return {"runsStopped": stopped}
|