Skip to content

[Server] Fix ownership transfer locking and admin refresh - #2313

Merged
yili-db merged 7 commits into
unitycatalog:mainfrom
timothyw553:stack/ownership-transfer-followup-20261120
Nov 26, 2026
Merged

yili-db merged 7 commits into
unitycatalog:mainfrom
timothyw553:stack/ownership-transfer-followup-20261120

Conversation

@timothyw553

@timothyw553 timothyw553 commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

🥞 Stacked PR

Use this link to review incremental changes.


PR Checklist

  • A description of the changes is added to the description of this PR.
  • If there is a related issue, make sure it is linked to this PR.
  • If you've fixed a bug or added code that should be tested, add tests!
  • If you've added or modified a feature, documentation in docs is updated

Description of changes

Follow-up to #2149.

On MySQL, transferring ownership could block grants and revokes for unrelated objects. A newly promoted metastore admin could also be denied a transfer because the server checked cached permissions.

Ownership updates use READ COMMITTED and an index on permission lookups. The owner field and OWNER grants still change in one database transaction. The admin check uses the existing refresh and retry path. Refreshing grants from another server requires server.authorization.policy-refresh=true.

The server tries to create the index at startup. If this fails, it logs a warning with the setup SQL and continues. Transfers can still block unrelated grants and revokes until the index exists. See the setup and upgrade instructions. PostgreSQL index creation can pause permission writes on running instances during an upgrade.

Validation:

  • 108 focused ownership, HTTP, authorization refresh, and transaction checks passed on each of H2, MySQL 8, and PostgreSQL 18.
  • Concurrency tests cover catalogs, schemas, volumes, tables, functions, and models. All six cases fail on MySQL without the isolation fix.
  • Startup tests cover denied index creation, a failed metadata recheck, concurrent creation, and connection cleanup after core setup fails.
  • Java formatting and server main/test Checkstyle passed.

@timothyw553 timothyw553 left a comment

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.

overall this is a good improvement, i left a few comments mostly around MySQL gap locking and the new startup index requirement. also a couple small cleanup and test coverage questions.

session
.createNativeQuery(
"SELECT v0 FROM casbin_rule WHERE ptype = 'p' AND v1 = :resource AND"
"SELECT id, v0 FROM casbin_rule WHERE ptype = 'p' AND v1 = :resource AND"

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.

under MySQL REPEATABLE READ, SELECT ... FOR UPDATE still takes gap locks between index entries, so an unrelated grant landing in that gap can block while holding Casbin's write lock. in OwnershipRepositoryTest.java, MODIFY inserts between the seeded MANAGE and SELECT rows rather than next to the transferred OWNER row. should we use transaction-scoped Optional.of(Connection.TRANSACTION_READ_COMMITTED) in the owner-update transactions instead (like CredentialRepository does) and add a MySQL test covering an adjacent insert?

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.

return;
}
try (Statement statement = connection.createStatement()) {
statement.executeUpdate(

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.

creating this index at startup needs INDEX on MySQL and table ownership on PostgreSQL, otherwise startup fails. if we switch to READ COMMITTED do we still need mandatory index creation here? if we keep it, could we also update upgrades.md (which still only mentions CREATE) and add tests for denied creation, concurrent creation, and connection cleanup?

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.

Kept the index because an unrelated revoke still blocked without it, even when the transfer used READ COMMITTED. Added the required privileges and manual setup instructions to upgrades.md and auth.md. Tests now cover simultaneous creation and an injected SQL failure, including connection cleanup when close also fails.

.map(UUID::fromString)
.toList();
.getResultList();
// The JDBC adapter commits on a separate connection. Use this transaction for both writes.

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.

since the SELECT ... FOR UPDATE already holds the same locks, does deleting by id in a loop actually save anything over the original predicate delete? if not, could we go back to the List<String> query and single DELETE?

-    for (Tuple owner : owners) {
-      session
-          .createNativeMutationQuery("DELETE FROM casbin_rule WHERE id = :id")
-          .setParameter("id", owner.get("id", Number.class).longValue())
-          .executeUpdate();
-    }
+    session
+        .createNativeMutationQuery(
+            "DELETE FROM casbin_rule WHERE ptype = 'p' AND v1 = :resource AND v2 = :owner")
+        .setParameter("resource", resource.toString())
+        .setParameter("owner", Privileges.OWNER.getValue())
+        .executeUpdate();

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.

Reverted to the string query and a single predicate DELETE in bffa129. The owner field and OWNER grants still update in one transaction. Ownership, audit, and concurrency checks passed on H2, MySQL 8, and PostgreSQL 18.

@hsluoyz

hsluoyz commented Nov 21, 2026

Copy link
Copy Markdown

Thanks for tracking this down. The lock contention comes from jdbc-adapter: it created casbin_rule without any secondary index, so removePolicy / removeFilteredPolicy (DELETE ... WHERE ptype = ? AND vN = ?) scanned the whole table and, under MySQL's default REPEATABLE READ, locked every row and gap. I reproduced it on MySQL 8.4 with 2,000 rules: removing one object's grants blocked an insert for an unrelated object until the lock wait timed out.

Fixed in apache/casbin-jcasbin-jdbc-adapter@b504565: when autoCreateTable is on, the adapter now creates idx_<table>_v0 (ptype, v0, v1) and idx_<table>_v1 (ptype, v1, v2), also on existing tables, and skips them without failing startup if the database user lacks the privilege. With the index in place the unrelated insert no longer blocks.

Once this is in a jdbc-adapter release, the idx_casbin_rule_resource index this PR creates is redundant with idx_casbin_rule_v1, so you could drop that startup step. For keeping policies in sync across servers, jCasbin's watchers (for example the Redis watcher) are the intended mechanism.

@timothyw553
timothyw553 marked this pull request as ready for review November 23, 2026 21:49
@timothyw553

timothyw553 commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator Author

@hsluoyz Yeah, we can remove our index setup when we upgrade to an adapter release containing your fix. We still need READ COMMITTED: our MySQL test blocked an adjacent insert during an ownership transfer even with the index present. Watcher integration can stay in a separate change.

Tracking the adapter upgrade and index cleanup in #2356.

@yili-db

yili-db commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator

/review

@yili-db yili-db left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[AI Assisted] Changes needed for finding 1, the startup failure when the index cannot be created. The MySQL lock fix checks out: the new regression test fails on MySQL without READ_COMMITTED and passes with it.

Findings 2 to 6 are inline. Finding 7 has inline nits for (a) and (b). The item below is not anchored to a changed line:

  • Nit: the PR description says the admin check uses the existing permission refresh and retry path. Please say that it refreshes only when server.authorization.policy-refresh is enabled. With it disabled, a newly promoted admin on another server stays denied.

protected void migrate() throws SQLException {
try {
super.migrate();
ensureOwnerLookupIndex(conn);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[AI Assisted] Startup now fails when the database user cannot create the index. Casbin storage has been in released versions since v0.2.0, so an upgrade from a release where the user has CREATE but not INDEX (MySQL) or casbin_rule ownership (PostgreSQL) stops at startup even when no ownership transfer is ever made. The index only narrows row locks, so could we log a WARN with the SQL from docs/server/auth.md and keep starting? If we keep the hard failure, the upgrades doc needs to say the server will not start without the index.

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.

Updated in c171fdf. Index setup failure now logs a warning with the manual setup SQL and allows startup. The index is still needed to avoid the locking issue. Errors setting up the policy table still stop startup.

try (Statement statement = connection.createStatement()) {
statement.executeUpdate(
"CREATE INDEX " + OWNER_LOOKUP_INDEX + " ON casbin_rule (ptype, v1, v2)");
} catch (SQLException e) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[AI Assisted] If the recheck throws, the original CREATE INDEX error is lost, because the recheck exception replaces it. Could we attach the recheck failure with addSuppressed and rethrow the original, and add a case where metadata access also fails?

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.

The warning now logs the original creation error, with a failed metadata recheck attached through addSuppressed. The startup test covers both failures.

}

@Test
void transferringOwnerDoesNotBlockUnrelatedGrantsOrRevokes() throws Exception {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[AI Assisted] This only covers updateCatalog. I reverted the catalog isolation level locally and this test fails on MySQL 8 as intended. Could we parameterize it over the securable types that call updateOwner (schema, volume, table, function, model), so a missing isolation level fails on MySQL?

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.

The test now covers all six resource types. Each case fails with a MySQL lock timeout when the isolation setting is removed. All six pass with the fix on H2, MySQL 8, and PostgreSQL 18.

"Failed to update catalog",
/* readOnly= */ false);
/* readOnly= */ false,
updateCatalog.getOwner() == null

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[AI Assisted] The isolation rule is written four ways here: conditional on owner (catalog, schema, volume), unconditional (function, table), and hand-wired in model. Could one helper pick the level from the owner, used at each call site? Unconditional is functionally fine, but a shared rule would stop a new securable from missing it.

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.

I kept the existing transaction calls. Table and function PATCH requests always transfer ownership. Other updates have optional owners, and models use their existing transaction code. The new test checks all six paths.

Comment thread docs/server/auth.md Outdated
Casbin stores grants in `casbin_rule`. The server adds the index below at startup if it is missing.
The index limits the rows scanned by permission changes. Creating it requires the `INDEX` privilege
on MySQL and ownership of `casbin_rule` on PostgreSQL. If the server's database user lacks this
permission, ask a database administrator to create it before starting the server:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[AI Assisted] Please say that startup fails with the DDL error when the index is missing and the user cannot create it. Also note that the server matches the index by name only, so the columns must be (ptype, v1, v2) as written.

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.

The docs now state that index setup failure logs a warning and allows startup. They also specify the exact index name and (ptype, v1, v2) column order.

}
try (Statement statement = connection.createStatement()) {
statement.executeUpdate(
"CREATE INDEX " + OWNER_LOOKUP_INDEX + " ON casbin_rule (ptype, v1, v2)");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[AI Assisted] On PostgreSQL the startup CREATE INDEX blocks grants and revokes on casbin_rule while it builds, which matters during a rolling upgrade. Followup: could we note this in upgrades.md and open a tracking issue for CREATE INDEX CONCURRENTLY?

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.

I updated upgrades.md to explain the pause in grants and revokes during PostgreSQL index creation. Concurrent index creation stays outside this fix. #2356 tracks replacing our startup setup with the upstream adapter.

}

/** Sets isolation before a transaction begins. The pool restores it on connection return. */
public static void setIsolationLevel(Session session, int isolationLevel) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[AI Assisted] Nit: this Javadoc does not say that the method rolls back an open implicit transaction, which callers need to know. Could we extend it?

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.

The Javadoc now says that the method rolls back any implicit transaction and must run before a transaction starts or data changes.

SecurableType.METASTORE,
metastoreRepository.getMetastoreId(),
Privileges.OWNER);
"#authorize(#principal, #metastore, OWNER)",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[AI Assisted] Nit: this SpEL string is repeated outside the annotation style used elsewhere. A shared constant would keep it in one place.

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.

I kept the single admin check inline. This change uses the existing evaluator to refresh and retry. Extracting a shared constant can stay separate.

@timothyw553

Copy link
Copy Markdown
Collaborator Author

@yili-db The PR description now states that refreshing permissions from another server requires server.authorization.policy-refresh=true.

Warn with setup SQL instead of stopping startup when index setup fails.
Preserve the creation error if its metadata recheck also fails.
Cover locking through all six ownership update paths.
Document index setup limits and the isolation helper rollback.

Signed-off-by: Timothy Wang <[email protected]>
@yili-db

yili-db commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator

/review

@timothyw553
timothyw553 force-pushed the stack/ownership-transfer-followup-20261120 branch from c171fdf to 6278bd6 Compare November 24, 2026 23:31
@yili-db

yili-db commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator

/review

@yili-db yili-db left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[AI Assisted] Approve at 6278bd6. The startup blocker is fixed: index setup failure now logs a warning and startup continues. The MySQL lock fix is verified: with READ_COMMITTED removed at all six sites, the parameterized regression test fails for every securable type, and the focused tests pass on H2 and MySQL 8.

Non-blocking asks:

  • Docs: upgrades.md and auth.md say ownership transfers can block unrelated grants and revokes without naming MySQL. That blocking comes from MySQL gap locks; PostgreSQL row-level locks block only the same row. Please name MySQL in both.
  • Tests: ownershipTransferRefreshesNewAdminPrivileges covers only functions. Could it be parameterized over view and model, which share canTransferOwnerTo?

Follow-up:

  • Add a case with policy refresh disabled that stays denied, to lock in the documented limit.

Verify that transfers stay denied after a remote admin grant when policy refresh is disabled.
Name MySQL in the ownership transfer locking warnings.

Signed-off-by: Timothy Wang <[email protected]>
@yili-db

yili-db commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator

/review

@timothyw553 timothyw553 reopened this Nov 25, 2026
@yili-db
yili-db merged commit f59e83d into unitycatalog:main Nov 26, 2026
51 of 52 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants