Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions docs/server/auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,20 @@ and grants. Set it back to `true` when the migration is complete.

Use the same value on every server instance. Restart each instance after changing it.

### Native policy storage

Casbin stores grants in `casbin_rule`. The server tries to add 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 setup fails, the server logs a
warning and continues to start. On MySQL, ownership transfers can still block unrelated grants and
revokes until the index exists. Ask a database administrator to run:

```sql
CREATE INDEX idx_casbin_rule_resource ON casbin_rule (ptype, v1, v2);
```

Use this exact index name and column order. The server checks the name alone.

### Multiple server instances

This section applies to Casbin. With OPA, `server.authorization.policy-refresh` does not change
Expand Down
9 changes: 9 additions & 0 deletions docs/server/upgrades.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,15 @@ connection pool, which needs at least 4 connections for that: with a smaller poo
`CREATE TABLE IF NOT EXISTS casbin_rule` at every start, so the database user needs the `CREATE` privilege (on
PostgreSQL, on the schema) while authorization is enabled.

Startup also tries to create the [permission lookup index](auth.md#native-policy-storage) if it is
missing. This requires `INDEX` on MySQL and ownership of `casbin_rule` on PostgreSQL. If setup fails,
the server logs a warning and continues. On MySQL, ownership transfers can still block unrelated
grants and revokes until a database administrator creates the index using the SQL in the auth guide.

On PostgreSQL, index creation blocks writes to `casbin_rule` while it runs. This can pause grants
and revokes on running instances during a rolling upgrade. A database administrator can create
the index before the upgrade during a maintenance window.

Two options of `bin/start-uc-server` check and change the schema. Neither starts the server. Both
exit with 0 when they succeed, and with 1 and the reasons when they refuse (see
[Messages](#messages)).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;

Expand All @@ -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);

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.

} 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.
Expand Down Expand Up @@ -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) {

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.

// 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.
Expand Down Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -216,7 +217,10 @@ public CatalogInfo updateCatalog(
session);
},
"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.

? Optional.empty()
: Optional.of(Connection.TRANSACTION_READ_COMMITTED));
}

public List<DeletedResource> deleteCatalog(String name, boolean force) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import io.unitycatalog.server.utils.IdentityUtils;
import io.unitycatalog.server.utils.JsonUtils;
import io.unitycatalog.server.utils.ValidationUtils;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
Expand Down Expand Up @@ -261,7 +262,8 @@ public FunctionInfo updateFunction(
return result;
},
"Failed to update function",
/* readOnly= */ false);
/* readOnly= */ false,
Optional.of(Connection.TRANSACTION_READ_COMMITTED));
}

public FunctionInfoDAO getFunctionDAO(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,12 @@
import io.unitycatalog.server.persist.utils.FileOperations;
import io.unitycatalog.server.persist.utils.PagedListingHelper;
import io.unitycatalog.server.persist.utils.RepositoryUtils;
import io.unitycatalog.server.persist.utils.TransactionManager;
import io.unitycatalog.server.utils.IdentityUtils;
import io.unitycatalog.server.utils.NormalizedURL;
import io.unitycatalog.server.utils.ServerProperties;
import io.unitycatalog.server.utils.ValidationUtils;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
Expand Down Expand Up @@ -402,6 +404,9 @@ public RegisteredModelInfo updateRegisteredModel(

Transaction tx;
try (Session session = sessionFactory.openSession()) {
if (updateRegisteredModel.getOwner() != null) {
TransactionManager.setIsolationLevel(session, Connection.TRANSACTION_READ_COMMITTED);
}
String[] parts = RepositoryUtils.parseRegisteredModelFullName(fullName);
String catalogName = parts[0];
String schemaName = parts[1];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,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.HashMap;
Expand Down Expand Up @@ -327,7 +328,10 @@ public SchemaInfo updateSchema(
return convertFromDAO(session, schemaInfoDAO, fullName);
},
"Failed to update schema",
/* readOnly= */ false);
/* readOnly= */ false,
updateSchema.getOwner() == null
? Optional.empty()
: Optional.of(Connection.TRANSACTION_READ_COMMITTED));
}

public List<DeletedResource> deleteSchema(String fullName, boolean force) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package io.unitycatalog.server.persist;

import static java.sql.Connection.TRANSACTION_READ_COMMITTED;
import static java.sql.Connection.TRANSACTION_REPEATABLE_READ;

import io.unitycatalog.server.delta.model.DeltaCommit;
Expand Down Expand Up @@ -1260,7 +1261,8 @@ public TableInfo updateTable(
result, TableInfo::setProperties, result.getTableId(), Constants.TABLE, session);
},
"Failed to update table owner",
/* readOnly= */ false);
/* readOnly= */ false,
Optional.of(TRANSACTION_READ_COMMITTED));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,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;
Expand Down Expand Up @@ -264,7 +265,10 @@ public VolumeInfo updateVolume(
return volumeInfo.toVolumeInfo(catalog, schema);
},
"Failed to update volume",
/* readOnly= */ false);
/* readOnly= */ false,
updateVolumeRequest.getOwner() == null
? Optional.empty()
: Optional.of(Connection.TRANSACTION_READ_COMMITTED));
}

public void deleteVolume(String name) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) {

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.

// 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.
*
Expand Down Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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(
Expand All @@ -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. */
Expand All @@ -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)",

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.

Map.of(SecurableType.METASTORE, metastoreRepository.getMetastoreId()),
Map.of());
}

/** Reloads after a commit attempt, including an uncertain commit or failed session cleanup. */
Expand Down
Loading
Loading