Skip to content

Mask the S3 locator of a Backup database with the same rule as BACKUP ... TO - #122776

Closed
groeneai wants to merge 12 commits into
ClickHouse:masterfrom
groeneai:groeneai/backup-database-s3-locator-secret-rule
Closed

groeneai wants to merge 12 commits into
ClickHouse:masterfrom
groeneai:groeneai/backup-database-s3-locator-secret-rule

Conversation

@groeneai

@groeneai groeneai commented Sep 28, 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 a secret of an S3 backup destination being written in plaintext to system.query_log and the server log, by a Backup database whose destination has a headers(...) argument, and by a backup destination with a function argument, such as S3(url, 'secret', concat(...)). A Backup database now masks its destination with the same rule as BACKUP ... TO.

Description

Related: https://github.com/ClickHouse/clickhouse-private/issues/76267
Related: #117429
Requested by @ kolsha: reuse classifyS3Arguments in findBackupDatabaseSecretArguments.

On 26.8 (also 26.3 and 26.9), CREATE DATABASE d ENGINE = Backup('db', S3(url, 'secret', headers('a' = 'b'))) writes secret to system.query_log and the server log, while BACKUP ... TO masks the same destination. S3(url, 'secret', concat(...)) leaks on both.

Root cause: findBackupDatabaseSecretArguments kept its own copy of the S3 argument classification. Its positional counter did not skip headers(...), so a two-positional locator looked like the valid url, access_key_id, secret_access_key triple and slot 1 stayed visible. Separately, the shared rule counted a function or an identifier as a positional, so S3(url, 'secret', concat(...)), which BackupInfo::fromAST reads as a url, one positional and a credential clause, looked like the triple too.

Change:

  • The database path runs findBackupNameSecretArguments on the nested locator and only writes its result back as text. The duplicated classification is removed.
  • findBackupNameSecretArguments hides every positional argument that is not a literal and shows the access key id only for three literal positionals and no function before the last argument, the only triple BackupInfo::fromAST accepts. This applies on every backup-locator surface.
  • As on every other S3 surface, a headers(...) map on the database path now keeps its keys (values hidden), and the access key id of a valid triple stays visible when a map is present.

Validation: new test 05291_database_backup_locator_headers_secret_mask: all 13 result lines red on master, green with the fix. 04510 changes one line (db_04510_hdr). A matrix of 31 locator shapes on both paths: 18 cells leak on master and none with the fix.

🤖 Generated with Claude Code


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

groeneai and others added 5 commits September 28, 2026 11:42
`findBackupDatabaseSecretArguments` kept its own copy of the S3 argument
classification: a positional counter, a secret-key test and a url test beside
the shared `classifyS3Arguments` / `maskS3UrlArgument` / `maskS3PositionalsFrom`
that `BACKUP ... TO` uses. The copy did not skip `headers(...)` when counting
positionals, so `Backup('db', S3(url, 'secret', headers(...)))` counted three
positionals, took the valid-triple branch and wrote `secret` to
`system.query_log` and the server log, while `BACKUP ... TO` hid it.

The database path now runs `findBackupNameSecretArguments` on a finder over the
nested locator and only writes that result back as text. The formatter reaches
the nested `S3(...)` as an ordinary function, so it cannot apply the result by
itself; the outer result keeps the whole-argument replacement it had. A
`headers(...)` map on this path now keeps its keys, as on every other S3
surface.

The shared rule also counted a function in the last position as a positional,
while `BackupInfo::fromAST` reads it as the credential clause, so
`S3(url, 'secret', concat(...))` leaked on every backup-locator surface. That
function is now hidden and takes no positional slot.

Requested by kolsha on https://github.com/ClickHouse/clickhouse-private/issues/76267
("simplify findBackupDatabaseSecretArguments by reusing classifyS3Arguments").
Measured on 26.3.33.24, 26.8.10.6 and 26.9.1.1629: both leaks present.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A non-literal in a position other than the last (a function such as
`concat(...)`, or an identifier) is rejected by `BackupInfo::fromAST` only
after the statement is logged, so it was printed in the access key id or
filename slot. It is now hidden, and it keeps its positional slot.

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

A function or an identifier among the positionals is rejected by `BackupInfo::fromAST`
after the statement is logged. It was hidden but still counted, so
`S3(url, 'secret', concat(...), headers(...))` kept `'secret'` visible (the `Backup`
database path hid it before this PR). Such a locator now shows nothing after the url,
which makes the separate trailing-function rule redundant, so it is removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…its last argument

A `headers(...)` or `extra_credentials(...)` map before the last argument takes no
positional slot, but `BackupInfo::fromAST` accepts a function only in the last position
and rejects the locator after the statement is logged. `S3(url, 'secret', headers(...), 'x')`
therefore still looked like the valid triple and kept `'secret'` visible on both paths
(the `Backup` database path hid it before this PR).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the obvious doc line of the local write_as_written helper and state the Backup database writer's invariant precisely: it shows at most what BACKUP ... TO shows (it also hides arguments it cannot print).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet labels Sep 28, 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; 3 findings over 4 rounds, the last round clean).

# Sev Finding Verdict Evidence / action
1 ❌ A function that is not the last argument of an S3 backup destination (for example S3('url', concat('secret', 'x'), 'tail')) was printed as written in the access key id or filename slot, although BackupInfo::fromAST rejects it after the statement is logged AGREE, fixed in fc82f669edb7 Every positional that is not a literal is hidden; BACKUP ... TO cases added to 05291
2 ❌ Such an argument was hidden but still counted, so S3('url', 'secret', concat('a', 'b'), headers(...)) still looked like the valid triple and kept 'secret' visible on both paths AGREE, fixed in 9f92eff1100b The access key id stays visible only for three literal positionals; both paths added to 05291
3 ❌ A map before the last argument takes no positional slot, so S3('url', 'secret', headers(...), 'tail') still looked like the valid triple, although BackupInfo::fromAST accepts a function only in the last position AGREE, fixed in eeca8e602b66 The triple also requires no function other than key = value before the last argument; both paths added to 05291

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-9:20260928-225200

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE DATABASE d ENGINE = Backup('src', S3(url, 'SEKRIT', headers('a' = 'zz'))) and S3(url, 'SEKRIT', concat('a', 'b')) on either path; system.query_log shows SEKRIT on every master run. Same on 26.3.33.24, 26.8.10.6, 26.9.1.1629.
b Root cause explained? The database path had its own positional counter that did not skip headers(...), so a two-positional locator took the valid-triple branch and its slot 1 was printed. The shared rule also counted a function or an identifier as a positional, while BackupInfo::fromAST reads only literals as positionals (a last function is the credential clause), so S3(url, 'secret', concat(...)) looked like the triple too.
c Fix matches root cause? Yes. The database path takes every hide/show decision from the rule BACKUP ... TO uses (the duplicate classification is deleted), and that rule shows the access key id only for three literal positionals with no function before the last argument, the one shape the engine reads as the triple.
d Test intent preserved / new tests added? New 05291_database_backup_locator_headers_secret_mask (12 statements + a no-secret invariant over every logged row). 04510 changes one line; 05233, 05234, 05218 pass unchanged.
e Both directions demonstrated? Master: all 13 result lines of 05291 red, 04510 one line red. Fix: green. Deleting each part of the fix (map writer, map value masking, the non-literal mask, the literal-only triple gate, the function-before-the-last-argument gate) reddens its own lines.
f Fix is general across code paths? Every backup-locator surface (BACKUP ... TO, RESTORE ... FROM, base_backup, snapshot destinations) goes through the one rule, and the database path now calls it too. RESTORE ... FROM and base_backup measured.
g Fix generalizes across inputs (params/datatypes/wrappers)? 31 locator shapes on both paths: explicit and named-collection forms, maps first/middle/last, a map before the last argument or before the url, expression and string-literal keys, credential-bearing urls, 1 to 4 positionals, a function or an identifier in any positional slot. With the fix no shape logs a secret on either path. Data types N/A.
h Backward compatible? (maintainer-approved exception only) Display only: no setting, no persisted format. Stored definitions are unmasked and a live Backup database cannot carry these shapes, so existing SHOW CREATE DATABASE output is unchanged.
i Invariants and contracts preserved? Every printed string is still URI-masked, anything the writer cannot print is hidden, and the access key id is shown only for three literal positionals with no function before the last argument; a valid locator renders as before. The outer result keeps start = 1, count = 1, replacement whenever something is hidden, so the raw query text is never logged.

Session id: cron:clickhouse-impl-slot-5:20260928-221700

@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [013b199]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) FAIL
05210_lightweight_update_materialized_cte_in_ignore FAIL cidb
02346_non_negative_derivative NOT_FAILED cidb
01283_max_threads_simple_query_optimization NOT_FAILED cidb
03273_group_by_in_order_still_used_when_group_by_key_doesnt_match_order_by_key NOT_FAILED cidb
02884_create_view_with_sql_security_option NOT_FAILED cidb
Upgrade check (amd_release) FAIL
Error message in clickhouse-server.log (see upgrade_error_messages.txt) FAIL cidb

AI Review

Summary

This PR moves most Backup database masking onto the shared backup-locator rules and hardens several clickhouse_json readers, which is the right direction. I still see one already-threaded logging leak for untagged/non-canonical JSON spellings, one new EXPLAIN AST leak because that path still bypasses findSecretArguments, and one non-logging serialization regression from routing BackupInfo::toString() through the backup-locator formatter.

Findings
❌ Blockers
  • [src/Parsers/FunctionSecretArgumentsFinderAST.h:113] The untagged-JSON fallback still depends on the parser spelling Backup. If a clickhouse_json client drops the kind tags and the outer function arrives under a spelling that misses this exact check, the special-case is skipped; then the outer node is treated as an ordinary function, and any nested backup-locator spelling that the ordinary-function factories also do not recognize is formatted verbatim into query_log / server logs. Suggested fix: make the Backup/locator checks case-insensitive, or canonicalize/reject non-parser spellings before formatting.
  • [src/Interpreters/InterpreterExplainQuery.cpp:452] EXPLAIN AST still bypasses the new fallback entirely. HideSecretArgumentsMatcher asks SecretArgumentsRegistry directly instead of calling findSecretArguments, so an untagged clickhouse_json Backup(..., S3(...)) AST that is now safe in normal formatting still dumps the raw secret_access_key through DumpASTNode. Suggested fix: reuse findSecretArguments(*function) here, just like ASTFunction::formatImpl and the other EXPLAIN masking paths do.
⚠️ Majors
  • [src/Backups/BackupInfo.cpp:45] BackupInfo::toString() is not just a logging helper: DatabaseBackup::getCreateDatabaseQueryImpl(), buildStoragePolicyName(), and the persisted .backup metadata all use it. Routing it through formatBackupOrSnapshotLocator() changes the stable text form of valid locators with named overrides from key = value to equals(key, value), which changes SHOW CREATE DATABASE, metadata text, and the derived storage-policy hash even though this PR is supposed to be a logging-only fix. Suggested fix: keep the new formatter only in toStringForLogging(), and leave toString() on the normal AST formatter.
Final Verdict

❌ Changes requested — the main masking refactor is good, but I would not merge with the remaining EXPLAIN AST leak, the already-threaded untagged/non-canonical JSON leak, and the BackupInfo::toString() serialization regression.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 28, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. label Sep 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 013b19919 with master 457f57469 (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

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

Job report

Route `Backup` database `S3` locators through the existing backup masking rule and keep operator formatting at the locator owners. This preserves established output while removing duplicated credential classification.

Add focused SQL and JSON AST coverage for masking and formatting.

Related: ClickHouse#122776
Merge `master` to restore PR mergeability. Apply replacement masks before nested map handling so a secret in a computed map key cannot enter the AST dump. Add a regression test for direct and database backup locators.

Related: ClickHouse#122776
@clickhouse-gh clickhouse-gh Bot added comp-backup Backup/restore infrastructure and backup formats. and removed comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. labels Sep 30, 2026
Filter the `system.query_log` read by `current_database = currentDatabase()`,
and flush it in a retry loop until all 12 rows have landed: the row of an HTTP
query is written after its response is sent (ClickHouse#84364).

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

Copy link
Copy Markdown
Collaborator Author

Pushed 0493fd5 on top of your head: 05292 only, for the Style check (a current_database = currentDatabase() filter and a flush retry loop, #84364). That failure was skipping the rest of CI.

Separately, measured on cc1ccb1 with dialect = 'clickhouse_json': if both kind fields are removed from the JSON of CREATE DATABASE d ENGINE = Backup('src', S3('url', 'AKID', 'SECRET')), query_log gets the raw JSON with the secret. Removing only DATABASE_ENGINE is masked now (it leaks on master). BACKUP ... TO S3(...) with BACKUP_NAME removed leaks too, on master as well, so it predates this PR. I have not changed anything for it.

Comment thread src/Parsers/ParserCreateQuery.cpp Resolved
@hanfei1991 hanfei1991 assigned kolsha and unassigned hanfei1991 Sep 30, 2026
kolsha added 2 commits October 1, 2026 12:35
Choose the `Backup` secret rule by function name so client-supplied JSON AST kinds cannot bypass masking.

Cover a locator with both kind tags removed in `05292`.

Related: ClickHouse#122776
Preserve explicit secret masks before formatting nested maps and let the
`S3` classifier handle named maps before the generic positional pass.

Related: ClickHouse#123238
Comment thread src/Parsers/ParserCreateQuery.cpp Resolved
…N AST

Secret masking of a backup locator dispatches on `ASTFunction::Kind::BACKUP_NAME`.
The parser sets it on every locator slot, but the `clickhouse_json` readers took it
from the client, so a JSON AST with that `kind` removed was logged with the secret:
`BACKUP ... TO`, `RESTORE ... FROM`, `base_backup`, `BACKUP FROM SNAPSHOT`,
`SYSTEM UNLOCK SNAPSHOT ... FROM` and `ALTER ... UNLOCK SNAPSHOT ... FROM`.

The readers now set the kind themselves. `SYSTEM` and `ALTER` also require the
locator to be a function, which is the only node the parser produces there.

Extend 05292 with these slots.

Related: ClickHouse#122776

Co-Authored-By: Claude Opus 5.5 <[email protected]>
if (!function->hasArguments())
return;

if (function_.name == "Backup")

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.

This still only hardens the clickhouse_json path for the parser’s exact Backup / S3 spellings. ASTFunction::readJSON preserves whatever name the client sends, so a payload like CREATE DATABASE d ENGINE = backup('', s3('u', 'ak', 'SECRET')) (with or without the kind fields) never enters this new branch, and findDatabaseEngineSecretArguments() also returns without masking because it does not recognize backup. The statement is formatted/logged before DatabaseFactory rejects the engine name, so SECRET still reaches query_log / server logs. I think this needs a case-insensitive check here (and in the related ParserCreateQuery retagging) or an early rejection/canonicalization of non-parser spellings.

# Conflicts:
#	src/Backups/BackupInfo.cpp
#	src/Parsers/ASTFunction.cpp
#	src/Parsers/FunctionSecretArgumentsFinder.cpp
#	src/Parsers/FunctionSecretArgumentsFinder.h
#	src/Parsers/FunctionSecretArgumentsFinderAST.h
{
if (auto * map = arguments[i]->as<ASTFunction>();
map && map->arguments && secret_arguments.nested_maps.contains(map->name))
if (auto replaced = secret_arguments.replaced_arguments.find(i); replaced != secret_arguments.replaced_arguments.end())

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.

EXPLAIN AST is still bypassing the Backup/backup-locator hardening this PR added. In this visitor the masking decision still comes from SecretArgumentsRegistry::instance().find(function->getKind(), ...), so an untagged clickhouse_json Backup(..., S3(...)) arrives here as an ordinary function again and DumpASTNode prints the raw secret_access_key.

Because FunctionSecretArgumentsFinderAST.h is already included in this file, I think this block needs to use findSecretArguments(*function) like ASTFunction::formatImpl and the other EXPLAIN masking paths do.

{
ASTPtr ast = toAST();
return ast->formatWithSecretsOneLine();
return formatBackupInfo(*this, /* show_secrets= */ true);

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.

BackupInfo::toString() is used outside logging (DatabaseBackup::getCreateDatabaseQueryImpl(), buildStoragePolicyName(), and the persisted .backup metadata), so switching it to formatBackupOrSnapshotLocator() changes the stable text form of valid locators. A Backup database with named overrides like S3('u', use_environment_credentials = 1) now serializes as S3('u', equals(use_environment_credentials, 1)), which changes SHOW CREATE DATABASE, metadata text, and the derived storage-policy hash even though this PR is supposed to be a logging-only fix.

I think only toStringForLogging() should go through the new helper; toString() needs to keep the normal AST formatter.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 013b199

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
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05210_lightweight_update_materialized_cte_in_ignore not from this PR (it only changes the secret masking of backup locators): UNKNOWN_TABLE on a reused MATERIALIZED CTE that a parallel replicas read with a local plan sends to the replicas. 147 of 147 reruns with the same settings passed; 147 PRs and 26 master runs show it in 30 days #123121 (mine, open)
Upgrade check (amd_release) / Error message in clickhouse-server.log (see upgrade_error_messages.txt) not from this PR: TCPHandler logs Can't skip excessive input packets after the exception for Unexpected packet Hello received from client (Code 101), seen on 20 PRs in 30 days #119368 (external, open)
Mergeable Check, PR praktika rollups of the rows above #123121 and #119368, as above

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261012-150017

@kolsha

kolsha commented Oct 19, 2026

Copy link
Copy Markdown
Contributor

Changes became too complicated
I think it's not worth it

@kolsha kolsha closed this Oct 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Understood. The leak itself is still on master (94e0f5ac): CREATE DATABASE d ENGINE = Backup('src', S3(url, 'KEY', headers('a' = 'b'))) writes KEY to system.query_log and the server log (it is logged before validation rejects it with code 42), while BACKUP ... TO with the same locator hides it. The narrow fix is one condition: make the positional counter in findBackupDatabaseSecretArguments skip headers(...) the way classifyS3Arguments does, plus one .sql test. Should I open that as a separate small PR, or leave it as is?

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-backup Backup/restore infrastructure and backup formats. groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants