backend/security/: /data/security-log.jsonl (append-only, rotated) and /data/security.json (Lock guests, which kinds push, the devices each guest signed in from). Logged: guest sign-ins and link requests (IP + UA), new devices, guest runs, anonymous edge requests on the admin host (the 2026-11-01 hole, now a tripwire), the guard hook's hits and sandbox denials (POST /api/security/events). Owner routes: GET /api/security/log|state, PUT /api/security/settings, POST /api/security/lock-guests (drops every guest session, refuses sign-in, interrupts their live runs) and /api/security/stop-runs (every live run, lab and online workers). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
106 lines
4.1 KiB
Python
106 lines
4.1 KiB
Python
"""Settings → Security: the log, the push picks, *Lock guests* and *Stop every
|
|
run* — the owner's only (none of it is in GUEST_ROUTES) — and the endpoint
|
|
the guard hook reports to."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import datetime
|
|
|
|
from fastapi import APIRouter, HTTPException
|
|
from pydantic import BaseModel
|
|
|
|
import schemas
|
|
from core.http import _r
|
|
from core.state import State
|
|
from security import service
|
|
from users.caller import OwnerDep
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
def _state(deps) -> dict:
|
|
from runs.sidecar_client import _sidecar_get
|
|
since = (datetime.datetime.now(datetime.timezone.utc)
|
|
- datetime.timedelta(hours=24)).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
counts: dict[str, int] = {}
|
|
for ev in deps.security_log.events(since=since, limit=10000):
|
|
counts[ev["kind"]] = counts.get(ev["kind"], 0) + 1
|
|
health = _sidecar_get("/health", timeout=3) or {}
|
|
return {**deps.security_state.get(), "pushable": list(service.PUSHABLE),
|
|
"counts24h": counts, "guestRunsLive": len(service.guest_live_runs(deps)),
|
|
"guard": bool(health.get("guard")), "sandbox": bool(health.get("sandbox"))}
|
|
|
|
|
|
@router.get("/api/security/log", responses=_r(schemas.SecurityLog))
|
|
def security_log(deps: State, _: OwnerDep, kind: str | None = None,
|
|
who: str | None = None, limit: int = 200):
|
|
kinds = {k for k in (kind or "").split(",") if k} or None
|
|
return {"events": deps.security_log.events(kinds=kinds, who=who or None,
|
|
limit=max(1, min(limit, 2000)))}
|
|
|
|
|
|
@router.get("/api/security/state", responses=_r(schemas.SecurityState))
|
|
def security_state(deps: State, _: OwnerDep):
|
|
return _state(deps)
|
|
|
|
|
|
class SecuritySettingsBody(BaseModel):
|
|
pushKinds: list[str]
|
|
|
|
|
|
@router.put("/api/security/settings", responses=_r(schemas.SecurityState))
|
|
def security_settings(deps: State, _: OwnerDep, body: SecuritySettingsBody):
|
|
unknown = set(body.pushKinds) - set(service.PUSHABLE)
|
|
if unknown:
|
|
raise HTTPException(400, f"not pushable: {sorted(unknown)}")
|
|
deps.security_state.set_push_kinds(body.pushKinds)
|
|
deps.hub.publish({"type": "security"})
|
|
return _state(deps)
|
|
|
|
|
|
class LockBody(BaseModel):
|
|
locked: bool
|
|
|
|
|
|
@router.post("/api/security/lock-guests", responses=_r(schemas.SecurityLockResult))
|
|
def security_lock_guests(deps: State, _: OwnerDep, body: LockBody):
|
|
out = service.lock_guests(deps, body.locked)
|
|
return {**_state(deps), "sessionsDropped": out.get("sessionsDropped"),
|
|
"runsStopped": out.get("runsStopped")}
|
|
|
|
|
|
@router.post("/api/security/stop-runs", responses=_r(schemas.SecurityStopResult))
|
|
def security_stop_runs(deps: State, _: OwnerDep):
|
|
return service.stop_every_run(deps)
|
|
|
|
|
|
class GuardEvent(BaseModel):
|
|
"""What the guard hook (sidecar/guard.py) saw: a rule a tool call
|
|
tripped, or a sandbox denial in a Bash result."""
|
|
kind: str # guard_block | guard_owner | sandbox_denial
|
|
sessionId: str | None = None
|
|
tool: str | None = None
|
|
rule: str | None = None # e.g. persistence.shell-rc
|
|
reason: str | None = None
|
|
input: str | None = None # the command / path, trimmed
|
|
cwd: str | None = None
|
|
|
|
|
|
@router.post("/api/security/events", responses=_r(schemas.OkResponse))
|
|
def security_event(deps: State, _: OwnerDep, body: GuardEvent):
|
|
"""From the hook, on the host: the owner's caller by construction (it runs
|
|
outside any sandbox, over loopback)."""
|
|
if body.kind not in ("guard_block", "guard_owner", "sandbox_denial"):
|
|
raise HTTPException(400, f"unknown kind: {body.kind!r}")
|
|
sid = body.sessionId or None
|
|
meta = deps.meta_store.peek(sid) if sid else {}
|
|
who = meta.get("runAs") or meta.get("owner") or "owner"
|
|
what = f"{body.tool or '?'} · {body.rule or ''}".strip(" ·")
|
|
detail = f"{what}: {(body.input or '')[:300]}"
|
|
if body.reason:
|
|
detail += f" — {body.reason[:150]}"
|
|
service.record(deps, body.kind, who=who, sid=sid, detail=detail,
|
|
data={k: v for k, v in body.model_dump().items()
|
|
if v and k not in ("kind", "sessionId")})
|
|
return {"ok": True}
|