gt-auth-sdk-python 0.4.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- gt_auth_sdk/__init__.py +25 -0
- gt_auth_sdk/errors.py +73 -0
- gt_auth_sdk/fastapi.py +269 -0
- gt_auth_sdk/mcp.py +274 -0
- gt_auth_sdk/me.py +188 -0
- gt_auth_sdk/principal.py +220 -0
- gt_auth_sdk/py.typed +0 -0
- gt_auth_sdk/session.py +111 -0
- gt_auth_sdk/settings.py +91 -0
- gt_auth_sdk/validator.py +164 -0
- gt_auth_sdk_python-0.4.2.dist-info/METADATA +249 -0
- gt_auth_sdk_python-0.4.2.dist-info/RECORD +13 -0
- gt_auth_sdk_python-0.4.2.dist-info/WHEEL +4 -0
gt_auth_sdk/__init__.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
from gt_auth_sdk.errors import ErrorCode, GtAuthError
|
|
2
|
+
from gt_auth_sdk.mcp import McpAuthenticator, McpAuthSettings
|
|
3
|
+
from gt_auth_sdk.me import CurrentAccess, MeSource
|
|
4
|
+
from gt_auth_sdk.principal import Principal, Role, ScopedRole
|
|
5
|
+
from gt_auth_sdk.session import SessionClient, SessionTokens
|
|
6
|
+
from gt_auth_sdk.settings import GtAuthSettings
|
|
7
|
+
from gt_auth_sdk.validator import Authentication, TokenValidator, resolve_token
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"Authentication",
|
|
11
|
+
"CurrentAccess",
|
|
12
|
+
"ErrorCode",
|
|
13
|
+
"GtAuthError",
|
|
14
|
+
"GtAuthSettings",
|
|
15
|
+
"McpAuthSettings",
|
|
16
|
+
"McpAuthenticator",
|
|
17
|
+
"MeSource",
|
|
18
|
+
"Principal",
|
|
19
|
+
"Role",
|
|
20
|
+
"ScopedRole",
|
|
21
|
+
"SessionClient",
|
|
22
|
+
"SessionTokens",
|
|
23
|
+
"TokenValidator",
|
|
24
|
+
"resolve_token",
|
|
25
|
+
]
|
gt_auth_sdk/errors.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
from enum import StrEnum
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class ErrorCode(StrEnum):
|
|
5
|
+
TOKEN_MISSING = "TOKEN_MISSING"
|
|
6
|
+
TOKEN_EXPIRED = "TOKEN_EXPIRED"
|
|
7
|
+
TOKEN_INVALID = "TOKEN_INVALID"
|
|
8
|
+
SESSION_REJECTED = "SESSION_REJECTED"
|
|
9
|
+
GT_AUTH_UNAVAILABLE = "GT_AUTH_UNAVAILABLE"
|
|
10
|
+
SIGN_IN_REJECTED = "SIGN_IN_REJECTED"
|
|
11
|
+
PERMISSION_DENIED = "PERMISSION_DENIED"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
_DEFAULT_MESSAGES: dict[ErrorCode, str] = {
|
|
15
|
+
ErrorCode.TOKEN_MISSING: "Debes iniciar sesión para continuar.",
|
|
16
|
+
ErrorCode.TOKEN_EXPIRED: "Tu sesión expiró. Vuelve a iniciar sesión.",
|
|
17
|
+
ErrorCode.TOKEN_INVALID: "Tu sesión no es válida. Vuelve a iniciar sesión.",
|
|
18
|
+
ErrorCode.SESSION_REJECTED: "Tu sesión no es válida. Vuelve a iniciar sesión.",
|
|
19
|
+
ErrorCode.GT_AUTH_UNAVAILABLE: (
|
|
20
|
+
"No pudimos validar tus permisos. Intenta de nuevo en unos minutos."
|
|
21
|
+
),
|
|
22
|
+
ErrorCode.SIGN_IN_REJECTED: "No pudimos iniciar tu sesión. Vuelve a intentarlo.",
|
|
23
|
+
ErrorCode.PERMISSION_DENIED: "No tienes permiso para esta acción.",
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class GtAuthError(Exception):
|
|
28
|
+
"""Authentication or authorization failure, as defined by the gt-auth-sdk contract.
|
|
29
|
+
|
|
30
|
+
The contract fixes ``code`` and ``status_code``; ``message`` is only a default that each
|
|
31
|
+
application may replace through its ``error_factory``.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def __init__(
|
|
35
|
+
self,
|
|
36
|
+
code: ErrorCode,
|
|
37
|
+
status_code: int,
|
|
38
|
+
*,
|
|
39
|
+
required_permissions: tuple[str, ...] = (),
|
|
40
|
+
) -> None:
|
|
41
|
+
self.code = code
|
|
42
|
+
self.status_code = status_code
|
|
43
|
+
self.message = _DEFAULT_MESSAGES[code]
|
|
44
|
+
self.required_permissions = required_permissions
|
|
45
|
+
super().__init__(self.message)
|
|
46
|
+
|
|
47
|
+
@classmethod
|
|
48
|
+
def token_missing(cls) -> "GtAuthError":
|
|
49
|
+
return cls(ErrorCode.TOKEN_MISSING, 401)
|
|
50
|
+
|
|
51
|
+
@classmethod
|
|
52
|
+
def token_expired(cls) -> "GtAuthError":
|
|
53
|
+
return cls(ErrorCode.TOKEN_EXPIRED, 401)
|
|
54
|
+
|
|
55
|
+
@classmethod
|
|
56
|
+
def token_invalid(cls) -> "GtAuthError":
|
|
57
|
+
return cls(ErrorCode.TOKEN_INVALID, 401)
|
|
58
|
+
|
|
59
|
+
@classmethod
|
|
60
|
+
def session_rejected(cls, status_code: int) -> "GtAuthError":
|
|
61
|
+
return cls(ErrorCode.SESSION_REJECTED, status_code)
|
|
62
|
+
|
|
63
|
+
@classmethod
|
|
64
|
+
def gt_auth_unavailable(cls) -> "GtAuthError":
|
|
65
|
+
return cls(ErrorCode.GT_AUTH_UNAVAILABLE, 503)
|
|
66
|
+
|
|
67
|
+
@classmethod
|
|
68
|
+
def sign_in_rejected(cls, status_code: int) -> "GtAuthError":
|
|
69
|
+
return cls(ErrorCode.SIGN_IN_REJECTED, status_code)
|
|
70
|
+
|
|
71
|
+
@classmethod
|
|
72
|
+
def permission_denied(cls, required_permissions: tuple[str, ...] = ()) -> "GtAuthError":
|
|
73
|
+
return cls(ErrorCode.PERMISSION_DENIED, 403, required_permissions=required_permissions)
|
gt_auth_sdk/fastapi.py
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
"""FastAPI adapter. Requires the ``fastapi`` extra: ``gt-auth-sdk-python[fastapi]``."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable, Iterable
|
|
4
|
+
from enum import Enum
|
|
5
|
+
from threading import Lock
|
|
6
|
+
|
|
7
|
+
from fastapi import APIRouter, Depends, HTTPException, Request, Response
|
|
8
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
9
|
+
|
|
10
|
+
from gt_auth_sdk.errors import GtAuthError
|
|
11
|
+
from gt_auth_sdk.principal import Principal
|
|
12
|
+
from gt_auth_sdk.session import (
|
|
13
|
+
ACCESS_COOKIE_MAX_AGE_SECONDS,
|
|
14
|
+
REFRESH_COOKIE_MAX_AGE_SECONDS,
|
|
15
|
+
SessionClient,
|
|
16
|
+
SessionTokens,
|
|
17
|
+
)
|
|
18
|
+
from gt_auth_sdk.settings import GtAuthSettings
|
|
19
|
+
from gt_auth_sdk.validator import Authentication, TokenValidator
|
|
20
|
+
|
|
21
|
+
ErrorFactory = Callable[[GtAuthError], Exception]
|
|
22
|
+
OnAuthenticated = Callable[[Request, Authentication], None]
|
|
23
|
+
OnAuthorized = Callable[[Request, Principal], None]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _http_exception(error: GtAuthError) -> Exception:
|
|
27
|
+
return HTTPException(
|
|
28
|
+
status_code=error.status_code,
|
|
29
|
+
detail={"code": error.code.value, "message": error.message},
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class ExchangeRequest(BaseModel):
|
|
34
|
+
model_config = ConfigDict(populate_by_name=True)
|
|
35
|
+
|
|
36
|
+
auth_code: str = Field(alias="authCode")
|
|
37
|
+
state: str
|
|
38
|
+
redirect_url: str = Field(alias="redirectUrl")
|
|
39
|
+
# Clients still send it, but the app name always comes from the settings.
|
|
40
|
+
app_name: str | None = Field(default=None, alias="appName")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class GtAuth:
|
|
44
|
+
"""Authenticates FastAPI requests against gt-auth.
|
|
45
|
+
|
|
46
|
+
``error_factory`` lets each application keep its own error type. ``on_authenticated`` runs
|
|
47
|
+
after a token is accepted and ``on_authorized`` after a permission check passes; they exist
|
|
48
|
+
so request tracking stays in the application instead of inside the SDK.
|
|
49
|
+
|
|
50
|
+
In tests, replace the user with ``app.dependency_overrides[auth.current_user]``: every
|
|
51
|
+
permission guard resolves the user through that dependency.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
def __init__(
|
|
55
|
+
self,
|
|
56
|
+
settings: GtAuthSettings | Callable[[], GtAuthSettings],
|
|
57
|
+
*,
|
|
58
|
+
error_factory: ErrorFactory = _http_exception,
|
|
59
|
+
on_authenticated: OnAuthenticated | None = None,
|
|
60
|
+
on_authorized: OnAuthorized | None = None,
|
|
61
|
+
validator: TokenValidator | None = None,
|
|
62
|
+
session_client: SessionClient | None = None,
|
|
63
|
+
) -> None:
|
|
64
|
+
# A callable is resolved on first use, so an application can create its GtAuth at import
|
|
65
|
+
# time, before its environment is complete: ``GtAuth(GtAuthSettings.from_env)``.
|
|
66
|
+
self._settings = None if callable(settings) else settings
|
|
67
|
+
self._settings_source = settings if callable(settings) else None
|
|
68
|
+
self._validator = validator
|
|
69
|
+
self._error_factory = error_factory
|
|
70
|
+
self._on_authenticated = on_authenticated
|
|
71
|
+
self._on_authorized = on_authorized
|
|
72
|
+
self._session_client = session_client
|
|
73
|
+
self._lock = Lock()
|
|
74
|
+
|
|
75
|
+
@property
|
|
76
|
+
def settings(self) -> GtAuthSettings:
|
|
77
|
+
if self._settings is None:
|
|
78
|
+
with self._lock:
|
|
79
|
+
if self._settings is None:
|
|
80
|
+
assert self._settings_source is not None
|
|
81
|
+
self._settings = self._settings_source()
|
|
82
|
+
return self._settings
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def validator(self) -> TokenValidator:
|
|
86
|
+
if self._validator is None:
|
|
87
|
+
settings = self.settings
|
|
88
|
+
with self._lock:
|
|
89
|
+
# One validator per GtAuth: it owns the gt-auth cache.
|
|
90
|
+
if self._validator is None:
|
|
91
|
+
self._validator = TokenValidator(settings)
|
|
92
|
+
return self._validator
|
|
93
|
+
|
|
94
|
+
def current_user(self, request: Request) -> Principal:
|
|
95
|
+
try:
|
|
96
|
+
authentication = self.validator.authenticate(
|
|
97
|
+
authorization=request.headers.get("authorization"),
|
|
98
|
+
cookie_token=request.cookies.get(self.settings.access_cookie_name),
|
|
99
|
+
)
|
|
100
|
+
except GtAuthError as error:
|
|
101
|
+
raise self._error_factory(error) from error
|
|
102
|
+
|
|
103
|
+
if self._on_authenticated is not None:
|
|
104
|
+
self._on_authenticated(request, authentication)
|
|
105
|
+
return authentication.principal
|
|
106
|
+
|
|
107
|
+
def require_permissions(
|
|
108
|
+
self,
|
|
109
|
+
*permissions: str,
|
|
110
|
+
submodule: str | Iterable[str] | None = None,
|
|
111
|
+
any_submodule_of: str | None = None,
|
|
112
|
+
) -> Callable[..., Principal]:
|
|
113
|
+
"""Dependency that lets the request through if the user holds any of ``permissions``.
|
|
114
|
+
|
|
115
|
+
Without permissions it only requires a valid session.
|
|
116
|
+
"""
|
|
117
|
+
|
|
118
|
+
def dependency(
|
|
119
|
+
request: Request, principal: Principal = Depends(self.current_user)
|
|
120
|
+
) -> Principal:
|
|
121
|
+
if permissions:
|
|
122
|
+
self.ensure_permissions(
|
|
123
|
+
principal, *permissions, submodule=submodule, any_submodule_of=any_submodule_of
|
|
124
|
+
)
|
|
125
|
+
if self._on_authorized is not None:
|
|
126
|
+
self._on_authorized(request, principal)
|
|
127
|
+
return principal
|
|
128
|
+
|
|
129
|
+
return dependency
|
|
130
|
+
|
|
131
|
+
def ensure_permissions(
|
|
132
|
+
self,
|
|
133
|
+
principal: Principal,
|
|
134
|
+
*permissions: str,
|
|
135
|
+
submodule: str | Iterable[str] | None = None,
|
|
136
|
+
any_submodule_of: str | None = None,
|
|
137
|
+
) -> None:
|
|
138
|
+
"""Raises the application's 403 unless the user holds any of ``permissions``.
|
|
139
|
+
|
|
140
|
+
For checks that depend on the request body and cannot be a dependency.
|
|
141
|
+
"""
|
|
142
|
+
required = tuple(_permission_name(permission) for permission in permissions)
|
|
143
|
+
if not principal.can_any(required, submodule=submodule, any_submodule_of=any_submodule_of):
|
|
144
|
+
raise self._error_factory(GtAuthError.permission_denied(required))
|
|
145
|
+
|
|
146
|
+
def ensure_none_of(self, principal: Principal, *permissions: str) -> None:
|
|
147
|
+
"""Raises the application's 403 if the user holds any of ``permissions`` anywhere."""
|
|
148
|
+
forbidden = tuple(_permission_name(permission) for permission in permissions)
|
|
149
|
+
if not principal.has_none_of(forbidden):
|
|
150
|
+
raise self._error_factory(GtAuthError.permission_denied())
|
|
151
|
+
|
|
152
|
+
def session_router(self, session_client: SessionClient | None = None) -> APIRouter:
|
|
153
|
+
"""Routes that keep the gt-auth session in HttpOnly cookies.
|
|
154
|
+
|
|
155
|
+
Mount it under the prefix the frontend calls, e.g. ``/v1/auth``.
|
|
156
|
+
"""
|
|
157
|
+
if session_client is not None:
|
|
158
|
+
self._session_client = session_client
|
|
159
|
+
return session_router(lambda: self)
|
|
160
|
+
|
|
161
|
+
@property
|
|
162
|
+
def session_client(self) -> SessionClient:
|
|
163
|
+
if self._session_client is None:
|
|
164
|
+
self._session_client = SessionClient(self.settings)
|
|
165
|
+
return self._session_client
|
|
166
|
+
|
|
167
|
+
def error(self, error: GtAuthError) -> Exception:
|
|
168
|
+
return self._error_factory(error)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def session_router(get_auth: Callable[[], GtAuth]) -> APIRouter:
|
|
172
|
+
"""Session routes for an application that cannot build its ``GtAuth`` at import time.
|
|
173
|
+
|
|
174
|
+
``get_auth`` runs on every request, so the settings are only read when a route is called.
|
|
175
|
+
"""
|
|
176
|
+
router = APIRouter()
|
|
177
|
+
|
|
178
|
+
@router.post("/callback/exchange")
|
|
179
|
+
def exchange(payload: ExchangeRequest, response: Response) -> dict[str, object]:
|
|
180
|
+
auth = get_auth()
|
|
181
|
+
try:
|
|
182
|
+
tokens = auth.session_client.exchange(
|
|
183
|
+
auth_code=payload.auth_code,
|
|
184
|
+
state=payload.state,
|
|
185
|
+
redirect_url=payload.redirect_url,
|
|
186
|
+
)
|
|
187
|
+
except GtAuthError as error:
|
|
188
|
+
raise auth.error(error) from error
|
|
189
|
+
|
|
190
|
+
_set_session_cookies(response, auth.settings, tokens)
|
|
191
|
+
user = tokens.user
|
|
192
|
+
return {
|
|
193
|
+
"authenticated": True,
|
|
194
|
+
"user": {"id": user.get("id"), "email": user.get("email"), "name": user.get("name")},
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
@router.get("/me")
|
|
198
|
+
def me(request: Request) -> dict[str, object]:
|
|
199
|
+
auth = get_auth()
|
|
200
|
+
try:
|
|
201
|
+
token = request.cookies.get(auth.settings.access_cookie_name)
|
|
202
|
+
if not token:
|
|
203
|
+
raise GtAuthError.token_missing()
|
|
204
|
+
current = auth.validator.current_access(token)
|
|
205
|
+
except GtAuthError as error:
|
|
206
|
+
raise auth.error(error) from error
|
|
207
|
+
# "permissions" stays for the frontends that already read it; gt-auth sends the
|
|
208
|
+
# permissions inside the roles of "user".
|
|
209
|
+
return {"authenticated": True, "user": dict(current.user), "permissions": []}
|
|
210
|
+
|
|
211
|
+
@router.post("/refresh")
|
|
212
|
+
def refresh(request: Request, response: Response) -> dict[str, bool]:
|
|
213
|
+
auth = get_auth()
|
|
214
|
+
try:
|
|
215
|
+
refresh_token = request.cookies.get(auth.settings.refresh_cookie_name)
|
|
216
|
+
if not refresh_token:
|
|
217
|
+
raise GtAuthError.token_missing()
|
|
218
|
+
tokens = auth.session_client.refresh(refresh_token)
|
|
219
|
+
except GtAuthError as error:
|
|
220
|
+
raise auth.error(error) from error
|
|
221
|
+
|
|
222
|
+
_set_session_cookies(response, auth.settings, tokens)
|
|
223
|
+
return {"authenticated": True}
|
|
224
|
+
|
|
225
|
+
@router.post("/logout")
|
|
226
|
+
def logout(request: Request, response: Response) -> dict[str, bool]:
|
|
227
|
+
auth = get_auth()
|
|
228
|
+
settings = auth.settings
|
|
229
|
+
token = request.cookies.get(settings.access_cookie_name)
|
|
230
|
+
if token:
|
|
231
|
+
auth.validator.forget(token)
|
|
232
|
+
for name in (settings.access_cookie_name, settings.refresh_cookie_name):
|
|
233
|
+
response.delete_cookie(
|
|
234
|
+
name,
|
|
235
|
+
path="/",
|
|
236
|
+
domain=settings.cookie_domain,
|
|
237
|
+
secure=settings.cookie_secure,
|
|
238
|
+
httponly=True,
|
|
239
|
+
samesite=settings.cookie_samesite,
|
|
240
|
+
)
|
|
241
|
+
return {"authenticated": False}
|
|
242
|
+
|
|
243
|
+
return router
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _set_session_cookies(
|
|
247
|
+
response: Response, settings: GtAuthSettings, tokens: SessionTokens
|
|
248
|
+
) -> None:
|
|
249
|
+
cookies = [(settings.access_cookie_name, tokens.access_token, ACCESS_COOKIE_MAX_AGE_SECONDS)]
|
|
250
|
+
# Without a rotated refresh token the browser keeps the cookie it already has.
|
|
251
|
+
if tokens.refresh_token is not None:
|
|
252
|
+
cookies.append(
|
|
253
|
+
(settings.refresh_cookie_name, tokens.refresh_token, REFRESH_COOKIE_MAX_AGE_SECONDS)
|
|
254
|
+
)
|
|
255
|
+
for name, value, max_age in cookies:
|
|
256
|
+
response.set_cookie(
|
|
257
|
+
key=name,
|
|
258
|
+
value=value,
|
|
259
|
+
max_age=max_age,
|
|
260
|
+
path="/",
|
|
261
|
+
domain=settings.cookie_domain,
|
|
262
|
+
secure=settings.cookie_secure,
|
|
263
|
+
httponly=True,
|
|
264
|
+
samesite=settings.cookie_samesite,
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _permission_name(permission: str) -> str:
|
|
269
|
+
return str(permission.value) if isinstance(permission, Enum) else str(permission)
|
gt_auth_sdk/mcp.py
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
"""Authentication of MCP clients with the tokens gt-auth issues for MCP servers.
|
|
2
|
+
|
|
3
|
+
An MCP token is a JWT signed with the MCP key, whose audience is the application name. Besides
|
|
4
|
+
verifying it locally, gt-auth is asked whether it is still active (introspection), so a revoked
|
|
5
|
+
token stops working after at most one cache TTL.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import hashlib
|
|
9
|
+
import os
|
|
10
|
+
import time
|
|
11
|
+
from collections.abc import Callable, Mapping
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from threading import Lock
|
|
14
|
+
from typing import Any
|
|
15
|
+
from uuid import UUID
|
|
16
|
+
|
|
17
|
+
import httpx
|
|
18
|
+
import jwt
|
|
19
|
+
|
|
20
|
+
from gt_auth_sdk.errors import GtAuthError
|
|
21
|
+
from gt_auth_sdk.principal import (
|
|
22
|
+
Principal,
|
|
23
|
+
_uuid_or_none,
|
|
24
|
+
roles_from_claims,
|
|
25
|
+
scoped_roles_from_claims,
|
|
26
|
+
)
|
|
27
|
+
from gt_auth_sdk.settings import DEFAULT_REQUEST_TIMEOUT_SECONDS
|
|
28
|
+
|
|
29
|
+
INTROSPECT_PATH = "/api/mcp/tokens/introspect"
|
|
30
|
+
MCP_TOKEN_TYPES = ("personal_access", "oauth_access")
|
|
31
|
+
MCP_SIGNING_ALGORITHM = "HS256"
|
|
32
|
+
DEFAULT_INTROSPECTION_CACHE_TTL_SECONDS = 60.0
|
|
33
|
+
REJECTIONS = frozenset({401, 403})
|
|
34
|
+
MAX_CACHE_ENTRIES = 1000
|
|
35
|
+
USER_TYPES = ("internal", "external")
|
|
36
|
+
|
|
37
|
+
Clock = Callable[[], float]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True)
|
|
41
|
+
class McpAuthSettings:
|
|
42
|
+
base_url: str
|
|
43
|
+
signing_key: str
|
|
44
|
+
# The audience gt-auth puts in the MCP tokens of this application.
|
|
45
|
+
app_name: str
|
|
46
|
+
introspection_cache_ttl_seconds: float = DEFAULT_INTROSPECTION_CACHE_TTL_SECONDS
|
|
47
|
+
request_timeout_seconds: float = DEFAULT_REQUEST_TIMEOUT_SECONDS
|
|
48
|
+
|
|
49
|
+
def __post_init__(self) -> None:
|
|
50
|
+
if not self.signing_key:
|
|
51
|
+
raise ValueError("signing_key is required (MCP_AUTH_SIGNING_KEY)")
|
|
52
|
+
if not self.app_name:
|
|
53
|
+
raise ValueError("app_name is required (MCP_AUTH_APP_NAME)")
|
|
54
|
+
|
|
55
|
+
@classmethod
|
|
56
|
+
def from_env(cls, env: Mapping[str, str] | None = None) -> "McpAuthSettings":
|
|
57
|
+
source = os.environ if env is None else env
|
|
58
|
+
ttl_ms = source.get("MCP_AUTH_INTROSPECTION_CACHE_TTL_MS")
|
|
59
|
+
return cls(
|
|
60
|
+
base_url=source.get("GT_AUTH_BASE_URL") or source.get("AUTH_BASE_URL") or "",
|
|
61
|
+
signing_key=source.get("MCP_AUTH_SIGNING_KEY") or "",
|
|
62
|
+
app_name=source.get("MCP_AUTH_APP_NAME") or "",
|
|
63
|
+
introspection_cache_ttl_seconds=(
|
|
64
|
+
float(ttl_ms) / 1000 if ttl_ms else DEFAULT_INTROSPECTION_CACHE_TTL_SECONDS
|
|
65
|
+
),
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@dataclass(frozen=True)
|
|
70
|
+
class _CacheEntry:
|
|
71
|
+
introspection: Mapping[str, Any]
|
|
72
|
+
expires_at: float
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class McpAuthenticator:
|
|
76
|
+
"""Turns the ``Authorization`` header of an MCP request into a ``Principal``.
|
|
77
|
+
|
|
78
|
+
``authenticate`` and ``authenticate_async`` apply the same rules and share one cache; servers
|
|
79
|
+
pick the one that matches how they run.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
def __init__(
|
|
83
|
+
self,
|
|
84
|
+
settings: McpAuthSettings,
|
|
85
|
+
*,
|
|
86
|
+
transport: httpx.BaseTransport | None = None,
|
|
87
|
+
async_transport: httpx.AsyncBaseTransport | None = None,
|
|
88
|
+
clock: Clock = time.time,
|
|
89
|
+
) -> None:
|
|
90
|
+
self._settings = settings
|
|
91
|
+
self._transport = transport
|
|
92
|
+
self._async_transport = async_transport
|
|
93
|
+
self._clock = clock
|
|
94
|
+
self._client: httpx.Client | None = None
|
|
95
|
+
self._async_client: httpx.AsyncClient | None = None
|
|
96
|
+
self._entries: dict[str, _CacheEntry] = {}
|
|
97
|
+
self._lock = Lock()
|
|
98
|
+
|
|
99
|
+
def authenticate(self, authorization: str | None) -> Principal:
|
|
100
|
+
token = bearer_token(authorization)
|
|
101
|
+
claims = self._verified_claims(token)
|
|
102
|
+
introspection = self._cached(token)
|
|
103
|
+
if introspection is None:
|
|
104
|
+
try:
|
|
105
|
+
response = self._http_client().post(INTROSPECT_PATH, headers=_bearer(token))
|
|
106
|
+
except httpx.HTTPError as error:
|
|
107
|
+
raise GtAuthError.gt_auth_unavailable() from error
|
|
108
|
+
introspection = self._accepted(token, claims, response)
|
|
109
|
+
return _build_principal(claims, introspection, self._settings.app_name)
|
|
110
|
+
|
|
111
|
+
async def authenticate_async(self, authorization: str | None) -> Principal:
|
|
112
|
+
token = bearer_token(authorization)
|
|
113
|
+
claims = self._verified_claims(token)
|
|
114
|
+
introspection = self._cached(token)
|
|
115
|
+
if introspection is None:
|
|
116
|
+
try:
|
|
117
|
+
response = await self._http_async_client().post(
|
|
118
|
+
INTROSPECT_PATH, headers=_bearer(token)
|
|
119
|
+
)
|
|
120
|
+
except httpx.HTTPError as error:
|
|
121
|
+
raise GtAuthError.gt_auth_unavailable() from error
|
|
122
|
+
introspection = self._accepted(token, claims, response)
|
|
123
|
+
return _build_principal(claims, introspection, self._settings.app_name)
|
|
124
|
+
|
|
125
|
+
def _verified_claims(self, token: str) -> dict[str, Any]:
|
|
126
|
+
try:
|
|
127
|
+
claims = jwt.decode(
|
|
128
|
+
token,
|
|
129
|
+
key=self._settings.signing_key,
|
|
130
|
+
algorithms=[MCP_SIGNING_ALGORITHM],
|
|
131
|
+
audience=self._settings.app_name,
|
|
132
|
+
options={"require": ["sub", "name", "email", "aud", "exp"]},
|
|
133
|
+
)
|
|
134
|
+
except jwt.ExpiredSignatureError as error:
|
|
135
|
+
raise GtAuthError.token_expired() from error
|
|
136
|
+
except jwt.InvalidTokenError as error:
|
|
137
|
+
raise GtAuthError.token_invalid() from error
|
|
138
|
+
|
|
139
|
+
if claims.get("type") not in MCP_TOKEN_TYPES or not isinstance(
|
|
140
|
+
claims.get("userRoles"), list
|
|
141
|
+
):
|
|
142
|
+
raise GtAuthError.token_invalid()
|
|
143
|
+
if _user_id(claims) is None:
|
|
144
|
+
raise GtAuthError.token_invalid()
|
|
145
|
+
return claims
|
|
146
|
+
|
|
147
|
+
def _cached(self, token: str) -> Mapping[str, Any] | None:
|
|
148
|
+
key = _cache_key(token)
|
|
149
|
+
with self._lock:
|
|
150
|
+
entry = self._entries.get(key)
|
|
151
|
+
if entry is None:
|
|
152
|
+
return None
|
|
153
|
+
if entry.expires_at <= self._clock():
|
|
154
|
+
del self._entries[key]
|
|
155
|
+
return None
|
|
156
|
+
return entry.introspection
|
|
157
|
+
|
|
158
|
+
def _accepted(
|
|
159
|
+
self, token: str, claims: Mapping[str, Any], response: httpx.Response
|
|
160
|
+
) -> Mapping[str, Any]:
|
|
161
|
+
"""The introspection body, only if it explicitly says the token is active."""
|
|
162
|
+
if response.status_code in REJECTIONS:
|
|
163
|
+
raise GtAuthError.session_rejected(response.status_code)
|
|
164
|
+
if not response.is_success:
|
|
165
|
+
raise GtAuthError.gt_auth_unavailable()
|
|
166
|
+
|
|
167
|
+
try:
|
|
168
|
+
body = response.json()
|
|
169
|
+
except ValueError as error:
|
|
170
|
+
raise GtAuthError.gt_auth_unavailable() from error
|
|
171
|
+
if not isinstance(body, dict) or not isinstance(body.get("active"), bool):
|
|
172
|
+
# An answer that does not say whether the token is active proves nothing.
|
|
173
|
+
raise GtAuthError.gt_auth_unavailable()
|
|
174
|
+
if body["active"] is not True or body.get("revoked") is True:
|
|
175
|
+
raise GtAuthError.session_rejected(401)
|
|
176
|
+
|
|
177
|
+
self._remember(token, body, claims["exp"])
|
|
178
|
+
return body
|
|
179
|
+
|
|
180
|
+
def _remember(self, token: str, introspection: Mapping[str, Any], token_expiry: float) -> None:
|
|
181
|
+
now = self._clock()
|
|
182
|
+
ttl = max(self._settings.introspection_cache_ttl_seconds, 0.0)
|
|
183
|
+
expires_at = min(now + ttl, float(token_expiry))
|
|
184
|
+
if expires_at <= now:
|
|
185
|
+
return
|
|
186
|
+
with self._lock:
|
|
187
|
+
self._entries = {k: e for k, e in self._entries.items() if e.expires_at > now}
|
|
188
|
+
if len(self._entries) >= MAX_CACHE_ENTRIES:
|
|
189
|
+
del self._entries[next(iter(self._entries))]
|
|
190
|
+
self._entries[_cache_key(token)] = _CacheEntry(introspection, expires_at)
|
|
191
|
+
|
|
192
|
+
# Clients are created on first use so importing the application never opens a connection pool.
|
|
193
|
+
def _http_client(self) -> httpx.Client:
|
|
194
|
+
if not self._settings.base_url:
|
|
195
|
+
raise httpx.UnsupportedProtocol("GT_AUTH_BASE_URL is not configured")
|
|
196
|
+
if self._client is None:
|
|
197
|
+
self._client = httpx.Client(
|
|
198
|
+
base_url=self._settings.base_url.rstrip("/"),
|
|
199
|
+
timeout=self._settings.request_timeout_seconds,
|
|
200
|
+
transport=self._transport,
|
|
201
|
+
)
|
|
202
|
+
return self._client
|
|
203
|
+
|
|
204
|
+
def _http_async_client(self) -> httpx.AsyncClient:
|
|
205
|
+
if not self._settings.base_url:
|
|
206
|
+
raise httpx.UnsupportedProtocol("GT_AUTH_BASE_URL is not configured")
|
|
207
|
+
if self._async_client is None:
|
|
208
|
+
self._async_client = httpx.AsyncClient(
|
|
209
|
+
base_url=self._settings.base_url.rstrip("/"),
|
|
210
|
+
timeout=self._settings.request_timeout_seconds,
|
|
211
|
+
transport=self._async_transport,
|
|
212
|
+
)
|
|
213
|
+
return self._async_client
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def bearer_token(authorization: str | None) -> str:
|
|
217
|
+
scheme, _, token = (authorization or "").partition(" ")
|
|
218
|
+
if scheme.lower() != "bearer" or not token.strip():
|
|
219
|
+
raise GtAuthError.token_missing()
|
|
220
|
+
return token.strip()
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _build_principal(
|
|
224
|
+
claims: Mapping[str, Any], introspection: Mapping[str, Any], audience: str
|
|
225
|
+
) -> Principal:
|
|
226
|
+
access = _current_access(claims, introspection)
|
|
227
|
+
user_type = claims.get("userType")
|
|
228
|
+
try:
|
|
229
|
+
return Principal(
|
|
230
|
+
id=UUID(str(claims["sub"])),
|
|
231
|
+
name=str(claims["name"]),
|
|
232
|
+
email=str(claims["email"]),
|
|
233
|
+
user_type=user_type if user_type in USER_TYPES else None,
|
|
234
|
+
audience=audience,
|
|
235
|
+
business_line_id=_uuid_or_none(access.get("businessLineId") or None),
|
|
236
|
+
roles=roles_from_claims(access.get("userRoles")),
|
|
237
|
+
scoped_roles=scoped_roles_from_claims(access.get("scopedRoles")),
|
|
238
|
+
)
|
|
239
|
+
except ValueError as error:
|
|
240
|
+
raise GtAuthError.token_invalid() from error
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _current_access(
|
|
244
|
+
claims: Mapping[str, Any], introspection: Mapping[str, Any]
|
|
245
|
+
) -> Mapping[str, Any]:
|
|
246
|
+
"""Roles and business line: what gt-auth answered when it sent them, else the token's."""
|
|
247
|
+
fresh = introspection.get("claims")
|
|
248
|
+
if not isinstance(fresh, dict):
|
|
249
|
+
return claims
|
|
250
|
+
|
|
251
|
+
access = dict(claims)
|
|
252
|
+
# Both kinds of role travel together: taking one from each source could mix two moments.
|
|
253
|
+
if any(isinstance(fresh.get(name), list) for name in ("userRoles", "scopedRoles")):
|
|
254
|
+
access["userRoles"] = fresh.get("userRoles") or []
|
|
255
|
+
access["scopedRoles"] = fresh.get("scopedRoles") or []
|
|
256
|
+
if "businessLineId" in fresh:
|
|
257
|
+
access["businessLineId"] = fresh["businessLineId"]
|
|
258
|
+
return access
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _user_id(claims: Mapping[str, Any]) -> UUID | None:
|
|
262
|
+
try:
|
|
263
|
+
return UUID(str(claims.get("sub")))
|
|
264
|
+
except ValueError:
|
|
265
|
+
return None
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _bearer(token: str) -> dict[str, str]:
|
|
269
|
+
return {"Authorization": f"Bearer {token}"}
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _cache_key(token: str) -> str:
|
|
273
|
+
# Never the raw token: a memory dump must not hand out sessions.
|
|
274
|
+
return hashlib.sha256(token.encode()).hexdigest()
|