"""Who may call which rendering route, and who owns which job.""" from __future__ import annotations import enum import logging from dataclasses import dataclass import jwt from fastapi import Depends, HTTPException, Request from config.auth import ( AUTH_ENFORCED, PREVISION_TOKEN_ISSUER, PROCESSING_TOKEN_AUDIENCE, PROCESSING_TOKEN_SECRET, TOKEN_ISSUERS, TOKEN_LEEWAY_SECONDS, ) logger = logging.getLogger(__name__) class Role(str, enum.Enum): ADMIN = "superadmin" CLIENT = "client" @dataclass(frozen=True) class Principal: # The job owner: a user id, or a widget session id ("widget:"). user_id: str role: Role issuer: str = "" # Optional feature entitlements supplied by the account service. organization_id: str = "" features: frozenset[str] = frozenset() @property def is_admin(self) -> bool: return self.role == Role.ADMIN @property def has_free_tries(self) -> bool: """Prevision accounts: every accepted job uses one of their free tries.""" return self.issuer == PREVISION_TOKEN_ISSUER def _unauthorized(detail: str) -> HTTPException: return HTTPException(status_code=401, detail=detail, headers={"WWW-Authenticate": "Bearer"}) def _bearer_token(request: Request) -> str | None: header = request.headers.get("authorization", "") scheme, _, token = header.partition(" ") if scheme.lower() != "bearer" or not token.strip(): return None return token.strip() def decode_processing_token(token: str) -> Principal: if not PROCESSING_TOKEN_SECRET: raise _unauthorized("Token verification is not configured on this server.") try: claims = jwt.decode( token, PROCESSING_TOKEN_SECRET, algorithms=["HS256"], audience=PROCESSING_TOKEN_AUDIENCE, issuer=TOKEN_ISSUERS, leeway=TOKEN_LEEWAY_SECONDS, options={"require": ["exp", "iat", "sub", "aud", "iss"]}, ) except jwt.ExpiredSignatureError as exc: raise _unauthorized("Your session expired. Please refresh the page.") from exc except jwt.PyJWTError as exc: raise _unauthorized("Invalid access token.") from exc issuer = str(claims["iss"]) try: role = Role(claims.get("role")) except ValueError: role = None if role is None: raise HTTPException(status_code=403, detail="This account cannot use the visualizer.") features = claims.get("feat") return Principal( user_id=str(claims["sub"]), role=role, issuer=issuer, organization_id=str(claims.get("org") or ""), features=frozenset(str(name) for name in features) if isinstance(features, list) else frozenset(), ) def optional_principal(request: Request) -> Principal | None: """Resolve the caller. With enforcement on, a token is mandatory.""" token = _bearer_token(request) if token is None: if AUTH_ENFORCED: raise _unauthorized("Please sign in to use the visualizer.") return None try: return decode_processing_token(token) except HTTPException: if AUTH_ENFORCED: raise # Enforcement off: a stale token must not break today's public flow. logger.info("Ignoring invalid processing token while enforcement is off") return None def require_client(principal: Principal | None = Depends(optional_principal)) -> Principal | None: """Approved client or admin (approval is checked when the token is minted).""" return principal def require_admin(request: Request) -> Principal: """Always enforced, even with AUTH_ENFORCEMENT=off: job listings, debug artifacts and QA runs expose every user's data, unlike a single job id.""" token = _bearer_token(request) if token is None: raise _unauthorized("Administrator sign-in is required.") principal = decode_processing_token(token) if not principal.is_admin: raise HTTPException(status_code=403, detail="Administrator access is required.") return principal def require_feature(feature: str): """A route for organizations that have `feature` switched on (and administrators). Always enforced, like `require_admin`: these routes spend paid API calls. """ def dependency(request: Request) -> Principal: token = _bearer_token(request) if token is None: raise _unauthorized("Please sign in to use the visualizer.") principal = decode_processing_token(token) if not principal.is_admin and feature not in principal.features: raise HTTPException(status_code=403, detail="This feature is not enabled for your account.") return principal return dependency def require_enhance(request: Request) -> Principal: """'Enhance with AI' v2: every signed-in Prevision account (each use is charged as a generation), administrators, and organizations with `ai_refinement` switched on. Always enforced, like `require_feature`: it spends paid API calls. """ token = _bearer_token(request) if token is None: raise _unauthorized("Please sign in to use the visualizer.") principal = decode_processing_token(token) if not (principal.is_admin or principal.has_free_tries or "ai_refinement" in principal.features): raise HTTPException(status_code=403, detail="This feature is not enabled for your account.") return principal def ensure_job_access(job: dict, principal: Principal | None) -> None: """Owner or admin. Jobs created before ownership existed are admin-only. Returns 404 (not 403) for other users' jobs so job ids cannot be probed. """ if not AUTH_ENFORCED: return if principal is None: raise _unauthorized("Please sign in to use the visualizer.") if principal.is_admin: return if job.get("ownerId") != principal.user_id: raise HTTPException(status_code=404, detail="Job not found.") def owner_fields(principal: Principal | None) -> dict: return {"ownerId": principal.user_id} if principal else {}