Repository navigation
[Server] Fix ownership transfer locking and admin refresh #2313
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
90634d2
e84b814
f507880
6278bd6
0bd8cac
87fd74e
3bd32ef
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -12,7 +12,10 @@ | |
| import java.lang.reflect.Proxy; | ||
| import java.nio.charset.StandardCharsets; | ||
| import java.sql.Connection; | ||
| import java.sql.DatabaseMetaData; | ||
| import java.sql.ResultSet; | ||
| import java.sql.SQLException; | ||
| import java.sql.Statement; | ||
| import java.util.Arrays; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
|
|
@@ -72,6 +75,9 @@ public class JCasbinAuthorizer implements UnityCatalogAuthorizer, AutoCloseable | |
| private static final int PRIVILEGE_INDEX = 2; | ||
|
|
||
| private static final String HIERARCHY_POLICY = "g2"; | ||
| private static final String OWNER_LOOKUP_INDEX = "idx_casbin_rule_resource"; | ||
| private static final String OWNER_LOOKUP_INDEX_SQL = | ||
| "CREATE INDEX " + OWNER_LOOKUP_INDEX + " ON casbin_rule (ptype, v1, v2)"; | ||
| private static final int HIERARCHY_PARENT_INDEX = 0; | ||
| private static final int HIERARCHY_CHILD_INDEX = 1; | ||
|
|
||
|
|
@@ -80,6 +86,21 @@ public JCasbinAuthorizer( | |
| throws Exception { | ||
| this.adapter = | ||
| new JDBCAdapter(autocommitOnCheckout(hibernateConfigurator.getDataSource())) { | ||
| @Override | ||
| protected void migrate() throws SQLException { | ||
| try { | ||
| super.migrate(); | ||
| ensureOwnerLookupIndex(conn); | ||
| } catch (SQLException | RuntimeException e) { | ||
| try { | ||
| conn.close(); | ||
| } catch (SQLException closeError) { | ||
| e.addSuppressed(closeError); | ||
| } | ||
| throw e; | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| protected void retry(ExecutionContext<Void> context) throws SQLException { | ||
| // The adapter replaces this connection without returning it to the pool. | ||
|
|
@@ -109,6 +130,47 @@ protected void retry(ExecutionContext<Void> context) throws SQLException { | |
| } | ||
| } | ||
|
|
||
| /** The adapter owns casbin_rule outside the Unity Catalog schema migrations. */ | ||
| private static void ensureOwnerLookupIndex(Connection connection) { | ||
| try { | ||
| if (hasOwnerLookupIndex(connection)) { | ||
| return; | ||
| } | ||
| try (Statement statement = connection.createStatement()) { | ||
| statement.executeUpdate(OWNER_LOOKUP_INDEX_SQL); | ||
| } | ||
| } catch (SQLException e) { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [AI Assisted] If the recheck throws, the original
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 |
||
| // Another server may have created the index after the metadata check. | ||
| try { | ||
| if (hasOwnerLookupIndex(connection)) { | ||
| return; | ||
| } | ||
| } catch (SQLException recheckError) { | ||
| e.addSuppressed(recheckError); | ||
| } | ||
| LOGGER.warn( | ||
| "Could not verify or create the permission lookup index. Ownership transfers may block" | ||
| + " unrelated grants and revokes. Ask a database administrator to run: {}", | ||
| OWNER_LOOKUP_INDEX_SQL, | ||
| e); | ||
| } | ||
| } | ||
|
|
||
| private static boolean hasOwnerLookupIndex(Connection connection) throws SQLException { | ||
| DatabaseMetaData metadata = connection.getMetaData(); | ||
| String table = metadata.storesUpperCaseIdentifiers() ? "CASBIN_RULE" : "casbin_rule"; | ||
| try (ResultSet indexes = | ||
| metadata.getIndexInfo( | ||
| connection.getCatalog(), connection.getSchema(), table, false, false)) { | ||
| while (indexes.next()) { | ||
| if (OWNER_LOOKUP_INDEX.equalsIgnoreCase(indexes.getString("INDEX_NAME"))) { | ||
| return true; | ||
| } | ||
| } | ||
| } | ||
| return false; | ||
| } | ||
|
|
||
| /** | ||
| * jdbc-adapter 2.7.0 calls {@link DataSource#getConnection()} once and holds it. Force autocommit | ||
| * on that checkout so {@code loadPolicy} does not leave Postgres/MySQL idle-in-transaction. | ||
|
|
@@ -151,7 +213,7 @@ private SyncedEnforcer newEnforcer() { | |
| * caller must reload the live authorizer after commit. | ||
| */ | ||
| public static List<UUID> replaceOwner(Session session, UUID resource, UUID newOwner) { | ||
| // A locking read sees the latest committed owners under MySQL REPEATABLE READ too. | ||
| // Owner-update transactions use READ_COMMITTED to avoid MySQL gap locks. | ||
| List<UUID> oldOwners = | ||
| session | ||
| .createNativeQuery( | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -20,6 +20,7 @@ | |
| import io.unitycatalog.server.utils.IdentityUtils; | ||
| import io.unitycatalog.server.utils.NormalizedURL; | ||
| import io.unitycatalog.server.utils.ValidationUtils; | ||
| import java.sql.Connection; | ||
| import java.util.ArrayList; | ||
| import java.util.Date; | ||
| import java.util.List; | ||
|
|
@@ -216,7 +217,10 @@ public CatalogInfo updateCatalog( | |
| session); | ||
| }, | ||
| "Failed to update catalog", | ||
| /* readOnly= */ false); | ||
| /* readOnly= */ false, | ||
| updateCatalog.getOwner() == null | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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.
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. |
||
| ? Optional.empty() | ||
| : Optional.of(Connection.TRANSACTION_READ_COMMITTED)); | ||
| } | ||
|
|
||
| public List<DeletedResource> deleteCatalog(String name, boolean force) { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -44,6 +44,22 @@ public static <R> R executeWithTransaction( | |
| sessionFactory, operation, errorMessage, readOnly, Optional.empty()); | ||
| } | ||
|
|
||
| /** | ||
| * Rolls back any implicit transaction and sets isolation. Call before starting a transaction or | ||
| * changing data. The pool restores isolation when the connection returns. | ||
| */ | ||
| public static void setIsolationLevel(Session session, int isolationLevel) { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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?
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. |
||
| // Without autocommit, a pooled connection may carry an open implicit transaction. H2 applies | ||
| // the isolation change to the NEXT transaction, so that transaction must end first. | ||
| session.doWork( | ||
| connection -> { | ||
| if (!connection.getAutoCommit()) { | ||
| connection.rollback(); | ||
| } | ||
| connection.setTransactionIsolation(isolationLevel); | ||
| }); | ||
| } | ||
|
|
||
| /** | ||
| * Executes a database operation with transaction management and optional custom isolation level. | ||
| * | ||
|
|
@@ -84,22 +100,8 @@ public static <R> R executeWithTransaction( | |
| session.setDefaultReadOnly(true); | ||
| } | ||
|
|
||
| // Set the custom isolation level if specified. Hikari resets it when the connection returns | ||
| // to the pool. | ||
| // IMPORTANT: without autocommit, a pooled connection may carry an open implicit transaction | ||
| // from its prior use. H2's setTransactionIsolation() takes effect for the NEXT transaction, | ||
| // not the current implicit one, so that transaction has to end first or REPEATABLE_READ | ||
| // reads can see stale data from before the connection was returned to the pool. MySQL and | ||
| // PostgreSQL reject rollback() on an autocommit connection, so only roll back when there is | ||
| // something to end. | ||
| if (isolationLevel.isPresent()) { | ||
| session.doWork( | ||
| connection -> { | ||
| if (!connection.getAutoCommit()) { | ||
| connection.rollback(); | ||
| } | ||
| connection.setTransactionIsolation(isolationLevel.get()); | ||
| }); | ||
| setIsolationLevel(session, isolationLevel.get()); | ||
| } | ||
|
|
||
| Transaction tx = session.beginTransaction(); | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -5,17 +5,18 @@ | |
| import io.unitycatalog.server.auth.decorator.KeyMapper; | ||
| import io.unitycatalog.server.auth.decorator.ResultFilter; | ||
| import io.unitycatalog.server.auth.decorator.UnityAccessDecorator; | ||
| import io.unitycatalog.server.auth.decorator.UnityAccessEvaluator; | ||
| import io.unitycatalog.server.exception.BaseException; | ||
| import io.unitycatalog.server.exception.ErrorCode; | ||
| import io.unitycatalog.server.model.SecurableType; | ||
| import io.unitycatalog.server.persist.MetastoreRepository; | ||
| import io.unitycatalog.server.persist.Repositories; | ||
| import io.unitycatalog.server.persist.UserRepository; | ||
| import io.unitycatalog.server.persist.model.DeletedResource; | ||
| import io.unitycatalog.server.persist.model.Privileges; | ||
| import io.unitycatalog.server.utils.IdentityUtils; | ||
| import io.unitycatalog.server.utils.ServerProperties; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.UUID; | ||
| import java.util.concurrent.atomic.AtomicBoolean; | ||
| import java.util.function.Function; | ||
|
|
@@ -32,6 +33,7 @@ public abstract class AuthorizedService { | |
| protected final KeyMapper keyMapper; | ||
| protected final ServerProperties serverProperties; | ||
| private final MetastoreRepository metastoreRepository; | ||
| private final UnityAccessEvaluator accessEvaluator; | ||
|
|
||
| @SneakyThrows | ||
| protected AuthorizedService( | ||
|
|
@@ -43,6 +45,8 @@ protected AuthorizedService( | |
| this.keyMapper = repositories.getKeyMapper(); | ||
| this.serverProperties = serverProperties; | ||
| this.metastoreRepository = repositories.getMetastoreRepository(); | ||
| this.accessEvaluator = | ||
| new UnityAccessEvaluator(authorizer, serverProperties.isStrictPrivilegeChecksEnabled()); | ||
| } | ||
|
|
||
| /** Views, functions, and models can be transferred to another user only by a metastore admin. */ | ||
|
|
@@ -58,11 +62,11 @@ protected boolean canTransferOwnerTo(String newOwner) { | |
| return newOwner == null | ||
| || !serverProperties.isAuthorizationEnabled() | ||
| || newOwner.equals(IdentityUtils.findPrincipalEmailAddress()) | ||
| || authorizer.authorize( | ||
| || accessEvaluator.evaluate( | ||
| userRepository.findPrincipalId(), | ||
| SecurableType.METASTORE, | ||
| metastoreRepository.getMetastoreId(), | ||
| Privileges.OWNER); | ||
| "#authorize(#principal, #metastore, OWNER)", | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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.
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. |
||
| Map.of(SecurableType.METASTORE, metastoreRepository.getMetastoreId()), | ||
| Map.of()); | ||
| } | ||
|
|
||
| /** Reloads after a commit attempt, including an uncertain commit or failed session cleanup. */ | ||
|
|
||
There was a problem hiding this comment.
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.mdand 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.
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.