Skip to content

Hide the password of a MongoDB connection URI in the query log - #121466

Closed
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/mongodb-uri-secret-arguments
Closed

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/mongodb-uri-secret-arguments

Conversation

@groeneai

@groeneai groeneai commented Sep 22, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

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

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

Fixed the mongodb table function and the MongoDB table engine writing the password of a connection URI in cleartext to the query log, the server log and SHOW CREATE. A uri override of a named collection was also masked at the wrong position and only in its first occurrence.

Description

Related: #120407 - it changes how this function masks a URI, this one which arguments. Found while reviewing the credential-masking finders; no issue reports it.

On 26.8 and 26.9, SELECT * FROM mongodb('mongodb://user:password@host/db', 'c', 'x String') writes the password to system.query_log.query and the server log in cleartext.

Root cause. The finder scanned a positional URI only at arity two, which is neither surface's documented URI form, so both fell through to the host:port branch and marked an index they lack. In the named-collection branch the mask index was hard-coded to 1, so the masked copy landed on another argument while the real uri override printed intact, and only the first override, with a literal key, was examined.

Change. Scan argument 0 at every arity, since masking a URI password is a no-op on a host:port; hide an unreadable argument 0 only at the URI arities, which both parsers select by count; mask each named override at its own index via result.replaced_arguments, as findURLSecretArguments does; hide a post-collection argument that is not a key = value override, which the collection parser ignores rather than rejects. Every existing mark is kept, so in SHOW CREATE, the query log and the server log the hidden arguments are a superset of today's for every input, checked over 71 statement shapes.

Not addressed here: a userinfo with no : separator, which #120407 owns; EXPLAIN QUERY TREE stops hiding such an argument, which SHOW CREATE and the query log print on both binaries anyway.

Validation. On a real server the rows and log lines carrying a password go 10 to 0 over 18 markers, with every statement's accept or reject status unchanged. The new test's masking rows all fail on the unfixed binary; its control rows are byte-identical to the current output.


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

groeneai and others added 2 commits September 22, 2026 00:02
`findMongoDBSecretArguments` read the argument list more narrowly than the
two MongoDB parsers write it, so the primary documented form of the
`mongodb` table function echoed its password into
`system.query_log.query`, `system.text_log`, the server log, `SHOW CREATE`
and a server-side exception. Four independent gaps:

  * The positional URI scan was gated on `arguments->size() == 2`. The
    table function's URI form is `mongodb(uri, collection, structure[,
    oid_columns])`, arity 3 or 4 (TableFunctionMongoDB.cpp:94-98), and the
    engine's is `MongoDB(uri, collection[, oid_columns])`, arity 2 or 3
    (StorageMongoDB.cpp:186-256). One size test cannot fit both, and this
    one fits neither: every other arity fell through to the `host:port`
    branch, which marks raw index 4 - an argument those calls do not have -
    so nothing was hidden.
  * `result.start` was hard-coded to 1 while the index returned by
    `findNamedArgument` was discarded, so the masked copy of a `uri`
    override was written over whatever argument sat at index 1 and the real
    override was printed intact. The logged query was then not the query the
    user ran.
  * Only the first `uri` override was examined, although
    `NamedCollectionsHelpers` applies every override in turn
    (NamedCollectionsHelpers.cpp:206), which makes the last one effective.
  * An override whose key is a constant expression was ignored, although
    `getKeyValueFromASTImpl` evaluates the key
    (NamedCollectionsHelpers.cpp:45). Such an override is not merely
    theoretical: it is accepted and effective, and it is accepted even where
    the literal spelling is rejected by the collection's key-set check
    (measured with a marker host - `concat('u','ri') = 'mongodb://...@H/db'`
    sends the connection to H).

The arity test is deleted rather than replaced by a surface-aware one.
Argument 0 is a connection URI in the URI forms and a `host:port` in the
host forms, and masking a URI password is a no-op on a `host:port`, which
has no `://`, so the forms need not be told apart at all. That avoids
plumbing an `is_table_function` parameter through two dispatchers and
keeping four arity sets in sync with two parsers.

The host form's password keeps its raw-index mark. Reclassifying it through
a positional list was considered and rejected on measurement: both MongoDB
parsers fold every argument with
`evaluateConstantExpressionOrIdentifierAsLiteral` and then bind fixed raw
indices, so a raw index already is the positional slot; and an `equals`
node can never be part of a valid MongoDB call, because every argument must
be a String while `equals` yields UInt8.

The named branch is the shape of `findURLSecretArguments`, with `url`
replaced by `uri` and a `password` key added. The duplication is
deliberate rather than extracted into a shared helper: that function is
being rewritten by two other open pull requests, and a shared helper would
collide with both.

The mechanism had to change from the legacy `start`/`count`/`replacement`
triple to `result.replaced_arguments`, because `markSecretArgument` asserts
`result.replacement.empty()` and this function now needs a partially masked
argument 0 together with a mark on argument 4. `replaced_arguments` is
documented as composing with the other masking and is consumed under the
same `show_secrets` gate, so when masking applies does not change.

Every mark master made is kept, so in the rendered query the set of hidden
arguments is a superset of the previous one for every input. That was
checked mechanically over 71 statement shapes rather than asserted: no
shape that rendered secret-free before becomes secret-bearing, and no shape
loses a `[HIDDEN]` marker. The only values that become visible are the ones
master overwrote with another argument's masked copy, which were never that
argument's own value.

One sink outside the rendered query does move. Master set `result.count = 1`
unconditionally, so `hasSecrets()` held whatever the URI contained, while
this version records nothing when `maskURIPassword` finds nothing to mask;
`EXPLAIN QUERY TREE` of a `uri` override whose userinfo has no `:` therefore
prints the URI where it printed `[HIDDEN]`. That discloses nothing new: the
same text is what `SHOW CREATE` and `system.query_log.query` print both
before and after this change, measured byte-identical, and the merged
`findURLSecretArguments` carries the same conditional.

Not addressed here: a userinfo with no `:` separator is still printed. A
positional argument after a collection name needs no handling either, for
two different reasons by spelling: a string literal is rejected by both
surfaces, while a function-shaped one is silently ignored by the parser and
echoed, exactly as master and `findURLSecretArguments` do.

Co-Authored-By: Claude Opus 5 <[email protected]>
Cut the four added prose blocks in findMongoDBSecretArguments to standalone invariants: the named collection parser's override and key evaluation semantics (3 lines to 2), maskURIPassword being a no-op without a scheme (2 to 1), the fail closed arm for an unreadable argument 0 (2 to 1), and the out of range index 4 floor (2 to 1). The signature lines follow the file's convention and stay.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-self PR origin: self-found defect (impact-bar validated) labels Sep 22, 2026
@groeneai

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

Pre-publication review by an independent model (engine: codex; 1 gate finding plus 4 from my own cold
review, over one full pass, one fix round and a delta recheck that returned 0 findings). The fix round
changed no source: git diff <reviewed> HEAD -- src/ is empty.

# Sev Finding Verdict Evidence / action
1 ❌ the new stateless test created and dropped two server-global named collections under fixed names, and Stateless tests (*, flaky check) reruns a new test 50 times over a shared worker queue (--no-self-parallel is passed only by the targeted option), so two copies could race on one name AGREE, fixed @ 1a8bcc8 both names now carry ${CLICKHOUSE_DATABASE} and the test is a .sh. Under --test-runs 20 --jobs 8: the new shape is 20/20 [ OK ] over 8 workers, the old one 15 [ FAIL ] / 5 [ OK ] on the two predicted collection-name errors. no-parallel avoided
2 ⚠️ the fail-closed arm for a uri override whose value is a constant expression had no test row, although such an override is accepted and effective AGREE, fixed @ 1a8bcc8 one row added. It is green on the unfixed binary too, since the old hard-coded index lands on that argument by position, so its liveness is pinned by a control build that removes only that arm: it fails on exactly that row with the credential in the clear
3 💡 the monotonicity statement was universal, but Result::hasSecrets() now returns false where the URI carries no :-separated password, which EXPLAIN QUERY TREE keys on AGREE, fixed @ 1a8bcc8 reproduced and scoped rather than changed in code, and now stated in the PR description. A real user:password prints [HIDDEN] on both binaries; only the credential-free face moves, and SHOW CREATE and system.query_log.query print that text byte-identically before and after. findURLSecretArguments carries the identical conditional; #120407 closes the face at its root
4 💡 a sentence claimed every positional after a collection name is rejected; a function-shaped one is silently ignored by the parser and echoed AGREE, fixed @ 1a8bcc8 corrected; master behaves the same way, so no code change

Noted, not blocking: an override key that is neither uri nor password keeps a value that cannot be
read here, and an unknown-key spelling such as URI = '...' is echoed before validation rejects it.
Master and the merged findURLSecretArguments behave identically, so closing either is a class-wide
change rather than this PR's contract.

Severity: ❌ blocker / ⚠️ major / 💡 nit.

Session id: cron:clickhouse-review-self-slot-58:20260922-001400

@clickhouse-gh

clickhouse-gh Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2ba884a]

Summary: ✅


AI Review

Summary

This PR fixes most of the MongoDB URI masking gaps and the new stateless test covers the accepted uri and named-collection cases well, but the current arity-only guard still leaves a rejected table-function path leaking a URI password into the exception, query log, and server log. I would not merge it until that surface split is closed.

Findings

❌ Blockers

  • [src/Parsers/FunctionSecretArgumentsFinder.cpp:396-401] The unreadable-argument-0 guard now keys only on size() <= 4, but findMongoDBSecretArguments is shared by both mongodb(...) and ENGINE = MongoDB(...). Only the engine surface has valid host:port calls with a computed first argument; on the table-function surface, TableFunctionMongoDB::parseArguments rejects any non-equals function node there. A query like mongodb(concat('mongodb://usr:', 'PW', '@127.0.0.1:27017/db'), 'db', 'c', 'u', 'p', 'x String') therefore still formats the URI password in cleartext while markSecretArgument(4) hides only the positional password slot. Split this logic by surface (or thread through ASTFunction::Kind) so the table function keeps the fail-closed mask on unreadable argument 0, and add a rejected-query regression that exercises the exception/query-log formatting path.
Final Verdict
  • Status: ❌ Block
    Minimum required actions: restore fail-closed masking for unreadable argument 0 on the mongodb table-function surface without regressing valid ENGINE = MongoDB(...) host expressions, and add a focused regression for the rejected table-function path because the current system.tables coverage cannot catch this leak.

LLVM Coverage Report

Measured on commit 2ba884a.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 26/26 (100.00%) · 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 22, 2026
The fail closed arm hid argument 0 whenever it could not be read as a string
literal, at every arity. Both MongoDB parsers fold a constant expression there,
so on the engine surface

    CREATE TABLE t (x String) ENGINE =
        MongoDB(concat('127.0.0.1', ':27017'), 'db', 'c', 'usr', 'pw')

is a table that gets created, and its SHOW CREATE, query log and server log
rendering hid the destination along with the password, as
MongoDB('[HIDDEN]', 'db', 'c', 'usr', '[HIDDEN]'). Master prints the expression.

Only the URI forms carry a credential in argument 0, and both surfaces select
that form by argument count: 2 or 3 for the engine and 3 or 4 for the table
function, against 5 to 7 and 6 to 8 for the host:port forms.
TableFunctionMongoDB itself tests the same size() <= 4 boundary, so the arm is
restricted to it. In the focused probe the 8 host arity shapes go back to
master's rendering while the 4 URI arity shapes stay hidden; over the 71 shape
corpus no row loses a mask relative to master.

The two control rows added to 05251 pin a folded host expression at both host
arities. They are byte-identical to master's output and fail on the previous
commit, so they fix the boundary in both directions.

The host:port arities therefore render as master does, including for a statement
that names an argument before the positional ones, such as
mongodb(password = 'S7', 'h:27017', 'db', 'c', 'usr'), which is rejected
(Code: 42 on the table function, Code: 47 on the engine) and echoed by master
too. That family stays the disclosed non-goal it already was.

The table function half of the report does not reproduce: that parser treats
every argument that is a function node as a malformed key = value, so
mongodb(concat('127.0.0.1', ':27017'), 'db', 'c', 'u', 'p', 'x String') is
rejected with Code: 36 on master as well and is not a valid query.

Co-Authored-By: Claude Opus 5 <[email protected]>
maskURIPassword(&uri);
result.count = 1;
result.replacement = std::move(uri);
/// The password of the `host:port` form; an out-of-range index is ignored, so the URI forms are unaffected.

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.

markSecretArgument(4) is still too optimistic for the host:port forms. A malformed call like mongodb('127.0.0.1:27017', 'db', 'c', structure = 'x String', 'usr', 'pw') is rejected later by TableFunctionMongoDB::parseArguments, but the query is formatted for the exception/query-log/server-log sinks before that validation runs. Here raw slot 4 is 'usr', so the real password at slot 5 is still emitted in cleartext. The engine path has the same issue with MongoDB(..., structure = 'x String', 'usr', 'pw') after evaluateConstantExpressionOrIdentifierAsLiteral leaves the stray equals result in the argument list. Since this PR explicitly covers the exception/logging sinks, this still needs a fail-closed branch once a named argument appears before the password slot, or a positional classification for the host:port forms.

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.

Measured at the sinks you name (not SHOW CREATE): 25 statement shapes on the published head db7c639 and on a master build 030993cc, with system.query_log and the server log diffed.

You are right that rejection does not prevent logging. mongodb('127.0.0.1:27017', 'db', 'c', structure = 'x String', 'usr', 'PW') fails with Code: 42 and still lands in query_log as ExceptionBeforeStart and in the server log twice, as ..., 'c', structure = 'x String', '[HIDDEN]', 'PW'). Raw slot 4 is 'usr', so the non-secret is hidden and the password is not. Engine spelling: Code: 47, same render.

It is not introduced or widened here. Exactly one of the 25 shapes renders differently between master and this head: the URI row this PR fixes. Master's non-collection path ends with else { markSecretArgument(4, false); return; }, and this head reaches the same markSecretArgument(4, false) at every host arity, so every named-argument shape is byte-identical.

The branch you propose would not close it, because the password is not at the named argument's index. mongodb('127.0.0.1:27017', 'db', 'c', structure = 'ignored String', 'usr', 'x String', 'PW') is accepted (Code: 1001 ... No suitable servers found, so the URI was built and the connection attempted), and raw argument 6 is what getConfiguration binds as the password: substituting 42 for it gives Argument 'password' must be a literal with type String, got UInt64 on both binaries. parseArguments keys on the raw index i (TableFunctionMongoDB.cpp:114-130), so a named argument below slot 5 drops an entry from main_arguments and a trailing positional refills the password slot. Fail-closing at the named argument's own position leaves that password in the clear.

And it is not free. options =, oid_columns = and structure = written after the password are accepted at the host arities (Code: 1001), so hiding whenever an equals is present would hide their non-secret values, which is the over-masking the previous round removed. The engine surface has no named arguments outside the named-collection form at all: structure = 'x String' is Code: 47, 'structure' = 'x String' folds to a UInt8 the user slot rejects with Code: 36, both as on master.

So this is the shifted-slot face disclosed as a non-goal in the description, pre-existing in master, 26.8 and 26.9, and closing it means resolving the slot through the parser's own binding rather than a fail-closed branch. I am leaving that scope call to a maintainer rather than folding a rendering change for accepted statements into a fix whose measured property is that it hides a superset of what master hides.

@clickhouse-gh

clickhouse-gh Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2ba884ab1 with master 365470f5a (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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - db7c639

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

Check / test Reason Owner / fixing PR
Integration tests (amd_asan_ubsan, db disk, 1/8) / test_max_bytes_ratio_before_external_order_group_by_for_server/test.py::test_max_bytes_ratio_before_external_distinct[server] Code: 241 (total) memory limit exceeded: would use 2.65 GiB, current RSS: 3.96 GiB, maximum: 4.00 GiB ... While executing BufferingFromFileSource. The ASan build's untracked RSS eats the test's 4 GiB server cap; nothing in this diff runs during external DISTINCT. 24 hours of CIDB: 62 rows over 55 unrelated PRs plus 5 true-master runs #121454 (external, open)
Performance Comparison (arm_release, master_head, 3/6) / formats_columns_nullable #1, adaptive_aggregation_heavy_payload #2 shard verdict 5 too long, 1 slower, 1 unstable; 1 confirmed regression(s) on the performance dashboard. Not attributable to this diff: the change is confined to FunctionSecretArgumentsFinder, which runs when a query is formatted for the log, and neither fixture issues a table function with credentials. Over the last 3 days adaptive_aggregation_heavy_payload is reported unstable on 267 distinct PRs and formats_columns_nullable slower on 8, so the master_head dashboard-verdict gate is misfiring rather than measuring a per-PR regression #121090 (mine, open) and #121189 (mine, open)
Mergeable Check, PR praktika rollups of the two rows above, no independent failure #121454, #121090 and #121189

Session id: cron:our-pr-ci-monitor:20260922-073125

@clickhouse-gh clickhouse-gh Bot added the comp-foreign-db Connectivity to external databases (ODBC/JDBC, MySQL, PostgreSQL, etc.). label Sep 22, 2026
…ction

The named collection branch skipped every post-collection argument that is not
a key = value override. Such an argument is not rejected:
tryGetNamedCollectionWithOverrides throws only when it is not an ASTFunction,
and under the default allow_named_collection_override_by_default = 1 it
silently ignores the rest. So

    CREATE TABLE t (x String) ENGINE =
        MongoDB(creds, concat('mongodb://usr:', 'PW', '@127.0.0.1:27017/db'))

is a table that gets created, and PW reached SHOW CREATE, the query log and the
server log in cleartext, on master as well as on this branch.

The same skip also cost a mask that master happens to keep. When such an
argument is written next to an effective uri override, master's mis-indexed
span replaces raw argument 1, the expression, with the masked text of the URI
it found elsewhere: it hides the expression and prints the effective password.
This branch did the opposite, hiding the effective password and printing the
expression. Failing closed on the argument hides both, so no shape loses a mask
relative to master any more.

Only a well-formed key = value pair keeps its value visible, so an override of
a key that is not a credential, such as structure, collection or oid_columns,
renders unchanged. An argument that cannot be an override carries no meaning to
the parser either: it is ignored under the default setting and rejects the
statement otherwise, which is why hiding it whole costs no information. Over 18
credential markers measured on master, on the previous commit and on this one,
the acceptance or rejection of every statement is identical and only the
rendering moves.

Rows f13 to f15 of 05251 pin the accepted engine and table function spellings
and the shape that carries an effective override beside the ignored argument;
all three fail on the previous commit. Row c11 pins an oid_columns override
against over-masking.

Co-Authored-By: Claude Opus 5 <[email protected]>
result.replaced_arguments[0] = quoteString(uri);
}
else
else if (function->arguments->size() <= 4)

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.

size() <= 4 is too coarse here because this helper now serves both mongodb(...) and ENGINE = MongoDB(...), but only the engine surface accepts a computed host:port in slot 0. On the table-function surface, TableFunctionMongoDB::parseArguments rejects any non-equals function node there, so mongodb(concat('mongodb://usr:', 'PW', '@127.0.0.1:27017/db'), 'db', 'c', 'u', 'p', 'x String') still reaches the exception/query-log/server-log formatters with the URI password in cleartext; markSecretArgument(4) hides only 'p'. Can we split findMongoDBSecretArguments by surface (or thread through ASTFunction::Kind) so the table function keeps the fail-closed mask on unreadable argument 0, while ENGINE = MongoDB(...) retains the host-expression exception?

@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author

Superseded on master: #122770 rewrote findMongoDBSecretArguments (argument 0 is scanned at every arity, every uri override is masked, and an unreadable one is hidden whole), and #123240 hides the arguments after a collection name.

I ran this PR's 05251_mongodb_uri_secret_arguments against a master build (44b568f4e): all 15 masking rows render exactly as in this PR's reference, and none of the test passwords reaches system.query_log or the server log. The only difference is c09/c10: master hides a computed host:port first argument of ENGINE = MongoDB whole, where this PR keeps it visible. That hides a destination, not a secret, so I see nothing left here that needs a PR.

@Algunenano, can this be closed as superseded by #122770?

@Algunenano Algunenano self-assigned this Oct 7, 2026

@Algunenano Algunenano left a comment

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.

Superseeded by #122770

@Algunenano Algunenano closed this Oct 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-foreign-db Connectivity to external databases (ODBC/JDBC, MySQL, PostgreSQL, etc.). groeneai-origin-self PR origin: self-found defect (impact-bar validated) pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants