Skip to content

Hide secret MongoDB connection options in SHOW CREATE, query_log and system.dictionaries - #123240

Merged
alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:mongodb-connection-options-secrets
Oct 2, 2026
Merged

alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:mongodb-connection-options-secrets

Conversation

@groeneai

@groeneai groeneai commented Oct 1, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

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

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

The values of MongoDB connection options that carry a secret (tlsCertificateKeyFilePassword, sslClientCertificateKeyPassword, AWS_SESSION_TOKEN in authMechanismProperties) are now hidden in SHOW CREATE, system.query_log and system.dictionaries.source for the MongoDB table engine, the mongodb table function and the MongoDB dictionary source, system.dictionaries.source no longer shows the MongoDB password, and a named-collection uri override after another override is no longer shown as written.

Description

Related: #120407 (asked in #120407 (comment)).

On 26.8.10.6, SHOW CREATE, system.query_log and system.dictionaries.source print the value of a MongoDB connection option that carries a secret, such as tlsCertificateKeyFilePassword, given in a URI or in options, and system.dictionaries.source also prints the password.

Every MongoDB display site masked only the URI password, and ASTPair::hasSecretParts did not report uri/options, so a CREATE DICTIONARY reached query_log as written.

Change:

  • maskMongoDBConnectionString hides the values of those three options together with the password maskURIPassword finds.
  • It is used for the dictionary URI/OPTIONS, MongoDBDictionarySource::toString, and the engine and table function arguments that carry a URI or an option list. A value that is an expression is hidden whole, and so are the table function's options/oid_columns when a named argument before the fifth positional one moves them into the password slot.
  • ASTPair::hasSecretParts reports uri and options.
  • A named-collection uri override is masked at its own index; it was masked into the argument at index 1 and printed as written (also on 26.8.10.6). A positional after the collection name is hidden whole: it is rejected or ignored only after logging.

In authMechanismProperties the six properties the driver accepts besides AWS_SESSION_TOKEN stay visible; any other value, and a percent-encoded list, is hidden.

With #120407, its userinfo rule for these sites would move into maskMongoDBConnectionString; note that maskURIUserinfo does not hide a MongoDB password containing ? or #. The merge with #122770 masks the URI in its findMongoDBSecretArguments with maskMongoDBConnectionString; #121466 needs the same if it merges later (the password rows catch it).

Test: 05315_mongodb_connection_options_secrets fails on master and passes here.

🤖 Generated with Claude Code


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

Version info

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

groeneai and others added 4 commits October 1, 2026 09:02
…system.dictionaries

The values of `tlsCertificateKeyFilePassword`, `sslClientCertificateKeyPassword` and
`authMechanismProperties` were printed as written wherever ClickHouse shows a MongoDB
connection string or option list: every MongoDB display site masked only the URI password
(`maskURIPassword`), and `MongoDBDictionarySource::toString` masked nothing, password
included. `ASTPair::hasSecretParts` did not report `uri`/`options`, so a `CREATE DICTIONARY`
was logged unformatted and the `ASTPair` masking never reached `query_log`.

`maskMongoDBConnectionString` reads the option grammar the way the driver does
(`_mongoc_uri_apply_query_string`: split on '&', name before the first '=', compared
case-insensitively and not percent-decoded) and hides the secret option values together
with the password range of `maskURIPassword`. Both ranges are located in the original
string and hidden as their union: the driver allows '?', '=' and '&' in a password, and an
'@' in an option value moves the end of the userinfo that `maskURIPassword` finds, so running
two scans one after the other leaks whichever runs second. `maskURIPassword` keeps its exact
behaviour: its scan moved into `findURIPasswordRange`, which the re2 comparison gtest guards.

Sites:
- `ASTPair::formatImpl` masks the raw `uri`/`options` value and prints it through a new
  literal or identifier, so quoting is unchanged; any other value is an expression that is
  evaluated only after the query is logged, so it is hidden whole.
- `MongoDBDictionarySource::toString` masks the URI it shows.
- `findMongoDBSecretArguments` masks its legacy replacement with the new function, and a new
  `findMongoDBConnectionStringSecretArguments`, called after it, covers the argument roles
  that carry a connection string or an option list: argument 0, the positional `options`,
  the named `uri`/`options` overrides (key read case-insensitively; a key that is an
  expression can name `options`, so such an argument is hidden whole), and any positional
  after a named argument. It never overrides an argument already masked, and hides through
  `replaced_arguments` because the named-collection `uri` override sets `result.replacement`.

Related: ClickHouse#120407 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
When an argument before it is missing, the mongodb() table function binds a named
oid_columns to the options slot, which is appended to the connection URI, so its
secret options were shown as written in query_log and SHOW CREATE.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…gument

The mongodb() table function appends options and oid_columns to the positionals before index 5, so a named
argument there can move a plain password into the user or password slot. In that case the named options and
oid_columns and every positional after structure are hidden whole; this replaces the oid_columns key term.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Condense the maskMongoDBConnectionString doc and the replaced_arguments note; drop two comments that narrate the code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 1, 2026
@groeneai

groeneai commented Oct 1, 2026

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

Pre-publication review by an independent model (engine: codex; 3 findings over three rounds, the last one clean) plus my own review (nits only).

# Sev Finding Verdict Evidence / action
1 ❌ A named oid_columns of mongodb() that the table function binds to the options slot (a named argument before the positional ones leaves fewer than five) was not scanned (FunctionSecretArgumentsFinder.cpp) AGREE, fixed @ b858239 superseded by row 2's rule; test row f06
2 ❌ The same shift can move a named options (or a positional after structure) into the password slot, where a plain password stayed visible AGREE, fixed @ 56d7025 when a named argument precedes the fifth positional one, the table function's options/oid_columns and the positionals after structure are hidden whole; rows f07, f08, control c05
3 ❌ A database/DB value written as db?tlsCertificateKeyFilePassword=X is pasted into the connection string unescaped and stays visible DISAGREE database is documented as the database name and options have their own options argument; the driver reads an option value up to the next &, so that value sets the option to X?<options> and only a hand-placed & makes X effective. Masking it means scanning the HOST/PORT/USER/DB keys every dictionary source shares, and percent-encoding the database breaks tables that pass db?authSource=admin today
4 💡 Exception text can echo a rejected argument (Expected key-value defined argument, got OPTIONS = '...') or the driver's own option error Noted, not blocking different mechanism (exception text), invalid input only; not changed here
5 💡 mongodb(structure = '...', 'h:p', 'db', 'c', 'usr', 'pw') reads 'pw' as the structure, is rejected, and 'pw' stays visible in query_log Noted, not blocking as on master; a positional after a named argument is the class #122770 covers

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

Session id: cron:clickhouse-review-slot-8:20261001-104900

@groeneai

groeneai commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On master and on 26.8.10.6, SHOW CREATE TABLE of MongoDB('mongodb://127.0.0.1:27017/db?tlsCertificateKeyFilePassword=S', 'c') prints S; 05315 prints its markers on every run against the base binary.
b Root cause explained? Every MongoDB display site masked only the URI password, MongoDBDictionarySource::toString masked nothing, and ASTPair::hasSecretParts ignored uri/options, so CREATE DICTIONARY was logged as written.
c Fix matches root cause? Yes. One MongoDB-aware masker at every display site, and hasSecretParts reports the two keys.
d Test intent preserved / new tests added? New 05315: 24 statements over the engine, the table function and the dictionary source, an exact query_log liveness check, and 5 controls.
e Both directions demonstrated? Yes. Base binary: FAIL (every probe row, logged with a secret 41). Fix: OK, 50/50 randomized, 50/50 with 10 jobs.
f Fix is general across code paths? The 3 asked sites plus dictionary OPTIONS, positional and named options, the table function's options and oid_columns hidden whole when a named argument before index 5 can move them into the user or password slot, named-collection overrides, the 3-argument URI forms, and query_log of CREATE DICTIONARY. Each rule has a mutation that turns the test red.
g Fix generalizes across inputs (params/datatypes/wrappers)? Literal, backquoted identifier and expression values; upper-case names and keys; repeated options; #, @, ?, =, & inside values and passwords.
h Backward compatible? (maintainer-approved exception only) Yes. Display only, no setting, stored metadata unchanged, and every value without a secret renders as before.
i Invariants and contracts preserved? maskURIPassword is unchanged (its re2 gtest passes); an argument already masked is never overridden, and every replacement is a parseable expression.

Session id: cron:clickhouse-impl-slot-7:20261001-075800

@clickhouse-gh

clickhouse-gh Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [45c755c]

Summary: ✅


AI Review

Summary

This PR adds maskMongoDBConnectionString, wires it into the MongoDB AST/logging/display paths, and covers many good edge cases around uri, options, authMechanismProperties, named collections, and malformed argument orderings. The remaining blocker is that the host-form database / DB field is still concatenated into the effective MongoDB URI without escaping, while the new masking only inspects uri / options, so a secret smuggled through database / DB still reaches SHOW CREATE and query_log verbatim.

Findings
  • ❌ Blockers
    • [src/Storages/StorageMongoDB.cpp:166, src/Storages/StorageMongoDB.cpp:214, src/Dictionaries/MongoDBDictionarySource.cpp:72, src/Parsers/ASTFunctionWithKeyValueArguments.cpp:92, src/Parsers/FunctionSecretArgumentsFinder.cpp:600] [dismissed by author -- https://github.com/Hide secret MongoDB connection options in SHOW CREATE, query_log and system.dictionaries #123240#issuecomment-5930321079] The host-form builders still splice raw database / DB text into mongodb://.../<db>?<options>, but the new formatter and AST masking only inspect uri / options. A query like MongoDB('127.0.0.1:27017', 'db?tlsCertificateKeyFilePassword=SECRET', ...), MongoDB(creds, database = 'db?tlsCertificateKeyFilePassword=SECRET'), or SOURCE(MONGODB(DB 'db?tlsCertificateKeyFilePassword=SECRET' ...)) therefore still leaks SECRET in SHOW CREATE / query_log even though the driver consumes it as a MongoDB connection option.
    • Suggested fix: either percent-encode the database / DB component before building the URI, or fail closed in the display-side masking by treating MongoDB database / DB values that contain a query suffix as potential connection strings and hiding or masking them. Please add a regression for the table engine, the mongodb table function, and the dictionary-source form.
Final Verdict

❌ Changes requested — the direct uri / options paths look solid now, but the unescaped host-form database / DB path still leaves a secret-bearing MongoDB option visible in formatted and logged queries.

LLVM Coverage Report

Measured on commit 45c755c.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 160/165 (96.97%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 1, 2026
Comment thread src/Common/maskURIPassword.h Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-foreign-db Connectivity to external databases (ODBC/JDBC, MySQL, PostgreSQL, etc.). label Oct 1, 2026
…roperties

`findMongoDBSecretArguments` put the masked `uri` override of a named
collection at index 1, so in `MongoDB(nc, collection = 'c2', uri = '...')`
the display overwrote `collection` with the URI, and on master (and
26.8.10.6) printed the `uri` override itself unmasked. Use the index
`findNamedArgument` returns.

`authMechanismProperties` was hidden whole. The driver accepts seven
properties and only `AWS_SESSION_TOKEN` is a secret, so hide the value of
every property except the six public ones (`SERVICE_NAME`,
`CANONICALIZE_HOST_NAME`, `SERVICE_REALM`, `SERVICE_HOST`, `ENVIRONMENT`,
`TOKEN_RESOURCE`, case-insensitive like the driver), an entry without a
colon whole, and the whole option when it contains '%', since the driver
percent-decodes the value before splitting it on ',' and ':'.

Both raised by the AI review on ClickHouse#123240.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Only `key = value` overrides may follow the collection name in `MongoDB(nc, ...)` and
`mongodb(nc, ...)`. `tryGetNamedCollectionWithOverrides` rejects a literal positional there
(and ignores a function one), but only after the statement has been formatted for
`system.query_log`, so `MongoDB(nc, 'mongodb://usr:pw@host/db?tlsCertificateKeyFilePassword=x')`
was logged verbatim. Hide such positionals whole, as `findS3NamedCollectionSecretArguments`
does for S3.

Rows e10 (engine, URI before any override) and f09 (table function, bare secret after an
override) fail on the previous head and pass with this change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 45c755c8c with master 016a75cbf (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 4e774e919; 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.

Object file sizes

8 object files changed (+79.44 KiB total), 0 added.

Object file Master PR Δ
src/Parsers/CMakeFiles/clickhouse_parsers.dir/FunctionSecretArgumentsFinder.cpp.o 199.76 KiB 232.38 KiB +32.62 KiB (+16.33%)
src/Dictionaries/CMakeFiles/clickhouse_dictionaries.dir/MongoDBDictionarySource.cpp.o 252.66 KiB 277.17 KiB +24.50 KiB (+9.70%)
src/Parsers/CMakeFiles/clickhouse_parsers.dir/ASTFunctionWithKeyValueArguments.cpp.o 344.21 KiB 366.11 KiB +21.90 KiB (+6.36%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@alexey-milovidov alexey-milovidov self-assigned this Oct 1, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, fix conflicts.

Resolve the conflict with ClickHouse#122770, which rewrote findMongoDBSecretArguments
and moved the per-engine finders into std::function dispatch.

- findMongoDBSecretArguments is master's version, with maskURIPassword
  replaced by maskMongoDBConnectionString for the first argument and every
  `uri` override, so an argument it rewrites keeps no secret option.
- findMongoDBConnectionStringSecretArguments still runs after it, now from
  both `find_secrets` lambdas. Its first-argument branch hides an unreadable
  value: master already hides a computed first argument whole.
- 05315: the positionals after a named argument (f06, f07, f08) are now hidden
  by master's classifyPositionalArguments, and an unreadable key (e07) keeps
  the key and hides the value, as master does for other engines.
- 05258: the collection argument after a backquoted URI identifier is hidden,
  since this PR hides every positional after a named-collection identifier.
  The statement is rejected as an unknown named collection either way.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

Merged master in 45c755c. The conflict was with #122770's rewrite of findMongoDBSecretArguments, which now masks with maskMongoDBConnectionString. One expected output in its test 05258 changed: the collection argument after a backquoted URI identifier is now hidden too, because this PR hides every positional after a named-collection name.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 2, 2026
Merged via the queue into ClickHouse:master with commit f8f14d9 Oct 2, 2026
149 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 2, 2026
clickgapai pushed a commit to clickgapai/ClickHouse that referenced this pull request Oct 4, 2026
`check_named_collection_dependencies` makes `DROP NAMED COLLECTION` throw
`NAMED_COLLECTION_IS_USED` only for tables that registered a dependency, and a
table engine registers by passing its `StorageID` to
`tryGetNamedCollectionWithOverrides`. `StorageMongoDB`'s `getConfigurationImpl`
had `table_id` in scope but did not pass it: ClickHouse#96181 added the argument in
2311e59, and its branch merge 468aaca with ClickHouse#89616 (which rewrote the
function) kept master's line without it. Every other table engine passes its
id. So the drop succeeded under a live MongoDB table, the table could not be
attached on the next restart (669), its database became unusable, and with
`async_load_databases = 0` the server did not start. The new line is identical
to the hunk in ClickHouse#112805.

`05315_mongodb_connection_options_secrets` (ClickHouse#123240) dropped its two
collections while `e06`, `e07` and `e08` still used them. Stateless CI drops the
test database, but Stress keeps it and restarts the server, so master Stress
jobs failed with `Cannot start clickhouse-server`. The test now expects the
drop to be refused while the tables exist, drops the tables first, and pins
`ast_fuzzer_any_query = 0` on every statement that names a collection: the
stress profile fuzzes DDL, and a fuzzed `DETACH` of such a table hides it from
the catalog, so its dependency is pruned and the collection drop succeeds
(the generic detached-table hole, ClickHouse#121519); `__fuzz_N` clones would otherwise
also hold the collection and make the final drop fail.

Not changed: table functions (`CREATE TABLE ... AS mongodb(nc)`) register no
dependency for any engine except `bigquery`; the experimental
`MaterializedPostgreSQL` engine has the same omission.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-foreign-db Connectivity to external databases (ODBC/JDBC, MySQL, PostgreSQL, etc.). groeneai-origin-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.

3 participants