Skip to content

Store all asked privileges for better RBAC auditing - #104693

Merged
alexbakharew merged 7 commits into
masterfrom
alexey-bakharev/audit-record-isgranted
May 23, 2026
Merged

alexbakharew merged 7 commits into
masterfrom
alexey-bakharev/audit-record-isgranted

Conversation

@alexbakharew

@alexbakharew alexbakharew commented May 12, 2026 •

Copy link
Copy Markdown
Contributor

Expand system.query_log.used_privileges coverage to also record privileges that are confirmed via the non-throwing isGranted path, so that READ ON FILE / READ ON S3 / READ ON AZURE / READ ON URL (and any other privilege checked through ContextAccess::checkAccessWithFilter) are visible in the audit trail.

Background

#99122 centralized source-access checks for file() / s3() / azure() / url() table functions and routed them through ContextAccess::checkAccessWithFilter, which uses isGranted for the granted path:

void ContextAccess::checkAccessWithFilter(...) const
{
    if (isGranted(context, flags, parameter))
        return;                              // ← granted short-circuit
    ...
    checkAccess(context, flags, parameter);  // throw if denied
}

isGranted is checkAccessImpl<throw_if_denied=false, ...>. In ContextAccess::checkAccessImplHelper, the call to Context::addQueryPrivilegesInfo(..., granted=true) was gated on throw_if_denied, so the granted branch on non-throwing entry points never recorded. Net effect: DESCRIBE file('…'), CREATE TABLE AS file('…'), and similar queries no longer reported READ ON FILE in system.query_log.used_privileges. The privilege check itself still ran — unauthorized users still get Code: 497 ACCESS_DENIED on the new branch — so enforcement was unchanged, only the audit trail was incomplete.

Change

Drop the if constexpr (throw_if_denied) gate around the granted-side addQueryPrivilegesInfo call in checkAccessImplHelper so every successful access check records, regardless of which public API (checkAccess / checkGrantOption / isGranted / checkAccessWithFilter) reached the helper. The denied-side gate is preserved so predicate-style isGranted callers do not pollute missing_privileges with speculative misses.

Measurement

Two ProfileEvents are added to allow the impact to be quantified directly from system.query_log:

  • QueryPrivilegesInfoUpdates — total recordings into used_privileges / missing_privileges after the change.
  • QueryPrivilegesInfoUpdatesLegacy — only the recordings from throwing call paths (checkAccess / checkGrantOption), matching the historical pre-change behavior.

Results

Full stateless asan run on this PR's commit 8e6cab260702ec24961ce1c48f36fab083fbcc35 (Stateless tests (amd_asan…), 282,702 QueryFinish rows):

Metric Value
legacy_baseline (old behavior) 258,781
new_total (this PR) 559,599
audit_gap_closed 300,818
audit_gap_pct 116.24 %
new_calls_per_query 1.98
legacy_calls_per_query 0.92

About one additional std::unordered_set<String>::emplace per query on average, distributed across the suite.

Tail check

Top queries by additional recordings:

Query extra_calls duration
SYSTEM START VIEWS 614 6 ms
SYSTEM START VIEWS 582 5 ms
SYSTEM PAUSE VIEWS 307 4 ms
SYSTEM PAUSE VIEWS 291 5 ms
SELECT count() FROM test.visits (×7) 182 each 10–17 ms
SELECT count() FROM test.hits (×7) 134 each 9–19 ms
kill mutation where … 102 1609 ms

All concentrated on legitimate "iterate over N objects and check each" patterns — view fan-out for SYSTEM DDL, per-column SELECT resolution on wide tables, per-mutation checks for KILL MUTATION — exactly the cases where granular per-object audit signal is useful. The worst-case query adds 614 set inserts on a 6 ms query (microseconds of extra work), and nothing in the distribution looks like a planner loop over millions of items.

Aggregation query used to produce the numbers above (works against the CI logs cluster's default.query_log_* tables):

WITH '8e6cab260702ec24961ce1c48f36fab083fbcc35' AS commit_to_check
SELECT
    sum(ProfileEvents['QueryPrivilegesInfoUpdates'])       AS new_total,
    sum(ProfileEvents['QueryPrivilegesInfoUpdatesLegacy']) AS legacy_baseline,
    new_total - legacy_baseline                            AS audit_gap_closed,
    round((new_total - legacy_baseline) / nullIf(legacy_baseline, 0) * 100, 2) AS audit_gap_pct,
    count()                                                AS rows,
    round(new_total / nullIf(rows, 0), 3)                  AS new_calls_per_query,
    round(legacy_baseline / nullIf(rows, 0), 3)            AS legacy_calls_per_query
FROM merge('default', '^query_log_')
WHERE commit_sha = commit_to_check
  AND check_name LIKE 'Stateless tests (amd_asan%'
  AND type = 'QueryFinish'
FORMAT Vertical

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Record privileges in system.query_log.used_privileges for all granted access checks, including those that go through the non-throwing isGranted path (checkAccessWithFilter). Previously only privileges checked via throwing entry points (checkAccess / checkGrantOption) were recorded, which made READ ON FILE / READ ON S3 / READ ON AZURE / READ ON URL invisible in the audit log for DESCRIBE, CREATE TABLE AS, and similar queries that use file() / s3() / azure() / url() table functions. Access enforcement is unchanged.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.6.1.109

@clickhouse-gh

clickhouse-gh Bot commented May 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4964544]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/check_report_messages.py FAIL IGNORED

AI Review

Summary

This PR updates ContextAccess to record granted privileges from non-throwing access checks so system.query_log.used_privileges captures more RBAC decisions. The core direction is correct, but one success path in checkAccessWithFilter still returns without recording, so the PR does not satisfy its stated contract of recording all granted checks.

Findings

❌ Blockers

  • [src/Access/ContextAccess.cpp:1093] checkAccessWithFilter still has a filter-match success branch that returns without calling Context::addQueryPrivilegesInfo, so grants like READ ON S3('s3://foo.*') can authorize access while system.query_log.used_privileges remains incomplete.
    Suggested fix: before the return in the filter-match branch, record the granted privilege (for example with AccessRightsElement{flags, parameter}.toStringWithoutOptions()) via context->addQueryPrivilegesInfo(..., true).
Tests
  • ⚠️ Add a focused regression test that grants filtered source access (for example READ ON S3('<pattern>')), executes a query that succeeds via the filter branch, and asserts the corresponding privilege appears in system.query_log.used_privileges.
Final Verdict

Status: ⚠️ Request changes
Minimum required actions:

  1. Record granted privileges in the filter-match success path of checkAccessWithFilter.
  2. Add a regression test proving that filtered grants are audited in used_privileges.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label May 12, 2026
{
/// Record every granted access, regardless of whether the caller is the throwing entry point
/// (`checkAccess` / `checkGrantOption`) or the non-throwing one (`isGranted`, used internally by
/// `checkAccessWithFilter`). Without this, an `isGranted`-driven success leaves no trace in

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.

The new logic/comments here state that every granted access is now recorded, but checkAccessWithFilter still has a second successful path (filter match) that returns without calling Context::addQueryPrivilegesInfo.

Concrete case: GRANT READ ON S3('s3://foo.*') can authorize s3://foo/bar.csv via the filter branch, yet system.query_log.used_privileges still misses READ ON S3 for that query.

Could we also record before the filter-branch return (for example with AccessRightsElement{flags, parameter}.toStringWithoutOptions()) so filtered grants are audited too?

alexbakharew and others added 5 commits May 20, 2026 23:16
The QueryPrivilegesInfoUpdates and QueryPrivilegesInfoUpdatesLegacy
counters were added only to measure the perf impact of always recording
granted accesses in `addQueryPrivilegesInfo` (see PR #104693
discussion). The numbers came back well within noise (~2x more
recordings, ~1 extra `unordered_set` insert per query on average, no
planner-loop pathology), so the counters are no longer needed and are
removed here. The functional change (dropping the
`if constexpr (throw_if_denied)` gate on the granted-side write) is kept.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
PR #80785 added a second app under /pg_testapp to the
`clickhouse/mysql_dotnet_client` image, making /pg_testapp the
last WORKDIR. `dotnet run` (no project arg) then launched the
Npgsql client against the MySQL port, producing
"Received unknown response X for SSLRequest (expecting S or N)".

The PR was reverted (#105615) but the cached `:latest` image on
integration runners still has /pg_testapp as the last WORKDIR.
Anchor the command to /testapp so the test passes regardless of
the image's working directory, matching what test_dotnet_client
in test_postgresql_protocol/test.py already does.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
/// (`checkAccess` / `checkGrantOption`) or the non-throwing one (`isGranted`, used internally by
/// `checkAccessWithFilter`). Without this, an `isGranted`-driven success leaves no trace in
/// system.query_log.used_privileges even though the privilege was effectively required by the query.
context->addQueryPrivilegesInfo(AccessRightsElement{flags, args...}.toStringWithoutOptions(), true);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This change alters the audit contract for granted checks, but there is still no focused regression test proving used_privileges is populated for the checkAccessWithFilter filter-match path (for example GRANT READ ON S3('<pattern>') authorizing a specific URL).

Could we add one stateless/integration test that exercises that path and asserts the corresponding privilege appears in system.query_log.used_privileges?

@clickhouse-gh

clickhouse-gh Bot commented May 22, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.40% 91.40% +0.00%
Branches 76.50% 76.50% +0.00%

Changed lines: 100.00% (3/3) · Uncovered code

Full report · Diff report

@alexbakharew
alexbakharew enabled auto-merge May 23, 2026 10:27
@alexbakharew
alexbakharew added this pull request to the merge queue May 23, 2026
Merged via the queue into master with commit 336c888 May 23, 2026
486 of 490 checks passed
@alexbakharew
alexbakharew deleted the alexey-bakharev/audit-record-isgranted branch May 23, 2026 10:41
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @alexbakharew @pufit — a couple of suggestions to make this PR easier for reviewers and the changelog reader.

Description (currently incomplete):

  • Why: The description mentions 'Two ProfileEvents are added' but the sentence is truncated and no ProfileEvents appear in the diff. The description accurately explains the isGranted fix but may reference planned features not yet implemented.

  • Suggested addition:

    Consider removing or completing the truncated 'Measurement' section about ProfileEvents if they are not part of this PR.

Ignore this if the current title/body is intentional.

@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 23, 2026
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
The QueryPrivilegesInfoUpdates and QueryPrivilegesInfoUpdatesLegacy
counters were added only to measure the perf impact of always recording
granted accesses in `addQueryPrivilegesInfo` (see PR ClickHouse#104693
discussion). The numbers came back well within noise (~2x more
recordings, ~1 extra `unordered_set` insert per query on average, no
planner-loop pathology), so the counters are no longer needed and are
removed here. The functional change (dropping the
`if constexpr (throw_if_denied)` gate on the granted-side write) is kept.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
…audit-record-isgranted

Store all asked privileges for better RBAC auditing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-improvement Pull request with some product improvements 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