/docs, /redoc y /openapi.json exigen sesión (sin ella, redirección a /login). POST /login admite 10 intentos fallidos por IP en 15 minutos y luego responde 429 con Retry-After; contador en memoria, sin dependencias nuevas.
108 lines
3.7 KiB
Python
108 lines
3.7 KiB
Python
"""Superficie pública: documentación de la API detrás de sesión y límite de intentos de login."""
|
|
|
|
from collections.abc import Iterator
|
|
|
|
import pytest
|
|
from fastapi.testclient import TestClient
|
|
from sqlalchemy.orm import Session, sessionmaker
|
|
|
|
from app.auth import MAX_INTENTOS_LOGIN, VENTANA_INTENTOS_S, LimiteIntentos
|
|
from app.db import crear_engine, crear_session_factory
|
|
from app.main import crear_app
|
|
from app.models import Base
|
|
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 cliente(monkeypatch: pytest.MonkeyPatch) -> Iterator[TestClient]:
|
|
engine = crear_engine("sqlite://")
|
|
Base.metadata.create_all(engine)
|
|
fabrica: sessionmaker[Session] = crear_session_factory(engine)
|
|
monkeypatch.setattr("app.db.SessionLocal", fabrica)
|
|
with fabrica() as sesion:
|
|
sembrar(sesion, CONTRASENAS)
|
|
sesion.commit()
|
|
with TestClient(crear_app(), follow_redirects=False) as c:
|
|
yield c
|
|
|
|
|
|
def intentar(cliente: TestClient, contrasena: str = "no-es-la-clave"):
|
|
return cliente.post("/login", data={"usuario": "oficial", "contrasena": contrasena})
|
|
|
|
|
|
# --- Documentación de la API ---------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.parametrize("ruta", ["/docs", "/redoc", "/openapi.json"])
|
|
def test_la_documentacion_sin_sesion_redirige_a_login(cliente: TestClient, ruta: str) -> None:
|
|
respuesta = cliente.get(ruta)
|
|
|
|
assert respuesta.status_code == 303
|
|
assert respuesta.headers["location"] == "/login"
|
|
|
|
|
|
def test_la_documentacion_con_sesion_se_sirve(cliente: TestClient) -> None:
|
|
intentar(cliente, CONTRASENAS[Rol.OFICIAL])
|
|
|
|
assert cliente.get("/docs").status_code == 200
|
|
assert cliente.get("/redoc").status_code == 200
|
|
esquema = cliente.get("/openapi.json")
|
|
assert esquema.status_code == 200
|
|
assert "/api/health" in esquema.json()["paths"]
|
|
|
|
|
|
# --- Límite de intentos --------------------------------------------------------------------
|
|
|
|
|
|
def test_el_intento_11_responde_429(cliente: TestClient) -> None:
|
|
for _ in range(MAX_INTENTOS_LOGIN):
|
|
assert intentar(cliente).status_code == 401
|
|
|
|
bloqueado = intentar(cliente)
|
|
assert bloqueado.status_code == 429
|
|
assert 0 < int(bloqueado.headers["retry-after"]) <= VENTANA_INTENTOS_S
|
|
assert "Demasiados intentos" in bloqueado.text
|
|
|
|
# Bloqueado incluso con la contraseña correcta, y sin crear sesión.
|
|
correcto = intentar(cliente, CONTRASENAS[Rol.OFICIAL])
|
|
assert correcto.status_code == 429
|
|
assert "set-cookie" not in correcto.headers
|
|
|
|
|
|
def test_los_logins_correctos_no_cuentan_como_intentos(cliente: TestClient) -> None:
|
|
for _ in range(MAX_INTENTOS_LOGIN + 5):
|
|
assert intentar(cliente, CONTRASENAS[Rol.OFICIAL]).status_code == 303
|
|
|
|
|
|
class Reloj:
|
|
def __init__(self) -> None:
|
|
self.ahora = 1000.0
|
|
|
|
def __call__(self) -> float:
|
|
return self.ahora
|
|
|
|
|
|
def test_el_limite_es_por_ip_y_vence_con_la_ventana() -> None:
|
|
reloj = Reloj()
|
|
limite = LimiteIntentos(maximo=10, ventana_s=900, reloj=reloj)
|
|
|
|
for _ in range(10):
|
|
assert limite.segundos_bloqueado("10.0.0.1") == 0
|
|
limite.registrar_fallo("10.0.0.1")
|
|
reloj.ahora += 10
|
|
|
|
assert limite.segundos_bloqueado("10.0.0.1") == 800 # vence el primero, de hace 100 s
|
|
assert limite.segundos_bloqueado("10.0.0.2") == 0
|
|
|
|
reloj.ahora += 800
|
|
assert limite.segundos_bloqueado("10.0.0.1") == 0 # salió de la ventana el más antiguo
|
|
limite.registrar_fallo("10.0.0.1")
|
|
assert limite.segundos_bloqueado("10.0.0.1") > 0
|
|
|
|
reloj.ahora += 900
|
|
assert limite.segundos_bloqueado("10.0.0.1") == 0
|
|
assert limite._fallos == {} # no acumula IPs sin fallos vigentes
|