Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 15 additions & 13 deletions packages/hflow-server/src/hflow_server/_curation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down
2 changes: 2 additions & 0 deletions packages/hflow-server/tests/test_server_curation_preview.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down
1 change: 1 addition & 0 deletions packages/hflow-server/tests/test_server_curation_report.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
51 changes: 34 additions & 17 deletions src/hflow/curation.py
Original file line number Diff line number Diff line change
Expand Up @@ -505,27 +505,37 @@ 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
result, so a tenant-supplied string can smuggle a second statement
(``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(
Expand All @@ -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(
Expand Down
38 changes: 37 additions & 1 deletion tests/test_catalog_curation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down