Skip to content

Authorize backup destinations against the SOURCES grant model - #114405

Merged
pufit merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/backup-destination-source-grants
Aug 14, 2026
Merged

pufit merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/backup-destination-source-grants

Conversation

@groeneai

@groeneai groeneai commented Aug 12, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #113073

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):

BACKUP, RESTORE and ENGINE = Backup now authorize the backup location against the user's SOURCES grants, the same way s3(), file() and azureBlobStorage() do. Previously a user holding BACKUP but not SOURCES could write a backup to, and read one from, any location the server could reach. Writing a backup now requires the WRITE direction on the destination's source (WRITE ON S3, WRITE ON AZURE, WRITE ON FILE) and reading one requires READ; Disk(...) destinations stay restricted by backups.allowed_disk only.

Description

A user with SOURCES ON *.* revoked could still name any S3, AzureBlobStorage or File location as a backup destination or restore source, so BACKUP alone was enough to exfiltrate data to an arbitrary bucket and to read back any backup the server could reach.

Each engine now declares the grant its location requires, and the check runs in BackupFactory::createBackup before any I/O. Needing no I/O itself, it also runs as a preflight at the four other points that still execute as the real user: an explicit base_backup (opened lazily, on the workers), CREATE DATABASE ... ENGINE = Backup under ON CLUSTER (which returns from executeQueryOnCluster before DatabaseFactory runs), an ENGINE = Backup definition embedded in a restored manifest, and a newly introduced Backup database definition. Worker legs run with no user, hence full access, so a check only there would enforce nothing.

Disk(...) is deliberately exempt: an allowlisted disk may be local, S3- or Azure-backed, so no single source describes it, and backups.allowed_disk already bounds it. A named collection is authorized whole-source rather than on the URL it currently resolves to, since it can be re-pointed after the check.

Validated by a stateless test and an 11-case integration suite over MinIO and Azurite. Each of the five sites was verified by reverting it alone and confirming a test reddens.

Two pre-existing gaps of the same class are not addressed here, described in a comment below: a base locator taken from a manifest rather than the setting, and the lightweight-snapshot manifest fields. I would rather take your call on scope than guess.

#113073 touches the same call site and is complementary; whichever merges second needs a trivial rebase there.

Version info

  • Merged into: 26.8.1.1384 (included in 26.8 and later)

BACKUP, RESTORE and ENGINE = Backup never authorized the backup location
against the user's SOURCES grants, unlike the matching table functions
(s3(), file(), azureBlobStorage()). A user holding BACKUP but not SOURCES
could therefore write a backup to, and read one from, any location the
server can reach.

Each backup engine now declares the SOURCES grant its location requires
through a SourceAccessFn registered with BackupFactory. The check performs
no I/O, so besides running in createBackup() before the creator opens
anything, it also serves as a preflight at each place that is the last
point still executing as the real user:

  - BackupsWorker, for an explicitly requested base_backup: a base opens
    lazily and on the workers, so on ON CLUSTER the initiator may never
    open it at all. Measured without this preflight, a RESTORE by a
    SOURCES-revoked user succeeds and returns the base backup's rows.
  - InterpreterCreateQuery::execute, because is_create_database returns
    from executeQueryOnCluster before DatabaseFactory runs.
  - RestorerFromBackup::checkAccessForObjectsFoundInBackup, for an
    ENGINE = Backup definition embedded in a restored manifest. Under
    CHECK_ACCESS_ONLY the creating host is a different one, so a local
    existence answer cannot stand in for it.
  - registerDatabaseBackup, for a newly introduced definition rather than
    one replayed from this server's own metadata.

Per-engine dispositions: S3 and AzureBlobStorage authorize a
regex-filterable URI normalized the same way ITableFunction does, and both
route UNLOCK through a reader. File requires the whole-source FILE grant,
matching file(), which has no path-filter semantics; path containment
remains the operator's backups.allowed_path. Disk is exempt because an
allowlisted disk may be local, S3- or Azure-backed, so no single Source
describes it, and backups.allowed_disk already bounds it. Memory and Null
have no external location.

A named collection is authorized whole-source rather than on the URL it
currently resolves to, since it can be re-pointed after the check. It is
still resolved, because that is where NAMED_COLLECTION is enforced.

Each of the five check sites was verified by reverting it alone and
confirming a test reddens.
A user holding BACKUP but not the matching SOURCES grant now gets
ACCESS_DENIED, so the requirement has to be discoverable. The backup
overview gains a table of the required direction per destination, the
regex-filter and named-collection behaviour, the Disk exemption and the
controlling server setting; the SOURCES grant reference no longer claims the
privilege applies only to table engines and table functions; and the Backup
database engine's own documentation states its READ requirement.
Two mistakes in the section added by the previous commit. The check does not
depend on enable_read_write_grants: that setting selects between the
READ/WRITE split and the legacy whole-source syntax, and the location is
authorized either way, so the note now describes the legacy spelling instead
of implying the check can be turned off. And an AZURE filter is matched
against the blob path inside the container, not a URL carrying the account
and container, which is the same string the azureBlobStorage table function
authorizes; verified by granting WRITE ON AZURE('backups/.*') and observing
that a backup to backups/az1 is allowed while other/az2 is denied.
The Azure case only granted whole-source privileges, so it would have passed
even if the hook always returned an empty URI: an empty URI can only be
satisfied whole-source, so the case could not distinguish a working filter
from no filter at all. It now grants a path-filtered privilege and asserts
both the matching and the non-matching destination, which also pins which
string the filter is matched against - the blob path inside the container,
the same one the azureBlobStorage table function authorizes.

Neither engine had an archive locator, so the field that captures the URI
before a trailing archive filename is stripped from it was untested. The new
S3 case grants exactly the archive path and asserts that a sibling archive in
the same directory is refused. Verified as a live oracle: authorizing the
stripped URI instead makes it fail.
@groeneai
groeneai requested a review from pufit August 12, 2026 00:46
@groeneai

Copy link
Copy Markdown
Collaborator Author

Two gaps of the same class as this PR, both pre-existing and both left alone. I would rather you decide the scope than guess.

1. A base backup locator that comes from the manifest, not the base_backup setting.

BackupImpl::readBackupMetadata fills base_backup_info from the outer backup's <base_backup> field when no override was given, and the base opens lazily. On RESTORE ... ON CLUSTER the initiator may never open it, so the first open happens on a worker whose context has no user and therefore full access. Measured on this branch: a user with SOURCES revoked, granted only READ ON S3('<allowed>/.*'), restoring an outer backup in allowed whose manifest names a base under denied, gets RESTORED and reads the base's rows.

I tried fixing it by walking the base chain on the initiator, which does close it (ACCESS_DENIED, naming READ ON S3). But it regresses 02915_lazy_loading_of_base_backups: that test pins ProfileEvents['BackupsOpenedForRead'] at r3 1 0, i.e. restoring a table that lives in the newest backup must open exactly one, and the eager walk measured r3 3 0. So a correct fix has to authorize the locator without opening it, which needs an accessor for the parsed base_backup_info, plus a decision on recursive chains and on cyclic manifests. That is its own change with its own tests. I reverted mine rather than ship the regression.

2. Lightweight snapshot manifests.

original_endpoint / original_namespace and the per-file object_key values come out of the manifest and select a second reader (BackupImpl.cpp:743-757), which is not authorized. Same shape as (1): a manifest-controlled locator. The commit and unlock paths are #if CLICKHOUSE_CLOUD (BackupsWorker.cpp:708,796), so I could not exercise it in this build and did not want to write a fix I cannot test.

Happy to do either or both, here or separately, if you want them in scope.

One more thing to overrule if you disagree: I used Bug Fix, not Critical Bug Fix (crash, data loss, RBAC), because the critical category is maintainer-requested. Say the word and I will switch it.

@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3acd172]

Summary: ⏳

job_name test_name status info comment
BuzzHouse (amd_tsan) ERROR IGNORED

AI Review

Summary

This PR wires the top-level locator checks for BACKUP, RESTORE, explicit base_backup, and ENGINE = Backup into the SOURCES grant model and adds focused stateless and integration coverage. The direct call sites look mostly consistent, but I would not approve it as a complete RBAC fix yet: two manifest-controlled restore paths still bypass the new authorization, so a crafted backup can still read from ungranted remote sources.

PR Metadata
  • Changelog category should be Critical Bug Fix (crash, data loss, RBAC), not Bug Fix, because this change is closing an RBAC bypass.
  • If the manifest-controlled gaps below stay out of scope, the Changelog entry should be narrowed so it does not read as a complete fix for every RESTORE read path. Suggested replacement: Top-level BACKUP and RESTORE destinations, explicit base_backup settings, and ENGINE = Backup locators are now authorized against the user's SOURCES grants before I/O. Disk(...) destinations continue to rely on backups.allowed_disk.
Missing context / blind spots
  • ⚠️ The public Praktika report linked on the PR currently shows only Build profile diff, so I could review the new tests statically but not verify that 04774_backup_destination_source_grants and test_backup_source_grants passed on this head.
Findings

❌ Blockers

  • [src/Backups/BackupImpl.cpp:321] [dismissed by author -- https://github.com/Authorize backup destinations against the SOURCES grant model #114405#discussion_r3764157828] The PR still leaves manifest-provided <base_backup> locators outside the new SOURCES check. BackupsWorker::checkAccessToExplicitBaseBackup only preflights the explicit base_backup setting, but BackupImpl::readBackupMetadata can still populate base_backup_info from the manifest at src/Backups/BackupImpl.cpp:642, and getBaseBackupUnlocked then opens it lazily through BackupFactory::createBackup. On RESTORE ... ON CLUSTER, that first open can still happen on an internal worker context with no user, which Context::getAccess treats as full access, so a crafted incremental backup can still read rows from an ungranted base backup.
    Suggested fix: surface the manifest-parsed base_backup_info for a no-I/O preflight before dispatch, including recursive base chains, and add a crafted-manifest regression test.
  • [src/Backups/BackupImpl.cpp:741] [dismissed by author -- https://github.com/Authorize backup destinations against the SOURCES grant model #114405#discussion_r3764157833] Lightweight snapshot restores still create a second reader from manifest-controlled original_endpoint / original_namespace plus per-file object_key, and that path never reaches BackupFactory::checkSourceAccess. A user who is allowed to read the outer backup can still restore snapshot data from an unrelated S3 or AzureBlobStorage location named only inside the manifest.
    Suggested fix: authorize the secondary reader target before constructing lightweight_snapshot_reader, with a crafted snapshot-manifest test in a build that exercises the cloud-only path.
Final Verdict

Not ready as a complete RBAC fix: the top-level locator checks are in place, but the remaining manifest-controlled reader paths still bypass the new SOURCES enforcement.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.00% 79.00% +0.00%

Changed lines: Changed C/C++ lines covered: 150/155 (96.77%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 12, 2026
@pufit pufit self-assigned this Aug 12, 2026
@pufit pufit added the can be tested Allows running workflows for external contributors label Aug 12, 2026
| `[SETTINGS ...]` | See below for complete list of settings | |
| `[ASYNC]` | Makes the operation run asynchronously (returns immediately with an ID you can monitor) |

### Required privileges for the destination {#destination-privileges}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please remove this docs update

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed, in 3acd172. I also dropped a third docs addition you did not point at: the same commit had added a READ note to the Backup database engine's own Documentation{} string in src/Databases/DatabaseBackup.cpp. It is the same docs update in a third file, so it went with these two rather than surviving as a trimmed version. The PR now carries source and tests only.

The two files were also mutually dependent: the grant.mdx line linked the #destination-privileges anchor that the overview section defined, so keeping either alone would have left a dangling link.

Comment thread docs/reference/statements/grant.mdx Outdated
### SOURCES {#sources}

Allows using external data sources. Applies to [table engines](/reference/engines/table-engines/index) and [table functions](/reference/functions/table-functions/index).
Allows using external data sources. Applies to [table engines](/reference/engines/table-engines/index), [table functions](/reference/functions/table-functions/index), the locations used by [BACKUP/RESTORE](/concepts/features/backup-restore/overview#destination-privileges), and the [Backup database engine](/reference/engines/database-engines/backup).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this too

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed in 3acd172.

if (use_same_s3_credentials_for_base_backup && backup_info.canCopyS3CredentialsTo(effective_base_backup_info))
backup_info.copyS3CredentialsTo(effective_base_backup_info);

BackupFactory::instance().checkSourceAccess(effective_base_backup_info, context, IBackup::OpenMode::READ);

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 only closes the user-supplied base_backup setting. A manifest-provided <base_backup> is still loaded later in BackupImpl::readBackupMetadata and first opened from getBaseBackupUnlocked; on RESTORE ... ON CLUSTER / internal restore that lazy open can still happen in a context with no user_id, which Context::getAccess treats as full access. So a crafted incremental backup can still read an unauthorized base backup even though this preflight passes.

The fix needs the same no-I/O authorization for the manifest-provided base locator before dispatch (or when parsing the metadata), plus a regression test for the manifest-only base path.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, and known: this is the manifest-provided base gap I measured and disclosed in #114405 (comment) rather than fixed here. A SOURCES-revoked user restoring an outer backup whose manifest names a base under an ungranted prefix does get RESTORED plus the base's rows, so it is real, not theoretical.

Your suggested seam is the interesting part, and it differs from what I tried. I closed it by walking the base chain on the initiator, which worked (ACCESS_DENIED, naming READ ON S3) but regressed 02915_lazy_loading_of_base_backups: that test pins ProfileEvents['BackupsOpenedForRead'] at r3 1 0 and the eager walk measured r3 3 0. I reverted it rather than ship the regression. Authorizing at metadata-parse time, as you suggest, would avoid those extra opens, but base_backup_info is a private BackupImpl member with no accessor on IBackup, so it needs a new API plus decisions on recursive chains and cyclic manifests.

That is a separate change with its own tests, and the scope call is @ pufit's. Not claiming it fixed here.

throw Exception(ErrorCodes::BACKUP_ENGINE_NOT_FOUND, "Not found backup engine '{}'", engine_name);

/// Authorize the location before the creator does any network or filesystem I/O.
checkSourceAccess(params.backup_info, params.context, params.open_mode);

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.

checkSourceAccess here only covers the outer backup_info. Lightweight snapshot restores still build a second reader from manifest-controlled original_endpoint / original_namespace and per-file object_key in BackupImpl::readBackupMetadata, and that secondary location never goes through the new SOURCES check. A user who is allowed to read the outer backup can therefore still restore snapshot data from an unrelated S3 / Azure location named in the manifest.

This needs an authorization step for the secondary reader target before constructing it, with a focused crafted-manifest test.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed in principle, and also already disclosed in #114405 (comment): original_endpoint / original_namespace and the per-file object_key are manifest-controlled and select a second reader that the new check never sees. Same shape as the base-locator gap above.

I did not fix it because I cannot exercise it in this build: the lightweight-snapshot commit and unlock paths are #if CLICKHOUSE_CLOUD (BackupsWorker.cpp:714,802), so a crafted-manifest test here would assert nothing. I would rather leave it visible than write a fix I cannot test.

Both this and the base-locator gap are pre-existing and neither is widened by this change. Scope is @ pufit's call.

Requested by the reviewer. The backup/restore overview section, the SOURCES
grant reference edit and the Backup engine's own note are all removed, so the
change carries source and tests only. The grant reference linked the anchor the
overview section defined, so keeping either alone would leave a dangling link.
BackupStarter runs the new destination check on a copy of the query context,
and makeQueryContext resets that copy to a fresh QueryPrivilegesInfo, so the
grant the check consumed never reached system.query_log. RestoreStarter already
shares the originating tracker for exactly this reason; the BACKUP side now does
the same.

Measured on a single node with an audit user granted BACKUP and WRITE ON FILE:
used_privileges was ['BACKUP ON default.t'] before and
['WRITE ON FILE','BACKUP ON default.t'] after. The stateless test asserts it,
and removing the line flips that assertion alone.
@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

No arm_release build profile data for commit 3acd172 - the build was skipped, reused from cache, or predates profile upload.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed 3acd172: both docs updates removed as asked (plus a third one in the Backup engine's own doc string, same change in a third file), and one fix to my own code that the removal round surfaced.

BackupStarter runs the new destination check on a copy of the query context, and makeQueryContext resets that copy to a fresh QueryPrivilegesInfo, so the source grant the check consumed never reached system.query_log. RestoreStarter already shares the originating tracker for exactly this reason; the BACKUP side now does the same. Measured with an audit user holding BACKUP and WRITE ON FILE:

used_privileges
before ['BACKUP ON default.t']
after ['WRITE ON FILE','BACKUP ON default.t']

04774 asserts it, and removing the line flips that one assertion and nothing else.

Still open for your scope call, unchanged: the manifest-provided base locator and the lightweight-snapshot manifest fields, both replied to in the threads above.

@pufit
pufit enabled auto-merge August 12, 2026 15:14
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger for 3acd172

Every failure below has an owner: a fixing PR (ours 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
BuzzHouse (amd_tsan) harness teardown hang, not a server bug: the fuzzer finished its 1800 s budget normally (Fuzzer exit code is 143), the post-fuzz SELECT 1 probe answered, then the job sat 4h28m in the unbounded wait $server_bg_pid after stop_server & (run-fuzzer.sh) until the 18000 s job ceiling (exit code [-15]). Server never died (server_died=0, server_exit_code=0); in-flight query was an unrelated TRUNCATE ... ON CLUSTER. The other three BuzzHouse variants on this same head all passed. #111934 (ours, open)

Not owned failures, for the record: Bugfix validation (integration tests, amd64/aarch64) carry
test_status=FAIL rows in CIDB while both jobs concluded success - that is the expected half
of the bugfix-validation contract (the regression test must fail on master HEAD), and the job
passing is the assertion. Build (arm_release) / Post Hooks is a CIDB bookkeeping row on a
SUCCESS check (LogCluster query failed with code 500), fleet-wide and unrelated to this PR.

Session id: cron:our-pr-ci-monitor:20260812-160000

@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 14, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 14, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 1, 2026
`Stateless tests (amd_asan_ubsan, flaky check)` failed this PR's head with
`Test runs too long (> 180s)` on 04774: 5 of 5 recorded runs over the gate
(183.76 to 190.85 s), no passes. That gate is per test file and fires only in
flaky-check mode (tests/clickhouse-test:3630-3646).

The cost is per client process, not per statement. 04774 was 49 client
invocations at 132.0 s p50 in ClickHouse#114405's slowest asan flaky-check job and is 75
here at 185.2 s p50: 2.69 and 2.47 s per invocation. Four interleaved local
pairs give 0.179 s per invocation on all three arms.

So the Disk section moves to 04776 with its own fixture, at 37 invocations.
04774 keeps the File coverage at 46 invocations, below the 49 it shipped with,
and its change is a pure deletion: the two arms that asserted the old `Disk`
exemption, plus the locator and admin backup only those arms used.

The moved block is verbatim apart from the local database identifier and one
added arm: `ENGINE = Backup` over a `Disk(...)` locator was asserted only in the
denied direction, here and before the split, so a regression that stopped
granting the new source on that path would not have been caught. `RESTORE` had
that positive arm already.

Equivalence is byte-exact rather than argued: dropping the two lines the new arm
prints from 04776's reference and reinserting the rest at the seam in 04774's
reproduces the published 04774 reference. With the `Disk` source hook reverted to
`std::nullopt`, 04776 fails on 7 lines and 04774 passes; with it made to demand
`WRITE` unconditionally, 04776 fails on the two positive arms.
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 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.

5 participants