Skip to content

Hide credentials in NATS/RabbitMQ addresses, XDBC connection strings and URL settings - #121425

Merged
alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:finish-mask-uri-password-sweep-121257
Sep 23, 2026
Merged

alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:finish-mask-uri-password-sweep-121257

Conversation

@groeneai

@groeneai groeneai commented Sep 21, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #121257
Related: #120407

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 credential masking for nats_url, rabbitmq_address, the jdbc/odbc connection string and the format_avro_schema_registry_url, url_base and s3_base settings in SHOW CREATE, system.tables and the query text in system.query_log: a password containing @ kept its tail visible, a userinfo with no password was not masked, and a credential-free URL whose query string contained @ was rewritten into a different host. A secret Kafka/RabbitMQ named-collection override in the engine arguments, and a secret named argument written before the positional ones, were not masked either. Closes #121257.

Description

On 26.8, SELECT 1 SETTINGS url_base = 'http://h:8080/d/[email protected]' is logged as url_base = 'http://h:[HIDDEN]@b.com', a host that is not the real one, and SET nats_url = 'u:secret@h:4222' is logged verbatim.

Six call sites used maskURIPassword, an unanchored scan whose extent matches no consumer in the tree: at once too narrow and too wide.

Swapping in maskURIUserinfo, which the issue asks for, turns a partial leak into a full one at five of the six: it is the Poco::URI bound, while libnats ends the userinfo at the last @, AMQP-CPP at the first @ after the scheme, and an XDBC connection string ClickHouse never parses. So nats://u:pa/ss@h:4222 authenticates with password pa/ss, which maskURIUserinfo leaves visible.

One rule instead, already the DatabaseURL.cpp policy: hide only the credential where ClickHouse owns the value's grammar, and do not echo a value whose grammar belongs to someone else. The broker addresses and the connection string are hidden whole; the three URL settings keep the partial mask and gain a fail-closed leg for a value with no scheme, since nothing validates them at SET time. The error that rejects such a value no longer echoes it either, which leaked it in full.

Reviewing that found the same defect one index out: Kafka and RabbitMQ read secret settings as named-collection overrides of their engine arguments and had no finder, and three scans started past index 0, so a secret named argument written before the positional ones was masked nowhere. Those scans start at 0 now, and the mysql/postgresql positional forms locate the password among the positional arguments, so an early named argument cannot shift it out of the mask.

format_display_secrets_in_show_and_select still shows the real value to a privileged reader. The issue's git grep criterion also needs #120407, which owns the four remaining callers.


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

Version info

  • Merged into: 26.10.1.538-master (included in 26.10 and later)

…and URL settings

Six call sites still masked a credential embedded in a URL-shaped value with
maskURIPassword, an unanchored scan that reproduces the old regular expression
([^:]+://[^:]*):([^@]*)@(.*) exactly: it masks from the first ':' after any
'://' to the first '@'. The masked extent has to cover whatever the value's
consumer treats as a credential, and that scan matches no consumer in the tree,
so it is at once too narrow (a password containing '@' keeps its tail, and a
userinfo with no password is not masked at all) and too wide (a credential-free
URL whose query string contains '@' is rewritten into a host that is not the
real one). All three show up in SHOW CREATE, system.tables and
system.query_log.

Swapping in maskURIUserinfo at every site, which is what the issue asks for,
would replace a partial leak with a full one at five of the six. That function
implements the RFC 3986 bound, which is Poco::URI's bound, and three of these
consumers are not Poco::URI:

  - libnats trims the value, takes the scheme as optional and ends the userinfo
    at the LAST '@' of the whole remainder, unbounded by the '/?#' that closes
    an authority (contrib/nats-io/src/url.c, natsUrl_Create; both halves go
    into the CONNECT frame in conn.c). So nats://u:pa/ss@h:4222 authenticates
    with password pa/ss, which maskURIUserinfo leaves untouched, and
    user:pass@h:4222 authenticates while neither masker touches it.
  - AMQP-CPP ends the login at the FIRST '@' after the scheme, again unbounded
    (contrib/AMQP-CPP/include/amqpcpp/address.h).
  - an XDBC connection string is never parsed by ClickHouse: it is read
    verbatim in ITableFunctionXDBC and forwarded to the bridge as one opaque
    parameter, so its grammar is the driver's. This repository's own examples
    put the password in a query parameter, and the majority spelling is
    DSN=...;Pwd=... . No URI scan can bound a credential in that.

A password containing '/' is an ordinary shape, so this is not a corner case.

Apply one rule instead: a value is echoed with only its credential hidden
where ClickHouse owns its grammar, and a value whose grammar belongs to
someone else is not echoed. The second half is already the policy in
DatabaseURL.cpp and in the old XDBC fallback. Concretely, the two broker
addresses and the XDBC connection string are hidden whole (for the brokers,
exactly when the value carries an '@', which is a superset of anything either
parser can read as a credential and is empty precisely when there is nothing
to hide, so the documented forms such as localhost:4222 and amqp://h:5672/v
stay fully visible).

The three query-level URL settings are read through Poco::URI, so there the
partial mask is right and is kept: it moves from maskURIPassword to
maskURIUserinfo, which is what fixes the reporter's three cases. They gain a
fail-closed leg, because nothing validates them at SET time, resolveURLBase
accepts a base whose '://' is anywhere rather than at the start, and a
statement is masked for logging before its settings are validated: a value
with no scheme in front of it therefore reaches a log, and no parser can say
which part of it is the credential. url_base additionally reaches the Azure
URL parser, where abfs and abfss put a non-secret container in front of the
'@', so it gets its own rule that skips the userinfo leg for those two
schemes; az and azure have no '@' in their grammar and need no exception.

Two holes in the XDBC named-collection branch close as a side effect of
dropping its bespoke helper for findSecretNamedArgument: only the first
occurrence of a duplicated datasource key used to be masked, and a key written
as a constant expression (concat('data', 'source') = ...) was applied by the
named-collection parser while being invisible to this finder, so the whole
connection string was echoed. The fail-closed scan that already covered that
hazard for the TLS keys is extracted and reused, leaving one carrier for it.
The anchored-scheme test is likewise reduced to one carrier, findURIAuthority,
which also replaces a private copy in DatabaseURL.cpp that used the
locale-dependent std::isalpha and std::isalnum.

Deliberate consequences: a broker address carrying a stray '@' and any
URI-shaped connection string are now hidden whole, and
format_display_secrets_in_show_and_select still shows the real value to a
privileged reader. maskURIUserinfo itself is unchanged, which the re2
equivalence test proves by passing unedited.

Closes: ClickHouse#121257
…eption

Three defects found reviewing the previous commit.

The abfs/abfss exception in CoreSettings::SETTINGS_TO_HIDE masked strictly LESS
than the code it replaced. maskURLBaseCredentials returned
maskPresignedURLParameters(value) alone for those two schemes, so
url_base = 'abfss://c:[email protected]/d/' logged pw verbatim where
maskURIPassword had logged abfss://c:[HIDDEN]@A... . That is a masking
regression in one of the settings this change set names, and it also contradicted
the rule the rest of the work applies: the exception's own comment said the
credential of such a base is the SAS in the query string, and then delegated to a
helper that carries only the AWS and GCS parameter names and so cannot mask a
SAS. A value whose credential ClickHouse cannot bound is not echoed with a
partial mask. The exception is therefore deleted rather than widened, url_base
goes back to maskURLCredentials, all three URL settings share one rule for every
scheme, and Core no longer mirrors a copy of the Azure grammar that had to be
kept in sync with parseAzureURL. This supersedes the paragraph of the previous
commit message that described the container as staying visible.

findTableEngineSecretArguments dispatched on the engine name and had branches for
NATS and XDBC but none for RabbitMQ or Kafka, although exactly three engines read
named-collection overrides out of their engine arguments
(tryGetNamedCollectionWithOverrides(args.engine_args, ...) in
StorageKafkaUtils.cpp, StorageNATS.cpp and StorageRabbitMQ.cpp) and only NATS had
a finder. So

  ENGINE = RabbitMQ(nc, rabbitmq_address = 'amqp://u:secret@h/')
  ENGINE = RabbitMQ(nc, rabbitmq_password = 'secret')
  ENGINE = Kafka(nc, kafka_sasl_password = 'secret')

reached SHOW CREATE, system.tables.create_table_query and system.query_log.query
in cleartext, while the same settings written in a SETTINGS clause were hidden by
the engine's own SETTINGS_TO_HIDE. Rather than copy the NATS loop, its body
becomes findBrokerTableEngineSecretArguments(secret_keys, address_key), so the
requirement that the finder and SETTINGS_TO_HIDE agree has one carrier; NATS and
RabbitMQ are two thin wrappers over it. Kafka deliberately does not use it,
because Kafka still accepts the legacy positional form
Kafka('brokers', 'topics', 'group', 'format', ...) whose arguments are all
non-secret, so failing closed on a positional argument there would hide
information a user is entitled to see. NATS and RabbitMQ accept no positional
argument other than the collection name, so for those two a positional is hidden.

In the XDBC named-collection branch every helper walks equals arguments only, so
a positional argument after the collection name was never masked and
jdbc(nc, 'jdbc://u:pw@h/db') echoed the connection string. Such a statement is
invalid and XDBC rejects it, but rejection happens after the statement has been
formatted for logging. The branch now hides any argument after the collection
name that is not a readable key = value pair, which is the treatment the NATS
sibling already gave that shape.

Tests: seven arms added to 05233_broker_and_xdbc_credential_masking, each
positive paired with the control that has to stay fully visible, in particular an
'@'-free rabbitmq_address and Kafka's legacy positional form. Three gtests added
next to the NATS ones, each asserting the engine-argument spelling, the SETTINGS
spelling and that control. Every existing NATS assertion, the re2 equivalence
test and the TLS expectations pass unedited.
Two defects found reviewing the previous commit, both the same shape one argument
index further out: a scan that starts at index 1 is only correct when index 0 is
proven to be a named-collection name.

The Kafka branch the previous commit added scanned from index 1, but Kafka is the
one engine here whose collection name is optional: registerStorageKafka falls
through to the legacy positional path when there is no identifier at index 0, and
rejects a malformed call in checkAndGetLiteralArgument only after the statement
has been formatted for logging. So

  ENGINE = Kafka(kafka_sasl_password = 'secret', 'clickhouse')

was masked nowhere and reached system.query_log.query and the server log in
cleartext. The shape is one users write; 03305_fix_kafka_table_with_kw_arguments
exists for exactly ENGINE = Kafka(a = '1', 'clickhouse'), and
kafka_sasl_password is the engine's only secret setting. Both scans now start at
0. That cannot widen the mask, because findNamedArgument and
markNamedArgumentsWithUnreadableKeys skip any argument that is not an equals
function with two arguments, which is what keeps the legacy positional form fully
visible.

findXDBCSecretArguments had the mirror image in its other branch. The else branch
is taken whenever index 0 is not an identifier, and it hid only index 0, so in a
keyword-argument call with no collection the connection string sits at another
index and was echoed:

  jdbc(external_table = 't', datasource = 'DSN=x;Uid=u;Pwd=secret')

jdbc and odbc have no validity precondition and ITableFunctionXDBC validates
after formatting, so the call is logged. Whether the credential leaked depended
only on the order the keys were typed in, while the named-argument style without
a collection is what a user coming from s3(url = ..., access_key_id = ...)
writes. The two aliases and the unreadable-key scan now run from index 1 in that
branch too, on top of the unchanged markSecretArgument(0, false). For a valid
positional call all three additions are no-ops, since no equals argument exists,
so the schema and table arguments stay visible.

The class is now closed rather than the two examples: every other named-argument
scan in the file that starts at a non-zero index sits inside an
isNamedCollectionName test, so index 0 is proven to be an identifier there, and
these two branches were the only ones without that property.

Two arms are added to 05233_broker_and_xdbc_credential_masking, each keeping its
non-secret neighbour visible so it doubles as the over-masking control, plus one
gtest for the XDBC engine spelling and one assertion block for the Kafka one.
findMySQLFunctionSecretArguments and findMySQLDatabaseSecretArguments scanned for
TLS credentials from index 5 and index 4 in their positional branches, one past
the last positional slot. The keys those scans hide are PEM material
(ssl_ca_pem, ssl_cert_pem, ssl_key_pem and the three PostgreSQL spellings), the
contents of a certificate or a private key, so a credential written before the
positional arguments was masked nowhere:

  mysql(ssl_key_pem = '<key>', '127.0.0.1:3306', 'db', 't', 'u')
  CREATE DATABASE d ENGINE = MySQL(ssl_ca_pem = '<cert>', '127.0.0.1:3306', 'db', 'u')

Such a call is invalid, but ASTFunction::formatImpl runs the finder whenever
show_secrets is false, which is before any argument is validated, so the
statement reaches system.query_log.query and the server log in cleartext first.
The first function serves the mysql and postgresql table functions and the MySQL,
PostgreSQL and MaterializedPostgreSQL table engines; the second serves the MySQL,
PostgreSQL, MaterializedPostgreSQL, Remote and RemoteSecure database engines.

Both scans now start at 0. That cannot widen the mask, because findNamedArgument
and markNamedArgumentsWithUnreadableKeys skip any argument that is not an equals
function with exactly two arguments, so every positional literal stays visible.
The pre-existing arms of 04648_mysql_tls_credentials keep asserting that byte for
byte.

Two corrections to the previous commit's message.

It claimed the class was closed, on the grounds that every other named-argument
scan in the file starting at a non-zero index sits inside an
isNamedCollectionName test and that the two branches it fixed were the only ones
without that property. That was wrong. These two positional MySQL branches have
the same shape and sit in the negative branch of the same test, where index 0 is
proven not to be a collection name, and they are closed here. The statement that
holds now is that no named-argument scan in the file starts past index 0 unless
index 0 is proven to be a collection name.

It also said the two arms it added each keep their non-secret neighbour visible,
"so it doubles as the over-masking control". That holds for the Kafka arm, whose
positional neighbour 'clickhouse' stays visible. It does not hold for the jdbc
one: that neighbour sits at index 0 and is hidden whole by the untouched
markSecretArgument(0, false). The over-masking control for that branch is d1 to
d3, which keep their schema and table arguments visible.

Two arms are added to 04648_mysql_tls_credentials, the test that already owns
these keys, one per code path, through the formatter that both share.
The positional branches of findMySQLFunctionSecretArguments and
findMySQLDatabaseSecretArguments got the password wrong in one way with two
faces: a positional slot is not a raw argument index, and a positional branch
owes the same named-argument scan its named-collection sibling runs.

A `key = value` argument written before the positional block shifts every
positional one index along, so markSecretArgument(4) and markSecretArgument(3)
hid the wrong argument and echoed the password; and because the branch scanned
named arguments only for the TLS keys, a `password =` override written there was
masked nowhere at all:

  mysql(ssl_key_pem = '<key>', '127.0.0.1:3306', 'db', 't', 'u', '<password>')
  mysql('127.0.0.1:3306', 'db', 't', password = '<password>', 'u')
  CREATE DATABASE d ENGINE = MySQL(ssl_ca_pem = '<cert>', '127.0.0.1:3306', 'db', 'u', '<password>')
  CREATE DATABASE d ENGINE = MySQL('127.0.0.1:3306', 'db', password = '<password>', 'u')

Such calls are invalid, but ASTFunction::formatImpl runs the finder whenever
show_secrets is false, which is before any argument is validated, so the
statement reaches system.query_log.query and the server log in cleartext first.

Both faces are fixed together. classifyPositionalArguments returns the raw
indexes of the arguments that are not `key = value` pairs, so the branch reads
its slot out of that list instead of counting raw arguments, and a positional
argument written after the first named one is hidden rather than listed: the
parsers reject that mix, the statement is formatted before they do, and the slot
it was meant to fill is then unknowable. classifyS3Arguments already applies that
rule to the s3 signatures, and the helper reuses its shape rather than its body,
which carries S3-specific key handling. The branch then runs
findSecretNamedArgument("password", 0), the call its named-collection sibling
already makes.

A well-formed call is unchanged byte for byte: its named arguments come after the
positional block, so the returned list is [0, 1, 2, ...] and the slot lookup
yields the same index as before. Twenty of the twenty-two formatting assertions
of 04648_mysql_tls_credentials are untouched; the two that move are the arms that
previously recorded a credential as visible, and they now carry the password so
the file's own leak oracle can see it.

The invariant this closes is narrow, and only the part I enumerated is claimed. A
named-argument scan in this file starts past index 0 in twenty-four places. It is
safe where index 0 is proven to be a collection name, and also where index 0 is
hidden whole: findXDBCSecretArguments's else branch scans from 1 with
isNamedCollectionName(0) false, and is safe because markSecretArgument(0, false)
above it hides that argument entirely. No claim is made for the file as a whole.
A scan that starts past index 0 behind isNamedCollectionName(N) for N greater
than zero still skips a secret named argument written first, which
ExternalDistributed, azureBlobStorage and remote were measured to echo. Those are
untouched here.
StorageURL::resolveURLBase rejects a base with no "://" by interpolating the raw
value into its BAD_ARGUMENTS message. The value is a setting that can carry a
credential, so the credential is disclosed in full through the client error, the
exception column of the query log and the server log:

  SELECT * FROM url('data.csv', CSV, 'c String')
      SETTINGS url_base = 'user:<password>@example.invalid/def/'

  Code: 36. The `url_base` setting must contain a scheme (e.g. https://),
            got: user:<password>@example.invalid/def/

Nothing gates that. url_base is settable in a settings profile, so the value
belongs to whoever wrote the profile while the error goes to whichever user trips
it, and the message is not behind format_display_secrets_in_show_and_select. The
same message carries s3_base and format_avro_schema_registry_url: the callers
that reach it with a raw user value are TableFunctionURL.cpp for url_base and
ObjectStorage/S3/Configuration.cpp in two places for s3_base.

The value is dropped rather than masked. A masker only finds a credential it can
locate: maskURLCredentials fires on a value containing '@', so
s3_base = 'DSN=x;Pwd=<password>' would still be echoed whole. The setting name
stays in the message, which is what a user needs in order to find their own typo.

The sibling carrier already has this treatment. DatabaseURL refuses a scheme-less
base without echoing it, and 04627_url_database_engine asserts that with a leak
count. The url_base and s3_base arms of the same invariant grep only the message
prefix, which is why nothing in tree caught this. They now carry the same pair of
assertions, so all three carriers are pinned the same way. The text before the
removed ", got:" is byte identical, so those pre-existing prefix arms and their
reference lines do not move.

The new arms run clickhouse-local rather than clickhouse-client: the client
appends the query it was given to an exception, and that echo is the caller's own
input rather than anything the message disclosed, so a leak count taken through
the client can never reach zero.

04648_mysql_tls_credentials gains two arms as well. The two
findSecretNamedArgument("password", 0) calls added to the positional MySQL
branches in the previous commit were exercised by no test: every existing named
password arm goes through the collection branch, and the arms that carry a named
credential beside a positional block use a TLS key. The new arms are the
collection-less named password shape for each branch, and deleting either call
reddens exactly one of them.
Delete comments narrating this change's own design, keep the third-party masker semantics (libnats, AMQP-CPP, XDBC driver grammar) and the cross-file sync invariants as standalone properties.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 21, 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; six rounds, 10 findings) plus my own
cold review of the resulting code in each round (17 findings), adjudicated together. The sixth round
returned no findings from the gate or from my own cold review, so nothing carried past it.

# Sev Finding Verdict Evidence / action
1 ❌ The url_base abfs/abfss carve-out un-masks a userinfo password that the old masker hid (src/Core/SettingsSecrets.h) AGREE, fixed @ f9b1691e2b82e url_base = 'abfss://c:[email protected]/d/' was logged verbatim where the old scan hid the password; the carve-out is removed, so all three URL settings share one rule and no Azure grammar is mirrored into Core. Raised independently by my own review.
2 ❌ Engine-argument overrides of a broker secret are not masked for RabbitMQ (src/Parsers/FunctionSecretArgumentsFinder.cpp) AGREE, fixed @ f9b1691e2b82e ENGINE = RabbitMQ(nc, rabbitmq_address = 'amqp://u:secret@h/') reached SHOW CREATE, system.tables and the query log in cleartext, and Kafka has the same gap with kafka_sasl_password; both are covered now through one shared broker finder, with Kafka's legacy positional form left visible.
3 ⚠️ The jdbc/odbc named-collection form does not fail closed on a positional argument AGREE, fixed @ f9b1691e2b82e jdbc(nc, 'jdbc://u:pw@h/db') is rejected only after the statement is formatted for logging, so the connection string reached the query log; an unexpected positional is hidden whole now, as the NATS finder already did.
4 ⚠️ An Azure SAS sig parameter is not masked in a URL-valued setting DISAGREE Equally unmasked before this change, and identically for s3_base, format_avro_schema_registry_url, the s3 url argument and the dictionary source, none of which this PR touches; the parameter set is documented as mirroring BackupInfo::removeCredentialsFromS3URL, so widening it changes every caller and needs its own decision on the SAS name set. Measured and tracked separately.
5 💡 05153_settings_masking_non_string_value.sh's header comment is left stale by the new rule DISAGREE The file is not in this diff, so its comment belongs to master and I did not edit it.
6 ⚠️ A Kafka secret written as the FIRST engine argument bypasses masking AGREE, fixed @ 561aa0d214a80 ENGINE = Kafka(kafka_sasl_password = 'secret', 'clickhouse') parses and is logged before it is rejected; both scans start at index 0 now, which cannot over-mask because they inspect only key = value arguments, so the legacy positional form stays fully visible.
7 ⚠️ A collection-less jdbc/odbc call echoes a connection string written after the first argument AGREE, fixed @ 561aa0d214a80 With no collection name only index 0 was hidden, so jdbc(external_table = 't', datasource = 'DSN=x;Pwd=secret') printed the DSN verbatim; the two DSN aliases and the unreadable-key scan run in that branch too now.
8 💡 A new test arm is named e12 but sits between e10 and e11 in the script DISAGREE The reference is ordered by arm name, which the regenerated file gets right, so no assertion is affected; renaming would churn a freshly regenerated reference for no gain.
9 ⚠️ A TLS credential written before the positional mysql/postgresql arguments is still echoed AGREE, fixed @ 66d6daf0c1b58 mysql(ssl_key_pem = '<key>', '127.0.0.1:3306', 'db', 't', 'u', 'p') is invalid but is logged from ASTFunction::formatImpl before any validation; the two TLS scans that started at 5 and 4 start at 0 now, and 04648_mysql_tls_credentials.sh gains the two uncovered arms. Raised independently by my own review and by the gate.
10 💡 The commit message of 561aa0d214a80 calls both new test arms their own over-masking control AGREE, corrected @ 66d6daf0c1b58 True for the Kafka arm, whose positional neighbour stays visible, not for the jdbc one, whose neighbour is hidden whole; corrected in the commit message rather than by changing a test.
11 ❌ A positional mysql/postgresql call maps its password by RAW argument index and runs no named scan, so the password is echoed AGREE, fixed @ acc8367eef987 mysql(ssl_key_pem = 'K', '127.0.0.1:3306', 'db', 't', 'u', 'PASSWORD') hides the user name and echoes the password, and mysql('127.0.0.1:3306', 'db', 't', password = 'PW', 'u') echoes PW; both branches locate the password among the positional arguments now and fail closed on a malformed mix, which classifyS3Arguments already does for the s3 signatures. Row 9's two arms were missing the password argument, so the file's canary oracle could not see this; they carry it now, with the A-side leak as the negative control.
12 💡 05233's Kafka positional control is a valid definition, so it builds a real storage AGREE, fixed @ acc8367eef987 On a build with librdkafka it constructed a StorageKafka against a broker that does not resolve and left the table behind, against the file header's claim that every statement is rejected; retargeted at the absent database the jdbc/odbc arms already use, which keeps the arm's job and builds nothing.
13 💡 66d6daf0c1b58's replacement closure claim holds only with one more clause AGREE, corrected @ acc8367eef987 Enumerating all 30 such scans leaves one exception, introduced by this PR: the collection-less jdbc/odbc branch scans from 1 where index 0 is hidden whole, so the invariant is "proven to be a collection name or hidden whole". Corrected in the message, with no source change.
14 💡 The commit series should be squashed: three messages narrate the review rounds and one partially reverts another DISAGREE Measured rather than asserted: #113436 merged with 8 commits including one that corrects an earlier one, and #111924 with 7; neither drew a comment about the series, and a history rewrite with no measured benefit is not worth a round.
15 ❌ The scheme-less url_base / s3_base value this PR now hides whole is still returned in full by the validation that rejects it AGREE, fixed @ 473bc30c4f140 StorageURL::resolveURLBase interpolated the raw value into its message, so SETTINGS url_base = 'user:[email protected]/def/' handed the credential back through the client error, system.query_log.exception and the server log, none of which format_display_secrets_in_show_and_select gates, and url_base is settable in a settings profile; the value is dropped from the message and both tests gain a leak-count arm. Raised independently by my own review and by the gate.
16 ⚠️ The two new collection-less password = ... scans have no test arm AGREE, fixed @ 473bc30c4f140 Deleting both scans left every test green, yet without them mysql('h:3306', 'db', 't', password = 'PW') prints PW; two arms cover them now, one per finder, each reddened by its own mutation so neither can cover the other.
17 ❌ The XDBC connection string reaches the jdbc/odbc bridge as a URI query parameter, so a non-2xx bridge answer returns it through the HTTP exception and the request log DISAGREE The mechanism is real and I traced all four sites, but the two carriers share no code and reverting every XDBC line here leaves that output byte-identical: it is a separate sink, not an incomplete mask. The remedy has to change what ReadWriteBufferFromHTTP renders for every storage, already measured and tracked in issue #120425 with a partial fix in #120407.
18 💡 For abfss://container@account... the masked userinfo is a container name, not a credential, so the container is now hidden too DISAGREE The flip side of row 1, and deliberate: one rule for all three URL settings and every scheme beats a per-scheme carve-out that demonstrably un-masked a password. Strictly more masking, never a leak, and pinned by three arms so a later change cannot drift it silently.

Also noticed and deliberately not raised, each measured and byte-identical before and after this diff:
a value with leading whitespace ( https://u:p@bucket/f.csv) is still echoed at the maskURIUserinfo
call sites this PR does not own; the engines that mask a secret at a fixed positional index
(ExternalDistributed, MongoDB, Redis, ArrowFlight) or scan past index 0 behind a collection name
that is not at index 0 (remote, azureBlobStorage); and the S3Queue / AzureQueue secret settings
(after_processing_move_secret_access_key, after_processing_move_connection_string) that have no
engine-argument branch, which are read from the SETTINGS clause, so I have no input that reaches a
leak. All tracked separately, none changed here.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-8:20260921-193300

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)

Five fix rounds are folded into the rows below, including the last one (src/Storages/StorageURL.cpp,
one statement, plus test-only arms in 04070, 04626 and 04648).

# Question Answer
a Deterministic repro? Yes, on demand, with no broker, bridge or network: SELECT 1 SETTINGS format_avro_schema_registry_url = 'http://user:pa@ss@reg:8080/' leaves the tail ss in system.query_log.query, SET nats_url = 'user:pass@h:4222' is logged verbatim, SETTINGS url_base = 'http://h:8080/d/[email protected]' is logged as http://h:[HIDDEN]@b.com (a host that is not the real one), SETTINGS url_base = 'user:[email protected]/def/' returns the credential in the rejection message, and clickhouse format alone echoes the PEM and then the password for the two positional MySQL shapes. 36 arms, each measured on both binaries.
b Root cause explained? maskURIPassword reproduces the old unanchored regex, masking from the first : after any :// to the first @, an extent that matches no consumer in the tree: at once too narrow (a password containing @ keeps its tail, a userinfo with no : is untouched) and too wide (a credential-free URL with @ in its query string is rewritten into a fake host). Separately, the engine-argument dispatcher had no RabbitMQ or Kafka branch although all three broker engines read named-collection overrides, three scans started past index 0, the positional MySQL branches addressed the password by RAW argument index and ran no named scan at all, and resolveURLBase interpolated the rejected base into its BAD_ARGUMENTS message.
c Fix matches root cause? One rule covers all six sites: hide only the credential where ClickHouse owns the value's grammar, and do not echo a value whose grammar belongs to someone else. The literal swap to maskURIUserinfo was rejected on measurement, not taste (libnats ends the userinfo at the last @ of the whole value and AMQP-CPP at the first @ after the scheme, so nats://u:pa/ss@h:4222 would still expose pa/ss). The missing dispatcher branches share ONE findBrokerTableEngineSecretArguments, the password slot is resolved through classifyPositionalArguments() the way classifyS3Arguments already does for the s3 signatures, and the rejected base is dropped at the throw site rather than masked, because s3_base = 'DSN=x;Pwd=secret' carries no @ for a masker to find. Net effect in FunctionSecretArgumentsFinder is a deletion.
d Test intent preserved / new tests added? New 05233_broker_and_xdbc_credential_masking.sh (36 arms, every positive paired with the control that must stay visible, plus a whole-test canary oracle), 4 new gtests, two arms added to 04648_mysql_tls_credentials (one per code path) and a leak-count arm to each of 04070 and 04626, mirroring the shape 04627_url_database_engine.sh already uses for the sibling carrier. The 5 pre-existing NATS gtests and the re2-equivalence gtest for the shared maskers are unedited and passing, which is what proves the findURIAuthority extraction behaviour-preserving; every reference was regenerated from a real run with all pre-existing lines byte-identical, and no existing arm was weakened.
e Both directions demonstrated? Yes, on Build-ID-verified A/B binaries throughout (each server's startup build id: and SELECT buildId() asserted against readelf): against master the new test is [ FAIL ] before and [ OK ] after with the canary oracle 11 -> 0, and in each fix round exactly the expected arms move against the previous PR head (6 -> 0, then 4 -> 0, then the two 04648 arms, then the new leak counts 0 -> 1 on the pre-fix binary, which still carries , got: {} and so IS the mutation), with every other arm byte-identical and the changed test the ONLY differing verdict in a 59- and then 60-test affected set run on both binaries. 5 of the 6 new gtest assertions were shown to redden on the unfixed binary by replaying their exact statements; the 6th is the over-masking control that must not move. 50 randomized plus 50 non-randomized runs green throughout.
f Fix is general across code paths? The sibling set is enumerated exhaustively rather than guessed: git grep tryGetNamedCollectionWithOverrides(args.engine_args gives exactly three engines (Kafka, NATS, RabbitMQ), and all three now have a dispatcher branch sharing one finder. Both NATS sinks are fixed together, the anchored-scheme predicate is reduced to a single carrier (findURIAuthority, deleting the private locale-dependent copy), the unreadable-key fail-closed scan is likewise one carrier now shared with the XDBC branch, and resolveURLBase is the single shared site for all three URL settings. S3Queue, AzureQueue and DataLakeCatalog are excluded deliberately: they do not read engine-argument overrides.
g Fix generalizes across inputs? Type wrappers do not apply: every value here is a String, or a non-String Field already guarded by tryGet (pinned by 05153_settings_masking_non_string_value). The input matrix that does apply is covered per site: password containing @, / or ?; userinfo with no password; no credential at all; no scheme; leading whitespace; uppercase scheme; a KEY=value; list; a query-parameter password; duplicated and computed keys; both aliases present; abfs/abfss with and without a userinfo password versus az/azure; presigned parameters; and the argument-position shapes, namely a secret named argument before the positional block (both code paths), after it (the control rows), and a call with fewer positionals than the slot index, where positional.size() > N guards the access.
h Backward compatible? No setting default, serialization or on-disk format changes, so no SettingsChangesHistory.cpp entry; the only user-visible change is masked output, which is the point. Two values that used to be partly visible are hidden whole (a broker address carrying a stray @, and a URI-shaped XDBC connection string), several malformed statement shapes that used to echo a credential now print [HIDDEN], and one BAD_ARGUMENTS message loses the echoed value while keeping its code, condition, setting name and prefix. format_display_secrets_in_show_and_select still shows the real value to a privileged reader, asserted by test_mask_sensitive_info's own raw-value check, and Kafka's legacy positional form stays fully visible, pinned by its own control arm and gtest.
i Invariants and contracts preserved? maskURIUserinfo keeps its contract byte-for-byte, so the extraction is a pure move and the unedited re2-equivalence gtest is the check; findBrokerTableEngineSecretArguments is a pure move of the NATS body, proven by every NATS assertion passing unedited; the masking rules still never throw (the tryGet guard and the fmt::format return in both fwd headers are untouched). Lowering the TLS scan's start to 0 cannot widen the mask because both loops skip any argument that is not an equals with exactly two arguments, and all 20 pre-existing TLS expectations are byte-identical across the change. In findXDBCSecretArguments the both-aliases branch still returns early, so the span and markSecretArgument never both write for one statement, which is what chassert(result.replacement.empty()) guards, and the new positional marks rely on the documented merge rule (it->second &= argument_is_named), under which a positional mark wins and so fails closed.

Session id: cron:clickhouse-impl-slot-7:20260921-183300

@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f20b9d0]

Summary: ✅


AI Review

Summary

This PR fixes several real masking gaps around URL-valued settings, broker addresses, XDBC connection strings, and some malformed mysql / Kafka call shapes. I do not think it is merge-ready yet, because the same credential-leak invariant is still broken in sibling FunctionSecretArgumentsFinder branches, so some queries can still write cleartext secrets into SHOW CREATE, system.query_log, and the server log.

Findings

❌ Blockers

  • [src/Parsers/FunctionSecretArgumentsFinder.cpp:694-761,969-980] The new zero-based positional / named-password handling was not fanned out to the remote / RemoteSecure and ExternalDistributed non-collection branches. remote('127.0.0.1', 'default', 't', password = '...') still formats the password verbatim, and ExternalDistributed('MySQL', password = '...', '127.0.0.1:9000', 'db', 't', 'u') still masks the wrong positional slot. Suggested fix: reuse the same classifyPositionalArguments plus findSecretNamedArgument(..., 0) treatment in those branches.
  • [src/Parsers/FunctionSecretArgumentsFinder.cpp:535-548,1004-1009] Azure named-collection overrides still do first-match-only masking for connection_string / storage_account_url and never apply the unreadable-key fallback. A computed or duplicated connection-string override therefore still logs the embedded AccountKey verbatim. Suggested fix: replace the one-shot maskAzureConnectionString path with an all-occurrences scan and call markNamedArgumentsWithUnreadableKeys on the Azure named-collection branches.
Final Verdict

❌ Changes requested

LLVM Coverage Report

Measured on commit f20b9d0.

Metric Baseline Current Δ
Lines 88.00% 88.00% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 115/117 (98.29%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 21, 2026
const auto positional = classifyPositionalArguments();
if (positional.size() > 4)
markSecretArgument(positional[4]);
findSecretNamedArgument("password", 0);

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.

remote / RemoteSecure and ExternalDistributed still have the same late-validation leak that this patch fixes for mysql/jdbc/Kafka, just in sibling branches that were not updated.

Today findRemoteFunctionSecretArguments never scans password = ... outside the named-collection path (current lines 694-761), so remote('127.0.0.1', 'default', 't', password = 'SECRET') formats with the password verbatim. findExternalDistributedTableEngineSecretArguments still hard-codes raw slot 5 (current lines 969-980), so ExternalDistributed('MySQL', password = 'SECRET', '127.0.0.1:9000', 'db', 't', 'u') hides 'u' instead of the secret. Both statements are formatted before validation, so they still leak cleartext credentials into system.query_log / the text log.

Please fan the same classifyPositionalArguments / findSecretNamedArgument(..., 0) treatment out to those branches too.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Both shapes reproduce, so this is a real gap. Measured on this branch's own debug binary (build id
f8341c7ef4e86c7e46ced3cf006bfe5fd640a90c), reading the masked text logQuery writes to
system.query_log.query:

SELECT * FROM remote('127.0.0.1', 'default', 't', password = 'leakRMT1')
SELECT * FROM remote('127.0.0.1', 'db', 't', password = 'leakRMT2', '[HIDDEN]', 'leakRMT3')
CREATE TABLE te1 (`x` UInt8) ENGINE = ExternalDistributed('MySQL', password = 'leakED1', '127.0.0.1:9000', 'db', 't', '[HIDDEN]')

It is three separate statements though:

  1. remote / remoteSecure, and the Remote / RemoteSecure table engines that share the finder:
    confirmed. The positional branch never scans a named password, and its walk is value dependent, so a
    named argument also shifts the slot: in the second line above the real positional password stays visible
    while the user name is hidden instead. This is being fixed separately and I will post the link here when
    that PR opens.

  2. The Remote / RemoteSecure database engines are already closed by this PR, because they share
    findMySQLDatabaseSecretArguments with the mysql fix here. On this head
    CREATE DATABASE dx1 ENGINE = Remote('127.0.0.1:9000', password = 'S', 'db', 'u') renders as
    Remote('127.0.0.1:9000', password = '[HIDDEN]', '[HIDDEN]', '[HIDDEN]').

  3. ExternalDistributed reproduces exactly as you wrote it, but the engine was removed in eac5e9883a24a
    (2024-10-29): that statement now fails with Code: 56. DB::Exception: Unknown table engine ExternalDistributed. (UNKNOWN_STORAGE), so the finder branch outlived its engine. I noted it on the fix
    task that covers this class instead of hardening a branch no engine backs.

Why not in this PR: this one finishes the masker policy of #121257, while the above is slot arithmetic.
findRemoteFunctionSecretArguments decides db versus db.table from the argument value, and the last
positional argument may itself be an equals expression:
remote('127.0.0.1', 'db', 't', 'u', 'p', x = 1) is a valid sharding key that renders visible today
(measured on the same binary) and has to keep doing so. Re-basing that walk on classified slots needs its
own over-masking control and its own test, not a hunk appended here.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Opened as #121474.

It fixes a third face of the same function rather than the two mechanisms I named in item 1, so item 1 is not closed. isNamedCollectionName(0) is only isIdentifier(), and an identifier there is either a named collection or a cluster name. In the cluster-name reading the user and the password are ordinary positional arguments, so remote(<cluster name>, 'db', 't', 'usr', 'secret'), which ClickHouse accepts and runs, took the collection branch and returned before the positional walk, writing the password verbatim. Deleting that return cannot unhide anything, because markSecretArgument only ever adds marks.

Still open: the named password = that the positional branch never scans, and the slot shift from a key = value argument written earlier (the leakRMT2 line above). Those do reach the log before argument validation rejects them, so the leak is real, but each fail-closed sweep I measured either masked a non-credential on a valid call (a password-spelled sharding key, or cityHash64(x) = 1, whose key is unreadable) or still leaked remote(u = 1, password = 'S7'). I kept the three counterexamples rather than ship one of them. If you would rather have that face covered too, say so and I will design it.


findSecretNamedArgument("datasource", 1);
findSecretNamedArgument("connection_settings", 1);
markNamedArgumentsWithUnreadableKeys(1);

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 new unreadable-key handling still does not cover Azure named-collection overrides. Both Azure branches still rely on maskAzureConnectionString(-1, true, start) (current lines 535-548 and 1004-1009), which masks only the first literal connection_string / storage_account_url match and never runs markNamedArgumentsWithUnreadableKeys.

Because tryGetNamedCollectionWithOverrides evaluates constant-expression keys, a valid override such as azureBlobStorage(azure_conf2, concat('connection_', 'string') = 'DefaultEndpointsProtocol=https;AccountKey=SECRET', container = 'cont', blob_path = 'x.csv') still formats the AccountKey verbatim. A duplicated connection_string = ... leaks its second value for the same reason. This is the same carrier this patch just closed for XDBC/TLS.

Please switch the Azure connection-string masking to an all-occurrences scan and apply the unreadable-key fallback on these branches as well.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Both shapes reproduce on the same binary, so I checked who owns them rather than whether they are real:

azureBlobStorage(azc, concat('connection_', 'string') = 'DefaultEndpointsProtocol=https;AccountName=a;AccountKey=leakAZ1;', container = 'c', blob_path = 'x.csv')
  -> rendered verbatim, nothing masked
azureBlobStorage(azc, connection_string = 'A;AccountKey=leakAZ2a;', connection_string = 'B;AccountKey=leakAZ2b;')
  -> connection_string = 'A;AccountKey=[HIDDEN];', connection_string = 'B;AccountKey=leakAZ2b;'

Both are already fixed by open PR #114964: it replaces the findNamedArgument pair in
maskAzureConnectionString with a scan over every argument from start on, hides the value of any
key = value whose key it cannot read as a plain literal, and records a replacement per occurrence instead
of returning after the first match. #114963 carries the same rewrite. Taking it here too would put a
second, conflicting rewrite of that function in flight, so I am leaving it to that PR. I am tracking
#114964 and will carry the fix myself if it is closed unmerged.

@clickhouse-gh

clickhouse-gh Bot commented Sep 22, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f20b9d0b9 with master e033cea64 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

33 translation units recompiled, 160 s compile time in total, 33 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×0.95 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -9.8 s (-6%) in total before that adjustment.

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-logging Logging/monitoring/observability (logs, metrics, tracing, instrumentation). label Sep 22, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 23, 2026
Merged via the queue into ClickHouse:master with commit fed957a Sep 23, 2026
176 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 23, 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-logging Logging/monitoring/observability (logs, metrics, tracing, instrumentation). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default 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.

Five call sites still use the weaker maskURIPassword after #120407, so credentials can remain partly visible

4 participants