Spaces:
Running

andervier commited on
Commit
d4ba7c6
·
1 Parent(s): 40320bc

feat(api): blindar la API contra fallos de red y accesos no autenticados

Browse files

- fetch_bcv/fetch_p2p/fetch_p2p_v2 clasifican y registran en stats los
fallos de red (timeout, conexion, HTTP) en vez de dejarlos propagar
sin manejar
- verify_app_check devuelve 404 en vez de 401 ante cualquier fallo, y
soporta un modo "shadow" (DISABLE_APP_CHECK=shadow) para medir el
impacto antes de bloquear en serio
- byPath/latencyByPath en stats se acotan a las rutas reales de la app,
evitando crecimiento sin limite por escaneos automatizados
- elimina /v1/p2p/debug: no tenia autenticacion y exponia llamadas
directas a Binance sin control

Files changed (3) hide show
  1. DESIGN_TAZAS_WORLDWIDE.md +4 -3
  2. main.py +79 -49
  3. stats.py +57 -0
DESIGN_TAZAS_WORLDWIDE.md CHANGED
@@ -345,7 +345,7 @@ Decisión: el **único** error 5xx que `/v2/rates` puede devolver es el del BCV
345
  | `fetch_p2p_safe()` | Modificar: aceptar `fiat: str` y pasarlo a `fetch_p2p` |
346
  | `validate_country()` | Agregar |
347
  | `rates_v2()` handler | Agregar |
348
- | `/v1/rates`, `/v1/p2p`, `/v1/p2p/debug` | Modificar: pasar `"VES"` explícito al llamar `fetch_p2p*` |
349
  | Logger | Agregar log INFO al inicio de cada fetch P2P con el fiat (útil para diagnosticar tráfico por país) |
350
 
351
  ### Snippet del `/v1` actualizado (sin romper contrato)
@@ -371,7 +371,7 @@ Antes del deploy a HF Spaces, validar en local o staging:
371
  - [ ] `GET /v1/rates` con AppCheck válido → response 200 con shape exacto del legacy
372
  - [ ] `GET /v1/bcv` → response 200 con campos BCV
373
  - [ ] `GET /v1/p2p` → response 200 con `p2pBuyMax` y `p2pSellMax`
374
- - [ ] `GET /v1/p2p/debug` → response con anuncios crudos
375
 
376
  ### 8.2 Funcionalidad `/v2`
377
 
@@ -426,9 +426,10 @@ Estos checks NO requieren el token AppCheck:
426
 
427
  ```bash
428
  curl https://andervier-tazas-api.hf.space/ # ping
429
- curl https://andervier-tazas-api.hf.space/v1/p2p/debug # P2P debug
430
  ```
431
 
 
 
432
  Para los endpoints autenticados, usar el cliente Android en build debug (que ya tiene AppCheck debug provider).
433
 
434
  ### 9.4 Rollback
 
345
  | `fetch_p2p_safe()` | Modificar: aceptar `fiat: str` y pasarlo a `fetch_p2p` |
346
  | `validate_country()` | Agregar |
347
  | `rates_v2()` handler | Agregar |
348
+ | `/v1/rates`, `/v1/p2p` | Modificar: pasar `"VES"` explícito al llamar `fetch_p2p*` |
349
  | Logger | Agregar log INFO al inicio de cada fetch P2P con el fiat (útil para diagnosticar tráfico por país) |
350
 
351
  ### Snippet del `/v1` actualizado (sin romper contrato)
 
371
  - [ ] `GET /v1/rates` con AppCheck válido → response 200 con shape exacto del legacy
372
  - [ ] `GET /v1/bcv` → response 200 con campos BCV
373
  - [ ] `GET /v1/p2p` → response 200 con `p2pBuyMax` y `p2pSellMax`
374
+ <!-- `/v1/p2p/debug` eliminado: no tenía Depends(verify_app_check), quedaba abierto al mundo y exponía llamadas directas a Binance sin control (hardening de seguridad). -->
375
 
376
  ### 8.2 Funcionalidad `/v2`
377
 
 
426
 
427
  ```bash
428
  curl https://andervier-tazas-api.hf.space/ # ping
 
429
  ```
430
 
431
+ <!-- `/v1/p2p/debug` eliminado (hardening): no tenía AppCheck, quedaba abierto al mundo. -->
432
+
433
  Para los endpoints autenticados, usar el cliente Android en build debug (que ya tiene AppCheck debug provider).
434
 
435
  ### 9.4 Rollback
main.py CHANGED
@@ -121,6 +121,20 @@ app.add_middleware(
121
  )
122
 
123
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  @app.middleware("http")
125
  async def _stats_middleware(request, call_next):
126
  # Mide throughput/latencia/errores por endpoint. Si call_next lanza, cuenta 500.
@@ -131,10 +145,12 @@ async def _stats_middleware(request, call_next):
131
  status = response.status_code
132
  return response
133
  finally:
134
- stats.record(request.url.path, status, time.perf_counter() - started)
135
- # DEBUG TEMPORAL: guarda el detalle de los 401 de App Check para diagnosticarlos.
 
 
136
  p = request.url.path
137
- if status == 401 and (p.startswith("/v1") or p.startswith("/v2")):
138
  await _capture_401(request)
139
 
140
  # ──────────────────────────────────────────────
@@ -148,11 +164,29 @@ _jwks_client = PyJWKClient(JWKS_URL, cache_jwk_set=True, lifespan=3600)
148
 
149
 
150
  def verify_app_check(x_firebase_appcheck: str = Header(None)):
151
- # PARCHE TEMPORAL: DISABLE_APP_CHECK=1 omite la validación mientras Google revisa la app
152
- if os.getenv("DISABLE_APP_CHECK") == "1":
 
 
 
 
 
 
 
153
  return
 
 
 
 
 
 
 
 
 
 
 
154
  if not x_firebase_appcheck:
155
- raise HTTPException(status_code=401, detail="Token App Check requerido")
156
  try:
157
  signing_key = _jwks_client.get_signing_key_from_jwt(x_firebase_appcheck)
158
  claims = jwt.decode(
@@ -163,9 +197,11 @@ def verify_app_check(x_firebase_appcheck: str = Header(None)):
163
  issuer=f"https://firebaseappcheck.googleapis.com/{PROJECT_NUMBER}",
164
  )
165
  if claims.get("sub") != APP_ID:
166
- raise HTTPException(status_code=401, detail="App no autorizada")
167
- except jwt.exceptions.PyJWTError:
168
- raise HTTPException(status_code=401, detail="Token App Check inválido")
 
 
169
 
170
 
171
  # ──────────────────────────────────────────────
@@ -243,6 +279,19 @@ def _parse_bcv_rate(text: str) -> float | None:
243
  return None
244
 
245
 
 
 
 
 
 
 
 
 
 
 
 
 
 
246
  # ──────────────────────────────────────────────
247
  # Fetchers
248
  # ────────���─────────────────────────────────────
@@ -267,8 +316,14 @@ async def fetch_bcv(force: bool = False) -> dict:
267
  }
268
 
269
  # verify=False porque bcv.org.ve tiene cadena de certificados incompleta (problema del BCV)
270
- response = await _http_nv.get("https://www.bcv.org.ve/", headers=headers)
271
- response.raise_for_status()
 
 
 
 
 
 
272
 
273
  soup = BeautifulSoup(response.text, "lxml")
274
 
@@ -287,9 +342,12 @@ async def fetch_bcv(force: bool = False) -> dict:
287
  rates[f"bcv{suffix}"] = _parse_bcv_rate(tag.text) if tag else None
288
 
289
  if all(v is None for v in rates.values()):
 
290
  logger.error("BCV: all rates are None — scraping failed")
291
  raise HTTPException(status_code=503, detail="No se pudo obtener las tasas BCV")
292
 
 
 
293
  updated_tag = soup.find("span", {"class": re.compile(r"date-display")})
294
  updated_at = updated_tag.text.strip() if updated_tag else None
295
 
@@ -397,8 +455,12 @@ async def fetch_p2p() -> dict:
397
 
398
  async def fetch_p2p_safe() -> dict:
399
  try:
400
- return await fetch_p2p()
 
 
401
  except Exception as e:
 
 
402
  logger.error("fetch_p2p failed: %s", e, exc_info=True)
403
  return {"p2pBuyMax": None, "p2pSellMax": None}
404
 
@@ -466,8 +528,12 @@ async def fetch_p2p_v2(fiat: str) -> dict:
466
 
467
  async def fetch_p2p_v2_safe(fiat: str) -> dict:
468
  try:
469
- return await fetch_p2p_v2(fiat)
 
 
470
  except Exception as e:
 
 
471
  logger.error("fetch_p2p_v2(%s) failed: %s", fiat, e, exc_info=True)
472
  return {"p2pBuyMax": None, "p2pSellMax": None}
473
 
@@ -544,42 +610,6 @@ async def p2p():
544
  return await fetch_p2p()
545
 
546
 
547
- @app.get("/v1/p2p/debug")
548
- async def p2p_debug():
549
- """Devuelve los primeros 5 anuncios crudos de cada dirección para diagnóstico."""
550
- headers = {"User-Agent": "Mozilla/5.0", "Content-Type": "application/json"}
551
- body_base = {
552
- "fiat": "VES", "page": 1, "rows": 10, "asset": "USDT",
553
- "countries": [], "proMerchantAds": False, "shieldMerchantAds": False,
554
- "publisherType": None, "payTypes": [],
555
- "classifies": ["mass", "profession"],
556
- }
557
- buy_res, sell_res = await asyncio.gather(
558
- _http.post("https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search",
559
- json={**body_base, "tradeType": "BUY"}, headers=headers),
560
- _http.post("https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search",
561
- json={**body_base, "tradeType": "SELL"}, headers=headers),
562
- )
563
-
564
- def extract(ads):
565
- return [
566
- {
567
- "index": i,
568
- "price": item["adv"].get("price"),
569
- "surplusAmount": item["adv"].get("surplusAmount"),
570
- "minSingleTransAmount": item["adv"].get("minSingleTransAmount"),
571
- "maxSingleTransAmount": item["adv"].get("maxSingleTransAmount"),
572
- "publisherType": item["adv"].get("publisherType"),
573
- }
574
- for i, item in enumerate(ads[:8])
575
- ]
576
-
577
- return {
578
- "buy_ads": extract(buy_res.json().get("data", [])),
579
- "sell_ads": extract(sell_res.json().get("data", [])),
580
- }
581
-
582
-
583
  # ──────────────────────────────────────────────
584
  # v2 — Endpoint multi-país (aislado de /v1)
585
  # ──────────────────────────────────────────────
 
121
  )
122
 
123
 
124
+ _known_paths: set[str] | None = None
125
+
126
+
127
+ def _tracked_path(path: str) -> str:
128
+ """Colapsa cualquier path que no sea una ruta real de la app a 'other'. Sin
129
+ esto, byPath/latencyByPath en stats crecen sin límite: un escáner probando
130
+ /wp-admin, /.env, etc. crea una entrada nueva en el dict por cada intento,
131
+ hasta reventar el límite de 1 MiB por documento de Firestore."""
132
+ global _known_paths
133
+ if _known_paths is None:
134
+ _known_paths = {route.path for route in app.routes if hasattr(route, "path")}
135
+ return path if path in _known_paths else "other"
136
+
137
+
138
  @app.middleware("http")
139
  async def _stats_middleware(request, call_next):
140
  # Mide throughput/latencia/errores por endpoint. Si call_next lanza, cuenta 500.
 
145
  status = response.status_code
146
  return response
147
  finally:
148
+ stats.record(_tracked_path(request.url.path), status, time.perf_counter() - started)
149
+ # DEBUG TEMPORAL: guarda el detalle de los fallos de App Check para diagnosticarlos.
150
+ # verify_app_check ahora devuelve 404 (no 401) en cualquier fallo, así que
151
+ # el disparador de esta captura tiene que ser 404, no 401.
152
  p = request.url.path
153
+ if status == 404 and (p.startswith("/v1") or p.startswith("/v2")):
154
  await _capture_401(request)
155
 
156
  # ──────────────────────────────────────────────
 
164
 
165
 
166
  def verify_app_check(x_firebase_appcheck: str = Header(None)):
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
170
+ # NUNCA bloquea. Sirve para medir cuánta gente fallaría antes de
171
+ # activar el bloqueo real, sin arriesgar usuarios reales (caso
172
+ # conocido: redes WiFi que bloquean el alcance a Play Integrity).
173
+ # (nada) → modo estricto: bloquea con 404.
174
+ mode = os.getenv("DISABLE_APP_CHECK")
175
+ if mode == "1":
176
  return
177
+ shadow = mode == "shadow"
178
+
179
+ # 404 en vez de 401 en modo estricto: a quien golpee sin token válido, el
180
+ # endpoint le parece inexistente. Un 401 delata que hay algo ahí protegido y
181
+ # digno de atacar; un 404 no invita a insistir.
182
+ def _reject(reason: str):
183
+ stats.record_auth_failure(reason)
184
+ if shadow:
185
+ return
186
+ raise HTTPException(status_code=404, detail="Not Found")
187
+
188
  if not x_firebase_appcheck:
189
+ return _reject("sin_token")
190
  try:
191
  signing_key = _jwks_client.get_signing_key_from_jwt(x_firebase_appcheck)
192
  claims = jwt.decode(
 
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:
202
+ # Nombre real de la excepción de PyJWT (ExpiredSignatureError, DecodeError,
203
+ # InvalidAudienceError, PyJWKClientError...) en vez de adivinar el motivo.
204
+ return _reject(type(e).__name__)
205
 
206
 
207
  # ──────────────────────────────────────────────
 
279
  return None
280
 
281
 
282
+ def _classify_fetch_error(e: Exception) -> str:
283
+ """Clasifica el fallo de un fetcher externo (BCV, P2P) en un motivo legible
284
+ para las stats — así el dashboard distingue timeout de caída de conexión de
285
+ un cambio de formato en la respuesta."""
286
+ if isinstance(e, httpx.TimeoutException):
287
+ return "timeout"
288
+ if isinstance(e, httpx.HTTPStatusError):
289
+ return f"http_error_{e.response.status_code}"
290
+ if isinstance(e, httpx.RequestError):
291
+ return "connection_error"
292
+ return type(e).__name__
293
+
294
+
295
  # ──────────────────────────────────────────────
296
  # Fetchers
297
  # ────────���─────────────────────────────────────
 
316
  }
317
 
318
  # verify=False porque bcv.org.ve tiene cadena de certificados incompleta (problema del BCV)
319
+ try:
320
+ response = await _http_nv.get("https://www.bcv.org.ve/", headers=headers)
321
+ response.raise_for_status()
322
+ except (httpx.TimeoutException, httpx.RequestError, httpx.HTTPStatusError) as e:
323
+ reason = _classify_fetch_error(e)
324
+ stats.record_fetch_error("bcv", reason, str(e))
325
+ logger.warning("BCV fetch falló (%s): %s", reason, e)
326
+ raise HTTPException(status_code=503, detail="No se pudo contactar al BCV") from e
327
 
328
  soup = BeautifulSoup(response.text, "lxml")
329
 
 
342
  rates[f"bcv{suffix}"] = _parse_bcv_rate(tag.text) if tag else None
343
 
344
  if all(v is None for v in rates.values()):
345
+ stats.record_fetch_error("bcv", "parse_error", "todas las tasas dieron None")
346
  logger.error("BCV: all rates are None — scraping failed")
347
  raise HTTPException(status_code=503, detail="No se pudo obtener las tasas BCV")
348
 
349
+ stats.record_fetch_success("bcv")
350
+
351
  updated_tag = soup.find("span", {"class": re.compile(r"date-display")})
352
  updated_at = updated_tag.text.strip() if updated_tag else None
353
 
 
455
 
456
  async def fetch_p2p_safe() -> dict:
457
  try:
458
+ data = await fetch_p2p()
459
+ stats.record_fetch_success("p2p")
460
+ return data
461
  except Exception as e:
462
+ reason = _classify_fetch_error(e)
463
+ stats.record_fetch_error("p2p", reason, str(e))
464
  logger.error("fetch_p2p failed: %s", e, exc_info=True)
465
  return {"p2pBuyMax": None, "p2pSellMax": None}
466
 
 
528
 
529
  async def fetch_p2p_v2_safe(fiat: str) -> dict:
530
  try:
531
+ data = await fetch_p2p_v2(fiat)
532
+ stats.record_fetch_success("p2p_v2")
533
+ return data
534
  except Exception as e:
535
+ reason = _classify_fetch_error(e)
536
+ stats.record_fetch_error("p2p_v2", reason, f"fiat={fiat}: {e}")
537
  logger.error("fetch_p2p_v2(%s) failed: %s", fiat, e, exc_info=True)
538
  return {"p2pBuyMax": None, "p2pSellMax": None}
539
 
 
610
  return await fetch_p2p()
611
 
612
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
613
  # ──────────────────────────────────────────────
614
  # v2 — Endpoint multi-país (aislado de /v1)
615
  # ──────────────────────────────────────────────
stats.py CHANGED
@@ -38,8 +38,24 @@ _by_path: dict[str, int] = defaultdict(int)
38
  _by_status: dict[str, int] = defaultdict(int)
39
  _latency_sum = 0.0
40
  _latency_max = 0.0
 
41
  _per_minute: dict[int, int] = defaultdict(int) # minuto_epoch → nº de peticiones
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
  def record(path: str, status: int, elapsed: float) -> None:
45
  """Registra una petición. `elapsed` en segundos."""
@@ -53,6 +69,12 @@ def record(path: str, status: int, elapsed: float) -> None:
53
  if elapsed > _latency_max:
54
  _latency_max = elapsed
55
 
 
 
 
 
 
 
56
  minute = int(time.time()) // 60 * 60
57
  _per_minute[minute] += 1
58
  # Podar la ventana rodante para que el dict no crezca sin límite.
@@ -61,6 +83,28 @@ def record(path: str, status: int, elapsed: float) -> None:
61
  del _per_minute[stale]
62
 
63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  def snapshot() -> dict:
65
  avg_latency = (_latency_sum / _total) if _total else 0.0
66
  return {
@@ -75,6 +119,19 @@ def snapshot() -> dict:
75
  "byStatus": dict(_by_status),
76
  # req/min de la última hora: mapa {minuto_epoch: nº}. Da la curva de carga.
77
  "perMinute": {str(k): v for k, v in sorted(_per_minute.items())},
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  }
79
 
80
 
 
38
  _by_status: dict[str, int] = defaultdict(int)
39
  _latency_sum = 0.0
40
  _latency_max = 0.0
41
+ _latency_by_path: dict[str, dict] = defaultdict(lambda: {"sum": 0.0, "max": 0.0, "count": 0})
42
  _per_minute: dict[int, int] = defaultdict(int) # minuto_epoch → nº de peticiones
43
 
44
+ # Fallos de fetchers externos (BCV, P2P), clasificados por motivo (timeout,
45
+ # connection_error, http_error_XXX, parse_error...). El status 5xx de arriba dice
46
+ # QUE algo falló; esto dice POR QUÉ, para poder diagnosticar desde el dashboard
47
+ # sin ir a revisar logs.
48
+ _fetch_errors: dict[str, dict[str, int]] = defaultdict(lambda: defaultdict(int))
49
+ _last_fetch_error: dict[str, dict] = {}
50
+ _last_fetch_success: dict[str, int] = {}
51
+
52
+ # Intentos de App Check rechazados, clasificados por motivo real (sin_token,
53
+ # nombre de la excepción de PyJWT como ExpiredSignatureError/DecodeError/etc.,
54
+ # o sub_no_coincide). El endpoint responde 404 para no delatar que hay algo
55
+ # protegido, pero esto deja visible en el dashboard si están tocando la puerta.
56
+ _auth_failures: dict[str, int] = defaultdict(int)
57
+ _last_auth_failure: dict | None = None
58
+
59
 
60
  def record(path: str, status: int, elapsed: float) -> None:
61
  """Registra una petición. `elapsed` en segundos."""
 
69
  if elapsed > _latency_max:
70
  _latency_max = elapsed
71
 
72
+ path_stat = _latency_by_path[path]
73
+ path_stat["sum"] += elapsed
74
+ path_stat["count"] += 1
75
+ if elapsed > path_stat["max"]:
76
+ path_stat["max"] = elapsed
77
+
78
  minute = int(time.time()) // 60 * 60
79
  _per_minute[minute] += 1
80
  # Podar la ventana rodante para que el dict no crezca sin límite.
 
83
  del _per_minute[stale]
84
 
85
 
86
+ def record_fetch_error(source: str, reason: str, detail: str = "") -> None:
87
+ """Registra el fallo de un fetcher externo (BCV, P2P...) clasificado por motivo."""
88
+ _fetch_errors[source][reason] += 1
89
+ _last_fetch_error[source] = {
90
+ "ts": int(time.time()),
91
+ "reason": reason,
92
+ "detail": detail[:200],
93
+ }
94
+
95
+
96
+ def record_auth_failure(reason: str) -> None:
97
+ """Cuenta un intento de App Check rechazado, clasificado por motivo."""
98
+ global _last_auth_failure
99
+ _auth_failures[reason] += 1
100
+ _last_auth_failure = {"ts": int(time.time()), "reason": reason}
101
+
102
+
103
+ def record_fetch_success(source: str) -> None:
104
+ """Marca la última vez que un fetcher externo respondió con éxito."""
105
+ _last_fetch_success[source] = int(time.time())
106
+
107
+
108
  def snapshot() -> dict:
109
  avg_latency = (_latency_sum / _total) if _total else 0.0
110
  return {
 
119
  "byStatus": dict(_by_status),
120
  # req/min de la última hora: mapa {minuto_epoch: nº}. Da la curva de carga.
121
  "perMinute": {str(k): v for k, v in sorted(_per_minute.items())},
122
+ "latencyByPath": {
123
+ p: {
124
+ "avgMs": round((s["sum"] / s["count"]) * 1000, 1) if s["count"] else 0.0,
125
+ "maxMs": round(s["max"] * 1000, 1),
126
+ "count": s["count"],
127
+ }
128
+ for p, s in _latency_by_path.items()
129
+ },
130
+ "fetchErrors": {source: dict(reasons) for source, reasons in _fetch_errors.items()},
131
+ "lastFetchError": dict(_last_fetch_error),
132
+ "lastFetchSuccess": dict(_last_fetch_success),
133
+ "authFailures": dict(_auth_failures),
134
+ "lastAuthFailure": _last_auth_failure,
135
  }
136
 
137