perf(api): cachear validez de App Check y subir TTL de precios
Browse filesEl token de App Check dura 7 dias del lado del cliente; verificar la firma
RSA en cada request era CPU-bound innecesario y ademas bloqueaba el
threadpool sync de FastAPI, el cuello de botella real de concurrencia.
verify_app_check pasa a async: los hits de cache resuelven en el event loop
sin threadpool, los misses verifican la firma via run_in_threadpool y
cachean el exito (nunca los fallos) hasta min(exp del token, ahora + 3
dias). Limpieza horaria del cache para no crecer sin limite, mas
invalidate_appcheck_token() para poder cortarle el acceso a un token
puntual sin esperar a que expire.
De paso, P2P_V2_TTL sube de 2 a 10 minutos: el lock anti-thundering-herd
ya garantizaba un solo fetch externo por moneda por ventana de cache, asi
que la carga externa a Binance/OKX baja sin que la app pierda la
capacidad de absorber usuarios concurrentes (eso lo resuelve el cache de
App Check, no el TTL de precios).
|
@@ -7,11 +7,13 @@ import httpx
|
|
| 7 |
import asyncio
|
| 8 |
import time
|
| 9 |
import re
|
|
|
|
| 10 |
import hmac
|
| 11 |
import jwt
|
| 12 |
import logging
|
| 13 |
import os
|
| 14 |
from jwt import PyJWKClient
|
|
|
|
| 15 |
|
| 16 |
import history
|
| 17 |
import stats
|
|
@@ -35,7 +37,7 @@ FORCED_REFRESH_MIN_INTERVAL = 30 # segundos
|
|
| 35 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 36 |
# v2 β Constantes (aislamiento total respecto a v1)
|
| 37 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 38 |
-
P2P_V2_TTL = 60 *
|
| 39 |
BINANCE_P2P_URL = "https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search"
|
| 40 |
COUNTRY_CODE_PATTERN = re.compile(r"^[A-Z]{2}$")
|
| 41 |
|
|
@@ -97,11 +99,13 @@ async def lifespan(app: FastAPI):
|
|
| 97 |
history.init()
|
| 98 |
sampler = asyncio.create_task(_history_sampler()) if history.is_enabled() else None
|
| 99 |
stats_task = stats.start(history.get_db)
|
|
|
|
| 100 |
yield
|
| 101 |
if sampler:
|
| 102 |
sampler.cancel()
|
| 103 |
if stats_task:
|
| 104 |
stats_task.cancel()
|
|
|
|
| 105 |
await _http.aclose()
|
| 106 |
await _http_nv.aclose()
|
| 107 |
|
|
@@ -162,8 +166,40 @@ JWKS_URL = "https://firebaseappcheck.googleapis.com/v1/jwks"
|
|
| 162 |
|
| 163 |
_jwks_client = PyJWKClient(JWKS_URL, cache_jwk_set=True, lifespan=3600)
|
| 164 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
|
| 166 |
-
|
|
|
|
| 167 |
# DISABLE_APP_CHECK tiene tres estados:
|
| 168 |
# "1" β desactivado del todo (parche histΓ³rico): no valida nada.
|
| 169 |
# "shadow" β valida y clasifica el motivo igual que en modo estricto, pero
|
|
@@ -187,15 +223,33 @@ def verify_app_check(x_firebase_appcheck: str = Header(None)):
|
|
| 187 |
|
| 188 |
if not x_firebase_appcheck:
|
| 189 |
return _reject("sin_token")
|
| 190 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
signing_key = _jwks_client.get_signing_key_from_jwt(x_firebase_appcheck)
|
| 192 |
-
|
| 193 |
x_firebase_appcheck,
|
| 194 |
signing_key.key,
|
| 195 |
algorithms=["RS256"],
|
| 196 |
audience=f"projects/{PROJECT_NUMBER}",
|
| 197 |
issuer=f"https://firebaseappcheck.googleapis.com/{PROJECT_NUMBER}",
|
| 198 |
)
|
|
|
|
|
|
|
|
|
|
| 199 |
if claims.get("sub") != APP_ID:
|
| 200 |
return _reject("sub_no_coincide")
|
| 201 |
except jwt.exceptions.PyJWTError as e:
|
|
@@ -205,6 +259,10 @@ def verify_app_check(x_firebase_appcheck: str = Header(None)):
|
|
| 205 |
|
| 206 |
# Llegar hasta acΓ‘ significa que no pasΓ³ por ningΓΊn _reject(): token presente,
|
| 207 |
# firma/audience/issuer vΓ‘lidos y sub coincide con la app. Request aceptada.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
stats.record_accepted_request()
|
| 209 |
|
| 210 |
|
|
|
|
| 7 |
import asyncio
|
| 8 |
import time
|
| 9 |
import re
|
| 10 |
+
import hashlib
|
| 11 |
import hmac
|
| 12 |
import jwt
|
| 13 |
import logging
|
| 14 |
import os
|
| 15 |
from jwt import PyJWKClient
|
| 16 |
+
from starlette.concurrency import run_in_threadpool
|
| 17 |
|
| 18 |
import history
|
| 19 |
import stats
|
|
|
|
| 37 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 38 |
# v2 β Constantes (aislamiento total respecto a v1)
|
| 39 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 40 |
+
P2P_V2_TTL = 60 * 10
|
| 41 |
BINANCE_P2P_URL = "https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search"
|
| 42 |
COUNTRY_CODE_PATTERN = re.compile(r"^[A-Z]{2}$")
|
| 43 |
|
|
|
|
| 99 |
history.init()
|
| 100 |
sampler = asyncio.create_task(_history_sampler()) if history.is_enabled() else None
|
| 101 |
stats_task = stats.start(history.get_db)
|
| 102 |
+
appcheck_cleanup_task = asyncio.create_task(_appcheck_cache_cleanup())
|
| 103 |
yield
|
| 104 |
if sampler:
|
| 105 |
sampler.cancel()
|
| 106 |
if stats_task:
|
| 107 |
stats_task.cancel()
|
| 108 |
+
appcheck_cleanup_task.cancel()
|
| 109 |
await _http.aclose()
|
| 110 |
await _http_nv.aclose()
|
| 111 |
|
|
|
|
| 166 |
|
| 167 |
_jwks_client = PyJWKClient(JWKS_URL, cache_jwk_set=True, lifespan=3600)
|
| 168 |
|
| 169 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 170 |
+
# Cache de validez de App Check
|
| 171 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 172 |
+
# El token de App Check dura 7 dΓas (config del cliente, fuera de este repo).
|
| 173 |
+
# Verificar la firma RSA (CPU-bound) en cada request de esos 7 dΓas es
|
| 174 |
+
# desperdicio: el mismo patrΓ³n _cached/_lock/_store que usa el resto del
|
| 175 |
+
# archivo no aplica igual acΓ‘ porque no queremos guardar el token crudo como
|
| 176 |
+
# clave, asΓ que este cache vive aparte con la clave hasheada.
|
| 177 |
+
# Clave: sha256(token) β nunca el token crudo. Valor: timestamp valido_hasta.
|
| 178 |
+
_appcheck_cache: dict[str, float] = {}
|
| 179 |
+
APPCHECK_CACHE_MAX_TTL = 3 * 24 * 3600 # techo: nunca cachear mΓ‘s de 3 dΓas
|
| 180 |
+
APPCHECK_CACHE_CLEANUP_INTERVAL = 60 * 60 # limpieza cada 1 hora
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def invalidate_appcheck_token(token: str) -> None:
|
| 184 |
+
"""Borra manualmente un token del cache de App Check (p.ej. si se detecta que
|
| 185 |
+
fue comprometido y no se quiere esperar a que expire su entrada). No falla si
|
| 186 |
+
el token no estaba cacheado."""
|
| 187 |
+
_appcheck_cache.pop(hashlib.sha256(token.encode()).hexdigest(), None)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
async def _appcheck_cache_cleanup():
|
| 191 |
+
"""Tarea periΓ³dica (cada 1 hora, ciclo independiente del flush de 120s de
|
| 192 |
+
stats.py) que purga del cache las entradas ya vencidas. Sin esto el dict
|
| 193 |
+
crece indefinidamente con tokens que ya no van a volver a usarse."""
|
| 194 |
+
while True:
|
| 195 |
+
await asyncio.sleep(APPCHECK_CACHE_CLEANUP_INTERVAL)
|
| 196 |
+
ahora = time.time()
|
| 197 |
+
vencidos = [k for k, valido_hasta in _appcheck_cache.items() if valido_hasta <= ahora]
|
| 198 |
+
for k in vencidos:
|
| 199 |
+
_appcheck_cache.pop(k, None)
|
| 200 |
|
| 201 |
+
|
| 202 |
+
async def verify_app_check(x_firebase_appcheck: str = Header(None)):
|
| 203 |
# DISABLE_APP_CHECK tiene tres estados:
|
| 204 |
# "1" β desactivado del todo (parche histΓ³rico): no valida nada.
|
| 205 |
# "shadow" β valida y clasifica el motivo igual que en modo estricto, pero
|
|
|
|
| 223 |
|
| 224 |
if not x_firebase_appcheck:
|
| 225 |
return _reject("sin_token")
|
| 226 |
+
|
| 227 |
+
token_hash = hashlib.sha256(x_firebase_appcheck.encode()).hexdigest()
|
| 228 |
+
|
| 229 |
+
# Cache-hit: este token ya se verificΓ³ antes y sigue vigente. No hace falta
|
| 230 |
+
# volver a validar la firma RSA (CPU-bound) ni pasar por el threadpool β se
|
| 231 |
+
# resuelve directo en el event loop. Este es el camino que toma la mayorΓa
|
| 232 |
+
# de los requests una vez que el cache se calienta.
|
| 233 |
+
valido_hasta = _appcheck_cache.get(token_hash)
|
| 234 |
+
if valido_hasta is not None and valido_hasta > time.time():
|
| 235 |
+
stats.record_accepted_request()
|
| 236 |
+
return
|
| 237 |
+
|
| 238 |
+
# Cache-miss: token nuevo o vencido en el cache. La verificaciΓ³n de firma es
|
| 239 |
+
# CPU-bound y cara, asΓ que se manda al threadpool para no bloquear el event
|
| 240 |
+
# loop mientras se calcula.
|
| 241 |
+
def _verificar_firma():
|
| 242 |
signing_key = _jwks_client.get_signing_key_from_jwt(x_firebase_appcheck)
|
| 243 |
+
return jwt.decode(
|
| 244 |
x_firebase_appcheck,
|
| 245 |
signing_key.key,
|
| 246 |
algorithms=["RS256"],
|
| 247 |
audience=f"projects/{PROJECT_NUMBER}",
|
| 248 |
issuer=f"https://firebaseappcheck.googleapis.com/{PROJECT_NUMBER}",
|
| 249 |
)
|
| 250 |
+
|
| 251 |
+
try:
|
| 252 |
+
claims = await run_in_threadpool(_verificar_firma)
|
| 253 |
if claims.get("sub") != APP_ID:
|
| 254 |
return _reject("sub_no_coincide")
|
| 255 |
except jwt.exceptions.PyJWTError as e:
|
|
|
|
| 259 |
|
| 260 |
# Llegar hasta acΓ‘ significa que no pasΓ³ por ningΓΊn _reject(): token presente,
|
| 261 |
# firma/audience/issuer vΓ‘lidos y sub coincide con la app. Request aceptada.
|
| 262 |
+
# Se cachea el Γ©xito (nunca los fallos) hasta el mΓnimo entre el exp real del
|
| 263 |
+
# token y el techo de 3 dΓas β nunca le damos al cache mΓ‘s vida que la que el
|
| 264 |
+
# token realmente tiene segΓΊn su propio claim.
|
| 265 |
+
_appcheck_cache[token_hash] = min(claims["exp"], time.time() + APPCHECK_CACHE_MAX_TTL)
|
| 266 |
stats.record_accepted_request()
|
| 267 |
|
| 268 |
|