Repository navigation
Conversation
timothyw553
left a comment
There was a problem hiding this comment.
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" |
There was a problem hiding this comment.
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?
| return; | ||
| } | ||
| try (Statement statement = connection.createStatement()) { | ||
| statement.executeUpdate( |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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();There was a problem hiding this comment.
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.
|
Thanks for tracking this down. The lock contention comes from jdbc-adapter: it created Fixed in apache/casbin-jcasbin-jdbc-adapter@b504565: when Once this is in a jdbc-adapter release, the |
|
@hsluoyz Yeah, we can remove our index setup when we upgrade to an adapter release containing your fix. We still need Tracking the adapter upgrade and index cleanup in #2356. |
|
/review |
yili-db
left a comment
There was a problem hiding this comment.
[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-refreshis enabled. With it disabled, a newly promoted admin on another server stays denied.
| protected void migrate() throws SQLException { | ||
| try { | ||
| super.migrate(); | ||
| ensureOwnerLookupIndex(conn); |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
[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?
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
[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?
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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.
| 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: |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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)"); |
There was a problem hiding this comment.
[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?
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
[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?
There was a problem hiding this comment.
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)", |
There was a problem hiding this comment.
[AI Assisted] Nit: this SpEL string is repeated outside the annotation style used elsewhere. A shared constant would keep it in one place.
There was a problem hiding this comment.
I kept the single admin check inline. This change uses the existing evaluator to refresh and retry. Extracting a shared constant can stay separate.
|
@yili-db The PR description now states that refreshing permissions from another server requires |
Signed-off-by: Timothy Wang <[email protected]>
Signed-off-by: Timothy Wang <[email protected]>
Signed-off-by: Timothy Wang <[email protected]>
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]>
|
/review |
c171fdf to
6278bd6
Compare
|
/review |
yili-db
left a comment
There was a problem hiding this comment.
[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]>
|
/review |
🥞 Stacked PR
Use this link to review incremental changes.
PR Checklist
docsis updatedDescription 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 COMMITTEDand an index on permission lookups. The owner field andOWNERgrants still change in one database transaction. The admin check uses the existing refresh and retry path. Refreshing grants from another server requiresserver.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: