Skip to content

Support TLS/SSL for PostgreSQL connections - #110615

Merged
alexey-milovidov merged 48 commits into
masterfrom
postgresql-tls-support
Aug 13, 2026
Merged

alexey-milovidov merged 48 commits into
masterfrom
postgresql-tls-support

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 15, 2026 •

Copy link
Copy Markdown
Member

Adds TLS/SSL support to all PostgreSQL integrations.

Until now, ClickHouse could not establish an encrypted connection to a PostgreSQL server that enforces SSL, nor verify the server certificate: postgres::formatConnectionString only emitted dbname/host/port/user/password/connect_timeout, so libpq's sslmode/sslrootcert/sslcert/sslkey could never be set. The bundled libpq is already compiled with SSL support (USE_SSL is defined through pg_config_manual.h), so this change is purely about exposing the options — no build change is required.

The design follows the model agreed in the review discussion (#110615 (comment)) and already implemented for MySQL in #112070:

  • sslmode (disable, allow, prefer, require, verify-ca or verify-full) can be specified anywhere: as a named collection key or as a trailing key = value argument after the positional arguments. When unset, the libpq default of prefer applies.
  • sslrootcert (CA certificate), sslcert (client certificate) and sslkey (client private key) are paths to server-local files. They are only accepted from a named collection defined in the server configuration file (or from a dictionary defined there) and cannot be overridden in a query: the server opens the files with its own privileges, so a path taken from SQL would let anyone who can define a PostgreSQL source probe the local filesystem and authenticate with a client certificate they are not allowed to read themselves.
  • sslrootcert_pem, sslcert_pem and sslkey_pem accept the literal contents of the corresponding file (copy-pasteable, also usable in ClickHouse Cloud where there is no server filesystem to reference). They are accepted from anywhere — a query, a named collection created with SQL, an override of a configuration-defined collection — and are masked in logs and SHOW queries like a password. libpq can only load credentials from files, so the contents are materialized into a private temporary file (mode 0600, the permission libpq requires of a key file) whose lifetime is tied to the connection pool that uses it.

These parameters work for the PostgreSQL table engine, the postgresql table function, the PostgreSQL and MaterializedPostgreSQL database engines, the MaterializedPostgreSQL table engine, and PostgreSQL dictionaries. The dictionary source previously accepted an sslmode key but silently ignored it; it is now honored.

The integration test test_postgresql_ssl enables TLS on a PostgreSQL server at runtime, requires SSL via pg_hba.conf, and checks positive and falsifying cases on every surface (wrong CA rejected, client certificate required, contents overriding a configured path, restart survival, masking). A stateless test pins the [HIDDEN] masking and the rejection of paths from SQL on every surface.

Closes: #80787
Related: #112070

Changelog category (leave one):

  • New Feature

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

Support TLS/SSL connections to PostgreSQL for the PostgreSQL table engine, the postgresql table function, the PostgreSQL and MaterializedPostgreSQL database engines, and PostgreSQL dictionaries: sslmode plus the certificates and the key, given either as literal contents (sslrootcert_pem, sslcert_pem, sslkey_pem; masked like passwords) or as paths (sslrootcert, sslcert, sslkey; accepted only from a named collection defined in the server configuration file).

Add `sslmode`, `sslrootcert`, `sslcert` and `sslkey` parameters to all
PostgreSQL integrations so connections can be encrypted and the server
certificate verified. Previously there was no way to pass these options, so
`sslmode=require`/`verify-ca`/`verify-full` and client-certificate
authentication were impossible.

`postgres::formatConnectionString` now forwards the options to `libpq` (empty
values keep the `libpq` defaults, i.e. `sslmode=prefer`). They can be set via
named collection keys for the `PostgreSQL` table engine, the `postgresql` table
function, the `PostgreSQL` database engine and `PostgreSQL` dictionaries, and
additionally via the `materialized_postgresql_ssl_mode`,
`materialized_postgresql_ssl_root_cert`, `materialized_postgresql_ssl_cert` and
`materialized_postgresql_ssl_key` settings for the `MaterializedPostgreSQL`
database and table engines.

The bundled `libpq` is already compiled with SSL support (`USE_SSL` is defined
through `pg_config_manual.h`), so no build change is required. The `PostgreSQL`
dictionary source previously accepted an `sslmode` key but silently ignored it;
it is now honored.

Closes: #80787

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [15d2288]

Summary: ✅


AI Review

Summary

This PR adds TLS/SSL support across the PostgreSQL integrations, masks PEM credential contents in SHOW / formatted-query surfaces, and keeps temporary credential files alive across reconnects and metadata reloads. I reviewed the current head against the full diff and prior review threads and did not find a remaining correctness, compatibility, or security issue that warrants a new review comment.

Missing context / blind spots
  • ⚠️ I did not run the PostgreSQL integration suite locally; this review is based on the current code, the added tests, and the available PR discussion / CI summary.
  • ⚠️ The current PR report available from this environment only exposed the Build profile diff summary, so I could not independently inspect full test-shard reports here.
Final Verdict

✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.00% 79.00% +0.00%

Changed lines: Changed C/C++ lines covered: 324/342 (94.74%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jul 15, 2026
@mintlify

mintlify Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Jul 15, 2026, 8:24 PM

The Style check flagged tests/integration/test_postgresql_ssl for
missing __init__.py, which every integration test directory requires
to avoid pytest import path collisions.
alexey-milovidov and others added 2 commits July 16, 2026 16:14
…replication

Address the AI review on #110615
which pointed out that the SSL suite left three advertised behaviors unproven.

- Rework the fixture to build a small CA that signs both the server certificate
  and a client certificate, and set `ssl_ca_file` on the server. `sslrootcert`
  now points at the CA (the server certificate is signed by it), so the existing
  `verify-ca`/`verify-full` cases keep passing.
- Add a `certdb` database whose `pg_hba.conf` entry requires a verified client
  certificate (`hostssl certdb all all cert`, which maps the certificate CN to
  the database user). `test_client_certificate_authentication` reads it with
  `sslcert`/`sslkey`, and `test_client_certificate_is_required` shows the same
  connection is rejected without a client certificate.
- `test_postgresql_dictionary_over_ssl` exercises the `PostgreSQL` dictionary
  source over `verify-full` (the source used to accept `sslmode` and silently
  ignore it).
- `test_materialized_postgresql_database_ssl` now inserts a row after the
  database is created and waits for it, so the WAL consumer path (not only the
  initial snapshot) is proven to replicate over `verify-full`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the AI review's Request changes items in 9fa887b2df1 (after merging master):

  • Client certificates (sslcert/sslkey) — the test_postgresql_ssl fixture now builds a small CA that signs both the server certificate and a client certificate, and the server gets an ssl_ca_file. A new certdb database requires a verified client certificate (hostssl certdb all all cert, mapping the certificate CN to the database user). test_client_certificate_authentication reads it with sslcert/sslkey, and test_client_certificate_is_required shows the same connection is rejected without one. (sslrootcert now points at the CA, which signs the server certificate, so the existing verify-ca/verify-full cases keep passing.)
  • Dictionaries — test_postgresql_dictionary_over_ssl exercises the PostgreSQL dictionary source over verify-full (the source used to accept sslmode and then silently ignore it).
  • MaterializedPostgreSQL replication — test_materialized_postgresql_database_ssl now inserts a row after CREATE DATABASE and waits for it in mpg_ssl.mat_table, so the WAL consumer path (not just the initial snapshot) is proven to replicate over verify-full.

Note: I could not run the integration suite locally in this environment (merging master triggers a large rebuild and the shared docker daemon is contended), so CI is the validating run for these additions.

Comment thread src/Core/PostgreSQL/Utils.cpp Resolved
…ectory

`sslrootcert`/`sslcert`/`sslkey` were forwarded to libpq as server-local
filesystem paths without any validation, so any user able to define a
PostgreSQL external source could make the server open arbitrary local
certificate/key files and use resident client credentials against a
remote endpoint.

Following the established precedent (`FileDictionarySource`, `SQLite`,
`EmbeddedRocksDB`), the new `StoragePostgreSQL::validateSSLCertificatePaths`
requires every certificate/key path accepted from SQL to reside inside
`user_files_path` (relative paths are resolved against it) and throws
`PATH_ACCESS_DENIED` otherwise. It is applied in
`processNamedCollectionResult` (the `postgresql` table function, the
`PostgreSQL` table engine and both database engines), after the
`materialized_postgresql_ssl_*` SETTINGS merge of the
`MaterializedPostgreSQL` database and table engines, and for DDL-created
dictionaries. Dictionaries defined in server configuration files are
admin-controlled and keep arbitrary paths, and clickhouse-local is
exempt (it runs with the privileges of the invoking user). The libpq
special value `system` for `sslrootcert` is not treated as a path.

Addresses the AI review blocker on #110615
…ble engine

The table engine goes through its own registration and
replication-handler startup path in `StorageMaterializedPostgreSQL.cpp`
(separate from the database engine), so prove it independently: the
initial snapshot and a post-create insert are both replicated over a
`verify-full` connection.

Addresses the AI review test finding on #110615
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed both remaining AI-review findings (after merging master again):

  • Certificate/key path restriction (584ded2ec8e) — the new StoragePostgreSQL::validateSSLCertificatePaths requires every sslrootcert/sslcert/sslkey path accepted from SQL to reside inside the user_files directory (relative paths are resolved against it) and throws PATH_ACCESS_DENIED otherwise — the same boundary that FileDictionarySource, SQLite and EmbeddedRocksDB enforce. It covers the postgresql table function, the PostgreSQL table engine, both database engines (processNamedCollectionResult), the materialized_postgresql_ssl_* settings of both MaterializedPostgreSQL engines, and DDL-created dictionaries. Dictionaries defined in server configuration files stay admin-controlled (arbitrary paths), clickhouse-local is exempt, and the libpq special value system is not treated as a path. New tests: test_certificate_path_outside_user_files_is_rejected (all three SQL surfaces) and test_relative_certificate_path_is_resolved_against_user_files; the fixture now drops the certificates into user_files, and the docs state the restriction.
  • Standalone MaterializedPostgreSQL table engine (a23633d514d) — test_materialized_postgresql_table_engine_ssl creates a CREATE TABLE ... ENGINE = MaterializedPostgreSQL(...) table with materialized_postgresql_ssl_mode = 'verify-full' and waits for both the initial snapshot and a post-create insert to replicate, proving the separate registration and replication-handler path of StorageMaterializedPostgreSQL.cpp.

The five touched translation units compile cleanly; as before, the shared docker daemon in this environment is too contended for a local integration run, so CI is the validating run. The current reds are known unrelated issues: test_replicated_table_structure_alter (#110036) and the UBSan stress failure (#110343).

@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, could you investigate this Upgrade check (amd_release) failure and provide a fix in a separate PR? It is unrelated to this PR (PostgreSQL TLS) — it is a master-wide, flaky upgrade-compatibility issue.

Failure report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110615&sha=cd3230f13038705339c3080112f4877341d1a7ad&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29

Code: 115. DB::Exception: Unknown setting 'allow_experimental_text_index_positions': for storage MergeTree: Cannot attach table `test_3`.`tab` ... ATTACH TABLE test_3.tab ... INDEX idx (message) TYPE text(tokenizer = splitByNonAlpha, positions = 1) GRANULARITY 100000000) ENGINE = MergeTree ORDER BY (id) SETTINGS allow_experimental_text_index_positions = 1 ... (UNKNOWN_SETTING)

Root cause. #109900 renamed the text-index feature without a backward-compatibility alias:

  • MergeTree setting allow_experimental_text_index_positions → allow_experimental_text_index_phrase_search
  • text index argument positions → support_phrase_search

An older binary writes a table whose metadata references the old names; the new server then fails to attach it, so the upgrade check reports an error-level message. The old setting is not in OBSOLETE_MERGE_TREE_SETTINGS, and the old positions index argument is not accepted either.

Evidence it is unrelated and flaky. The same failure hit three different, unrelated PRs recently (none touching text indexes): #110615 (2026-07-17), #108950 (2026-07-14), #100394 (2026-07-13).

Suggested fix direction (a maintainer/feature-owner call on the compat policy):

  1. Add MAKE_OBSOLETE_MERGE_TREE_SETTING(M, Bool, allow_experimental_text_index_positions, false) to OBSOLETE_MERGE_TREE_SETTINGS so the removed setting is tolerated on ATTACH.
  2. Accept the old positions text-index argument as an alias of support_phrase_search when reading existing metadata.

I did not want to patch the experimental text-index feature unilaterally since the backward-compatibility policy for it is your/the feature owner's decision. No open tracking issue exists yet.

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov confirmed and fixed in a separate PR: #110787.

It implements both directions you suggested:

  1. MAKE_OBSOLETE_MERGE_TREE_SETTING(M, Bool, allow_experimental_text_index_positions, false) so the removed setting is tolerated on ATTACH.
  2. The legacy positions text-index argument is accepted as an alias of support_phrase_search when reading existing metadata (both names at once is rejected).

The experimental gate is skipped on ATTACH (an existing table must load even though the new experimental setting is not in its metadata); CREATE still requires allow_experimental_text_index_phrase_search = 1. Regression test 02346_text_index_positions_attach_compat reproduces the ATTACH cycle. This Upgrade check (amd_release) failure is unrelated to the PostgreSQL TLS PR.

The `test_postgresql_ssl` suite exercised the table function, the
`PostgreSQL` table engine, dictionaries, and both `MaterializedPostgreSQL`
surfaces, but never the plain `PostgreSQL` database engine. That engine has
its own registration and named-collection parsing path in
`DatabasePostgreSQL.cpp` (separate from `StoragePostgreSQL`), so its TLS
support was unproven.

Add `test_postgresql_database_engine_over_ssl`: it creates
`CREATE DATABASE ... ENGINE = PostgreSQL(pg_ssl, sslmode='verify-full',
sslrootcert=...)` over a verify-full connection and reads through one of
its tables, exercising the same `validateSSLCertificatePaths` /
`processNamedCollectionResult` chain for the database-engine surface.

Addresses the AI review request-changes finding on
#110615

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the AI review's Request changes item (the PostgreSQL database engine surface was untested):

  • 93450039a37 adds test_postgresql_database_engine_over_ssl to tests/integration/test_postgresql_ssl/test.py. It runs CREATE DATABASE ... ENGINE = PostgreSQL(pg_ssl, sslmode='verify-full', sslrootcert=...) over a verify-full connection and reads through one of its tables. This exercises the separate registration and named-collection parsing path in DatabasePostgreSQL.cpp (its processNamedCollectionResult / StoragePostgreSQL::validateSSLCertificatePaths chain), so the database-engine TLS surface is now proven alongside the table function, table engine, dictionary, and both MaterializedPostgreSQL surfaces.

The Upgrade check (amd_release) red is unrelated (the allow_experimental_text_index_positions -> allow_experimental_text_index_phrase_search rename with no obsolete alias) and is being fixed separately in #110787.

@groeneai

Copy link
Copy Markdown
Collaborator

Follow-up on the Upgrade check (amd_release) UNKNOWN_SETTING failure: opened #110865.

Since the setting and the positions index argument are experimental and the engine-side compat alias was declined (#110787), the fix is in the upgrade check itself: allow-list the exact removed setting name allow_experimental_text_index_positions in the upgrade error grep, mirroring the existing Unknown tokenizer: 'unicode_word' entry that already handles the sibling text-index tokenizer rename from #109900. Narrowed to the exact name so genuinely unknown settings are not masked.

The `test_postgresql_database_engine_over_ssl` test used the `pg_ssl` named
collection, which carries a `table` key. `CREATE DATABASE ... ENGINE =
PostgreSQL(...)` goes through `DatabasePostgreSQL`, which calls
`StoragePostgreSQL::processNamedCollectionResult(..., require_table=false)`;
that validator rejects the `table`/`query` keys, so the query failed with
`Unexpected key `table` in named collection` (Code 36) before the SSL path was
ever reached, leaving the database-engine TLS surface unproven.

Add a dedicated `table`-less named collection `pg_ssl_db` (host/port/database/
user/password only) and use it for the database-engine test, so the test now
actually exercises the `DatabasePostgreSQL` named-collection + TLS path.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed abcef8d42d09..9c97ca899e4a, addressing this round:

  • AI Blocker (SHOW CREATE TABLE drops the remote schema): DatabasePostgreSQL::getCreateTableQueryImpl now keeps a string-valued fifth positional argument — after the table name is inserted it lands in the table engine's own schema position — and drops only use_table_cache (including its deprecated numeric-fifth-argument form). Thread replied and resolved.
  • The 6 red integration jobs were this PR's own new test, and the failure was in the assertions, not the behavior: SHOW CREATE TABLE returns a single TSV row with quotes escaped as \', so "'test_table'" in show_create could never match even though the emitted DDL correctly preserved the TLS arguments. The test now unescapes the row, uses a dedicated non-public schema (show_create_schema) per the review's test ask, and pins that the schema survives while use_table_cache does not.
  • 02280_add_query_level_settings (Stateless amd_debug): Too many parts (1 ...) on the test's own INSERT — the insert-counts-its-own-part family already diagnosed on this PR for 02458_relax_too_many_parts (tracking issue 'parts_to_delay_insert' and 'parts_to_throw_insert' are checked in different processors indepentently #61260, fixes Perform the Too many parts check once per INSERT query #113045 / Do not count an insert's own parts in the "too many parts" check #114016 in progress). Unrelated, not clearable by a master merge.
  • AST fuzzer (amd_debug): Bad cast from type DB::ColumnNothing to DB::ColumnVector<char8_t> in FunctionComparison — known issue Logical error: Bad cast from type A to B (STID: 1499-2747) #113640, unrelated to this PR.
  • CH Inc sync: the private sync PR fails on the same test_postgresql_ssl jobs, so it clears once this push propagates.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

After we merged #112070, implement it similarly for Postgres here.

…thesized DDL

`DatabasePostgreSQL::getCreateTableQueryImpl` decided whether the fifth
positional argument of the database engine is the remote `schema` or
`use_table_cache` by inspecting the stored AST node for an `ASTLiteral` of type
`String`. But `registerDatabasePostgreSQL` folds every positional argument with
`evaluateConstantExpressionOrIdentifierAsLiteral` before reading that slot, so
the schema may legitimately be stored as an arbitrary constant expression, e.g.

    CREATE DATABASE pg ENGINE = PostgreSQL('h:5432', 'db', 'u', 'p', concat('show_', 'create_schema'))

In that form the argument is an `ASTFunction`, so it was dropped and
`SHOW CREATE TABLE` emitted a table-engine definition pointing back at
PostgreSQL's default schema.

Decide it from the already-parsed `configuration.schema` instead — the same
value the create path derived from the evaluated copy — and emit that folded
value as a literal, so the synthesized definition is independent of the shape of
the stored expression.

The regression test now also creates the database with the schema supplied as
`concat('show_create', '_schema')` and asserts the emitted definition keeps it
immediately before the TLS `key = value` arguments.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 9c97ca899e4a..30127bd2c6fc.

  • AI Major (SHOW CREATE TABLE still drops a non-literal positional schema): legit and fixed. DatabasePostgreSQL::getCreateTableQueryImpl decided whether the fifth positional argument is the remote schema or use_table_cache by checking the stored AST node for a string ASTLiteral, but registerDatabasePostgreSQL folds every positional argument with evaluateConstantExpressionOrIdentifierAsLiteral first, so the schema may be stored as any constant expression. It is now decided from the already-parsed configuration.schema and emitted as its folded literal value, which also makes the synthesized definition independent of the shape of the stored expression. The deprecated numeric-fifth-argument use_table_cache form is unaffected (configuration.schema stays empty there).
  • Test: test_database_engine_show_create_table_preserves_tls_arguments now also creates the database with concat('show_create', '_schema') as the schema, reads the nested table, and asserts the emitted definition keeps 'show_create_schema', sslmode = 'verify-full' with sslrootcert_pem = '[HIDDEN]'.

Sole CI red on 9c97ca899e4a is unrelated: 04357_distributed_alias_same_expression (Stateless tests, arm_binary, parallel) — the harness's own randomized-settings diagnosis reports it flaky (18/88 reruns failed with the same settings), and it is the known wrong-results issue #112987, whose fix #108855 is open and not yet on master, so merging master would not clear it.

The getValueBeforeQueryOverride narrowing of the empty-contents-override rejection is still pending #113947 (open); it will be ported to StoragePostgreSQL::getSSLParams once that lands on master.

@groeneai

Copy link
Copy Markdown
Collaborator

This looks already done on this branch, so before I open anything I want to be sure I am not duplicating your own work.

c985f266d6ec ("Rework PostgreSQL TLS support: credentials as contents, paths only in the configuration file", 2026-08-06) implements the #112070 model for Postgres: sslrootcert_pem/sslcert_pem/sslkey_pem accepted everywhere, paths accepted only when getSourceId() == CONFIG and rejected with BAD_ARGUMENTS anywhere else, contents materialized into a TemporarySecretFile owned by postgres::ConnectionInfo, and masking added to the shared tls_credentials_secret_keys table. All six surfaces are covered: the table function, the PostgreSQL table engine, both MaterializedPostgreSQL engines, the dictionary source and the PostgreSQL database engine.

I checked the two remaining parts of #112070 for a Postgres analogue:

One coverage gap, not a behavior gap: 04820_postgresql_tls_credentials pins masking on the formatted-query surface, but there is no Postgres counterpart to 04657_mysql_tls_credentials_query_tree. The behavior itself holds, since FunctionSecretArgumentsFinderTreeNodeImpl inherits the same table: on a master binary EXPLAIN QUERY TREE run_passes = 0 SELECT * FROM postgresql('h:1','d','t','u','p', ssl_ca_pem = 'x') prints constant_value: [HIDDEN], while sslrootcert_pem is still printed verbatim there because master lacks the key this branch adds.

Is there something specific left here for me? If it is that query-tree test, or something in the model I have read as done and is not, I will send it as a separate PR against master like #110787. All 45 commits here are yours, so I will not push to this branch.

alexey-milovidov and others added 2 commits August 10, 2026 23:44
…aths

The note in the PostgreSQL dictionary source docs claimed `sslrootcert`,
`sslcert` and `sslkey` are only accepted for a dictionary defined in a
server configuration file, but a named collection defined there is a
supported path-based route as well (`StoragePostgreSQL::getSSLParams`
gates on the collection's source being the configuration file). Widen
the wording to cover both routes.

Co-Authored-By: Claude Fable 5 <[email protected]>
Counterpart of `04657_mysql_tls_credentials_query_tree`: the TLS
credentials given as contents (`sslrootcert_pem`, `sslcert_pem`,
`sslkey_pem`) must be redacted in `EXPLAIN QUERY TREE` output, not only
in the formatted query. `run_passes = 0` dumps the tree without
resolving the table function, so no PostgreSQL server is needed.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Your reading is right — the contents-based model from #112070 has been implemented for Postgres on this branch since c985f266d6ec, and your two non-analogues (no shared-pool cache key in postgres::PoolWithFailover, and the getValueBeforeQueryOverride narrowing tracked behind #113947) match my own analysis. The query-tree coverage gap you found is now closed here directly: 04846_postgresql_tls_credentials_query_tree (0211243), mirroring 04657_mysql_tls_credentials_query_tree — verified against a scratch server on this branch's binary. So nothing is left here for a separate PR. The one remaining follow-up on this branch is porting the #113947 narrowing to StoragePostgreSQL::getSSLParams once that PR merges.

Status of this round (30127bd2c6fc): the sole AI-review finding (docs note narrower than the implementation) is fixed in f2d2da044994. Both CI reds are unrelated to this diff:

pull Bot pushed a commit to sonvt1710/ClickHouse that referenced this pull request Aug 11, 2026
…d named collections

The note claimed `ssl_ca`, `ssl_cert` and `ssl_key` are only accepted
for a dictionary defined in a server configuration file, but a named
collection defined there is a supported path-based route as well
(`StorageMySQL::getSSLParams` gates on the collection's source being
the configuration file). Widen the wording to cover both routes, the
same fix as applied to the PostgreSQL counterpart in
ClickHouse#110615.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status check on 0211243bcc0c (automated):

No changes needed on this branch itself.

@clickhouse-gh

clickhouse-gh Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 37 queries analysed

This PR adds TLS/SSL parameters to ClickHouse's PostgreSQL integration (table function, PostgreSQL/MaterializedPostgreSQL table and database engines, and the dictionary source) — entirely connection-string construction, argument parsing, and credential masking that the server's query-execution path never touches. The only flagged query, clickbench Q18, was already decided no_change because its median (1196.5 ms) sits inside master's current variance band; the -7.8% shift is run-to-run variance, not a PR effect. That deterministic suppression is consistent with the diff. No real regressions or improvements to report.

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 2bd7e15c-ed60-4376-9e4e-52bf64ba0705
  • MIRAI run: 0cac2694-d9bc-44a7-83af-3bd95840b6ee
  • PR check IDs:
    • clickbench_889324_1786535089
    • clickbench_889330_1786535089
    • clickbench_889347_1786535089
    • tpch_adapted_1_official_889355_1786535089
    • tpch_adapted_1_official_889381_1786535089
    • tpch_adapted_1_official_889395_1786535089

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status update (automated): the CH Inc sync red on 0211243bcc0c was a Check public build compile failure unrelated to this PR: public master updated NuRaft (new peer_id parameter of log_entries_ext) together with KeeperLogStore.h after this branch's merge-base, so the sync composite mixed the new NuRaft pin with the old 3-parameter override in KeeperLogStore.h. Merged master (conflict-free) to bring the branch up to date; the affected PostgreSQL translation units rebuild cleanly.

The two stress reds on the previous round remain tracked and unrelated: the stale set skip index (#112213, fix #112484 still open) and the uninterruptible analysis hung check (#112203).

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Now all good. Approved.

@alexey-milovidov alexey-milovidov self-assigned this Aug 12, 2026
bacek pushed a commit to bacek/ClickHouse that referenced this pull request Aug 12, 2026
… stores contents

The empty-override rejection in `StorageMySQL::getSSLParams` only ran
when the base named collection stored a credential *path*: with the
credential stored in the contents form (`ssl_ca_pem` / `ssl_cert_pem` /
`ssl_key_pem`), `get_path` returned at the empty-path fast path before
looking at `isQueryOverridden`, so a query could pass `ssl_ca_pem = ''`
and silently strip the collection-provided CA or client certificate,
e.g. disable the verification of the server certificate. The check is
now hoisted above the fast path, so an empty contents override is
rejected regardless of the form the stored credential has.

The same defect in the PostgreSQL counterpart (ClickHouse#110615) was flagged by
the AI review there; this is the twin fix for the MySQL surface that
had already merged in ClickHouse#112070.
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 12, 2026
Merged via the queue into master with commit c4dc947 Aug 13, 2026
181 checks passed
@alexey-milovidov
alexey-milovidov deleted the postgresql-tls-support branch August 13, 2026 00:06
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 13, 2026
pull Bot pushed a commit to admariner/ClickHouse that referenced this pull request Aug 14, 2026
| `sslrootcert_pem` | Contents of the CA certificate that the PostgreSQL server certificate is verified against. Optional. |
| `sslcert_pem` | Contents of the client certificate, for certificate-based authentication. Optional. |
| `sslkey_pem` | Contents of the private key belonging to `sslcert_pem`. Optional. |
| `sslrootcert`, `sslcert`, `sslkey` | The same credentials as paths to files on the server. Only allowed for a dictionary defined in a server configuration file, or through a named collection defined there, see below. Optional. |

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai are these paths going to be validated against the user_files_path allowed to read from?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

No, and no user_files_path check is needed: a path is never accepted from SQL in the first place.

Only a named collection (or dictionary) defined in the server configuration file may name a path, gated on named_collection.getSourceId() == SourceId::CONFIG (StoragePostgreSQL.cpp:609). Every SQL route rejects it with Code 36, measured at master 5c9f28e:

  • CREATE DICTIONARY ... SOURCE(POSTGRESQL(... sslrootcert '...')) -> "sslrootcert cannot be specified in a dictionary created with a DDL query. Pass the contents of the file in sslrootcert_pem instead" (PostgreSQLDictionarySource.cpp:52,261)
  • postgresql(..., sslrootcert='...') -> "can only be specified in a named collection defined in the server configuration file" (StoragePostgreSQL.cpp:715)
  • CREATE NAMED COLLECTION ... sslrootcert='...' -> same (StoragePostgreSQL.cpp:652)
  • postgresql(cfg_collection, sslrootcert='...') -> "cannot be overridden in a query" (StoragePostgreSQL.cpp:629)

So the reason a path is unsafe from SQL (the server opens the file with its own privileges) is handled by refusing it, not by scoping it. A user_files scope would be weaker: it still lets any user who can define a source probe that directory and authenticate with a client key they cannot read themselves. Paths in the configuration file are written by an operator and stay unrestricted, same trust model as #112070 for MySQL.

For the record, an earlier revision of this PR did scope the paths to user_files (validateSSLCertificatePaths); it was replaced by the contents-based model in c985f266d6e per the design agreed in #110615 (comment), so that function no longer exists at master.

This branch was successfully deployed

1 active deployment
staging - docs — 15d22880 Deployed Aug 12, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-feature Pull request with new product feature pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MaterializedPostgreSQL DB Engine: Support for TLS

5 participants