Skip to content

Fixes #38024: validate queryStatementSource in Timescale Test Connection - #38052

Merged
IceS2 merged 4 commits into
mainfrom
detail/bug-fix/fixes-38024-validate-querystatementsource-in-times-61bf12
Nov 27, 2026
Merged

IceS2 merged 4 commits into
mainfrom
detail/bug-fix/fixes-38024-validate-querystatementsource-in-times-61bf12

Conversation

@detail-app

@detail-app detail-app Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Detail bug report: View on Detail

Describe your changes:

Fixes #38024

I hardened the Timescale queryStatementSource handling against SQL injection by routing it through the existing validate_query_statement_source validator (added to postgres/utils.py by #33477 for the Postgres call sites). The Timescale copies had been left interpolating the raw, user-controlled value into the FROM clause of the query-history SQL, so a user who could edit a Timescale service connection could execute arbitrary SQL against the target database at Test Connection time (e.g. pg_stat_statements) UNION SELECT rolname, rolpassword FROM pg_authid --).

Type of change:

  • Bug fix

High-level design:

N/A — small change. The fix mirrors the Postgres hardening already shipped in #33477 at postgres/connection.py:188 and postgres/query_parser.py:75:

  • ingestion/src/metadata/ingestion/source/database/timescale/connection.py — the live attack surface: TimescaleConnection.test_connection builds the GetQueries probe that test_connection_db_common runs against the configured ingestion DB user. Replaced the raw self.service_connection.queryStatementSource or "pg_stat_statements" with validate_query_statement_source(self.service_connection.queryStatementSource) in the POSTGRES_TEST_GET_QUERIES.format(...) call.
  • ingestion/src/metadata/ingestion/source/database/timescale/query_parser.py — the dead copy in PostgresQueryParserSource.get_sql_statement. The module is not imported anywhere today (TimescaleUsageSource/TimescaleLineageSource inherit the validated PostgresQueryParserSource from postgres/query_parser.py), but the same fix prevents the flaw from silently regaining effect if it is ever re-registered.

The validator constrains the value to an optionally schema-quoted relation identifier (matching pg_stat_statements, my_schema.custom_pg_stat_statements, "Audit Schema"."Query Log", …) and raises ValueError for anything else, so it can no longer close the relation and append UNION SELECT / -- etc.

Tests:

Use cases covered

  • A malicious queryStatementSource (the two bug-report exploits — pg_authid UNION and pg_stat_file file-read — plus the Postgres validator's existing rejection set) raises ValueError("Invalid queryStatementSource ...") at timescale/connection.py:71 before test_connection_db_common is invoked, so no SQL reaches the database.
  • The same is true for the dead timescale/query_parser.py::get_sql_statement copy (defense-in-depth).
  • Empty/None queryStatementSource falls back to DEFAULT_QUERY_STATEMENT_SOURCE (pg_stat_statements) at both call sites — benign deployments that never set the field still work.
  • Valid identifiers (bare, schema-qualified, and quoted) are interpolated verbatim into the FROM clause unchanged, preserving the documented custom-view support.

Unit tests

  • Files added: ingestion/tests/unit/topology/database/test_timescale_query_statement_source.py (51 parametrized cases: 17 injection payloads × 2 call sites that must raise; valid-identifier pass-through; empty fallback; and wiring guards that assert each call site routes through validate_query_statement_source).
  • Coverage on the changed methods is full: validate_query_statement_source 100% covered, both new Timescale call sites fully covered across empty/valid/malicious branches. Module-level line coverage from nox -s unit-tests for the two files: timescale/connection.py 71%, timescale/query_parser.py 44% (the uncovered lines are the auth-strategy dispatch and the live-DB get_table_query stream, neither of which the fix touches).

Backend integration tests

  • Not applicable (no backend API changes).

Ingestion integration tests

  • Not run. PR CI runs only the ingestion unit tests; the merge queue runs tests/integration/. The fix touches two source modules under ingestion/src/metadata/ingestion/source/database/timescale/; the connector's integration suite (tests/integration/source/timescale/) is the relevant broader set and would run in the merge queue.

Playwright (UI) tests

  • Not applicable (no UI changes).

Visual regression baselines

  • Not applicable (no rendering change).

Manual testing performed

I drove TimescaleConnection.test_connection — the exact Python entry point the UI "Test Connection" button and a test-connection automation workflow dispatch to via Airflow — end-to-end against a live Postgres 16 container with statement logging enabled:

  1. Started Postgres 16 in Docker, enabled log_statement = 'all' + logging_collector = on, and created a custom view my_schema.custom_pg_stat_statements with the expected columns for the happy-path step.
  2. Built a TimescaleConnection service config pointing at the live DB with the malicious queryStatementSource = "pg_stat_statements) UNION SELECT rolname, rolpassword FROM pg_authid --" and called test_connection(metadata=...) (with a stubbed OpenMetadata.get_by_name returning the seeded Timescale TestConnectionDefinition).
  3. Exploit (pg_authid UNION): the call raised ValueError at timescale/connection.py:71; test_connection_db_common was not invoked; the postgres log had zero matches for pg_authid/UNION SELECT rolname.
  4. File-read variant (pg_stat_file('/tmp/pwned')): same behavior — ValueError at timescale/connection.py:71, no SQL reached the DB.
  5. Default happy path (unset queryStatementSource): test_connection returned; all mandatory steps passed against the live DB; GetQueries reached the DB and cleanly failed with the documented 42P01 undefined_table (relation "pg_stat_statements" does not exist) — not a validation error.
  6. Custom-view happy path (my_schema.custom_pg_stat_statements): the validator accepted the schema-qualified identifier and the custom-view SQL actually executed against the DB; all 7 test-connection steps passed.

I also started the OpenMetadata Java server against a Dockerized MySQL 8.0 + Elasticsearch 9.3 stack (after working around an ES 8.11 media_type_header_exception by upgrading to 9.3 and a Quartz UnknownHostException by adding the sandbox hostname to /etc/hosts), logged in as admin, and verified via PUT /api/v1/services/databaseServices that the server accepts and stores the malicious queryStatementSource in a Timescale service config verbatim (HTTP 200, value preserved) — confirming the server-side tier does not validate the SQL field; validation lives in the Python ingestion worker that Airflow runs, which is exactly the layer the fix patches and the manual steps above exercised.

The full UI-button → Airflow worker → DB chain was not exercised: POST /api/v1/automations/workflows rejected my hand-crafted TestConnection workflow payload with HTTP 400 Invalid request format (the polymorphic request field needs a discriminator the generated TypeScript client produces but my curl did not), and the Noop Airflow client used for the boot would not have run a dispatched workflow anyway. Both UI exit points dispatch to the same TimescaleConnection.test_connection method exercised above and asserted-against in the unit test's wiring checks.

UI screen recording:

Not applicable — backend-only ingestion security fix; no UI changes.

Checklist:

  • I have read the CONTRIBUTING document.
  • My PR title is Fixes <issue-number>: <short explanation>
  • My PR is linked to a GitHub issue via Fixes #<issue-number> above.
  • I have commented on my code, particularly in hard-to-understand areas.
  • For JSON Schema changes: I updated the migration scripts or explained why it is not needed. — N/A (no schema change).
  • For a UI feature or feature task: … — N/A (no UI changes).
  • I have added tests (unit / integration / Playwright as applicable) and listed them above.
  • Self-review: I reviewed the final diff against REVIEW.md (the pr-checklist skill runs it) and fixed every 🔴 finding, or answered it on the line below.
  • Decision check: … — N/A (mirrors a decision already recorded with the Postgres hardening in Mask secrets nested in collections, and validate outbound URLs, query source and attachment access #33477; no new durable decision).

Automatic Fixes PRs can be configured here.

RetriggerView in GreptileConfidence Score: 5/5

The PR appears safe to merge; the previous finding is fixed and no new issues were found.

Summary

The PR routes Timescale query-history relation names through the existing Postgres validator. The follow-up removes wiring-only tests while keeping checks for rejected SQL payloads, default values, and valid custom relation names.

  • Timescale query-history SQL accepts only valid relation names.

Reviews (2) · Last reviewed commit: "Remove wiring-only tests asserting valid..." · Reviewed by Greptile

queryStatementSource names a relation, so it is interpolated into the
FROM clause of the query-history SQL rather than bound as a parameter.
f669f7d (#33477) added validate_query_statement_source and wired it
into both Postgres call sites, but the Timescale copies in
timescale/connection.py (the live Test Connection path) and
timescale/query_parser.py (a dead copy that TimescaleUsageSource /
TimescaleLineageSource no longer import) kept interpolating the raw,
user-controlled value, leaving the rest of the statement open to being
rewritten via UNION SELECT / file-read functions at test-connection time.

Route both Timescale call sites through validate_query_statement_source,
mirroring postgres/connection.py:188 and postgres/query_parser.py:75.
@detail-app
detail-app Bot requested a review from a team as a code owner November 18, 2026 04:32
@detail-app
detail-app Bot requested a review from harshsoni2024 November 18, 2026 04:32
@harshsoni2024 harshsoni2024 added Ingestion safe to test Add this label to run secure Github workflows on PRs labels Nov 18, 2026
@IceS2
IceS2 requested review from IceS2 and removed request for harshsoni2024 November 27, 2026 06:24
@IceS2 IceS2 assigned IceS2 and unassigned harshsoni2024 Nov 27, 2026
@IceS2

IceS2 commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator

Can you check the pushed commit and review it?

@detail-app

detail-app Bot commented Nov 27, 2026

Copy link
Copy Markdown
Contributor Author

Re: #38052 (comment)

Reviewed the pushed commit 6452a973ef ("Share query history checks between PostgreSQL and Timescale"):

  • Shared helper: check_query_history in postgres/connection.py:144 now owns the validate → format → run_sql sequence. PostgresChecks.get_queries calls it (connection.py:193), and Timescale wires it via additional_checks={"GetQueries": partial(check_query_history, engine, ...)} (timescale/connection.py). This removes the duplicated interpolation/validation in Timescale. Confirmed test_connection_db_common supports the keyword-only additional_checks arg and merges it into test_fn (test_connections.py:304,337-338), and _test_connection_steps catches the ValueError from validate_query_statement_source and records it as a non-mandatory step failure with errorLog (test_connections.py:208-218) — so an invalid relation fails only the optional GetQueries step, not the whole test.
  • Error message: validate_query_statement_source (postgres/utils.py:552) no longer echoes the raw user-controlled value, which avoids reflecting the injection payload back — good.
  • Defense-in-depth: validate_query_statement_source is still called in timescale/query_parser.py:75, so the unregistered parser copy stays hardened.
  • Tests: rewritten to assert observable outcomes (real in-memory sqlite engine, step pass/fail, SQL content) instead of mock call-counts — addresses the earlier "test behavior, not wiring" feedback. All 15 tests in test_timescale_query_statement_source.py pass locally (15 passed in 0.25s). The 3 failures I saw in postgres/test_connection.py are from psycopg2 being absent in my local venv, not from this PR; CI py-tests-status is green.

LGTM. No changes needed from me.

@IceS2
IceS2 enabled auto-merge (squash) November 27, 2026 10:56
@IceS2
IceS2 merged commit 4f335d9 into main Nov 27, 2026
36 checks passed
@IceS2
IceS2 deleted the detail/bug-fix/fixes-38024-validate-querystatementsource-in-times-61bf12 branch November 27, 2026 11:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Ingestion safe to test Add this label to run secure Github workflows on PRs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Detail Bug] Timescale: SQL injection via unvalidated queryStatementSource in Test Connection

4 participants