142 lines
6.0 KiB
Python
142 lines
6.0 KiB
Python
"""Encabezados de seguridad, rechazo de peticiones de otro sitio y límite de intentos por cuenta."""
|
|
|
|
from collections.abc import Iterator
|
|
|
|
import pytest
|
|
import sqlalchemy as sa
|
|
from fastapi.testclient import TestClient
|
|
from sqlalchemy.orm import Session, sessionmaker
|
|
from starlette.datastructures import Headers
|
|
|
|
from app.auth import MAX_INTENTOS_LOGIN
|
|
from app.db import crear_engine, crear_session_factory
|
|
from app.main import crear_app
|
|
from app.models import AuditTrail, Base
|
|
from app.models.usuario import Rol
|
|
from app.seguridad import viene_de_otro_sitio
|
|
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]:
|
|
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()
|
|
return fabrica
|
|
|
|
|
|
@pytest.fixture
|
|
def cliente(fabrica) -> Iterator[TestClient]:
|
|
with TestClient(crear_app(), follow_redirects=False) as c:
|
|
yield c
|
|
|
|
|
|
def entrar(cliente: TestClient, **encabezados: str):
|
|
return cliente.post(
|
|
"/login",
|
|
data={"usuario": "oficial", "contrasena": CONTRASENAS[Rol.OFICIAL]},
|
|
headers=encabezados,
|
|
)
|
|
|
|
|
|
# --- Encabezados -------------------------------------------------------------------------------
|
|
|
|
|
|
def test_toda_respuesta_lleva_los_encabezados_de_seguridad(cliente: TestClient) -> None:
|
|
for respuesta in (cliente.get("/login"), cliente.get("/api/health"), cliente.get("/no-existe")):
|
|
assert respuesta.headers["x-frame-options"] == "DENY"
|
|
assert respuesta.headers["x-content-type-options"] == "nosniff"
|
|
assert respuesta.headers["referrer-policy"] == "same-origin"
|
|
politica = respuesta.headers["content-security-policy"]
|
|
assert "default-src 'self'" in politica and "frame-ancestors 'none'" in politica
|
|
assert "form-action 'self'" in politica and "object-src 'none'" in politica
|
|
# Por http no se promete https.
|
|
assert "strict-transport-security" not in respuesta.headers
|
|
|
|
|
|
def test_hsts_solo_cuando_la_peticion_llego_por_https(cliente: TestClient) -> None:
|
|
respuesta = cliente.get("/login", headers={"X-Forwarded-Proto": "https"})
|
|
assert respuesta.headers["strict-transport-security"].startswith("max-age=31536000")
|
|
|
|
|
|
def test_la_documentacion_de_la_api_va_sin_politica_de_contenido(cliente: TestClient) -> None:
|
|
entrar(cliente)
|
|
respuesta = cliente.get("/docs")
|
|
assert respuesta.status_code == 200
|
|
assert "content-security-policy" not in respuesta.headers
|
|
assert respuesta.headers["x-frame-options"] == "DENY"
|
|
|
|
|
|
# --- Peticiones de otro sitio --------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("encabezados", "rechazada"),
|
|
[
|
|
({}, False), # una terminal o las pruebas: sin navegador no hay engaño
|
|
({"origin": "http://testserver"}, False),
|
|
({"origin": "https://testserver"}, False), # detrás del proxy el esquema puede diferir
|
|
({"referer": "http://testserver/alertas/3"}, False),
|
|
({"sec-fetch-site": "same-origin"}, False),
|
|
({"origin": "https://otro-sitio.example"}, True),
|
|
({"referer": "https://otro-sitio.example/pagina"}, True),
|
|
({"origin": "null"}, True),
|
|
({"sec-fetch-site": "cross-site"}, True),
|
|
({"origin": "http://testserver", "sec-fetch-site": "cross-site"}, True),
|
|
({"origin": "http://testserver.otro-sitio.example"}, True),
|
|
],
|
|
)
|
|
def test_que_cuenta_como_otro_sitio(encabezados: dict[str, str], rechazada: bool) -> None:
|
|
assert viene_de_otro_sitio(Headers({"host": "testserver", **encabezados})) is rechazada
|
|
|
|
|
|
def test_un_post_de_otro_sitio_se_rechaza_antes_de_llegar_a_la_aplicacion(
|
|
cliente: TestClient, fabrica
|
|
) -> None:
|
|
ajeno = entrar(cliente, Origin="https://otro-sitio.example")
|
|
assert ajeno.status_code == 403 and "otro sitio" in ajeno.text
|
|
assert "set-cookie" not in ajeno.headers
|
|
assert ajeno.headers["x-frame-options"] == "DENY"
|
|
with fabrica() as sesion:
|
|
assert sesion.scalar(sa.select(AuditTrail).where(AuditTrail.accion == "login")) is None
|
|
|
|
propio = entrar(cliente, Origin="http://testserver")
|
|
assert propio.status_code == 303
|
|
# Con sesión, un formulario de otro sitio tampoco pasa (y la sesión sigue viva).
|
|
otro = {"Origin": "https://otro-sitio.example"}
|
|
assert cliente.post("/logout", headers=otro).status_code == 403
|
|
assert cliente.get("/inicio").status_code == 200
|
|
# Las lecturas no se tocan: un enlace desde otro sitio abre la página.
|
|
desde_otro = {"Referer": "https://otro-sitio.example/"}
|
|
assert cliente.get("/inicio", headers=desde_otro).status_code == 200
|
|
|
|
|
|
# --- Límite por cuenta ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_los_fallos_contra_una_cuenta_cuentan_vengan_de_la_ip_que_vengan(fabrica) -> None:
|
|
app = crear_app()
|
|
|
|
def intentar(ip: str, usuario: str = "oficial", contrasena: str = "no-es-la-clave"):
|
|
with TestClient(app, follow_redirects=False, client=(ip, 50000)) as c:
|
|
return c.post("/login", data={"usuario": usuario, "contrasena": contrasena})
|
|
|
|
# Un intento desde cada IP: ninguna llega al límite por IP, la cuenta sí.
|
|
for n in range(MAX_INTENTOS_LOGIN):
|
|
assert intentar(f"10.0.0.{n + 1}").status_code == 401
|
|
bloqueada = intentar("10.0.1.1", contrasena=CONTRASENAS[Rol.OFICIAL])
|
|
assert bloqueada.status_code == 429 and "set-cookie" not in bloqueada.headers
|
|
assert int(bloqueada.headers["retry-after"]) > 0
|
|
# Mayúsculas y espacios no la evaden; otra cuenta desde esa misma IP entra.
|
|
assert intentar("10.0.1.2", usuario=" OFICIAL ").status_code == 429
|
|
assert (
|
|
intentar("10.0.1.1", usuario="analista", contrasena=CONTRASENAS[Rol.ANALISTA]).status_code
|
|
== 303
|
|
)
|