diff --git a/pyproject.toml b/pyproject.toml index f46f097..880a25d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -3,7 +3,17 @@ name = "webapi" version = "0.0.0" description = "FastAPI: FHIR routes, control routes, the auth dependency." requires-python = ">=3.12" -dependencies = ["core", "persistance", "fastapi[standard]", "dagster-graphql", "requests"] +dependencies = [ + "core", + "persistance", + "fastapi[standard]", + "dagster-graphql", + "authlib>=1.6", + "fastapi-users[sqlalchemy]>=15", + "aiosqlite>=0.20", + "asyncpg>=0.30", + "requests", +] [build-system] requires = ["uv_build>=0.12,<0.13"] diff --git a/tests/test_backup.py b/tests/test_backup.py new file mode 100644 index 0000000..33b86ee --- /dev/null +++ b/tests/test_backup.py @@ -0,0 +1,99 @@ +"""Backups (persistance.backup): a platform's data backed up while it holds a site's +configuration comes back whole into an empty platform, on SQLite and PostgreSQL; a damaged +backup restores nothing; restoring over a platform needs --force and keeps what was there.""" + +import json +import subprocess +from pathlib import Path + +FIXTURES = Path(__file__).parents[2] / "tests" / "fixtures" +STORED = "select pipeline_id, version, doc from config.{kind} order by pipeline_id, version" + + +def _stored(platform) -> list: + """Every saved version of every pipeline and concept map (a kind never saved: none).""" + found = [] + for kind in ("pipelines", "concept_maps"): + try: + found += [tuple(r) for r in platform.query(STORED.format(kind=kind))] + except Exception as e: # its table appears with its first save + if "no such table" not in str(e) and "does not exist" not in str(e): + raise + return found + + +def _backup(platform, cli: str, *args: str) -> subprocess.CompletedProcess: + return subprocess.run( + ["python", "-m", "persistance.backup", cli, *args], + env=platform.env, cwd=platform.env["ISSSTELEON_DATA"], capture_output=True, text=True, + ) # fmt: skip + + +def _made(platform, tmp_path_factory) -> Path: + """A backup of the platform, outside its data folder; its folder.""" + made = _backup(platform, "create", "--to", str(tmp_path_factory.mktemp("backups"))) + assert made.returncode == 0, made.stderr + return Path(made.stdout.strip()) + + +def _reset(platform) -> None: + """The platform emptied, as on a new machine: its data folder and (PostgreSQL) schemas.""" + data = Path(platform.env["ISSSTELEON_DATA"]) + for p in data.iterdir(): + if p.name.startswith("platform") or p.name in ("dlt", "mlflow.db"): + subprocess.run(["rm", "-rf", str(p)], check=True) + if "postgres" in platform.env["PLATFORM_DATABASE_URL"]: + for schema in ("bronze", "silver", "gold", "config"): + subprocess.run(["psql", platform.env["PLATFORM_DATABASE_URL"], "-qc", + f"drop schema if exists {schema} cascade"], check=True) # fmt: skip + + +def test_a_backup_restores_the_site_whole(platform, tmp_path_factory): + platform.save("pipelines", "erick", FIXTURES / "pipelines" / "erick_site.json") + platform.save("pipelines", "erick", FIXTURES / "pipelines" / "erick_site.json") # v2 + platform.save("concept_maps", "erick_site", FIXTURES / "concept_maps" / "erick_site.json") + before = _stored(platform) + assert len(before) == 3 + + made = _backup(platform, "create", "--to", str(tmp_path_factory.mktemp("backups"))) + assert made.returncode == 0, made.stderr + folder = Path(made.stdout.strip()) + manifest = json.loads((folder / "manifest.json").read_text()) + assert all(len(f["sha256"]) == 64 for f in manifest["files"].values()) + assert _backup(platform, "verify", str(folder)).stdout.strip() == "ok" + + # over a platform: refused without --force + refused = _backup(platform, "restore", str(folder)) + assert refused.returncode != 0 and "--force" in refused.stderr + + _reset(platform) + assert not any(n.startswith("platform") for n in + (p.name for p in Path(platform.env["ISSSTELEON_DATA"]).iterdir())) # fmt: skip + restored = _backup(platform, "restore", str(folder)) + assert restored.returncode == 0, restored.stderr + assert _stored(platform) == before + + +def test_a_damaged_backup_restores_nothing(platform, tmp_path_factory): + platform.save("pipelines", "erick", FIXTURES / "pipelines" / "erick_site.json") + folder = _made(platform, tmp_path_factory) + damaged = next(p for p in folder.rglob("*") if p.is_file() and p.name != "manifest.json") + damaged.write_bytes(damaged.read_bytes() + b"\0") # one byte more + checked = _backup(platform, "verify", str(folder)) + assert checked.returncode == 1 and "changed since the backup" in checked.stdout + + restored = _backup(platform, "restore", str(folder), "--force") + assert restored.returncode != 0 and "damaged" in restored.stderr + assert len(_stored(platform)) == 1 # the platform as it was + + +def test_restoring_over_a_platform_keeps_what_was_there(fresh_platform, tmp_path_factory): + """SQLite: what the data folder held is set aside, not mixed with the backup's.""" + platform = fresh_platform + platform.save("pipelines", "erick", FIXTURES / "pipelines" / "erick_site.json") + folder = _made(platform, tmp_path_factory) + platform.save("pipelines", "erick", FIXTURES / "pipelines" / "erick_site.json") # newer + assert _backup(platform, "restore", str(folder), "--force").returncode == 0 + assert len(_stored(platform)) == 1 # the backup's moment, nothing newer mixed in + aside = list(Path(platform.env["ISSSTELEON_DATA"]).glob(".before-restore-*")) + assert len(aside) == 1 and any(aside[0].glob("platform__config.db")) diff --git a/tests/test_sources.py b/tests/test_sources.py new file mode 100644 index 0000000..f9e9177 --- /dev/null +++ b/tests/test_sources.py @@ -0,0 +1,165 @@ +"""The Conectar dialog's API: an operator who knows nothing of dlt picks a kind of source, +answers its questions, and "Probar conexión" says in plain words what it found.""" + +import os +import sqlite3 + +import pytest +from fastapi.testclient import TestClient +from sqlalchemy import make_url + +from webapi import sources +from webapi.main import app + + +@pytest.fixture +def client(own_platform, monkeypatch): + monkeypatch.setenv("SOURCE_ROOTS", str(own_platform / "shared")) + (own_platform / "shared" / "reportes" / "2026").mkdir(parents=True) + with TestClient(app) as c: + yield c + + +def probe(client, kind, **answers): + response = client.post("/ingest/sources/test", json={"type": kind, "answers": answers}) + assert response.status_code == 200, response.text + return response.json() + + +def test_the_dialog_lists_every_kind_with_its_questions(client): + found = client.get("/ingest/sources/types").json() + assert {"database", "files", "cloud", "web"} <= set(found["groups"]) + assert found["types"]["sqlserver"]["fields"]["password"]["type"] == "password" + + +def test_erick_sql_server_through_the_dialog(client, site): + url = make_url(site.url) + answers = {"host": url.host, "port": url.port, "database": url.database, + "user": url.username, "password": url.password} # fmt: skip + found = probe(client, "sqlserver", **answers) + assert found["ok"] and found["tables"] == ["ResultadoSubrogado"] + rows = probe(client, "sqlserver", **answers, table="ResultadoSubrogado")["rows"] + assert rows and all(r["Archivo"].endswith(" bytes>") for r in rows) + wrong = probe(client, "sqlserver", **answers | {"password": "not-it"}) + assert not wrong["ok"] and "contraseña" in wrong["message"] and wrong["detail"] + + +def test_an_unknown_server_and_a_missing_answer_say_so_plainly(client): + gone = probe(client, "sqlserver", host="nowhere.invalid", database="P", user="u", + password="p") # fmt: skip + assert not gone["ok"] and gone["message"].startswith(("No se encontró", "El servidor no")) + assert probe(client, "postgresql", host="h")["message"].startswith("falta «Base de datos»") + + +@pytest.mark.skipif(not os.environ.get("POSTGRES_TEST_URL"), reason="needs PostgreSQL") +def test_postgresql_through_the_dialog(client): + url = make_url(os.environ["POSTGRES_TEST_URL"]) + found = probe(client, "postgresql", host=url.host, port=url.port or 5432, + database=url.database, user=url.username, password=url.password) # fmt: skip + assert found["ok"], found + + +def test_a_sqlite_file_lists_its_tables_then_shows_rows(client, own_platform): + path = own_platform / "shared" / "hospital.db" + with sqlite3.connect(path) as con: + con.execute("create table pacientes (id int, nombre text)") + con.execute("insert into pacientes values (1, 'Ana')") + assert probe(client, "sqlite", path=str(path))["tables"] == ["pacientes"] + rows = probe(client, "sqlite", path=str(path), table="pacientes")["rows"] + assert rows == [{"id": 1, "nombre": "Ana"}] + + +def test_server_folders_are_browsed_only_under_the_mounted_roots(client, own_platform): + roots = client.get("/ingest/sources/browse").json()["entries"] + assert [e["name"] for e in roots] == ["shared"] + inside = client.get("/ingest/sources/browse", params={"path": roots[0]["path"]}).json() + assert [e["name"] for e in inside["entries"]] == ["reportes"] + assert client.get("/ingest/sources/browse", params={"path": "/etc"}).status_code == 404 + escape = str(own_platform / "shared" / ".." / "data") + assert client.get("/ingest/sources/browse", params={"path": escape}).status_code == 404 + + +def test_a_folder_uploaded_from_a_computer_is_read_as_spreadsheets_or_documents(client): + sent = [("files", ("informes/enero/a.csv", b"folio,resultado\n1,NEGATIVO\n")), + ("files", ("informes/b.pdf", b"%PDF-1.4 ..."))] # fmt: skip + uploaded = client.post("/ingest/uploads", files=sent).json() + assert sorted(uploaded["files"]) == ["informes/b.pdf", "informes/enero/a.csv"] + more = client.post("/ingest/uploads", files=[("files", ("../../fuera.csv", b"x\n"))], + data={"folder": uploaded["bucket_url"]}).json() # fmt: skip + assert more["files"] == ["fuera.csv"] and more["bucket_url"] == uploaded["bucket_url"] + other = client.post("/ingest/uploads", files=[("files", ("x", b"x"))], data={"folder": "/"}) + assert other.status_code == 422 + rows = probe(client, "upload", folder=uploaded["bucket_url"], pattern="**/*.csv", + read_as="dlt.sources.filesystem:read_csv")["rows"] # fmt: skip + assert rows == [{"folio": 1, "resultado": "NEGATIVO"}] + files = probe(client, "upload", folder=uploaded["bucket_url"], pattern="**/*.pdf")["rows"] + assert [f["file_name"] for f in files] == ["b.pdf"] + + +def test_an_empty_folder_says_what_to_check(client, own_platform): + found = probe(client, "server_folder", folder=str(own_platform / "shared" / "reportes")) + assert found["ok"] and "Revise la ruta" in found["message"] + + +def test_a_sign_in_button_without_an_app_registration_says_who_must_register_one(client): + found = client.get("/ingest/sources/oauth/google/start", params={"origin": "http://x"}) + assert found.status_code == 503 and "GOOGLE_CLIENT_ID" in found.json()["detail"] + + +def test_signing_in_hands_the_account_to_the_dialog(client, monkeypatch, tmp_path): + from authlib.integrations.httpx_client import OAuth2Client, oauth2_client + + httpx = oauth2_client.httpx2 # the HTTP library this authlib is built on + + monkeypatch.setenv("MICROSOFT_CLIENT_ID", "app") + monkeypatch.setenv("MICROSOFT_CLIENT_SECRET", "app-secret") + exchanged = {} + + def provider(request: httpx.Request) -> httpx.Response: # the token endpoint + exchanged["body"] = request.content.decode() + return httpx.Response(200, json={"access_token": "at", "refresh_token": "rt", + "token_type": "Bearer", "expires_in": 3600}) # fmt: skip + + def client_for(found, env, redirect_uri): + return OAuth2Client(env["client_id"], env["client_secret"], scope=found.scope, + redirect_uri=redirect_uri, code_challenge_method="S256", + transport=httpx.MockTransport(provider)) # fmt: skip + + monkeypatch.setattr(sources, "_client", client_for) + monkeypatch.setattr(sources, "PENDING", tmp_path / "pending") # any worker's callback + monkeypatch.setattr(sources, "account", lambda p, token, env: { + "user": "ana@hospital.mx", "drive_id": "d1", + "oauth2_client_params": {"client_id": env["client_id"], "token": token}}) # fmt: skip + start = client.get("/ingest/sources/oauth/microsoft/start", + params={"origin": "http://10.0.10.41:5710"}).json() # fmt: skip + assert start["url"].startswith("https://login.microsoftonline.com/organizations/") + assert "code_challenge=" in start["url"] and "client_id=app" in start["url"] + back = client.get("/ingest/sources/oauth/microsoft/callback", + params={"state": start["state"], "code": "c0de"}) # fmt: skip + assert back.status_code == 200 + assert '"user": "ana@hospital.mx"' in back.text and '"http://10.0.10.41:5710"' in back.text + assert "code_verifier=" in exchanged["body"] and "code=c0de" in exchanged["body"] + again = client.get("/ingest/sources/oauth/microsoft/callback", + params={"state": start["state"], "code": "c0de"}) # fmt: skip + assert again.status_code == 400 # a sign-in is used once + + +def test_a_saved_account_shows_who_but_never_its_tokens(): + from core.pipeline import MASK, Pipeline, redacted, restored + + params = {"client_id": "app", "client_secret": "app-secret-xyz", + "token": {"refresh_token": "refresh-xyz"}} # fmt: skip + account = {"user": "ana@hospital.mx", "drive_id": "d1", "oauth2_client_params": params} + saved = Pipeline(nodes=[{"id": "s", "kind": "source", "guided": { + "type": "onedrive", "answers": {"account": account, "folder": "Reportes"}}}]) # fmt: skip + shown = redacted(saved) + answer = shown.nodes[0].guided.answers["account"] + assert answer["user"] == "ana@hospital.mx" + dumped = shown.model_dump_json() + assert "refresh-xyz" not in dumped and "app-secret-xyz" not in dumped + assert answer["oauth2_client_params"]["client_secret"] == MASK + back = restored(Pipeline.model_validate(shown.model_dump()), saved).nodes[0] + assert ( + back.args["storage_options"]["oauth2_client_params"]["token"]["refresh_token"] + == "refresh-xyz" + ) diff --git a/tests/test_users.py b/tests/test_users.py new file mode 100644 index 0000000..108fde4 --- /dev/null +++ b/tests/test_users.py @@ -0,0 +1,50 @@ +"""Sign-in for the web app: an administrator from the environment, users who see some +domains, a session cookie, and an API that answers everyone as before.""" + +import pytest +from fastapi.testclient import TestClient + +from webapi.main import app + + +@pytest.fixture +def client(own_platform, monkeypatch): + monkeypatch.setenv("AUTH_ADMIN_EMAIL", "admin@isssteleon.mx") + monkeypatch.setenv("AUTH_ADMIN_PASSWORD", "una-clave-larga") + with TestClient(app) as c: + yield c + + +def login(client, email, password): + return client.post("/auth/login", data={"username": email, "password": password}) + + +def test_the_first_administrator_signs_in_and_adds_a_team(client): + assert client.get("/users/me").status_code == 401 + assert login(client, "admin@isssteleon.mx", "mala").status_code == 400 + assert login(client, "admin@isssteleon.mx", "una-clave-larga").status_code == 204 + me = client.get("/users/me").json() + assert me["is_superuser"] and me["domains"] == ["cacu", "cama", "tea"] + team = {"email": "cacu@isssteleon.mx", "password": "equipo-cacu", "name": "Equipo CaCu", + "domains": ["cacu"]} # fmt: skip + assert client.post("/users/register", json=team).status_code == 201 + client.post("/auth/logout") + assert login(client, "cacu@isssteleon.mx", "equipo-cacu").status_code == 204 + assert client.get("/users/me").json()["domains"] == ["cacu"] + other = {"email": "x@isssteleon.mx", "password": "otra-clave"} + assert client.post("/users/register", json=other).status_code == 403 # not an admin + + +def test_the_api_answers_without_a_session(client): + # routes that read no platform data (the in-process app's database is the default one) + for path in ("/health", "/domains", "/ingest/schema", "/ingest/sources/types"): + assert client.get(path).status_code == 200, path + + +def test_a_restart_keeps_the_administrator_once_and_the_session_secret(client, own_platform): + assert login(client, "admin@isssteleon.mx", "una-clave-larga").status_code == 204 + secret = (own_platform / "auth_secret").read_text() + with TestClient(app): # the app starts again on the same data + pass + assert (own_platform / "auth_secret").read_text() == secret + assert client.get("/users/me").status_code == 200 # the session still holds diff --git a/tests/test_webapp.py b/tests/test_webapp.py index 395f987..32ce6b4 100644 --- a/tests/test_webapp.py +++ b/tests/test_webapp.py @@ -78,6 +78,8 @@ def _platform(data: Path): "MLFLOW_DISABLE_AGENT_HINT": "1", "EXECUTION_MODE": "sync", "TEA_REFERENCE_ROOT": str(data / "reference"), + "AUTH_ADMIN_EMAIL": "admin@isssteleon.mx", + "AUTH_ADMIN_PASSWORD": "solo-para-pruebas", } webserver = subprocess.Popen( ["dagster-webserver", "-m", "models.definitions", "-h", "127.0.0.1", diff --git a/webapi/fhir.py b/webapi/fhir.py index b445027..8d0d38c 100644 --- a/webapi/fhir.py +++ b/webapi/fhir.py @@ -3,6 +3,7 @@ uses, paging, and a CapabilityStatement built from these routes themselves. Reso built by Core's mappers from the rows Persistance reads; nothing is computed here beyond counting a few thousand rows (measures) and ordering the follow-up list.""" +import unicodedata from collections import defaultdict from datetime import date, datetime from typing import Annotated, Any @@ -184,6 +185,25 @@ def _with_identity(domain: Domain, rows: list[dict]) -> list[dict]: ] # fmt: skip +def _folded(text: str) -> str: + return "".join(c for c in unicodedata.normalize("NFKD", text.casefold()) + if not unicodedata.combining(c)) # fmt: skip + + +def _matches(row: dict, name: str | None, identifier: str | None) -> bool: + if name: + words = _folded(name).split() + if not any(all(any(w.startswith(q) for w in _folded(n).split()) for q in words) + for n in row["names"]): # fmt: skip + return False + if identifier: + system, _, value = identifier.rpartition("|") + if not any((not system or s == system) and v.casefold() == value.strip().casefold() + for s, v in row["identifiers"]): # fmt: skip + return False + return True + + @router.get( "/Patient", responses=_OK, @@ -202,6 +222,12 @@ def search_patient( start: date | None = _START, cutoff: date | None = _CUTOFF, status: str | None = _STATUS, + name: str | None = Query( + None, description="each word starts a word of her name (case and accents ignored)" + ), + identifier: str | None = Query( + None, description="[system|]value: a CURP or record number (case ignored)" + ), sort: str = Query("-recent", alias="_sort", description="-recent or -risk-"), horizon: float | None = Query(None, alias="risk-horizon", description="years"), revinclude: list[str] = Query([], alias="_revinclude", description=f"any of {REVINCLUDES}"), @@ -219,6 +245,10 @@ def search_patient( ) except ValueError as exc: return outcome(422, str(exc)) + if name or identifier: + found = {r["person_id"] for r in _with_identity(domain, rows) + if _matches(r, name, identifier)} # fmt: skip + rows = [r for r in rows if r["person_id"] in found] persons = [r["person_id"] for r in rows] risks: dict[str, list[dict]] = {} if domain != Domain.TEA and (listed and sort != "-recent" or @@ -464,7 +494,7 @@ def search_condition(request: Request, domain: Domain, subject: str | None = Query(None, description=SUBJECT), _count: int | None = Query(None), _offset: int = Query(0)) -> Response: # fmt: skip - """What clinical notes diagnosed.""" + """What clinical notes diagnosed (CaMa: and each recurrence).""" def build(rows): return [f.condition(r) for r in rows] @@ -477,10 +507,11 @@ def search_procedure(request: Request, domain: Domain, subject: str | None = Query(None, description=SUBJECT), _count: int | None = Query(None), _offset: int = Query(0)) -> Response: # fmt: skip - """The procedures the domain's timeline infers (CaCu: colposcopies and treatments).""" + """The procedures the domain's timeline infers (CaCu: colposcopies and treatments; + CaMa: each treatment, by its kind).""" def build(rows): - return [f.procedure(r) for r in rows] + return [f.procedure(r, domain.value) for r in rows] return _clinical_search("procedure", build, request, domain, subject, _count, _offset) @@ -546,8 +577,9 @@ def search_measure_report( raise HTTPException(422, f"reporting-period: {e}") from e rows = measure_reads.rows(domain.value, found.rows, **found.params) reports = [] - for text, period in _sliced(asked, count, offset): - result = m.evaluate(found, rows, period, as_of, event_cutoff) + page = _sliced(asked, count, offset) + results = m.evaluate_periods(found, rows, [p for _, p in page], as_of, event_cutoff) + for (text, period), result in zip(page, results, strict=True): report = m.report(found, period, result, as_of) report.id = f"{f.measure_id(found.id)}-{text.lower()}" reports.append(report) @@ -652,4 +684,6 @@ _STANDARD = { "subject": "reference", "measure": "reference", "follow-up-start": "date", + "name": "string", + "identifier": "token", } diff --git a/webapi/ingest.py b/webapi/ingest.py index 3d06ff5..2c202dd 100644 --- a/webapi/ingest.py +++ b/webapi/ingest.py @@ -1,10 +1,9 @@ """/conectar: look into a site's sources, draw and save pipelines, run them, inspect nodes.""" -from pathlib import Path as FilePath from typing import Annotated, Any from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError -from fastapi import APIRouter, Depends, HTTPException, Path, Query, UploadFile +from fastapi import APIRouter, Depends, HTTPException, Path, Query from fhir.resources.R4B.conceptmap import ConceptMap from pydantic import BaseModel @@ -12,7 +11,6 @@ from core import concept_map from core.pipeline import ID_PATTERN, ImportPath, Pipeline, Source, redacted, restored from core.schema import ENTITIES from persistance import config_log, nodes -from persistance.config import DATA_DIR from webapi.runs import dagster router = APIRouter(prefix="/ingest", tags=["ingest"]) @@ -21,11 +19,6 @@ NodeId = Annotated[str, Path(pattern=ID_PATTERN, max_length=40)] Rows = list[dict[str, Any]] -def _shown(row: dict) -> dict: - """A row as JSON: file contents shown by size, never sent whole.""" - return {k: f"<{len(v)} bytes>" if isinstance(v, bytes) else v for k, v in row.items()} - - def _from_source(call, *args): try: return call(*args) @@ -56,19 +49,7 @@ def source_resources(ref: SourceRef) -> list[str]: @router.post("/sources/preview") def source_preview(node: Source, limit: Annotated[int, Query(ge=1, le=200)] = 20) -> Rows: """The first rows a source node would load.""" - return [_shown(r) for r in _from_source(nodes.preview, node, limit)] - - -@router.post("/uploads") -def upload(file: UploadFile) -> dict[str, str]: - """A CSV, Excel or document file for a `filesystem` source: use `bucket_url`.""" - name = FilePath(file.filename or "").name - if not name: - raise HTTPException(422, detail="the file needs a name") - folder = DATA_DIR / "uploads" - folder.mkdir(parents=True, exist_ok=True) - (folder / name).write_bytes(file.file.read()) - return {"bucket_url": str(folder), "file_name": name} + return [nodes.shown(r) for r in _from_source(nodes.preview, node, limit)] @router.get("/pipelines") @@ -168,7 +149,7 @@ def node_rows( """What a node produced in the last run (empty if it produced nothing yet).""" out = [] for row in nodes.rows(pipeline_id, node_id): - out.append(_shown(row)) + out.append(nodes.shown(row)) if len(out) == limit: break return out diff --git a/webapi/main.py b/webapi/main.py index 8547b8d..4322049 100644 --- a/webapi/main.py +++ b/webapi/main.py @@ -3,7 +3,7 @@ from fastapi.exception_handlers import http_exception_handler from starlette.exceptions import HTTPException from core.domains import Domain -from webapi import eeg, execution, fhir, ingest, models, preview, review, runs +from webapi import eeg, execution, fhir, ingest, models, preview, review, runs, sources, users from webapi.auth import caller app = FastAPI( @@ -11,8 +11,10 @@ app = FastAPI( version="0.0.0", dependencies=[Depends(caller)], # every route; where authentication will go generate_unique_id_function=lambda route: route.name, # clean names in the generated client + lifespan=users.lifespan, ) app.include_router(ingest.router) +app.include_router(sources.router) app.include_router(review.router) app.include_router(runs.router) app.include_router(execution.router) @@ -20,6 +22,7 @@ app.include_router(models.router) app.include_router(eeg.router) app.include_router(preview.router) app.include_router(fhir.router) +app.include_router(users.router) # sign-in for the web app; no route requires it @app.exception_handler(HTTPException) diff --git a/webapi/models.py b/webapi/models.py index 6b3aa69..6d68a92 100644 --- a/webapi/models.py +++ b/webapi/models.py @@ -14,6 +14,7 @@ from pydantic import BaseModel, Field, WithJsonSchema from core import tea from core.domains import Domain, InputSpec +from core.models import title from persistance import bundle, cluster, inputs, registry from persistance.cluster import Execution, Reference from webapi.runs import dagster, execution_config, submit @@ -31,10 +32,15 @@ class Version(BaseModel): status: Literal["champion", "retired", "candidate"] +class Model(BaseModel): + name: str + title: str + + @router.get("/{domain}") -def models(domain: Domain) -> list[str]: +def models(domain: Domain) -> list[Model]: prefix = f"{domain.value}." - return [n.removeprefix(prefix) for n in registry.names(prefix)] + return [Model(name=n.removeprefix(prefix), title=title(n)) for n in registry.names(prefix)] @router.get( @@ -121,7 +127,8 @@ def read_report(domain: Domain, name: str, version: int, report: str) -> Respons @router.post("/{domain}/{name}/versions/{version}/reports/clinical_validation") def add_clinical_validation(domain: Domain, name: str, version: int, file: UploadFile) -> dict: - """The clinical team's validation of a version: the third report promotion needs.""" + """The clinical team's validation of a version: the third report, which promotion needs + unless the site left it out of PROMOTION_REPORTS.""" registry.add_report(f"{domain.value}.{name}", version, "clinical_validation", file.filename or "report", file.file.read()) # fmt: skip return {"reports": sorted(registry.reports(f"{domain.value}.{name}", version))} @@ -129,8 +136,9 @@ def add_clinical_validation(domain: Domain, name: str, version: int, file: Uploa @router.post("/{domain}/{name}/versions/{version}/promote") def promote(domain: Domain, name: str, version: int) -> dict: - """The version risk batches come from from now on; refused (409) without its three - reports: technical validation, interpretability and clinical validation.""" + """The version risk batches come from from now on; refused (409) without the reports + the site requires (PROMOTION_REPORTS; default: technical validation, interpretability + and clinical validation).""" try: registry.promote(f"{domain.value}.{name}", version) except registry.UnknownVersion as e: diff --git a/webapi/review.py b/webapi/review.py index da8e206..2f8ef29 100644 --- a/webapi/review.py +++ b/webapi/review.py @@ -26,10 +26,17 @@ def conflicts(entity: EntityName) -> Rows: return review.conflicts(entity) +@router.get("/unrecognised") +def unrecognised(pipeline: Id) -> Rows: + """Documents a pipeline's routes don't recognise (what its `otherwise` routes took): + a new layout, a study the platform doesn't know, a scan nothing could read.""" + return review.unrecognised(pipeline) + + @router.get("/persons") def persons(pipeline: Id, node: Id) -> dict[str, Rows]: - """Persons to settle (with their possible owners) and torn persons (with their - records) left by a pipeline's link node.""" + """Persons to settle (with their possible owners), torn persons and persons nothing + names (with their records) left by a pipeline's link node.""" return review.persons(pipeline, node) diff --git a/webapi/sources.py b/webapi/sources.py new file mode 100644 index 0000000..525c0e0 --- /dev/null +++ b/webapi/sources.py @@ -0,0 +1,361 @@ +"""The Conectar dialog: the kinds of source an operator can pick, "Probar conexión", the +server folders they may browse, and the files they upload. Open like the rest of the API.""" + +import os +import re +import shutil +import uuid +from pathlib import Path, PurePosixPath +from typing import Annotated, Any, Literal + +from fastapi import APIRouter, Form, HTTPException, Query, UploadFile +from pydantic import BaseModel, ValidationError + +from core import sources +from core.pipeline import MASK, Pipeline, Source, restored +from persistance import config_log, nodes +from persistance.config import DATA_DIR + +router = APIRouter(prefix="/ingest", tags=["ingest"]) +UPLOADS = "uploads" + + +@router.get("/sources/types") +def source_types() -> sources.Catalog: + """Every kind of source the dialog offers, grouped, with the fields each one asks.""" + return sources.catalog() + + +class Answers(BaseModel): + type: str + answers: dict[str, Any] = {} + pipeline: str | None = None # editing a saved source: its secrets come back masked + node: str | None = None + + +class Tested(BaseModel): + ok: bool + message: str # in plain words, for the operator + detail: str | None = None # the source's own words, for whoever helps them + tables: list[str] = [] + rows: list[dict[str, Any]] = [] + + +# What a source's own error means, in words an operator can act on (first match wins). +PLAIN = [ + ( + r"login failed|password authentication failed|access denied|authentication|" + r"401|403|permission denied|invalid credentials", + "El usuario o la contraseña no son correctos, o no tiene permiso.", + ), # fmt: skip + ( + r"name or service not known|could not translate host|nodename nor servname|" + r"getaddrinfo|unknown host|no such host|resolve", + "No se encontró el servidor. Revise el nombre o la dirección.", + ), # fmt: skip + ( + r"timed out|timeout|connection refused|unable to connect|adaptive server is unavailable|" + r"could not connect|connection reset", + "El servidor no respondió. Revise la dirección, el puerto o si está encendido.", + ), # fmt: skip + ( + r"database .* does not exist|cannot open database|unknown database", + "No existe esa base de datos en el servidor.", + ), # fmt: skip + ( + r"no such table|invalid object name|does not exist|not found|no such file|404", + "No se encontró lo que pidió (la tabla, la carpeta o el archivo).", + ), # fmt: skip +] + + +def plain(error: BaseException) -> str: + said = f"{type(error).__name__}: {error}" + for pattern, message in PLAIN: + if re.search(pattern, said, re.IGNORECASE): + return message + return "No se pudo conectar. Abajo está lo que respondió el sistema." + + +def _with_saved_secrets(asked: Answers) -> dict[str, Any]: + if MASK not in repr(asked.answers): + return asked.answers + if not (asked.pipeline and asked.node and config_log.latest_version(asked.pipeline)): + raise HTTPException(422, detail="una contraseña oculta necesita la fuente guardada") + saved = config_log.get(asked.pipeline)[1] + node = {"id": asked.node, "kind": "source", "source": "core.sources:catalog", + "guided": {"type": asked.type, "answers": asked.answers}} # fmt: skip + try: + found = restored(Pipeline(nodes=[node]), saved).nodes[0] + except ValueError as e: + raise HTTPException(422, detail=str(e)) from e + return found.guided.answers + + +@router.post("/sources/test") +def test_source(asked: Answers, limit: Annotated[int, Query(ge=1, le=100)] = 20) -> Tested: + """ "Probar conexión": reaches the source with the answers given. A database lists its + tables (until one is picked; then its first rows); files and records show their first + rows. Never a server error: what went wrong comes back in plain words.""" + if asked.type not in sources.catalog().types: + raise HTTPException(404, detail=f"no source type {asked.type}") + answers = _with_saved_secrets(asked) + spec = sources.catalog().types[asked.type] + picked = all(answers.get(k) for k, f in spec.fields.items() if f.type == "table") + try: + if not picked and (listed := sources.listing(asked.type, answers)): + tables = nodes.resources(*listed) + count = "1 tabla" if len(tables) == 1 else f"{len(tables)} tablas" + return Tested(ok=True, message=f"Conexión correcta: {count}.", + tables=tables) # fmt: skip + node = Source(id="probe", guided={"type": asked.type, "answers": answers}) + rows = [nodes.shown(r) for r in nodes.preview(node, limit)] + except (sources.MissingAnswer, ValidationError) as e: # an answer missing: plain words + return Tested(ok=False, message=_missing(e)) + except Exception as e: # noqa: BLE001 - whatever the source says goes back to the operator + return Tested(ok=False, message=plain(e), detail=f"{type(e).__name__}: {e}"[:2000]) + found = ( + "Conexión correcta." + if rows + else ( + "Se conectó, pero no encontró archivos ni filas. Revise la ruta y qué archivos tomar." + ) + ) + return Tested(ok=True, message=found, rows=rows) + + +def _missing(e: Exception) -> str: + if isinstance(e, ValidationError): # raised while the node is made from the answers + return next((str(err["ctx"]["error"]) for err in e.errors() + if isinstance(err.get("ctx", {}).get("error"), sources.MissingAnswer)), + str(e)) # fmt: skip + return str(e) + + +def roots() -> dict[str, Path]: + """The folders the operator mounted for sources (SOURCE_ROOTS, separated by ":"), by + name; uploads always.""" + found = {"Subidos": (DATA_DIR / UPLOADS).resolve()} + for raw in filter(None, os.environ.get("SOURCE_ROOTS", "").split(os.pathsep)): + path = Path(raw).resolve() + found[path.name or str(path)] = path + return found + + +class Entry(BaseModel): + name: str + path: str # what a folder field takes + kind: Literal["folder", "file"] + size: int | None = None + + +class Browsed(BaseModel): + path: str | None # None: the list of roots + parent: str | None + entries: list[Entry] + + +@router.get("/sources/browse") +def browse(path: str | None = None) -> Browsed: + """The server folders a source may read: the roots, or what one folder under them + holds. Nothing outside the roots is shown.""" + allowed = roots() + if path is None: + return Browsed(path=None, parent=None, entries=[ + Entry(name=name, path=str(root), kind="folder") + for name, root in allowed.items() if root.is_dir()]) # fmt: skip + folder = Path(path).resolve() + root = next((r for r in allowed.values() if folder == r or r in folder.parents), None) + if root is None or not folder.is_dir(): + raise HTTPException(404, detail="esa carpeta no está entre las habilitadas") + entries = sorted( + (Entry(name=p.name, path=str(p), kind="folder" if p.is_dir() else "file", + size=None if p.is_dir() else p.stat().st_size) + for p in folder.iterdir() if not p.name.startswith(".")), + key=lambda e: (e.kind != "folder", e.name.lower())) # fmt: skip + return Browsed(path=str(folder), parent=None if folder == root else str(folder.parent), + entries=entries) # fmt: skip + + +class Uploaded(BaseModel): + bucket_url: str # the folder: what an upload field and a filesystem source take + files: list[str] + + +def _relative(name: str) -> PurePosixPath: + """A file's name as the browser sent it (a folder upload keeps its subfolders), never + reaching outside its folder.""" + parts = [p for p in PurePosixPath(name.replace("\\", "/")).parts if p not in ("", ".", "..")] + if not parts: + raise HTTPException(422, detail="the file needs a name") + return PurePosixPath(*parts) + + +@router.post("/uploads") +def upload(files: list[UploadFile], folder: Annotated[str | None, Form()] = None) -> Uploaded: + """Files from the operator's computer (one, many, or a whole folder), kept on the + server for a `filesystem` source; streamed to disk, so large recordings fit. Send + `folder` from a previous answer to add to the same set.""" + base = (DATA_DIR / UPLOADS).resolve() + target = Path(folder).resolve() if folder else base / uuid.uuid4().hex[:12] + if target.parent != base: + raise HTTPException(422, detail="folder is not an upload set") + kept = [] + for file in files: + relative = _relative(file.filename or "") + destination = target / relative + destination.parent.mkdir(parents=True, exist_ok=True) + with destination.open("wb") as out: + shutil.copyfileobj(file.file, out, length=1 << 20) + kept.append(str(relative)) + return Uploaded(bucket_url=str(target), files=kept) + + +# Sign-in buttons: OAuth 2.0 authorization code flow with PKCE (authlib). The dialog opens +# `start`'s address in a window; the provider sends the user back to `callback`, which +# hands the account to the dialog (window.opener) and closes. A pending sign-in is a file +# in the data folder for ten minutes, so whichever API worker gets the callback finds it. +PENDING = DATA_DIR / "oauth_pending" +PENDING_SECONDS = 600 +STATE = re.compile(r"[A-Za-z0-9_-]{8,128}") + + +def _pend(state: str, pending: dict[str, Any]) -> None: + import json + import time + + PENDING.mkdir(parents=True, exist_ok=True) + for old in PENDING.glob("*.json"): + if time.time() - old.stat().st_mtime > PENDING_SECONDS: + old.unlink(missing_ok=True) + path = PENDING / f"{state}.json" + path.write_text(json.dumps(pending)) + path.chmod(0o600) + + +def _claimed(state: str) -> dict[str, Any] | None: + """The pending sign-in of `state`, taken once (by an atomic rename), if still fresh.""" + import json + import time + + if not STATE.fullmatch(state): + return None + taken = PENDING / f"{state}.{uuid.uuid4().hex}.taken" + try: + (PENDING / f"{state}.json").rename(taken) + except FileNotFoundError: + return None + try: + fresh = time.time() - taken.stat().st_mtime <= PENDING_SECONDS + return json.loads(taken.read_text()) if fresh else None + finally: + taken.unlink(missing_ok=True) + + +def _registration(provider: str) -> tuple[sources.Provider, dict[str, str]]: + found = sources.catalog().providers.get(provider) + if found is None: + raise HTTPException(404, detail=f"no provider {provider}") + env = {k: os.environ.get(f"{found.env}_{k.upper()}", "") + for k in ("client_id", "client_secret", "tenant_id", "project_id")} # fmt: skip + if not (env["client_id"] and env["client_secret"]): + needed = f"{found.env}_CLIENT_ID y {found.env}_CLIENT_SECRET" + raise HTTPException(503, detail=( + f"Para iniciar sesión con {found.title}, el área de sistemas debe registrar la " + f"aplicación y darle al servidor {needed}.")) # fmt: skip + return found, env + + +def _endpoint(url: str, env: dict[str, str]) -> str: + return url.format(tenant=env["tenant_id"] or "organizations") + + +def _client(provider: sources.Provider, env: dict[str, str], redirect_uri: str): + from authlib.integrations.httpx_client import OAuth2Client + + return OAuth2Client(env["client_id"], env["client_secret"], scope=provider.scope, + redirect_uri=redirect_uri, code_challenge_method="S256") # fmt: skip + + +class SignIn(BaseModel): + url: str # where the dialog's window goes + state: str + + +@router.get("/sources/oauth/{provider}/start") +def oauth_start(provider: str, origin: str) -> SignIn: + """The provider's sign-in address. `origin` is the web app's (where the user returns: + `{origin}/api/…/callback`, the address IT registered).""" + import secrets + + found, env = _registration(provider) + redirect_uri = f"{origin.rstrip('/')}/api/ingest/sources/oauth/{provider}/callback" + verifier = secrets.token_urlsafe(48) + url, state = _client(found, env, redirect_uri).create_authorization_url( + _endpoint(found.authorize_url, env), code_verifier=verifier, **found.authorize_params + ) + _pend(state, {"provider": provider, "verifier": verifier, "redirect_uri": redirect_uri, + "origin": origin.rstrip("/")}) # fmt: skip + return SignIn(url=url, state=state) + + +def account(provider: str, token: dict[str, Any], env: dict[str, str]) -> dict[str, Any]: + """What a source needs to read as the signed-in user, and who they are (shown in the + dialog). Microsoft: msgraphfs's OAuth client parameters and the user's own drive; + Google: dlt's OAuth credentials for Drive.""" + import httpx + + found = sources.catalog().providers[provider] + bearer = {"Authorization": f"Bearer {token['access_token']}"} + if provider == "microsoft": + me = httpx.get("https://graph.microsoft.com/v1.0/me", headers=bearer).json() + drive = httpx.get("https://graph.microsoft.com/v1.0/me/drive", headers=bearer).json() + return { + "user": me.get("mail") or me.get("userPrincipalName") or me.get("displayName"), + "drive_id": drive.get("id"), + "oauth2_client_params": { + "client_id": env["client_id"], "client_secret": env["client_secret"], + "token_endpoint": _endpoint(found.token_url, env), "scope": found.scope, + "token": token, + }, + } # fmt: skip + about = httpx.get("https://www.googleapis.com/drive/v3/about", params={"fields": "user"}, + headers=bearer).json() # fmt: skip + credentials = {"client_id": env["client_id"], "client_secret": env["client_secret"], + "refresh_token": token.get("refresh_token"), + "project_id": env["project_id"] or None} # fmt: skip + return {"user": about.get("user", {}).get("emailAddress"), + "credentials": {k: v for k, v in credentials.items() if v}} # fmt: skip + + +@router.get("/sources/oauth/{provider}/callback", include_in_schema=False) +def oauth_callback(provider: str, state: str, code: str | None = None, error: str | None = None): + """Where the provider returns the user: the account goes to the dialog that asked.""" + import json + + from fastapi.responses import HTMLResponse + + pending = _claimed(state) + if pending is None or pending["provider"] != provider: + return HTMLResponse("

La solicitud de inicio de sesión venció. Cierre esta ventana " + "e inténtelo de nuevo.

", status_code=400) # fmt: skip + message: dict[str, Any] = {"type": "isssteleon-oauth", "state": state} + if error or not code: + message["error"] = "No se completó el inicio de sesión." + else: + found, env = _registration(provider) + try: + token = _client(found, env, pending["redirect_uri"]).fetch_token( + _endpoint(found.token_url, env), code=code, code_verifier=pending["verifier"] + ) + message["account"] = account(provider, dict(token), env) + except Exception as e: # noqa: BLE001 - shown to the person signing in + message["error"] = f"No se pudo iniciar sesión: {e}" + payload = json.dumps(message).replace("ISSSTELEON" + "

Listo. Puede cerrar esta ventana.

" + f"" + ) diff --git a/webapi/users.py b/webapi/users.py new file mode 100644 index 0000000..7e7528f --- /dev/null +++ b/webapi/users.py @@ -0,0 +1,169 @@ +"""Sign-in for the web app (fastapi-users): users, the domains each may see, and a session +cookie. It decides only what the web app shows; no API route requires a session, so +pipelines, the FHIR door and scripts answer as before. + +Users live in the platform database (`config.users`). The first administrator comes from +AUTH_ADMIN_EMAIL and AUTH_ADMIN_PASSWORD at startup; AUTH_SECRET signs the sessions (without +it, one is made and kept in the data folder). +""" + +import os +import secrets +import uuid +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from functools import cache + +from fastapi import APIRouter, Depends, FastAPI +from fastapi_users import BaseUserManager, FastAPIUsers, UUIDIDMixin, schemas +from fastapi_users.authentication import AuthenticationBackend, CookieTransport, JWTStrategy +from fastapi_users.exceptions import UserAlreadyExists +from fastapi_users_db_sqlalchemy import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase +from sqlalchemy import JSON, String, event, make_url, text +from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine +from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column + +from core.domains import Domain +from persistance.config import DATA_DIR, platform_url + +SESSION_HOURS = 10 +SCHEMA = "config" + + +class Base(DeclarativeBase): + pass + + +class User(SQLAlchemyBaseUserTableUUID, Base): + __tablename__ = "users" + __table_args__ = {"schema": SCHEMA} + name: Mapped[str] = mapped_column(String(120), default="") + # the domains the web app shows this user (an administrator sees every one) + domains: Mapped[list[str]] = mapped_column(JSON, default=list) + + +class UserRead(schemas.BaseUser[uuid.UUID]): + name: str = "" + domains: list[Domain] = [] + + +class UserCreate(schemas.BaseUserCreate): + name: str = "" + domains: list[Domain] = [] + + +class UserUpdate(schemas.BaseUserUpdate): + name: str | None = None + domains: list[Domain] | None = None + + +@cache +def _engine(): + """The platform database, opened asynchronously (SQLite: its `config` file attached).""" + url = make_url(platform_url()) + if url.drivername.startswith("sqlite"): + engine = create_async_engine(url.set(drivername="sqlite+aiosqlite")) + + @event.listens_for(engine.sync_engine, "connect") + def _attach(connection, _record): + path = DATA_DIR / f"platform__{SCHEMA}.db" + connection.execute(f"ATTACH DATABASE '{path}' AS {SCHEMA}") + + return engine + return create_async_engine(url.set(drivername="postgresql+asyncpg")) + + +async def _session() -> AsyncIterator[AsyncSession]: + async with async_sessionmaker(_engine(), expire_on_commit=False)() as session: + yield session + + +async def _users(session: AsyncSession = Depends(_session)): + yield SQLAlchemyUserDatabase(session, User) + + +@cache +def _secret() -> str: + if found := os.environ.get("AUTH_SECRET"): + return found + path = DATA_DIR / "auth_secret" + if not path.exists(): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(secrets.token_urlsafe(48)) + path.chmod(0o600) + return path.read_text().strip() + + +class Manager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]): + @property + def reset_password_token_secret(self) -> str: # type: ignore[override] + return _secret() + + @property + def verification_token_secret(self) -> str: # type: ignore[override] + return _secret() + + +async def _manager(users=Depends(_users)): + yield Manager(users) + + +backend = AuthenticationBackend( + name="cookie", + transport=CookieTransport( + cookie_name="isssteleon_session", + cookie_max_age=SESSION_HOURS * 3600, + cookie_secure=os.environ.get("AUTH_COOKIE_SECURE", "") == "1", # behind HTTPS + cookie_samesite="lax", + ), + get_strategy=lambda: JWTStrategy(secret=_secret(), lifetime_seconds=SESSION_HOURS * 3600), +) +users = FastAPIUsers[User, uuid.UUID](_manager, [backend]) +current_user = users.current_user(active=True) + +router = APIRouter() +router.include_router(users.get_auth_router(backend), prefix="/auth", tags=["auth"]) +router.include_router(users.get_users_router(UserRead, UserUpdate), prefix="/users", tags=["users"]) +admins_only = [Depends(users.current_user(active=True, superuser=True))] +router.include_router( # an administrator adds users + users.get_register_router(UserRead, UserCreate), + prefix="/users", + tags=["users"], + dependencies=admins_only, +) + + +async def first_admin() -> None: + """The users table, and the administrator AUTH_ADMIN_EMAIL names (once).""" + async with _engine().begin() as connection: + if connection.dialect.name != "sqlite": # SQLite: the attached file is the schema + await connection.execute(text(f"create schema if not exists {SCHEMA}")) + await connection.run_sync(Base.metadata.create_all) + email, password = os.environ.get("AUTH_ADMIN_EMAIL"), os.environ.get("AUTH_ADMIN_PASSWORD") + if not (email and password): + return + async with async_sessionmaker(_engine(), expire_on_commit=False)() as session: + manager = Manager(SQLAlchemyUserDatabase(session, User)) + try: + admin = UserCreate(email=email, password=password, is_superuser=True, + name="Administrador", domains=list(Domain)) # fmt: skip + await manager.create(admin) + except UserAlreadyExists: + pass + + +@asynccontextmanager +async def lifespan(_app: FastAPI) -> AsyncIterator[None]: + """Each API worker starts here; one at a time (a lock in the data folder), so the + users table, the first administrator and the session secret are made once.""" + import fcntl + + DATA_DIR.mkdir(parents=True, exist_ok=True) + with open(DATA_DIR / "startup.lock", "w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + try: + _secret() + await first_admin() + finally: + fcntl.flock(lock, fcntl.LOCK_UN) + yield