Repository navigation
Conversation
`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]>
…on and backup 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]>
Preview approval requiredThis pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit |
Internal second-model review (rounds 1-3): 3 findings fixed, 2 not changed
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20261102-214900 |
|
cc @pufit @vitlibar, could you review this and add the |
|
Workflow [PR], commit [89f9e68] Summary: ❌
AI ReviewSummaryThis PR adds SQL-managed query masking rules backed by access storage, with a dedicated privilege, introspection, replication, and backup/restore support. Reviewed head Findings❌ Blockers
Tests
Final VerdictStatus: ❌ 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. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes129 object files changed (+483.68 KiB total), 6 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units1121 translation units recompiled, 7589 s compile time in total, 1114 of them have a recent master baseline. Translation units without a recent master baseline:
|
… 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]>
|
Resolved the conflict by merging master in ab471f8 (both sides added an One more commit, 4ca4f81, corrects the This PR and my #129033 each add an |
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
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
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(); |
There was a problem hiding this comment.
❌ 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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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.
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]>
|
One more point that needs your decision: Should I (A) keep the access-entity behaviour, or (B) require |
|
Let's keep A |
CI finish ledger - d3927f2Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261108-030003 |
|
About the |
|
Fixing PR for the |
…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]>
Closes: #128251
Changelog category (leave one):
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 RULESand thesystem.query_masking_rulestable. Like the rules of thequery_masking_rulesserver 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 thereplicateduser directory, included in backups ofsystem.query_masking_rules), are applied after the rules from the configuration, and are managed with the newQUERY MASKING RULE ADMINprivilege. TheREGEXPis 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.SensitiveDataMaskernow 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.QueryMaskingRulesCacheinAccessControlpublishes the SQL rules, ordered by name, on every change and after a disk or replicated storage is added (their initial load sends no notification).REGEXP, or aREPLACEthat 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 ofAccessType; #116757 widens the type.Validation: a new stateless test (masking of logs,
query_logand 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]