File size: 6,161 Bytes
1fe7075
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7a38a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1fe7075
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
"""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:<hex>").
    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 {}