Files
WebApi/webapi/imports/connectors/sql_policy.py
T
Roberto Treviño Cervantes fce6ccd40a reorganization
2026-10-31 12:47:59 -06:00

115 lines
5.1 KiB
Python

"""What a client-supplied connection or query may reach. The SQL
connector is the one place where the client picks what the server connects
to, so:
- dialects are allowlisted (`WEBAPI_SQL_ALLOWED_DIALECTS`); sqlite is off
by default because its URL is a path on this server's filesystem;
- hosts can be allowlisted (`WEBAPI_SQL_ALLOWED_HOSTS`, comma-separated);
- the application's own databases are never a valid source;
- custom SQL must be a single SELECT/WITH statement (on top of the
read-only connection, not instead of it).
"""
import os
from dataclasses import dataclass
import sqlglot
from sqlglot import exp
from sqlalchemy.engine import URL, make_url
from sqlalchemy.exc import ArgumentError
from webapi.imports.connectors.errors import ConnectorError
_DEFAULT_DIALECTS = "mysql,mariadb,postgresql,mssql"
_DEFAULT_PORTS = {"mysql": 3306, "mariadb": 3306, "postgresql": 5432, "mssql": 1433}
# SQLAlchemy dialect name -> sqlglot's name for it, where they differ.
_SQLGLOT_DIALECTS = {"postgresql": "postgres", "mssql": "tsql", "mariadb": "mysql"}
# Anything that writes, wherever it sits in the tree: a top-level
# `SELECT ... INTO table`/`INTO OUTFILE`, or a writable CTE
# (`WITH t AS (DELETE FROM x RETURNING *) SELECT * FROM t` still parses as a
# top-level SELECT, so checking only the root node's type is not enough).
_WRITE_NODES = (exp.Into, exp.Insert, exp.Update, exp.Delete)
@dataclass(frozen=True)
class SqlSourcePolicy:
allowed_dialects: frozenset[str]
allowed_hosts: frozenset[str] | None
@classmethod
def from_env(cls) -> "SqlSourcePolicy":
dialects = os.environ.get("WEBAPI_SQL_ALLOWED_DIALECTS", _DEFAULT_DIALECTS)
hosts = os.environ.get("WEBAPI_SQL_ALLOWED_HOSTS")
return cls(
allowed_dialects=frozenset(d.strip().lower() for d in dialects.split(",") if d.strip()),
allowed_hosts=frozenset(h.strip().lower() for h in hosts.split(",") if h.strip()) if hosts else None,
)
def check_url(self, connection: "str | URL") -> URL:
try:
url = connection if isinstance(connection, URL) else make_url(connection)
except ArgumentError as exc:
raise ConnectorError(f"cadena de conexión inválida: {exc}") from exc
dialect = url.get_backend_name()
if dialect not in self.allowed_dialects:
raise ConnectorError(
f"el motor {dialect!r} no está permitido como fuente (permitidos: {', '.join(sorted(self.allowed_dialects))})"
)
if self.allowed_hosts is not None and (url.host or "").lower() not in self.allowed_hosts:
raise ConnectorError(f"el servidor {url.host!r} no está entre los permitidos como fuente")
if _same_database(url, _own_database_urls()):
raise ConnectorError("esta conexión apunta a una base de datos de la propia aplicación; no puede ser una fuente")
return url
@staticmethod
def check_query(query: str, *, dialect: str | None = None) -> str:
"""Parses the query with `sqlglot` (in the source's own SQL dialect,
when known) and inspects the resulting syntax tree, rather than
matching keywords on the raw text — a string check can't tell a
read-only `SELECT` from one hiding a write, e.g. MySQL's
`SELECT ... INTO OUTFILE` (writes a file to the server) or a
PostgreSQL CTE performing the write (`WITH t AS (DELETE FROM x
RETURNING *) SELECT * FROM t` is a syntactic SELECT at the top)."""
statement = query.strip()
if not statement:
raise ConnectorError("la consulta no puede estar vacía")
try:
parsed = [node for node in sqlglot.parse(statement, read=_SQLGLOT_DIALECTS.get(dialect, dialect)) if node is not None]
except sqlglot.errors.ParseError as exc:
raise ConnectorError(f"la consulta no es SQL válido: {exc}") from exc
if len(parsed) != 1:
raise ConnectorError("la consulta debe ser una sola instrucción")
root = parsed[0]
if not isinstance(root, (exp.Select, exp.Union, exp.Intersect, exp.Except)):
raise ConnectorError("la consulta debe ser un SELECT (o WITH ... SELECT)")
if root.find(*_WRITE_NODES) is not None:
raise ConnectorError("la consulta no puede escribir en el servidor de origen")
return statement.rstrip(";").strip()
def _own_database_urls() -> list[URL]:
from persistance.settings import settings
urls = []
for raw in (
settings.cacu_database_url,
settings.cama_database_url,
settings.tea_database_url,
settings.governance_database_url,
):
try:
urls.append(make_url(raw))
except ArgumentError:
continue
return urls
def _same_database(candidate: URL, own: list[URL]) -> bool:
def key(url: URL) -> tuple:
if url.get_backend_name() == "sqlite":
return ("sqlite", os.path.realpath(url.database or ""))
backend = url.get_backend_name()
port = url.port or _DEFAULT_PORTS.get(backend)
return (backend, (url.host or "localhost").lower(), port, (url.database or "").lower())
return key(candidate) in {key(url) for url in own}