Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#15412] fix(authz): resolve Semantic Model permissions before first publication (#15413)

mchades6b296151ae78
diff --git a/core/src/main/java/org/apache/gravitino/EntityStore.java b/core/src/main/java/org/apache/gravitino/EntityStore.java
index 72b52d1960..6eeb6213b6 100644
--- a/core/src/main/java/org/apache/gravitino/EntityStore.java
+++ b/core/src/main/java/org/apache/gravitino/EntityStore.java
@@ -39,6 +39,22 @@ import org.apache.gravitino.utils.Executable;
public interface EntityStore extends Closeable {
+ /**
+ * Resolves the stable ID of a Semantic Model identity, whether or not it has an active revision.
+ *
+ * <p>The default reads the model through {@link #get}. A store whose {@code get} returns only the
+ * active revision and that supports deferred publication must override this method, so that a
+ * model with only drafts still resolves.
+ *
+ * @param ident The Semantic Model identifier.
+ * @return The stable Semantic Model ID.
+ * @throws NoSuchEntityException If the Semantic Model or its namespace does not exist.
+ * @throws IOException If the lookup fails.
+ */
+ default long getSemanticModelId(NameIdentifier ident) throws IOException {
+ return get(ident, EntityType.SEMANTIC_MODEL, SemanticModelEntity.class).id();
+ }
+
/** Loads a retained Semantic Model snapshot or the latest saved revision. */
default SemanticModelEntity loadSemanticModelRevision(
NameIdentifier ident, SemanticModelRevisionSelector selector) throws IOException {
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java b/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java
index b79db9dbdd..0f6665f157 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java
@@ -318,6 +318,11 @@ public class JDBCBackend implements RelationalBackend, SupportsOrphanedRelationC
return TableMetaService.getInstance().getTableIdByIdentifier(identifier);
}
+ @Override
+ public long getSemanticModelId(NameIdentifier identifier) {
+ return SemanticModelMetaService.getInstance().getSemanticModelIdByIdentifier(identifier);
+ }
+
@Override
public <E extends Entity & HasIdentifier> E get(
NameIdentifier ident, Entity.EntityType entityType)
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/RelationalBackend.java b/core/src/main/java/org/apache/gravitino/storage/relational/RelationalBackend.java
index aa9e130ddd..88a8e2709c 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/RelationalBackend.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/RelationalBackend.java
@@ -60,6 +60,21 @@ public interface RelationalBackend
return get(identifier, Entity.EntityType.TABLE).id();
}
+ /**
+ * Resolves a Semantic Model ID from its identity, whether or not it has an active revision.
+ *
+ * <p>The default reads the active revision. A backend that supports deferred publication must
+ * override it so that a model with only drafts still resolves.
+ *
+ * @param identifier the full Semantic Model identifier
+ * @return the stable Semantic Model ID
+ * @throws NoSuchEntityException if the Semantic Model or its namespace does not exist
+ * @throws IOException if the lookup fails
+ */
+ default long getSemanticModelId(NameIdentifier identifier) throws IOException {
+ return this.<SemanticModelEntity>get(identifier, Entity.EntityType.SEMANTIC_MODEL).id();
+ }
+
/** Loads a retained Semantic Model snapshot or the latest saved revision. */
default SemanticModelEntity loadSemanticModelRevision(
NameIdentifier ident, SemanticModelRevisionSelector selector) throws IOException {
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java b/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java
index cb1a4343dd..f1e0f15b28 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java
@@ -262,6 +262,13 @@ public class RelationalEntityStore
return backend.listDescendantSchemas(identifier);
}
+ /** {@inheritDoc} */
+ @Override
+ public long getSemanticModelId(NameIdentifier ident) throws IOException {
+ // Semantic Models are not in the entity cache allowlist, so the identity row is always read.
+ return backend.getSemanticModelId(ident);
+ }
+
@Override
public SemanticModelEntity loadSemanticModelRevision(
NameIdentifier ident, SemanticModelRevisionSelector selector) throws IOException {
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetaService.java
index 7f302c75e4..b12549e1a4 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetaService.java
@@ -176,6 +176,20 @@ public class SemanticModelMetaService {
return fromSemanticModelPO(po, identifier.namespace());
}
+ /**
+ * Resolves a live Semantic Model ID from its identity row, including a model with only drafts.
+ *
+ * @param identifier The Semantic Model identifier.
+ * @return The stable Semantic Model ID.
+ * @throws NoSuchEntityException If the Semantic Model or its schema does not exist.
+ */
+ @Monitored(
+ metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+ baseMetricName = "getSemanticModelIdByIdentifier")
+ public long getSemanticModelIdByIdentifier(NameIdentifier identifier) {
+ return selectModel(identifier, identityOps).getSemanticModelId();
+ }
+
/** Checks for a live identity, including a model with only drafts. */
public boolean semanticModelExists(NameIdentifier identifier) {
try {
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestManagedSemanticModelOperationsJDBC.java b/core/src/test/java/org/apache/gravitino/catalog/TestManagedSemanticModelOperationsJDBC.java
index b87a371c98..9aa72dcf83 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestManagedSemanticModelOperationsJDBC.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestManagedSemanticModelOperationsJDBC.java
@@ -46,8 +46,11 @@ import org.apache.gravitino.Entity;
import org.apache.gravitino.GravitinoEnv;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
+import org.apache.gravitino.cache.CaffeineEntityCache;
+import org.apache.gravitino.cache.EntityCache;
import org.apache.gravitino.cache.NoOpsCache;
import org.apache.gravitino.exceptions.IllegalSemanticModelException;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.exceptions.NoSuchSemanticModelException;
import org.apache.gravitino.exceptions.NoSuchSemanticModelRevisionException;
import org.apache.gravitino.exceptions.OptimisticLockException;
@@ -450,6 +453,48 @@ public class TestManagedSemanticModelOperationsJDBC extends TestJDBCBackend {
assertArrayEquals(new int[] {2, 1}, revisionNumbers(operations, renamed));
}
+ @TestTemplate
+ void testDraftOnlyModelResolvesIdentityIdWithAndWithoutCache() throws Exception {
+ ManagedSemanticModelOperations deferred =
+ new ManagedSemanticModelOperations(
+ store, RandomIdGenerator.INSTANCE, (ident, definition) -> {}, ident -> false);
+ TableEntity source = createAndInsertTableEntity(modelIdent.namespace(), "orders");
+ SemanticModelEntity draft =
+ (SemanticModelEntity)
+ deferred.createSemanticModel(
+ modelIdent,
+ null,
+ definitionWithMetric(source, "order_count"),
+ Map.of(),
+ associations(source));
+ NameIdentifier missingModel = NameIdentifier.of(modelIdent.namespace(), "missing_model");
+ NameIdentifier missingSchema =
+ NameIdentifier.of(
+ modelIdent.namespace().level(0),
+ modelIdent.namespace().level(1),
+ "missing_schema",
+ modelIdent.name());
+
+ Config cacheConfig = new Config(false) {};
+ cacheConfig.set(Configs.CACHE_ENABLED, true);
+ CaffeineEntityCache caffeine = new CaffeineEntityCache(cacheConfig);
+ try {
+ for (EntityCache cache : List.of(new NoOpsCache(cacheConfig), caffeine)) {
+ FieldUtils.writeField(store, "cache", cache, true);
+ // Consumer reads see only the active revision, which a draft-only model does not have.
+ assertThrows(
+ NoSuchEntityException.class,
+ () ->
+ store.get(modelIdent, Entity.EntityType.SEMANTIC_MODEL, SemanticModelEntity.class));
+ assertEquals(draft.id(), store.getSemanticModelId(modelIdent));
+ assertThrows(NoSuchEntityException.class, () -> store.getSemanticModelId(missingModel));
+ assertThrows(NoSuchEntityException.class, () -> store.getSemanticModelId(missingSchema));
+ }
+ } finally {
+ caffeine.clear();
+ }
+ }
+
@TestTemplate
void testDeferredPublishingAndRetentionAcrossConsumers() throws Exception {
ManagedSemanticModelOperations deferred =
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelDraftAuthorizationH2.java b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelDraftAuthorizationH2.java
new file mode 100644
index 0000000000..d9dd3c57ce
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelDraftAuthorizationH2.java
@@ -0,0 +1,340 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.catalog;
+
+import static org.apache.gravitino.authorization.Privilege.Name.MODIFY_SEMANTIC_MODEL;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.io.IOException;
+import java.nio.file.Path;
+import java.security.Principal;
+import java.time.Instant;
+import java.util.List;
+import java.util.Map;
+import org.apache.commons.lang3.reflect.FieldUtils;
+import org.apache.gravitino.Catalog;
+import org.apache.gravitino.Config;
+import org.apache.gravitino.Configs;
+import org.apache.gravitino.GravitinoEnv;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.MetadataObjects;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.authorization.AuthorizationRequestContext;
+import org.apache.gravitino.authorization.AuthorizationUtils;
+import org.apache.gravitino.authorization.Privileges;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.connector.BaseCatalog;
+import org.apache.gravitino.connector.capability.Capability;
+import org.apache.gravitino.exceptions.NoSuchSemanticModelException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.BaseMetalake;
+import org.apache.gravitino.meta.CatalogEntity;
+import org.apache.gravitino.meta.EntityIdResolver;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.SchemaEntity;
+import org.apache.gravitino.meta.SchemaVersion;
+import org.apache.gravitino.meta.TableEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.semantic.Dataset;
+import org.apache.gravitino.semantic.SemanticModel;
+import org.apache.gravitino.semantic.SemanticModelDefinition;
+import org.apache.gravitino.semantic.SemanticModelSource;
+import org.apache.gravitino.semantic.SemanticModelSourceUpdate;
+import org.apache.gravitino.server.authorization.jcasbin.JcasbinAuthorizer;
+import org.apache.gravitino.storage.RandomIdGenerator;
+import org.apache.gravitino.storage.relational.CoreBackend;
+import org.apache.gravitino.storage.relational.RelationalEntityStore;
+import org.apache.gravitino.storage.relational.service.EntityIdService;
+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
+import org.apache.gravitino.utils.ThrowableFunction;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+/**
+ * Authorizes a Semantic Model that has only drafts through the real H2 store and JCasbin.
+ *
+ * <p>Grants are written against the model identity, so enforcement must resolve the same identity
+ * rather than the active revision, which a never-published model does not have.
+ */
+public class TestSemanticModelDraftAuthorizationH2 {
+ private static final String METALAKE = "semantic_draft_metalake";
+ private static final String CATALOG = "semantic_draft_catalog";
+ private static final String SCHEMA = "semantic_draft_schema";
+ private static final String MODEL = "sales";
+ private static final String EDITOR = "semantic_draft_editor";
+ private static final String DENIED = "semantic_draft_denied";
+ private static final MetadataObject MODEL_OBJECT =
+ MetadataObjects.of(List.of(CATALOG, SCHEMA, MODEL), MetadataObject.Type.SEMANTIC_MODEL);
+ private static final MetadataObject SCHEMA_OBJECT =
+ MetadataObjects.of(List.of(CATALOG, SCHEMA), MetadataObject.Type.SCHEMA);
+ private static final AuditInfo AUDIT =
+ AuditInfo.builder().withCreator("creator").withCreateTime(Instant.EPOCH).build();
+
+ @TempDir Path directory;
+
+ private Object previousConfig;
+ private Object previousStore;
+ private Object previousIdGenerator;
+ private Object previousMetrics;
+ private Object previousCatalogManager;
+ private EntityIdResolver previousIdResolver;
+ private RelationalEntityStore store;
+ private JcasbinAuthorizer authorizer;
+
+ @BeforeEach
+ void setUp() throws Exception {
+ GravitinoEnv env = GravitinoEnv.getInstance();
+ previousConfig = FieldUtils.readField(env, "config", true);
+ previousStore = FieldUtils.readField(env, "entityStore", true);
+ previousIdGenerator = FieldUtils.readField(env, "idGenerator", true);
+ previousMetrics = FieldUtils.readField(env, "metricsSystem", true);
+ previousCatalogManager = FieldUtils.readField(env, "catalogManager", true);
+ previousIdResolver =
+ (EntityIdResolver)
+ FieldUtils.readStaticField(EntityIdService.class, "entityIdResolver", true);
+ assertNull(
+ FieldUtils.readStaticField(SqlSessionFactoryHelper.class, "sqlSessionFactory", true),
+ "The isolated H2 fixture must not reuse another test's MyBatis factory");
+
+ Config config = new Config(false) {};
+ String dbPath = directory.resolve("semantic").toAbsolutePath().toString();
+ config.set(Configs.ENTITY_STORE, Configs.RELATIONAL_ENTITY_STORE);
+ config.set(Configs.ENTITY_RELATIONAL_JDBC_BACKEND_PATH, dbPath);
+ config.set(
+ Configs.ENTITY_RELATIONAL_JDBC_BACKEND_URL,
+ "jdbc:h2:file:" + dbPath + ";DB_CLOSE_DELAY=-1;MODE=MYSQL;AUTO_SERVER=FALSE");
+ config.set(Configs.ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER, "org.h2.Driver");
+ config.set(Configs.ENTITY_RELATIONAL_JDBC_BACKEND_USER, "test");
+ config.set(Configs.ENTITY_RELATIONAL_JDBC_BACKEND_PASSWORD, "test");
+ config.set(Configs.CACHE_ENABLED, false);
+ config.set(Configs.GRAVITINO_AUTHORIZATION_CHANGE_POLL_INTERVAL_SECS, 3600L);
+ config.set(Configs.ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS, 3600L);
+ FieldUtils.writeField(env, "config", config, true);
+ FieldUtils.writeField(env, "idGenerator", RandomIdGenerator.INSTANCE, true);
+ FieldUtils.writeField(env, "metricsSystem", null, true);
+ FieldUtils.writeField(env, "catalogManager", caseSensitiveCatalogs(), true);
+
+ store = new RelationalEntityStore();
+ store.initialize(config);
+ FieldUtils.writeField(env, "entityStore", store, true);
+ seedEntities();
+ authorizer = new JcasbinAuthorizer();
+ authorizer.initialize();
+ }
+
+ @AfterEach
+ void tearDown() throws Exception {
+ try {
+ if (authorizer != null) {
+ authorizer.close();
+ }
+ } finally {
+ try {
+ if (store != null) {
+ store.close();
+ }
+ } finally {
+ GravitinoEnv env = GravitinoEnv.getInstance();
+ FieldUtils.writeField(env, "config", previousConfig, true);
+ FieldUtils.writeField(env, "entityStore", previousStore, true);
+ FieldUtils.writeField(env, "idGenerator", previousIdGenerator, true);
+ FieldUtils.writeField(env, "metricsSystem", previousMetrics, true);
+ FieldUtils.writeField(env, "catalogManager", previousCatalogManager, true);
+ EntityIdService.initialize(previousIdResolver);
+ }
+ }
+ }
+
+ @Test
+ void testModelPrivilegesApplyBeforeFirstPublication() {
+ assertModelHasOnlyDrafts();
+ assertTrue(
+ authorizer.authorize(
+ principal(EDITOR),
+ METALAKE,
+ MODEL_OBJECT,
+ MODIFY_SEMANTIC_MODEL,
+ new AuthorizationRequestContext()),
+ "a model-level grant must let its editor read and edit the first draft");
+ }
+
+ @Test
+ void testModelDenyOverridesSchemaAllowBeforeFirstPublication() {
+ assertModelHasOnlyDrafts();
+ assertTrue(
+ authorizer.authorize(
+ principal(DENIED),
+ METALAKE,
+ SCHEMA_OBJECT,
+ MODIFY_SEMANTIC_MODEL,
+ new AuthorizationRequestContext()));
+ assertTrue(
+ authorizer.deny(
+ principal(DENIED),
+ METALAKE,
+ MODEL_OBJECT,
+ MODIFY_SEMANTIC_MODEL,
+ new AuthorizationRequestContext()),
+ "a model-level deny must still override the schema-level allow");
+ }
+
+ private void assertModelHasOnlyDrafts() {
+ ManagedSemanticModelOperations operations = deferredOperations();
+ NameIdentifier model = NameIdentifier.of(METALAKE, CATALOG, SCHEMA, MODEL);
+ assertTrue(operations.semanticModelExists(model));
+ // Consumers do not see the model until it is published.
+ assertThrows(NoSuchSemanticModelException.class, () -> operations.loadSemanticModel(model));
+ }
+
+ private void seedEntities() throws IOException {
+ store.put(
+ BaseMetalake.builder()
+ .withId(RandomIdGenerator.INSTANCE.nextId())
+ .withName(METALAKE)
+ .withComment("")
+ .withProperties(null)
+ .withVersion(SchemaVersion.V_0_1)
+ .withAuditInfo(AUDIT)
+ .build(),
+ false);
+ store.put(
+ CatalogEntity.builder()
+ .withId(RandomIdGenerator.INSTANCE.nextId())
+ .withName(CATALOG)
+ .withNamespace(Namespace.of(METALAKE))
+ .withType(Catalog.Type.RELATIONAL)
+ .withProvider("test")
+ .withComment("")
+ .withProperties(null)
+ .withAuditInfo(AUDIT)
+ .build(),
+ false);
+ store.put(
+ SchemaEntity.builder()
+ .withId(RandomIdGenerator.INSTANCE.nextId())
+ .withName(SCHEMA)
+ .withNamespace(Namespace.of(METALAKE, CATALOG))
+ .withComment("")
+ .withProperties(null)
+ .withAuditInfo(AUDIT)
+ .build(),
+ false);
+ TableEntity orders =
+ TableEntity.builder()
+ .withId(RandomIdGenerator.INSTANCE.nextId())
+ .withName("orders")
+ .withNamespace(Namespace.of(METALAKE, CATALOG, SCHEMA))
+ .withAuditInfo(AUDIT)
+ .build();
+ store.put(orders, false);
+ SemanticModel draft =
+ deferredOperations()
+ .createSemanticModel(
+ NameIdentifier.of(METALAKE, CATALOG, SCHEMA, MODEL),
+ null,
+ SemanticModelDefinition.builder()
+ .withDatasets(
+ new Dataset[] {
+ Dataset.builder()
+ .withName("orders")
+ .withSource(NameIdentifier.of(CATALOG, SCHEMA, "orders"))
+ .build()
+ })
+ .build(),
+ Map.of(),
+ SemanticModelSourceUpdate.replace(
+ List.of(new SemanticModelSource("orders", orders.type(), orders.id()))));
+ assertEquals(SemanticModel.Status.DRAFT, draft.status());
+
+ SecurableObject catalog = SecurableObjects.ofCatalog(CATALOG, List.of());
+ SecurableObject schema = SecurableObjects.ofSchema(catalog, SCHEMA, List.of());
+ addUser(
+ EDITOR,
+ List.of(
+ SecurableObjects.ofSemanticModel(
+ schema, MODEL, List.of(Privileges.ModifySemanticModel.allow()))));
+ addUser(
+ DENIED,
+ List.of(
+ SecurableObjects.ofSchema(
+ catalog, SCHEMA, List.of(Privileges.ModifySemanticModel.allow())),
+ SecurableObjects.ofSemanticModel(
+ schema, MODEL, List.of(Privileges.ModifySemanticModel.deny()))));
+ }
+
+ private void addUser(String user, List<SecurableObject> objects) throws IOException {
+ long roleId = RandomIdGenerator.INSTANCE.nextId();
+ String role = user + "_role";
+ store.put(
+ RoleEntity.builder()
+ .withId(roleId)
+ .withName(role)
+ .withNamespace(AuthorizationUtils.ofRoleNamespace(METALAKE))
+ .withProperties(null)
+ .withAuditInfo(AUDIT)
+ .withSecurableObjects(objects)
+ .build(),
+ false);
+ store.put(
+ UserEntity.builder()
+ .withId(RandomIdGenerator.INSTANCE.nextId())
+ .withName(user)
+ .withNamespace(AuthorizationUtils.ofUserNamespace(METALAKE))
+ .withRoleIds(List.of(roleId))
+ .withRoleNames(List.of(role))
+ .withAuditInfo(AUDIT)
+ .build(),
+ false);
+ }
+
+ private ManagedSemanticModelOperations deferredOperations() {
+ return new ManagedSemanticModelOperations(
+ store, RandomIdGenerator.INSTANCE, (ident, definition) -> {}, ident -> false);
+ }
+
+ private static Principal principal(String user) {
+ return () -> user;
+ }
+
+ private static CatalogManager caseSensitiveCatalogs() throws Exception {
+ BaseCatalog<?> catalog = mock(BaseCatalog.class);
+ when(catalog.capability()).thenReturn(new Capability() {});
+ CatalogManager catalogs = mock(CatalogManager.class);
+ doAnswer(
+ invocation -> {
+ ThrowableFunction<BaseCatalog<?>, Object> operation = invocation.getArgument(1);
+ return operation.apply(catalog);
+ })
+ .when(catalogs)
+ .doWithCatalog(any(), any());
+ return catalogs;
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStore.java b/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStore.java
index 2713358c87..1d6853fc42 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStore.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStore.java
@@ -172,6 +172,22 @@ public class TestRelationalEntityStore {
Mockito.verifyNoMoreInteractions(injected);
}
+ @Test
+ void testSemanticModelIdLookupUsesBackendIdentityLookup() throws Exception {
+ NameIdentifier ident = NameIdentifier.of("metalake", "catalog", "schema", "model");
+ NameIdentifier missing = NameIdentifier.of("metalake", "catalog", "schema", "missing");
+ Mockito.when(backend.getSemanticModelId(ident)).thenReturn(7L);
+ Mockito.when(backend.getSemanticModelId(missing))
+ .thenThrow(new NoSuchEntityException("Missing Semantic Model"));
+
+ Assertions.assertEquals(7L, store.getSemanticModelId(ident));
+ Assertions.assertThrows(NoSuchEntityException.class, () -> store.getSemanticModelId(missing));
+ // A content read would miss a model with only drafts, so the lookup must not fall back to it.
+ Mockito.verify(backend).getSemanticModelId(ident);
+ Mockito.verify(backend).getSemanticModelId(missing);
+ Mockito.verifyNoMoreInteractions(backend);
+ }
+
@Test
void testTableIdLookupAfterInvalidationReadsReplacementId() throws Exception {
NameIdentifier ident = NameIdentifier.of("metalake", "catalog", "schema", "table");
diff --git a/design-docs/gravitino-semantic-model-revision-design.md b/design-docs/gravitino-semantic-model-revision-design.md
index 8149cec42f..df76fab50b 100644
--- a/design-docs/gravitino-semantic-model-revision-design.md
+++ b/design-docs/gravitino-semantic-model-revision-design.md
@@ -338,6 +338,7 @@ Every current reader of Semantic Model state, and the selector it uses after thi
| REST alter preflight for `ReplaceDefinition` | `SemanticModelOperations` alter handler → load | `current_version` | `LATEST` |
| Internal existence check | `MetadataObjectUtil.checkMetadataObject` → `SemanticModelDispatcher.semanticModelExists` (default: load) | `current_version` | Identity: override the load-based default with an identity-row lookup |
| ID resolution | `RelationalEntityStoreIdResolver` | Identity row | Identity (unchanged) |
+| Authorization ID lookup on a cache miss | `MetadataIdConverter.loadId` → `EntityStore.getSemanticModelId` | `current_version` | Identity: override the load-based default with an identity-row lookup |
| Full-name resolution for tag, policy, and owner listings | `MetadataObjectService.getSemanticModelObjectsFullName` | Identity row | Identity (unchanged) |
| Alter, rename, drop | `SemanticModelMetaService` update and delete | Identity + `current_version` | Identity + `LATEST` |
@@ -881,7 +882,7 @@ a test policy that returns `false` and exercises publication end to end.
| Scenario | Expected result |
| ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| Create under a deferred policy | r1 is `DRAFT`; every consumer surface omits the model (`404` on load and export, absent from list, metrics, and lookup). |
-| Draft-only model and identity operations | The internal existence check succeeds; tag, owner, grant, policy, Domain, alter, and drop work. |
+| Draft-only model and identity operations | The internal existence check succeeds; tag, owner, grant, policy, Domain, alter, and drop work, and model-level grants and denies are enforced. |
| Draft-only model in a Domain | Tagged directly or through its schema, it is a Domain member on both paths; membership and tag listings are unchanged when it is published. |
| Tags on a model with a newer draft | Tags and Domain membership stay on the model; saving or publishing the draft changes neither. |
| Editor prepares the next draft | Default load returns `404` even for the editor; the editor loads `latest` and uses its revision as `expectedRevision`. |
diff --git a/server-common/src/main/java/org/apache/gravitino/server/authorization/MetadataIdConverter.java b/server-common/src/main/java/org/apache/gravitino/server/authorization/MetadataIdConverter.java
index e0b87c2c32..38b9ca1662 100644
--- a/server-common/src/main/java/org/apache/gravitino/server/authorization/MetadataIdConverter.java
+++ b/server-common/src/main/java/org/apache/gravitino/server/authorization/MetadataIdConverter.java
@@ -166,6 +166,9 @@ public class MetadataIdConverter {
if (entityType == Entity.EntityType.TABLE && entityStore instanceof SupportsTableIdLookup) {
return Optional.of(((SupportsTableIdLookup) entityStore).getTableId(ident));
}
+ if (entityType == Entity.EntityType.SEMANTIC_MODEL) {
+ return Optional.of(entityStore.getSemanticModelId(ident));
+ }
entity = entityStore.get(ident, entityType, EntityClassMapper.getEntityClass(entityType));
} catch (NoSuchEntityException e) {
return Optional.empty();
diff --git a/server-common/src/test/java/org/apache/gravitino/server/authorization/TestMetadataIdConverter.java b/server-common/src/test/java/org/apache/gravitino/server/authorization/TestMetadataIdConverter.java
index c1769ed34c..a0f4716607 100644
--- a/server-common/src/test/java/org/apache/gravitino/server/authorization/TestMetadataIdConverter.java
+++ b/server-common/src/test/java/org/apache/gravitino/server/authorization/TestMetadataIdConverter.java
@@ -62,7 +62,6 @@ import org.apache.gravitino.meta.GroupEntity;
import org.apache.gravitino.meta.ModelEntity;
import org.apache.gravitino.meta.SchemaEntity;
import org.apache.gravitino.meta.SchemaVersion;
-import org.apache.gravitino.meta.SemanticModelEntity;
import org.apache.gravitino.meta.TableEntity;
import org.apache.gravitino.meta.TopicEntity;
import org.apache.gravitino.rel.types.Types;
@@ -97,7 +96,6 @@ public class TestMetadataIdConverter {
private FilesetEntity entity6;
private TopicEntity entity7;
private GroupEntity entity8;
- private SemanticModelEntity entity9;
@BeforeAll
void initTest() throws IOException {
@@ -126,11 +124,8 @@ public class TestMetadataIdConverter {
.when(catalogs)
.doWithCatalog(any(), any());
EntityStore store = mock(EntityStore.class);
- SemanticModelEntity model = mock(SemanticModelEntity.class);
- when(model.id()).thenReturn(91L);
NameIdentifier normalized = NameIdentifier.of("metalake", "catalog", "schema", "SalesModel");
- when(store.get(normalized, Entity.EntityType.SEMANTIC_MODEL, SemanticModelEntity.class))
- .thenReturn(model);
+ when(store.getSemanticModelId(normalized)).thenReturn(91L);
GravitinoEnv env = mock(GravitinoEnv.class);
when(env.catalogManager()).thenReturn(catalogs);
when(env.entityStore()).thenReturn(store);
@@ -548,8 +543,6 @@ public class TestMetadataIdConverter {
getTestTopicEntity(
7L, "topic", Namespace.of("metalake", "catalog", "schema"), "test_topic");
entity8 = getTestGroupEntity(8L, "group", Namespace.of("metalake"));
- entity9 = mock(SemanticModelEntity.class);
- when(entity9.id()).thenReturn(9L);
}
private void initMockCache() throws IOException {
@@ -563,8 +556,7 @@ public class TestMetadataIdConverter {
when(mockStore.get(ident6, Entity.EntityType.FILESET, FilesetEntity.class)).thenReturn(entity6);
when(mockStore.get(ident7, Entity.EntityType.TOPIC, TopicEntity.class)).thenReturn(entity7);
when(mockStore.get(ident8, Entity.EntityType.GROUP, GroupEntity.class)).thenReturn(entity8);
- when(mockStore.get(ident9, Entity.EntityType.SEMANTIC_MODEL, SemanticModelEntity.class))
- .thenReturn(entity9);
+ when(mockStore.getSemanticModelId(ident9)).thenReturn(9L);
}
private BaseMetalake getTestMetalake(long id, String name, String comment) {
diff --git a/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinMetadataIdCacheNormalization.java b/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinMetadataIdCacheNormalization.java
index bd41673861..d40e4c77c2 100644
--- a/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinMetadataIdCacheNormalization.java
+++ b/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinMetadataIdCacheNormalization.java
@@ -137,6 +137,7 @@ public class TestJcasbinMetadataIdCacheNormalization {
}
return entity;
});
+ when(store.getSemanticModelId(any())).thenCallRealMethod();
env = mock(GravitinoEnv.class);
when(env.entityStore()).thenReturn(store);
when(env.catalogManager()).thenReturn(catalogs);