From 922af7b35391d807c7cb035d76881ca1944ee9cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorem=20Ju=C3=A1rez?= Date: Tue, 6 Oct 2026 13:57:21 -0600 Subject: [PATCH] test(app): auth, audit y autoregistro --- tests/test_audit.py | 203 +++++++++++++++++++ tests/test_auth.py | 314 +++++++++++++++++++++++++++++ tests/test_routers_autoregistro.py | 94 +++++++++ 3 files changed, 611 insertions(+) create mode 100644 tests/test_audit.py create mode 100644 tests/test_auth.py create mode 100644 tests/test_routers_autoregistro.py diff --git a/tests/test_audit.py b/tests/test_audit.py new file mode 100644 index 0000000..4914df6 --- /dev/null +++ b/tests/test_audit.py @@ -0,0 +1,203 @@ +"""Audit trail: accesos autenticados, `registrar` y su inmutabilidad (secciones 3 y 6).""" + +from collections.abc import Iterator +from datetime import UTC, date, datetime +from decimal import Decimal + +import pytest +import sqlalchemy as sa +from fastapi.testclient import TestClient +from sqlalchemy.orm import Session, sessionmaker + +from app import audit +from app.db import BorradoProhibidoError, crear_engine, crear_session_factory +from app.main import crear_app +from app.models import AuditTrail, Base, Tenant +from app.models.usuario import Rol +from seed.usuarios_demo import sembrar + +CONTRASENAS = {Rol.ANALISTA: "clave-analista-1", Rol.OFICIAL: "clave-oficial-2"} + + +@pytest.fixture +def fabrica(monkeypatch: pytest.MonkeyPatch) -> sessionmaker[Session]: + """Base en memoria propia del test, con el tenant demo y dos usuarios.""" + 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) -> None: + respuesta = cliente.post("/login", data={"usuario": rol.value, "contrasena": CONTRASENAS[rol]}) + assert respuesta.status_code == 303 + + +def filas_de(fabrica: sessionmaker[Session], entidad: str) -> list[AuditTrail]: + with fabrica() as sesion: + return list( + sesion.scalars( + sa.select(AuditTrail).where(AuditTrail.entidad == entidad).order_by(AuditTrail.id) + ) + ) + + +# --- Accesos ------------------------------------------------------------------------------- + + +def test_acceso_autenticado_deja_fila_con_usuario( + cliente: TestClient, fabrica: sessionmaker[Session] +) -> None: + entrar(cliente, Rol.ANALISTA) + assert cliente.get("/inicio?desde=prueba").status_code == 200 + + (fila,) = filas_de(fabrica, "http") + assert fila.accion == "GET /inicio" + assert fila.usuario == "analista" + assert fila.created_by == "analista" + assert fila.entidad_id is None + assert fila.despues == {"ruta": "/inicio", "status": 200, "consulta": "desde=prueba"} + assert fila.fecha is not None + with fabrica() as sesion: + assert fila.tenant_id == sesion.scalar(sa.select(Tenant.id)) + + +def test_rutas_publicas_y_accesos_sin_sesion_no_dejan_fila( + cliente: TestClient, fabrica: sessionmaker[Session] +) -> None: + cliente.get("/api/health") + cliente.get("/login") + cliente.get("/static/app.css") + cliente.get("/") + assert cliente.get("/inicio").status_code == 303 # sin sesión + + assert filas_de(fabrica, "http") == [] + + +def test_login_y_logout_quedan_registrados( + cliente: TestClient, fabrica: sessionmaker[Session] +) -> None: + entrar(cliente, Rol.OFICIAL) + cliente.post("/logout") + + acciones = [(f.accion, f.usuario) for f in filas_de(fabrica, "usuario") if f.usuario != "seed"] + assert acciones == [("login", "oficial"), ("logout", "oficial")] + + +def test_una_ruta_larga_se_recorta_en_accion_y_queda_completa_en_despues() -> None: + ruta = "/expediente/123456/documentos/7890/versiones" + accion = audit._accion_http("GET", ruta) + + assert len(accion) == audit.LARGO_ACCION + assert accion.startswith("GET /expediente/") + assert audit._accion_http("GET", "/inicio") == "GET /inicio" + + +# --- registrar ----------------------------------------------------------------------------- + + +def test_registrar_serializa_fechas_y_decimales(fabrica: sessionmaker[Session]) -> None: + with fabrica() as sesion: + tenant_id = sesion.scalar(sa.select(Tenant.id)) + audit.fijar_actor(sesion, "oficial", tenant_id) + fila = audit.registrar( + sesion, + "credito", + 7, + "actualizar", + antes={"monto": Decimal("188283.55"), "fecha_disposicion": date(2026, 8, 31)}, + despues={ + "monto": Decimal("190000.00"), + "revisado_el": datetime(2026, 10, 6, 12, 30, tzinfo=UTC), + "rol": Rol.OFICIAL, + "pagos": [Decimal("1.10"), None], + }, + motivo="Corrección de captura", + ) + sesion.commit() + fila_id = fila.id + + with fabrica() as sesion: + guardada = sesion.get(AuditTrail, fila_id) + assert guardada.antes == {"monto": "188283.55", "fecha_disposicion": "2026-08-31"} + assert guardada.despues == { + "monto": "190000.00", + "revisado_el": "2026-10-06T12:30:00+00:00", + "rol": "oficial", + "pagos": ["1.10", None], + } + assert (guardada.usuario, guardada.tenant_id) == ("oficial", tenant_id) + assert (guardada.entidad, guardada.entidad_id) == ("credito", 7) + assert guardada.motivo == "Corrección de captura" + assert guardada.fecha is not None + + +def test_registrar_sin_actor_falla(fabrica: sessionmaker[Session]) -> None: + with fabrica() as sesion, pytest.raises(ValueError, match="sin actor"): + audit.registrar(sesion, "credito", 1, "crear") + + +def test_registrar_rechaza_un_valor_que_no_sabe_serializar( + fabrica: sessionmaker[Session], +) -> None: + with fabrica() as sesion, pytest.raises(TypeError): + audit.registrar( + sesion, "credito", 1, "crear", despues={"x": object()}, usuario="oficial", tenant_id=1 + ) + + +# --- Inmutabilidad ------------------------------------------------------------------------- + + +def test_borrar_una_fila_de_audit_trail_falla( + cliente: TestClient, fabrica: sessionmaker[Session] +) -> None: + entrar(cliente, Rol.ANALISTA) + cliente.get("/inicio") + + with fabrica() as sesion: + total = sesion.scalar(sa.select(sa.func.count()).select_from(AuditTrail)) + fila = sesion.scalar(sa.select(AuditTrail).where(AuditTrail.entidad == "http")) + + sesion.delete(fila) + with pytest.raises(BorradoProhibidoError): + sesion.commit() + sesion.rollback() + + with pytest.raises(audit.AuditoriaInmutableError): + sesion.execute(sa.delete(AuditTrail).where(AuditTrail.id == fila.id)) + sesion.rollback() + + assert sesion.scalar(sa.select(sa.func.count()).select_from(AuditTrail)) == total + + +def test_modificar_una_fila_de_audit_trail_falla( + cliente: TestClient, fabrica: sessionmaker[Session] +) -> None: + entrar(cliente, Rol.ANALISTA) + + with fabrica() as sesion: + fila = sesion.scalar(sa.select(AuditTrail).where(AuditTrail.accion == "login")) + + fila.usuario = "otro" + with pytest.raises(audit.AuditoriaInmutableError): + sesion.commit() + sesion.rollback() + + with pytest.raises(audit.AuditoriaInmutableError): + sesion.execute(sa.update(AuditTrail).values(usuario="otro")) + sesion.rollback() + + assert sesion.scalar(sa.select(AuditTrail.usuario).where(AuditTrail.id == fila.id)) == ( + "analista" + ) diff --git a/tests/test_auth.py b/tests/test_auth.py new file mode 100644 index 0000000..f037675 --- /dev/null +++ b/tests/test_auth.py @@ -0,0 +1,314 @@ +"""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('