Estructura inicial funcional con documentación en el README.md de la FastAPI

This commit is contained in:
2026-09-25 11:20:50 -03:00
parent edc71742fa
commit 774e227642
2710 changed files with 1012769 additions and 0 deletions

0
tests/__init__.py Normal file
View File

202
tests/test_api.py Normal file
View File

@@ -0,0 +1,202 @@
"""Pruebas de la API con un Elasticsearch simulado.
Las respuestas simuladas tienen la misma forma que las de un índice de FSCrawler
(campos file.*, path.virtual, matched_queries, highlight). Lo que NO prueban es
cómo Elasticsearch interpreta la consulta: eso se verifica contra el servidor real
(ver README, "Verificar contra Elasticsearch").
"""
import json
import time
import httpx
import jwt
import pytest
from fastapi.testclient import TestClient
SECRETO = "secreto-de-prueba-con-mas-de-32-caracteres"
DOCS = {
"a1b2": {"file": {"filename": "cv_juan.docx", "extension": "docx", "filesize": 30,
"last_modified": "2026-05-10T12:00:00.000+00:00"},
"path": {"virtual": "/CURRICULUMS/cv_juan.docx"}},
"c3d4": {"file": {"filename": "resolucion_45.pdf", "extension": "pdf", "filesize": 26,
"last_modified": "2025-01-02T08:00:00.000+00:00"},
"path": {"virtual": "/DEMANDAS - VARIOS/resolucion_45.pdf"}},
"e5f6": {"file": {"filename": "informe.txt", "extension": "txt", "filesize": 10},
"path": {"virtual": "/DATOS POLICIA/informe.txt"}},
"malo": {"file": {"filename": "passwd"}, "path": {"virtual": "/../../etc/passwd"}},
}
class FakeES:
"""Imita las dos llamadas que usa la API: _search y _doc/{id}."""
def __init__(self):
self.ultima_busqueda = None
self.caido = False
self.hits = []
def __call__(self, request: httpx.Request) -> httpx.Response:
if self.caido:
raise httpx.ConnectError("sin conexión")
if request.url.path.endswith("/_search"):
self.ultima_busqueda = json.loads(request.content)
return httpx.Response(200, json={"hits": {"total": {"value": len(self.hits), "relation": "eq"},
"hits": self.hits}})
if "/_doc/" in request.url.path:
doc_id = request.url.path.rsplit("/", 1)[1]
if doc_id in DOCS:
return httpx.Response(200, json={"_id": doc_id, "found": True, "_source": DOCS[doc_id]})
return httpx.Response(404, json={"found": False})
if request.url.path.endswith("/_count"):
return httpx.Response(200, json={"count": len(DOCS)})
return httpx.Response(400)
def _hit(doc_id, nombradas, fragmento):
return {"_id": doc_id, "_score": 1, "_source": DOCS[doc_id], "matched_queries": nombradas,
"highlight": {"content": [fragmento]}}
@pytest.fixture()
def api(tmp_path, monkeypatch):
raiz = tmp_path / "archivos"
(raiz / "CURRICULUMS").mkdir(parents=True)
(raiz / "DEMANDAS - VARIOS").mkdir()
(raiz / "DATOS POLICIA").mkdir()
(raiz / "CURRICULUMS" / "cv_juan.docx").write_bytes(b"contenido del curriculum")
(raiz / "DATOS POLICIA" / "informe.txt").write_bytes(b"reservado")
monkeypatch.chdir(tmp_path)
for k, v in {"STORAGE_TYPE": "local", "STORAGE_ROOT": str(raiz), "EXCLUDE_FOLDERS": "DATOS POLICIA",
"ES_URL": "http://es:9200", "ES_INDEX": "archivos",
"DATABASE_URL": f"sqlite:///{tmp_path / 'logs.db'}", "JWT_SECRET": SECRETO,
"DOWNLOAD_SECRET": "descarga-de-prueba-con-mas-de-32-caracteres",
"LOG_FILE": str(tmp_path / "logs" / "api.log")}.items():
monkeypatch.setenv(k, v)
import app.config
import app.database as dbm
import app.elastic
import app.main
import app.storage
app.config.get_settings.cache_clear()
app.storage.get_storage.cache_clear()
app.elastic.cliente.cache_clear()
fake = FakeES()
monkeypatch.setattr(app.elastic, "cliente",
lambda: httpx.Client(base_url="http://es:9200", transport=httpx.MockTransport(fake)))
dbm.engine = dbm._crear_engine()
dbm.SessionLocal.configure(bind=dbm.engine)
with TestClient(app.main.app) as c:
c.es = fake
yield c
def auth(rol="admin", exp_seg=600):
t = jwt.encode({"sub": "7", "rol": rol, "exp": int(time.time()) + exp_seg}, SECRETO, "HS256")
return {"Authorization": f"Bearer {t}"}
# ---------------------------------------------------------------- la consulta que se manda
def test_consulta_cedula_busca_las_tres_formas_y_la_ruta():
from app.busqueda import variantes_cedula
assert variantes_cedula("1234567") == ["1234567", "1.234.567", "1,234,567"]
assert variantes_cedula("123456") == ["123456", "123.456", "123,456"]
def test_consulta_armada(api):
api.get("/archivos", params={"cedula": "1.234.567", "nombres": "Juan Carlos",
"apellidos": "Pérez González"}, headers=auth())
q = api.es.ultima_busqueda
texto = json.dumps(q, ensure_ascii=False)
should = q["query"]["bool"]["should"]
assert [c["constant_score"]["_name"] for c in should] == ["cedula", "nombre_completo", "nombre_parcial"]
assert '"1.234.567"' in texto and '"1234567"' in texto and "*1234567*" in texto
# Nombre: busca con y sin tilde, en cualquier orden
completo = should[1]["constant_score"]["filter"]["intervals"]["content"]["all_of"]
assert completo["ordered"] is False and len(completo["intervals"]) == 4
assert '"pérez"' in texto and '"perez"' in texto
parcial = should[2]["constant_score"]["filter"]["intervals"]["content"]["all_of"]
assert len(parcial["intervals"]) == 2 and parcial["max_gaps"] == 2
# Carpeta excluida y nunca se trae el contenido completo
assert q["query"]["bool"]["must_not"] == [{"prefix": {"path.virtual": "/DATOS POLICIA/"}}]
assert "content" not in q["_source"]
assert q["highlight"]["pre_tags"] == ["«"]
def test_caracteres_raros_no_llegan_a_la_consulta(api):
api.get("/archivos", params={"nombres": 'Juan" OR *', "apellidos": "Pérez}{"}, headers=auth())
texto = json.dumps(api.es.ultima_busqueda)
assert '"OR"' not in texto.replace('"or"', "") and "}{" not in texto
# ---------------------------------------------------------------- la respuesta de la API
def test_respuesta_con_coincidencias(api):
api.es.hits = [
_hit("a1b2", ["cedula", "nombre_completo", "nombre_parcial"], "Juan Carlos Pérez\nC.I. «1.234.567»"),
_hit("c3d4", ["nombre_parcial"], "Demandado: «Perez», «Juan»"),
]
r = api.get("/archivos", params={"cedula": "1234567", "nombres": "Juan Carlos",
"apellidos": "Pérez González"}, headers=auth())
assert r.status_code == 200
d = r.json()
assert d["total"] == d["total_coincidencias"] == 2
a, b = d["resultados"]
assert (a["id"], a["nombre"], a["carpeta"], a["extension"]) == ("a1b2", "cv_juan.docx", "CURRICULUMS", ".docx")
assert a["coincide_cedula"] is True and a["coincide_nombre"] == "completo"
assert a["fragmento"] == "Juan Carlos Pérez C.I. «1.234.567»"
assert b["coincide_cedula"] is False and b["coincide_nombre"] == "parcial"
def test_validaciones_y_seguridad(api):
assert api.get("/archivos", headers=auth()).status_code == 422
assert api.get("/archivos", params={"nombres": "Juan"}, headers=auth()).status_code == 422
assert api.get("/archivos", params={"cedula": "12"}, headers=auth()).status_code == 422
assert api.get("/archivos", params={"cedula": "1234567"}).status_code == 401
assert api.get("/archivos", params={"cedula": "1234567"}, headers=auth(rol="invitado")).status_code == 403
assert api.get("/archivos", params={"cedula": "1234567"}, headers=auth(exp_seg=-5)).status_code == 401
def test_elasticsearch_caido(api):
api.es.caido = True
assert api.get("/archivos", params={"cedula": "1234567"}, headers=auth()).status_code == 503
salud = api.get("/salud").json()
assert salud["estado"] == "degradado" and salud["elasticsearch_accesible"] is False
# ---------------------------------------------------------------- descargas
def _enlace(api, doc_id):
api.es.hits = [_hit(doc_id, ["cedula"], "x")]
url = api.get("/archivos", params={"cedula": "1234567"}, headers=auth()).json()["resultados"][0]["url_descarga"]
return url.split("/descargas/", 1)[1]
def test_descarga_ok_y_enlace_manipulado(api):
enlace = _enlace(api, "a1b2")
r = api.get("/descargas/" + enlace)
assert r.status_code == 200 and r.content == b"contenido del curriculum"
assert api.get("/descargas/" + enlace.replace("a1b2", "c3d4", 1)).status_code == 403 # firma no coincide
def test_descarga_de_archivo_que_ya_no_esta_en_disco(api):
assert api.get("/descargas/" + _enlace(api, "c3d4")).status_code == 404
def test_descarga_de_carpeta_excluida_bloqueada(api):
assert api.get("/descargas/" + _enlace(api, "e5f6")).status_code == 404
def test_ruta_maliciosa_en_elasticsearch_no_sale_de_la_raiz(api):
# Aunque alguien lograra meter un documento con una ruta "../..", no se entrega
assert api.get("/descargas/" + _enlace(api, "malo")).status_code == 404
def test_salud_ok(api):
assert api.get("/salud").json() == {"estado": "ok", "elasticsearch_accesible": True,
"tipo_almacenamiento": "local", "almacenamiento_accesible": True}

48
tests/test_linux.py Normal file
View File

@@ -0,0 +1,48 @@
"""Casos propios de Linux al DESCARGAR: aunque FSCrawler indexe un enlace simbólico
o una FIFO, la API no debe entregarlos ni colgarse. Y nombres con ':' funcionan."""
import os
import pytest
@pytest.fixture()
def storage(tmp_path, monkeypatch):
raiz = tmp_path / "archivos"
(raiz / "docs").mkdir(parents=True)
afuera = tmp_path / "afuera"
afuera.mkdir()
(afuera / "secreto.txt").write_text("secreto")
(raiz / "docs" / "Reunión 10:30.txt").write_text("acta") # ':' es válido en Linux
(raiz / "docs" / "enlace.txt").symlink_to(afuera / "secreto.txt") # apunta fuera de la raíz
(raiz / "docs" / "interno.txt").symlink_to(raiz / "docs" / "Reunión 10:30.txt") # enlace interno
os.mkfifo(raiz / "docs" / "tuberia.txt") # leerla colgaría la API
monkeypatch.setenv("STORAGE_TYPE", "local")
monkeypatch.setenv("STORAGE_ROOT", str(raiz))
import app.config
import app.storage
app.config.get_settings.cache_clear()
app.storage.get_storage.cache_clear()
yield app.storage.get_storage()
app.storage.get_storage.cache_clear()
def test_nombre_con_dos_puntos(storage):
assert storage.existe("docs/Reunión 10:30.txt") is True
with storage.abrir("docs/Reunión 10:30.txt") as f:
assert f.read() == b"acta"
def test_no_entrega_enlaces_ni_fifos(storage):
assert storage.existe("docs/enlace.txt") is False # sale de la raíz
assert storage.existe("docs/tuberia.txt") is False # no es un archivo regular
def test_no_sale_de_la_raiz(storage):
from app.storage import RutaInvalidaError
for ruta in ("../afuera/secreto.txt", "/etc/passwd", "C:/Windows/win.ini", "docs/../../afuera/secreto.txt"):
with pytest.raises(RutaInvalidaError):
storage.ruta_absoluta(ruta)
assert storage.existe(ruta) is False