From 5d8a6358ed046906db244c858be0eb4be8197520 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorem=20Ju=C3=A1rez?= Date: Mon, 20 Jul 2026 19:38:32 -0600 Subject: [PATCH] =?UTF-8?q?feat(panel):=20panel=20madre=20v1=20=E2=80=94?= =?UTF-8?q?=20alta=20de=20clientes=20cifrada=20+=20estampado/despliegue=20?= =?UTF-8?q?(Etapa=203)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- .gitignore | 5 + generador/nucleo.py | 2 + panel/README.md | 87 +++++++++ panel/__init__.py | 14 ++ panel/__main__.py | 87 +++++++++ panel/app.py | 287 +++++++++++++++++++++++++++++ panel/db.py | 134 ++++++++++++++ panel/plantillas/base.html | 46 +++++ panel/plantillas/cliente_form.html | 100 ++++++++++ panel/plantillas/index.html | 53 ++++++ panel/plantillas/login.html | 15 ++ panel/seguridad.py | 137 ++++++++++++++ requirements-panel.txt | 5 + tests/test_panel_app.py | 184 ++++++++++++++++++ tests/test_panel_seguridad.py | 127 +++++++++++++ 15 files changed, 1283 insertions(+) create mode 100644 panel/README.md create mode 100644 panel/__init__.py create mode 100644 panel/__main__.py create mode 100644 panel/app.py create mode 100644 panel/db.py create mode 100644 panel/plantillas/base.html create mode 100644 panel/plantillas/cliente_form.html create mode 100644 panel/plantillas/index.html create mode 100644 panel/plantillas/login.html create mode 100644 panel/seguridad.py create mode 100644 requirements-panel.txt create mode 100644 tests/test_panel_app.py create mode 100644 tests/test_panel_seguridad.py diff --git a/.gitignore b/.gitignore index 28336e0..8d37a64 100644 --- a/.gitignore +++ b/.gitignore @@ -22,5 +22,10 @@ fichas/* generador/central.yml *.tar.gz +# Panel madre — base con fichas cifradas y su .env +panel/panel.db +panel/*.db +panel/.env + # OS .DS_Store diff --git a/generador/nucleo.py b/generador/nucleo.py index b6add85..72d0d01 100644 --- a/generador/nucleo.py +++ b/generador/nucleo.py @@ -34,6 +34,8 @@ EXCLUIR_DEL_PAQUETE = [ "generador", "fichas", "replicas", + "panel", # el panel madre es del VPS, no de las réplicas + "requirements-panel.txt", ] diff --git a/panel/README.md b/panel/README.md new file mode 100644 index 0000000..27eb83d --- /dev/null +++ b/panel/README.md @@ -0,0 +1,87 @@ +# Panel madre del generador de réplicas + +App para el VPS: alta de clientes (fichas **cifradas en reposo**) y +estampado/despliegue de réplicas invocando el generador de Etapa 2. + +## Puesta en marcha (una vez) + +```bash +cd wk-bot-plantilla +.venv/bin/pip install -r requirements.txt -r requirements-panel.txt + +# 1. Llave maestra — UNA SOLA VEZ +.venv/bin/python -m panel generar-llave +``` + +> ⚠️ **PANEL_MASTER_KEY es irrecuperable si se pierde.** Cifra todas las +> fichas de clientes; sin ella no hay manera de descifrarlas (ni "reset"). +> Guárdala en el entorno del VPS (archivo con `chmod 600`) **y respáldala +> fuera del VPS** en un gestor de contraseñas. Nunca en git ni en la base. + +```bash +# 2. Ponla en el entorno (ejemplo con archivo de entorno) +install -m 600 /dev/null /etc/panel-generador.env +echo 'PANEL_MASTER_KEY=' >> /etc/panel-generador.env + +# 3. Usuario admin (contraseña mínimo 12 chars; se guarda solo el hash bcrypt) +.venv/bin/python -m panel crear-admin + +# 4. Servir (SOLO escucha en 127.0.0.1) +set -a; source /etc/panel-generador.env; set +a +.venv/bin/python -m panel servir --puerto 8090 +``` + +## Exposición segura (obligatoria) + +El panel **solo escucha en loopback**; la única entrada es tu reverse proxy +con HTTPS. Ejemplo nginx: + +```nginx +server { + listen 443 ssl; + server_name panel.midominio.com; + # ... certificados ... + + # Opcional pero recomendado: restringe por IP + allow 187.xxx.xxx.xxx; # tu IP + deny all; + + location / { + proxy_pass http://127.0.0.1:8090; + proxy_set_header X-Forwarded-Proto https; + } +} +``` + +Sin proxy HTTPS **no** expongas el puerto: la cookie de sesión lleva +`Secure` y no funcionará sobre HTTP plano (a propósito). + +## Seguridad implementada + +| Capa | Mecanismo | +|---|---| +| Contraseña admin | bcrypt (solo hash en la base); mínimo 12 caracteres | +| Sesión | token aleatorio; en la base solo su SHA-256; expira (`PANEL_SESSION_HORAS`, default 8h); cookie HttpOnly+Secure+SameSite=Strict; nada de tokens en URL | +| Login | rate-limit por IP: 5 fallos en 5 min → bloqueo 15 min | +| Fichas de clientes | Fernet (AES+HMAC) con `PANEL_MASTER_KEY`; descifradas SOLO el instante del estampado (tmp 0600 borrado en finally) | +| Base | `panel.db` chmod 600, gitignored | +| Red | uvicorn en 127.0.0.1; HTTPS y allowlist en el proxy | + +## Variables de entorno + +| Variable | Qué es | Default | +|---|---|---| +| `PANEL_MASTER_KEY` | Llave Fernet (obligatoria; ver advertencia) | — | +| `PANEL_DB` | Ruta de la base | `panel/panel.db` | +| `PANEL_SESSION_HORAS` | Expiración de sesión | `8` | +| `PANEL_COOKIE_SECURE` | `false` SOLO para desarrollo sin HTTPS | `true` | + +## Qué hace cada botón + +- **Guardar cliente** — valida con `generador.ficha` (la misma validación + del CLI) y guarda la ficha YAML cifrada en SQLite. +- **Estampar** — descifra → `generador.nucleo.estampar()` (solo-generar): + produce `replicas//` con sus 7 checks. No levanta nada. +- **Desplegar** — `desplegar_paquete()` en segundo plano (build + healthcheck); + el estado se lee de `replicas/registry.json` (el generador es la fuente + de verdad; el panel no lo duplica). diff --git a/panel/__init__.py b/panel/__init__.py new file mode 100644 index 0000000..8a7080c --- /dev/null +++ b/panel/__init__.py @@ -0,0 +1,14 @@ +"""Panel madre del generador de réplicas. + +App NUEVA que USA el generador (Etapa 2) como librería; no lo modifica. +Un solo admin en v1, estructura lista para más usuarios. + +Seguridad v1 (no negociable): +- Login con bcrypt; sesión server-side con expiración; cookie HttpOnly. +- Fichas de clientes CIFRADAS en reposo (Fernet + PANEL_MASTER_KEY). +- Escucha solo en 127.0.0.1; se expone únicamente vía reverse proxy HTTPS. + +CLI: python -m panel generar-llave | crear-admin | servir +""" + +VERSION = "0.1.0" diff --git a/panel/__main__.py b/panel/__main__.py new file mode 100644 index 0000000..c0bd1a8 --- /dev/null +++ b/panel/__main__.py @@ -0,0 +1,87 @@ +"""CLI del panel. + + python -m panel generar-llave # PANEL_MASTER_KEY (UNA vez; respáldala) + python -m panel crear-admin # crea/actualiza el usuario admin + python -m panel servir # levanta el panel en 127.0.0.1 +""" + +import argparse +import getpass +import sys + + +def cmd_generar_llave(_args) -> int: + from cryptography.fernet import Fernet + + llave = Fernet.generate_key().decode() + print("PANEL_MASTER_KEY=" + llave) + print() + print("⚠️ ADVERTENCIA — lee esto completo:") + print(" 1. Genera esta llave UNA SOLA VEZ y ponla en el entorno del VPS") + print(" (ej. /etc/panel-generador.env con chmod 600, o el .env del panel).") + print(" 2. RESPÁLDALA en un lugar seguro FUERA del VPS (gestor de") + print(" contraseñas). Si se pierde, las fichas cifradas de TODOS los") + print(" clientes son IRRECUPERABLES: no hay reset ni recuperación.") + print(" 3. Nunca la commitees ni la pongas en el código o la base.") + return 0 + + +def cmd_crear_admin(args) -> int: + from panel import db, seguridad + + username = args.username or input("Usuario admin: ").strip() + if not username: + print("Usuario vacío.", file=sys.stderr) + return 1 + password = getpass.getpass("Contraseña: ") + if len(password) < 12: + print("Contraseña demasiado corta (mínimo 12 caracteres).", file=sys.stderr) + return 1 + if getpass.getpass("Repítela: ") != password: + print("No coinciden.", file=sys.stderr) + return 1 + hash_ = seguridad.hash_password(password) + if db.obtener_usuario(username): + db.actualizar_password(username, hash_) + print(f"Contraseña de '{username}' actualizada.") + else: + db.crear_usuario(username, hash_) + print(f"Usuario '{username}' creado.") + return 0 + + +def cmd_servir(args) -> int: + import os + + import uvicorn + + if not os.getenv("PANEL_MASTER_KEY"): + print("Falta PANEL_MASTER_KEY en el entorno. Génerala con:", file=sys.stderr) + print(" python -m panel generar-llave", file=sys.stderr) + return 1 + # SOLO loopback: la única entrada pública es el reverse proxy con HTTPS. + uvicorn.run("panel.app:app", host="127.0.0.1", port=args.puerto) + return 0 + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(prog="panel", description=__doc__) + sub = parser.add_subparsers(dest="comando", required=True) + + p = sub.add_parser("generar-llave", help="genera PANEL_MASTER_KEY (una sola vez)") + p.set_defaults(fn=cmd_generar_llave) + + p = sub.add_parser("crear-admin", help="crea o actualiza el usuario admin") + p.add_argument("--username", help="nombre de usuario (si no, lo pregunta)") + p.set_defaults(fn=cmd_crear_admin) + + p = sub.add_parser("servir", help="levanta el panel (solo 127.0.0.1)") + p.add_argument("--puerto", type=int, default=8090) + p.set_defaults(fn=cmd_servir) + + args = parser.parse_args(argv) + return args.fn(args) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/panel/app.py b/panel/app.py new file mode 100644 index 0000000..01b58da --- /dev/null +++ b/panel/app.py @@ -0,0 +1,287 @@ +"""App FastAPI del panel madre. + +Toda ruta exige sesión salvo /login. Las fichas se guardan CIFRADAS y solo +se descifran el instante del estampado (archivo temporal 0600 que se borra +en el finally). El estampado/despliegue reusa generador.nucleo tal cual. +""" + +import logging +import os +import tempfile +from pathlib import Path + +import yaml +from fastapi import BackgroundTasks, Depends, FastAPI, Form, Request +from fastapi.responses import HTMLResponse, RedirectResponse +from fastapi.templating import Jinja2Templates + +from generador.ficha import cargar_ficha +from generador.nucleo import DIR_REPLICAS, ErrorEstampado, desplegar_paquete, estampar +from generador.registro import ErrorRegistro, Registro +from panel import db, seguridad + +logger = logging.getLogger(__name__) + +plantillas = Jinja2Templates(directory=str(Path(__file__).parent / "plantillas")) +limitador = seguridad.RateLimiter() + +COOKIE = "panel_sesion" + + +def _cookie_segura() -> bool: + # SOLO false para desarrollo local/tests sin HTTPS. En el VPS (detrás + # del proxy HTTPS) debe quedarse en true. + return os.getenv("PANEL_COOKIE_SECURE", "true").lower() != "false" + + +class NoAutenticado(Exception): + pass + + +def usuario_actual(request: Request) -> str: + sesion = seguridad.validar_sesion(request.cookies.get(COOKIE)) + if not sesion: + raise NoAutenticado() + return sesion["username"] + + +def crear_app() -> FastAPI: + app = FastAPI(title="Panel generador", docs_url=None, redoc_url=None, openapi_url=None) + + @app.exception_handler(NoAutenticado) + async def _redirigir_login(request: Request, exc: NoAutenticado): + return RedirectResponse("/login", status_code=303) + + # ── login / logout ────────────────────────────────────────────── + + @app.get("/login", response_class=HTMLResponse) + async def login_form(request: Request): + return plantillas.TemplateResponse( + request, "login.html", {"usuario": None, "error": None} + ) + + @app.post("/login") + async def login(request: Request, username: str = Form(...), password: str = Form(...)): + ip = request.client.host if request.client else "?" + permitido, espera = limitador.permitido(ip) + if not permitido: + return plantillas.TemplateResponse( + request, "login.html", + {"usuario": None, + "error": f"Demasiados intentos fallidos. Reintenta en {espera // 60 + 1} min."}, + status_code=429, + ) + usuario = db.obtener_usuario(username.strip()) + if not usuario or not seguridad.verificar_password(password, usuario["password_hash"]): + limitador.registrar_fallo(ip) + logger.warning("Login fallido para %r desde %s", username, ip) + return plantillas.TemplateResponse( + request, "login.html", + {"usuario": None, "error": "Usuario o contraseña incorrectos."}, + status_code=401, + ) + limitador.registrar_exito(ip) + token = seguridad.crear_sesion(usuario["id"]) + resp = RedirectResponse("/", status_code=303) + resp.set_cookie( + COOKIE, token, + httponly=True, samesite="strict", secure=_cookie_segura(), + max_age=seguridad.SESSION_HORAS * 3600, path="/", + ) + return resp + + @app.post("/logout") + async def logout(request: Request): + seguridad.cerrar_sesion(request.cookies.get(COOKIE)) + resp = RedirectResponse("/login", status_code=303) + resp.delete_cookie(COOKIE, path="/") + return resp + + # ── listado ───────────────────────────────────────────────────── + + def _contexto_index(request, usuario, mensaje=None, error=None): + replicas = {} + try: + replicas = Registro(DIR_REPLICAS / "registry.json").listar() + except ErrorRegistro as e: + error = (error + "\n" if error else "") + f"registry.json ilegible: {e}" + clientes = [ + {"slug": c["slug"], "nombre": c["nombre"], "replica": replicas.get(c["slug"])} + for c in db.listar_clientes() + ] + return {"usuario": usuario, "clientes": clientes, "mensaje": mensaje, "error": error} + + @app.get("/", response_class=HTMLResponse) + async def index(request: Request, usuario: str = Depends(usuario_actual)): + return plantillas.TemplateResponse(request, "index.html", _contexto_index(request, usuario)) + + # ── alta de cliente ───────────────────────────────────────────── + + CAMPOS = [ + "slug", "nombre_comercial", "marca_corta", "representante", "ubicacion", + "email_soporte", "admin_nombre", "admin_numero", "numeros_autorizados", + "openai_api_key", "google_sheet_id", "google_sheet_name", + "google_credentials_json", "conekta_private_key", + "evolution_api_url", "evolution_api_key", "base_url", "destino", + ] + + def _ficha_desde_form(v: dict) -> dict: + autorizados = [n.strip() for n in (v.get("numeros_autorizados") or "").split(",") if n.strip()] + return { + "cliente": { + "slug": v.get("slug", "").strip(), + "nombre_comercial": v.get("nombre_comercial", "").strip(), + "marca_corta": v.get("marca_corta", "").strip(), + "representante": v.get("representante", "").strip(), + "ubicacion": v.get("ubicacion", "").strip(), + "email_soporte": v.get("email_soporte", "").strip(), + }, + "admin": { + "nombre": v.get("admin_nombre", "").strip() or "Admin", + "numero_wa": v.get("admin_numero", "").strip(), + "numeros_autorizados": autorizados or [v.get("admin_numero", "").strip()], + "require_authorization": True, + }, + "credenciales": { + "openai_api_key": v.get("openai_api_key", "").strip(), + "google_sheet_id": v.get("google_sheet_id", "").strip(), + "google_sheet_name": v.get("google_sheet_name", "").strip() or "Contratos", + "google_credentials_json": v.get("google_credentials_json", "").strip(), + "conekta_private_key": v.get("conekta_private_key", "").strip(), + }, + "evolution": { + "api_url": v.get("evolution_api_url", "").strip(), + "api_key": v.get("evolution_api_key", "").strip(), + }, + "despliegue": { + "base_url": v.get("base_url", "").strip(), + "destino": v.get("destino", "").strip() or "vps-propio", + }, + } + + @app.get("/clientes/nuevo", response_class=HTMLResponse) + async def cliente_nuevo_form(request: Request, usuario: str = Depends(usuario_actual)): + return plantillas.TemplateResponse( + request, "cliente_form.html", {"usuario": usuario, "errores": None, "v": {}} + ) + + @app.post("/clientes/nuevo", response_class=HTMLResponse) + async def cliente_nuevo(request: Request, usuario: str = Depends(usuario_actual)): + form = await request.form() + v = {c: str(form.get(c) or "") for c in CAMPOS} + ficha_dict = _ficha_desde_form(v) + ficha_yaml = yaml.safe_dump(ficha_dict, allow_unicode=True, sort_keys=False) + + # Reusa la validación REAL del generador (misma que el CLI). + errores = _validar_yaml(ficha_yaml) + if errores: + return plantillas.TemplateResponse( + request, "cliente_form.html", + {"usuario": usuario, "errores": errores, "v": v}, status_code=422, + ) + slug = ficha_dict["cliente"]["slug"] + db.guardar_cliente(slug, ficha_dict["cliente"]["nombre_comercial"], + seguridad.cifrar_ficha(ficha_yaml)) + logger.info("Cliente %s guardado (ficha cifrada)", slug) + return plantillas.TemplateResponse( + request, "index.html", + _contexto_index(request, usuario, + mensaje=f"Cliente '{slug}' guardado (ficha cifrada). " + "Usa «Estampar» para generar su paquete."), + ) + + # ── estampar / desplegar ──────────────────────────────────────── + + @app.post("/clientes/{slug}/estampar", response_class=HTMLResponse) + async def estampar_cliente(request: Request, slug: str, usuario: str = Depends(usuario_actual)): + fila = db.obtener_cliente(slug) + if not fila: + return plantillas.TemplateResponse( + request, "index.html", + _contexto_index(request, usuario, error=f"No existe el cliente '{slug}'."), + status_code=404, + ) + try: + resultado = _estampar_cifrada(fila["ficha_cifrada"]) + except (ErrorEstampado, ErrorRegistro, seguridad.ErrorLlaveMaestra) as e: + return plantillas.TemplateResponse( + request, "index.html", + _contexto_index(request, usuario, error=f"Estampado de '{slug}' falló:\n{e}"), + status_code=500, + ) + detalle = "\n".join( + f"{'✅' if c.ok else '❌'} {c.nombre}" for c in resultado.checks + ) + return plantillas.TemplateResponse( + request, "index.html", + _contexto_index(request, usuario, + mensaje=f"Réplica '{slug}' → {resultado.estado} " + f"(puerto {resultado.puerto}).\n{detalle}"), + ) + + @app.post("/clientes/{slug}/desplegar", response_class=HTMLResponse) + async def desplegar_cliente(request: Request, slug: str, tareas: BackgroundTasks, + usuario: str = Depends(usuario_actual)): + registro = Registro(DIR_REPLICAS / "registry.json") + entrada = registro.listar().get(slug) + if not entrada: + return plantillas.TemplateResponse( + request, "index.html", + _contexto_index(request, usuario, + error=f"'{slug}' no está estampada aún."), + status_code=404, + ) + tareas.add_task(_desplegar_fondo, slug, entrada["puerto"]) + return plantillas.TemplateResponse( + request, "index.html", + _contexto_index(request, usuario, + mensaje=f"Desplegando '{slug}' en segundo plano " + "(el build inicial tarda varios minutos). " + "Recarga para ver el estado."), + ) + + return app + + +# ── helpers de estampado (fuera de crear_app para poder testearlos) ── + +def _validar_yaml(ficha_yaml: str) -> list[str]: + """Valida una ficha YAML con generador.ficha (que consume rutas).""" + with tempfile.NamedTemporaryFile("w", suffix=".yml", delete=False) as tmp: + tmp.write(ficha_yaml) + ruta = tmp.name + try: + _, errores = cargar_ficha(ruta) + return errores + finally: + os.unlink(ruta) + + +def _estampar_cifrada(ficha_cifrada: bytes): + """Descifra la ficha SOLO durante el estampado (tmp 0600, borrado al final).""" + ficha_yaml = seguridad.descifrar_ficha(ficha_cifrada) + fd, ruta = tempfile.mkstemp(suffix=".yml") + try: + os.fchmod(fd, 0o600) + with os.fdopen(fd, "w") as f: + f.write(ficha_yaml) + return estampar(ruta) + finally: + os.unlink(ruta) + + +def _desplegar_fondo(slug: str, puerto: int) -> None: + registro = Registro(DIR_REPLICAS / "registry.json") + try: + desplegar_paquete(DIR_REPLICAS / slug, puerto) + registro.actualizar(slug, estado="desplegada") + logger.info("Réplica %s desplegada", slug) + except (ErrorEstampado, ErrorRegistro): + logger.exception("Despliegue de %s falló", slug) + try: + registro.actualizar(slug, estado="fallida") + except ErrorRegistro: + pass + + +app = crear_app() diff --git a/panel/db.py b/panel/db.py new file mode 100644 index 0000000..f2e9b69 --- /dev/null +++ b/panel/db.py @@ -0,0 +1,134 @@ +"""SQLite del panel: usuarios, sesiones y clientes (fichas cifradas). + +`registry.json` NO vive aquí: el estado de réplicas sigue siendo del +generador; el panel solo lo lee. +""" + +import os +import sqlite3 +from datetime import datetime, timedelta +from pathlib import Path + +_ESQUEMA = """ +CREATE TABLE IF NOT EXISTS usuarios ( + id INTEGER PRIMARY KEY, + username TEXT NOT NULL UNIQUE, + password_hash BLOB NOT NULL, + activo INTEGER NOT NULL DEFAULT 1, + creado TEXT NOT NULL +); +CREATE TABLE IF NOT EXISTS sesiones ( + token_hash TEXT PRIMARY KEY, + usuario_id INTEGER NOT NULL REFERENCES usuarios(id), + expira TEXT NOT NULL +); +CREATE TABLE IF NOT EXISTS clientes ( + id INTEGER PRIMARY KEY, + slug TEXT NOT NULL UNIQUE, + nombre TEXT NOT NULL, + ficha_cifrada BLOB NOT NULL, + creado TEXT NOT NULL, + actualizado TEXT NOT NULL +); +""" + + +def ruta_db() -> Path: + return Path(os.getenv("PANEL_DB", str(Path(__file__).parent / "panel.db"))) + + +def conectar() -> sqlite3.Connection: + ruta = ruta_db() + nueva = not ruta.exists() + con = sqlite3.connect(ruta) + con.row_factory = sqlite3.Row + con.executescript(_ESQUEMA) + if nueva: + os.chmod(ruta, 0o600) # la base guarda blobs cifrados y hashes + return con + + +def _ahora() -> str: + return datetime.now().isoformat(timespec="seconds") + + +# ── usuarios ──────────────────────────────────────────────────────── + +def crear_usuario(username: str, password_hash: bytes) -> None: + with conectar() as con: + con.execute( + "INSERT INTO usuarios (username, password_hash, creado) VALUES (?, ?, ?)", + (username, password_hash, _ahora()), + ) + + +def actualizar_password(username: str, password_hash: bytes) -> bool: + with conectar() as con: + cur = con.execute( + "UPDATE usuarios SET password_hash = ? WHERE username = ?", + (password_hash, username), + ) + return cur.rowcount > 0 + + +def obtener_usuario(username: str) -> sqlite3.Row | None: + with conectar() as con: + return con.execute( + "SELECT * FROM usuarios WHERE username = ? AND activo = 1", (username,) + ).fetchone() + + +# ── sesiones ──────────────────────────────────────────────────────── + +def guardar_sesion(token_hash: str, usuario_id: int, horas: int) -> None: + expira = (datetime.now() + timedelta(hours=horas)).isoformat(timespec="seconds") + with conectar() as con: + con.execute( + "INSERT INTO sesiones (token_hash, usuario_id, expira) VALUES (?, ?, ?)", + (token_hash, usuario_id, expira), + ) + + +def obtener_sesion(token_hash: str) -> sqlite3.Row | None: + with conectar() as con: + con.execute("DELETE FROM sesiones WHERE expira < ?", (_ahora(),)) + return con.execute( + """SELECT s.*, u.username FROM sesiones s + JOIN usuarios u ON u.id = s.usuario_id + WHERE s.token_hash = ? AND s.expira >= ? AND u.activo = 1""", + (token_hash, _ahora()), + ).fetchone() + + +def borrar_sesion(token_hash: str) -> None: + with conectar() as con: + con.execute("DELETE FROM sesiones WHERE token_hash = ?", (token_hash,)) + + +# ── clientes ──────────────────────────────────────────────────────── + +def guardar_cliente(slug: str, nombre: str, ficha_cifrada: bytes) -> None: + with conectar() as con: + con.execute( + """INSERT INTO clientes (slug, nombre, ficha_cifrada, creado, actualizado) + VALUES (?, ?, ?, ?, ?) + ON CONFLICT(slug) DO UPDATE SET + nombre = excluded.nombre, + ficha_cifrada = excluded.ficha_cifrada, + actualizado = excluded.actualizado""", + (slug, nombre, ficha_cifrada, _ahora(), _ahora()), + ) + + +def obtener_cliente(slug: str) -> sqlite3.Row | None: + with conectar() as con: + return con.execute( + "SELECT * FROM clientes WHERE slug = ?", (slug,) + ).fetchone() + + +def listar_clientes() -> list[sqlite3.Row]: + with conectar() as con: + return con.execute( + "SELECT slug, nombre, creado, actualizado FROM clientes ORDER BY slug" + ).fetchall() diff --git a/panel/plantillas/base.html b/panel/plantillas/base.html new file mode 100644 index 0000000..3f24be7 --- /dev/null +++ b/panel/plantillas/base.html @@ -0,0 +1,46 @@ + + + + + +{% block titulo %}Panel generador{% endblock %} + + + +
+ ⚙️ Panel generador de réplicas + {% if usuario %} + {{ usuario }} · +
+
+ {% endif %} +
+
{% block cuerpo %}{% endblock %}
+ + diff --git a/panel/plantillas/cliente_form.html b/panel/plantillas/cliente_form.html new file mode 100644 index 0000000..e73ee52 --- /dev/null +++ b/panel/plantillas/cliente_form.html @@ -0,0 +1,100 @@ +{% extends "base.html" %} +{% block titulo %}Nuevo cliente · Panel generador{% endblock %} +{% block cuerpo %} +
+

Alta de cliente

+ {% if errores %}
{{ errores | join("\n") }}
{% endif %} +
+

Identidad

+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +

Admin y autorización

+
+
+ + +
+
+ + +
+
+ + + +

Credenciales

+ + +
+
+ + +
+
+ + +
+
+ + + + + +

Evolution y despliegue

+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +

+ + +

+
+
+{% endblock %} diff --git a/panel/plantillas/index.html b/panel/plantillas/index.html new file mode 100644 index 0000000..8e1b13b --- /dev/null +++ b/panel/plantillas/index.html @@ -0,0 +1,53 @@ +{% extends "base.html" %} +{% block titulo %}Clientes · Panel generador{% endblock %} +{% block cuerpo %} +{% if mensaje %}
{{ mensaje }}
{% endif %} +{% if error %}
{{ error }}
{% endif %} + +
+

Clientes y réplicas

+ {% if clientes %} + + + {% for c in clientes %} + + + + + + + + {% endfor %} +
SlugClienteRéplicaPuertoAcciones
{{ c.slug }}{{ c.nombre }} + {% if c.replica %} + {{ c.replica.estado }} + {% else %} + sin estampar + {% endif %} + {{ c.replica.puerto if c.replica else "—" }} + {% if not c.replica %} +
+ +
+ {% elif c.replica.estado == "estampada" %} +
+ +
+ {% elif c.replica.estado == "fallida" %} +
+ +
+ {% else %} + en {{ c.replica.destino }} + {% endif %} +
+ {% else %} +

Aún no hay clientes. Da de alta el primero.

+ {% endif %} +

+
+ +

El estado de réplicas viene de replicas/registry.json (el generador es la +fuente de verdad). «Desplegar» levanta la réplica en este VPS; los paquetes portables se +entregan con su README-ARRANQUE.md.

+{% endblock %} diff --git a/panel/plantillas/login.html b/panel/plantillas/login.html new file mode 100644 index 0000000..58ca79d --- /dev/null +++ b/panel/plantillas/login.html @@ -0,0 +1,15 @@ +{% extends "base.html" %} +{% block titulo %}Entrar · Panel generador{% endblock %} +{% block cuerpo %} +
+

Entrar

+ {% if error %}
{{ error }}
{% endif %} +
+ + + + +

+
+
+{% endblock %} diff --git a/panel/seguridad.py b/panel/seguridad.py new file mode 100644 index 0000000..e690269 --- /dev/null +++ b/panel/seguridad.py @@ -0,0 +1,137 @@ +"""Seguridad del panel: bcrypt, cifrado Fernet de fichas, sesiones y +rate-limit del login con bloqueo tras intentos fallidos. + +La llave maestra (PANEL_MASTER_KEY) vive SOLO en el entorno del VPS. +⚠️ Si se pierde, las fichas cifradas son IRRECUPERABLES: respáldala. +""" + +import hashlib +import os +import secrets +import time + +import bcrypt +from cryptography.fernet import Fernet, InvalidToken + +from panel import db + +SESSION_HORAS = int(os.getenv("PANEL_SESSION_HORAS", "8")) + +# Rate-limit del login: tras MAX_FALLOS fallidos en VENTANA_S, la IP queda +# bloqueada BLOQUEO_S segundos. En memoria (el panel es un solo proceso). +MAX_FALLOS = 5 +VENTANA_S = 300 +BLOQUEO_S = 900 + + +class ErrorLlaveMaestra(Exception): + pass + + +# ── contraseñas ───────────────────────────────────────────────────── + +def hash_password(password: str) -> bytes: + return bcrypt.hashpw(password.encode(), bcrypt.gensalt()) + + +def verificar_password(password: str, password_hash: bytes) -> bool: + try: + return bcrypt.checkpw(password.encode(), password_hash) + except (ValueError, TypeError): + return False + + +# ── cifrado de fichas ─────────────────────────────────────────────── + +def _fernet() -> Fernet: + llave = os.getenv("PANEL_MASTER_KEY", "") + if not llave: + raise ErrorLlaveMaestra( + "Falta PANEL_MASTER_KEY en el entorno. Génerala UNA sola vez con " + "`python -m panel generar-llave` y respáldala: sin ella, las " + "fichas cifradas son irrecuperables." + ) + try: + return Fernet(llave.encode()) + except (ValueError, TypeError) as e: + raise ErrorLlaveMaestra(f"PANEL_MASTER_KEY inválida: {e}") from e + + +def cifrar_ficha(ficha_yaml: str) -> bytes: + return _fernet().encrypt(ficha_yaml.encode()) + + +def descifrar_ficha(blob: bytes) -> str: + try: + return _fernet().decrypt(blob).decode() + except InvalidToken as e: + raise ErrorLlaveMaestra( + "No se pudo descifrar la ficha: PANEL_MASTER_KEY no corresponde " + "a la llave con la que se cifró (¿llave rotada o equivocada?)." + ) from e + + +# ── sesiones ──────────────────────────────────────────────────────── + +def _hash_token(token: str) -> str: + return hashlib.sha256(token.encode()).hexdigest() + + +def crear_sesion(usuario_id: int) -> str: + token = secrets.token_urlsafe(32) + db.guardar_sesion(_hash_token(token), usuario_id, SESSION_HORAS) + return token + + +def validar_sesion(token: str | None): + """Devuelve la fila de sesión (con username) o None.""" + if not token: + return None + return db.obtener_sesion(_hash_token(token)) + + +def cerrar_sesion(token: str | None) -> None: + if token: + db.borrar_sesion(_hash_token(token)) + + +# ── rate-limit del login ──────────────────────────────────────────── + +class RateLimiter: + """Bloqueo por IP tras varios intentos fallidos. + + - permitido(ip) → (True, 0) o (False, segundos_para_reintentar) + - registrar_fallo(ip): cuenta el fallo; al llegar a MAX_FALLOS bloquea. + - registrar_exito(ip): limpia el historial de esa IP. + """ + + def __init__(self, max_fallos=MAX_FALLOS, ventana_s=VENTANA_S, + bloqueo_s=BLOQUEO_S, reloj=time.monotonic): + self.max_fallos = max_fallos + self.ventana_s = ventana_s + self.bloqueo_s = bloqueo_s + self._reloj = reloj + self._fallos: dict[str, list[float]] = {} + self._bloqueadas: dict[str, float] = {} + + def permitido(self, ip: str) -> tuple[bool, int]: + ahora = self._reloj() + hasta = self._bloqueadas.get(ip) + if hasta is not None: + if ahora < hasta: + return False, int(hasta - ahora) + 1 + del self._bloqueadas[ip] + self._fallos.pop(ip, None) + return True, 0 + + def registrar_fallo(self, ip: str) -> None: + ahora = self._reloj() + historial = [t for t in self._fallos.get(ip, []) if ahora - t < self.ventana_s] + historial.append(ahora) + self._fallos[ip] = historial + if len(historial) >= self.max_fallos: + self._bloqueadas[ip] = ahora + self.bloqueo_s + + def registrar_exito(self, ip: str) -> None: + self._fallos.pop(ip, None) + self._bloqueadas.pop(ip, None) diff --git a/requirements-panel.txt b/requirements-panel.txt new file mode 100644 index 0000000..cf00b83 --- /dev/null +++ b/requirements-panel.txt @@ -0,0 +1,5 @@ +# Dependencias del PANEL madre (no van en las réplicas ni en el bot). +# pip install -r requirements.txt -r requirements-panel.txt +bcrypt==4.2.0 +cryptography==43.0.1 +jinja2==3.1.4 diff --git a/tests/test_panel_app.py b/tests/test_panel_app.py new file mode 100644 index 0000000..1e5edc4 --- /dev/null +++ b/tests/test_panel_app.py @@ -0,0 +1,184 @@ +"""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 diff --git a/tests/test_panel_seguridad.py b/tests/test_panel_seguridad.py new file mode 100644 index 0000000..caade7b --- /dev/null +++ b/tests/test_panel_seguridad.py @@ -0,0 +1,127 @@ +"""Tests de la capa de seguridad del panel: bcrypt, Fernet, sesiones y +rate-limit con bloqueo.""" + +import pytest +from cryptography.fernet import Fernet + +from panel import db, seguridad +from panel.seguridad import RateLimiter + + +@pytest.fixture(autouse=True) +def entorno(tmp_path, monkeypatch): + monkeypatch.setenv("PANEL_DB", str(tmp_path / "panel.db")) + monkeypatch.setenv("PANEL_MASTER_KEY", Fernet.generate_key().decode()) + + +# ── contraseñas ───────────────────────────────────────────────────── + +def test_password_hash_y_verificacion(): + h = seguridad.hash_password("secreta-muy-larga-123") + assert h != b"secreta-muy-larga-123" + assert h.startswith(b"$2b$") # bcrypt, nunca texto plano + assert seguridad.verificar_password("secreta-muy-larga-123", h) + assert not seguridad.verificar_password("otra", h) + assert not seguridad.verificar_password("otra", b"basura-no-hash") + + +# ── cifrado de fichas ─────────────────────────────────────────────── + +def test_ficha_cifrada_roundtrip(): + yaml_ficha = "cliente:\n slug: x\ncredenciales:\n openai_api_key: sk-SECRETO\n" + blob = seguridad.cifrar_ficha(yaml_ficha) + assert b"sk-SECRETO" not in blob # nada legible en reposo + assert seguridad.descifrar_ficha(blob) == yaml_ficha + + +def test_llave_equivocada_error_claro(monkeypatch): + blob = seguridad.cifrar_ficha("cliente: {}") + monkeypatch.setenv("PANEL_MASTER_KEY", Fernet.generate_key().decode()) + with pytest.raises(seguridad.ErrorLlaveMaestra, match="no corresponde"): + seguridad.descifrar_ficha(blob) + + +def test_sin_llave_error_con_instrucciones(monkeypatch): + monkeypatch.delenv("PANEL_MASTER_KEY") + with pytest.raises(seguridad.ErrorLlaveMaestra, match="generar-llave"): + seguridad.cifrar_ficha("x") + + +# ── sesiones ──────────────────────────────────────────────────────── + +def test_sesion_crear_validar_cerrar(): + db.crear_usuario("admin", seguridad.hash_password("clave-larga-123")) + usuario = db.obtener_usuario("admin") + token = seguridad.crear_sesion(usuario["id"]) + assert len(token) >= 40 + sesion = seguridad.validar_sesion(token) + assert sesion["username"] == "admin" + # en la base NO está el token, solo su hash + with db.conectar() as con: + fila = con.execute("SELECT token_hash FROM sesiones").fetchone() + assert fila["token_hash"] != token + seguridad.cerrar_sesion(token) + assert seguridad.validar_sesion(token) is None + assert seguridad.validar_sesion(None) is None + assert seguridad.validar_sesion("token-inventado") is None + + +def test_sesion_expirada_no_valida(): + db.crear_usuario("admin", seguridad.hash_password("clave-larga-123")) + usuario = db.obtener_usuario("admin") + token = seguridad.crear_sesion(usuario["id"]) + with db.conectar() as con: # simular expiración + con.execute("UPDATE sesiones SET expira = '2000-01-01T00:00:00'") + assert seguridad.validar_sesion(token) is None + + +# ── rate-limit con bloqueo ────────────────────────────────────────── + +def test_rate_limit_bloquea_tras_max_fallos(): + reloj = [0.0] + rl = RateLimiter(max_fallos=5, ventana_s=300, bloqueo_s=900, reloj=lambda: reloj[0]) + + for _ in range(4): + rl.registrar_fallo("1.2.3.4") + assert rl.permitido("1.2.3.4") == (True, 0) # 4 fallos: aún permitido + rl.registrar_fallo("1.2.3.4") # 5º fallo → bloqueo + permitido, espera = rl.permitido("1.2.3.4") + assert not permitido and 0 < espera <= 901 # redondea hacia arriba + # otra IP no está afectada + assert rl.permitido("5.6.7.8") == (True, 0) + + +def test_rate_limit_expira_el_bloqueo(): + reloj = [0.0] + rl = RateLimiter(max_fallos=2, ventana_s=300, bloqueo_s=900, reloj=lambda: reloj[0]) + rl.registrar_fallo("ip") + rl.registrar_fallo("ip") + assert not rl.permitido("ip")[0] + reloj[0] = 901.0 # pasa el bloqueo + assert rl.permitido("ip") == (True, 0) + rl.registrar_fallo("ip") # historial limpio: 1 fallo no bloquea + assert rl.permitido("ip") == (True, 0) + + +def test_rate_limit_exito_resetea(): + rl = RateLimiter(max_fallos=3) + rl.registrar_fallo("ip") + rl.registrar_fallo("ip") + rl.registrar_exito("ip") + rl.registrar_fallo("ip") + rl.registrar_fallo("ip") + assert rl.permitido("ip") == (True, 0) # el reset borró los previos + + +# ── CLI: generar-llave con advertencia ────────────────────────────── + +def test_generar_llave_imprime_advertencia(capsys): + from panel.__main__ import main + assert main(["generar-llave"]) == 0 + out = capsys.readouterr().out + assert "PANEL_MASTER_KEY=" in out + assert "IRRECUPERABLES" in out + assert "RESPÁLDALA" in out + # la llave generada es Fernet válida + llave = out.splitlines()[0].split("=", 1)[1] + "=" # base64 termina en = + Fernet(out.splitlines()[0].removeprefix("PANEL_MASTER_KEY=").encode())