- 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
288 lines
12 KiB
Python
288 lines
12 KiB
Python
"""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()
|