Skip to content

Mask secrets in SHOW CREATE DATABASE of a Backup database - #117429

Merged
jkartseva merged 1 commit into
ClickHouse:masterfrom
groeneai:mask-backup-database-locator-secret
Sep 24, 2026
Merged

jkartseva merged 1 commit into
ClickHouse:masterfrom
groeneai:mask-backup-database-locator-secret

Conversation

@groeneai

@groeneai groeneai commented Sep 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):

Fixed a Backup database engine printing the credentials of its destination in plaintext.
SHOW CREATE DATABASE, system.databases.engine_full, system.query_log and the messages that
reject a malformed locator showed an AzureBlobStorage account_key, a connection string or a
presigned URL regardless of format_display_secrets_in_show_and_select.

Description

Related: https://github.com/ClickHouse/clickhouse-private/issues/69069
Related: #118349
Requested by @ nikitamikhaylov; verified by @ oranjeai.

Reading a Backup database's definition needs only SHOW_DATABASES, implied by any grant on it.
#118674 renders the locator as the function it is, so the pre-existing nested-S3 rule redacts it.
This PR covers the shapes that rule does not model, and the messages that reject a locator.

  • FunctionSecretArgumentsFinder: only Backup(database_name, locator) has known slots, so any
    other shape hides every argument, as does a locator whose engine is not the reconstructed S3 -
    unless its arguments are exactly the literals that engine reads, which name a destination and no
    credential (File, Disk, Memory, Null). An AzureBlobStorage destination reads a different
    signature than the table engine of the same name, so it gets its own rule, and both now fail
    closed on an account url that is no plain storage account URL and on a named-collection override
    that is unreadable, repeated, or paired with another credential. Engine names and arity stay
    visible, and a statement is logged before validation rejects it.
  • Rejection messages no longer echo the argument they reject: BackupInfo::fromAST, the
    database_name check of DatabaseBackup::parseArguments, the S3 creator, and both
    duplicate-definition messages of BackupMetadataFinder, database and table.

Each change has an arm measured to redden without it: 04510, two new stateless tests, and
test_mask_sensitive_info.

Rebased on #118674, which owns #118349. Its definition rendering, its acceptance of a locator held
in a string literal while metadata is replayed, and its refusal of one elsewhere are dropped here,
along with the tests that covered them. Archives still store definitions unmasked, so backups stay
restorable. Unchanged: the shared Azure connection-string helper (#114946, #114964).


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

Version info

  • Merged into: 26.10.1.565-master (included in 26.10 and later)
  • Backported to: 26.9.2.37, 26.8.11.50, 26.7.18.2, 26.3.37.3

@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 1, 2026
@groeneai

groeneai commented Sep 1, 2026

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

Three rounds of an independent cold review plus a second-model gate, adjudicated against the recorded
validation evidence. Two blockers were found and returned for fix rounds; the third round's gate
returned no findings.

❌ Blockers

# Finding Verdict
1 tests/integration/test_backup_source_grants/test.py pins the pre-change quoted-locator spelling of an uncrafted BACKUP DATABASE manifest (:317) and expects the target-absent restore to fail at creation (:330-338). Both become false once the locator stays a function. AGREE, fixed in r1
2 BackupMetadataFinder::findDatabaseInBackupImpl renders both definitions with formatWithSecretsOneLine in its "Extracted two different create queries" CANNOT_RESTORE_DATABASE message, so a locator credential reaches the error, the log and system.query_log.exception in plaintext. Reachable with RESTORE DATABASE a AS c, DATABASE b AS c, before the embedded-source access checks. The exposure is byte-identical before and after this change, but the twin message in RestorerFromBackup uses formatForErrorMessage and is masked here, so this was a symmetric-path gap inside the function this change edits. AGREE, fixed in r2

⚠️ Major

# Finding Verdict
3 The ALTER DATABASE ... MODIFY COMMENT consequence in the changelog entry (pre-change the rewritten metadata stopped the server from starting) was measured by hand but had no test. AGREE, fixed in r1
4 BackupInfo::fromAST changes three messages; only the not-a-function one was measured. The literal-argument message is independently reachable and also used to echo its argument. AGREE, fixed in r1
5 The draft described the printed definition as "valid SQL again". Measured across all 7 commits touching src/Databases/DatabaseBackup.cpp: the locator has been a string literal since 35a5cf694e752cb (2025-02-07), so it was never re-executable and no regression happened. AGREE, corrected

💡 Noted, not blocking

  • The commit message credits the FunctionSecretArgumentsFinder change with masking
    RestorerFromBackup's definition-mismatch message. That message is masked, but by the producer
    change plus the archive normalization rather than by the new non-function branch: the normalization
    runs at BackupMetadataFinder.cpp:433, ahead of :454, which is the only writer of the AST that
    message prints, and DatabaseBackup::parseArguments accepts exactly two arguments, so no definition
    a server can write escapes it. The behaviour claimed is real; only the attribution is off.
  • normalizeLegacyBackupDatabaseLocator catches every exception and reports BAD_ARGUMENTS, so a
    memory-limit or cancellation raised inside parseQuery is reclassified. Narrowing it needs error-code
    inspection, and appending the original message would re-echo the locator, which is what the hunk
    exists to prevent.
  • No test asserts that a reader with format_display_secrets_in_show_and_select = 1 still sees the real
    value. It is structurally unreachable: ASTFunction::formatImplWithoutAlias consults the
    secret-arguments finder only under if (!settings.show_secrets), so nothing in this change can affect
    an entitled formatter.
  • 05055 guarded only its setup block with --send_logs_level 'error' where 02843 and 04327 guard
    every call. Verified to carry no CI consequence, since .sh tests already run at error with
    --client_logs_file; aligned with the siblings anyway.
  • The two statements added to 04510 extend an existing test rather than starting a new one. They are
    asserted by that test's own aggregate over system.query_log for its current_database, and the
    measured 1 1 1 -> 1 0 1 -> 1 0 0 ladder is defined over that single row, so splitting them out
    would duplicate the whole fixture and spread one invariant over two files.
  • The masked duplicate-definition message prints two identical strings when the two definitions differ
    only in their credential. RestorerFromBackup has had the same property for as long as it has masked,
    so this follows the existing behaviour rather than inventing a diff-highlighting scheme. The
    comparison itself still uses formatWithSecretsOneLine, deliberately: masking the comparison key
    would make two definitions differing only in their credential compare equal.

Suggested and declined

  • Classifying this as Critical Bug Fix (crash, data loss, RBAC). That category is not selected
    proactively; if a maintainer wants it, say so on this PR and I will switch it and record the request.

Session id: cron:clickhouse-review-slot-10:20260831-234400

@clickhouse-gh clickhouse-gh Bot closed this Sep 1, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 1, 2026
@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. New 05055_database_backup_locator_secret_mask fails on demand on pristine master with testtest in its output; new 05056_restore_duplicate_database_definition_secret_mask fails on demand with testtest on three lines of the restore error, both against pristine master (where that message prints the quoted locator, measured) and against a build with only the message change reverted; 04510's own final invariant returns 1 1 1 pristine; the new test_database_backup case throws Code: 36. No probabilistic arm anywhere.
b Root cause explained? getCreateDatabaseQueryImpl wrapped the locator in quoteString, so BackupInfo::toString (which formats with secrets by design) became an opaque ASTLiteral before masking ran. findBackupDatabaseSecretArguments then returned early at FunctionSecretArgumentsFinder.cpp:1183 because argument 1 was not an ASTFunction, leaving its reconstruction path (:1185-1339) dead for this input, so the literal was printed verbatim regardless of format_display_secrets_in_show_and_select.
c Fix matches root cause? Yes, at the layer that owns each surface: the representation is corrected at the producer, the masker fails closed where it cannot reconstruct, the three BackupInfo::fromAST messages stop echoing the fragment, the one boundary where the old representation still enters is normalized, and the duplicate-definition message reports its two definitions through formatForErrorMessage instead of the two comparison strings. No widened bound, no no-random-* tag, no guard at a crash site.
d Test intent preserved / new tests added? Yes. 03279's reference was regenerated only on the line that prints the locator; 04510 gained two statements and one widened assertion column and lost nothing, and its Backup cases still assert by error code, so the message change cannot disturb them. Two new stateless tests, three new integration cases. One existing case in test_backup_source_grants asserted the pre-change spelling of an uncrafted manifest, so its exact-text assertion was inverted to the function form and its target-absent arm now asserts success with an engine_full positive control; the coverage that retired is replaced by a stronger arm (a legacy string locator's inner destination is now authorized rather than skipped). No assertion was weakened or dropped.
e Both directions demonstrated? Yes, one build id per arm with the server's buildId asserted equal to the binary before each verdict. 04510's invariant: 1 1 1 pristine (9b2ea536) -> 1 0 1 with the masking hunk alone (50849a2f) -> 1 0 0 complete (f74d09da). 05055: secret visible pristine, [HIDDEN] fixed. 05056: the restore error carries the secret on three lines and no [HIDDEN] both on pristine master (c2863c04) and with only the message change reverted (a8709503), and the reverse fixed (53da679d), while its two "reached this check" counters stay 1 on every arm so only the masking differs. On that pristine arm 05055, 04510 and 03279 fail too. 03279 passed pristine on the old spelling and reddened on the fix. The integration case fails against a build with the normalization removed (537e7e77) and passes with it. Three further arms, each isolating one hunk: reverting only BackupInfo::fromAST's literal-argument message turns 04510's invariant into 1 0 1 (57cbeca8); removing the normalization call turns the new authorization case from ACCESS_DENIED/READ ON S3 into BAD_ARGUMENTS (097cae77); reverting the producer alone makes ALTER DATABASE ... MODIFY COMMENT followed by a restart fail to bring the server up at all, with Code: 36 ... while loading database (9a398ffc).
f Fix is general across code paths? Yes. Fixed at the producer (SHOW CREATE DATABASE and system.databases.engine_full), at the masker (logged query text, and RestorerFromBackup's definition-mismatch CANNOT_RESTORE_DATABASE message, measured to mask to '[HIDDEN]'), at the three error strings, at the archive reader, which covers restore creation, locator authorization, definition comparison and the duplicate-definition check with one change, and at BackupMetadataFinder's own duplicate-definition message, the unmasked sibling of that twin, twelve lines from the reader's own insertion point. Sibling engines that rebuild a create query (DatabaseS3, DatabaseHDFS, DatabaseFilesystem, DatabaseURL, DatabaseRemote) were checked; none reproduces the opaque-composite pattern. Two residuals are stated in the description.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Locator shapes exercised: nested S3 positional, nested Disk, named-collection and key-value forms, a quoted string literal, an undecodable literal, and an argument-less locator. The key-value form was measured specifically, because BackupInfo::toAST renders such an argument as equals(k, v); the normalization installs the parsed node so a legacy definition still compares equal to a live one. Both format_display_secrets_in_show_and_select states are covered structurally: show_secrets = true skips the finder entirely, so no change here can reach an entitled caller.
h Backward compatible? (maintainer-approved exception only) Yes. No setting default changes, so no SettingsChangesHistory.cpp entry. The only input still carrying the old spelling, a definition inside an existing backup archive, is normalized as it is read; removing that normalization was measured to break restore in two distinct ways, which is what makes it the migration path rather than a documentation note. Two knowingly-unfixed edges are stated in the description.
i Invariants and contracts preserved? Yes. The normalization rewrites argument 1 only for a two-argument Backup engine whose argument 1 is a String literal, and returns untouched otherwise, so no other engine or locator shape is observable. It runs at the single boundary where an archived definition enters, before the comparison string is computed, so every consumer sees one representation. It fails closed: a locator that does not decode throws instead of being left in place, which would have preserved the checkSourceAccess skip that only applies to a non-function argument; the surrounding reader already propagates the first exception. Authorization moves in the safe direction, since a normalized locator no longer takes that early return. The masking change only widens what is hidden, never what is shown. The duplicate-definition message change alters no state and no comparison: both ASTs are non-null there (the first is the leading conjunct of the guard), the comparison key is deliberately left formatting with secrets so definitions differing only in a credential still compare unequal, and it runs on the failure path only. No lock, allocation or lifetime is touched, and the parsed node is owned by the same AST graph as the node it replaces.

Session id: cron:clickhouse-impl-slot-41:20260831-223900

Verification: 200/200 randomized runs over 03279, 04510, 05055 and 05056 plus a
no-random-settings control run, and both integration modules green - test_database_backup at
15 passed and test_backup_source_grants at 13 passed.

@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [44a9802]

Summary: ✅


AI Review

Summary

This PR rebases the post-#118674 remainder of the Backup-locator masking fix: it removes credential echoes from BackupInfo/DatabaseBackup errors, routes duplicate-definition restore errors through secret-aware formatting, and teaches FunctionSecretArgumentsFinder to hide more malformed Backup / AzureBlobStorage locators. I found one new blocker in the current diff and one previously-discussed blocker that is still present, so this should not merge yet.

Findings

❌ Blockers

  • [src/Parsers/FunctionSecretArgumentsFinder.cpp:691-700] azureCollectionArgumentsAreShowable still treats any readable key = value override as display-safe. BACKUP TABLE t TO AzureBlobStorage(nc, foo = 'SEKRIT') leaves SEKRIT in system.query_log.query / the server log before BackupInfo::getNamedCollection() rejects foo as non-overridable, and CREATE TABLE ... ENGINE = AzureBlobStorage(nc, foo = 'SEKRIT') has the same leak before validateNamedCollection() throws.
    Suggested fix: restrict the visible override set to the keys the Azure backup/table paths actually consume (connection_string / storage_account_url with dedicated masking, account_key hidden, and the explicitly non-secret keys such as container, blob_path, account_name, plus the one backup filename positional). Any other key should fail closed and hide the locator whole. Add a 04510 regression for an unknown override key.

  • [src/Parsers/FunctionSecretArgumentsFinder.cpp:661-678] [dismissed by author -- https://github.com/Mask secrets in SHOW CREATE DATABASE of a Backup database #117429#discussion_r3941875984] maskAzureConnectionString still stops after hiding the first credential field in a connection string. AzureBlobStorage('...;AccountKey=K;SharedAccessSignature=S', 'cont', 'path') therefore still writes whichever secret comes second into query_log.query on the backup-locator paths this PR adds. Deferring the helper rewrite to #114964 does not make the current branch safe.
    Suggested fix: keep scanning the same connection string for both AccountKey= and SharedAccessSignature= (and all occurrences of each) before returning, or fail closed on a string that contains more than one credential-bearing key.

Final Verdict

❌ Request changes. The new Azure named-collection masking helper is still too permissive for unknown overrides, and the author-deferred multi-credential connection-string leak is still reachable on the backup-locator paths introduced here.

LLVM Coverage Report

Measured on commit 44a9802.

Metric Baseline Current Δ
Lines 88.50% 88.50% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.80% 80.80% +0.00%

Changed lines: Changed C/C++ lines covered: 191/196 (97.45%) · 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 1, 2026
@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @jkartseva @tavplubix, could you review this? DatabaseBackup::getCreateDatabaseQueryImpl wrapped the locator in quoteString, so it reached the formatter as an opaque string literal and findBackupDatabaseSecretArguments returned early on a non-function argument, printing an S3 secret_access_key in plaintext in SHOW CREATE DATABASE and system.databases.engine_full. Keeping it a nested function also makes the printed definition parse again, and the archive reader normalizes the old spelling so existing backups still restore.

@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 44a980257 with master de0734db6 (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

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

Job report

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

Confirmed and fixed in 18822a2.

Both cited facts hold at source: registerBackupEngineAzureBlobStorage.cpp:356 registers only the
capitalized AzureBlobStorage, into a case-sensitive std::unordered_map (BackupFactory.h:114),
and FunctionSecretArgumentsFinder.cpp:248 matches only the lowercase table-function spelling.
Measured on a debug server, reading the masked text back from system.query_log, with an S3
locator alongside as a live control:

nested locator before after
AzureBlobStorage(url, cont, blob, account, 'CANARY') canary printed '[HIDDEN]'
AzureBlobStorage('...;AccountKey=CANARY;...', cont, blob) canary printed '[HIDDEN]'
AzureBlobStorage(collection, account_key = 'CANARY') canary printed '[HIDDEN]'
S3('url', 'ak', 'CANARY') (control) '[HIDDEN]' '[HIDDEN]'

The BACKUP ... TO AzureBlobStorage(...) twin was already masked at
FunctionSecretArgumentsFinder.cpp:841, so only the database engine was exposed.

A locator is printed verbatim only when its engine holds no credential in its arguments (Disk,
File, Memory, Null). Any other engine keeps its engine name and argument count, neither a
secret, and hides every argument:

ENGINE = Backup('src', AzureBlobStorage('[HIDDEN]', '[HIDDEN]', '[HIDDEN]', '[HIDDEN]', '[HIDDEN]'))

I did not reconstruct the Azure signature argument by argument: its accepted forms (3 positionals,
5 positionals, an AccountKey= connection string, a named collection with overrides) and the
invalid counts are each their own leak path, while hiding the arguments has none. Keeping the
function shape also preserves the invariant this PR is built on, so the definition still parses back
into a locator function rather than an opaque string.

The regression case joins the Backup reconstructor block of 04510; reverting this commit alone
drops its masked line and turns its canary count from 0 to 1. Its url carries a query string, so the
engine rejects it before any network access.

The changelog entry and the description claimed S3 only, and said non-S3 locators were masked in
neither spelling; both are corrected.

@PedroTadim

Copy link
Copy Markdown
Member

cc @orloffv

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e98ca33

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.

Check / test Reason Owner / fixing PR
Bugfix validation (functional tests, amd64) / job-level AssertionError: Could not find master builds in S3 CI harness: the shared find_master_builds helper still builds the REFs/master/<sha> prefix the artifact uploader stopped writing, so no arm can validate anything. 87 distinct PRs carry it since 2026-08-31 19:31Z #117433 (mine, open)
Bugfix validation (functional tests, aarch64) / same assertion same harness defect, sibling arch #117433 (mine, open)
Bugfix validation (integration tests, amd64) / same assertion, raised from ci/jobs/integration_test_job.py same helper: both job scripts import find_master_builds from ci/jobs/scripts/bugfix_validation.py, which is the file the fix touches #117433 (mine, open)
Bugfix validation (integration tests, aarch64) / same assertion same helper, sibling arch #117433 (mine, open)
Finish Workflow / new_tests_check.py cascade: it needs one per-arch arm to report OK or XFAIL, and all four arms errored above #117433 (mine, open)
Stateless tests (arm_binary, parallel) / 00084_external_aggregation Code: 241 query memory limit while spilling external aggregation, would use 572.80 MiB ... maximum: 572.20 MiB in SourceFromNativeStream. 17 distinct PRs plus 2 true-master runs in 30 days, and the job's own rerun diagnosis with the identical randomized settings is 18 of 18 passing #117326 (mine, open)
Docs examples / Documentation examples, Function/toYYYYMM#0 the example pinned SELECT toYYYYMM(now(), 'US/Eastern') to 202608 and the month rolled over. 128 PRs plus 6 master runs carry it since 2026-09-01 04:10Z #117459 (mine, merged 2026-09-01), absent from this tree
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / Container memory budget exceeded (/docker) the nested-container budget sized the unreclaimable /docker leaf last #117412 (external, merged 2026-09-01), absent from this tree

Both merged owners landed after this tree was built, which is why they are absent from it. I am holding the master merge until #117433 and #117326 merge, so one rebuild picks up every owner instead of four.

Session id: cron:our-pr-ci-monitor:20260901-153000

@clickhouse-gh clickhouse-gh Bot added the comp-backup Backup/restore infrastructure and backup formats. label Sep 4, 2026
@jkartseva jkartseva self-assigned this Sep 4, 2026
@jkartseva

Copy link
Copy Markdown
Member

@groeneai Merge master please

@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

@jkartseva Merged master at 625e1ce7e12baface0bcfbb900cd2479ea394674; the head is now 4b57bf4abe306eae6c87c8a877f5d887f645d785.

Clean merge, no conflicts and no submodule pins moved. The diff against master is unchanged at 13 files, +486/-30. I rebuilt on the merged tree and the four stateless tests this PR touches pass locally (03279, 04510, 05055, 05056). CI is running on the new head.

@zlareb1

zlareb1 commented Sep 6, 2026

Copy link
Copy Markdown
Member

TL;DR: the residual this PR discloses ("a metadata file a pre-fix MODIFY COMMENT already rewrote stays unloadable: re-create the database") is more severe than the sentence implies — that file aborts server startup entirely, so the suggested remedy cannot be performed. Filed #118349 with a repro on 26.8.2.7 LTS and 26.9.1.1 (control restart clean, fault restart down permanently).

  1. The stated remedy is unreachable. loadDatabase rethrows the parse failure with no catch above it, so one metadata/<db>.sql carrying the string-literal locator stops the whole server before it accepts connections. No DDL can be issued to drop or re-create the database; the only recovery is hand-editing the file while the server is down.

  2. The repair in this diff covers one of the two consumers. normalizeLegacyBackupDatabaseLocator runs on the restore-from-backup path (BackupMetadataFinder), but parseArguments in DatabaseBackup.cpp still feeds engine_args[1] straight to BackupInfo::fromAST, which throws Expected function on the literal form. Applying the same normalizer there (or falling back to the already-existing BackupInfo::fromString when the argument is a string literal) would make installs that hit the pre-fix rewrite bootable again after upgrading to this fix.

The forward fix itself looks right — getCreateDatabaseQueryImpl now emits the function form, so new MODIFY COMMENT runs stop producing the broken shape.

@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author

Both confirmed, and both are fixed here rather than in a follow-up (head 5edfd78).

1. The remedy was unreachable, and the description no longer claims it. Measured on the
previous head (d2646b6d, build a8898a21d8e3c59d): with one metadata/<db>.sql carrying the
string-literal locator, the server exits during metadata loading and never listens.

<Error> Application: Code: 36. DB::Exception: Expected a function as the backup locator:
  while loading database `bdb` from file metadata/bdb.sql. (BAD_ARGUMENTS)
  BackupInfo::fromAST -> parseArguments (DatabaseBackup.cpp:516) -> registerDatabaseBackup
  -> DatabaseFactory::get -> InterpreterCreateQuery::createDatabase -> executeCreateQuery
  -> loadDatabase (loadMetadata.cpp:129) -> loadMetadata (:297) -> Server::main (Server.cpp:3390)

loadDatabase is the only handler on that path and it rethrows, so there is no window in which
DDL could drop or re-create the database. The ### Description sentence is corrected.

2. The second consumer now runs the same normalizer. parseArguments normalizes the argument
before decoding it; the normalizer moved to DatabaseBackup::normalizeLegacyLocator, so the archive
reader and the metadata-load path accept exactly the same two spellings and reject the same third.
A string that decodes to no locator is still refused, with a message that does not quote it, because
it carries credentials. Same data directory, same legacy files, build 0701416a14137bc6: the server
starts, both databases read through their backups, SHOW CREATE DATABASE prints the function form
with the secret hidden, and the next MODIFY COMMENT persists that form, so the file self-heals.

One consequence of accepting the string form was worth closing with it. parseAndAuthorizeLocator
returned early for a non-function locator, which was safe only while creation rejected that
spelling, and it is the only check that runs as the real user for CREATE DATABASE ... ON CLUSTER,
since the worker leg that creates the database carries no user. Measured with that predicate left as
it was: a user without READ ON S3 creates the database from the string spelling, while the
identical function form is refused. Covered by a new case in test_backup_source_grants;
test_database_backup gains the restart with a hand-written legacy metadata file, and 04510
gains the two rejection messages that the normalization moved out of reach of its existing case.

#118349 is closed by this PR, named in the changelog entry and in the linked-issue block.

Comment thread src/Backups/BackupMetadataFinder.cpp Resolved
@PedroTadim

Copy link
Copy Markdown
Member

It seems #114405 needs to be backported before #118674 cc @pufit

robot-ch-test-poll4 added a commit that referenced this pull request Sep 25, 2026
Cherry pick #117429 to 26.9: Mask secrets in SHOW CREATE DATABASE of a Backup database
robot-clickhouse added a commit that referenced this pull request Sep 25, 2026
robot-clickhouse added a commit that referenced this pull request Sep 25, 2026
robot-clickhouse-ci-1 added a commit that referenced this pull request Sep 25, 2026
Cherry pick #117429 to 26.8: Mask secrets in SHOW CREATE DATABASE of a Backup database
robot-clickhouse added a commit that referenced this pull request Sep 25, 2026
robot-clickhouse added a commit that referenced this pull request Sep 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Confirmed, and on 26.3 and 26.7 the chain is one step longer than that.

#118674 edits tests/integration/test_backup_source_grants/test.py and the configs/backups.xml next to it, both added by #114405; both 404 on 26.3 and 26.7 and are present on 26.8 and 26.9, as is src/Backups/BackupSourceAccess.h.

#114405 itself sits on #110610 ("Add factory-owned backup destination identity", merged 2026-07-23, no backport label): RegisteredEngine and destination_identity_fn in src/Backups/BackupFactory.h are absent on 26.3 and 26.7, and #114405 adds its SourceAccessFn next to them. That is why all five of its cherry-picks conflicted and were closed unmerged in August (#114741 through #114745). So the order for the two older branches is #110610, #114405, #118674, then this one. None of those labels are mine to set.

26.8 and 26.9 need nothing further: #122173 and #122172 landed #118674 there, the robot re-tried my cherry-picks #121968 and #121967 against the moved heads and merged both, and the resulting backports #122202 and #122209 are mergeable with CI still running. I will follow up on those two if anything reds.

If the full chain is not worth it for 26.3 and 26.7, there is a cheaper option. On those branches getCreateDatabaseQueryImpl still renders the locator through quoteString(backup_info.toString()), so it arrives as a single string literal and is masked whole, which leaves the display half of this PR moot there. What still applies is the exception path, where registerBackupEngineS3.cpp formats the rejected argument into the error message. I can port that hunk alone onto #121965 and #121966, without the two tests that assert the post-#118674 rendering. Otherwise closing those two cherry-picks is fine by me.

clickhouse-gh Bot added a commit that referenced this pull request Sep 25, 2026
Backport #117429 to 26.9: Mask secrets in SHOW CREATE DATABASE of a Backup database
clickhouse-gh Bot added a commit that referenced this pull request Sep 25, 2026
Backport #117429 to 26.8: Mask secrets in SHOW CREATE DATABASE of a Backup database
PedroTadim added a commit that referenced this pull request Sep 28, 2026
The bot's base predates the prerequisite (#122640), so 26.3 is merged in first and the
cherry-pick on top of that.

Conflicts resolved as in the already-merged 26.6 and 26.4 cherry-picks of the same change; the
delta is byte-identical to them outside the integration test:

- `registerBackupEngineS3.cpp`: kept 26.3's `collectCredentials` call without `->clone()`, and
  with it master's paragraph about `BackupImpl::writeBackupMetadata` comparing locators as text.
- `test_mask_sensitive_info/test.py` and
  `04510_s3_explicit_url_named_secret_mask.{sql,reference}`: empty release side, took the added
  blocks. 26.3 gains both new test functions, where private 26.4 gained only the Azure one
  because it already had the S3 one.

Related: #121965

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
robot-ch-test-poll4 added a commit that referenced this pull request Sep 28, 2026
Cherry pick #117429 to 26.3: Mask secrets in SHOW CREATE DATABASE of a Backup database
robot-clickhouse added a commit that referenced this pull request Sep 28, 2026
PedroTadim added a commit that referenced this pull request Sep 28, 2026
Cherry pick #117429 to 26.7: Mask secrets in SHOW CREATE DATABASE of a Backup database
PedroTadim added a commit that referenced this pull request Sep 28, 2026
The bot's base predates the prerequisite (#122641), so 26.7 is merged in first and the
cherry-pick on top of that.

Conflicts resolved as in the already-merged 26.6 cherry-pick and the 26.4/26.3 ones; the applied
delta is byte-identical to them:

- `registerBackupEngineS3.cpp`: kept 26.7's `collectCredentials` call without `->clone()`, and
  with it master's paragraph about `BackupImpl::writeBackupMetadata` comparing locators as text.
- `04510_s3_explicit_url_named_secret_mask.{sql,reference}`: empty release side, took the added
  `system.query_log` masking assertion.

Related: #121966

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
PedroTadim added a commit that referenced this pull request Sep 28, 2026
All 7 builds failed on `src/Parsers/FunctionSecretArgumentsFinder.cpp` with `isAlphaASCII`,
`isAlphaNumericASCII` and `equalsCaseInsensitive` undeclared (the `std::all_of` error is a
cascade of the second, used inside the lambda).

On master those come from `<Common/StringUtils.h>`, which that file includes - but the include
was added there by a different commit, not by #117429, so 26.3 never got it. 26.3 also has only
the `(char, char)` overload of `equalsCaseInsensitive`, while the backported call site passes a
`std::string_view`, so the overload is taken verbatim from master rather than rewriting the call
sites to something 26.3 already has.

The four existing `equalsCaseInsensitive` call sites on this branch all pass `char`, which
`std::string_view` cannot be converted from, so none of them becomes ambiguous.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=122669&sha=b297f764fdbb6ce824c8285dc637330b72c40f3e&name_0=BackportPR&name_1=Build%20%28amd_debug%29

Related: #122669

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
robot-clickhouse added a commit that referenced this pull request Sep 28, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 28, 2026
PedroTadim added a commit that referenced this pull request Sep 29, 2026
`04510_s3_explicit_url_named_secret_mask` asserts `BAD_ARGUMENTS` for
`AzureBlobStorage('DefaultEndpointsProtocol=...;AccountKey=...;', 'cont',
'blob', 'acct', 'key')`, a connection string written where the five-argument
shape requires a plain storage account URL. On master that arm never reaches
the SDK: `validatePlainStorageAccountURL` rejects it first. Without that
validator the SDK base64-decodes the account key instead and throws
`std::runtime_error`, which surfaces as `STD_EXCEPTION` (Code 1001).

The helper is transplanted verbatim from master and is called from the same
two sites: the five-argument form, and a named collection carrying explicit
credentials. The three-argument form is left unvalidated, as on master.

The failures this fixes:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=122669&sha=dd96fc97dd7c07ee43e7a484c08090bae8485a01&name_0=BackportPR

Related: #117429

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
PedroTadim added a commit that referenced this pull request Sep 29, 2026
`Azure::Core::Url` has no userinfo support, so the three-argument
destination `AzureBlobStorage('http://user:pass@host:port/acct', 'cont',
'blob')` is parsed with `user` as the host, and `std::stoi` then throws a
bare `std::invalid_argument`. On a thread-pool thread a non-`DB::Exception`
reaching `tryLogCurrentException` is a logical error, so a debug or sanitizer
build calls `abortOnFailedAssertion` and the server dies.

`validatePlainStorageAccountURL` does not cover this arm: master validates
the five-argument and named-collection forms only, so the three-argument one
still reaches the SDK and relies on this guard. 26.5, 26.7, 26.8 and master
already have it; 26.3 and 26.4 are the branches without it.

It is transplanted verbatim, so the helper and the three catch sites are
byte-identical to 26.7. With it in place the userinfo arm of
`04510_s3_explicit_url_named_secret_mask` passes here as it does there.

The failures this fixes:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=122669&sha=dd96fc97dd7c07ee43e7a484c08090bae8485a01&name_0=BackportPR

Related: #117429

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
PedroTadim added a commit that referenced this pull request Sep 29, 2026
`04510_s3_explicit_url_named_secret_mask` asserts `BAD_ARGUMENTS` for
`AzureBlobStorage('DefaultEndpointsProtocol=...;AccountKey=...;', 'cont',
'blob', 'acct', 'key')`, a connection string written where the five-argument
shape requires a plain storage account URL. On master that arm never reaches
the SDK: `validatePlainStorageAccountURL` rejects it first. Without that
validator the SDK base64-decodes the account key instead and throws
`std::runtime_error`, which surfaces as `STD_EXCEPTION` (Code 1001).

`translateAzureSdkParseError` does not cover this: it catches
`std::logic_error`, and the base64 failure is a `std::runtime_error`. 26.7
already has that guard and still fails this arm, so the validator is a
separate, additional backport.

The helper is transplanted verbatim from master and is called from the same
two sites: the five-argument form, and a named collection carrying explicit
credentials. The three-argument form is left unvalidated, as on master.

The failures this fixes:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=122674&sha=f287da9ce8b0c957579b67372272c437d1f35045&name_0=BackportPR

Related: #117429

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
clickhouse-gh Bot added a commit that referenced this pull request Sep 29, 2026
Backport #117429 to 26.7: Mask secrets in SHOW CREATE DATABASE of a Backup database
PedroTadim added a commit that referenced this pull request Sep 29, 2026
Backport #117429 to 26.3: Mask secrets in SHOW CREATE DATABASE of a Backup database
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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR 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.

8 participants