Files
gabrielvidalandClaude Opus 5.5 bfcb3d3b3b fix(remoteaccess): what the security review found — revocation that revokes
- removing a passkey ends every session it opened (sessions record the id);
- an open Chrome view on the internet address re-checks its session every
  5 s and closes when it ends (sign-out, passkey removed, access off);
- Sign out there always ends the owner's session unless the guest cookie
  beside it is a live impersonation — a cookie a guest's *.gabvdl.xyz site
  planted can no longer turn it into a no-op;
- the passkey link and "back on" need Authelia on the admin host, not just
  "not the internet address": the host token / loopback (what a run started
  from a stolen session can call) are refused; making a link now pushes;
- switching internet access off cancels an open link;
- ceremony tickets capped per address (10) so one address can't drain them;
- docs: what the off switch can't undo (the owner is a shell).
- 13 regression tests (test_remote_access: 51).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 15:19:41 +01:00

261 lines
11 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"),
"mcp_connected": ("🔌", "An AI app connected to ai-agent"),
"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",
"worker_linked", "ip_locked", "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) -> dict | None:
"""Append one event (never raises) and push the owner when its kind is
one of his ``pushKinds``."""
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]
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 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 _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}