Repository navigation
Keep a Backup database loadable after ALTER DATABASE ... MODIFY COMMENT - #118674
Conversation
`DatabaseBackup::getCreateDatabaseQueryImpl` regenerated the definition with the
backup locator quoted into a string literal
(`Backup('db', 'Disk(\'backups\', \'x\')')`). `ALTER DATABASE ... MODIFY
COMMENT` persists exactly that AST into `metadata/<db>.sql`, and the load path
parses the second argument with `BackupInfo::fromAST`, which accepts only a
function - so the next start aborted with `BAD_ARGUMENTS` while loading
metadata, and the server stayed down until the file was hand-edited.
Two changes, so both new and already-written metadata work:
- the locator is emitted as the function it is (`BackupInfo::toString` produces
that form), so the definition round-trips;
- a locator held in a string literal is parsed with `BackupInfo::fromString`, so
a database whose metadata an older server rewrote still loads.
`parseAndAuthorizeLocator` treats such a literal as a locator too, so a
`CREATE DATABASE` that uses it is authorized against the backup source like
the function form.
`03279_database_backup_database_disk_engine` pinned the old
`SHOW CREATE DATABASE` output and now expects the function form.
Closes: #118349
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Workflow [PR], commit [b743dd5] Summary: ✅
AI ReviewSummaryThis PR fixes Findings❌ Blockers
Final VerdictRequest changes: the masking gap above still leaves credential-bearing LLVM Coverage ReportMeasured on commit b743dd5.
Changed lines: Changed C/C++ lines covered: 39/39 (100.00%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units8 translation units recompiled, 12 s compile time in total, 8 of them have a recent master baseline. |
The compatibility path was broader than the contract it has to satisfy: any statement could pass the locator as a string literal, and `FunctionSecretArgumentsFinder` redacts only the nested-function form, so a quoted `S3(...)` locator would carry its credentials verbatim into `query_log`, `SHOW PROCESSLIST` and the distributed DDL payload. The string form is accepted only when the definition comes from existing metadata - the load path that a server rewritten by an older version depends on. A statement a user writes must spell the locator as the function it is, and is refused with `Expected function` otherwise. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Addressed - the security point is right. The quoted locator is now accepted only when the definition comes from existing metadata ( The test asserts the refusal; the metadata-load path itself is what |
`test_restore_on_cluster_of_a_real_backup_engine_manifest_is_unchanged` pinned the old serialization: it asserted that a real `BACKUP DATABASE` manifest carries the inner locator as a string literal, and that restoring it fails with `BAD_ARGUMENTS` while creating the database. Both are gone now that the definition spells the locator as the function it is. The case keeps its point - a manifest that is *not* rewritten by the test - and asserts what the corrected form makes possible: the embedded locator round-trips, so it is authorized like a rewritten one, and the restore recreates a usable database. The outer locator becomes a `Disk` backup, which needs `READ ON DISK`, so a denial naming `READ ON FILE` can only come from the inner one; `configs/backups.xml` gains the disk that makes that possible. Verified against a local build with and without the fix: the manifest assertion is what fails without it.
| def test_restore_on_cluster_of_a_real_backup_engine_manifest_authorizes_the_inner_locator( | ||
| started_cluster, | ||
| ): | ||
| # The manifest is NOT crafted here, which is the point: `BACKUP DATABASE` writes the inner locator |
There was a problem hiding this comment.
This only proves manifests written after this patch. The persisted carrier existing users already have is the old CREATE DATABASE ... ENGINE = Backup('db', 'File(...)') form, and that still does not restore.
RESTORE DATABASE replays the backed-up definition through InterpreterCreateQuery with internal = true (src/Backups/RestorerFromBackup.cpp:601-603), but DatabaseBackup::create_fn still treats only FORCE_ATTACH / attach_short_syntax as existing metadata (src/Databases/DatabaseBackup.cpp:558-563). So an old manifest still throws Expected function when the target database is absent, and when the target already exists checkDatabase still rejects the restore because getCreateDatabaseQueryImpl now emits the function form while BackupUtils::compareRestoredDatabaseDef compares the old string-literal text verbatim (src/Backups/RestorerFromBackup.cpp:640-641, src/Backups/BackupUtils.cpp:136-138).
Please keep restore compatibility for the pre-fix manifest as well, and add a regression that restores a manifest containing Backup('db', 'File(...)').
There was a problem hiding this comment.
🕵 The restore path is intentionally left refusing the quoted carrier. A RESTORE replays a manifest the restoring user controls, and a locator held in a string literal is the one form FunctionSecretArgumentsFinder cannot redact, so accepting it there would carry credentials verbatim into query_log, SHOW PROCESSLIST and the distributed DDL payload - the exposure the earlier round of this PR closed. Startup replay is different: that metadata file was written by this server after the definition had already been validated and logged in redacted form.
The consequence for backups an older server took of an ENGINE = Backup database - Expected function when the target is absent, CANNOT_RESTORE_DATABASE when it exists, with allow_different_database_def = 1 as the way out of the latter - is spelled out in the changelog entry as a backward incompatibility. @jkartseva raised the same point in review and accepted it as unlikely in practice, asking for exactly that changelog note. The pre-fix manifest is therefore not made restorable, and no regression is added for it, on purpose.
jkartseva
left a comment
There was a problem hiding this comment.
In its present form the fix is not backward compatible with backups taken before it that contain a database with ENGINE = Backup. Restoring one onto an existing database now fails with CANNOT_RESTORE_DATABASE, because the live definition is serialized in the function form while the manifest holds the old quoted one. It previously succeeded.
$ mkdir -p tmp/min/data tmp/min/backups
cat > tmp/min/config.xml <<'EOF'
<clickhouse>
<backups>
<allowed_path>/home/ubuntu/src/ClickHouse/tmp/min/backups</allowed_path>
</backups>
</clickhouse>
EOF
Phase A — pre-fix server (26.8 / master)
CREATE DATABASE d;
BACKUP DATABASE d TO File('inner');
CREATE DATABASE dbreal ENGINE = Backup('d', File('inner'));
BACKUP DATABASE dbreal TO File('outer');
RESTORE DATABASE dbreal FROM File('outer'); -- succeeds
Verified output:
restore on the pre-fix server: OK
$ cat tmp/min/backups/outer/metadata/dbreal.sql
CREATE DATABASE dbreal ENGINE = Backup('d', 'File(\'inner\')') <- quoted, frozen in the backup
$ cat tmp/min/data/metadata/dbreal.sql
ATTACH DATABASE dbreal
ENGINE = Backup('d', File('inner')) <- function form
Phase B — same directory, server with #118674
RESTORE DATABASE dbreal FROM File('outer'); -- expect Code: 607 CANNOT_RESTORE_DATABASE
jkartseva
left a comment
There was a problem hiding this comment.
The backward incompatibility use case described above is unlikely, so accepting. Could you please describe it to the changelog?
…ify-comment-118349
…ata at server start `loadMetadata` replays the stored full `ATTACH DATABASE ... ENGINE = Backup(...)` statement as an internal query in plain `ATTACH` mode with `attach_short_syntax` false, so neither `isLoadingFromExistingMetadata` nor the short-syntax check recognised it as existing metadata, and a definition an older server rewrote with the locator quoted into a string literal still failed with `Expected function` on the very startup path from the issue. `DatabaseBackup` now treats an internal query in `ATTACH` mode or above as a replay of validated metadata, the same way `DatabaseDataLake` does. The integration test `test_database_backup_metadata_with_quoted_locator_loads_on_restart` rewrites `metadata/<db>.sql` to the form an older server left after `ALTER DATABASE ... MODIFY COMMENT`, restarts the server and checks that the database loads with its tables and comment, that the regenerated definition holds the locator as a function, and that a comment change on this server survives a restart too. Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
🕵 @jkartseva thank you. The changelog entry now describes the backward incompatibility: a backup taken by an older server of an Also pushed 2e54f5b: the bot's finding about the startup replay was right. |
…`, not `internal`
`DatabaseBackup` accepted a backup locator held in a string literal - and skipped
`checkSourceAccess` - for every internal query in `ATTACH` mode or above, taking
that pair as the server's replay of its own metadata. `internal` is broader than
that: wrappers such as `PARALLEL WITH` run user statements as internal queries, so
`PARALLEL WITH ATTACH DATABASE db ENGINE = Backup('src', 'S3(...)')` got a quoted
locator accepted in the form `FunctionSecretArgumentsFinder` cannot redact and
bypassed the `READ` source grant.
`DatabaseFactory::Arguments::is_metadata_replay` exists for exactly this
distinction and `loadMetadata` sets it on the database replay path, so the
compatibility path is now gated on it, as `DatabaseFilesystem` already does.
Test `05218_database_backup_quoted_locator_parallel_with` checks that the quoted
locator is refused through `PARALLEL WITH` for both `ATTACH DATABASE` and
`CREATE DATABASE`, while the function form still works through the same wrapper.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
| /// statements as internal ones, and a user's `ATTACH DATABASE ... ENGINE = Backup(...)` must neither | ||
| /// skip the source authorization nor get its locator accepted in the form the secret masker cannot redact. | ||
| const bool has_real_user = args.context->getAccess()->getUserID().has_value(); | ||
| const bool is_internal_metadata_replay = args.is_metadata_replay && args.mode >= LoadingStrictnessLevel::ATTACH; |
There was a problem hiding this comment.
args.is_metadata_replay is the right discriminator here, but the same exemption is still keyed off args.internal && args.mode >= LoadingStrictnessLevel::ATTACH in src/Databases/PostgreSQL/DatabasePostgreSQL.cpp:715 and src/Databases/PostgreSQL/DatabaseMaterializedPostgreSQL.cpp:786.
That leaves the external-host policy bypass open through those siblings. InterpreterParallelWithQuery runs each subquery with QueryFlags{ .internal = true } (src/Interpreters/InterpreterParallelWithQuery.cpp:125), and RESTORE DATABASE executes the stored ATTACH DATABASE ... ENGINE = PostgreSQL(...) as an internal query (src/Backups/RestorerFromBackup.cpp:642), so both paths still skip remote_url_allow_hosts and can attach a PostgreSQL-backed database to a host the server would normally forbid. Since this PR adds DatabaseFactory::Arguments::is_metadata_replay exactly to separate startup replay from user-controlled internal execution, can we switch the PostgreSQL-family checks to that flag in the same change?
There was a problem hiding this comment.
🕵 Agreed that the PostgreSQL-family gate has the same PARALLEL WITH hole, with one correction: RESTORE DATABASE is not affected, because it replays a CREATE in CREATE mode (getLoadingStrictnessLevel(create.attach = false, ...)), so args.mode >= ATTACH is false there and the host filter already runs.
Those gates are pre-existing master code in three unrelated engines (DatabasePostgreSQL, DatabaseMaterializedPostgreSQL, and also DatabaseDataLake, which carries the same pair), untouched by this PR, and this PR is an approved bug fix for the Backup engine. Rather than widen it, the switch to is_metadata_replay for all three, with a PARALLEL WITH ATTACH DATABASE ... ENGINE = PostgreSQL(...) / MaterializedPostgreSQL(...) regression in test_postgresql_remote_host_filter, is in #120280.
…e next check Whether the `CREATE DATABASE` that runs beside a throwing statement of a `PARALLEL WITH` is committed or rolled back depends on how the two statements were scheduled: with `max_threads = 1` it commits, so the second check reported `Database already exists` instead of the quoted-locator refusal it is testing, and only one `refused` line was printed. Drop the sibling database between the checks so each starts from the same state.
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
`test_database_backup_metadata_with_quoted_locator_loads_on_restart` rewrites `metadata/<db>.sql` in place, but with a remote database disk that metadata is an object on the disk, so the file the test writes is ignored: the server loaded the regenerated definition and the database came up without the comment. Run that test on an instance which keeps the local database disk. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Address review: a locator held in a string literal is text `FunctionSecretArgumentsFinder` cannot parse, and it can carry an access key or a presigned URL. The engine accepts that form only while replaying its own metadata, but a statement carrying it is formatted before the engine rejects it - by `PARALLEL WITH`, by the distributed DDL queue, and by `query_log` - so the credentials went into those surfaces verbatim. Hide such a locator whole. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🕵 On the remaining Related: #117429 |
`SHOW CREATE DATABASE` of a `Backup` database renders the locator as the function it is since ClickHouse#118674, so the pre-existing nested-`S3` rule redacts it. What is left are the shapes that rule does not model, and the messages that reject a locator: - A `Backup` engine with an arity other than two, or with a first argument that is no literal, hides every argument: a locator can be written in either position, and the statement is formatted for logging before validation rejects it. - A locator whose engine is not `S3` keeps its engine name and argument count and hides every argument, unless the engine reads exactly the literal arguments it accepts, which name a destination and no credential (`File`, `Disk`, `Memory`, `Null`). - An `AzureBlobStorage` backup destination reads a different signature than the table engine of the same name: a shared access signature beside a two-argument url, an `account_key` in the longer forms, named-collection overrides. It gets its own rule, and both rules now fail closed on an argument that neither `maskAzureConnectionString` nor the plain-account-url check can read, instead of leaving it visible. - `BackupInfo::fromAST`, `checkAndGetLiteralArgument` for `database_name`, `StorageS3Configuration::collectCredentials` and the two duplicate-definition checks of `BackupMetadataFinder` formatted the argument they reject into their messages, which reach the error log and `query_log.exception`. A nested map such as `headers(..)` is masked only by its enclosing formatter, so one formatted on its own prints its values: none of these echoes the argument now. Rebased on ClickHouse#118674 and reduced to the above. The definition rendering, the acceptance of a locator held in a string literal on the metadata-replay paths and the preflight refusal of one elsewhere are that PR's, and its own tests cover them.
Backport #118674 to 26.9: Keep a `Backup` database loadable after `ALTER DATABASE ... MODIFY COMMENT`
Backport #118674 to 26.8: Keep a `Backup` database loadable after `ALTER DATABASE ... MODIFY COMMENT`
Cherry pick #118674 to 26.3: Keep a `Backup` database loadable after `ALTER DATABASE ... MODIFY COMMENT`
Cherry pick #118674 to 26.7: Keep a `Backup` database loadable after `ALTER DATABASE ... MODIFY COMMENT`
…TER DATABASE ... MODIFY COMMENT`
…TER DATABASE ... MODIFY COMMENT`
Backport #118674 to 26.3: Keep a `Backup` database loadable after `ALTER DATABASE ... MODIFY COMMENT`
Backport #118674 to 26.7: Keep a `Backup` database loadable after `ALTER DATABASE ... MODIFY COMMENT`
… after `ALTER DATABASE ... MODIFY COMMENT`
… after `ALTER DATABASE ... MODIFY COMMENT`
…reSQL` and `DataLakeCatalog` on the loader flag The three database engines skipped `remote_url_allow_hosts` (and, for `MaterializedPostgreSQL`, the single-address validation; for `DataLakeCatalog`, the tolerant catalog load) when `args.internal && args.mode >= ATTACH`, taking that pair as the signature of the server replaying its own stored metadata. `internal` does not imply a replay: `InterpreterParallelWithQuery` runs every statement of a user's `PARALLEL WITH` as an internal query, and the full `ATTACH DATABASE ... ENGINE = ...` form runs in `ATTACH` mode, so a user could attach a `PostgreSQL`-backed database to a host the policy forbids by wrapping the statement in `PARALLEL WITH`. `DatabaseFactory::Arguments::is_metadata_replay` is set only by `loadMetadata`, which is the discriminator `DatabaseFilesystem` and `DatabaseBackup` already use. Switch the three engines to it. Startup replay is unchanged (`loadDatabase` sets both flags), and `RESTORE DATABASE` was never covered by the exemption because it replays a `CREATE` in `CREATE` mode. The integration test now wraps a user `ATTACH DATABASE` over the blocked host in `PARALLEL WITH` for both PostgreSQL engines and asserts `UNACCEPTABLE_URL`. Found by the automated review of ClickHouse#118674. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Both instances loaded `configs/backups.xml`, so they claimed the same `cas_server_root_id` on the same rustfs prefix; whichever server started second refused to start ("CAS server-root 'itest-database-backup' was claimed by a different server during our claim (foreign owner)") and every test on `instance` timed out waiting for it (Integration tests amd_asan_ubsan 6/8, 26 failures, red on PR 2579 as well). The second instance came with the backport of ClickHouse#118674. `instance_local_metadata` now loads `backups_local_metadata.xml`: the same disks with a distinct root id and prefix.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Mikhail Filimonov <[email protected]>
Closes: #118349
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
ALTER DATABASE ... MODIFY COMMENTon a database withENGINE = Backupno longer writes a definition the server cannot read back, which made it refuse to start; metadata already written in that form now loads too. Backward incompatibility: a backup taken by an older server of a database withENGINE = Backupstores the locator quoted into a string literal, and such a definition is no longer accepted from aRESTORE. Restoring it onto a missing database fails withExpected function, and onto an existing one withCANNOT_RESTORE_DATABASEbecause the live definition now spells the locator as a function; useSETTINGS allow_different_database_def = 1for the latter, or recreate the database with the function form.Description
DatabaseBackup::getCreateDatabaseQueryImplregenerated the definition with the backup locator quoted into a string literal (Backup('db', 'Disk(\'backups\', \'x\')')).ALTER DATABASE ... MODIFY COMMENTpersists exactly that AST intometadata/<db>.sql, and the load path parses the second argument withBackupInfo::fromAST, which accepts only a function - so the next start aborted withBAD_ARGUMENTSwhile loading metadata, and the server stayed down until the file was hand-edited.Two changes, so that both new and already-written metadata work:
BackupInfo::toStringalready produces that form), so the definition round-trips;BackupInfo::fromString, so a database whose metadata an older server rewrote still loads.parseAndAuthorizeLocatortreats such a literal as a locator too, soCREATE DATABASEwith it is authorized against the backup source like the function form.A locator held in a string literal is accepted only while loading metadata this server already validated: the short
ATTACH DATABASE, aforce_restore_dataload, and the internal replay of the stored fullATTACH DATABASE ... ENGINE = Backup(...)statement at server start. A definition arriving in a user statement or in aRESTOREmust spell the locator as the function it is, because that is the formFunctionSecretArgumentsFinderredacts before the text reachesquery_log,SHOW PROCESSLISTor the distributed DDL payload. This makes backups of such databases taken by an older server incompatible withRESTORE, as described in the changelog entry.A locator that is not a function is also refused without echoing it, and
FunctionSecretArgumentsFindernow hides it: a statement carrying one is formatted before the engine rejects it - byPARALLEL WITH, by the distributed DDL queue, byquery_log- so its text, which can hold an access key or a presigned URL and which the masker cannot parse, used to reach those surfaces verbatim.The new test covers the comment change followed by
DETACH/ATTACH(the same parsing path as a restart) and aCREATEwith a string-literal locator. The integration testtest_database_backup_metadata_with_quoted_locator_loads_on_restartrewritesmetadata/<db>.sqlto the form an older server left and restarts the server, which is the exact startup path from the issue.03279_database_backup_database_disk_enginepinned the oldSHOW CREATE DATABASEoutput and now expects the function form.Workflow [PR]
Sync PR [sync-upstream/pr/118674]
Version info
26.10.1.316-master(included in26.10and later)26.9.2.34,26.8.11.46,26.7.16.5,26.3.35.4