- 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
128 lines
5.3 KiB
Python
128 lines
5.3 KiB
Python
"""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())
|