security: hardening contra 7 vectores de ataque identificados
Análisis ofensivo → defensas implementadas:
1. /health/history sin auth (CRÍTICO)
- Requiere Bearer token (HEALTH_AUTH_TOKEN en .env)
- chat_ids enmascarados como hash SHA256[:8] opaco ("usr_a3b4c5d6")
- Accesos denegados loggeados con IP + User-Agent
2. /health revela inteligencia operacional (MEDIO)
- Sin auth: solo {"status", "timestamp"} — sin conteo de tenants ni timing
- Con auth: respuesta completa con métricas internas
- Misma URL, auth desbloquea detalle
3. Variables sensibles en proceso env (CRÍTICO)
- Después de cargar Settings(), se limpian FERNET_KEY, TELEGRAM_BOT_TOKEN,
PJ_USUARIO_ENC, PJ_PASSWORD_ENC, WEBHOOK_SECRET, HEALTH_AUTH_TOKEN, INVITE_CODE
- Protege contra /proc/<pid>/environ y herencia por subprocesos
4. Race condition TOCTOU en invite codes (MEDIO)
- SELECT+UPDATE reemplazado por UPDATE WHERE usado=0
- rowcount=0 → False; imposible que dos requests simultáneos consuman el mismo código
5. Timing oracle en invite codes (BAJO-MEDIO)
- Delay mínimo de 800ms en _paso_codigo() independientemente del resultado
- secrets.compare_digest() para comparación del código del .env
6. Information disclosure en respuestas a no-registrados (BAJO)
- _rechazar_no_registrado: "Para usar este bot escribí /start." (sin revelar comandos)
- handle_texto_libre: silencio total para usuarios sin registro (no confirmar que el bot existe)
7. Nginx rate limiting (DEPLOY.md)
- limit_req_zone pedrito_webhook: 30r/s, burst=50
- limit_req_zone pedrito_health: 10r/m, burst=5
- Headers de seguridad: X-Content-Type-Options, X-Frame-Options
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
141
health.py
141
health.py
@@ -2,20 +2,31 @@
|
||||
health.py — Servidor HTTP para health check y webhook de Telegram.
|
||||
|
||||
Rutas:
|
||||
GET /health → JSON con estado actual del bot
|
||||
GET /health/history → últimos N eventos del audit_log (?limit=50)
|
||||
GET /health → estado mínimo (público) | estado completo (con Bearer token)
|
||||
GET /health/history → últimos N eventos del audit_log — REQUIERE Bearer token
|
||||
POST /webhook → recibe updates de Telegram (solo en modo webhook)
|
||||
|
||||
Modo webhook opt-in: solo se activa si settings.webhook_url está configurado.
|
||||
En modo long-polling, /webhook no se registra.
|
||||
Seguridad:
|
||||
- /health sin auth: solo devuelve {"status": "ok"|"degraded", "timestamp": "..."}
|
||||
Sin conteos de tenants ni timing que revele inteligencia operacional.
|
||||
- /health con auth: respuesta completa con métricas internas.
|
||||
- /health/history siempre requiere auth.
|
||||
- chat_ids en el historial se enmascaran como hashes opacos (no reversibles desde HTTP).
|
||||
- Webhook valida X-Telegram-Bot-Api-Secret-Token con compare_digest.
|
||||
|
||||
Configurar en .env:
|
||||
HEALTH_AUTH_TOKEN=<token largo aleatorio>
|
||||
(generar con: python -c "import secrets; print(secrets.token_hex(32))")
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import secrets
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import asyncio
|
||||
import aiohttp.web
|
||||
import structlog
|
||||
from telegram import Update
|
||||
@@ -29,7 +40,7 @@ logger = structlog.get_logger(__name__)
|
||||
# ── Estado global del poller ──────────────────────────────────────────────────
|
||||
_last_poll_at: datetime | None = None
|
||||
_last_poll_tenant_count: int = 0
|
||||
_alert_sent: bool = False # evitar spam de alertas consecutivas
|
||||
_alert_sent: bool = False
|
||||
|
||||
|
||||
def record_poll(tenant_count: int) -> None:
|
||||
@@ -40,6 +51,17 @@ def record_poll(tenant_count: int) -> None:
|
||||
_alert_sent = False
|
||||
|
||||
|
||||
def _mask_chat_id(chat_id: int | None) -> str | None:
|
||||
"""
|
||||
Convierte un chat_id en un identificador opaco no reversible.
|
||||
Preserva la capacidad de correlacionar eventos del mismo usuario
|
||||
sin exponer el Telegram ID real.
|
||||
"""
|
||||
if chat_id is None:
|
||||
return None
|
||||
return "usr_" + hashlib.sha256(str(chat_id).encode()).hexdigest()[:8]
|
||||
|
||||
|
||||
# ── Servidor ──────────────────────────────────────────────────────────────────
|
||||
|
||||
class HealthServer:
|
||||
@@ -61,7 +83,11 @@ class HealthServer:
|
||||
await self._runner.setup()
|
||||
site = aiohttp.web.TCPSite(self._runner, "0.0.0.0", self._settings.health_port)
|
||||
await site.start()
|
||||
logger.info("health_server_iniciado", port=self._settings.health_port)
|
||||
logger.info(
|
||||
"health_server_iniciado",
|
||||
port=self._settings.health_port,
|
||||
auth_configurada=bool(self._settings.health_auth_token),
|
||||
)
|
||||
|
||||
self._watcher_task = asyncio.create_task(self._watcher_loop())
|
||||
|
||||
@@ -76,37 +102,60 @@ class HealthServer:
|
||||
await self._runner.cleanup()
|
||||
logger.info("health_server_detenido")
|
||||
|
||||
# ── Auth ──────────────────────────────────────────────────────────────────
|
||||
|
||||
def _is_authenticated(self, request: aiohttp.web.Request) -> bool:
|
||||
"""
|
||||
Valida el header Authorization: Bearer <token>.
|
||||
Si health_auth_token no está configurado, siempre retorna False
|
||||
(los endpoints protegidos devuelven respuesta mínima, no error).
|
||||
"""
|
||||
if not self._settings.health_auth_token:
|
||||
return False
|
||||
auth = request.headers.get("Authorization", "")
|
||||
if not auth.startswith("Bearer "):
|
||||
return False
|
||||
provided = auth[7:]
|
||||
# compare_digest previene timing attacks sobre el token de admin
|
||||
return secrets.compare_digest(provided, self._settings.health_auth_token)
|
||||
|
||||
# ── Handlers ─────────────────────────────────────────────────────────────
|
||||
|
||||
async def _handle_health(self, request: aiohttp.web.Request) -> aiohttp.web.Response:
|
||||
from database import get_conn
|
||||
conn = get_conn()
|
||||
|
||||
async with conn.execute(
|
||||
"SELECT COUNT(*) as n FROM tenants WHERE estado = 'activo'"
|
||||
) as cur:
|
||||
row = await cur.fetchone()
|
||||
tenant_count = row["n"] if row else 0
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
seconds_since_poll: int | None = None
|
||||
stale = False
|
||||
|
||||
if _last_poll_at:
|
||||
delta = now - _last_poll_at
|
||||
seconds_since_poll = int(delta.total_seconds())
|
||||
stale = delta > timedelta(hours=self._settings.health_alert_hours)
|
||||
stale = (now - _last_poll_at) > timedelta(hours=self._settings.health_alert_hours)
|
||||
|
||||
data = {
|
||||
# Respuesta pública mínima — no revela conteos ni timing operacional
|
||||
data: dict = {
|
||||
"status": "degraded" if stale else "ok",
|
||||
"timestamp": now.isoformat(),
|
||||
"tenants_activos": tenant_count,
|
||||
"last_poll": _last_poll_at.isoformat() if _last_poll_at else None,
|
||||
"last_poll_tenants": _last_poll_tenant_count,
|
||||
"seconds_since_last_poll": seconds_since_poll,
|
||||
"poll_interval_minutes": self._settings.poll_interval_minutes,
|
||||
"webhook_mode": bool(self._settings.webhook_url),
|
||||
}
|
||||
|
||||
# Respuesta extendida solo con auth válida
|
||||
if self._is_authenticated(request):
|
||||
from database import get_conn
|
||||
conn = get_conn()
|
||||
async with conn.execute(
|
||||
"SELECT COUNT(*) as n FROM tenants WHERE estado = 'activo'"
|
||||
) as cur:
|
||||
row = await cur.fetchone()
|
||||
tenant_count = row["n"] if row else 0
|
||||
|
||||
seconds_since_poll: int | None = None
|
||||
if _last_poll_at:
|
||||
seconds_since_poll = int((now - _last_poll_at).total_seconds())
|
||||
|
||||
data.update({
|
||||
"tenants_activos": tenant_count,
|
||||
"last_poll": _last_poll_at.isoformat() if _last_poll_at else None,
|
||||
"last_poll_tenants": _last_poll_tenant_count,
|
||||
"seconds_since_last_poll": seconds_since_poll,
|
||||
"poll_interval_minutes": self._settings.poll_interval_minutes,
|
||||
"webhook_mode": bool(self._settings.webhook_url),
|
||||
})
|
||||
|
||||
return aiohttp.web.Response(
|
||||
text=json.dumps(data, indent=2),
|
||||
content_type="application/json",
|
||||
@@ -114,6 +163,20 @@ class HealthServer:
|
||||
)
|
||||
|
||||
async def _handle_history(self, request: aiohttp.web.Request) -> aiohttp.web.Response:
|
||||
# Este endpoint siempre requiere autenticación — contiene PII (chat_ids)
|
||||
if not self._is_authenticated(request):
|
||||
logger.warning(
|
||||
"health_history_acceso_denegado",
|
||||
ip=request.remote,
|
||||
ua=request.headers.get("User-Agent", "")[:80],
|
||||
)
|
||||
return aiohttp.web.Response(
|
||||
status=401,
|
||||
text=json.dumps({"error": "Authentication required"}),
|
||||
content_type="application/json",
|
||||
headers={"WWW-Authenticate": 'Bearer realm="pedrito-health"'},
|
||||
)
|
||||
|
||||
from database import get_conn
|
||||
conn = get_conn()
|
||||
|
||||
@@ -129,16 +192,26 @@ class HealthServer:
|
||||
) as cur:
|
||||
rows = await cur.fetchall()
|
||||
|
||||
# Enmascarar chat_ids: el consumidor puede correlacionar eventos del mismo usuario
|
||||
# pero no puede determinar la identidad real sin acceso a la DB.
|
||||
records = []
|
||||
for r in rows:
|
||||
row_dict = dict(r)
|
||||
row_dict["chat_id"] = _mask_chat_id(row_dict.get("chat_id"))
|
||||
records.append(row_dict)
|
||||
|
||||
return aiohttp.web.Response(
|
||||
text=json.dumps([dict(r) for r in rows], indent=2),
|
||||
text=json.dumps(records, indent=2),
|
||||
content_type="application/json",
|
||||
)
|
||||
|
||||
async def _handle_webhook(self, request: aiohttp.web.Request) -> aiohttp.web.Response:
|
||||
secret = request.headers.get("X-Telegram-Bot-Api-Secret-Token", "")
|
||||
if self._settings.webhook_secret and secret != self._settings.webhook_secret:
|
||||
logger.warning("webhook_token_invalido", ip=request.remote)
|
||||
return aiohttp.web.Response(status=403, text="Forbidden")
|
||||
provided = request.headers.get("X-Telegram-Bot-Api-Secret-Token", "")
|
||||
if self._settings.webhook_secret:
|
||||
if not secrets.compare_digest(provided, self._settings.webhook_secret):
|
||||
logger.warning("webhook_token_invalido", ip=request.remote)
|
||||
# Respuesta genérica — no revelar si es auth vs otro error
|
||||
return aiohttp.web.Response(status=404, text="Not Found")
|
||||
|
||||
try:
|
||||
body = await request.json()
|
||||
@@ -155,7 +228,7 @@ class HealthServer:
|
||||
"""Alerta al admin si el poller lleva más de health_alert_hours sin actualizar."""
|
||||
global _alert_sent
|
||||
while True:
|
||||
await asyncio.sleep(300) # revisar cada 5 minutos
|
||||
await asyncio.sleep(300)
|
||||
if _last_poll_at is None or _alert_sent:
|
||||
continue
|
||||
delta = datetime.now(timezone.utc) - _last_poll_at
|
||||
|
||||
Reference in New Issue
Block a user