Repository navigation
Support TLS/SSL for PostgreSQL connections - #110615
Conversation
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]>
|
Workflow [PR], commit [15d2288] Summary: ✅
AI ReviewSummaryThis PR adds TLS/SSL support across the PostgreSQL integrations, masks PEM credential contents in Missing context / blind spots
Final Verdict✅ Approve LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 324/342 (94.74%) · Uncovered code |
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
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.
…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]>
|
Addressed the AI review's Request changes items in
Note: I could not run the integration suite locally in this environment (merging |
…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
|
Addressed both remaining AI-review findings (after merging
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). |
|
@groeneai, could you investigate this Root cause. #109900 renamed the text-index feature without a backward-compatibility alias:
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 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):
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. |
|
@alexey-milovidov confirmed and fixed in a separate PR: #110787. It implements both directions you suggested:
The experimental gate is skipped on |
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]>
|
Addressed the AI review's Request changes item (the
The |
|
Follow-up on the Since the setting and the |
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]>
|
🕵 Pushed
|
|
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.
|
🕵 Pushed
Sole CI red on The |
|
This looks already done on this branch, so before I open anything I want to be sure I am not duplicating your own work.
I checked the two remaining parts of #112070 for a Postgres analogue:
One coverage gap, not a behavior gap: 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. |
…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]>
|
🕵 Your reading is right — the contents-based model from #112070 has been implemented for Postgres on this branch since Status of this round (
|
…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]>
|
🕵 Status check on
No changes needed on this branch itself. |
|
📊 Cloud Performance Report ✅ AI verdict: 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
|
|
🕵 Status update (automated): the The two stress reds on the previous round remain tracked and unrelated: the stale |
alexey-milovidov
left a comment
There was a problem hiding this comment.
Now all good. Approved.
… 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.
| | `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. | |
There was a problem hiding this comment.
@groeneai are these paths going to be validated against the user_files_path allowed to read from?
There was a problem hiding this comment.
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 '...'))-> "sslrootcertcannot be specified in a dictionary created with a DDL query. Pass the contents of the file insslrootcert_peminstead" (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.
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::formatConnectionStringonly emitteddbname/host/port/user/password/connect_timeout, solibpq'ssslmode/sslrootcert/sslcert/sslkeycould never be set. The bundledlibpqis already compiled with SSL support (USE_SSLis defined throughpg_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-caorverify-full) can be specified anywhere: as a named collection key or as a trailingkey = valueargument after the positional arguments. When unset, thelibpqdefault ofpreferapplies.sslrootcert(CA certificate),sslcert(client certificate) andsslkey(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_pemandsslkey_pemaccept 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 andSHOWqueries like a password.libpqcan only load credentials from files, so the contents are materialized into a private temporary file (mode 0600, the permissionlibpqrequires of a key file) whose lifetime is tied to the connection pool that uses it.These parameters work for the
PostgreSQLtable engine, thepostgresqltable function, thePostgreSQLandMaterializedPostgreSQLdatabase engines, theMaterializedPostgreSQLtable engine, andPostgreSQLdictionaries. The dictionary source previously accepted ansslmodekey but silently ignored it; it is now honored.The integration test
test_postgresql_sslenables TLS on a PostgreSQL server at runtime, requires SSL viapg_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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Support TLS/SSL connections to PostgreSQL for the
PostgreSQLtable engine, thepostgresqltable function, thePostgreSQLandMaterializedPostgreSQLdatabase engines, andPostgreSQLdictionaries:sslmodeplus 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).