"""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 # ── dockerización: /health público y --host parametrizado ─────────── def test_health_es_publico_y_no_expone_nada(cliente_http): r = cliente_http.get("/health") # sin sesión assert r.status_code == 200 assert r.json() == {"status": "ok"} def test_servir_pasa_host_y_puerto_a_uvicorn(monkeypatch, tmp_path): import sys import types from panel.__main__ import main monkeypatch.setenv("PANEL_MASTER_KEY", "x" * 44) llamadas = {} fake_uvicorn = types.SimpleNamespace( run=lambda app, host, port: llamadas.update(app=app, host=host, port=port) ) monkeypatch.setitem(sys.modules, "uvicorn", fake_uvicorn) # default: loopback (uso bare-metal) assert main(["servir"]) == 0 assert llamadas == {"app": "panel.app:app", "host": "127.0.0.1", "port": 8090} # contenedor: 0.0.0.0 explícito assert main(["servir", "--host", "0.0.0.0", "--puerto", "8090"]) == 0 assert llamadas["host"] == "0.0.0.0" def test_servir_sin_llave_maestra_falla_claro(monkeypatch, capsys): from panel.__main__ import main monkeypatch.delenv("PANEL_MASTER_KEY", raising=False) assert main(["servir"]) == 1 assert "generar-llave" in capsys.readouterr().err