Repository navigation
Use parameterized queries in HiveStatsCollectionOperator - #66751
Conversation
|
Congratulations on your first Pull Request and welcome to the Apache Airflow community! If you have any issues or are unsure about any anything please check our Contributors' Guide
|
HiveStatsCollectionOperator builds its bookkeeping SQL (the SELECT and DELETE against hive_stats in the MySQL metastore, and the SELECT ... FROM <table> WHERE <partition_key> = '<value>' against Presto) by f-string-interpolating template-rendered fields (table, partition, dttm) directly into raw SQL strings. Per the security model in airflow-core/docs/security/security_model.rst and airflow-core/docs/security/sql.rst, Dag authors are trusted users responsible for sanitizing input before passing it to operators. The change here is defense-in-depth so that the operator does not rely on each Dag author to sanitize. The MySQL bookkeeping SELECT and DELETE now use %s placeholders with the parameters= kwarg of MySqlHook.get_records / .run, so the values are bound by the driver instead of interpolated. For the Presto SELECT, partition values are passed as bound parameters using the hook's declared placeholder (PrestoHook overrides the DbApiHook default to "?"). Identifiers (table name and partition column names) cannot be parameterized in standard SQL — they are validated against ^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)?$ for the table and ^[A-Za-z_][A-Za-z0-9_]*$ for partition keys, raising AirflowException on mismatch.
7ed5db6 to
4bb0946
Compare
…nOperator
The static check `check-no-new-airflow-exceptions` flagged the two new
`raise AirflowException` calls added in this PR (the table-identifier
allowlist and the partition-column allowlist).
Switch both to `raise ValueError`, matching the existing input-validation
pattern in the same provider (sensors/named_hive_partition.py:81 raises
`ValueError` for an invalid partition string).
This keeps the pre-existing `raise AirflowException("The query returned
None")` at line 161 untouched (that one is in the allowlist already) and
restores the AirflowException count for this file to its prior value.
Nataneljpwd
left a comment
There was a problem hiding this comment.
Looks good overall yet it won't work for all cases such as columns with special chars which is a breaking change, in presto it uses " and in MySQL it uses backticks, I think that it needs to be fixed before it can be merged
…jecting them The previous approach rejected any table or column identifier that was not a plain word, which broke valid Hive identifiers containing dashes or spaces. Instead, quote every identifier interpolated into the Presto stats query -- the table in FROM (per dotted component, so database.table still works), the partition columns in WHERE, and the metastore columns and their aliases projected in the SELECT -- using double quotes with embedded quotes doubled. Plain identifiers are still emitted bare, so existing Dags are unaffected. Partition values and the MySQL bookkeeping values stay bound as query parameters.
|
Pushed a fix. I dropped the reject-regex and instead quote the identifiers that get interpolated into the Presto SELECT: the table in |
Nataneljpwd
left a comment
There was a problem hiding this comment.
looks better, one last edge case and we are done
An identifier the caller already double-quoted (e.g. "weird-col") was re-escaped into """weird-col""", breaking the Presto stats query for users who quoted identifiers themselves. Recognize a well-formed double-quoted identifier and pass it through unchanged; anything else is still double-quoted with embedded quotes doubled, so injection payloads stay inert as a single identifier.
Nataneljpwd
left a comment
There was a problem hiding this comment.
Looks great!
Now there is no SQL injection nor will it break old queries, unless I missed something which I don't think so
Great job!
|
CI failed once here on a transient Docker Hub issue, not on this change. The That's a Docker Hub registry timeout on the runner (exit 125 = |
|
@potiuk , following up...Any more checks pending? |
potiuk
left a comment
There was a problem hiding this comment.
Thanks — this is a solid hardening pass. Moving the Presto WHERE values and the MySQL statements onto bound parameters is exactly right, and using presto.placeholder rather than hardcoding ? is a nice touch for connections that override it.
I tried to break _quote_presto_identifier and couldn't — "a" OR 1=1 --" comes back as """a"" OR 1=1 --""", a single correctly-escaped identifier, and the _QUOTED_IDENT_RE pass-through can't be fooled into leaving an unbalanced quote. The escaping logic itself is sound.
One genuine bug in how the table name is assembled, plus a note on the helper — both inline.
On framing: worth being explicit in the PR description that this is a robustness/correctness fix rather than a security vulnerability. Under Airflow's security model the Dag author is a trusted party who can already execute arbitrary code, so operator arguments aren't an untrusted input boundary. Saying so plainly avoids anyone routing this through the security process or reading the merge as a silent CVE fix.
Drafted-by: Claude Code (Opus 5); reviewed by @potiuk before posting
Quoting the table name per `self.table.split(".")` component treated a dot
inside a quoted identifier as a catalog/schema separator, so each fragment
matched neither the plain-identifier nor the quoted-identifier regex and both
halves were re-escaped: `"my.table"` became `"""my"."table"""` and
`db."odd.name"` became `db."""odd"."name"""`. Plain `db.tbl` and bare `tbl`
were unaffected, so this only hit the quoted-with-dot case, which is exactly
the case the quoting support exists for.
Move the assembly into `_quote_presto_table`, which splits on the dots
*outside* a quoted identifier, leaving a quoted component that contains a dot
intact.
Add `test_quote_presto_table` pinning the pass-through behaviour (bare,
qualified-plain, special-character, pre-quoted, embedded doubled quote, and
quoted-containing-a-dot), so a future refactor cannot quietly reintroduce the
double-escaping, plus the dotted cases at the emitted-SQL level in
`test_execute_quotes_table_identifier`.
|
Thanks @potiuk , both addressed, and I rewrote the PR description along the lines you suggested. The table-name split. You're right, and both examples reproduce exactly as you posted them. The assembly now lives in _QUALIFIED_NAME_PART_RE = re.compile(r'"(?:[^"]|"")*"|[^.]+')
def _quote_presto_table(table: str) -> str:
return ".".join(_quote_presto_identifier(part) for part in _QUALIFIED_NAME_PART_RE.findall(table))
The helper note. Added One thing worth flagging, which I have deliberately left out of this diff. The quoted-dotted case cannot actually reach the # providers/apache/hive/src/airflow/providers/apache/hive/hooks/hive.py:703-704
if db == "default" and "." in table_name:
db, table_name = table_name.split(".")[:2]So I still think the helper should be correct on its own terms, since it is the identifier-quoting primitive and the tests now pin it. But if you want the quoted-dotted case to be genuinely reachable end to end, that means changing how |
|
Awesome work, congrats on your first merged pull request! You are invited to check our Issue Tracker for additional contributions. |
Summary
HiveStatsCollectionOperatorbuilds its SQL by f-string-interpolating template-rendered fields (table,partition,dttm) directly into raw SQL strings: theSELECTandDELETEagainsthive_statsin the MySQL metastore, and theSELECT ... FROM <table> WHERE <partition_key> = '<value>'against Presto.This is a robustness and correctness fix, not a security fix. Under Airflow's security model the Dag author is a trusted party who can already execute arbitrary code, so operator arguments are not an untrusted input boundary and there is no vulnerability here. Please do not route this through the security process or read the merge as a silent CVE fix.
What the current code does get wrong is ordinary correctness. Any table or column name that is not a plain word identifier is interpolated bare and produces invalid SQL, so a Dag over a table with a hyphenated or spaced column name fails outright with a Presto parse error rather than collecting stats. Binding the values as parameters and quoting the identifiers fixes that, and as a side effect retires the string-concatenation pattern that
sql.rstdiscourages.What changed
SELECTandDELETEuse%splaceholders with theparameters=kwarg ofMySqlHook.get_records/.run, so values are bound by the driver instead of interpolated.SELECT, partition values are passed as bound parameters using the hook's declared placeholder (PrestoHookoverridesDbApiHook's default%sto?), rather than hardcoding?, so a connection that overridesplaceholderstill works.weird-colnow renders asCOUNT("weird-col")where it previously emitted invalid SQL."my.table",db."odd.name") stays a single identifier instead of being split and re-escaped.extra_exprsandassignment_funcstill accept Dag-authored SQL expressions by design and are intentionally unchanged.Test plan
test_quote_presto_identifierpins the identifier helper: plain, special-character, pre-quoted, embedded-doubled-quote, dotted-and-quoted, and malformed-quote inputs.test_quote_presto_tablepins the qualified-name assembly: bare, dotted-plain, special-character-per-component, pre-quoted, embedded-quote, and quoted-containing-a-dot names, plus a trailing-SQL input that stays one inert component.test_execute_quotes_table_identifier,test_execute_quotes_partition_columnandtest_execute_quotes_special_char_projection_columnassert the quoting reaches the emitted Presto SQL, and that the quoting does not leak into the values written tohive_stats.col.test_execute_parameterizes_mysql_bookkeeping_queriesandtest_execute_parameterizes_presto_partition_valuesverify the SQL is parameterized (no interpolation oftable/partitionvalues into the SQL body) and that the Presto query uses the hook's?placeholder.test_execute_delete_previous_runs_rowsandtest_runs_for_hive_statsupdated to assert the parameterized form.test_hive_stats.pymodule passes locally.Was generative AI tooling used to co-author this PR?
I used Claude to assist with this PR, following the Gen-AI Assisted contributions guidelines:
presto.placeholder, the MySQL parameterization, and the tests were iterated against the Presto/Trino identifier grammar and the Airflow security docs rather than blindly accepted.ruff==0.15.12) pass on both changed files.providers/apache/hive/with no unrelated changes.