c326f4901d
Remove 64 Python docstrings and 39 comments, and trim prose from three noqa pragmas. The submodule had zero tracked Markdown files. Move published route descriptions into decorator arguments and the Correction schema description into ConfigDict. Drop internal docstrings, including the OAuth callback excluded from OpenAPI. Published route descriptions are unchanged in the before-and-after comparison of the nine application routers. The full application OpenAPI check requires fastapi-users, which is missing from the shared environment.
370 lines
14 KiB
Python
370 lines
14 KiB
Python
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",
|
|
description="Every kind of source the dialog offers, grouped, with the fields each one asks.",
|
|
)
|
|
def source_types() -> sources.Catalog:
|
|
return sources.catalog()
|
|
|
|
|
|
class Answers(BaseModel):
|
|
type: str
|
|
answers: dict[str, Any] = {}
|
|
pipeline: str | None = None
|
|
node: str | None = None
|
|
|
|
|
|
class Tested(BaseModel):
|
|
ok: bool
|
|
message: str
|
|
detail: str | None = None
|
|
tables: list[str] = []
|
|
rows: list[dict[str, Any]] = []
|
|
|
|
|
|
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",
|
|
description=(
|
|
'"Probar conexión": reaches the source with the answers given. A '
|
|
"database lists its\n"
|
|
"tables (until one is picked; then its first rows); files and "
|
|
"records show their first\n"
|
|
"rows. Never a server error: what went wrong comes back in plain "
|
|
"words."
|
|
),
|
|
)
|
|
def test_source(asked: Answers, limit: Annotated[int, Query(ge=1, le=100)] = 20) -> Tested:
|
|
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:
|
|
return Tested(ok=False, message=_missing(e))
|
|
except Exception as e: # noqa: BLE001
|
|
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):
|
|
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]:
|
|
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
|
|
kind: Literal["folder", "file"]
|
|
size: int | None = None
|
|
|
|
|
|
class Browsed(BaseModel):
|
|
path: str | None
|
|
parent: str | None
|
|
entries: list[Entry]
|
|
|
|
|
|
@router.get(
|
|
"/sources/browse",
|
|
description=(
|
|
"The server folders a source may read: the roots, or what one "
|
|
"folder under them\n"
|
|
"holds. Nothing outside the roots is shown."
|
|
),
|
|
)
|
|
def browse(path: str | None = None) -> Browsed:
|
|
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
|
|
files: list[str]
|
|
|
|
|
|
def _relative(name: str) -> PurePosixPath:
|
|
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",
|
|
description=(
|
|
"Files from the operator's computer (one, many, or a whole "
|
|
"folder), kept on the\n"
|
|
"server for a `filesystem` source; streamed to disk, so large "
|
|
"recordings fit. Send\n"
|
|
"`folder` from a previous answer to add to the same set."
|
|
),
|
|
)
|
|
def upload(files: list[UploadFile], folder: Annotated[str | None, Form()] = None) -> Uploaded:
|
|
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)
|
|
|
|
|
|
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:
|
|
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
|
|
state: str
|
|
|
|
|
|
@router.get(
|
|
"/sources/oauth/{provider}/start",
|
|
description=(
|
|
"The provider's sign-in address. `origin` is the web app's "
|
|
"(where the user returns:\n"
|
|
"`{origin}/api/…/callback`, the address IT registered)."
|
|
),
|
|
)
|
|
def oauth_start(provider: str, origin: str) -> SignIn:
|
|
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]:
|
|
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):
|
|
import json
|
|
|
|
from fastapi.responses import HTMLResponse
|
|
|
|
pending = _claimed(state)
|
|
if pending is None or pending["provider"] != provider:
|
|
return HTMLResponse("<p>La solicitud de inicio de sesión venció. Cierre esta ventana "
|
|
"e inténtelo de nuevo.</p>", 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
|
|
message["error"] = f"No se pudo iniciar sesión: {e}"
|
|
payload = json.dumps(message).replace("</", "<\\/")
|
|
target = json.dumps(pending["origin"])
|
|
return HTMLResponse(
|
|
"<!doctype html><meta charset=utf-8><title>ISSSTELEON</title>"
|
|
"<p>Listo. Puede cerrar esta ventana.</p>"
|
|
f"<script>window.opener&&window.opener.postMessage({payload},{target});"
|
|
"window.close()</script>"
|
|
)
|