"""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 import re from dataclasses import dataclass 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} _LEADING_COMMENTS = re.compile(r"^\s*((--[^\n]*\n)|(/\*.*?\*/)|\s)*", re.S) @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) -> str: statement = query.strip().rstrip(";").strip() if ";" in statement: raise ConnectorError("la consulta debe ser una sola instrucción") body = _LEADING_COMMENTS.sub("", statement, count=1) first_word = body.split(None, 1)[0].upper() if body else "" if first_word not in ("SELECT", "WITH"): raise ConnectorError("la consulta debe ser un SELECT (o WITH ... SELECT)") return statement 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}