diff --git a/packages/hflow-server/src/hflow_server/_curation.py b/packages/hflow-server/src/hflow_server/_curation.py index 856779652..7726d51a5 100644 --- a/packages/hflow-server/src/hflow_server/_curation.py +++ b/packages/hflow-server/src/hflow_server/_curation.py @@ -29,7 +29,12 @@ from fastapi.responses import FileResponse, Response from pydantic import BaseModel, Field -from hflow.curation import CurationReport, curate +from hflow.curation import ( + CurationReport, + NonSingleSelectQueryError, + curate, + reject_non_single_select, +) from hflow.dataset import ManifestAlreadyExistsError, write_dataset_manifest from hflow.workspace import Workspace from hflow_server import _catalog, _connections, _media, _sidecar @@ -154,24 +159,21 @@ def _bad_sql_refusal(error: duckdb.Error) -> HTTPException: def _reject_non_single_select(user_sql: str) -> None: """Refuse anything that is not exactly one SELECT statement. - ``execute()`` with no bind parameters runs EVERY statement in the string - and returns only the LAST result, so a smuggled second statement - (``SELECT ...); CREATE TABLE ...; SELECT ... FROM (SELECT ...``) would run - silently -- preview 500s on the resulting shape and report answers over - the wrong statement. ``extract_statements`` parses the text WITHOUT - executing it; require exactly one statement whose type is SELECT. + ``hflow.reject_non_single_select`` owns the rule (exactly one statement + whose type is SELECT, judged by parsing with ``extract_statements`` + WITHOUT executing anything); this route only maps its two failure modes + onto the two client-facing 400s: DuckDB's own diagnostic for SQL the + parser rejects, the fixed sentence for SQL that is well-formed but not a + single SELECT. """ - parser_connection = duckdb.connect() try: - statements = parser_connection.extract_statements(user_sql) + reject_non_single_select(user_sql) except duckdb.Error as error: raise _bad_sql_refusal(error) from error - finally: - parser_connection.close() - if len(statements) != 1 or statements[0].type != duckdb.StatementType.SELECT: + except NonSingleSelectQueryError: raise HTTPException( status_code=400, detail="sql must be exactly one read-only SELECT statement" - ) + ) from None def _browsable_relations( diff --git a/packages/hflow-server/tests/test_server_curation_preview.py b/packages/hflow-server/tests/test_server_curation_preview.py index ded92a4fd..6a00d9ede 100644 --- a/packages/hflow-server/tests/test_server_curation_preview.py +++ b/packages/hflow-server/tests/test_server_curation_preview.py @@ -119,6 +119,7 @@ def test_preview_refuses_multiple_statements(api: TestClient) -> None: json={"sql": "SELECT 1; DROP TABLE episodes_raw"}, ) assert response.status_code == 400 + assert response.json()["detail"] == "sql must be exactly one read-only SELECT statement" def test_preview_refuses_a_paren_closing_smuggle_as_400_not_500(api: TestClient) -> None: @@ -150,6 +151,7 @@ def test_preview_refuses_a_non_select_single_statement(api: TestClient) -> None: # A single well-formed but non-SELECT statement is refused too. response = api.post("/api/v1/curation/preview", json={"sql": "CREATE TABLE t AS SELECT 1"}) assert response.status_code == 400 + assert response.json()["detail"] == "sql must be exactly one read-only SELECT statement" def test_preview_refuses_an_oversized_sql_body(api: TestClient) -> None: diff --git a/packages/hflow-server/tests/test_server_curation_report.py b/packages/hflow-server/tests/test_server_curation_report.py index 7c7564b04..a676c78bb 100644 --- a/packages/hflow-server/tests/test_server_curation_report.py +++ b/packages/hflow-server/tests/test_server_curation_report.py @@ -54,6 +54,7 @@ def test_report_refuses_a_plain_multi_statement(api: TestClient) -> None: json={"sql": "SELECT 1; DROP TABLE episodes_raw"}, ) assert response.status_code == 400 + assert response.json()["detail"] == "sql must be exactly one read-only SELECT statement" def test_report_over_an_empty_catalog(empty_catalog_api: TestClient) -> None: diff --git a/src/hflow/curation.py b/src/hflow/curation.py index 527d3a4c4..0793d73d2 100644 --- a/src/hflow/curation.py +++ b/src/hflow/curation.py @@ -505,8 +505,19 @@ def _refresh_local_catalog_connection( raise -def _reject_non_single_select(sql: str) -> None: - """Raise ValueError if *sql* is not exactly one SELECT statement. +class NonSingleSelectQueryError(ValueError): + """SQL that parsed cleanly but is not exactly one SELECT statement. + + The single-SELECT rule's failure modes stay distinct so a caller can face + them differently: a syntactically invalid string raises the parser's + ``duckdb.Error`` with DuckDB's own diagnostic, while this exception is a + WELL-FORMED input that just is not the one allowed shape — a lone + ``CREATE TABLE``, a multi-statement string, or no statements at all. + """ + + +def reject_non_single_select(sql: str) -> None: + """Raise ``NonSingleSelectQueryError`` unless *sql* is one SELECT statement. ``connection.execute()`` and ``connection.sql()`` both run **every** semicolon-separated statement in the input and return only the last @@ -514,18 +525,17 @@ def _reject_non_single_select(sql: str) -> None: (``SELECT ...; CREATE TABLE pwned AS SELECT ...``) and it will execute silently. ``extract_statements`` parses the text **without executing it** and lets us count statements and check their types before anything - touches the connection. A syntactically invalid string raises - ``duckdb.Error`` here — treat that as "not exactly one SELECT" too. + touches the connection. A syntactically invalid string propagates the + parser's ``duckdb.Error`` untouched — that is NOT this exception — so + the two failure modes stay distinguishable. """ parser_connection = duckdb.connect() try: statements = parser_connection.extract_statements(sql) - except duckdb.Error as exc: - raise ValueError("sql must be exactly one SELECT statement") from exc finally: parser_connection.close() if len(statements) != 1 or statements[0].type != duckdb.StatementType.SELECT: - raise ValueError("sql must be exactly one SELECT statement") + raise NonSingleSelectQueryError("sql must be exactly one SELECT statement") def _stage_manifest_and_count( @@ -534,20 +544,27 @@ def _stage_manifest_and_count( """COPY the query's result to the staged manifest; return its row count. ``sql`` is tenant-supplied on constrained connections. - ``_reject_non_single_select`` calls ``connection.extract_statements`` - to parse the input **without executing it** and raises ``ValueError`` - on any payload that is not exactly one SELECT statement — including - multi-statement injections separated by semicolons (e.g. - ``SELECT ...; CREATE TABLE pwned AS SELECT ...``), DDL-only input, or - syntactically invalid strings. ``connection.sql()`` is **not** the - guard: on duckdb 1.5.5 it silently executes all statements and returns - ``None`` for multi-statement input. ``write_parquet`` then materialises - the single confirmed-safe relation to the staged path. + ``reject_non_single_select`` parses the input **without executing it** + and refuses any payload that is not exactly one SELECT statement — + including multi-statement injections separated by semicolons (e.g. + ``SELECT ...; CREATE TABLE pwned AS SELECT ...``) and DDL-only input. + ``connection.sql()`` is **not** the guard: on duckdb 1.5.5 it silently + executes all statements and returns ``None`` for multi-statement input. + ``write_parquet`` then materialises the single confirmed-safe relation + to the staged path. + + A parser ``duckdb.Error`` here is surfaced as the same ``ValueError`` + this function has always raised for library callers; the + parse-failure/rule-rejection distinction the service relies on is intact + on ``reject_non_single_select`` itself. The row-count query only ever receives an internally-generated path, so it keeps the existing f-string form. """ - _reject_non_single_select(sql) + try: + reject_non_single_select(sql) + except duckdb.Error as exc: + raise ValueError("sql must be exactly one SELECT statement") from exc connection.sql(sql).write_parquet(str(staged_manifest)) (row_count,) = connection.execute( diff --git a/tests/test_catalog_curation.py b/tests/test_catalog_curation.py index 69aa96464..30f9bfdc2 100644 --- a/tests/test_catalog_curation.py +++ b/tests/test_catalog_curation.py @@ -18,7 +18,13 @@ ) from hflow.checks import camera_frame_stats from hflow.cli import main as cli_main -from hflow.curation import CurationReport, curate, open_catalog_connection +from hflow.curation import ( + CurationReport, + NonSingleSelectQueryError, + curate, + open_catalog_connection, + reject_non_single_select, +) from hflow.format import CATALOG_FORMAT_VERSION from hflow.testing import SyntheticEpisodeSpec, synthesize_episode from hflow.transform import EpisodeStamps @@ -909,6 +915,36 @@ def test_stage_manifest_and_count_rejects_non_single_select( connection.close() +def test_reject_non_single_select_refuses_a_single_non_select_statement() -> None: + # A lone well-formed CREATE TABLE parses cleanly but is not a SELECT: + # a rule rejection, never a parser error. + with pytest.raises(NonSingleSelectQueryError, match="exactly one SELECT"): + reject_non_single_select("CREATE TABLE t(x INT)") + + +def test_reject_non_single_select_refuses_multiple_statements() -> None: + with pytest.raises(NonSingleSelectQueryError, match="exactly one SELECT"): + reject_non_single_select("SELECT 1 AS one; CREATE TABLE pwned AS SELECT 1") + with pytest.raises(NonSingleSelectQueryError, match="exactly one SELECT"): + reject_non_single_select("SELECT 1 AS one; DROP TABLE episodes_raw") + + +def test_reject_non_single_select_accepts_a_single_select() -> None: + reject_non_single_select("SELECT 1 AS one") + reject_non_single_select("SELECT episode_id FROM episodes") + + +def test_reject_non_single_select_distinguishes_parse_failure_from_rule_rejection() -> None: + # Syntactically invalid SQL surfaces DuckDB's own parser error (which a + # service renders as the diagnostic message); a well-formed non-SELECT is + # the rule's ValueError instead. The server's 400 detail depends on the + # two staying apart. + with pytest.raises(duckdb.Error, match="Parser Error"): + reject_non_single_select("SELEC 1") + with pytest.raises(NonSingleSelectQueryError): + reject_non_single_select("CREATE TABLE t(x INT)") + + def test_write_parquet_and_copy_format_parquet_are_byte_identical( tmp_path: Path, ) -> None: