File size: 2,614 Bytes
348eedc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Authentication + RBAC dependencies.
- Web app: httpOnly session cookie `fpt_session` + CSRF double-submit (`fpt_csrf` cookie, X-CSRF-Token header) on
  every unsafe method.
- Desktop/API clients: `Authorization: Bearer <token>` (POST /api/auth/token). Bearer requests are CSRF-exempt.
Roles: viewer, consultant, qa_approver, admin (coworker/platform/users.PERMISSIONS). Enforced here, not in the UI."""
from __future__ import annotations

from dataclasses import dataclass

from fastapi import Depends, Request

from ..platform.users import PERMISSIONS, consteq
from .errors import ApiError

SESSION_COOKIE = "fpt_session"
CSRF_COOKIE = "fpt_csrf"
CSRF_HEADER = "x-csrf-token"
UNSAFE = {"POST", "PUT", "PATCH", "DELETE"}


@dataclass
class Principal:
    id: int
    username: str
    role: str
    via: str  # cookie | bearer

    def can(self, perm: str) -> bool:
        return self.role in PERMISSIONS.get(perm, ())

    def to_dict(self) -> dict:
        return {"id": self.id, "username": self.username, "role": self.role, "via": self.via,
                "permissions": sorted(p for p in PERMISSIONS if self.can(p))}


def current_user(request: Request) -> Principal:
    svc = request.app.state.svc
    authz = request.headers.get("authorization", "")
    if authz.lower().startswith("bearer "):
        if authz[7:].strip().startswith("pwt_"):   # personal access tokens are for the MCP and A2A connectors only
            raise ApiError(401, "UNAUTHENTICATED", "personal access tokens work only on /mcp and /a2a (the MCP and A2A connectors)")
        got = svc.users.session_user(authz[7:].strip())
        if not got:
            raise ApiError(401, "UNAUTHENTICATED", "invalid or expired bearer token")
        u, _ = got
        p = Principal(u["id"], u["username"], u["role"], "bearer")
    else:
        tok = request.cookies.get(SESSION_COOKIE)
        got = svc.users.session_user(tok) if tok else None
        if not got:
            raise ApiError(401, "UNAUTHENTICATED", "not signed in")
        u, s = got
        if request.method in UNSAFE:
            hdr = request.headers.get(CSRF_HEADER, "")
            if not hdr or not consteq(hdr, s["csrf"]):
                raise ApiError(403, "CSRF", "missing or invalid CSRF token")
        p = Principal(u["id"], u["username"], u["role"], "cookie")
    request.state.user = p
    return p


def require(perm: str):
    def dep(user: Principal = Depends(current_user)) -> Principal:
        if not user.can(perm):
            raise ApiError(403, "FORBIDDEN", f"role '{user.role}' lacks permission '{perm}'")
        return user
    return dep