Files
WebApi/webapi/imports/connectors/sql_policy.py
T

91 lines
3.6 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
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,oracle"
_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"invalid connection string: {exc}") from exc
dialect = url.get_backend_name()
if dialect not in self.allowed_dialects:
raise ConnectorError(
f"dialect {dialect!r} is not allowed for import sources (allowed: {', '.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"host {url.host!r} is not in the allowed import-source hosts")
if _same_database(url, _own_database_urls()):
raise ConnectorError("this connection points at the application's own database — not a valid import source")
return url
@staticmethod
def check_query(query: str) -> str:
statement = query.strip().rstrip(";").strip()
if ";" in statement:
raise ConnectorError("custom SQL must be a single statement")
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("custom SQL must be a SELECT (or WITH ... SELECT) query")
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 ""))
return (url.get_backend_name(), (url.host or "localhost").lower(), url.port, (url.database or "").lower())
return key(candidate) in {key(url) for url in own}