Skip to content

Add SQL-managed query masking rules: CREATE QUERY MASKING RULE - #128773

Open
groeneai wants to merge 16 commits into
ClickHouse:masterfrom
groeneai:sql-query-masking-rules
Open

groeneai wants to merge 16 commits into
ClickHouse:masterfrom
groeneai:sql-query-masking-rules

Conversation

@groeneai

@groeneai groeneai commented Nov 2, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #128251

Changelog category (leave one):

  • New Feature

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

Query masking rules can now be managed with SQL: CREATE QUERY MASKING RULE name REGEXP '...' [REPLACE '...'], ALTER QUERY MASKING RULE, DROP QUERY MASKING RULE, SHOW QUERY MASKING RULES and the system.query_masking_rules table. Like the rules of the query_masking_rules server setting, they hide matches in the query logs, server logs and exception messages, but they need no access to the server configuration. They are stored like users and roles (replicated with the replicated user directory, included in backups of system.query_masking_rules), are applied after the rules from the configuration, and are managed with the new QUERY MASKING RULE ADMIN privilege. The REGEXP is shown as [HIDDEN]. Closes #128251.

Description

As asked in #128251 (option A), a query masking rule is a new access entity, so the existing access storages, DROP, MOVE, SHOW CREATE, SHOW ACCESS, ON CLUSTER and BACKUP/RESTORE handle it.

  • SensitiveDataMasker now has two rule lists, from the config (setInstance) and from SQL (setSQLDefinedRules), published as one instance with the config rules first. A config reload no longer replaces SQL rules and vice versa.
  • QueryMaskingRulesCache in AccessControl publishes the SQL rules, ordered by name, on every change and after a disk or replicated storage is added (their initial load sends no notification).
  • An empty or invalid REGEXP, or a REPLACE that names a capture group the regexp lacks (RE2 would then replace nothing), is rejected without quoting the pattern, both in CREATE/ALTER and when a stored rule is read. A stored rule that cannot be read stops the server from starting, as an invalid rule in the config does, except where an access storage already skips unreadable entities of every type.

One privilege, QUERY MASKING RULE ADMIN, covers both managing and listing the rules, because it takes the last free value of AccessType; #116757 widens the type.

Validation: a new stateless test (masking of logs, query_log and exceptions; order; ALTER; secrets; errors; privileges), 50/50 with randomized settings, and three integration tests (config reload and restart, replicated access storage including a restart, backup/restore). Each of thirteen mutations of the design reddens its own assertion; the startup failure on a corrupted rule file was checked by hand.


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

groeneai and others added 6 commits November 2, 2026 18:33
`CREATE / ALTER / DROP QUERY MASKING RULE` define rules like those of the
`query_masking_rules` server setting, for environments without access to the
server configuration (ClickHouse Cloud and other managed services).

A rule is a new access entity (`QUERY_MASKING_RULE`), so it is stored by the
`user_directories` storages like users and roles: replicated through Keeper,
backed up with `system.query_masking_rules`, moved with `MOVE`, and listed
with `SHOW QUERY MASKING RULES` / `SHOW CREATE QUERY MASKING RULE`. All of it
is gated by the new `QUERY MASKING RULE ADMIN` privilege (a child of
`ACCESS MANAGEMENT`), which takes the last free `AccessType` value.

`SensitiveDataMasker` now has two independent rule sources, the server
config (`setInstance`, unchanged for its callers) and the SQL rules
(`setSQLDefinedRules`), published config-first as one instance, so a config
reload cannot drop the SQL rules and vice versa. `QueryMaskingRulesCache`
in `AccessControl` keeps the SQL list in sync from access notifications, and
re-reads all rules after a disk or replicated storage is added, because their
initial load does not notify. A publish that throws stays pending and is
retried on the next notification pass.

The REGEXP is a secret: hidden in the query logs (`hasSecretParts`), in
`SHOW CREATE` and in the system table unless secrets may be displayed.
`SensitiveDataMasker::validateRule` rejects an empty or invalid REGEXP and a
REPLACE that references a missing capture group (RE2 would silently replace
nothing), without quoting the pattern; it runs for CREATE, ALTER and when a
stored rule is deserialized, so an invalid stored rule is handled by the
storage's own invalid-entity policy.

Closes ClickHouse#128251

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A server log line is masked once more when it is written, which hides the
order in which the rules were applied.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…once

`CREATE/ALTER QUERY MASKING RULE ... IN <storage>` wrote through the nested
storage, which only queues the change notification, so the masker kept the
old rules until an unrelated access change flushed the queue. Route the
writes through `AccessControl` (`insertInto`, `update`, `tryUpdate`), as the
role and settings profile interpreters do; `insertInto` also does the
name-collision check against the other storages.

Test the `IN <storage>` path, the privilege checks of `SHOW CREATE` and
`MOVE` for query masking rules, and the privilege check of `RESTORE` of
`system.query_masking_rules`.

Drop RE2's trailing period from the `Invalid REPLACE` error.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`QueryMaskingRulesCache::reload` caught the error of every rule it could
not read, logged it and published the remaining rules. A stored rule whose
file is missing, unparsable or unreadable, or that fails validation, was
therefore silently dropped until a restart or a change of that rule, and
the secrets it exists to hide reached `system.query_log`, `system.text_log`
and the server log.

Build the new rule set first and replace the published one only after
every listed rule was read. A read error now propagates out of
`AccessControl::addDiskStorage` / `addReplicatedStorage`, so the server
refuses to start and names the file, as it already does for an invalid
`query_masking_rules` config rule; the row policy, settings profile and
quota caches propagate read errors the same way.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop a reload() doc line that repeats the call-site comments in AccessControl.cpp.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@mintlify

mintlify Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit 89f9e68.

Approve preview

@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (rounds 1-3): 3 findings fixed, 2 not changed
Finding Verdict
❌ CREATE/ALTER QUERY MASKING RULE ... IN <storage> stored the rule but did not publish it to the masker until the next access change Agreed, fixed: both now go through AccessControl, as CREATE ROLE does; new test case
❌ A stored rule that could not be read at startup was skipped, and the other rules were published without it Agreed, fixed: the server now refuses to start with the read error, as with an invalid config rule or an unreadable settings profile; the cache never publishes a partial set
⚠️ The privilege checks of SHOW CREATE, MOVE and RESTORE had no test Agreed, fixed: denial cases added to the stateless test and the backup integration test
⚠️ The new privilege renumbers the later AccessType values in system.privileges Not applicable: a child must precede its group (AccessType.h:162), so every new ACCESS MANAGEMENT privilege shifts the later values (also #99702, #123545); grants are stored by name
⚠️ The access storages still skip an unreadable rule when they rebuild their lists or read an invalid replicated entity Not changed here: that is the storages' policy for every entity type, and throw_on_invalid_replicated_access_entities makes the replicated one fail instead. Such a rule needs a hand-edited or damaged access file, because CREATE, ALTER and RESTORE validate it
💡 SHOW ACCESS lists the rules (with the REGEXP hidden) to SHOW ACCESS holders; under readonly, SHOW CREATE QUERY MASKING RULE is refused because the single privilege counts as access management; the ALTER docs do not list IN access_storage_type Noted: the first two follow from the single privilege, the docs match ALTER ROLE

@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? New feature: master rejects CREATE QUERY MASKING RULE with SYNTAX_ERROR. Each property of the design has a deterministic red under a mutation (table in e).
b Root cause explained? The masker had one source, the server config, and setInstance replaced it wholesale on every config reload; there was no SQL entity. A second source needs two independent rule lists in the masker plus an access entity whose changes are pushed to it.
c Fix matches root cause? Two lists published as one instance (config first), a new access entity QUERY_MASKING_RULE, and a cache in AccessControl that publishes the SQL list. Readers of the masker are unchanged.
d Test intent preserved / new tests added? New 05483_query_masking_rules_sql.sh plus test_reload_query_masking_rules, test_replicated_users and test_backup_restore_new extensions (incl. denial cases for SHOW CREATE, MOVE and RESTORE); 01271/04926 references gain the new privilege and statements. No existing assertion changed.
e Both directions demonstrated? Mutations, each built alone: config reload drops SQL rules, no reload after adding a disk storage, no reload after adding a replicated storage, REGEXP not secret, SQL rules before config rules, reverse name order, no ON CLUSTER removal for replicated storage, no REPLACE check, CREATE/ALTER ... IN <storage> written through the nested storage, a permissive privilege for SHOW CREATE, MOVE and RESTORE. Each reddens its own assertion; all pass on the fix. A stored rule file that cannot be read (unparsable or missing) was silently dropped at startup before; now startup fails naming the file (checked locally).
f Fix is general across code paths? Every reader of the masker (server log, text_log, query log, exceptions, async inserts) sees SQL rules. All entity-type switches handled; disk, replicated, memory storages, backup/restore, MOVE and clickhouse-local covered; writes into a named storage (IN <storage>) go through AccessControl like every other write, so they reach the masker at once.
g Fix generalizes across inputs (params/datatypes/wrappers)? Empty REGEXP, uncompilable REGEXP (error quotes no part of it), REPLACE with a missing capture group, default REPLACE, IF NOT EXISTS / OR REPLACE / IF EXISTS / RENAME TO, plural SHOW CREATE.
h Backward compatible? (maintainer-approved exception only) No setting or default changed. Config rules behave as before (same order, throw_on_match kept, no new validation for them). New privilege, new entity type and system table only.
i Invariants and contracts preserved? Config rules always precede SQL rules; a config reload never drops SQL rules and vice versa; publication stays an atomic MultiVersion swap; a failed publish is retried on the next notification; a stored rule that cannot be read stops startup, as an invalid config rule does; the replicated storage keeps its own skip/throw policy for invalid entities.

Session id: cron:clickhouse-impl-slot-4:20261102-214900

@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @pufit @vitlibar, could you review this and add the can be tested label so CI runs? It adds QUERY MASKING RULE as a new access entity (option A in #128251): AccessControl publishes the SQL-defined rules to SensitiveDataMasker, which keeps them as a second list after the config rules, and one new privilege, QUERY MASKING RULE ADMIN, covers managing and listing them.

@clickhouse-gh

clickhouse-gh Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [89f9e68]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

This PR adds SQL-managed query masking rules backed by access storage, with a dedicated privilege, introspection, replication, and backup/restore support. Reviewed head 89f9e68618d0f1b53711e69338a04ff6e359c7fb. One previously discussed publication-safety blocker remains; there are no new inline findings.

Findings

❌ Blockers

  • src/Access/QueryMaskingRulesCache.cpp:38 — [dismissed by author -- https://github.com/Add SQL-managed query masking rules: CREATE QUERY MASKING RULE #128773#discussion_r4484313902]. A stored rule can remain inactive indefinitely after notification loss. AccessChangesNotifier::sendNotifications drains the queue at line 110, then allocates at lines 116 and 132 before entering this handler's memory-tracker blocker. With min_allocation_size_to_throw_on_memory_limit=1, an allocation exception discards that batch. The cache receives neither the rule nor a pending-publication flag, so subsequent empty dispatches cannot recover it, and CREATE QUERY MASKING RULE IF NOT EXISTS returns without dispatching. With concurrent callers, another query can lose the creator's notification before the creator dispatches successfully. Secrets then reach logs and exception messages without masking.

    The author deliberately deferred this because the dispatcher defect predates the PR, affects the other access caches, and requires an opt-in allocation setting. It remains a real masking-contract violation because the new handler's protection cannot cover allocations before the handler runs. Preserve undelivered notifications or protect dispatch; alternatively, explicitly link a tracking issue for the deferred shared defect. No matching tracking issue was found. The existing thread was left unchanged.

Tests
  • ⚠️ The low-memory creation test protects compilation inside the handler, but does not exercise failure between draining the notification queue and invoking the handler. Add focused fault injection at that boundary and verify that the rule is eventually enforced, including after an IF NOT EXISTS retry. The existing thread contains a dispatcher-only reproduction; this review rechecked the current source and did not rerun a full-server reproduction.
Final Verdict

Status: ❌ Block

Preserve publication after dispatcher allocation failure and cover that boundary, or link a tracking issue explicitly accepting deferral of the pre-existing shared defect.

@clickhouse-gh clickhouse-gh Bot added pr-feature Pull request with new product feature can be tested Allows running workflows for external contributors comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. labels Nov 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d3927f20f with master 0fbea1ea4 (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.

Object file sizes

129 object files changed (+483.68 KiB total), 6 added.

Object file Master PR Δ
src/Storages/System/CMakeFiles/clickhouse_storages_system.dir/StorageSystemQueryMaskingRules.cpp.o new 163.38 KiB +163.38 KiB
src/CMakeFiles/dbms.dir/Access/QueryMaskingRulesCache.cpp.o new 78.88 KiB +78.88 KiB
src/Parsers/CMakeFiles/clickhouse_parsers.dir/Access/ASTCreateQueryMaskingRuleQuery.cpp.o new 64.17 KiB +64.17 KiB
src/CMakeFiles/dbms.dir/Interpreters/Access/InterpreterCreateQueryMaskingRuleQuery.cpp.o new 57.81 KiB +57.81 KiB
src/Parsers/CMakeFiles/clickhouse_parsers.dir/Access/ParserCreateQueryMaskingRuleQuery.cpp.o new 51.12 KiB +51.12 KiB
src/CMakeFiles/dbms.dir/Access/QueryMaskingRule.cpp.o new 25.46 KiB +25.46 KiB

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

1121 translation units recompiled, 7589 s compile time in total, 1114 of them have a recent master baseline.

Translation units without a recent master baseline:

  • programs/keeper/Keeper.cpp (clickhouse-keeper): 7.1 s
  • src/Storages/System/StorageSystemQueryMaskingRules.cpp: 5.5 s

Job report

@pufit pufit self-assigned this Nov 3, 2026

@pufit pufit left a comment

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.

@groeneai please also resolve conflicts

Comment thread src/Access/AccessControl.cpp Resolved
Comment thread src/Access/Common/AccessEntityType.cpp Resolved
groeneai and others added 2 commits November 4, 2026 10:01
… rule

The query logs always hide it, and `SHOW CREATE QUERY MASKING RULE` and
`system.query_masking_rules` show it only when the server setting
`display_secrets_in_show_and_select`, the format setting
`format_display_secrets_in_show_and_select` and the
`displaySecretsInShowAndSelect` privilege all allow it (`canDisplaySecrets`).
A statement that cannot be parsed has no AST to hide secrets in, so it is
logged with only the masking rules applied, like a password.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

Resolved the conflict by merging master in ab471f8 (both sides added an #include in src/Access/AccessControl.cpp).

One more commit, 4ca4f81, corrects the CREATE QUERY MASKING RULE doc on when the REGEXP is shown: the query logs always hide it, and SHOW CREATE / system.query_masking_rules show it only with display_secrets_in_show_and_select, format_display_secrets_in_show_and_select and the displaySecretsInShowAndSelect privilege.

This PR and my #129033 each add an AccessType value, and only one is free, so whichever is merged second has to widen the enum (as #116757 does).

Check that rejected `ALTER QUERY MASKING RULE` and `CREATE QUERY MASKING RULE OR REPLACE` statements preserve masking in query logs and exception messages.

Related: ClickHouse#128773
@mintlify

mintlify Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Nov 5, 2026, 4:22 PM

Comment thread src/Access/AccessControl.cpp Resolved
groeneai and others added 2 commits November 5, 2026 16:58
It is declared after `changes_notifier`, which its constructor subscribes to,
so the initializer order is the same as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Style check / various requires every stateless test that reads
system.query_log to filter by current_database = currentDatabase().
The query_id is already unique, so the result is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
needs_publish = true;

if (needs_publish)
publishLocked();

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.

❌ Blocker: surface failures to publish a masking rule

publishLocked runs inside an AccessChangesNotifier handler, and sendNotifications catches and logs handler exceptions. The entity is already stored at this point, so a failure leaves the previous masker active while CREATE QUERY MASKING RULE reports success. Ordinary queries do not retry publication, and a successful CREATE ... IF NOT EXISTS retry does not either.

Reproduced with this head's Fast test binary: enable server setting min_allocation_size_to_throw_on_memory_limit=1, use client setting max_untracked_memory=0, and create 12 rules whose regexp is [A-M]{1000} concatenated 20 times. Creating candidate_6400000 REGEXP 'REVIEWSECRET_6400000' REPLACE '[new-masked]' with client setting max_memory_usage=6400000 returns success and the rule appears in system.query_masking_rules, but a separate unrestricted connection running SELECT throwIf(1, 'REVIEWSECRET_6400000') receives plaintext REVIEWSECRET_6400000 in the server exception. Retrying creation with IF NOT EXISTS still leaves it unmasked. The server logs show MEMORY_LIMIT_EXCEEDED in re2::Prog::Flatten → QueryMaskingRulesCache::publishLocked, swallowed by sendNotifications.

Ensure a successful mutation means its rules were published; otherwise surface the publication failure and arrange a guaranteed retry. Add a focused regression case for failure after persistence, since the rejected-update tests cover validation before persistence.

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.

Fixed in 5557173: rebuilding the masker is no longer charged to the query that changes a rule, with a regression case in test_reload_query_masking_rules.

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 query-limit reproduction is fixed, but publication can still fail silently at src/Access/QueryMaskingRulesCache.cpp:38: the blocker added at line 64 defaults to VariableContext::User, so the total server memory limit still throws inside this notification handler.

Reproduced on 55571732567cb with max_server_memory_usage=1073741824, min_allocation_size_to_throw_on_memory_limit=70000, the 24 large rules from the new regression test, and an unrelated read holding 450,467,664 bytes. Set memory_overcommit_ratio_denominator=0 and memory_overcommit_ratio_denominator_for_user=0 on the read and creation query so overcommit cannot cancel the read to make room. CREATE QUERY MASKING RULE nonkill_total_24000000 REGEXP 'NONKILLSECRET_24000000' REPLACE '[holder-hidden]' returned HTTP 200. After the read finished successfully and released its memory, the rule was visible in system.query_masking_rules, but SELECT throwIf(1, 'NONKILLSECRET_24000000') returned the plaintext secret. A subsequent CREATE ... IF NOT EXISTS returned HTTP 200 and still left it unmasked.

For creation query 0c178f73-14db-4b66-a94b-ae095b776b86, the server logged a swallowed MEMORY_LIMIT_EXCEEDED on a 128 KiB allocation in re2::Prog::IsOnePass → QueryMaskingRulesCache::publishLocked → AccessChangesNotifier::sendNotifications. This still needs publication failure propagation and a retry that does not depend on another access notification; bypassing query accounting alone does not establish that a successful creation activates the rule.

@groeneai groeneai Nov 5, 2026 •

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.

Fixed in 3910941: the handler now blocks the memory trackers at the global level, so no limit can refuse the rebuild (the server tracker still counts it), which also avoids the RE2 DFATAL abort in debug builds that a refused allocation caused there.

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.

[Blocker] The global blocker in 3910941b6de5e still starts too late: src/Access/AccessChangesNotifier.cpp:110 drains the queue, then lines 116 and 132 allocate under the sender's memory tracker before reaching the blocker at src/Access/QueryMaskingRulesCache.cpp:38. With min_allocation_size_to_throw_on_memory_limit=1, a memory-limit exception there destroys the drained batch. This cache never receives the change or sets needs_publish, so later notification passes cannot recover the missing rule.

I compiled the current production AccessChangesNotifier.cpp with minimal entity/logging stubs and injected failure into the first dispatch allocation: after enqueueing one change, the first dispatch throws; two subsequent successful dispatches deliver zero changes and two empty batches. This is a focused dispatcher reproduction, not a full server reproduction.

Persistence precedes dispatch at src/Access/AccessControl.cpp:663–666, so a failed creation can leave a stored rule permanently inactive, including after a successful CREATE QUERY MASKING RULE IF NOT EXISTS retry. With concurrent senders, another query can consume and lose the rule's batch while the creator's own dispatch subsequently succeeds. Please protect dispatch as well, or preserve and retry undelivered batches, and cover failure before the handler starts.

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.

This batch is lost in AccessChangesNotifier::sendNotifications before any handler runs, which this PR does not change, and every access cache (RowPolicyCache, QuotaCache, SettingsProfilesCache, RoleCache) receives its changes through that same batch. It also needs the opt-in min_allocation_size_to_throw_on_memory_limit (with the default 0, operator new is never refused), so I am keeping it out of this PR.

groeneai and others added 2 commits November 5, 2026 19:02
QueryMaskingRulesCache rebuilds the server-wide masker in the thread that
sends the access change notifications, usually the query running
CREATE/ALTER/DROP QUERY MASKING RULE, so compiling all the rules was charged
to that query. With `min_allocation_size_to_throw_on_memory_limit` set, its
`max_memory_usage` could then fail the rebuild after the rule was stored:
AccessChangesNotifier only logs a handler exception, so the statement reported
success while the new rule was not applied until the next access change.
Reproduced with 12 rules of `[A-M]{1000}` x 20 and a CREATE limited to 3 MB:
the secret then reached the server exception and logs in plaintext.

The masker outlives the query, so it is built with the query and user memory
trackers blocked, like DateLUT does. The server memory limit still applies.

Also document that `SELECT` on `system.query_masking_rules` is enough to read
it when `select_from_system_db_requires_grant` is enabled.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… stored

The notification handler of QueryMaskingRulesCache blocked only the query and
user memory trackers, so with `min_allocation_size_to_throw_on_memory_limit`
set, the server memory limit could still refuse an allocation while the masker
was rebuilt. AccessChangesNotifier only logs a handler exception, so
CREATE QUERY MASKING RULE reported success while the stored rule was not
applied. When the refusal hit RE2 in the middle of compiling a rule, RE2
aborted the server (`walker-inl.h:151 Stack not empty`).

Reproduced with `max_server_memory_usage` 1 GiB,
`min_allocation_size_to_throw_on_memory_limit` 70000, 24 rules of
`[A-M]{1000}` x 20 and a Memory table holding the server 1-3 MiB below its
limit: the CREATE succeeded, the secret reached the server exception in
plaintext, and `sendNotifications` logged `Code: 241 (total) memory limit
exceeded` from `re2::Prog::Flatten`. With 5 MiB left the server aborted.

The handler now blocks the trackers at the global level, as SymbolIndex and
ColumnsCache do for structures that outlive a query: the server tracker still
accounts for the rules, but no limit refuses them. The block also covers the
update of the rule map, so the handler cannot stop between receiving a change
and publishing it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
QueryMaskingRulesCache now subscribes and reads all rules in a lazy
ensureAllRulesRead(), like RowPolicyCache and SettingsProfilesCache,
instead of being reloaded by hand from addDiskStorage and
addReplicatedStorage. SensitiveDataMasker is used from server start for
every log line and exception, before any storage exists, so the read is
triggered once after setup: at the end of
AccessControl::setupFromMainConfig and in LocalServer::setupUsers.
An unreadable rule still stops startup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 7, 2026

Copy link
Copy Markdown
Collaborator Author

One more point that needs your decision: BACKUP TABLE system.query_masking_rules writes the REGEXP in plaintext for a user who has only BACKUP on that table and FILE, although that user gets ACCESS_DENIED for SELECT from the table and for SHOW CREATE. This is how every access entity is backed up today: with the same grants, a backup of system.users contains the password hashes. #126028, on the other hand, made exporting system.named_collections require the rights to read the secrets.

Should I (A) keep the access-entity behaviour, or (B) require QUERY MASKING RULE ADMIN plus the rights to display secrets for this export, like named collections?

@pufit

pufit commented Nov 7, 2026

Copy link
Copy Markdown
Member

Let's keep A

@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d3927f2

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. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (amd_tsan) / Hung check failed, possible deadlock found hung query, not from this PR (no window function code in the diff): a server-side AST fuzzer variant of 03711_contingency_window_function computes contingency(number, number) OVER (ORDER BY number ROWS BETWEEN 7 PRECEDING AND UNBOUNDED FOLLOWING) over numbers(100000), which rebuilds the aggregate state for every row in AggregateWindowFunctionRecalculate::evaluate; it was still running 1936 s after it was cancelled a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR praktika rollups of the row above a fix task is created (investigating at full effort, fixing-PR link to follow here)
Sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20261108-030003

@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

About the Stress test (amd_tsan) hung check row of the ledger above: I am not opening a fix for it. Window functions evaluate each batch without cancellation checks by design (see WindowTransform::computeReadyRows), so this query keeps running until its batch ends. It is not caused by this PR, and this PR needs no change for it.

@groeneai

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Stress test (amd_tsan) / Hung check failed, possible deadlock found row of the ledger above: #130328 (external, open). It replaces my comment above that said no fix was needed.

groeneai and others added 2 commits November 22, 2026 13:51
…ules

# Conflicts:
#	src/Common/ErrorCodes.cpp
#	tests/queries/0_stateless/01271_show_privileges.reference
Master enabled clang-tidy modernize-use-nodiscard, so Build (arm_tidy)
failed on the new QueryMaskingRule, InterpreterCreateQueryMaskingRuleQuery
and ParserCreateQueryMaskingRuleQuery headers. Mark the flagged overrides
like their siblings (Role, InterpreterCreateQuotaQuery,
ParserCreateRoleQuery).

Also state in the SHOW QUERY MASKING RULES doc that SELECT on
system.query_masking_rules suffices when
select_from_system_db_requires_grant is enabled: the statement is
rewritten into a SELECT from that table, whose access check accepts it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch was successfully deployed

1 active (outdated) deployment
staging - docs — 6c5f2809 Deployed Nov 5, 2026 by mintlify[bot]
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-rbac Authorization: roles, grants, quotas, row-level security, access checks. pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

enable query_masking_rules in DDL statements

3 participants