Skip to content

Fix reading SQLite tables whose identifiers contain a double quote or a backslash - #121180

Closed
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:sqlite-read-identifier-escaping
Closed

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:sqlite-read-identifier-escaping

Conversation

@groeneai

@groeneai groeneai commented Sep 20, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed reading SQLite tables and columns whose names contain a double quote or a backslash. The SQLite table engine, the sqlite() table function and the SQLite database engine escaped identifiers with backslashes, which SQLite does not honour inside a quoted identifier, so such a table could not be read and the query failed with SQLITE_ENGINE_ERROR; a crafted column name could instead redirect the read to another table in the same database file.

Description

Related: #117421. That PR fixes the SQLite INSERT sink; this is the read path it scoped out, promised in #117421 (comment).

The four SQLite read call sites passed IdentifierQuotingStyle::DoubleQuotes, which emits an embedded " as \" and doubles a real backslash. SQLite, like the SQL standard and PostgreSQL, escapes " by doubling it and treats \ as a literal byte, so the identifier sent was not the one SQLite parsed: c"1 went out as "c\"1", and a\b as "a\\b". Reading such a table failed with Code: 591 ... SQL logic error (SQLITE_ENGINE_ERROR). CREATE TABLE succeeded, because structure inference passes the name as a literal, so after #117421 such a table is writable but never readable. Both characters are legal in SQLite identifiers.

This is an identifier-injection primitive, not only an unparseable name. A column named a" FROM other_table -- went out as SELECT "a\" FROM other_table --" FROM "target", a valid statement over other_table: on master that read silently returns other_table's rows. It stays within one statement and one file: SQLiteSource.cpp:53 passes pzTail == nullptr, so text after a ; is discarded rather than executed, and the same DDL author can already pass arbitrary SQLite text via the (SELECT ...) and query() forms.

The fix passes IdentifierQuotingStyle::DoubleQuotesPostgreSQL at those four sites. That enumerator is the SQL-standard delimited-identifier rule, byte-for-byte what SQLite requires, so no enum member, helper, dispatcher or shared header changes. DoubleQuotes is left untouched for its other consumers: the show_create_query_identifier_quoting_style setting value, Cassandra and the XDBC bridge.

The four sites reach two dispatchers, IAST::writeIdentifier and quoteExternalIdentifier, and both needed the change, so the test isolates each with its own arm. It covers the engine table-name, (SELECT ...) and query() forms, the table function, a pushed-down WHERE, both halves of the escaping rule, and two controls green on master.


Workflow [PR]
Sync PR [sync-upstream/pr/121180]

… a backslash

The SQLite read path passed IdentifierQuotingStyle::DoubleQuotes, which emits an
embedded `"` as `\"` and doubles a real backslash. SQLite, like the SQL standard
and like PostgreSQL, escapes `"` by doubling it and treats `\` as a literal byte,
so the identifier ClickHouse sent was not the identifier SQLite parsed: `c"1`
went out as `"c\"1"`, which SQLite tokenizes as the identifier `c\` followed by
stray SQL, and `a\b` went out as `"a\\b"`, a different name. Reading such a table
failed with SQLITE_ENGINE_ERROR. CREATE TABLE succeeded, because structure
inference passes the name as a SQLite string literal, so the table was writable
but never readable. Both characters are legal in SQLite identifiers, and such
names are created by SQLite itself.

IdentifierQuotingStyle::DoubleQuotesPostgreSQL is not a vendor quirk but the
SQL-standard delimited-identifier rule, and it is byte-for-byte what SQLite
requires, so this changes only which existing value the four read sites pass: the
generated wrapper column list and the table-name form in StorageSQLite::read, the
engine's `(SELECT ...)`/`query()` argument in registerStorageSQLite, and the same
argument in TableFunctionSQLite::parseArguments. Those four sites reach exactly
two dispatchers, IAST::FormatSettings::writeIdentifier and
quoteExternalIdentifier, and both already implement that rule, so no enum member,
helper, dispatcher or shared header changes. Fixing either dispatcher alone would
have been insufficient, which the new test pins with one arm per dispatcher. The
SQLite database engine references no quoting style and inherits the fix
transitively.

DoubleQuotes keeps its behaviour for its other consumers: the
show_create_query_identifier_quoting_style setting value, Cassandra and the XDBC
bridge. No setting is added or changed.

This is not an injection. Reads go through sqlite3_prepare_v2, which compiles a
single statement, so a mis-quoted identifier fails loudly instead of executing a
statement list. The INSERT sink defect is separate.

Related: ClickHouse#117421

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR labels Sep 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 finding), plus my own cold
review of the resulting tree (2 findings). No blockers and no majors in either pass, so nothing
was bounced back for a fix round.

# Sev Finding Verdict Evidence / action
1 💡 DoubleQuotes's documented consumer list still names SQLite (src/Parsers/tests/gtest_identifier_quoting_style.cpp:20-21) AGREE, not blocking Verified: after this change the only remaining consumers are the show_create_query_identifier_quoting_style value, ExternalQueryBuilder, Cassandra and the ODBC/JDBC bridge, so the sentence is stale. It is prose in a file this PR does not touch, and no assertion depends on it: the suite pins both enumerators' outputs directly and passes.
2 💡 The new test compares captured stderr on the success path, and shell_config.sh forwards server logs at warning AGREE, not blocking A server warning on a passing query would break the byte-exact reference. 17 of the 18 stateless tests using this capture pattern do not neutralise logs either, this code path logs its generated query at LOG_TRACE (below the forwarded level), and 100 runs (50 randomized, 50 not) showed no corruption. The failure path already greps a single stable token, so it is unaffected.
3 💡 IdentifierQuotingStyle.h documents DoubleQuotesPostgreSQL in PostgreSQL-only terms although SQLite now selects it AGREE, not blocking The rule it states is already dialect-neutral in substance (" doubled, backslash literal), which is exactly SQLite's rule, and the call site carries a two-line note. The header line is outside this diff.

What I checked hardest, since none of it is visible in the diff:

  • The reused enumerator is exact, not approximate. writeDoubleQuotedStringPostgreSQL is open
    quote, double every ", close quote, every other byte passed through, which is SQLite's quoted
    identifier rule character for character.
  • It cannot emit an odd identifier unquoted. Both writers route through
    writeProbablyQuotedStringImpl, whose gate starts with isValidIdentifier, so a name holding "
    or \ is always quoted.
  • Carrier completeness, enumerated independently before reading the plan: exactly four sites in
    src/ select a quoting style for SQLite, all four are converted, and no unconverted use remains in
    either file. The SQLite database engine and fetchSQLiteTableStructure are not identifier carriers
    (the first builds StorageSQLite and inherits, the second passes the name as a string literal to
    pragma table_info). The INSERT sink is untouched and belongs to Fix SQL injection through identifiers when inserting into a SQLite table #117421, with no hunk overlap.
  • The approach matches existing in-tree convention.
    gtest_transform_query_for_external_database.cpp already documents the query-backed path as what
    StoragePostgreSQL and StorageSQLite do, and already pins a"b under both enumerators. This
    enumerator is treated as the shared SQL-standard style rather than a vendor quirk, which is why no
    new enum member was added.
  • Test liveness, traced arm by arm. Arms 5 and 6 are the load-bearing pair: arm 5 keeps the
    verbatim query() text clean and breaks only the generated wrapper column list, isolating
    quoteExternalIdentifier; arm 6 aliases the odd column to a plain name so the wrapper is clean and
    only the reserialized subquery text is odd, isolating IAST::writeIdentifier. Fixing one dispatcher
    alone leaves one of them red. Arms 1 and 9 pass before and after, so a vacuously failing harness
    cannot be mistaken for a pass, and the test asserts rows rather than error text.
  • no-parallel is deliberately absent. The two nearest sibling tests carry it, but six SQLite
    tests create ENGINE = SQLite tables and run parallel safe without it, one of them with thirteen
    such tables, and this test's database file is scoped per test database.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal
per finding. Findings on hunks unchanged by a fix round are auto-dropped.

Session id: cron:clickhouse-review-self-slot-58:20260920-110500

@clickhouse-gh clickhouse-gh Bot closed this Sep 20, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse-test 05233_sqlite_read_identifier_escaping fails on every run against pristine master and passes on every run with the fix. No randomization, timing or retry.
b Root cause explained? Yes. The four SQLite read sites passed IdentifierQuotingStyle::DoubleQuotes, which emits an embedded " as \" and doubles a real backslash. SQLite escapes " by doubling it and treats \ as a literal byte, so c"1 was sent as "c\"1" and a\b as "a\\b", i.e. not the identifiers SQLite parses. Verified in plain sqlite3 3.45.1 and in the engine's own Query: trace.
c Fix matches root cause? Yes. It passes the correct dialect value, IdentifierQuotingStyle::DoubleQuotesPostgreSQL (the SQL-standard delimited-identifier rule), at those four sites. No widened bound, no relaxed assertion, no reduced dataset, no no-random-* tag, no defensive check and no guard at the failure site.
d Test intent preserved / new tests added? Yes. No existing test was weakened, retagged or reduced. New regression test with 9 arms, one per scenario: the three engine-argument forms, the table function, a pushed-down WHERE, both halves of the escaping rule, one plain-identifier control and one negative control that passes on master today.
e Both directions demonstrated? Yes. Before: [ FAIL ], arms 2-8 print SQL logic error while both controls print their rows. After: [ OK ], all nine arms, reference byte-identical. The generated SQL was captured before and after for each arm, showing \" become "" and \\ become \.
f Fix is general across code paths? Yes. All four read sites in one change. This design has no compile-time safety net, so completeness is mechanical: after the edit, grep -n "IdentifierQuotingStyle" over both files returns exactly those 4 hits, all DoubleQuotesPostgreSQL, and grep -n "DoubleQuotes\b" returns zero. The SQLite database engine references IdentifierQuotingStyle nowhere and inherits the fix transitively, measured rather than argued: CREATE DATABASE ... ENGINE = SQLite then reading through it fails before and returns its rows after.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, for the input space that exists on this path: it is outbound SQL text generation for an identifier, so there are no value types, type wrappers or data formats involved. Covered on both halves of the rule, on both branches of the must_quote test, and on the table name and column name separately. A name holding both " and \ needs no extra arm, since the helper is one per-character loop with no cross-character state. Names containing a tab or newline are repaired by the same change.
h Backward compatible? (maintainer-approved exception only) Yes, and nothing is gated. No setting added or changed, so no SettingsChangesHistory.cpp entry; no persisted or transmitted format. DoubleQuotes is left byte-identical for its other consumers: the show_create_query_identifier_quoting_style setting value (pinned by 03230_show_create_query_identifier_quoting_style.sql, green), Cassandra and the XDBC bridge. For identifiers holding neither " nor \ the emitted bytes are unchanged.
i Invariants and contracts preserved? Yes. No signature, arity or pre/postcondition changes; only the value of an existing enum parameter, and every accepted value was already handled by both dispatchers on every branch. No lock, atomicity, ordering, block-structure or crash/restart path is involved. query('...') pass-through is byte-identical before and after, guarded by the negative-control arm.

Session id: cron:clickhouse-impl-self-slot-57:20260920-102400

@clickhouse-gh

clickhouse-gh Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f757c75]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 2/6) FAIL Performance dashboard
read_in_reverse_order_final #1 FAIL dashboard
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) ERROR
LLVM Coverage DROPPED

AI Review

Summary

This PR fixes SQLite read-side identifier escaping by switching the four SQLite read/query carriers to IdentifierQuotingStyle::DoubleQuotesPostgreSQL, which matches SQLite's quoted-identifier rules for embedded " and \. The new stateless test covers the table engine, the sqlite table function, query-backed sources, and pushed-down predicates. I did not find any remaining unconverted read path or unresolved contract issue in the current tree.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 20, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-foreign-db Connectivity to external databases (ODBC/JDBC, MySQL, PostgreSQL, etc.). label Sep 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7d58cea

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build profile diff infra, not reachable from this diff: the job aborts with a Python traceback out of run_comparison (ci/jobs/build_profile_diff_job.py:1623, reached from main() at :1623) when the CI logs cluster does not answer, instead of degrading to "no baseline". Its only work is reading that cluster; it neither builds nor runs the server. Fleet-wide in the last 24 hours: check_status = error on 320 rows across 320 distinct heads and 310 distinct pull requests, against 540 successes, and the job runs on pull requests only (0 rows at pull_request_number = 0). Open incident: #120462. Re-running or merging master cannot clear it while the endpoint keeps refusing #121048 (external, open). @ alexey-milovidov ruled on 2026-09-20 that this is the one to keep for this class (#120288 (comment)); my #118708 is stood down at his request
Stateless tests (amd_debug, parallel) / 05227_storage_settings_unknown_name true master, deterministic, not reachable from this diff: the server no longer stores the max_threads = DEFAULT reset on the CREATE, so SHOW CREATE prints SETTINGS disk = 'default' where the reference still expects SETTINGS disk = 'default', max_threads = DEFAULT. The in-job randomized-settings diagnosis reports the failure reproducible 159/159 runs with the same settings and 214/214 with randomization off, so it is not a randomization draw. On true master in the last 24 hours: 210 FAIL rows over 9 master heads and 13 distinct checks, first seen 05:31:02Z and last 14:04:49Z #121163 (mine, open)
Stateless tests (arm_binary, parallel) / 05227_storage_settings_unknown_name true master, deterministic, not reachable from this diff: the server no longer stores the max_threads = DEFAULT reset on the CREATE, so SHOW CREATE prints SETTINGS disk = 'default' where the reference still expects SETTINGS disk = 'default', max_threads = DEFAULT. The in-job randomized-settings diagnosis reports the failure reproducible 159/159 runs with the same settings and 214/214 with randomization off, so it is not a randomization draw. On true master in the last 24 hours: 210 FAIL rows over 9 master heads and 13 distinct checks, first seen 05:31:02Z and last 14:04:49Z #121163 (mine, open)
Finish Workflow / Post Hooks (new_tests_check.py) cascade of the 05227 rows above, not an independent failure: new_tests_check.py validates a bug fix when at least one per-arch Bugfix validation job reports OK or XFAIL, and both functional variants report DROPPED (Dropped due to previous failure [Stateless tests (amd_debug, parallel)]) while both integration variants report SKIPPED (Skipped, no integration tests updates), which is the correct outcome for a diff whose regression coverage is a stateless test. The hook has an input again once 05227 is green #121163 (mine, open), same root cause

Mergeable Check and PR are the praktika aggregators of the rows above, not an independent failure. Census of the paginated check-runs at this head: 173 distinct names, 49 green, 120 skipped, 4 red, and zero still queued or in progress. Fast test and Style check are green. This head also carries a superseded first attempt: 346 raw check-runs collapse to 173 distinct names, and for every name the latest run is the one counted here, so the CANCELLED rows belong to the earlier attempt and are not failures.

Gates: (a) 0 of 173 checks queued or running; (b) Finish Workflow completed (red, row above) and Mergeable Check completed; (c) 43.9 min since the last job finished, measured against the last completion at 2026-09-20T13:54:17Z; (d) all 4 ownable red rows owned, 0 ownerless, 0 new fix tasks needed.

Session id: cron:our-pr-ci-monitor:20260920-143138

@tiandiwonder tiandiwonder left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The description: "This is not an injection: reads go through sqlite3_prepare_v2, which compiles a single statement, so a mis-quoted identifier fails loudly" is wrong on both halves.

SQLiteSource.cpp:53 passes pzTail == nullptr, so a trailing statement is silently ignored rather than rejected; and "only the first statement executes" does not mean that statement cannot be altered — a column named a" FROM other_table -- formatted as SELECT "a\" FROM other_table --" FROM "target", so the embedded quote rewrites the FROM clause with no semicolon involved. That is an injection primitive, and closing it is what this PR does.

@tiandiwonder tiandiwonder self-assigned this Sep 21, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Both halves confirmed, and I have rewritten that sentence.

At source: SQLiteSource.cpp:53 and StorageSQLite.cpp:380 both pass nullptr for pzTail, so a trailing statement is dropped silently rather than rejected.

Measured end-to-end on clean master (26.10.1.1, fix not applied), against a SQLite file holding target (2 rows) and other_table (3 rows):

ClickHouse column name SQL the engine sent result
a (control) SELECT "a" FROM "target" 2 rows, target's data
a" FROM other_table -- SELECT "a\" FROM other_table --" FROM "target" 3 rows, no error
a" ; DROP TABLE target -- SELECT "a\" ; DROP TABLE target --" FROM "target" 1 row, no error, target still present

Row 2 is your example: the FROM clause is rewritten and the read silently returns rows from a table the query never named, so "fails loudly" was wrong. Row 3 is the pzTail half, and it also shows the tail is neither executed nor rejected.

I left the changelog category at Bug Fix. The reach is one statement over one database file, and the same DDL author can already ask for that data directly: on the same build, SQLite(path, query('SELECT secret FROM other_table')) returns [777,888,999], and the table function takes two arguments with an inferred structure (TableFunctionSQLite.cpp:98), so a chosen column name requires writing the CREATE TABLE in the first place. If you would rather see Critical Bug Fix, I will change it.

The ### Description now states the primitive with your example, and the changelog entry mentions the redirect.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d97d807

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build profile diff infra: the CI logs cluster read timed out (LogCluster select failed with exception then ReadTimeoutError against the staging endpoint), so the job exits 1 instead of skipping (issue #120462) #121048 (external, open)

156 checks succeeded, 18 were skipped, Finish Workflow is green, and no test row on this head is FAIL or ERROR in the CI database. PR is the aggregate rollup over the one failure above, not a separate result. The previous ledger covered the superseded head 7d58cea7478f6f8c586ee9c766429f05c69aff21.

Session id: cron:our-pr-ci-monitor:20260921-103829

@clickhouse-gh

clickhouse-gh Bot commented Oct 21, 2026

Copy link
Copy Markdown
Contributor

Dear @tiandiwonder, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@PedroTadim PedroTadim self-assigned this Nov 10, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@groeneai is this PR still needed? A similar fix went to master recently

@groeneai

Copy link
Copy Markdown
Collaborator Author

No, it is no longer needed. #104510 switched every SQLite read site to the new BackticksSQLite quoting style, which covers the same cases. I re-ran this PR's 9 test cases plus the a" FROM other_table -- column-name injection on current master (41a73dec307, 26.11.1.1): all 9 return the expected rows, and the injection is now rejected with no such column.

@PedroTadim PedroTadim closed this Nov 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-foreign-db Connectivity to external databases (ODBC/JDBC, MySQL, PostgreSQL, etc.). groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants