File size: 6,449 Bytes
72fc0ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
"""
Authentication and Role-Based Access Control (RBAC).

Provides:
  - JWT token creation / verification
  - User roles: VIEWER, ANALYST, TRADER, ADMIN
  - Permission guards via the @require_permission decorator
  - AuthContext dataclass (pass-through for API handlers)

JWT is signed with HMAC-SHA256.  The secret is read from the
``QUANTLIB_JWT_SECRET`` environment variable; if absent a temporary
random key is generated (dev-safe, not prod-safe).
"""

from __future__ import annotations

import hashlib
import hmac
import json
import logging
import os
import time
from base64 import urlsafe_b64decode, urlsafe_b64encode
from dataclasses import dataclass, field
from enum import Enum
from functools import wraps
from typing import Any, Callable, Optional, TypeVar

log = logging.getLogger(__name__)

F = TypeVar("F", bound=Callable[..., Any])


# ─── Roles & permissions ──────────────────────────────────────────────────────

class Role(str, Enum):
    VIEWER = "viewer"
    ANALYST = "analyst"
    TRADER = "trader"
    ADMIN = "admin"


# Permission matrix: role β†’ set of allowed actions
_PERMISSIONS: dict[Role, set[str]] = {
    Role.VIEWER: {"read:prices", "read:reports"},
    Role.ANALYST: {
        "read:prices", "read:reports",
        "compute:options", "compute:risk", "compute:portfolio",
    },
    Role.TRADER: {
        "read:prices", "read:reports",
        "compute:options", "compute:risk", "compute:portfolio",
        "execute:orders", "manage:portfolio",
    },
    Role.ADMIN: {"*"},  # wildcard β€” all permissions
}


def has_permission(role: Role, action: str) -> bool:
    perms = _PERMISSIONS.get(role, set())
    return "*" in perms or action in perms


# ─── JWT implementation (stdlib only, no PyJWT dependency) ────────────────────

_SECRET: bytes = os.environ.get("QUANTLIB_JWT_SECRET", "").encode() or os.urandom(32)
_ALGORITHM = "HS256"
_HEADER_B64 = urlsafe_b64encode(
    json.dumps({"alg": _ALGORITHM, "typ": "JWT"}).encode()
).rstrip(b"=")


def _b64_encode(data: bytes) -> bytes:
    return urlsafe_b64encode(data).rstrip(b"=")


def _b64_decode(data: str | bytes) -> bytes:
    if isinstance(data, str):
        data = data.encode()
    padding = 4 - len(data) % 4
    if padding != 4:
        data += b"=" * padding
    return urlsafe_b64decode(data)


def _sign(header_b64: bytes, payload_b64: bytes) -> bytes:
    msg = header_b64 + b"." + payload_b64
    return _b64_encode(hmac.new(_SECRET, msg, hashlib.sha256).digest())


def create_token(
    user_id: str,
    role: Role,
    ttl_seconds: int = 3600,
    extra_claims: Optional[dict] = None,
) -> str:
    """Return a signed JWT string."""
    now = int(time.time())
    payload: dict[str, Any] = {
        "sub": user_id,
        "role": role.value,
        "iat": now,
        "exp": now + ttl_seconds,
    }
    if extra_claims:
        payload.update(extra_claims)
    payload_b64 = _b64_encode(json.dumps(payload, separators=(",", ":")).encode())
    sig = _sign(_HEADER_B64, payload_b64)
    return f"{_HEADER_B64.decode()}.{payload_b64.decode()}.{sig.decode()}"


def verify_token(token: str) -> dict[str, Any]:
    """
    Verify signature and expiry.  Returns the decoded payload dict.

    Raises
    ------
    AuthenticationError
        On any verification failure.
    """
    try:
        header_b64, payload_b64, sig_b64 = token.split(".")
    except ValueError as exc:
        raise AuthenticationError("Malformed token") from exc

    expected_sig = _sign(header_b64.encode(), payload_b64.encode())
    if not hmac.compare_digest(expected_sig, sig_b64.encode()):
        raise AuthenticationError("Invalid token signature")

    try:
        payload = json.loads(_b64_decode(payload_b64))
    except Exception as exc:
        raise AuthenticationError("Failed to decode token payload") from exc

    if payload.get("exp", 0) < int(time.time()):
        raise AuthenticationError("Token has expired")

    return payload


# ─── Exceptions ──────────────────────────────────────────────────────────────

class AuthenticationError(PermissionError):
    pass


class AuthorizationError(PermissionError):
    pass


# ─── Auth context ─────────────────────────────────────────────────────────────

@dataclass
class AuthContext:
    user_id: str
    role: Role
    issued_at: int
    expires_at: int
    extra: dict = field(default_factory=dict)

    @classmethod
    def from_token(cls, token: str) -> "AuthContext":
        payload = verify_token(token)
        return cls(
            user_id=payload["sub"],
            role=Role(payload["role"]),
            issued_at=payload["iat"],
            expires_at=payload["exp"],
            extra={k: v for k, v in payload.items() if k not in ("sub", "role", "iat", "exp")},
        )

    def require_permission(self, action: str) -> None:
        if not has_permission(self.role, action):
            raise AuthorizationError(
                f"User '{self.user_id}' ({self.role.value}) lacks permission: '{action}'"
            )


# ─── Decorator ────────────────────────────────────────────────────────────────

def require_permission(action: str) -> Callable[[F], F]:
    """
    Decorator that validates ``auth_ctx`` keyword argument on the
    decorated function.

    Usage::

        @require_permission("compute:options")
        def price_option(S, K, T, r, sigma, *, auth_ctx: AuthContext):
            ...
    """
    def decorator(fn: F) -> F:
        @wraps(fn)
        def wrapper(*args: Any, **kwargs: Any) -> Any:
            ctx: Optional[AuthContext] = kwargs.get("auth_ctx")
            if ctx is None:
                raise AuthenticationError(
                    f"Function '{fn.__name__}' requires 'auth_ctx' keyword argument"
                )
            ctx.require_permission(action)
            return fn(*args, **kwargs)
        return wrapper  # type: ignore[return-value]
    return decorator