106 lines
4.8 KiB
Python
106 lines
4.8 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"])
|
|
def test_select_queries_pass(query):
|
|
assert SqlSourcePolicy.check_query(query)
|
|
|
|
|
|
def test_connection_is_read_only_even_for_a_select_shaped_write(tmp_path):
|
|
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))
|
|
with pytest.raises(ConnectorError):
|
|
# Passes the keyword check, but the read-only connection refuses it.
|
|
connector.select_query("WITH d AS (DELETE FROM t RETURNING a) SELECT a FROM d").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}]
|