315 lines
11 KiB
Python
315 lines
11 KiB
Python
"""Sesión por cookie firmada, roles y alta de los usuarios demo (sección 5 del brief)."""
|
|
|
|
from collections.abc import Iterator
|
|
from typing import Annotated
|
|
|
|
import pytest
|
|
import sqlalchemy as sa
|
|
from fastapi import Depends
|
|
from fastapi.testclient import TestClient
|
|
from itsdangerous import URLSafeTimedSerializer
|
|
from sqlalchemy.orm import Session, sessionmaker
|
|
|
|
from app.auth import (
|
|
COOKIE_SESION,
|
|
hashear_contrasena,
|
|
requiere_rol,
|
|
verificar_contrasena,
|
|
)
|
|
from app.db import crear_engine, crear_session_factory
|
|
from app.main import crear_app
|
|
from app.models import AuditTrail, Base, Tenant, Usuario
|
|
from app.models.usuario import Rol
|
|
from app.routers import plantillas
|
|
from seed.usuarios_demo import TENANT_DEMO_NOMBRE, sembrar
|
|
|
|
CONTRASENAS = {
|
|
Rol.ANALISTA: "clave-analista-1",
|
|
Rol.OFICIAL: "clave-oficial-2",
|
|
Rol.AUDITOR: "clave-auditor-3",
|
|
}
|
|
|
|
|
|
@pytest.fixture
|
|
def fabrica(monkeypatch: pytest.MonkeyPatch) -> sessionmaker[Session]:
|
|
"""Base en memoria propia del test, con el tenant y los tres usuarios demo."""
|
|
engine = crear_engine("sqlite://")
|
|
Base.metadata.create_all(engine)
|
|
fabrica = crear_session_factory(engine)
|
|
monkeypatch.setattr("app.db.SessionLocal", fabrica)
|
|
with fabrica() as sesion:
|
|
sembrar(sesion, CONTRASENAS)
|
|
sesion.commit()
|
|
return fabrica
|
|
|
|
|
|
@pytest.fixture
|
|
def cliente(fabrica: sessionmaker[Session]) -> Iterator[TestClient]:
|
|
with TestClient(crear_app(), follow_redirects=False) as c:
|
|
yield c
|
|
|
|
|
|
def entrar(cliente: TestClient, rol: Rol, contrasena: str | None = None):
|
|
return cliente.post(
|
|
"/login", data={"usuario": rol.value, "contrasena": contrasena or CONTRASENAS[rol]}
|
|
)
|
|
|
|
|
|
# --- Login y cookie ------------------------------------------------------------------------
|
|
|
|
|
|
def test_login_correcto_crea_cookie_firmada(
|
|
cliente: TestClient, fabrica: sessionmaker[Session]
|
|
) -> None:
|
|
respuesta = entrar(cliente, Rol.OFICIAL)
|
|
|
|
assert respuesta.status_code == 303
|
|
assert respuesta.headers["location"] == "/inicio"
|
|
cabecera = respuesta.headers["set-cookie"].lower()
|
|
assert cabecera.startswith(f"{COOKIE_SESION}=")
|
|
assert "httponly" in cabecera
|
|
assert "samesite=lax" in cabecera
|
|
assert "secure" not in cabecera # la petición de prueba llega por http
|
|
|
|
with fabrica() as sesion:
|
|
oficial = sesion.scalar(sa.select(Usuario).where(Usuario.usuario == "oficial"))
|
|
datos = URLSafeTimedSerializer("secreto-de-pruebas", salt="pld.sesion").loads(
|
|
respuesta.cookies[COOKIE_SESION]
|
|
)
|
|
assert datos == {"uid": oficial.id, "tid": oficial.tenant_id}
|
|
|
|
|
|
def test_la_cookie_es_secure_cuando_la_peticion_llega_por_https(
|
|
fabrica: sessionmaker[Session],
|
|
) -> None:
|
|
with TestClient(crear_app(), base_url="https://testserver", follow_redirects=False) as c:
|
|
respuesta = entrar(c, Rol.ANALISTA)
|
|
assert "secure" in respuesta.headers["set-cookie"].lower()
|
|
|
|
|
|
@pytest.mark.parametrize("rol", list(Rol))
|
|
def test_los_tres_usuarios_entran_y_ven_inicio(cliente: TestClient, rol: Rol) -> None:
|
|
assert entrar(cliente, rol).status_code == 303
|
|
|
|
respuesta = cliente.get("/inicio")
|
|
assert respuesta.status_code == 200
|
|
assert rol.value in respuesta.text
|
|
|
|
|
|
def test_contrasena_incorrecta_no_crea_cookie(cliente: TestClient) -> None:
|
|
respuesta = entrar(cliente, Rol.OFICIAL, "no-es-la-clave")
|
|
|
|
assert respuesta.status_code == 401
|
|
assert "set-cookie" not in respuesta.headers
|
|
assert "Usuario o contraseña incorrectos" in respuesta.text
|
|
assert cliente.get("/inicio").status_code == 303
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"datos", [{"usuario": "nadie", "contrasena": "x"}, {"usuario": "oficial"}, {}]
|
|
)
|
|
def test_usuario_inexistente_o_formulario_incompleto_no_entra(
|
|
cliente: TestClient, datos: dict[str, str]
|
|
) -> None:
|
|
respuesta = cliente.post("/login", data=datos)
|
|
assert respuesta.status_code == 401
|
|
assert "set-cookie" not in respuesta.headers
|
|
|
|
|
|
def test_cookie_alterada_se_rechaza(cliente: TestClient) -> None:
|
|
token = entrar(cliente, Rol.OFICIAL).cookies[COOKIE_SESION]
|
|
assert cliente.get("/inicio").status_code == 200
|
|
|
|
cuerpo, resto = token.split(".", 1)
|
|
alterada = ("A" if cuerpo[0] != "A" else "B") + cuerpo[1:] + "." + resto
|
|
cliente.cookies.set(COOKIE_SESION, alterada)
|
|
|
|
respuesta = cliente.get("/inicio")
|
|
assert respuesta.status_code == 303
|
|
assert respuesta.headers["location"] == "/login"
|
|
|
|
|
|
def test_cookie_firmada_con_otra_clave_se_rechaza(
|
|
cliente: TestClient, fabrica: sessionmaker[Session]
|
|
) -> None:
|
|
with fabrica() as sesion:
|
|
oficial = sesion.scalar(sa.select(Usuario).where(Usuario.usuario == "oficial"))
|
|
falsa = URLSafeTimedSerializer("otra-clave", salt="pld.sesion").dumps(
|
|
{"uid": oficial.id, "tid": oficial.tenant_id}
|
|
)
|
|
cliente.cookies.set(COOKIE_SESION, falsa)
|
|
|
|
assert cliente.get("/inicio").status_code == 303
|
|
|
|
|
|
def test_logout_cierra_la_sesion(cliente: TestClient) -> None:
|
|
entrar(cliente, Rol.AUDITOR)
|
|
assert cliente.get("/inicio").status_code == 200
|
|
|
|
respuesta = cliente.post("/logout")
|
|
assert respuesta.status_code == 303
|
|
assert respuesta.headers["location"] == "/login"
|
|
assert cliente.get("/inicio").status_code == 303
|
|
|
|
|
|
# --- Rutas públicas, raíz y roles ----------------------------------------------------------
|
|
|
|
|
|
def test_health_sin_sesion_responde_200(cliente: TestClient) -> None:
|
|
assert cliente.get("/api/health").status_code == 200
|
|
|
|
|
|
def test_raiz_redirige_segun_haya_sesion(cliente: TestClient) -> None:
|
|
sin_sesion = cliente.get("/")
|
|
assert sin_sesion.status_code == 303
|
|
assert sin_sesion.headers["location"] == "/login"
|
|
|
|
entrar(cliente, Rol.ANALISTA)
|
|
con_sesion = cliente.get("/")
|
|
assert con_sesion.status_code == 303
|
|
assert con_sesion.headers["location"] == "/inicio"
|
|
|
|
|
|
def test_login_con_sesion_abierta_redirige_a_inicio(cliente: TestClient) -> None:
|
|
assert cliente.get("/login").status_code == 200
|
|
entrar(cliente, Rol.ANALISTA)
|
|
assert cliente.get("/login").headers["location"] == "/inicio"
|
|
|
|
|
|
def test_requiere_rol_devuelve_403_al_rol_equivocado(fabrica: sessionmaker[Session]) -> None:
|
|
app = crear_app()
|
|
|
|
@app.post("/solo-oficial")
|
|
def solo_oficial(usuario: Annotated[Usuario, Depends(requiere_rol(Rol.OFICIAL))]) -> dict:
|
|
return {"usuario": usuario.usuario}
|
|
|
|
with TestClient(app, follow_redirects=False) as c:
|
|
assert c.post("/solo-oficial").status_code == 303 # sin sesión: a /login
|
|
|
|
entrar(c, Rol.ANALISTA)
|
|
assert c.post("/solo-oficial").status_code == 403
|
|
|
|
c.post("/logout")
|
|
entrar(c, Rol.OFICIAL)
|
|
respuesta = c.post("/solo-oficial")
|
|
assert respuesta.status_code == 200
|
|
assert respuesta.json() == {"usuario": "oficial"}
|
|
|
|
|
|
def test_api_sin_sesion_responde_401_en_vez_de_redirigir(fabrica: sessionmaker[Session]) -> None:
|
|
app = crear_app()
|
|
|
|
@app.get("/api/privado")
|
|
def privado(usuario: Annotated[Usuario, Depends(requiere_rol(*Rol))]) -> dict:
|
|
return {}
|
|
|
|
with TestClient(app, follow_redirects=False) as c:
|
|
assert c.get("/api/privado").status_code == 401
|
|
|
|
|
|
# --- Portada, navegación y componentes ---------------------------------------------------
|
|
|
|
|
|
def test_inicio_muestra_tenant_regimen_actividad_y_los_ocho_pasos(cliente: TestClient) -> None:
|
|
entrar(cliente, Rol.OFICIAL)
|
|
html = cliente.get("/inicio").text
|
|
|
|
assert TENANT_DEMO_NOMBRE in html
|
|
assert "LFPIORPI" in html
|
|
assert "Art. 17 fracción IV" in html
|
|
|
|
pasos = [
|
|
"Expediente",
|
|
"Beneficiario controlador",
|
|
"Screening",
|
|
"Clasificación de riesgo",
|
|
"Créditos y operaciones",
|
|
"Alertas y casos",
|
|
"Evidencia",
|
|
"Laboratorio",
|
|
]
|
|
lateral = html[html.index('<nav class="nav"') : html.index("</nav>")]
|
|
posiciones = [lateral.index(paso) for paso in pasos]
|
|
assert posiciones == sorted(posiciones)
|
|
assert "Cartera" in lateral
|
|
|
|
# Lo que aún no existe va deshabilitado y dice en qué fase llega; Inicio ya es enlace.
|
|
assert lateral.count('aria-disabled="true"') == 9
|
|
assert "fase 4" in lateral
|
|
assert 'href="/inicio"' in lateral
|
|
assert 'href="/expediente"' not in lateral
|
|
|
|
|
|
def test_los_componentes_pintan_niveles_estados_tabla_y_tarjeta() -> None:
|
|
fuente = """
|
|
{%- from "_componentes/badges.html" import badge_nivel, badge_estado_alerta -%}
|
|
{%- from "_componentes/tabla.html" import tabla -%}
|
|
{%- from "_componentes/tarjeta.html" import tarjeta -%}
|
|
{{ badge_nivel("alto") }}{{ badge_nivel(1) }}{{ badge_estado_alerta("en_revisión") }}
|
|
{% call tarjeta("Reglas") %}{{ tabla(["clave", "nombre"], filas) }}{% endcall %}
|
|
{{ tabla(["clave"], []) }}
|
|
"""
|
|
html = plantillas.env.from_string(fuente).render(
|
|
filas=[{"clave": "A-01", "nombre": "<b>Umbral</b>"}, {"clave": "B-05", "nombre": None}]
|
|
)
|
|
|
|
assert 'class="badge badge--peligro" data-nivel="alto">Alto<' in html
|
|
assert 'class="badge badge--exito" data-nivel="bajo">Bajo<' in html
|
|
assert 'data-estado="en_revision">En revisión<' in html
|
|
assert '<h2 class="tarjeta__titulo">Reglas</h2>' in html
|
|
assert '<th scope="col">Nombre</th>' in html
|
|
assert "<b>Umbral</b>" in html # el contenido de las celdas se escapa
|
|
assert "<td>—</td>" in html
|
|
assert "Sin registros." in html
|
|
|
|
|
|
# --- Contraseñas y usuarios demo -----------------------------------------------------------
|
|
|
|
|
|
def test_hash_de_contrasena_verifica_y_no_la_contiene() -> None:
|
|
hash_ = hashear_contrasena("mi-clave-secreta")
|
|
|
|
assert "mi-clave-secreta" not in hash_
|
|
assert len(hash_) <= 255
|
|
assert verificar_contrasena("mi-clave-secreta", hash_)
|
|
assert not verificar_contrasena("otra", hash_)
|
|
assert not verificar_contrasena("mi-clave-secreta", "formato-desconocido")
|
|
assert hashear_contrasena("mi-clave-secreta") != hash_ # sal distinta en cada hash
|
|
|
|
|
|
def test_sembrar_es_idempotente_y_actualiza_la_contrasena(fabrica: sessionmaker[Session]) -> None:
|
|
with fabrica() as sesion:
|
|
assert set(sembrar(sesion, CONTRASENAS).values()) == {"sin_cambios"}
|
|
|
|
nuevas = CONTRASENAS | {Rol.OFICIAL: "clave-nueva"}
|
|
assert sembrar(sesion, nuevas)[Rol.OFICIAL] == "actualizado"
|
|
sesion.commit()
|
|
|
|
assert sesion.scalar(sa.select(sa.func.count()).select_from(Usuario)) == 3
|
|
assert sesion.scalar(sa.select(sa.func.count()).select_from(Tenant)) == 1
|
|
oficial = sesion.scalar(sa.select(Usuario).where(Usuario.usuario == "oficial"))
|
|
assert verificar_contrasena("clave-nueva", oficial.hash)
|
|
|
|
|
|
def test_sembrar_omite_al_usuario_sin_contrasena_y_no_la_filtra(
|
|
caplog: pytest.LogCaptureFixture,
|
|
) -> None:
|
|
engine = crear_engine("sqlite://")
|
|
Base.metadata.create_all(engine)
|
|
|
|
with caplog.at_level("INFO"), crear_session_factory(engine)() as sesion:
|
|
resultado = sembrar(sesion, {Rol.ANALISTA: "clave-analista-1", Rol.OFICIAL: ""})
|
|
sesion.commit()
|
|
|
|
assert resultado == {
|
|
Rol.ANALISTA: "creado",
|
|
Rol.OFICIAL: "omitido",
|
|
Rol.AUDITOR: "omitido",
|
|
}
|
|
assert sesion.scalars(sa.select(Usuario.usuario)).all() == ["analista"]
|
|
auditado = str(sesion.execute(sa.select(AuditTrail.antes, AuditTrail.despues)).all())
|
|
|
|
assert "DEMO_PASSWORD_OFICIAL" in caplog.text
|
|
assert "clave-analista-1" not in caplog.text
|
|
assert "clave-analista-1" not in auditado
|