"""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 app.services.tenant import NOMBRE_TENANT_DEMO from seed.usuarios_demo import 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 NOMBRE_TENANT_DEMO 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('