"""Same-origin, capability-scoped Operator grants and audited setup records. This module is deliberately transport-neutral. The browser and a future MCP adapter call the same authorization function; neither receives a secret, provider credential, or cross-tenant wildcard. """ from __future__ import annotations import copy import hashlib import secrets import time from typing import Any STORE_KEY = "operator_control" SETUP_KEY = "operator_setup" AUDIENCE = "loopable-operator" CAPABILITIES = frozenset({"tenant.read", "tenant.configure", "voice.read", "voice.configure"}) SETUP_FIELDS = frozenset({"displayName", "timezone", "voicePurpose", "consentPolicy", "queryEnabled", "providerLabel"}) class OperatorRefusal(ValueError): pass def _now() -> int: return int(time.time()) def _hash(value: str) -> str: return hashlib.sha256(str(value or "").encode("utf-8")).hexdigest() def _origin(value: Any) -> str: text = str(value or "").strip().lower().rstrip("/") if not text.startswith(("https://", "http://localhost", "http://127.0.0.1")): raise OperatorRefusal("Operator grants require the current Loopable origin") if any(ch in text for ch in ("?", "#", "@")): raise OperatorRefusal("Operator origin is invalid") return text[:240] def _document(rt: Any) -> dict: try: raw = rt.get(STORE_KEY) or {} except Exception: raw = {} if not isinstance(raw, dict): raw = {} return {"grants": copy.deepcopy(raw.get("grants") or {}), "audit": copy.deepcopy(raw.get("audit") or [])} def _update(rt: Any, fn): return rt.update(STORE_KEY, lambda raw: fn({ "grants": copy.deepcopy((raw or {}).get("grants") or {}), "audit": copy.deepcopy((raw or {}).get("audit") or []), }), flush="sync") def _audit(rt: Any, *, actor: str, tenant: str, capability: str, action: str, outcome: str, grant_id: str = "", source: str = "browser") -> dict: event = {"id": f"opa_{_now()}_{secrets.token_hex(4)}", "at": _now(), "actor": str(actor or "")[:120], "tenant": str(tenant or "")[:120], "capability": str(capability or "")[:80], "action": str(action or "")[:120], "outcome": str(outcome or "refused")[:40], "grantId": str(grant_id or "")[:120], "source": "mcp" if source == "mcp" else "browser"} def up(doc): doc["audit"] = (list(doc.get("audit") or []) + [event])[-2000:] return doc _update(rt, up) return event def mint_grant(rt: Any, *, actor: str, tenant: str, capabilities: Any, origin: str, audience: str = AUDIENCE, ttl_seconds: int = 900) -> dict: target = str(tenant or "").strip().lower() gid, outcome = "", "refused" try: if not target or target == "*": raise OperatorRefusal("Operator grant needs one exact tenant") requested = sorted({str(value) for value in (capabilities or [])}) if not requested or any(value not in CAPABILITIES for value in requested): raise OperatorRefusal("Operator grant contains an unsupported capability") if str(audience or "") != AUDIENCE: raise OperatorRefusal("Operator grant audience is invalid") bound_origin = _origin(origin) ttl = max(60, min(int(ttl_seconds or 900), 3600)) token = secrets.token_urlsafe(32) gid = "opg_" + secrets.token_hex(8) rec = {"id": gid, "actor": str(actor or "")[:120], "tenant": target, "capabilities": requested, "origin": bound_origin, "audience": AUDIENCE, "tokenHash": _hash(token), "createdAt": _now(), "expiresAt": _now() + ttl, "revokedAt": 0} _update(rt, lambda doc: {**doc, "grants": {**doc["grants"], gid: rec}}) outcome = "allowed" return {"grant": grant_dto(rec), "token": token} finally: _audit(rt, actor=actor, tenant=target, capability="grant.mint", action="mint", outcome=outcome, grant_id=gid) def grant_dto(rec: Any) -> dict: row = rec if isinstance(rec, dict) else {} return {key: copy.deepcopy(row.get(key)) for key in ("id", "actor", "tenant", "capabilities", "origin", "audience", "createdAt", "expiresAt", "revokedAt")} def revoke_grant(rt: Any, grant_id: str, actor: str) -> dict: result = {} outcome = "refused" def up(doc): rec = doc["grants"].get(str(grant_id)) if not isinstance(rec, dict): raise OperatorRefusal("unknown Operator grant") rec = {**rec, "revokedAt": _now()} doc["grants"][str(grant_id)] = rec result.update(rec) return doc try: _update(rt, up) outcome = "allowed" return grant_dto(result) finally: _audit(rt, actor=actor, tenant=result.get("tenant", ""), capability="grant.revoke", action="revoke", outcome=outcome, grant_id=str(grant_id)) def authorize(rt: Any, *, token: str, actor: str, tenant: str, capability: str, origin: str, audience: str = AUDIENCE, action: str = "read", source: str = "browser") -> dict: target, cap = str(tenant or "").strip().lower(), str(capability or "") outcome, matched = "refused", None try: bound_origin = _origin(origin) now = _now() for rec in _document(rt)["grants"].values(): if isinstance(rec, dict) and secrets.compare_digest(str(rec.get("tokenHash") or ""), _hash(token)): matched = rec break if not matched or matched.get("actor") != str(actor or ""): raise OperatorRefusal("Operator grant is invalid") if matched.get("tenant") != target: raise OperatorRefusal("Operator grant does not cover that tenant") if matched.get("audience") != audience or audience != AUDIENCE: raise OperatorRefusal("Operator grant audience is invalid") if matched.get("origin") != bound_origin: raise OperatorRefusal("Operator grant origin is invalid") if matched.get("revokedAt") or int(matched.get("expiresAt") or 0) <= now: raise OperatorRefusal("Operator grant is expired or revoked") if cap not in set(matched.get("capabilities") or []): raise OperatorRefusal("Operator capability is denied") outcome = "allowed" return grant_dto(matched) finally: _audit(rt, actor=actor, tenant=target, capability=cap, action=action, outcome=outcome, grant_id=str((matched or {}).get("id") or ""), source=source) def authorize_mcp(rt: Any, **kwargs) -> dict: """Optional adapter seam. MCP gets the identical grant, audience, origin, and audit wall.""" return authorize(rt, source="mcp", **kwargs) def setup_dto(rt: Any, tenant: str) -> dict: try: raw = rt.get(SETUP_KEY) or {} except Exception: raw = {} row = raw if isinstance(raw, dict) else {} safe = {key: copy.deepcopy(row.get(key)) for key in SETUP_FIELDS if key in row} return {"tenant": str(tenant or ""), "setup": safe, "secretsPresent": False, "rawProviderBindings": False} def update_setup(rt: Any, tenant: str, raw: Any, actor: str) -> dict: body = raw if isinstance(raw, dict) else {} unknown = sorted(set(body) - SETUP_FIELDS) if unknown: raise OperatorRefusal("unsupported setup properties: " + ", ".join(unknown)) clean = {} for key, value in body.items(): if key == "queryEnabled": if not isinstance(value, bool): raise OperatorRefusal("queryEnabled must be true or false") clean[key] = value else: clean[key] = " ".join(str(value or "").split())[:240] clean.update({"updatedBy": str(actor or "")[:120], "updatedAt": _now()}) rt.update(SETUP_KEY, lambda old: {**dict(old or {}), **clean}, flush="sync") return setup_dto(rt, tenant) def audit_rows(rt: Any, limit: int = 200) -> list[dict]: rows = _document(rt)["audit"][-max(1, min(int(limit or 200), 500)):] return [copy.deepcopy(row) for row in reversed(rows)] def audit_attempt(rt: Any, *, actor: str, tenant: str, capability: str, action: str, outcome: str, grant_id: str = "", source: str = "browser") -> dict: """Public final-operation audit seam; authorization is not operation success.""" return _audit(rt, actor=actor, tenant=tenant, capability=capability, action=action, outcome=outcome, grant_id=grant_id, source=source)