feat(auth): verify pinned RS256 bearer tokens and deny forged reviewer claims
davoodmehraban89 committed
Oct 30, 2026 at 22:11 UTC
649864cfa3ca77948e00ac15f444d282b80594aa
1 file changed
+133
backend/src/aram_backend/authenticated_identity.py
new
+133
@@ -0,0 +1,133 @@
1
+"""Fail-closed public-key verification of identity-provider access tokens.
2
+
3
+Only the operator-configured public RSA key can verify a token; no client
4
+headers, unsigned JWTs, HS256 shared secrets or user-supplied public keys can
5
+create a verified principal. This module has NO finance approve/apply action.
6
+"""
7
+from __future__ import annotations
8
+
9
+from dataclasses import dataclass
10
+from time import time
11
+from unicodedata import category
12
+
13
+import jwt
14
+from cryptography.hazmat.primitives import serialization
15
+from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey
16
+from fastapi import Depends, HTTPException
17
+from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
18
+
19
+from aram_backend.config import Settings, get_settings
20
+
21
+MAX_TOKEN_LENGTH = 8192
22
+MAX_LIFETIME_SECONDS = 900
23
+TRUSTED_ROLES = frozenset(("mapping_proposer", "mapping_reviewer"))
24
+bearer_scheme = HTTPBearer(auto_error=False)
25
+
26
+
27
+@dataclass(frozen=True)
28
+class VerifiedPrincipal:
29
+ """Identity from successfully validated RS256 issuer/audience claims only."""
30
+
31
+ issuer: str
32
+ subject: str
33
+ roles: tuple[str, ...]
34
+ expires_at: int
35
+
36
+
37
+def _fail_invalid() -> None:
38
+ raise HTTPException(
39
+ status_code=401, detail="Invalid bearer token",
40
+ headers={"WWW-Authenticate": "Bearer"},
41
+ )
42
+
43
+
44
+def _is_safe_string(value: object, limit: int) -> bool:
45
+ return (
46
+ isinstance(value, str) and 0 < len(value) <= limit
47
+ and value == value.strip()
48
+ and not any(category(char) in ("Cc", "Cf", "Cs") for char in value)
49
+ )
50
+
51
+
52
+def _trusted_public_key(settings: Settings) -> RSAPublicKey:
53
+ if (
54
+ not _is_safe_string(settings.auth_issuer, 512)
55
+ or not settings.auth_issuer.startswith("https://")
56
+ or not _is_safe_string(settings.auth_audience, 256)
57
+ or not settings.auth_public_key_pem
58
+ ):
59
+ raise HTTPException(status_code=503, detail="Identity provider is not configured")
60
+ try:
61
+ key = serialization.load_pem_public_key(
62
+ settings.auth_public_key_pem.encode("ascii"),
63
+ )
64
+ except (ValueError, TypeError, UnicodeError) as exc:
65
+ raise HTTPException(
66
+ status_code=503, detail="Identity provider is not configured",
67
+ ) from exc
68
+ if not isinstance(key, RSAPublicKey) or key.key_size < 2048:
69
+ raise HTTPException(status_code=503, detail="Identity provider is not configured")
70
+ return key
71
+
72
+
73
+def verify_access_token(token: str, *, settings: Settings) -> VerifiedPrincipal:
74
+ """Verify a short-lived RSA-signed access token, fail closed on all claims.
75
+
76
+ Static public-key pinning is intentional here; rotating/jwks validation and
77
+ a deployed enterprise IdP must be separately configured and reviewed.
78
+ """
79
+ key = _trusted_public_key(settings)
80
+ if not isinstance(token, str) or not token or len(token) > MAX_TOKEN_LENGTH:
81
+ _fail_invalid()
82
+ try:
83
+ claims = jwt.decode(
84
+ token,
85
+ key,
86
+ algorithms=["RS256"],
87
+ audience=settings.auth_audience,
88
+ issuer=settings.auth_issuer,
89
+ leeway=0,
90
+ options={
91
+ "require": [
92
+ "iss", "aud", "sub", "exp", "iat", "nbf",
93
+ "token_use", "aram_roles",
94
+ ],
95
+ },
96
+ )
97
+ except (jwt.InvalidTokenError, ValueError, TypeError) as exc:
98
+ raise HTTPException(
99
+ status_code=401, detail="Invalid bearer token",
100
+ headers={"WWW-Authenticate": "Bearer"},
101
+ ) from exc
102
+ roles = claims.get("aram_roles")
103
+ exp = claims.get("exp")
104
+ iat = claims.get("iat")
105
+ nbf = claims.get("nbf")
106
+ if (
107
+ claims.get("token_use") != "access"
108
+ or not _is_safe_string(claims.get("sub"), 128)
109
+ or type(exp) is not int or type(iat) is not int or type(nbf) is not int
110
+ or exp <= iat or exp - iat > MAX_LIFETIME_SECONDS
111
+ or nbf > exp
112
+ or not isinstance(roles, list) or not roles
113
+ or any(type(role) is not str or role not in TRUSTED_ROLES for role in roles)
114
+ or len(set(roles)) != len(roles)
115
+ or len(roles) > 1
116
+ ):
117
+ _fail_invalid()
118
+ return VerifiedPrincipal(
119
+ issuer=claims["iss"], subject=claims["sub"],
120
+ roles=tuple(sorted(roles)), expires_at=exp,
121
+ )
122
+
123
+
124
+def require_verified_principal(
125
+ credentials: HTTPAuthorizationCredentials | None = Depends(bearer_scheme),
126
+ settings: Settings = Depends(get_settings),
127
+) -> VerifiedPrincipal:
128
+ """FastAPI dependency; never trust X-User / X-Role headers."""
129
+ # Misconfigured deployment cannot accidentally become authenticated.
130
+ _trusted_public_key(settings)
131
+ if credentials is None or credentials.scheme.lower() != "bearer":
132
+ _fail_invalid()
133
+ return verify_access_token(credentials.credentials, settings=settings)