""" ALLI Backend - Authentication & Workspace Resolution Middleware Layer Verifies Supabase Bearer JWTs or X-API-Key, resolves workspace role via orgs_repo/app_metadata, and enforces strict auth or explicit localhost dev solo loopback mode. """ import os import secrets from typing import Optional, Set from fastapi import Request from starlette.middleware.base import BaseHTTPMiddleware from starlette.responses import JSONResponse from database.mongo import workflow_repo from security.rbac import is_local_loopback_request, resolve_workspace_context # Insecure placeholder keys that must never be accepted as valid master credentials PROHIBITED_KEY_DEFAULTS = { "your_master_api_key_here", "alli_dev_secret_key_2026", "changeme", "secret", "admin", } # Public endpoints that do not require authentication PUBLIC_PATHS: Set[str] = { "/", "/api", "/ping", "/api/ping", "/health", "/api/health", "/health/live", "/api/health/live", "/health/ready", "/api/health/ready", "/docs", "/redoc", "/openapi.json", "/favicon.ico", } class AuthenticationMiddleware(BaseHTTPMiddleware): """ Middleware that intercepts incoming HTTP requests to verify authentication and attach verified user + workspace RBAC context onto request.state. """ def __init__(self, app, supabase_client=None): super().__init__(app) self.supabase_client = supabase_client self._auth_required_override: Optional[bool] = None self.master_api_key = os.environ.get("MASTER_API_KEY", "") @property def auth_required(self) -> bool: if self._auth_required_override is not None: return self._auth_required_override stage = os.environ.get("STAGE", "dev").lower() default_auth = "true" if stage in ("production", "prod", "staging") else "false" return os.environ.get("AUTH_REQUIRED", default_auth).lower() in ("true", "1", "yes") @auth_required.setter def auth_required(self, value: bool) -> None: self._auth_required_override = bool(value) async def dispatch(self, request: Request, call_next): path = request.url.path method = request.method if method == "OPTIONS": return await call_next(request) if path in PUBLIC_PATHS or path.startswith("/docs") or path.startswith("/redoc"): return await call_next(request) auth_header = request.headers.get("Authorization", "") api_key_header = request.headers.get("X-API-Key", "") requested_org_id = request.headers.get("X-Org-Id") authenticated_user = None is_authenticated = False invalid_token = False # 3A. Master API Key (service-to-service / CI) clean_key = (self.master_api_key or "").strip() clean_header = (api_key_header or "").strip() if ( clean_key and len(clean_key) >= 16 and clean_key not in PROHIBITED_KEY_DEFAULTS and clean_header and secrets.compare_digest(clean_header, clean_key) ): is_authenticated = True authenticated_user = {"id": "service_account", "role": "owner", "app_metadata": {"platform_role": "admin"}} # 3B. Supabase Bearer JWT verification elif auth_header.startswith("Bearer "): token = auth_header[7:].strip() if self.supabase_client and token: try: user_response = self.supabase_client.auth.get_user(token) if user_response and user_response.user: u = user_response.user app_meta = getattr(u, "app_metadata", None) or {} is_authenticated = True authenticated_user = { "id": u.id, "email": u.email, "app_metadata": app_meta, # Do NOT expose Postgres 'authenticated' as an app RBAC role "supabase_role": getattr(u, "role", None), } else: invalid_token = True except Exception as auth_err: print(f"[ALLI Auth Middleware] Supabase token validation failed: {auth_err}") is_authenticated = False invalid_token = True elif token: is_authenticated = False invalid_token = True # 4. Enforce authentication policy if self.auth_required and not is_authenticated: return JSONResponse( status_code=401, content={ "error": "Unauthorized", "detail": "Authentication required. Please provide a valid Bearer token or X-API-Key.", "path": path, }, headers={ "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "*", }, ) # 5. Resolve Workspace & RBAC Role (orgs_repo / app_metadata / local solo loopback) is_loopback = is_local_loopback_request(request) workspace = resolve_workspace_context( user=authenticated_user if not invalid_token else None, requested_org_id=requested_org_id, repo=workflow_repo, is_local_loopback=is_loopback and not invalid_token, ) if authenticated_user and not invalid_token: authenticated_user["role"] = workspace["role"] authenticated_user["org_id"] = workspace["org_id"] request.state.user = authenticated_user request.state.is_authenticated = is_authenticated request.state.invalid_token = invalid_token request.state.workspace = workspace request.state.org_id = workspace.get("org_id") request.state.org_role = workspace.get("role") if is_authenticated and workspace.get("org_access_denied"): return JSONResponse( status_code=403, content={ "error": "Forbidden", "detail": f"Workspace access denied for org '{workspace.get('org_id')}'.", "path": path, }, ) return await call_next(request)