""" ALLI Backend - Commercial Multi-Tenant RBAC & Audit Guard Enforces workspace membership roles (owner | admin | editor | viewer), explicit local solo loopback policy, and structured audit logging. """ import os from typing import Any, Dict, Optional, Set from fastapi import HTTPException, Request, status VALID_ROLES = ("owner", "admin", "editor", "viewer") ROLE_RANK = {"viewer": 1, "editor": 2, "admin": 3, "owner": 4} LOOPBACK_HOSTS = {"", "localhost", "127.0.0.1", "::1", "testserver", "testclient"} def _is_loopback_or_private(h: str) -> bool: if not h or h in LOOPBACK_HOSTS: return True if h.startswith(("127.", "10.", "192.168.")) or h.endswith(".local"): return True if h.startswith("172."): parts = h.split(".") if len(parts) > 1 and parts[1].isdigit() and 16 <= int(parts[1]) <= 31: return True return False def is_local_loopback_request(request: Optional[Request]) -> bool: """Return True only in dev-equivalent STAGE on localhost/test client or LAN context.""" if _get_normalized_stage() not in _DEV_STAGES: return False if request is None: return True headers = getattr(request, "headers", None) or {} host = str(headers.get("host", "")).split(":")[0].lower().strip() client_host = str(getattr(getattr(request, "client", None), "host", "") or "").lower().strip() return _is_loopback_or_private(host) and _is_loopback_or_private(client_host) ROLE_CAPABILITIES: Dict[str, Set[str]] = { "owner": { "workflow:read", "workflow:write", "workflow:execute", "workflow:fork", "library:introspect", "template:publish", "node:promote", "node:reject", "org:members:manage", "org:billing:manage", "audit:read", "env:read", "env:write", "env:reveal", }, "admin": { "workflow:read", "workflow:write", "workflow:execute", "workflow:fork", "library:introspect", "template:publish", "node:promote", "node:reject", "org:members:manage", "audit:read", "env:read", "env:write", "env:reveal", }, "editor": { "workflow:read", "workflow:write", "workflow:execute", "workflow:fork", "library:introspect", "template:publish", "env:read", "env:write", }, "viewer": {"workflow:read", "workflow:fork"}, } _DEV_STAGES = frozenset({"dev", "development", "local", "test"}) def _get_normalized_stage() -> str: return (os.environ.get("STAGE") or "dev").strip().lower() def is_auth_required() -> bool: """Resolve strict auth enforcement dynamically from STAGE and AUTH_REQUIRED env vars.""" if _get_normalized_stage() not in _DEV_STAGES: return True return os.environ.get("AUTH_REQUIRED", "false").strip().lower() in ("true", "1", "yes", "on") def normalize_app_role(raw_role: Optional[str], default: str = "viewer") -> str: """Normalize application role while ignoring raw Supabase Postgres 'authenticated' claim.""" r = str(raw_role or "").lower().strip() return r if r in VALID_ROLES else default def _denied_ctx(org_id: Optional[str], uid: Optional[str], email: str = "", is_auth: bool = False, loopback: bool = False) -> Dict[str, Any]: return { "org_id": org_id, "role": "none", "user_id": uid, "email": email, "is_authenticated": is_auth, "is_platform_admin": False, "is_local_loopback": loopback, "org_access_denied": True, } def resolve_workspace_context( user: Optional[Dict[str, Any]], requested_org_id: Optional[str], repo: Any, is_local_loopback: bool = False, ) -> Dict[str, Any]: """Resolve active workspace (org_id) and RBAC role from verified JWT + orgs_repo.""" req_org = (requested_org_id or "").strip() or None if user and isinstance(user, dict) and user.get("id"): uid = str(user["id"]) email = user.get("email", "") if uid == "service_account": return { "org_id": req_org or "local_personal", "role": "owner", "user_id": uid, "email": email, "is_authenticated": True, "is_platform_admin": True, "is_local_loopback": False, "org_access_denied": False, } repo.ensure_personal_org(uid, email=email) app_meta = user.get("app_metadata") if isinstance(user.get("app_metadata"), dict) else {} is_platform_admin = ( app_meta.get("platform_role") == "admin" or app_meta.get("role") == "admin" or user.get("role") == "admin" ) target_org = req_org if (req_org and req_org != "local_personal") else f"personal_{uid}" membership = repo.get_org_membership(target_org, uid) if membership and membership.get("status", "active") == "active": role = normalize_app_role(membership.get("role"), default="viewer") elif target_org == f"personal_{uid}": role = "owner" elif is_platform_admin: role = "admin" elif isinstance(app_meta.get("org_roles"), dict) and target_org in app_meta["org_roles"]: role = normalize_app_role(app_meta["org_roles"][target_org], default="viewer") else: return _denied_ctx(target_org, uid, email=email, is_auth=True) return { "org_id": target_org, "role": role, "user_id": uid, "email": email, "is_authenticated": True, "is_platform_admin": is_platform_admin, "is_local_loopback": False, "org_access_denied": False, } if not is_auth_required() and is_local_loopback: if req_org and req_org != "local_personal": return _denied_ctx(req_org, None, loopback=True) return { "org_id": "local_personal", "role": "owner", "user_id": None, "email": "", "is_authenticated": False, "is_platform_admin": False, "is_local_loopback": True, "org_access_denied": False, } return _denied_ctx(req_org, None) def get_request_workspace(request: Optional[Request]) -> Dict[str, Any]: """Read workspace context from request.state, safely supporting unit-test MockRequests.""" if request is None: solo = not is_auth_required() return { "org_id": "local_personal", "role": "owner" if solo else "none", "user_id": None, "is_authenticated": False, "is_platform_admin": False, "is_local_loopback": solo, "org_access_denied": False, } state = getattr(request, "state", None) ctx = getattr(state, "workspace", None) if state else None if isinstance(ctx, dict): return ctx from database.mongo import workflow_repo auth_user = getattr(state, "user", None) if state else None headers = getattr(request, "headers", None) or {} req_org = headers.get("x-org-id") or headers.get("X-Org-Id") return resolve_workspace_context( user=auth_user, requested_org_id=req_org, repo=workflow_repo, is_local_loopback=is_local_loopback_request(request), ) def audit_action( request: Optional[Request], repo: Any, action: str, resource_type: str, resource_id: str = "", status_code: int = 200, metadata: Optional[Dict[str, Any]] = None, ) -> None: """Persist structured RBAC audit log event.""" ctx = get_request_workspace(request) repo.record_audit_log( org_id=ctx.get("org_id") or "local_personal", actor_user_id=ctx.get("user_id") or "local_solo", actor_role=ctx.get("role") or "none", action=action, resource_type=resource_type, resource_id=str(resource_id or ""), status_code=status_code, metadata=metadata, ) def require_roles( request: Optional[Request], allowed_roles: Set[str], allow_local_solo: bool = True, action: Optional[str] = None, resource_type: str = "workspace", resource_id: str = "", ) -> Dict[str, Any]: """Enforce authentication and workspace role membership (401/403).""" from database.mongo import workflow_repo state = getattr(request, "state", None) if request else None if state and getattr(state, "invalid_token", False): is_dev_solo = allow_local_solo and not is_auth_required() and is_local_loopback_request(request) if not is_dev_solo: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid or expired authentication token.") ctx = get_request_workspace(request) is_auth = bool(ctx.get("is_authenticated")) is_solo_ok = allow_local_solo and bool(ctx.get("is_local_loopback")) and not is_auth_required() if not is_auth and not is_solo_ok: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Authentication required to perform this action.") if ctx.get("org_access_denied"): if action: audit_action(request, workflow_repo, action, resource_type, resource_id, status_code=403) raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=f"Forbidden: Not an active member of workspace '{ctx.get('org_id')}'.") role = ctx.get("role", "none") if role not in allowed_roles and not ctx.get("is_platform_admin"): if action: audit_action(request, workflow_repo, action, resource_type, resource_id, status_code=403) raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=f"Forbidden: Role '{role}' lacks permission. Required: {sorted(allowed_roles)}.") return ctx