Skip to content

fix: prevent table rename from bypassing role row filters - #29186

Merged
XuPeng-SH merged 15 commits into
matrixorigin:mainfrom
iamlinjunhong:fix/29133-role-rule-rename
Oct 14, 2026
Merged

XuPeng-SH merged 15 commits into
matrixorigin:mainfrom
iamlinjunhong:fix/29133-role-rule-rename

Conversation

@iamlinjunhong

@iamlinjunhong iamlinjunhong commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #29133

What this PR does / why we need it:

  • Add shared admission for ALTER TABLE ... RENAME TO and RENAME TABLE.
  • Lock mo_catalog.mo_role_rule, establish a logtail freshness barrier, and check current-account rewrite metadata before any rename mutation.
  • Reject renames conservatively when role rewrite rules exist, including cluster-table and chained rename paths.
  • Invalidate role-rule caches for all active sessions on the CN after a successful role-rule or role drop.
  • Keep session-owned temporary-table renames on their existing DDL path.
  • Add compiler, two-CN lock-concurrency, and distributed access-control regression coverage.

Root cause

Role rewrite rules are persisted by <database>.<table> name and retain raw SQL. Table rename execution updated relation and foreign-key metadata but did not coordinate with that name-keyed catalog, leaving a stale rule that could bypass filtering when remap hints were enabled.

Validation

  • go test ./pkg/sql/parsers ./pkg/sql/compile ./pkg/frontend
  • go test ./pkg/frontend -run 'TestInvalidateRoleRuleCachesAcrossSessions|TestProperty10_CacheInvalidation' -count=1
  • go test ./pkg/sql/compile -run 'TestRoleRuleRenameAdmissionProtocol' -count=1
  • go test ./pkg/tests/issues -run '^TestIssue29133RenameAdmissionSerializesRoleRuleWrite$' -count=1 -v
  • make build
  • Same MatrixOne service instance, normal mo-tester comparison of test/distributed/cases/zz_accesscontrol/role_rule.sql: run 1 passed 260/260 statements; teardown counts for users, roles, rules, tables, and databases were all 0; run 2 passed 260/260 with the same teardown counts.

The accepted mitigation intentionally blocks table renames for accounts with role rewrite rules until a dependency-safe migration exists; it does not repair rules made stale by older renames.

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@matrix-meow matrix-meow added the size/L Denotes a PR that changes [500,999] lines label Sep 21, 2026
@iamlinjunhong
iamlinjunhong force-pushed the fix/29133-role-rule-rename branch from d9b90a5 to 0edfbce Compare September 21, 2026 11:52

@XuPeng-SH XuPeng-SH left a comment

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.

Deep review (gpt-6-astra medium, exact head 0edfbce).\n\nREQUEST_CHANGES.\n\nP1 — Rename admission uses a different rule-key identity from rewrite execution.\n\nAt pkg/sql/compile/alter.go:2052-2059, admission compares lower(rule_name) with source/destination names. Rewrite execution instead calls NormalizeRewriteKey, which trims whitespace separately from database and table components. Quoted identifiers preserve whitespace, and ADD RULE persists the target key without canonicalizing it.\n\nReachable witness:\n\nALTER ROLE r ADD RULE\n 'select * from db.t where id = 1'\n ON TABLE db.t;\n\nALTER TABLE db.t RENAME TO db.t2;\n\nThe persisted key is db.t. Rewrite execution canonicalizes it to db.t and applies the filter before rename, but admission checks only db.t/db.t2, permits the rename, and subsequent queries against db.t2 can expose rows without the rewrite rule. RENAME TABLE shares the same bypass.\n\nMake admission use the same canonical identity as execution, including existing noncanonical persisted rows, and add public regressions for both rename entry points that assert rejection and preserved filtering.\n\nAll changed closures, lock/barrier ordering, batch preflight, chained/cluster rename paths, cleanup, and exact-head CI were reviewed. No additional blocker was found.

@XuPeng-SH XuPeng-SH left a comment

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.

Supplemental force-again review (gpt-6-astra medium, exact head 0edfbce).\n\nREQUEST_CHANGES.\n\nThe P1 remains confirmed: rename admission compares lower(rule_name) directly, while rewrite execution uses NormalizeRewriteKey and trims whitespace from database/table components. ADD RULE can persist a quoted noncanonical key such as db.t. Execution treats it as db.t, but admission checks only db.t/db.t2 and permits ALTER TABLE RENAME TO or RENAME TABLE. Subsequent reads of db.t2 can bypass the role filter.\n\nThis is an existing persisted-row compatibility issue; normalizing only future writes is insufficient. Make admission use the same execution-equivalent identity and add both rename-entry-point regressions with the noncanonical key. Current two-CN/concurrency tests use canonical keys and do not close this case.

@XuPeng-SH XuPeng-SH left a comment

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.

Deep review verdict: REQUEST_CHANGES on b1e590703a06cd2630efe36ff29d744ae516c17b. Performed directly without subagents.

[P1] Do not treat an old SI snapshot as proof that no role rule exists

pkg/sql/compile/alter.go:2103

hasRoleRules runs through runSqlWithResultAndOptions using the caller transaction. For a supported REPEATABLE READ transaction opened before an administrator adds a rule, this query still sees no mo_role_rule rows, so the new non-RC branch returns without the lifecycle lock or freshness barrier. A real restricted-user probe with only SELECT and ALTER TABLE privileges reproduces: BEGIN/SELECT t pins the old snapshot; another session commits the rule; direct SELECT now sees1row; ALTER TABLE t RENAME TO t2 in the old transaction succeeds and, after COMMIT, t2 exposes both rows. RC and fresh-SI controls reject the rename. Preserve no-rule compatibility only with a current, serialized admission proof or reject the unsafe transaction mode; an empty historical snapshot is insufficient. Add this public old-SI/committed-writer regression. Standalone RENAME TABLE is rejected in the tested controls and is not claimed affected.

Validation and scope:

Exact-head public MySQL probe uses a restricted user with SELECT and ALTER TABLE privileges. An old REPEATABLE READ transaction pins a pre-rule snapshot; the administrator commits a rule; fresh restricted SELECT returns1 row; ALTER TABLE RENAME in the old transaction succeeds and the renamed table exposes2 rows after commit. Five nearest controls pass, including RC and fresh-SI rejection and standalone RENAME TABLE rejection. The six-scenario probe exits1 and cleans up users, roles, transactions and database. All14changed files/hunks were reviewed; production +479/-32, tests/BVT +868/-8, docs0.

Comment thread pkg/sql/compile/alter.go Resolved

@XuPeng-SH XuPeng-SH left a comment

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.

Deep review: REQUEST_CHANGES at 6f214b989e07be83425ddf95aa5f35b0a9358bf1 (merge-base aee2a0b3764781a8ca908618548dfef75e336263). Reviewed directly, without subagents.

[P1] Fence an in-flight cache load when invalidating another session's role rules.

The new cross-session invalidator only sets ruleCache = nil under ruleCacheMu (rewrite_rule.go:1302-1305). Its consumer, captureRewritePolicy (lines 138-157), deliberately performs loadRuleCache outside that mutex, then publishes the returned map whenever the cache is nil. This permits the following ordering on the same CN:

  1. Session A has an unloaded cache and reads the old empty/weaker rule set from mo_role_rule; it has not yet published that result.
  2. Session B commits ALTER ROLE ... ADD RULE with a new restrictive filter. Its deferred invalidation completes for A and the DDL returns success.
  3. A resumes, sees the nil cache left by invalidation, and installs its pre-commit result. Subsequent COM_QUERY / COM_STMT_PREPARE policy captures use that non-nil stale map without another catalog read.

This is a lost invalidation, not an unprotected-map data race or merely a statement that started before the rule change. Later requests can continue to expose rows excluded by the committed mandatory rule. The rule lifecycle table lock protects the writers/rename admission; loadRuleCache does not participate in that protocol, and no cache generation/TTL closes publication after invalidation. This finding comes from the traced production ordering; I did not run a local SQL reproduction of the interleaving.

Coordinate invalidation with the existing cache loader/publication owner so a result loaded before invalidation cannot become the current cache. Add a deterministic test that holds the actual loader after reading old metadata, completes the other session's mutation/invalidation, resumes it, then checks the next request's filtering. The new TestInvalidateRoleRuleCachesAcrossSessions only invalidates already populated maps; it cannot exercise this ordering.

Earlier review findings. The stale-SI rename bypass is closed: non-pessimistic/non-RC renames now fail before the historical existence query, and the unsafe compatibility branch and its optimistic-success oracle were removed. Current CI explicitly passes the new stale-SI subcase. The conservative account-rule existence check also closes the old canonical-key and indirect allowlist-dependency bypasses. Both rename entry points preflight before mutation; the waiting ADD RULE resolves its target only after the shared lock/barrier, covering rename-first as well as writer-first. Commit errors flow through the named return, rollback and cache-preservation path. The previous same-instance BVT evidence is recorded in the PR; this review is not reopening that resolved evidence request. The old inline SI thread remains marked unresolved on GitHub, but its cited code problem is fixed.

Design, quality and performance. Full 15-file change map: production +462/-32, tests/BVT +902/-10, docs 0. This is a corrective security/lifecycle fix, not a new feature requiring a design document. Lock ownership stays with the transaction; the existing lock refresh and applied-logtail barrier are reused, with context cancellation reaching the actual waits. The batch admission flag is reset by the Scope pool. The conservative restrictions on cluster-table and non-RC rename are explicit compatibility costs. Rename/rule DDL adds lock/barrier/catalog work; rule mutations also enumerate all active CN sessions and invalidate unrelated tenants' caches, so their cost is O(active sessions) plus subsequent reloads. No TP benchmark or quantitative TPS/P99 claim is established.

Non-blocking cleanup: NormalizeRewriteKeyParts now has only NormalizeRewriteKey as a caller after admission switched to a simple existence query; the separate exported abstraction and boundary-oriented comment no longer serve the original rename consumer. The production wrapper and hook implementation also duplicate rename/temporary/cluster preflight. These can be simplified without adding another framework.

Evidence. Current-head CI 37882798889 checks out this exact SHA. Downloaded logs show complete UT success and all four TestIssue29133RenameAdmissionSerializesRoleRuleWrite scenarios passing (1.75s total), including stale SI and rename-first/waiting ADD. Pessimistic BVT reports zz_accesscontrol/role_rule.sql 260/260, zero failed/ignored/abnormal. Local diff whitespace validation passes. Green race/SQL checks do not select the lost-invalidation interleaving above; that is the remaining blocker.

Comment thread pkg/frontend/rewrite_rule.go Resolved

@XuPeng-SH XuPeng-SH left a comment

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.

Deep re-review of f967266 against merge-base 8f48d6f. APPROVE. Reviewed directly, without subagents.

The last blocking comment is closed. captureRewritePolicy snapshots ruleCacheGeneration under ruleCacheMu, performs the catalog read outside the lock, and publishes only if the generation is unchanged. Both privilege-cache invalidation and role-rule invalidation increment that same generation under the same mutex. A load overtaken by invalidation retries instead of resurrecting an older policy. This extends the existing cache owner; it does not introduce a second policy authority or hold a session mutex across SQL I/O.

Independent counterexample validation on this exact head (Apple M4, Go 1.27.1, matching native prerequisites): TestCaptureRewritePolicyReloadsAfterInFlightInvalidation and TestInvalidateRoleRuleCachesAcrossSessions each PASS once under -race and then 100/100 repetitions. The new regression runs the real capture/load path with a catalog-result barrier. A reviewer-only overlay restoring the previous capture implementation makes the same test FAIL: it returns version=1 after version=2 was installed and the cache invalidated. The fixed implementation returns version=2, performs the required reload, and serves the next read from the refreshed cache. No tracked source was modified.

Historical comment closure: canonical/quoted rule keys, indirect rule-SQL dependencies, rename-first/waiting ADD RULE, writer-first admission, stale SI snapshots, successful-commit-only invalidation, cross-session invalidation and the previous BVT cleanup/reuse requirement remain closed. Exact-head CI run 37981627126 has a successful frontend-containing light race stage; TestIssue29133RenameAdmissionSerializesRoleRuleWrite and all four ordering/isolation cases pass. Previously verified public SQL/cleanup evidence is reused where its behavior and fixture remain unchanged.

Design and unhappy paths: reviewed all 16 changed files and traced role-rule writers, both rename syntaxes, transaction finish/rollback, lock ownership, applied-logtail barrier and snapshot advancement, the scoped background-process hook, cache publication and pooled Scope reset. The existing transaction/lock/snapshot owners remain authoritative. Renames fail before mutation when the rule/isolation contract cannot be proved; multi-rename admission is checked before applying the batch. Locks end with the transaction, background executors close, and cancellation reaches the logtail wait. No additional wrong-result, hang, leak or unbounded retained-state failure was established.

Performance: rename and role-rule DDL acquire the lifecycle gate and refresh the snapshot; ordinary TP statements do not acquire that DDL gate. Cache hits retain the existing read-lock/clone path. A committed role-rule change invalidates the CN's active session caches, and a colliding load may repeat its metadata query; that cost is justified by policy correctness. No end-to-end TP throughput measurement is claimed. Existing small cleanup suggestions are not promoted into new blockers.

Increment: implementation 9 files +490/-44; tests/fixtures 7 files +1014/-10; documentation 0. Implementation, tests and documentation were assessed separately; this is an ordinary corrective security/lifecycle fix, not a new feature requiring another design framework. The test additions cover separate catalog, serialization and concurrency boundaries, including an independently failing old-implementation control.

@aunjgr aunjgr left a comment

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.

Reviewed f967266 against merge-base 8f48d6f. No blocking finding.

Both rename entry points admit the complete batch before mutation. Rename and frontend rule writers share the existing role-rule relation lock, followed by a TN-ordered applied-logtail barrier and current-transaction catalog decisions. A waiting ADD RULE rechecks target existence after admission; stale non-RC/optimistic and cluster-table renames fail closed, while session-owned temporary tables retain their existing route. The batch-admission flag is cleared by the Scope pool's full reset.

Rule/role changes invalidate local active-session caches only after successful transaction completion. The generation check prevents an in-flight pre-invalidation load from republishing its stale result. Background process hooks restore their prior owner, and statement/result/transaction cleanup remains with existing owners. The tests exercise both lock orderings, failure/non-advancement/cancellation, chained rename atomicity, stale snapshots and commit-failure cache preservation.

I accept the documented conservative account-wide rename restriction: raw rule SQL can depend on relations beyond its ON TABLE target, and dependency-safe migration is not implemented here. This does not repair already-stale rules, nor does CN-local invalidation establish a new cross-CN cache-consistency guarantee.

Validation: reviewed all changed hunks and reused the reported owning tests, two-CN deterministic lock regression, service build and twice-repeated access-control BVT with explicit teardown. Current-head CI passes. I did not independently rerun the native suite or perform contention/throughput measurements.

@aptend aptend left a comment

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.

Deep re-review: APPROVE at exact head f96726609ff31dcaf03b9acb96f1113e6ed87a7e, against declared base/merge-base 8f48d6fac04bf612be65ed1b44477ef9b32cb88f.

I read all 16 changed files/hunks, all 13 historical reviews, all PR conversation/inline comments and author replies, and both resolved-state/outdated-state thread records. I compared against my previous reviewed head 0edfbce70b74b7a6146d4aa292d50380ac95bdfc with a rebase-aware range-diff, then checked the full current change. No blocking finding remains.

Historical closure:

  • The canonical-key mismatch in my earlier review is closed by the conservative current-account rule-existence check, not by trusting author claims or only normalizing new writes. Any persisted rule blocks both rename entry points, including noncanonical legacy keys and rule-SQL dependencies outside the ON TABLE target.
  • The complete RENAME TABLE batch is admitted before mutation. ALTER TABLE follows the same gate. Cluster-table and unsupported optimistic/SI transactions fail closed; session-owned temporary-table renames keep their existing path.
  • Rename and ADD/DROP RULE/DROP ROLE share the existing transaction-owned relation lock, followed by TN-ordered applied-logtail freshness and snapshot advancement. A waiting ADD RULE resolves its target after that gate, so rename-first cannot publish the demonstrated stale target rule. Old SI snapshots are rejected before the existence query.
  • Successful transaction completion precedes CN-local cache invalidation; commit failures are returned and preserve the cache. The generation fence and both invalidators share ruleCacheMu, so a load overtaken by invalidation cannot republish its old result. The two threads remain unresolved in GitHub, but their cited implementation defects are closed; I have not changed thread resolution.

Change/risk map: R3 rename/writer serialization and security admission; R3 cache invalidation/publication and session ownership; R1 identifier-helper extraction preserving comparison semantics; R2/R3 focused UT, two-CN ordering and public SQL/cleanup regressions. This is a corrective security/lifecycle fix, not a new feature/major refactor requiring a design artifact. Contract, concurrency, liveness, resource, compatibility/security, performance and test lenses were applied to their relevant closures. No new wire/disk format, generated consumer, native dependency or build-tag contract is introduced.

Unhappy-path check Closure
Q1 ownership Transactions own locks through commit/rollback; background executors/results and temporary hooks reach existing close/restore owners; pooled Scope reset clears batch admission.
Q2 termination Lock and applied-logtail/snapshot waits use the owning context; barrier errors, cancellation and non-advancement reject before mutation. Cache SQL loading occurs outside the session cache mutex.
Q3 retained state Session cache replacement and discarded load results remain GC-managed; session enumeration is a temporary snapshot of active sessions; no new retained worker/queue is added.

Validation:

  • Local Linux/amd64, Go 1.27.1, CPU release/SIMSIMD=0: top-level make -j2 cgo completed successfully with this worktree's native provenance. Repository-controlled mo-cgo-test wrapper used throughout; primary workspace unchanged.
  • Focused normal tests passed with non-empty named output: seven frontend roots covering drop-role, cache invalidation, real loader publication, concurrent cache access, successful ADD and commit failures; all three compile rename/admission roots (including eight protocol subcases); parser identifier-comparison modes 0/1/2. Diff whitespace and changed-Go gofmt checks passed.
  • TestIssue29133RenameAdmissionSerializesRoleRuleWrite passed locally under -race with all four ordering/isolation cases. Filtered go-test JSON measured the exact root at 10.14s including fixture startup; the 30s adaptive budget selects N=2. The separate exact-root -race -count=2 -timeout=240s run passed both repetitions and all eight subcase executions, exit 0.
  • Reused exact-head focused cache race evidence and old-implementation negative control documented in the independent review: both cache roots pass once and 100 repetitions; restoring old publication logic fails the same deterministic loader oracle. This is reused evidence, not a claim that I reran those 100 repetitions.
  • Verified CI run 37981627126 checks out this exact head and has terminal successful Ubuntu UT/race, SCA and shared-build results. Its issue-test log names all four cases. Skipped optional jobs are not counted as passes.
  • Downloaded compose execution artifact independently confirms normal comparison selected zz_accesscontrol/role_rule.sql: 266/266, zero failed/ignored/abnormal. The pessimistic artifact does not select this case; I do not claim that it passed there.
  • Reused the earlier same-instance 260/260 + 260/260 cleanup record specifically for the unchanged rename/rule teardown and reuse boundary. I compared the case to that revision: the later SQL changes add a base-side ordinary-view control and move db2 setup before target validation; the rename/rule scenarios and all five teardown postconditions are unchanged. The full current case has separate exact-head 266/266 evidence above. This is not a claim of two local exact-head 266-statement BVT runs.

Accepted scope/cost: the account-wide rename restriction is intentional until dependency-safe migration exists. This does not repair previously stale rules or establish cross-CN cache consistency. Rule DDL adds lock/barrier work and O(active CN sessions) invalidation/reloads; no throughput/P99 improvement or contention benchmark is claimed.

@mergify

mergify Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Queued — the merge queue status continues in this comment ↓.

@mergify

mergify Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-14 10:40 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-10-14 10:51 UTC · at 606b5253d68e752b0bc449be08e29edb912e655b

This pull request spent 11 minutes 10 seconds in the queue, with no time running CI.

Reason

Pull request #29186 has been dequeued

Pull request from fork cannot be queued. This pull request comes from a fork, and Mergify needs the author's permission to update its branch.

The author needs to enable "Allow edits from maintainers" on this pull request.

Hint

You should look at the reason for the failure and decide if the pull request needs to be fixed or if you want to requeue it.
If you do update this pull request, it will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue instead, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Waiting for any of
  • check-neutral = CI Required
  • check-skipped = CI Required
  • check-success = CI Required
All conditions

Tick the box to put this pull request back in the merge queue (same as @mergifyio queue).

  • Requeue this pull request

This branch was previously deployed

1 inactive deployment
ci — 606b5253 Deployed Oct 14, 2026 by mergify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dequeued size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: renaming a controlled table bypasses its row filter

5 participants