Files
WebApi/tests/test_sql_policy.py
T
Roberto Treviño Cervantes fce6ccd40a reorganization
2026-10-31 12:47:59 -06:00

140 lines
6.5 KiB
Python

"""The SQL connector is the one import path where the client chooses what
the server connects to; these tests pin its guard rails (see
webapi.imports.connectors.sql_policy)."""
import pytest
import sqlalchemy as sa
from webapi.imports.connectors.errors import ConnectorError
from webapi.imports.connectors.sql import SqlConnector
from webapi.imports.connectors.sql_policy import SqlSourcePolicy
PRODUCTION_POLICY = SqlSourcePolicy(
allowed_dialects=frozenset({"mysql", "mariadb", "postgresql", "mssql"}), allowed_hosts=None
)
def test_sqlite_is_refused_by_default_policy(tmp_path):
with pytest.raises(ConnectorError, match="'sqlite' no está permitido"):
SqlConnector(f"sqlite:///{tmp_path / 'x.db'}", policy=PRODUCTION_POLICY)
def test_host_allowlist_is_enforced():
policy = SqlSourcePolicy(allowed_dialects=frozenset({"mysql"}), allowed_hosts=frozenset({"10.0.10.50"}))
with pytest.raises(ConnectorError, match="no está entre los permitidos"):
policy.check_url("mysql+pymysql://u:p@evil.example.com/db")
assert policy.check_url("mysql+pymysql://u:p@10.0.10.50/db").host == "10.0.10.50"
def test_refuses_the_applications_own_database(monkeypatch, tmp_path):
from persistance import settings as persistance_settings
own = tmp_path / "cacu.db"
monkeypatch.setattr(persistance_settings.settings, "cacu_database_url", f"sqlite:///{own}")
policy = SqlSourcePolicy(allowed_dialects=frozenset({"sqlite"}), allowed_hosts=None)
with pytest.raises(ConnectorError, match="propia aplicación"):
policy.check_url(f"sqlite:///{own}")
monkeypatch.setattr(persistance_settings.settings, "cama_database_url", "mysql+pymysql://app:pw@db.internal:3306/isss_cama")
mysql_policy = SqlSourcePolicy(allowed_dialects=frozenset({"mysql"}), allowed_hosts=None)
with pytest.raises(ConnectorError, match="propia aplicación"):
mysql_policy.check_url("mysql+pymysql://someone_else:pw@DB.internal:3306/isss_cama")
mysql_policy.check_url("mysql+pymysql://app:pw@db.internal:3306/hospital_legacy")
def test_an_explicit_default_port_does_not_bypass_the_own_database_check(monkeypatch):
from persistance import settings as persistance_settings
monkeypatch.setattr(persistance_settings.settings, "cacu_database_url", "mysql+pymysql://app:pw@db/isss_cacu")
policy = SqlSourcePolicy(allowed_dialects=frozenset({"mysql"}), allowed_hosts=None)
with pytest.raises(ConnectorError, match="propia aplicación"):
policy.check_url("mysql+pymysql://app:pw@db:3306/isss_cacu")
@pytest.mark.parametrize(
"query",
[
"DELETE FROM paciente",
"select 1; drop table paciente",
"UPDATE t SET a = 1",
"-- harmless\nDROP TABLE t",
"",
],
)
def test_only_single_select_queries_pass(query):
with pytest.raises(ConnectorError):
SqlSourcePolicy.check_query(query)
@pytest.mark.parametrize(
"query",
["SELECT * FROM t;", " with x as (select 1 as a) select a from x", "/* c */ SELECT 1", "SELECT 'a;b' AS literal"],
)
def test_select_queries_pass(query):
assert SqlSourcePolicy.check_query(query)
def test_a_writable_cte_is_rejected_by_parsing_the_query_not_matching_keywords():
"""`WITH d AS (DELETE FROM t RETURNING a) SELECT a FROM d` is a syntactic
SELECT at the top level, so a check that only looks at the first keyword
lets it through; parsing the query and inspecting the tree catches the
write hiding inside the CTE."""
with pytest.raises(ConnectorError, match="no puede escribir"):
SqlSourcePolicy.check_query("WITH d AS (DELETE FROM t RETURNING a) SELECT a FROM d")
def test_select_into_a_new_table_is_rejected():
"""SQL Server's `SELECT ... INTO` creates a table — a write a keyword
check would miss entirely, since the statement still starts with SELECT."""
with pytest.raises(ConnectorError, match="no puede escribir"):
SqlSourcePolicy.check_query("SELECT * INTO nueva_tabla FROM t", dialect="mssql")
def test_mysql_select_into_outfile_is_rejected():
"""MySQL's `SELECT ... INTO OUTFILE` writes a file to the server's own
filesystem. sqlglot's MySQL grammar doesn't model this clause at all, so
it fails to parse — rejected as invalid SQL, which is the safe default
for anything that can't be positively confirmed to be a plain read."""
with pytest.raises(ConnectorError):
SqlSourcePolicy.check_query("SELECT * FROM t INTO OUTFILE '/tmp/x.csv'", dialect="mysql")
def test_connection_is_read_only_even_for_a_write_the_query_parser_could_miss(tmp_path):
"""Defense in depth: even if a future sqlglot version or an edge-case
dialect quirk let a write-shaped query past `check_query`, the
connection itself is read-only and the transaction is always rolled
back, so the underlying database still refuses to execute it."""
db = tmp_path / "src.db"
engine = sa.create_engine(f"sqlite:///{db}")
with engine.begin() as conn:
conn.execute(sa.text("CREATE TABLE t (a INTEGER)"))
conn.execute(sa.text("INSERT INTO t VALUES (1), (2)"))
connector = SqlConnector(f"sqlite:///{db}", policy=SqlSourcePolicy(frozenset({"sqlite"}), None))
# Bypass check_query directly to isolate the read-only connection itself,
# rather than testing the parser twice.
connector._query, connector._table = "WITH d AS (DELETE FROM t RETURNING a) SELECT a FROM d", None
with pytest.raises(ConnectorError):
connector.preview()
with engine.connect() as conn:
assert conn.execute(sa.text("SELECT COUNT(*) FROM t")).scalar_one() == 2
def test_preview_only_fetches_the_limit_but_counts_everything(tmp_path):
db = tmp_path / "big.db"
engine = sa.create_engine(f"sqlite:///{db}")
with engine.begin() as conn:
conn.execute(sa.text("CREATE TABLE t (id INTEGER, cp TEXT)"))
conn.execute(sa.text("INSERT INTO t VALUES " + ",".join(f"({i}, '0{i:04d}')" for i in range(500))))
connector = SqlConnector(f"sqlite:///{db}", policy=SqlSourcePolicy(frozenset({"sqlite"}), None)).select_table("t")
preview = connector.preview(limit=5)
assert len(preview.sample_rows) == 5
assert preview.total_rows == 500
assert {c.name: c.inferred_type for c in preview.columns} == {"id": "integer", "cp": "string"}
custom = SqlConnector(f"sqlite:///{db}", policy=SqlSourcePolicy(frozenset({"sqlite"}), None)).select_query(
"SELECT id AS expediente FROM t WHERE id < 10"
)
assert custom.preview(limit=3).total_rows == 10
assert list(custom.read_rows({"expediente": "pac_id_hospital"}))[:2] == [{"pac_id_hospital": 0}, {"pac_id_hospital": 1}]