- panel/: app FastAPI server-rendered (Jinja2), SOLO escucha en 127.0.0.1 - Seguridad v1: bcrypt (min 12 chars, sin credenciales default), sesión server-side con expiración y cookie HttpOnly+Secure+SameSite=Strict, rate-limit de login con bloqueo (5 fallos → 15 min), fichas de clientes cifradas en reposo con Fernet + PANEL_MASTER_KEY (env del VPS) - CLI: generar-llave (con advertencia de irrecuperabilidad y respaldo), crear-admin, servir - Estampar/desplegar reusan generador.nucleo tal cual (ficha descifrada solo en tmp 0600 durante el estampado); estado desde registry.json - panel/ y requirements-panel.txt excluidos de los paquetes de réplicas - 26 tests nuevos (auth en todas las rutas, bloqueo, cifrado en reposo, estampado real a tmp): 190 verdes en total Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
185 lines
7.0 KiB
Python
185 lines
7.0 KiB
Python
"""Tests de la app del panel (TestClient): auth en todo, login con bloqueo,
|
|
alta cifrada y estampado real (generador de verdad, salida a tmp)."""
|
|
|
|
import functools
|
|
|
|
import pytest
|
|
import yaml
|
|
from cryptography.fernet import Fernet
|
|
from fastapi.testclient import TestClient
|
|
|
|
import panel.app as app_mod
|
|
from generador import nucleo
|
|
from panel import db, seguridad
|
|
|
|
PASSWORD = "clave-de-admin-larga-123"
|
|
|
|
|
|
@pytest.fixture()
|
|
def cliente_http(tmp_path, monkeypatch):
|
|
monkeypatch.setenv("PANEL_DB", str(tmp_path / "panel.db"))
|
|
monkeypatch.setenv("PANEL_MASTER_KEY", Fernet.generate_key().decode())
|
|
monkeypatch.setenv("PANEL_COOKIE_SECURE", "false") # TestClient va sobre http
|
|
# replicas/ y registry a tmp — jamás el repo real
|
|
monkeypatch.setattr(app_mod, "DIR_REPLICAS", tmp_path / "replicas")
|
|
monkeypatch.setattr(nucleo, "DIR_REPLICAS", tmp_path / "replicas")
|
|
# estampado real pero permitiendo árbol sucio (desarrollo) y salida tmp
|
|
monkeypatch.setattr(
|
|
app_mod, "estampar",
|
|
functools.partial(nucleo.estampar, salida=tmp_path / "replicas", permitir_sucio=True),
|
|
)
|
|
# rate-limiter fresco por test
|
|
monkeypatch.setattr(app_mod, "limitador", seguridad.RateLimiter())
|
|
db.crear_usuario("admin", seguridad.hash_password(PASSWORD))
|
|
return TestClient(app_mod.crear_app(), follow_redirects=False)
|
|
|
|
|
|
def _login(c: TestClient) -> None:
|
|
r = c.post("/login", data={"username": "admin", "password": PASSWORD})
|
|
assert r.status_code == 303 and r.headers["location"] == "/"
|
|
|
|
|
|
DATOS_FORM = {
|
|
"slug": "cliente-panel",
|
|
"nombre_comercial": "Cliente Panel S.A.",
|
|
"marca_corta": "Panel",
|
|
"representante": "Ana Prueba",
|
|
"ubicacion": "CDMX, México",
|
|
"email_soporte": "soporte@panel.mx",
|
|
"admin_nombre": "Ana",
|
|
"admin_numero": "5512345678",
|
|
"numeros_autorizados": "5512345678",
|
|
"openai_api_key": "sk-panel-FAKE",
|
|
"google_sheet_id": "1PanelSheetFAKE",
|
|
"google_sheet_name": "Contratos",
|
|
"google_credentials_json": '{"type":"service_account","project_id":"panel-fake"}',
|
|
"conekta_private_key": "",
|
|
"evolution_api_url": "http://evolution.fake:8080",
|
|
"evolution_api_key": "evo-fake",
|
|
"base_url": "https://panel-bot.fake.mx",
|
|
"destino": "vps-propio",
|
|
}
|
|
|
|
|
|
# ── auth obligatoria en TODAS las rutas ─────────────────────────────
|
|
|
|
@pytest.mark.parametrize("metodo,ruta", [
|
|
("GET", "/"),
|
|
("GET", "/clientes/nuevo"),
|
|
("POST", "/clientes/nuevo"),
|
|
("POST", "/clientes/x/estampar"),
|
|
("POST", "/clientes/x/desplegar"),
|
|
])
|
|
def test_sin_sesion_todo_redirige_a_login(cliente_http, metodo, ruta):
|
|
r = cliente_http.request(metodo, ruta)
|
|
assert r.status_code == 303
|
|
assert r.headers["location"] == "/login"
|
|
|
|
|
|
def test_login_page_es_publica(cliente_http):
|
|
assert cliente_http.get("/login").status_code == 200
|
|
|
|
|
|
# ── login ───────────────────────────────────────────────────────────
|
|
|
|
def test_login_correcto_setea_cookie_segura(cliente_http):
|
|
r = cliente_http.post("/login", data={"username": "admin", "password": PASSWORD})
|
|
assert r.status_code == 303
|
|
set_cookie = r.headers["set-cookie"].lower()
|
|
assert "httponly" in set_cookie
|
|
assert "samesite=strict" in set_cookie
|
|
# con sesión, el index responde
|
|
assert cliente_http.get("/").status_code == 200
|
|
|
|
|
|
def test_login_incorrecto_401(cliente_http):
|
|
r = cliente_http.post("/login", data={"username": "admin", "password": "mala"})
|
|
assert r.status_code == 401
|
|
assert "incorrectos" in r.text
|
|
|
|
|
|
def test_login_bloqueado_tras_5_fallos(cliente_http):
|
|
for _ in range(5):
|
|
cliente_http.post("/login", data={"username": "admin", "password": "mala"})
|
|
r = cliente_http.post("/login", data={"username": "admin", "password": PASSWORD})
|
|
assert r.status_code == 429
|
|
assert "Demasiados intentos" in r.text
|
|
# ni siquiera la contraseña correcta entra durante el bloqueo
|
|
assert cliente_http.get("/").status_code == 303
|
|
|
|
|
|
def test_logout_invalida_la_sesion(cliente_http):
|
|
_login(cliente_http)
|
|
assert cliente_http.get("/").status_code == 200
|
|
cliente_http.post("/logout")
|
|
assert cliente_http.get("/").status_code == 303
|
|
|
|
|
|
# ── alta de cliente (cifrada) ───────────────────────────────────────
|
|
|
|
def test_alta_invalida_muestra_errores(cliente_http):
|
|
datos = dict(DATOS_FORM, slug="Slug Invalido", admin_numero="123")
|
|
_login(cliente_http)
|
|
r = cliente_http.post("/clientes/nuevo", data=datos)
|
|
assert r.status_code == 422
|
|
assert "slug inválido" in r.text
|
|
assert "numero_wa inválido" in r.text
|
|
assert db.obtener_cliente("Slug Invalido") is None
|
|
|
|
|
|
def test_alta_valida_guarda_cifrado(cliente_http):
|
|
_login(cliente_http)
|
|
r = cliente_http.post("/clientes/nuevo", data=DATOS_FORM)
|
|
assert r.status_code == 200
|
|
assert "guardado" in r.text
|
|
|
|
fila = db.obtener_cliente("cliente-panel")
|
|
blob = fila["ficha_cifrada"]
|
|
# NADA legible en reposo: ni la API key ni el sheet
|
|
assert b"sk-panel-FAKE" not in blob
|
|
assert b"1PanelSheetFAKE" not in blob
|
|
# y descifra al YAML exacto
|
|
ficha = yaml.safe_load(seguridad.descifrar_ficha(blob))
|
|
assert ficha["credenciales"]["openai_api_key"] == "sk-panel-FAKE"
|
|
assert ficha["cliente"]["slug"] == "cliente-panel"
|
|
|
|
|
|
# ── estampar / desplegar ────────────────────────────────────────────
|
|
|
|
def test_estampar_desde_panel_genera_paquete_real(cliente_http, tmp_path):
|
|
_login(cliente_http)
|
|
cliente_http.post("/clientes/nuevo", data=DATOS_FORM)
|
|
r = cliente_http.post("/clientes/cliente-panel/estampar")
|
|
assert r.status_code == 200
|
|
assert "estampada" in r.text
|
|
|
|
paquete = tmp_path / "replicas" / "cliente-panel"
|
|
assert (paquete / ".env").exists()
|
|
env = (paquete / ".env").read_text()
|
|
assert "BOT_BRAND_NAME=Cliente Panel S.A." in env
|
|
assert "REDIS_PREFIX=cliente-panel:" in env
|
|
assert not (paquete / "Plantilla_WK2.docm").exists()
|
|
assert not (paquete / "panel").exists() # el panel NO viaja
|
|
# el índice ahora muestra la réplica estampada
|
|
assert "estampada" in cliente_http.get("/").text
|
|
|
|
|
|
def test_estampar_cliente_inexistente_404(cliente_http):
|
|
_login(cliente_http)
|
|
assert cliente_http.post("/clientes/nadie/estampar").status_code == 404
|
|
|
|
|
|
def test_desplegar_sin_estampar_404(cliente_http):
|
|
_login(cliente_http)
|
|
cliente_http.post("/clientes/nuevo", data=DATOS_FORM)
|
|
assert cliente_http.post("/clientes/cliente-panel/desplegar").status_code == 404
|
|
|
|
|
|
def test_slug_duplicado_al_estampar_error_claro(cliente_http):
|
|
_login(cliente_http)
|
|
cliente_http.post("/clientes/nuevo", data=DATOS_FORM)
|
|
cliente_http.post("/clientes/cliente-panel/estampar")
|
|
r = cliente_http.post("/clientes/cliente-panel/estampar")
|
|
assert r.status_code == 500
|
|
assert "Ya existe la carpeta" in r.text
|