feat(panel): panel madre v1 — alta de clientes cifrada + estampado/despliegue (Etapa 3)
- 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
This commit is contained in:
1 parent
21f04df711
commit
5d8a6358ed
15 files changed
+1283
No files matched your search
@@ -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
|
||||
@@ -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",
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -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=<la-llave>' >> /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/<slug>/` 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).
|
||||
@@ -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"
|
||||
@@ -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())
|
||||
+287
@@ -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()
|
||||
+134
@@ -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()
|
||||
@@ -0,0 +1,46 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="es">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>{% block titulo %}Panel generador{% endblock %}</title>
|
||||
<style>
|
||||
:root { --tinta:#1c2733; --borde:#d8dee6; --fondo:#f4f6f8; --acento:#0b62a4; --error:#b3261e; --ok:#1b7f4d; }
|
||||
* { box-sizing:border-box; }
|
||||
body { margin:0; font:15px/1.5 -apple-system, "Segoe UI", sans-serif; color:var(--tinta); background:var(--fondo); }
|
||||
header { background:#fff; border-bottom:1px solid var(--borde); padding:.7rem 1.2rem; display:flex; justify-content:space-between; align-items:center; }
|
||||
header b { letter-spacing:.02em; }
|
||||
main { max-width:880px; margin:1.5rem auto; padding:0 1rem; }
|
||||
.caja { background:#fff; border:1px solid var(--borde); border-radius:8px; padding:1.2rem 1.4rem; margin-bottom:1rem; }
|
||||
h1 { font-size:1.2rem; margin:.2rem 0 1rem; }
|
||||
label { display:block; font-size:.82rem; font-weight:600; margin:.7rem 0 .15rem; }
|
||||
input, textarea, select { width:100%; padding:.45rem .6rem; border:1px solid var(--borde); border-radius:6px; font:inherit; }
|
||||
textarea { font-family:ui-monospace, monospace; font-size:.82rem; }
|
||||
.fila { display:grid; grid-template-columns:1fr 1fr; gap:0 1rem; }
|
||||
button { background:var(--acento); color:#fff; border:0; border-radius:6px; padding:.5rem 1rem; font:inherit; font-weight:600; cursor:pointer; }
|
||||
button.secundario { background:#5a6a7a; }
|
||||
button.enlinea { padding:.3rem .7rem; font-size:.82rem; }
|
||||
.error { background:#fdeceb; border:1px solid #f2b8b5; color:var(--error); border-radius:6px; padding:.6rem .8rem; margin:.8rem 0; white-space:pre-line; }
|
||||
.exito { background:#e8f5ee; border:1px solid #b7dfc8; color:var(--ok); border-radius:6px; padding:.6rem .8rem; margin:.8rem 0; white-space:pre-line; }
|
||||
table { width:100%; border-collapse:collapse; }
|
||||
th, td { text-align:left; padding:.5rem .6rem; border-bottom:1px solid var(--borde); font-size:.9rem; }
|
||||
.estado { font-size:.78rem; font-weight:700; padding:.15rem .5rem; border-radius:99px; background:#e7ecf1; }
|
||||
.estado.estampada { background:#e2eefb; color:var(--acento); }
|
||||
.estado.desplegada { background:#e8f5ee; color:var(--ok); }
|
||||
.estado.fallida { background:#fdeceb; color:var(--error); }
|
||||
.mini { font-size:.78rem; color:#5a6a7a; }
|
||||
form.inline { display:inline; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<b>⚙️ Panel generador de réplicas</b>
|
||||
{% if usuario %}
|
||||
<span class="mini">{{ usuario }} ·
|
||||
<form class="inline" method="post" action="/logout"><button class="enlinea secundario">Salir</button></form>
|
||||
</span>
|
||||
{% endif %}
|
||||
</header>
|
||||
<main>{% block cuerpo %}{% endblock %}</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,100 @@
|
||||
{% extends "base.html" %}
|
||||
{% block titulo %}Nuevo cliente · Panel generador{% endblock %}
|
||||
{% block cuerpo %}
|
||||
<div class="caja">
|
||||
<h1>Alta de cliente</h1>
|
||||
{% if errores %}<div class="error">{{ errores | join("\n") }}</div>{% endif %}
|
||||
<form method="post" action="/clientes/nuevo">
|
||||
<h3>Identidad</h3>
|
||||
<div class="fila">
|
||||
<div>
|
||||
<label for="slug">Slug (único, minúsculas-y-guiones)</label>
|
||||
<input id="slug" name="slug" required pattern="[a-z0-9][a-z0-9-]{1,22}[a-z0-9]"
|
||||
value="{{ v.slug or '' }}" placeholder="arrendadora-demo">
|
||||
</div>
|
||||
<div>
|
||||
<label for="nombre_comercial">Nombre comercial</label>
|
||||
<input id="nombre_comercial" name="nombre_comercial" required
|
||||
value="{{ v.nombre_comercial or '' }}" placeholder="Arrendadora Demo S.A. de C.V.">
|
||||
</div>
|
||||
<div>
|
||||
<label for="marca_corta">Marca corta</label>
|
||||
<input id="marca_corta" name="marca_corta" required value="{{ v.marca_corta or '' }}" placeholder="Demo">
|
||||
</div>
|
||||
<div>
|
||||
<label for="representante">Representante (firma del PDF)</label>
|
||||
<input id="representante" name="representante" required value="{{ v.representante or '' }}">
|
||||
</div>
|
||||
<div>
|
||||
<label for="ubicacion">Ubicación</label>
|
||||
<input id="ubicacion" name="ubicacion" value="{{ v.ubicacion or '' }}" placeholder="Querétaro, México">
|
||||
</div>
|
||||
<div>
|
||||
<label for="email_soporte">Email de soporte</label>
|
||||
<input id="email_soporte" name="email_soporte" type="email" value="{{ v.email_soporte or '' }}">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h3>Admin y autorización</h3>
|
||||
<div class="fila">
|
||||
<div>
|
||||
<label for="admin_nombre">Nombre del admin</label>
|
||||
<input id="admin_nombre" name="admin_nombre" value="{{ v.admin_nombre or '' }}">
|
||||
</div>
|
||||
<div>
|
||||
<label for="admin_numero">WhatsApp del admin (10 dígitos)</label>
|
||||
<input id="admin_numero" name="admin_numero" required pattern="[0-9]{10}" value="{{ v.admin_numero or '' }}">
|
||||
</div>
|
||||
</div>
|
||||
<label for="numeros_autorizados">Números autorizados (separados por coma; vacío = solo el admin)</label>
|
||||
<input id="numeros_autorizados" name="numeros_autorizados" value="{{ v.numeros_autorizados or '' }}">
|
||||
|
||||
<h3>Credenciales</h3>
|
||||
<label for="openai_api_key">OpenAI API key</label>
|
||||
<input id="openai_api_key" name="openai_api_key" required autocomplete="off" value="{{ v.openai_api_key or '' }}">
|
||||
<div class="fila">
|
||||
<div>
|
||||
<label for="google_sheet_id">Google Sheet ID</label>
|
||||
<input id="google_sheet_id" name="google_sheet_id" required value="{{ v.google_sheet_id or '' }}">
|
||||
</div>
|
||||
<div>
|
||||
<label for="google_sheet_name">Pestaña del sheet</label>
|
||||
<input id="google_sheet_name" name="google_sheet_name" value="{{ v.google_sheet_name or 'Contratos' }}">
|
||||
</div>
|
||||
</div>
|
||||
<label for="google_credentials_json">Service account JSON (pega el contenido)</label>
|
||||
<textarea id="google_credentials_json" name="google_credentials_json" rows="4" required>{{ v.google_credentials_json or '' }}</textarea>
|
||||
<label for="conekta_private_key">Conekta private key (opcional)</label>
|
||||
<input id="conekta_private_key" name="conekta_private_key" autocomplete="off" value="{{ v.conekta_private_key or '' }}">
|
||||
|
||||
<h3>Evolution y despliegue</h3>
|
||||
<div class="fila">
|
||||
<div>
|
||||
<label for="evolution_api_url">Evolution API URL</label>
|
||||
<input id="evolution_api_url" name="evolution_api_url" required value="{{ v.evolution_api_url or '' }}"
|
||||
placeholder="https://evolution.vps.midominio.com">
|
||||
</div>
|
||||
<div>
|
||||
<label for="evolution_api_key">Evolution API key</label>
|
||||
<input id="evolution_api_key" name="evolution_api_key" required autocomplete="off" value="{{ v.evolution_api_key or '' }}">
|
||||
</div>
|
||||
<div>
|
||||
<label for="base_url">URL pública de la réplica</label>
|
||||
<input id="base_url" name="base_url" required value="{{ v.base_url or '' }}" placeholder="https://demo-bot.midominio.com">
|
||||
</div>
|
||||
<div>
|
||||
<label for="destino">Destino</label>
|
||||
<select id="destino" name="destino">
|
||||
<option value="vps-propio" {{ "selected" if v.destino != "servidor-cliente" }}>VPS propio (Evolution central)</option>
|
||||
<option value="servidor-cliente" {{ "selected" if v.destino == "servidor-cliente" }}>Servidor del cliente (su Evolution)</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p style="margin-top:1.2rem;">
|
||||
<button>Guardar cliente (cifrado)</button>
|
||||
<a href="/"><button type="button" class="secundario">Cancelar</button></a>
|
||||
</p>
|
||||
</form>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,53 @@
|
||||
{% extends "base.html" %}
|
||||
{% block titulo %}Clientes · Panel generador{% endblock %}
|
||||
{% block cuerpo %}
|
||||
{% if mensaje %}<div class="exito">{{ mensaje }}</div>{% endif %}
|
||||
{% if error %}<div class="error">{{ error }}</div>{% endif %}
|
||||
|
||||
<div class="caja">
|
||||
<h1>Clientes y réplicas</h1>
|
||||
{% if clientes %}
|
||||
<table>
|
||||
<tr><th>Slug</th><th>Cliente</th><th>Réplica</th><th>Puerto</th><th>Acciones</th></tr>
|
||||
{% for c in clientes %}
|
||||
<tr>
|
||||
<td><code>{{ c.slug }}</code></td>
|
||||
<td>{{ c.nombre }}</td>
|
||||
<td>
|
||||
{% if c.replica %}
|
||||
<span class="estado {{ c.replica.estado }}">{{ c.replica.estado }}</span>
|
||||
{% else %}
|
||||
<span class="mini">sin estampar</span>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td>{{ c.replica.puerto if c.replica else "—" }}</td>
|
||||
<td>
|
||||
{% if not c.replica %}
|
||||
<form class="inline" method="post" action="/clientes/{{ c.slug }}/estampar">
|
||||
<button class="enlinea">Estampar</button>
|
||||
</form>
|
||||
{% elif c.replica.estado == "estampada" %}
|
||||
<form class="inline" method="post" action="/clientes/{{ c.slug }}/desplegar">
|
||||
<button class="enlinea">Desplegar</button>
|
||||
</form>
|
||||
{% elif c.replica.estado == "fallida" %}
|
||||
<form class="inline" method="post" action="/clientes/{{ c.slug }}/estampar">
|
||||
<button class="enlinea secundario">Reintentar estampado</button>
|
||||
</form>
|
||||
{% else %}
|
||||
<span class="mini">en {{ c.replica.destino }}</span>
|
||||
{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</table>
|
||||
{% else %}
|
||||
<p class="mini">Aún no hay clientes. Da de alta el primero.</p>
|
||||
{% endif %}
|
||||
<p style="margin-top:1rem;"><a href="/clientes/nuevo"><button type="button">+ Nuevo cliente</button></a></p>
|
||||
</div>
|
||||
|
||||
<p class="mini">El estado de réplicas viene de <code>replicas/registry.json</code> (el generador es la
|
||||
fuente de verdad). «Desplegar» levanta la réplica en este VPS; los paquetes portables se
|
||||
entregan con su <code>README-ARRANQUE.md</code>.</p>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,15 @@
|
||||
{% extends "base.html" %}
|
||||
{% block titulo %}Entrar · Panel generador{% endblock %}
|
||||
{% block cuerpo %}
|
||||
<div class="caja" style="max-width:380px; margin:3rem auto;">
|
||||
<h1>Entrar</h1>
|
||||
{% if error %}<div class="error">{{ error }}</div>{% endif %}
|
||||
<form method="post" action="/login">
|
||||
<label for="username">Usuario</label>
|
||||
<input id="username" name="username" autocomplete="username" required autofocus>
|
||||
<label for="password">Contraseña</label>
|
||||
<input id="password" name="password" type="password" autocomplete="current-password" required>
|
||||
<p><button>Entrar</button></p>
|
||||
</form>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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())
|
||||
Reference in new issue
Block a user