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/validator.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
from collections.abc import Mapping
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
from typing import Any
|
|
4
|
+
from uuid import UUID
|
|
5
|
+
|
|
6
|
+
import jwt
|
|
7
|
+
|
|
8
|
+
from gt_auth_sdk.errors import GtAuthError
|
|
9
|
+
from gt_auth_sdk.me import CurrentAccess, MeSource, unverified_claims
|
|
10
|
+
from gt_auth_sdk.principal import Principal, roles_from_claims, scoped_roles_from_claims
|
|
11
|
+
from gt_auth_sdk.settings import GtAuthSettings
|
|
12
|
+
|
|
13
|
+
ACCESS_TOKEN_TYPE = "access"
|
|
14
|
+
ACCESS_TOKEN_PROFILE = "gt-auth-access"
|
|
15
|
+
THIN_TOKEN_FORMAT = "thin"
|
|
16
|
+
USER_TYPES = ("internal", "external")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class Authentication:
|
|
21
|
+
principal: Principal
|
|
22
|
+
token: str
|
|
23
|
+
# Verified in local mode. In remote mode they are read without verification, after gt-auth
|
|
24
|
+
# accepted the token.
|
|
25
|
+
claims: Mapping[str, Any]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class TokenValidator:
|
|
29
|
+
"""Turns the credentials of a request into a ``Principal``, without any web framework."""
|
|
30
|
+
|
|
31
|
+
def __init__(self, settings: GtAuthSettings, *, me_source: MeSource | None = None) -> None:
|
|
32
|
+
self._settings = settings
|
|
33
|
+
self._me_source = me_source or MeSource(settings)
|
|
34
|
+
|
|
35
|
+
def authenticate(
|
|
36
|
+
self, *, authorization: str | None = None, cookie_token: str | None = None
|
|
37
|
+
) -> Authentication:
|
|
38
|
+
token = resolve_token(authorization, cookie_token)
|
|
39
|
+
if self._settings.validation == "remote":
|
|
40
|
+
return self._authenticate_remotely(token)
|
|
41
|
+
return self._authenticate_locally(token)
|
|
42
|
+
|
|
43
|
+
def current_access(self, token: str) -> CurrentAccess:
|
|
44
|
+
"""What gt-auth knows about a token right now, through the shared cache."""
|
|
45
|
+
return self._me_source.current_access(token)
|
|
46
|
+
|
|
47
|
+
def forget(self, token: str) -> None:
|
|
48
|
+
"""Drops the cached access of a token. Call it on logout."""
|
|
49
|
+
self._me_source.forget(token)
|
|
50
|
+
|
|
51
|
+
def _authenticate_locally(self, token: str) -> Authentication:
|
|
52
|
+
claims = self._verified_claims(token)
|
|
53
|
+
self._require_expected_audience(claims["aud"])
|
|
54
|
+
|
|
55
|
+
data_user = _mapping(claims.get("dataUser"))
|
|
56
|
+
access = data_user
|
|
57
|
+
if data_user.get("tokenFormat") == THIN_TOKEN_FORMAT:
|
|
58
|
+
access = self._me_source.current_access(token).user
|
|
59
|
+
|
|
60
|
+
principal = _build_principal(
|
|
61
|
+
claims=claims, identity=data_user, access=access, audience=claims["aud"]
|
|
62
|
+
)
|
|
63
|
+
return Authentication(principal=principal, token=token, claims=claims)
|
|
64
|
+
|
|
65
|
+
def _authenticate_remotely(self, token: str) -> Authentication:
|
|
66
|
+
current = self._me_source.current_access(token)
|
|
67
|
+
claims = unverified_claims(token)
|
|
68
|
+
audience = current.app_name or _string(claims.get("aud"))
|
|
69
|
+
self._require_expected_audience(audience)
|
|
70
|
+
|
|
71
|
+
principal = _build_principal(
|
|
72
|
+
claims=claims, identity=current.user, access=current.user, audience=audience
|
|
73
|
+
)
|
|
74
|
+
return Authentication(principal=principal, token=token, claims=claims)
|
|
75
|
+
|
|
76
|
+
def _verified_claims(self, token: str) -> dict[str, Any]:
|
|
77
|
+
try:
|
|
78
|
+
claims = jwt.decode(
|
|
79
|
+
token,
|
|
80
|
+
key=self._settings.secret_key,
|
|
81
|
+
algorithms=[self._settings.algorithm],
|
|
82
|
+
options={"verify_aud": False, "require": ["exp"]},
|
|
83
|
+
)
|
|
84
|
+
except jwt.ExpiredSignatureError as error:
|
|
85
|
+
raise GtAuthError.token_expired() from error
|
|
86
|
+
except jwt.InvalidTokenError as error:
|
|
87
|
+
raise GtAuthError.token_invalid() from error
|
|
88
|
+
|
|
89
|
+
is_access_token = claims.get("type") == ACCESS_TOKEN_TYPE and claims.get("typ") in (
|
|
90
|
+
None, # tokens issued before the V2 contract carry no profile
|
|
91
|
+
ACCESS_TOKEN_PROFILE,
|
|
92
|
+
)
|
|
93
|
+
if not is_access_token or not _string(claims.get("sub")) or not _string(claims.get("aud")):
|
|
94
|
+
raise GtAuthError.token_invalid()
|
|
95
|
+
return claims
|
|
96
|
+
|
|
97
|
+
def _require_expected_audience(self, audience: str | None) -> None:
|
|
98
|
+
expected = self._settings.expected_audiences
|
|
99
|
+
if expected and audience not in expected:
|
|
100
|
+
raise GtAuthError.token_invalid()
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def resolve_token(authorization: str | None, cookie_token: str | None) -> str:
|
|
104
|
+
bearer = _bearer_token(authorization)
|
|
105
|
+
if bearer:
|
|
106
|
+
return bearer
|
|
107
|
+
if cookie_token:
|
|
108
|
+
return cookie_token
|
|
109
|
+
raise GtAuthError.token_missing()
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _bearer_token(authorization: str | None) -> str | None:
|
|
113
|
+
if not authorization:
|
|
114
|
+
return None
|
|
115
|
+
parts = authorization.split()
|
|
116
|
+
if len(parts) != 2 or parts[0].lower() != "bearer":
|
|
117
|
+
return None
|
|
118
|
+
return parts[1]
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _build_principal(
|
|
122
|
+
*,
|
|
123
|
+
claims: Mapping[str, Any],
|
|
124
|
+
identity: Mapping[str, Any],
|
|
125
|
+
access: Mapping[str, Any],
|
|
126
|
+
audience: str | None,
|
|
127
|
+
) -> Principal:
|
|
128
|
+
user_id = _uuid(identity.get("id") or claims.get("sub"))
|
|
129
|
+
if user_id is None:
|
|
130
|
+
raise GtAuthError.token_invalid()
|
|
131
|
+
|
|
132
|
+
user_type = claims.get("userType")
|
|
133
|
+
return Principal(
|
|
134
|
+
id=user_id,
|
|
135
|
+
name=_string(identity.get("name")) or _string(claims.get("name")),
|
|
136
|
+
email=_string(identity.get("email")) or _string(claims.get("email")),
|
|
137
|
+
user_type=user_type if user_type in USER_TYPES else None,
|
|
138
|
+
audience=audience,
|
|
139
|
+
business_line_id=_uuid(identity.get("businessLineId")),
|
|
140
|
+
organization_id=_uuid(identity.get("organizationId")),
|
|
141
|
+
roles=roles_from_claims(access.get("userRoles")),
|
|
142
|
+
scoped_roles=scoped_roles_from_claims(access.get("scopedRoles")),
|
|
143
|
+
data_user=identity,
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _uuid(value: object) -> UUID | None:
|
|
148
|
+
"""gt-auth ids are UUIDs. A missing one is ``None``; any other value makes the token invalid."""
|
|
149
|
+
if value is None or value == "":
|
|
150
|
+
return None
|
|
151
|
+
if not isinstance(value, str):
|
|
152
|
+
raise GtAuthError.token_invalid()
|
|
153
|
+
try:
|
|
154
|
+
return UUID(value)
|
|
155
|
+
except ValueError as error:
|
|
156
|
+
raise GtAuthError.token_invalid() from error
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _mapping(value: object) -> Mapping[str, Any]:
|
|
160
|
+
return value if isinstance(value, dict) else {}
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _string(value: object) -> str | None:
|
|
164
|
+
return value if isinstance(value, str) and value else None
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: gt-auth-sdk-python
|
|
3
|
+
Version: 0.4.2
|
|
4
|
+
Summary: Validate gt-auth sessions and permissions in Python backends
|
|
5
|
+
Author: Grant Thornton Chile
|
|
6
|
+
Classifier: Framework :: FastAPI
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
11
|
+
Classifier: Typing :: Typed
|
|
12
|
+
Requires-Python: >=3.11
|
|
13
|
+
Requires-Dist: httpx>=0.28
|
|
14
|
+
Requires-Dist: pyjwt>=2.10
|
|
15
|
+
Provides-Extra: fastapi
|
|
16
|
+
Requires-Dist: fastapi>=0.115; extra == 'fastapi'
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+
# gt-auth-sdk-python
|
|
20
|
+
|
|
21
|
+
Valida sesiones y permisos de gt-auth en backends Python. Cumple el contrato de `../contract/README.md`, el mismo que `gt-auth-sdk-node`.
|
|
22
|
+
|
|
23
|
+
Estado: v0.4.1. Incluye validación, roles, permisos, el adaptador de FastAPI, las rutas de sesión y la autenticación de servidores MCP.
|
|
24
|
+
|
|
25
|
+
## Instalación
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
uv add "gt-auth-sdk-python[fastapi]"
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
El extra `fastapi` solo hace falta para `gt_auth_sdk.fastapi`. El núcleo depende de `httpx` y `pyjwt`.
|
|
32
|
+
|
|
33
|
+
## Uso con FastAPI
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
from fastapi import Depends, FastAPI
|
|
37
|
+
|
|
38
|
+
from gt_auth_sdk import GtAuthSettings, Principal
|
|
39
|
+
from gt_auth_sdk.fastapi import GtAuth
|
|
40
|
+
|
|
41
|
+
auth = GtAuth(GtAuthSettings.from_env())
|
|
42
|
+
app = FastAPI()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@app.get("/sociedades")
|
|
46
|
+
def listar(user: Principal = Depends(auth.current_user)): ...
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@app.post("/bots/run", dependencies=[Depends(auth.require_permissions("bot.execute"))])
|
|
50
|
+
def ejecutar(): ...
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@app.post("/f22")
|
|
54
|
+
def declarar(
|
|
55
|
+
user: Principal = Depends(
|
|
56
|
+
auth.require_permissions(
|
|
57
|
+
"cumplimiento_tributario.write", submodule="cumplimiento_tributario.f22"
|
|
58
|
+
)
|
|
59
|
+
),
|
|
60
|
+
): ...
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
`require_permissions` deja pasar si el usuario tiene alguno de los permisos. Acepta strings o miembros de un `StrEnum`. Sin permisos, solo exige una sesión válida.
|
|
64
|
+
|
|
65
|
+
Si la app se importa antes de tener su configuración (por ejemplo, en tests), se pasa la función en vez del resultado y se resuelve en la primera petición:
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
auth = GtAuth(GtAuthSettings.from_env)
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Para chequeos que dependen del cuerpo de la petición y no pueden ser una dependencia:
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
auth.ensure_permissions(user, "form.update") # lanza el 403 de la app
|
|
75
|
+
auth.ensure_none_of(user, "admin.delete")
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Configuración
|
|
79
|
+
|
|
80
|
+
`GtAuthSettings.from_env()` lee:
|
|
81
|
+
|
|
82
|
+
| Variable | Uso |
|
|
83
|
+
|---|---|
|
|
84
|
+
| `GT_AUTH_BASE_URL` (o `AUTH_BASE_URL`) | URL de gt-auth. Obligatoria en modo remoto y para las rutas de sesión; en modo local, sin ella los tokens «thin» responden 503 |
|
|
85
|
+
| `SECRET_KEY` | Clave compartida; obligatoria en modo local |
|
|
86
|
+
| `ALGORITHM` | Por defecto `HS256` |
|
|
87
|
+
| `GT_AUTH_EXPECTED_AUDIENCES` | Nombres de app aceptados, separados por coma. Vacío: no se valida la audiencia |
|
|
88
|
+
| `GT_AUTH_CACHE_TTL_MS` | TTL de la caché de `/api/auth/me`. Por defecto `60000`; `0` la desactiva |
|
|
89
|
+
| `GT_AUTH_INTERNAL_KEY` | Clave interna para hablar con gt-auth; obligatoria para las rutas de sesión |
|
|
90
|
+
| `GT_AUTH_APP_NAME` | Nombre de la app en gt-auth; obligatorio para las rutas de sesión |
|
|
91
|
+
| `APP_COOKIE_SECURE` | `false` desactiva `Secure`. Sin la variable, las cookies son `Secure` |
|
|
92
|
+
| `APP_COOKIE_DOMAIN` | Dominio de las cookies; opcional |
|
|
93
|
+
| `APP_COOKIE_SAMESITE` | `lax` (por defecto), `strict` o `none`. Con `none`, `Secure` se fuerza |
|
|
94
|
+
|
|
95
|
+
También se puede construir a mano: `GtAuthSettings(base_url=..., secret_key=...)`.
|
|
96
|
+
|
|
97
|
+
Modo de validación:
|
|
98
|
+
|
|
99
|
+
- `local` (por defecto): verifica la firma con `SECRET_KEY` y solo consulta a gt-auth para tokens «thin».
|
|
100
|
+
- `remote`: no necesita la clave; consulta a gt-auth por cada token, con caché. Se elige con `GtAuthSettings.from_env(validation="remote")`.
|
|
101
|
+
|
|
102
|
+
## Integración con la aplicación
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
auth = GtAuth(
|
|
106
|
+
settings,
|
|
107
|
+
error_factory=to_app_error,
|
|
108
|
+
on_authenticated=remember_token,
|
|
109
|
+
on_authorized=authorize_tracking,
|
|
110
|
+
)
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
- **`error_factory(error)`** recibe un `GtAuthError` y devuelve la excepción que la aplicación quiere lanzar. El error trae `code`, `status_code`, `message` y, en un 403, `required_permissions`. Sin él se lanza un `HTTPException` con `{"code", "message"}`.
|
|
114
|
+
- **`on_authenticated(request, authentication)`** corre cuando el token se acepta. `authentication` trae `principal`, `token` y `claims`.
|
|
115
|
+
- **`on_authorized(request, principal)`** corre cuando un guard deja pasar la petición.
|
|
116
|
+
|
|
117
|
+
Los dos últimos existen para que el registro de actividad (GT Tracker) quede en la aplicación.
|
|
118
|
+
|
|
119
|
+
## Rutas de sesión
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
app.include_router(auth.session_router(), prefix="/v1/auth")
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
| Ruta | Qué hace | Respuesta |
|
|
126
|
+
|---|---|---|
|
|
127
|
+
| `POST /callback/exchange` | Cambia el código de gt-auth por tokens y los guarda en cookies. Cuerpo: `{authCode, state, redirectUrl}` | `{authenticated: true, user: {id, email, name}}` |
|
|
128
|
+
| `GET /me` | Devuelve el usuario actual según gt-auth, con la misma caché de la validación | `{authenticated: true, user, permissions: []}` |
|
|
129
|
+
| `POST /refresh` | Renueva el access token con la cookie de refresco | `{authenticated: true}` |
|
|
130
|
+
| `POST /logout` | Borra las dos cookies y la entrada de caché del token | `{authenticated: false}` |
|
|
131
|
+
|
|
132
|
+
Las cookies son `app_access_token` (1 hora) y `app_refresh_token` (7 días), `HttpOnly` y con `Path=/`.
|
|
133
|
+
|
|
134
|
+
- El nombre de la app siempre sale de la configuración; el `appName` que mande el navegador se ignora.
|
|
135
|
+
- Si gt-auth no devuelve un refresh token nuevo, la cookie de refresco no se toca.
|
|
136
|
+
- Los errores pasan por `error_factory`. Hay un código más: `SIGN_IN_REJECTED`, cuando gt-auth rechaza el intercambio, con el estado que devolvió gt-auth.
|
|
137
|
+
|
|
138
|
+
Si la aplicación no tiene la configuración al importarse (por ejemplo, en tests), el router se puede crear sin ella. `get_auth` se llama en cada petición:
|
|
139
|
+
|
|
140
|
+
```python
|
|
141
|
+
from gt_auth_sdk.fastapi import session_router
|
|
142
|
+
|
|
143
|
+
router = session_router(get_auth)
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
Sin FastAPI, `SessionClient(settings)` ofrece `exchange(...)` y `refresh(...)`.
|
|
147
|
+
|
|
148
|
+
`GtAuth(settings, session_client=SessionClient(settings, transport=...))` fija el cliente de las rutas de sesión, igual que `validator=` fija el de la validación. Sirve para simular gt-auth en los tests de la aplicación con un `httpx.MockTransport`.
|
|
149
|
+
|
|
150
|
+
## `Principal`
|
|
151
|
+
|
|
152
|
+
| Atributo | Contenido |
|
|
153
|
+
|---|---|
|
|
154
|
+
| `id`, `name`, `email` | Identidad. `id` es un `UUID` |
|
|
155
|
+
| `user_type` | `"internal"`, `"external"` o `None` en tokens antiguos |
|
|
156
|
+
| `audience` | Nombre de la app para la que se emitió el token |
|
|
157
|
+
| `business_line_id`, `organization_id` | `UUID` o `None` |
|
|
158
|
+
| `roles`, `scoped_roles` | Roles de módulo completo y roles con alcance |
|
|
159
|
+
| `permissions` | Permisos de módulo completo, ordenados |
|
|
160
|
+
| `data_user` | El `dataUser` completo del token, para campos que el contrato no fija |
|
|
161
|
+
|
|
162
|
+
Consultas:
|
|
163
|
+
|
|
164
|
+
```python
|
|
165
|
+
user.can("form.view")
|
|
166
|
+
user.can("cumplimiento_tributario.write", submodule="cumplimiento_tributario.f22")
|
|
167
|
+
user.can("cumplimiento_tributario.write", any_submodule_of="cumplimiento_tributario")
|
|
168
|
+
user.can_any(["form.view", "form.update"])
|
|
169
|
+
user.has_none_of(["admin.delete"])
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
Sin `submodule`, los permisos con alcance no cuentan. `submodule` también acepta una lista: basta con que el rol cubra uno.
|
|
173
|
+
|
|
174
|
+
Para llevar el usuario a un job en segundo plano:
|
|
175
|
+
|
|
176
|
+
```python
|
|
177
|
+
payload = {"usuario": user.to_dict()}
|
|
178
|
+
user = Principal.from_dict(payload["usuario"])
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
`to_dict` no incluye `data_user`. `from_dict` también lee los payloads que los backends encolaron antes de adoptar el SDK.
|
|
182
|
+
|
|
183
|
+
## Sin FastAPI
|
|
184
|
+
|
|
185
|
+
```python
|
|
186
|
+
from gt_auth_sdk import GtAuthError, GtAuthSettings, TokenValidator
|
|
187
|
+
|
|
188
|
+
validator = TokenValidator(GtAuthSettings.from_env())
|
|
189
|
+
|
|
190
|
+
try:
|
|
191
|
+
authentication = validator.authenticate(authorization=header, cookie_token=cookie)
|
|
192
|
+
except GtAuthError as error:
|
|
193
|
+
... # error.code, error.status_code
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
`validator.forget(token)` borra la entrada de caché de un token; se llama al cerrar sesión.
|
|
197
|
+
|
|
198
|
+
## Servidores MCP
|
|
199
|
+
|
|
200
|
+
Los tokens MCP (personales y OAuth) se firman con otra clave y llevan como audiencia el nombre de la aplicación. `McpAuthenticator` verifica el token y consulta a gt-auth si sigue vigente:
|
|
201
|
+
|
|
202
|
+
```python
|
|
203
|
+
from gt_auth_sdk import GtAuthError, McpAuthenticator, McpAuthSettings
|
|
204
|
+
|
|
205
|
+
authenticator = McpAuthenticator(McpAuthSettings.from_env())
|
|
206
|
+
|
|
207
|
+
try:
|
|
208
|
+
principal = authenticator.authenticate(request.headers.get("authorization"))
|
|
209
|
+
except GtAuthError as error:
|
|
210
|
+
... # error.status_code, error.code, error.message
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
- `authenticate_async()` aplica las mismas reglas para servidores asíncronos; las dos variantes comparten la caché.
|
|
214
|
+
- Devuelve el mismo `Principal` que la API, así que los permisos se revisan igual (`principal.can(...)`, `auth.ensure_permissions(...)`).
|
|
215
|
+
- La respuesta de gt-auth se guarda `MCP_AUTH_INTROSPECTION_CACHE_TTL_MS` (60 s por defecto): un token revocado deja de servir a más tardar en ese plazo. Los rechazos no se guardan.
|
|
216
|
+
- Solo una respuesta JSON con `active: true` valida el token. Si gt-auth no responde o responde otra cosa, el resultado es 503 `GT_AUTH_UNAVAILABLE`.
|
|
217
|
+
|
|
218
|
+
| Variable | Uso |
|
|
219
|
+
|---|---|
|
|
220
|
+
| `GT_AUTH_BASE_URL` | URL de gt-auth |
|
|
221
|
+
| `MCP_AUTH_SIGNING_KEY` | Clave con que gt-auth firma los tokens MCP |
|
|
222
|
+
| `MCP_AUTH_APP_NAME` | Nombre de la aplicación en gt-auth (audiencia del token) |
|
|
223
|
+
| `MCP_AUTH_INTROSPECTION_CACHE_TTL_MS` | Duración de la caché, en milisegundos |
|
|
224
|
+
|
|
225
|
+
## Tests
|
|
226
|
+
|
|
227
|
+
En FastAPI, el usuario se reemplaza con `dependency_overrides`; los guards lo resuelven por esa misma dependencia:
|
|
228
|
+
|
|
229
|
+
```python
|
|
230
|
+
from uuid import uuid4
|
|
231
|
+
|
|
232
|
+
app.dependency_overrides[auth.current_user] = lambda: Principal(id=uuid4())
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
## Desarrollo
|
|
236
|
+
|
|
237
|
+
```bash
|
|
238
|
+
uv sync
|
|
239
|
+
uv run pytest
|
|
240
|
+
uv run ruff check .
|
|
241
|
+
uv run ruff format --check .
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
`tests/test_contract.py` corre los casos de `../contract/cases` en los dos modos de validación.
|
|
245
|
+
|
|
246
|
+
## Limitaciones de esta versión
|
|
247
|
+
|
|
248
|
+
- La validación de sesiones solo expone API síncrona (la de MCP tiene las dos). Las dependencias de FastAPI corren en el threadpool, como en los backends actuales.
|
|
249
|
+
- En modo local, un token completo revocado sigue pasando hasta que vence. Los tokens «thin» y el modo remoto sí ven la revocación, con un retraso máximo igual al TTL de la caché.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
gt_auth_sdk/__init__.py,sha256=fRb1Oh89W2Gl8Xei5GOel4pKuEJGUGMDU3Psv6BbFXs,729
|
|
2
|
+
gt_auth_sdk/errors.py,sha256=O1vkf0hgDkp-n1a0mUpiS8qCrNNOJr4TG-ABdb1xvq4,2590
|
|
3
|
+
gt_auth_sdk/fastapi.py,sha256=mxEKD9bqoS9sAVQuPcw_yFmt5OZncGFRxRoo4XEQ4xA,10415
|
|
4
|
+
gt_auth_sdk/mcp.py,sha256=SurFOnHRoElVEl83VWcTkxettJ2WcxcAeTPSKHcT0HQ,10562
|
|
5
|
+
gt_auth_sdk/me.py,sha256=alme4uP87VhvU1NZWtBkJtrcrJOe6pNbaGdoHtL1lkw,6076
|
|
6
|
+
gt_auth_sdk/principal.py,sha256=yXG9dil3FZDWi3NbvFrD7GXb-TDhjwJg3eRW6W_HBiA,7666
|
|
7
|
+
gt_auth_sdk/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
gt_auth_sdk/session.py,sha256=L8zbB0wOBjeZnDak0vUKZ2H6nLobODmMi4YUYQq0SOw,4218
|
|
9
|
+
gt_auth_sdk/settings.py,sha256=qlegj-nImTSuS3_k0EQqdxRMrvItY8eQVxGK5qUHyvM,4108
|
|
10
|
+
gt_auth_sdk/validator.py,sha256=VViJxZkvSZw_kSSGxe8EV6XmxHp3-JNMLGFBX1Y450Q,5979
|
|
11
|
+
gt_auth_sdk_python-0.4.2.dist-info/METADATA,sha256=G_gTKPQusgOqyvseF0Wmp3Z8k0Hh2j8pEGqO4IevTP4,10094
|
|
12
|
+
gt_auth_sdk_python-0.4.2.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
13
|
+
gt_auth_sdk_python-0.4.2.dist-info/RECORD,,
|