Repository navigation
Authorize a restored view's external targets - #117423
Conversation
RESTORE of a table whose backup metadata is a MATERIALIZED VIEW with an
external TO target never checked any privilege on that target, so the
restored view became an arbitrary write primitive: rows inserted into the
user's own source table were written into a table they hold no INSERT
grant on. External TimeSeries targets (Samples, Tags, Metrics,
RecentSamples) live in the same create.targets list and were reachable
the same way.
The attacker does not need a backup produced by anyone else.
getRequiredAccessToBackup authorizes AccessType::BACKUP on the original
element names only, while the per-element AS name drives makeRenamingMap
and DDLRenamingVisitor rewrites create.targets with it. So
"BACKUP TABLE own.mv, TABLE own.dummy AS victim.ledger" forges a backup
whose view points at victim.ledger using no privilege on it at all.
Root cause: the restore path voids the create query's own authorization
and re-derives it by hand, and the hand-written version never read
create.targets. createTableRestoredFromBackup runs InterpreterCreateQuery
with setInternal(true), so getRequiredAccess() returns {} and the
SELECT | INSERT requirement it normally imposes on create.targets never
fires. checkAccessForObjectsFoundInBackup() is the only gate that still
runs as the real user, before anything is created, for all three
createTableRestoredFromBackup implementations at once, and it is also
what the ON CLUSTER CHECK_ACCESS_ONLY pre-flight evaluates.
The fix mirrors InterpreterCreateQuery::getRequiredAccess() verbatim at
that gate. The if (target_id) guard is load-bearing: ASTViewTargets::
setTableID appends a target only for a non-empty StorageID, so an
inner-table view carries its target as an inner engine plus inner_uuid
and is correctly skipped. The loop sits inside the existing
create_table != kMustExist block because under kMustExist createTable()
returns before doing anything and the backup's create query is only
compared, never executed, so requiring the target there would be a
spurious denial.
This tightens grants: restoring a view with an explicit external target
now needs SELECT, INSERT on that target. That is exactly what creating
the same view by hand already requires.
Same threat model and remedy as the existing local-target check on
RESTORE of a Remote engine in StorageDistributed.
Co-Authored-By: Claude Opus 5 <[email protected]>
Review round 1 found the previous commit incomplete inside its own contract. checkAccessForObjectsFoundInBackup() short-circuits the temporary-database branch with `continue` before the create query is bound, so the target loop never ran for a restored `TEMPORARY TABLE`. InterpreterCreateQuery's getRequiredAccess has no such asymmetry: its own target loop sits after its temporary/non-temporary chain, so a direct `CREATE TEMPORARY TABLE t ENGINE = TimeSeries METRICS <external>` does require `SELECT, INSERT` on that target while the restore did not. Since this change claims to cover a TimeSeries table with external targets, that gap was in scope rather than a pre-existing residual. Bind the create query and run the loop once, above the temporary branch, so both shapes share a single loop and cannot drift apart again. The loop is gone from its old position; there is no second copy. Requiring the target is still gated on `create_table != kMustExist`, because under kMustExist the backup's create query is only compared, never executed, so demanding the target there would be a spurious denial. The hoisted dereference is safe: table_infos has one insertion point, BackupMetadataFinder.cpp:312, whose next line assigns create_table_query unconditionally from a parseQuery that throws rather than returning null. Two test arms were added, each with its own proof that it fails on a binary lacking precisely the change it covers. The first pins the SELECT half of the requirement separately. The forged target held neither privilege and the diagnostic arm grepped only for `INSERT ON <db>.dst`, so weakening the requirement to `AccessType::INSERT` alone left the reference byte-identical. Granting INSERT and re-running now asserts the denial still fires and names the SELECT it is missing, then grants SELECT and asserts the same restore succeeds. The trailing REVOKE and DROP keep the later positive arms meaning what they meant. The second is the regression test for the hoist: a user granted only inside their own database creates a temporary TimeSeries table, backs it up while renaming its metrics target onto a table they cannot write, and the restore must be denied naming that target. It needs `structure_only = 1`, because backing up a temporary TimeSeries table otherwise fails on its own inner samples table, which is an unrelated pre-existing limitation. Comments in both files stay within 140 characters, measured rather than estimated: the source comment is 124 including its indentation. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex) across two passes, plus my own cold
Severity: ❌ blocker / Also checked and found clean, so a reviewer does not have to re-derive it. |
|
Workflow [PR], commit [9106339] Summary: ✅
AI ReviewSummaryThe PR requires Missing context / blind spots
FindingsThe following findings predate this patch. The author explicitly defers them to follow-up work; none is being posted again inline. ❌ Blockers
Final VerdictStatus: ❌ Block on the preserved, unresolved privilege bypasses. The new external-target check itself has no additional finding. Minimum remediation is to enforce the database-engine and temporary-object creation privileges with focused negative tests. The skipped-object grant concern remains a separate follow-up; no existing discussion was duplicated or reopened. |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20260831-210700 |
|
cc @SmitaRKulkarni @vitlibar, could you review this? The restored |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 12 s compile time in total, 7 of them have a recent master baseline. |
Review feedback found the previous commit over-denying inside its own contract. Under restore_replace_external_engines_to_null, createAndCheckDatabaseImpl skips a database whose engine is external and createAndCheckTableImpl then returns early for every table under it, so nothing there is created. The target loop in checkAccessForObjectsFoundInBackup still ran for those tables, and that check runs first: it is called at the top of run(), long before any database is classified. So a restore that creates nothing could be refused for a grant it would never use. Measured on three binaries, each asserted by build id, restoring a backup whose view sits under a Filesystem-engine database and points at a table the user cannot write. Before this change the restore is denied naming SELECT, INSERT on that target; granting exactly that makes it succeed and still creates no database, no table and no row, which is what makes the denial spurious rather than merely strict. Before the parent commits the same restore was allowed, so the denial came from this change and is not pre-existing. Gate the target requirement on the same predicate the skip uses. Both sites now call one helper, so they cannot answer differently: a database absent from database_infos is never skipped, matching createAndCheckDatabases, which derives its work list from that map. Nothing erases from it, so reading it unconditionally cannot throw where the old code did not. The requirement is unchanged wherever the table is really created. With the setting off the same backup is restored and does demand the target, and a view under an ordinary database is still refused with the setting on, so the setting is not a way to skip the check. Both are asserted. The new arm reddens in both directions: against the parent commit only the skipped-database line moves, allowed to denied, with the other 25 lines byte-identical; against master before this work the two lines that pin the requirement move instead. Co-Authored-By: Claude Opus 5 <[email protected]>
CI finish ledger - 6e5a51fEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
No failure on this head is caused by this PR: the two Bugfix validation arms never executed a Session id: cron:our-pr-ci-monitor:20260901-080000 |
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
CI finish ledger -
|
| Check / test | Reason | Owner / fixing PR |
|---|---|---|
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / Container memory budget exceeded (/docker) |
the shard's nested containers breach the /docker cgroup leaf, the kernel OOM-kills processes inside it and the job errors with no test attributed |
#117412 (external, merged 2026-09-01T11:31:33Z) |
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / test_polymorphic_parts/test.py::test_polymorphic_parts_index |
node1.query(...) fails Code: 209. DB::NetException: Timeout: connect timed out: 172.16.1.17:9000 because the server it talks to was one of the processes the kernel killed inside that leaf |
#117412 (external, merged 2026-09-01T11:31:33Z) |
Finish Workflow / Post Hooks |
both Bugfix validation (functional tests, *) jobs are DROPPED due to previous failure [Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6)], so no arch reported OK or XFAIL and new_tests_check.py reds the post hook |
#117412 (external, merged 2026-09-01T11:31:33Z) |
The /docker breach is a job-level condition, not a test result. I measured #117412 ABSENT from the tree that ran, from the job's own environment rather than from git ancestry: this job was launched with CI_DIND_INIT_RESERVE=17179869184 (the 16 GiB share #117412 replaces), and so were all ten failing legs I read this tick. The probe discriminates, with a positive control: two shards launched at 14:53Z and 14:59Z carry CI_DIND_INIT_RESERVE=8589934592 (the flat 8 GiB reserve #117412 introduces) and both passed. So this is rule 3c and not rule 3d, and #117411 is not a co-owner: it was closed unmerged at 11:11:48Z in favour of #117412, whose own diff comment states the causal link.
The test_polymorphic_parts_index row is a passenger of that same kill, and I tested that rather than assuming it. This job's own dmesg-follow.log records 5 oom-killer invocations with constraint=CONSTRAINT_MEMCG and clickhouse among the victims 3 times. Across 30 days, all 5 jobs carrying this leaf's client-failure signature also carry the /docker breach and none fires without it. The 3 remaining hits of the same leaf NAME are a different signature entirely (start_cluster / cluster.shutdown() / Crash in instance 'node5') and belong to the pull request that produces them.
An earlier head of this PR, 6e5a51fc3db0, failed the post hook through the other route, the Could not find master builds in S3 abort that #117433 (mine, open) fixes. That route will reappear once the breach stops dropping those jobs, which is why a master merge alone will not settle this head.
I have not merged master to pick those fixes up yet. It would not clear Mergeable Check on this head, because the Bugfix validation abort behind the dropped jobs is fixed only by a PR that is still open, so a merge now would cost a full CI cycle and leave the head red on the same count. One master merge picks everything up once the remaining fixes land.
Mergeable Check reports Failed: 2, Dropped: 102 at this head, which counts only the jobs it gates on. The table above is the complete non-OK, non-SKIPPED node set of the head's praktika report, so it also covers the rows Mergeable Check does not gate.
CH Inc sync was pending at this head.
Session id: cron:our-pr-ci-monitor:20260901-163000
|
@jkartseva maybe you can review this |
Picks up three merged fixes that post-date this branch's previous master merge and that its CI run was red on: ClickHouse#117580 Bugfix validation master-build lookup for the new S3 prefix ClickHouse#117459 date-dependent toYYYYMM documentation example ClickHouse#117412 integration tests' nested-container memory budget Co-Authored-By: Claude Opus 5 <[email protected]>
A `Disk(...)` backup location is now authorized against the DISK source (ClickHouse#117406): the Disk backup engine's SourceAccessFn returns a real SourceAccessTarget, so writing a backup demands `WRITE ON DISK` and reading one demands `READ ON DISK`. This test's user holds neither, so after merging master every statement it issues as that user stopped at the location check before reaching the materialized-view target logic under test: six `allowed` lines flipped to `denied`, both assertions that the denial names the target went 1 -> 0, and the TimeSeries arm reported `forge failed`. Grant both halves to the test user, the spelling ClickHouse#117406 used for its own tests. The DISK source says nothing about a view target, so the oracle is unchanged: with the grants in place the forged restore is denied with `SELECT, INSERT ON <db>.dst` again, and with the RestorerFromBackup change reverted the same test file still fails on six assertion lines.
| continue; | ||
| } | ||
|
|
||
| const ASTCreateQuery & create = table_info.create_table_query->as<const ASTCreateQuery &>(); |
There was a problem hiding this comment.
RESTORE TEMPORARY TABLE can still carry a backed-up CREATE TEMPORARY VIEW definition through this branch: the backup grammar uses the TEMPORARY TABLE element for session-scoped objects, BackupEntriesCollector maps that element to DatabaseCatalog::TEMPORARY_DATABASE, and it accepts any create->isTemporary() object it finds there. But this preflight always asks for CREATE_TEMPORARY_TABLE, while direct CREATE TEMPORARY VIEW requires CREATE_TEMPORARY_VIEW (InterpreterCreateQuery::getRequiredAccess).
Because the restore later executes the CREATE internally, there is no second privilege check to correct that mismatch. A user with CREATE_TEMPORARY_TABLE but no temporary-view grant can still restore a temporary view, while a user who only has the view grant is denied. Can we mirror the create.isView() split here and add a focused BACKUP/RESTORE TEMPORARY TABLE case for a temporary view?
CI finish ledger -
|
| Check / test | Reason | Owner / fixing PR |
|---|---|---|
Stateless tests (arm_binary, parallel) / 05098_client_psql_describe_table |
flaky expect stall: the script exits 1 through its own expect_after ... timeout arm, and the job's randomized-settings diagnosis then re-ran it 71 times with the same settings for 0 failures. The test is one day old (added in 2a7ccd72b648) and this is its only failure in 30 days of CIDB, none of them on master |
a fix task is created (investigating at full effort - fixing-PR link to follow here) |
174 check-runs on this head: 153 success, 18 skipped, 3 failure. Mergeable Check and PR are aggregate statuses rolling up that same single leaf, not separate failures. CH Inc sync is success here, so nothing is exempt.
Not PR-caused: this diff is src/Backups/RestorerFromBackup.cpp plus 05055_restore_mv_target_access.{sh,reference}, which is neither the interactive client, the psql-protocol \d path, nor the expect harness.
Every row of my previous ledger (e52b2c3845a8) is clear on this head without a master merge: both Bugfix validation (functional tests, *) legs, Bugfix validation (unit tests), Docs examples, all six Integration tests (amd_asan_ubsan, db disk, old analyzer, *) shards and Finish Workflow are success.
Session id: cron:our-pr-ci-monitor:20260906-030103
|
Fixing PR for the Root cause: |
`match_max 100000` on line 23 runs before the `spawn` on line 41, and without `-d` it applies to the *current* spawn id, of which there is none at that point, so the client ran with expect's 2000-byte default buffer, i.e. 6001 chars of capacity. The bare `\l` expands to `SHOW DATABASES`. On a shared `arm_binary, parallel` runner that listed 69 databases with every row padded to 219 chars, because a concurrent test held a ~200-char database name: a 15,754-char burst, 2.6x the window. The test failed by timeout there, on https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117423&sha=8f6c4316969230ee19799531b03487484cacf0b6&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29 (ClickHouse#117423), where the `.expect.debuglog` shows expect forgetting output four times while matching the prompt on line 94, ending with the buffer pinned at 6001 and a final read of 13 chars. Use `match_max -d 100000` so the value the test already asks for is inherited by the `spawn`. Verified locally: `[match_max]` after a `spawn` reports 2000 without `-d` and 100000 with it. With 75 databases and one 206-char name making the listing 17,679 chars, the debuglogs of 50 runs hold 304 full-buffer discards without this change and 0 with it, and the widest buffer expect examines rises from the 6001-char ceiling to the whole listing; reverting only the `-d` brings the discards back. 50/50 runs pass with and without that fixture. The 60 s timeout itself is rate-dependent and did not reproduce locally, so what is shown here is that the assertion ran inside a discard regime the test's declared buffer would never have entered. Of the 62 `.expect` tests under `tests/queries/0_stateless`, the other 60 set `match_max` the same ineffective way; as in ClickHouse#112160 this commit only changes the test that is failing, since a larger buffer also makes expect retain older output, which could affect negative `expect` patterns in the other tests. Co-Authored-By: Claude Opus 5 <[email protected]>
|
@groeneai merge master. |
…et-access # Conflicts: # src/Backups/RestorerFromBackup.cpp
|
Merged master and pushed The single conflict was in |
CI finish ledger - 67fb906Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
Session id: cron:our-pr-ci-monitor:20260915-213215 |
|
@groeneai refresh the PR. |
TimeSeries engine version 6 renamed the inner metric families column from `metric_family_name` to `metric_family` (a78d687, after the previous master merge on this branch), so `CREATE TEMPORARY TABLE ts ENGINE = TimeSeries METRICS <t>` now rejects the test's fixture with THERE_IS_NO_COLUMN. That aborted the forge step of the temporary-TimeSeries arm, and the RESTORE it sets up then failed with BACKUP_NOT_FOUND instead of the access denial the arm asserts. Only the fixture's column name changes. The arm, the reference and the fix itself are untouched: on the merged tree the test is 5/5 green, and 3/3 red with the `RestorerFromBackup.cpp` change reverted, where the forged restore is allowed again and the denial no longer names the target.
|
Refreshed: merged master ( The refresh did catch one thing. Re-measured on the merged head: the test is green with the fix (40/40 on valid randomized draws) and red with the CI is running on the new head; I will post the finish ledger here when it completes. |
CI finish ledger - 459e4e7Every 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
Session id: cron:our-pr-ci-monitor:20260924-040113 |
…et-access # Conflicts: # src/Backups/RestorerFromBackup.cpp
…on 9 Master's 681c2e1 made version 10 the default for new `TimeSeries` tables, and a table of version 10 can have inner targets only, so the `CREATE` in this arm now fails with `INCORRECT_QUERY` and the arm checked nothing. Tables of version 9 and earlier still accept external targets and are still restored with them, so the arm pins `version = 9`, the same way master pinned its own tests of external targets. Version 9 keeps the tags in a `ReplacingMergeTree` inner table, which needs its engine grant under `table_engines_require_grant`; that grant confers no `SELECT` or `INSERT`, so the denial still comes from the forged target. Also quote the SQL names in the test's shell comments. Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - 399030dEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
CIDB has no other Session id: cron:our-pr-ci-monitor:20261021-180006 |
|
Taking a closer look at the bot comments before merging. |
…et-access Resolves the conflict in checkAccessForObjectsFoundInBackup with ClickHouse#127180, which also binds create above the temporary branch: keep master's is_temporary and export-access check, then authorize the view targets as before. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@jkartseva let's merge? |
Related: #115351
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a privilege check that
RESTOREskipped: restoring aMATERIALIZED VIEWwith an externalTOtarget, or aTimeSeriestable with external targets, needed no privilege on those targets, so the restored view could write into a table the user has noINSERTgrant on. Restoring one now requiresSELECT, INSERTon each external target, the same asCREATE MATERIALIZED VIEW ... TO .... Targets of objects the restore skips are exempt, since they are never created.Description
RESTOREof backup metadata that isMATERIALIZED VIEW ... TO other_db.other_tablechecked no privilege on theTOtarget, so the restored view was an arbitrary write primitive: rows inserted into the user's own source table landed in a table they hold noINSERTgrant on. ExternalTimeSeriestargets sit in the same list, reached the same way.The backup need not be anyone else's.
BACKUPauthorizes only the original element names, while the per-elementASname drives the renamingDDLRenamingVisitorapplies tocreate.targets, soBACKUP TABLE own.mv, TABLE own.dummy AS victim.ledgerforges it from the user's own objects alone.Root cause:
createTableRestoredFromBackuprunsInterpreterCreateQuerywithsetInternal(true), sogetRequiredAccessreturns nothing and theSELECT | INSERTrequirement oncreate.targetsnever fires.checkAccessForObjectsFoundInBackupis the only gate left running as the real user, and did not read them. This mirrorsgetRequiredAccessthere, which also covers theON CLUSTERCHECK_ACCESS_ONLYpre-flight. Theif (target_id)guard keeps inner-table views working, and the loop sits above the temporary-table branch so restored temporary tables are covered.Targets are not required where nothing is created: under
restore_replace_external_engines_to_nullan external-engine database and every table under it are skipped. That gate and the skip share one predicate, so they cannot disagree.This tightens grants, deliberately. Found by an internal security review; no public issue.
Left for later PRs: a restored database engine is not checked against
TABLE ENGINE, a restored temporary object asks forCREATE_TEMPORARY_TABLEwhereCREATErequiresCREATE_ARBITRARY_TEMPORARY_TABLEorCREATE_TEMPORARY_VIEW, and a skipped database still demands create grants it never uses.05055_restore_mv_target_accesscovers the denial, a temporaryTimeSeriestarget, the skipped-database exemption, that the setting does not lift the check elsewhere, that nothing is created, the granted-target and inner-table passes, and aCREATE-path control.Workflow [PR]
Sync PR [sync-upstream/pr/117423]
Version info
26.11.1.1584-master(included in26.11and later)