You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@polaris.apache.org by co...@apache.org on 2024/11/26 04:31:19 UTC
(polaris) 02/03: Merge branch 'mcollado-authz-use-grantmanager' into mcollado-hk2-di
This is an automated email from the ASF dual-hosted git repository.
collado pushed a commit to branch mcollado-hk2-di
in repository https://gitbox.apache.org/repos/asf/polaris.git
commit d48743c11b9f2a3a2247425f19581151db40f640
Merge: d1abeb8e 8bc43abc
Author: Michael Collado <co...@gmail.com>
AuthorDate: Mon Nov 25 19:47:14 2024 -0800
Merge branch 'mcollado-authz-use-grantmanager' into mcollado-hk2-di
.../polaris/core/auth/PolarisAuthorizerImpl.java | 29 +-
.../polaris/core/auth/PolarisGrantManager.java | 7 +
.../core/persistence/PolarisEntityManager.java | 77 +---
.../persistence/PolarisResolvedPathWrapper.java | 33 +-
.../core/persistence/ResolvedPolarisEntity.java | 80 ----
.../core/persistence/cache/EntityCache.java | 8 +
.../persistence/cache/EntityCacheGrantManager.java | 219 +++++++++++
.../resolver/PolarisResolutionManifest.java | 46 ++-
.../storage/cache/EntityCacheGrantManagerTest.java | 437 +++++++++++++++++++++
.../apache/polaris/service/PolarisApplication.java | 25 +-
.../polaris/service/admin/PolarisAdminService.java | 2 +-
.../service/catalog/BasePolarisCatalog.java | 13 +-
.../catalog/PolarisCatalogHandlerWrapper.java | 67 +---
.../service/config/RealmEntityManagerFactory.java | 14 +-
.../service/admin/PolarisAuthzTestBase.java | 27 +-
.../service/catalog/BasePolarisCatalogTest.java | 10 +-
.../catalog/BasePolarisCatalogViewTest.java | 9 +-
17 files changed, 817 insertions(+), 286 deletions(-)
diff --cc polaris-core/src/main/java/org/apache/polaris/core/auth/PolarisAuthorizerImpl.java
index b6170232,a4ef46fb..b9d0d8e1
--- a/polaris-core/src/main/java/org/apache/polaris/core/auth/PolarisAuthorizerImpl.java
+++ b/polaris-core/src/main/java/org/apache/polaris/core/auth/PolarisAuthorizerImpl.java
@@@ -91,7 -91,6 +91,8 @@@ import static org.apache.polaris.core.e
import com.google.common.base.Preconditions;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.SetMultimap;
+import jakarta.inject.Inject;
++import jakarta.inject.Provider;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@@@ -460,10 -460,12 +462,13 @@@ public class PolarisAuthorizerImpl impl
}
private final PolarisConfigurationStore featureConfig;
- private final PolarisGrantManager.Factory grantManagerFactory;
++ private final Provider<PolarisGrantManager> grantManagerFactory;
+ @Inject
- public PolarisAuthorizerImpl(PolarisConfigurationStore featureConfig) {
+ public PolarisAuthorizerImpl(
- PolarisConfigurationStore featureConfig, PolarisGrantManager.Factory grantManagerFactory) {
++ PolarisConfigurationStore featureConfig, Provider<PolarisGrantManager> grantManagerFactory) {
this.featureConfig = featureConfig;
+ this.grantManagerFactory = grantManagerFactory;
}
/**
@@@ -604,6 -606,10 +609,8 @@@
Set<Long> activatedGranteeIds,
PolarisPrivilege desiredPrivilege,
PolarisResolvedPathWrapper resolvedPath) {
- PolarisGrantManager grantManager =
- grantManagerFactory.getGrantManagerForRealm(
- CallContext.getCurrentContext().getRealmContext());
++ PolarisGrantManager grantManager = grantManagerFactory.get();
+ PolarisCallContext callContext = CallContext.getCurrentContext().getPolarisCallContext();
// Iterate starting at the parent, since the most common case should be to manage grants as
// high up in the resource hierarchy as possible, so we expect earlier termination.
diff --cc polaris-core/src/main/java/org/apache/polaris/core/persistence/PolarisEntityManager.java
index 922e97b0,f3ba2830..cefe728d
--- a/polaris-core/src/main/java/org/apache/polaris/core/persistence/PolarisEntityManager.java
+++ b/polaris-core/src/main/java/org/apache/polaris/core/persistence/PolarisEntityManager.java
@@@ -50,8 -55,8 +55,8 @@@ public class PolarisEntityManager
/**
* @param metaStoreManager the metastore manager for the current realm
- * @param credentialCache the storage credential cache for the current realm
+ * @param entityCache
+ * @param credentialCache the storage credential cache for the current realm
- * @param entityCache the entity cache
*/
public PolarisEntityManager(
PolarisMetaStoreManager metaStoreManager,
diff --cc polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCache.java
index fdf8e1dd,487e03ef..34bf2a77
--- a/polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCache.java
+++ b/polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCache.java
@@@ -27,8 -26,8 +27,9 @@@ import java.util.List
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import org.apache.polaris.core.PolarisCallContext;
+import org.apache.polaris.core.context.RealmScope;
import org.apache.polaris.core.entity.PolarisBaseEntity;
+ import org.apache.polaris.core.entity.PolarisEntityCore;
import org.apache.polaris.core.entity.PolarisEntityType;
import org.apache.polaris.core.entity.PolarisGrantRecord;
import org.apache.polaris.core.persistence.cache.PolarisRemoteCache.CachedEntryResult;
diff --cc polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCacheGrantManager.java
index 00000000,79e5c371..407311d1
mode 000000,100644..100644
--- a/polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCacheGrantManager.java
+++ b/polaris-core/src/main/java/org/apache/polaris/core/persistence/cache/EntityCacheGrantManager.java
@@@ -1,0 -1,236 +1,219 @@@
+ /*
+ * 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.polaris.core.persistence.cache;
+
++import jakarta.inject.Inject;
+ import java.util.ArrayList;
+ import java.util.List;
+ import java.util.stream.Collectors;
+ import org.apache.polaris.core.PolarisCallContext;
+ import org.apache.polaris.core.auth.PolarisGrantManager;
-import org.apache.polaris.core.context.RealmContext;
+ import org.apache.polaris.core.entity.PolarisBaseEntity;
+ import org.apache.polaris.core.entity.PolarisEntityConstants;
+ import org.apache.polaris.core.entity.PolarisEntityCore;
+ import org.apache.polaris.core.entity.PolarisEntityType;
+ import org.apache.polaris.core.entity.PolarisGrantRecord;
+ import org.apache.polaris.core.entity.PolarisPrivilege;
+ import org.apache.polaris.core.persistence.BaseResult;
+ import org.jetbrains.annotations.NotNull;
+ import org.jetbrains.annotations.Nullable;
+ import org.slf4j.Logger;
+ import org.slf4j.LoggerFactory;
+
+ /**
+ * PolarisGrantManger implementation that uses an EntityCache to retrieve entities and is backed by
+ * a delegate grant manager for persisting grant changes. This allows consumers to reuse cache
+ * entities without necessarily being aware of the {@link EntityCache} or the {@link
+ * EntityCacheEntry} specifics. Typically, the {@link
+ * org.apache.polaris.core.persistence.resolver.Resolver} is responsible for validating the cache
+ * state. This class does no validation of the entity version or the grant version of any cache
+ * record.
+ */
+ public class EntityCacheGrantManager implements PolarisGrantManager {
+ private static final Logger LOGGER = LoggerFactory.getLogger(EntityCacheGrantManager.class);
+ private final PolarisGrantManager delegateGrantManager;
+ private final EntityCache entityCache;
+ private PolarisGrantRecord serviceAdminRootContainerGrant;
+ private PolarisBaseEntity serviceAdminEntity;
+
- public static final class EntityCacheGrantManagerFactory implements PolarisGrantManager.Factory {
- private final PolarisGrantManager.Factory delegateGrantManagerFactory;
- private final RealmEntityCacheFactory realmEntityCacheFactory;
-
- public EntityCacheGrantManagerFactory(
- Factory delegateGrantManagerFactory, RealmEntityCacheFactory realmEntityCacheFactory) {
- this.delegateGrantManagerFactory = delegateGrantManagerFactory;
- this.realmEntityCacheFactory = realmEntityCacheFactory;
- }
-
- @Override
- public PolarisGrantManager getGrantManagerForRealm(RealmContext realm) {
- return new EntityCacheGrantManager(
- delegateGrantManagerFactory.getGrantManagerForRealm(realm),
- realmEntityCacheFactory.getOrCreateEntityCache(realm));
- }
- }
-
++ @Inject
+ public EntityCacheGrantManager(
+ PolarisGrantManager delegateGrantManager, EntityCache entityCache) {
+ this.delegateGrantManager = delegateGrantManager;
+ this.entityCache = entityCache;
+ }
+
+ @Override
+ public @NotNull PrivilegeResult grantUsageOnRoleToGrantee(
+ @NotNull PolarisCallContext callCtx,
+ @Nullable PolarisEntityCore catalog,
+ @NotNull PolarisEntityCore role,
+ @NotNull PolarisEntityCore grantee) {
+ try {
+ return delegateGrantManager.grantUsageOnRoleToGrantee(callCtx, catalog, role, grantee);
+ } finally {
+ LOGGER.debug("Invalidating cache for role {} and grantee {}", role, grantee);
+ entityCache.removeCacheEntry(role);
+ entityCache.removeCacheEntry(grantee);
+ }
+ }
+
+ @Override
+ public @NotNull PrivilegeResult revokeUsageOnRoleFromGrantee(
+ @NotNull PolarisCallContext callCtx,
+ @Nullable PolarisEntityCore catalog,
+ @NotNull PolarisEntityCore role,
+ @NotNull PolarisEntityCore grantee) {
+ try {
+ return delegateGrantManager.revokeUsageOnRoleFromGrantee(callCtx, catalog, role, grantee);
+ } finally {
+ LOGGER.debug("Invalidating cache for role {} and grantee {}", role, grantee);
+ entityCache.removeCacheEntry(role);
+ entityCache.removeCacheEntry(grantee);
+ }
+ }
+
+ @Override
+ public @NotNull PrivilegeResult grantPrivilegeOnSecurableToRole(
+ @NotNull PolarisCallContext callCtx,
+ @NotNull PolarisEntityCore grantee,
+ @Nullable List<PolarisEntityCore> catalogPath,
+ @NotNull PolarisEntityCore securable,
+ @NotNull PolarisPrivilege privilege) {
+ try {
+ return delegateGrantManager.grantPrivilegeOnSecurableToRole(
+ callCtx, grantee, catalogPath, securable, privilege);
+ } finally {
+ LOGGER.debug("Invalidating cache for securable {} and grantee {}", securable, grantee);
+ entityCache.removeCacheEntry(securable);
+ entityCache.removeCacheEntry(grantee);
+ }
+ }
+
+ @Override
+ public @NotNull PrivilegeResult revokePrivilegeOnSecurableFromRole(
+ @NotNull PolarisCallContext callCtx,
+ @NotNull PolarisEntityCore grantee,
+ @Nullable List<PolarisEntityCore> catalogPath,
+ @NotNull PolarisEntityCore securable,
+ @NotNull PolarisPrivilege privilege) {
+ try {
+ return delegateGrantManager.revokePrivilegeOnSecurableFromRole(
+ callCtx, grantee, catalogPath, securable, privilege);
+ } finally {
+ LOGGER.debug("Invalidating cache for securable {} and grantee {}", securable, grantee);
+ entityCache.removeCacheEntry(securable);
+ entityCache.removeCacheEntry(grantee);
+ }
+ }
+
+ @Override
+ public @NotNull LoadGrantsResult loadGrantsOnSecurable(
+ @NotNull PolarisCallContext callCtx, long securableCatalogId, long securableId) {
+ EntityCacheLookupResult lookupResult =
+ entityCache.getOrLoadEntityById(callCtx, securableCatalogId, securableId);
+ if (lookupResult == null || lookupResult.getCacheEntry() == null) {
+ return new LoadGrantsResult(BaseResult.ReturnStatus.GRANT_NOT_FOUND, null);
+ }
+ List<PolarisGrantRecord> grantRecords =
+ lookupResult.getCacheEntry().getGrantRecordsAsSecurable();
+ List<PolarisBaseEntity> granteeList = new ArrayList<>();
+ grantRecords.stream()
+ .map(
+ gr ->
+ entityCache.getOrLoadEntityById(
+ callCtx, gr.getGranteeCatalogId(), gr.getGranteeId()))
+ .filter(lr -> lr != null && lr.getCacheEntry() != null)
+ .map(lr -> lr.getCacheEntry().getEntity())
+ .forEach(granteeList::add);
+ if (granteeList.size() != lookupResult.getCacheEntry().getGrantRecordsAsSecurable().size()) {
+ LOGGER.error(
+ "Failed to resolve all grantees for securable {}",
+ lookupResult.getCacheEntry().getEntity());
+ return new LoadGrantsResult(BaseResult.ReturnStatus.GRANT_NOT_FOUND, null);
+ }
+
+ // If the securable is the root container, then we need to add a grant record for the
+ // service_admin PrincipalRole, which is the only role that has the SERVICE_MANAGE_ACCESS
+ // privilege on the root
+ if (lookupResult
+ .getCacheEntry()
+ .getEntity()
+ .getName()
+ .equals(PolarisEntityConstants.getRootContainerName())) {
+ if (serviceAdminEntity == null || serviceAdminRootContainerGrant == null) {
+ EntityCacheLookupResult serviceAdminRole =
+ entityCache.getOrLoadEntityByName(
+ callCtx,
+ new EntityCacheByNameKey(
+ 0L,
+ 0L,
+ PolarisEntityType.PRINCIPAL_ROLE,
+ PolarisEntityConstants.getNameOfPrincipalServiceAdminRole()));
+ if (serviceAdminRole == null || serviceAdminRole.getCacheEntry() == null) {
+ LOGGER.error("Failed to resolve service_admin PrincipalRole");
+ return new LoadGrantsResult(BaseResult.ReturnStatus.GRANT_NOT_FOUND, null);
+ }
+ serviceAdminRootContainerGrant =
+ new PolarisGrantRecord(
+ 0L,
+ 0L,
+ serviceAdminRole.getCacheEntry().getEntity().getCatalogId(),
+ serviceAdminRole.getCacheEntry().getEntity().getId(),
+ PolarisPrivilege.SERVICE_MANAGE_ACCESS.getCode());
+ serviceAdminEntity = serviceAdminRole.getCacheEntry().getEntity();
+ }
+ grantRecords.add(serviceAdminRootContainerGrant);
+ granteeList.add(serviceAdminEntity);
+ }
+ return new LoadGrantsResult(
+ lookupResult.getCacheEntry().getEntity().getGrantRecordsVersion(),
+ grantRecords,
+ granteeList);
+ }
+
+ @Override
+ public @NotNull LoadGrantsResult loadGrantsToGrantee(
+ PolarisCallContext callCtx, long granteeCatalogId, long granteeId) {
+ EntityCacheLookupResult lookupResult =
+ entityCache.getOrLoadEntityById(callCtx, granteeCatalogId, granteeId);
+ if (lookupResult == null || lookupResult.getCacheEntry() == null) {
+ return new LoadGrantsResult(BaseResult.ReturnStatus.GRANT_NOT_FOUND, null);
+ }
+ List<PolarisBaseEntity> securableList =
+ lookupResult.getCacheEntry().getGrantRecordsAsGrantee().stream()
+ .map(
+ gr ->
+ entityCache.getOrLoadEntityById(
+ callCtx, gr.getSecurableCatalogId(), gr.getSecurableId()))
+ .filter(lr -> lr != null && lr.getCacheEntry() != null)
+ .map(lr -> lr.getCacheEntry().getEntity())
+ .collect(Collectors.toList());
+ if (securableList.size() != lookupResult.getCacheEntry().getGrantRecordsAsGrantee().size()) {
+ LOGGER.error(
+ "Failed to resolve all securables for grantee {}",
+ lookupResult.getCacheEntry().getEntity());
+ return new LoadGrantsResult(BaseResult.ReturnStatus.GRANT_NOT_FOUND, null);
+ }
+ return new LoadGrantsResult(
+ lookupResult.getCacheEntry().getEntity().getGrantRecordsVersion(),
+ lookupResult.getCacheEntry().getGrantRecordsAsGrantee(),
+ securableList);
+ }
+ }
diff --cc polaris-core/src/test/java/org/apache/polaris/core/storage/cache/EntityCacheGrantManagerTest.java
index 00000000,e8a232c8..81ed6f77
mode 000000,100644..100644
--- a/polaris-core/src/test/java/org/apache/polaris/core/storage/cache/EntityCacheGrantManagerTest.java
+++ b/polaris-core/src/test/java/org/apache/polaris/core/storage/cache/EntityCacheGrantManagerTest.java
@@@ -1,0 -1,435 +1,437 @@@
+ /*
+ * 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.polaris.core.storage.cache;
+
+ import java.util.List;
+ import java.util.Set;
+ import java.util.stream.Collectors;
+ import org.apache.iceberg.catalog.Namespace;
+ import org.apache.iceberg.catalog.TableIdentifier;
+ import org.apache.polaris.core.PolarisCallContext;
+ import org.apache.polaris.core.PolarisDefaultDiagServiceImpl;
+ import org.apache.polaris.core.PolarisDiagnostics;
+ import org.apache.polaris.core.auth.AuthenticatedPolarisPrincipal;
+ import org.apache.polaris.core.auth.PolarisGrantManager;
+ import org.apache.polaris.core.context.CallContext;
+ import org.apache.polaris.core.context.RealmContext;
+ import org.apache.polaris.core.entity.CatalogEntity;
+ import org.apache.polaris.core.entity.CatalogRoleEntity;
+ import org.apache.polaris.core.entity.NamespaceEntity;
+ import org.apache.polaris.core.entity.PolarisBaseEntity;
+ import org.apache.polaris.core.entity.PolarisEntity;
+ import org.apache.polaris.core.entity.PolarisEntityCore;
+ import org.apache.polaris.core.entity.PolarisEntityType;
+ import org.apache.polaris.core.entity.PolarisGrantRecord;
+ import org.apache.polaris.core.entity.PolarisPrivilege;
+ import org.apache.polaris.core.entity.PrincipalEntity;
+ import org.apache.polaris.core.entity.PrincipalRoleEntity;
+ import org.apache.polaris.core.entity.TableLikeEntity;
+ import org.apache.polaris.core.persistence.BaseResult;
+ import org.apache.polaris.core.persistence.LocalPolarisMetaStoreManagerFactory;
+ import org.apache.polaris.core.persistence.MetaStoreManagerFactory;
+ import org.apache.polaris.core.persistence.PolarisEntityManager;
+ import org.apache.polaris.core.persistence.PolarisMetaStoreManager;
+ import org.apache.polaris.core.persistence.PolarisMetaStoreSession;
+ import org.apache.polaris.core.persistence.PolarisResolvedPathWrapper;
+ import org.apache.polaris.core.persistence.PolarisTreeMapMetaStoreSessionImpl;
+ import org.apache.polaris.core.persistence.PolarisTreeMapStore;
++import org.apache.polaris.core.persistence.PrincipalSecretsGenerator;
+ import org.apache.polaris.core.persistence.cache.EntityCache;
+ import org.apache.polaris.core.persistence.cache.EntityCacheGrantManager;
+ import org.apache.polaris.core.persistence.resolver.PolarisResolutionManifest;
+ import org.apache.polaris.core.persistence.resolver.ResolverPath;
+ import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+ import org.assertj.core.api.Assertions;
+ import org.assertj.core.api.InstanceOfAssertFactories;
+ import org.jetbrains.annotations.NotNull;
+ import org.junit.jupiter.api.BeforeEach;
+ import org.junit.jupiter.api.Test;
+ import org.mockito.Mockito;
+
+ public class EntityCacheGrantManagerTest {
+
+ public static final String NS_1 = "ns1";
+ public static final String NS_2 = "ns2";
+ public static final String TABLE_1 = "table1";
+ private MetaStoreManagerFactory metastoreManagerFactory;
+ private RealmContext realmContext;
+ private PolarisMetaStoreManager metaStoreManager;
+ private PolarisCallContext polarisCallContext;
+ private CatalogEntity catalog;
+ private PrincipalEntity principal;
+ private PrincipalRoleEntity principalRole1;
+ private PrincipalRoleEntity principalRole2;
+ private CatalogRoleEntity catalogRole1;
+ private CatalogRoleEntity catalogRole2;
+
+ @BeforeEach
+ public void setup() {
+ // Create a MetastoreManager
+ PolarisDefaultDiagServiceImpl diagServices = new PolarisDefaultDiagServiceImpl();
+ PolarisTreeMapStore treeMapStore = new PolarisTreeMapStore(diagServices);
+ PolarisTreeMapMetaStoreSessionImpl session =
- new PolarisTreeMapMetaStoreSessionImpl(treeMapStore, Mockito.mock());
++ new PolarisTreeMapMetaStoreSessionImpl(
++ treeMapStore, Mockito.mock(), PrincipalSecretsGenerator.RANDOM_SECRETS);
+ metastoreManagerFactory =
+ new LocalPolarisMetaStoreManagerFactory<PolarisTreeMapStore>() {
+
+ @Override
+ protected PolarisTreeMapStore createBackingStore(
+ @NotNull PolarisDiagnostics diagnostics) {
+ return treeMapStore;
+ }
+
+ @Override
+ protected PolarisMetaStoreSession createMetaStoreSession(
+ @NotNull PolarisTreeMapStore store, @NotNull RealmContext realmContext) {
+ return session;
+ }
+ };
+ // Create a Resolver and an EntityCacheGrantManager
+ realmContext = () -> "realm";
+ metastoreManagerFactory.bootstrapRealms(List.of(realmContext.getRealmIdentifier()));
+ metaStoreManager = metastoreManagerFactory.getOrCreateMetaStoreManager(realmContext);
+ polarisCallContext = new PolarisCallContext(session, diagServices);
+
+ // Create a principal with three Principal roles
+ principal =
+ new PrincipalEntity.Builder()
+ .setId(metaStoreManager.generateNewEntityId(polarisCallContext).getId())
+ .setName("principal1")
+ .setCreateTimestamp(System.currentTimeMillis())
+ .setEntityVersion(1)
+ .build();
+ principalRole1 =
+ new PrincipalRoleEntity.Builder()
+ .setId(metaStoreManager.generateNewEntityId(polarisCallContext).getId())
+ .setName("principalRole1")
+ .setCreateTimestamp(System.currentTimeMillis())
+ .setEntityVersion(1)
+ .build();
+ principalRole2 =
+ new PrincipalRoleEntity.Builder()
+ .setId(metaStoreManager.generateNewEntityId(polarisCallContext).getId())
+ .setName("principalRole2")
+ .setCreateTimestamp(System.currentTimeMillis())
+ .setEntityVersion(1)
+ .build();
+
+ // Persist the principal and principal roles
+ metaStoreManager.createPrincipal(polarisCallContext, principal);
+ metaStoreManager.createEntityIfNotExists(polarisCallContext, null, principalRole1);
+ metaStoreManager.createEntityIfNotExists(polarisCallContext, null, principalRole2);
+
+ // Create a catalog with two catalog roles
+ catalog =
+ new CatalogEntity.Builder()
+ .setId(metaStoreManager.generateNewEntityId(polarisCallContext).getId())
+ .setName("mycatalog")
+ .setCreateTimestamp(System.currentTimeMillis())
+ .setEntityVersion(1)
+ .build();
+ catalogRole1 =
+ new CatalogRoleEntity.Builder()
+ .setId(metaStoreManager.generateNewEntityId(polarisCallContext).getId())
+ .setName("mycatrole1")
+ .setCatalogId(catalog.getId())
+ .setCreateTimestamp(System.currentTimeMillis())
+ .setEntityVersion(1)
+ .build();
+ catalogRole2 =
+ new CatalogRoleEntity.Builder()
+ .setId(metaStoreManager.generateNewEntityId(polarisCallContext).getId())
+ .setName("mycatrole2")
+ .setCatalogId(catalog.getId())
+ .setCreateTimestamp(System.currentTimeMillis())
+ .setEntityVersion(1)
+ .build();
+ metaStoreManager.createCatalog(polarisCallContext, catalog, List.of(principalRole1));
+ metaStoreManager.createEntityIfNotExists(polarisCallContext, List.of(catalog), catalogRole1);
+ metaStoreManager.createEntityIfNotExists(polarisCallContext, List.of(catalog), catalogRole2);
+ metaStoreManager.grantUsageOnRoleToGrantee(
+ polarisCallContext, catalog, catalogRole1, principalRole1);
+ metaStoreManager.grantUsageOnRoleToGrantee(
+ polarisCallContext, catalog, catalogRole2, principalRole2);
+ metaStoreManager.grantUsageOnRoleToGrantee(polarisCallContext, null, principalRole1, principal);
+ metaStoreManager.grantUsageOnRoleToGrantee(polarisCallContext, null, principalRole2, principal);
+
+ PolarisBaseEntity ns1 =
+ metaStoreManager
+ .createEntityIfNotExists(
+ polarisCallContext,
+ List.of(catalog),
+ new NamespaceEntity.Builder(Namespace.of(NS_1))
+ .setId(metaStoreManager.generateNewEntityId(polarisCallContext).getId())
+ .setCatalogId(catalog.getId())
+ .setParentId(catalog.getId())
+ .setCreateTimestamp(System.currentTimeMillis())
+ .setEntityVersion(1)
+ .build())
+ .getEntity();
+
+ Namespace ns2Namespace = Namespace.of(NS_1, NS_2);
+ PolarisBaseEntity ns2 =
+ metaStoreManager
+ .createEntityIfNotExists(
+ polarisCallContext,
+ List.of(catalog, ns1),
+ new NamespaceEntity.Builder(ns2Namespace)
+ .setId(metaStoreManager.generateNewEntityId(polarisCallContext).getId())
+ .setCatalogId(catalog.getId())
+ .setParentId(ns1.getId())
+ .setCreateTimestamp(System.currentTimeMillis())
+ .setEntityVersion(1)
+ .build())
+ .getEntity();
+
+ TableIdentifier tbId = TableIdentifier.of(ns2Namespace, TABLE_1);
+ PolarisBaseEntity tb1 =
+ metaStoreManager
+ .createEntityIfNotExists(
+ polarisCallContext,
+ List.of(catalog),
+ new TableLikeEntity.Builder(tbId, "file://abc")
+ .setId(metaStoreManager.generateNewEntityId(polarisCallContext).getId())
+ .setCatalogId(catalog.getId())
+ .setParentId(ns2.getId())
+ .setCreateTimestamp(System.currentTimeMillis())
+ .setEntityVersion(1)
+ .build())
+ .getEntity();
+ metaStoreManager.grantPrivilegeOnSecurableToRole(
+ polarisCallContext,
+ new PolarisEntityCore(catalogRole1),
+ List.of(PolarisEntity.toCore(catalog)),
+ PolarisEntity.toCore(ns1),
+ PolarisPrivilege.NAMESPACE_LIST);
+ metaStoreManager.grantPrivilegeOnSecurableToRole(
+ polarisCallContext,
+ new PolarisEntityCore(catalogRole1),
+ List.of(PolarisEntity.toCore(catalog), PolarisEntity.toCore(ns1)),
+ PolarisEntity.toCore(ns2),
+ PolarisPrivilege.TABLE_CREATE);
+ metaStoreManager.grantPrivilegeOnSecurableToRole(
+ polarisCallContext,
+ new PolarisEntityCore(catalogRole2),
+ List.of(
+ PolarisEntity.toCore(catalog), PolarisEntity.toCore(ns1), PolarisEntity.toCore(ns2)),
+ PolarisEntity.toCore(tb1),
+ PolarisPrivilege.TABLE_READ_DATA);
+ }
+
+ @Test
+ public void testReadFromResolverPopulatedCache() {
+ Namespace ns2 = Namespace.of(NS_1, NS_2);
+ TableIdentifier tbId = TableIdentifier.of(ns2, TABLE_1);
+ EntityCache entityCache = new EntityCache(metaStoreManager);
+ PolarisResolutionManifest manifest =
+ new PolarisResolutionManifest(
+ CallContext.of(realmContext, polarisCallContext),
+ new PolarisEntityManager(metaStoreManager, entityCache, new StorageCredentialCache()),
+ new AuthenticatedPolarisPrincipal(
+ principal, Set.of(principalRole1.getName(), principalRole2.getName())),
+ catalog.getName());
+ manifest.addPath(new ResolverPath(List.of(NS_1, NS_2), PolarisEntityType.NAMESPACE), ns2);
+ manifest.addPath(
+ new ResolverPath(List.of(NS_1, NS_2, TABLE_1), PolarisEntityType.TABLE_LIKE), tbId);
+
+ ResolverStatus resolverStatus = manifest.resolveAll();
+ Assertions.assertThat(resolverStatus.getStatus()).isEqualTo(ResolverStatus.StatusEnum.SUCCESS);
+
+ // now create an EntityCacheGrantManager with a dummy grantManager implementation.
+ // everything should be returned from the cache
+ EntityCacheGrantManager grantManager = new EntityCacheGrantManager(Mockito.mock(), entityCache);
+ PolarisResolvedPathWrapper resolvedNamespace = manifest.getResolvedPath(ns2, false);
+
+ PolarisGrantManager.LoadGrantsResult grantsResult =
+ grantManager.loadGrantsOnSecurable(
+ polarisCallContext,
+ manifest.getResolvedReferenceCatalogEntity().getRawLeafEntity().getId(),
+ resolvedNamespace.getRawLeafEntity().getId());
+ Assertions.assertThat(grantsResult)
+ .returns(true, PolarisGrantManager.LoadGrantsResult::isSuccess)
+ .extracting(PolarisGrantManager.LoadGrantsResult::getGrantRecords)
+ .asInstanceOf(InstanceOfAssertFactories.list(PolarisGrantRecord.class))
+ .hasSize(1)
+ .satisfiesExactly(
+ grant -> {
+ Assertions.assertThat(grant)
+ .returns(catalogRole1.getId(), PolarisGrantRecord::getGranteeId)
+ .returns(
+ PolarisPrivilege.TABLE_CREATE.getCode(),
+ PolarisGrantRecord::getPrivilegeCode);
+ });
+
+ PolarisResolvedPathWrapper resolvedTable = manifest.getResolvedPath(tbId, false);
+ PolarisGrantManager.LoadGrantsResult tbGrantsResult =
+ grantManager.loadGrantsOnSecurable(
+ polarisCallContext,
+ manifest.getResolvedReferenceCatalogEntity().getRawLeafEntity().getId(),
+ resolvedTable.getRawLeafEntity().getId());
+ Assertions.assertThat(tbGrantsResult)
+ .returns(true, PolarisGrantManager.LoadGrantsResult::isSuccess)
+ .extracting(PolarisGrantManager.LoadGrantsResult::getGrantRecords)
+ .asInstanceOf(InstanceOfAssertFactories.list(PolarisGrantRecord.class))
+ .hasSize(1)
+ .satisfiesExactly(
+ grant -> {
+ Assertions.assertThat(grant)
+ .returns(catalogRole2.getId(), PolarisGrantRecord::getGranteeId)
+ .returns(
+ PolarisPrivilege.TABLE_READ_DATA.getCode(),
+ PolarisGrantRecord::getPrivilegeCode);
+ });
+ }
+
+ @Test
+ public void testRevokeGrantsClearsCache() {
+ Namespace ns2 = Namespace.of(NS_1, NS_2);
+ TableIdentifier tbId = TableIdentifier.of(ns2, TABLE_1);
+ EntityCache entityCache = new EntityCache(metaStoreManager);
+ PolarisResolutionManifest manifest =
+ new PolarisResolutionManifest(
+ CallContext.of(realmContext, polarisCallContext),
+ new PolarisEntityManager(metaStoreManager, entityCache, new StorageCredentialCache()),
+ new AuthenticatedPolarisPrincipal(
+ principal, Set.of(principalRole1.getName(), principalRole2.getName())),
+ catalog.getName());
+ manifest.addPath(new ResolverPath(List.of(NS_1, NS_2), PolarisEntityType.NAMESPACE), ns2);
+ manifest.addPath(
+ new ResolverPath(List.of(NS_1, NS_2, TABLE_1), PolarisEntityType.TABLE_LIKE), tbId);
+
+ ResolverStatus resolverStatus = manifest.resolveAll();
+ Assertions.assertThat(resolverStatus.getStatus()).isEqualTo(ResolverStatus.StatusEnum.SUCCESS);
+
+ PolarisGrantManager mockGrantManager = Mockito.mock();
+ EntityCacheGrantManager grantManager =
+ new EntityCacheGrantManager(mockGrantManager, entityCache);
+ PolarisResolvedPathWrapper resolvedNamespace = manifest.getResolvedPath(ns2, false);
+
+ // update the mock to return a successful response when we revoke the privilege
+ Mockito.when(
+ grantManager.revokePrivilegeOnSecurableFromRole(
+ polarisCallContext,
+ catalogRole1,
+ resolvedNamespace.getRawParentPath().stream()
+ .map(PolarisEntity::toCore)
+ .collect(Collectors.toList()),
+ resolvedNamespace.getRawLeafEntity(),
+ PolarisPrivilege.TABLE_CREATE))
+ .thenReturn(new PolarisGrantManager.PrivilegeResult(BaseResult.ReturnStatus.SUCCESS, null));
+ PolarisGrantManager.PrivilegeResult result =
+ grantManager.revokePrivilegeOnSecurableFromRole(
+ polarisCallContext,
+ catalogRole1,
+ resolvedNamespace.getRawParentPath().stream()
+ .map(PolarisEntity::toCore)
+ .collect(Collectors.toList()),
+ resolvedNamespace.getRawLeafEntity(),
+ PolarisPrivilege.TABLE_CREATE);
+ Assertions.assertThat(result)
+ .returns(
+ BaseResult.ReturnStatus.SUCCESS, PolarisGrantManager.PrivilegeResult::getReturnStatus);
+
+ // the cache is cleared
+ Assertions.assertThat(entityCache.getEntityById(resolvedNamespace.getRawLeafEntity().getId()))
+ .isNull();
+
+ // update the mock to return a successful, but empty response when we load the grants
+ Mockito.when(
+ mockGrantManager.loadGrantsOnSecurable(
+ polarisCallContext,
+ manifest.getResolvedReferenceCatalogEntity().getRawLeafEntity().getId(),
+ resolvedNamespace.getRawLeafEntity().getId()))
+ .thenReturn(new PolarisGrantManager.LoadGrantsResult(2, List.of(), List.of()));
+ PolarisGrantManager.LoadGrantsResult grantsResult =
+ mockGrantManager.loadGrantsOnSecurable(
+ polarisCallContext,
+ manifest.getResolvedReferenceCatalogEntity().getRawLeafEntity().getId(),
+ resolvedNamespace.getRawLeafEntity().getId());
+ Assertions.assertThat(grantsResult)
+ .returns(true, PolarisGrantManager.LoadGrantsResult::isSuccess)
+ .extracting(PolarisGrantManager.LoadGrantsResult::getGrantRecords)
+ .asInstanceOf(InstanceOfAssertFactories.list(PolarisGrantRecord.class))
+ .isEmpty();
+ }
+
+ @Test
+ public void testUpdateGrantsClearsCache() {
+ Namespace ns2 = Namespace.of(NS_1, NS_2);
+ TableIdentifier tbId = TableIdentifier.of(ns2, TABLE_1);
+ EntityCache entityCache = new EntityCache(metaStoreManager);
+ PolarisResolutionManifest manifest =
+ new PolarisResolutionManifest(
+ CallContext.of(realmContext, polarisCallContext),
+ new PolarisEntityManager(metaStoreManager, entityCache, new StorageCredentialCache()),
+ new AuthenticatedPolarisPrincipal(
+ principal, Set.of(principalRole1.getName(), principalRole2.getName())),
+ catalog.getName());
+ manifest.addPath(new ResolverPath(List.of(NS_1, NS_2), PolarisEntityType.NAMESPACE), ns2);
+ manifest.addPath(
+ new ResolverPath(List.of(NS_1, NS_2, TABLE_1), PolarisEntityType.TABLE_LIKE), tbId);
+
+ ResolverStatus resolverStatus = manifest.resolveAll();
+ Assertions.assertThat(resolverStatus.getStatus()).isEqualTo(ResolverStatus.StatusEnum.SUCCESS);
+
+ EntityCacheGrantManager grantManager =
+ new EntityCacheGrantManager(metaStoreManager, entityCache);
+ PolarisResolvedPathWrapper resolvedTable = manifest.getResolvedPath(tbId, false);
+
+ PolarisGrantManager.PrivilegeResult result =
+ grantManager.grantPrivilegeOnSecurableToRole(
+ polarisCallContext,
+ catalogRole2,
+ resolvedTable.getRawParentPath().stream()
+ .map(PolarisEntity::toCore)
+ .collect(Collectors.toList()),
+ resolvedTable.getRawLeafEntity(),
+ PolarisPrivilege.TABLE_DROP);
+ Assertions.assertThat(result)
+ .returns(
+ BaseResult.ReturnStatus.SUCCESS, PolarisGrantManager.PrivilegeResult::getReturnStatus);
+
+ // the cache is cleared
+ Assertions.assertThat(entityCache.getEntityById(resolvedTable.getRawLeafEntity().getId()))
+ .isNull();
+
+ PolarisGrantManager.LoadGrantsResult grantsResult =
+ grantManager.loadGrantsOnSecurable(
+ polarisCallContext,
+ manifest.getResolvedReferenceCatalogEntity().getRawLeafEntity().getId(),
+ resolvedTable.getRawLeafEntity().getId());
+ Assertions.assertThat(grantsResult)
+ .returns(true, PolarisGrantManager.LoadGrantsResult::isSuccess)
+ .extracting(PolarisGrantManager.LoadGrantsResult::getGrantRecords)
+ .asInstanceOf(InstanceOfAssertFactories.list(PolarisGrantRecord.class))
+ .hasSize(2)
+ .satisfiesExactlyInAnyOrder(
+ (PolarisGrantRecord gr) ->
+ Assertions.assertThat(gr)
+ .returns(catalogRole2.getId(), PolarisGrantRecord::getGranteeId)
+ .returns(
+ PolarisPrivilege.TABLE_READ_DATA.getCode(),
+ PolarisGrantRecord::getPrivilegeCode),
+ (PolarisGrantRecord gr) ->
+ Assertions.assertThat(gr)
+ .returns(catalogRole2.getId(), PolarisGrantRecord::getGranteeId)
+ .returns(
+ PolarisPrivilege.TABLE_DROP.getCode(),
+ PolarisGrantRecord::getPrivilegeCode));
+ }
+ }
diff --cc polaris-service/src/main/java/org/apache/polaris/service/PolarisApplication.java
index 3db95dd8,61fb6e58..595565db
--- a/polaris-service/src/main/java/org/apache/polaris/service/PolarisApplication.java
+++ b/polaris-service/src/main/java/org/apache/polaris/service/PolarisApplication.java
@@@ -88,29 -79,25 +88,30 @@@ import org.apache.polaris.core.auth.Pol
import org.apache.polaris.core.auth.PolarisGrantManager;
import org.apache.polaris.core.context.CallContext;
import org.apache.polaris.core.context.RealmContext;
-import org.apache.polaris.core.monitor.MetricRegistryAware;
+import org.apache.polaris.core.context.RealmScope;
import org.apache.polaris.core.monitor.PolarisMetricRegistry;
import org.apache.polaris.core.persistence.MetaStoreManagerFactory;
+import org.apache.polaris.core.persistence.PolarisMetaStoreManager;
import org.apache.polaris.core.persistence.cache.EntityCache;
+ import org.apache.polaris.core.persistence.cache.EntityCacheGrantManager;
-import org.apache.polaris.core.persistence.cache.RealmEntityCacheFactory;
+import org.apache.polaris.core.persistence.cache.PolarisRemoteCache;
+import org.apache.polaris.core.storage.PolarisStorageIntegrationProvider;
import org.apache.polaris.service.admin.PolarisServiceImpl;
import org.apache.polaris.service.admin.api.PolarisCatalogsApi;
+import org.apache.polaris.service.admin.api.PolarisCatalogsApiService;
import org.apache.polaris.service.admin.api.PolarisPrincipalRolesApi;
+import org.apache.polaris.service.admin.api.PolarisPrincipalRolesApiService;
import org.apache.polaris.service.admin.api.PolarisPrincipalsApi;
-import org.apache.polaris.service.auth.DiscoverableAuthenticator;
+import org.apache.polaris.service.admin.api.PolarisPrincipalsApiService;
+import org.apache.polaris.service.auth.TokenBrokerFactory;
import org.apache.polaris.service.catalog.IcebergCatalogAdapter;
import org.apache.polaris.service.catalog.api.IcebergRestCatalogApi;
+import org.apache.polaris.service.catalog.api.IcebergRestCatalogApiService;
import org.apache.polaris.service.catalog.api.IcebergRestConfigurationApi;
+import org.apache.polaris.service.catalog.api.IcebergRestConfigurationApiService;
import org.apache.polaris.service.catalog.api.IcebergRestOAuth2Api;
+import org.apache.polaris.service.catalog.api.IcebergRestOAuth2ApiService;
import org.apache.polaris.service.catalog.io.FileIOFactory;
-import org.apache.polaris.service.config.ConfigurationStoreAware;
-import org.apache.polaris.service.config.HasMetaStoreManagerFactory;
-import org.apache.polaris.service.config.OAuth2ApiService;
import org.apache.polaris.service.config.PolarisApplicationConfig;
import org.apache.polaris.service.config.RealmEntityManagerFactory;
import org.apache.polaris.service.config.Serializers;
@@@ -179,149 -156,52 +180,147 @@@ public class PolarisApplication extend
bootstrap.addCommand(new BootstrapRealmsCommand());
bootstrap.addCommand(new PurgeRealmsCommand());
+ SimpleModule module = new SimpleModule();
+ serviceLocator = ServiceLocatorUtilities.createAndPopulateServiceLocator();
+ SimpleValueInstantiators instantiators = new SimpleValueInstantiators();
+ ObjectMapper objectMapper = bootstrap.getObjectMapper();
+ DeserializationConfig deserializationConfig = objectMapper.getDeserializationConfig();
+ serviceLocator
+ .getDescriptors((c) -> true)
+ .forEach(
+ descriptor -> {
+ try {
+ Class<?> klazz =
+ PolarisApplication.class
+ .getClassLoader()
+ .loadClass(descriptor.getImplementation());
+ String name = descriptor.getName();
+ if (name == null) {
+ objectMapper.registerSubtypes(klazz);
+ } else {
+ objectMapper.registerSubtypes(new NamedType(klazz, name));
+ }
+ } catch (ClassNotFoundException e) {
+ LOGGER.error("Error loading class {}", descriptor.getImplementation(), e);
+ throw new RuntimeException("Unable to start Polaris application");
+ }
+ });
+ module.setValueInstantiators(instantiators);
+ module.setMixInAnnotation(Authenticator.class, NamedAuthenticator.class);
+ objectMapper.registerModule(module);
}
+ @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "class")
+ static final class NamedAuthenticator {}
+
@Override
public void run(PolarisApplicationConfig configuration, Environment environment) {
- MetaStoreManagerFactory metaStoreManagerFactory = configuration.getMetaStoreManagerFactory();
+ OpenTelemetry openTelemetry = setupTracing();
+ environment
+ .jersey()
+ .register(
+ new AbstractBinder() {
+ @Override
+ protected void configure() {
+ bind(RealmScopeContext.class)
+ .in(Singleton.class)
+ .to(new TypeLiteral<Context<RealmScope>>() {});
+ bind(configuration.getMetaStoreManagerFactory()).to(MetaStoreManagerFactory.class);
+ bindFactory(PolarisMetaStoreManagerFactory.class)
+ .to(PolarisMetaStoreManager.class)
+ .in(RealmScope.class);
- metaStoreManagerFactory.setStorageIntegrationProvider(
- new PolarisStorageIntegrationProviderImpl(
- () -> {
- StsClientBuilder stsClientBuilder = StsClient.builder();
- AwsCredentialsProvider awsCredentialsProvider = configuration.credentialsProvider();
- if (awsCredentialsProvider != null) {
- stsClientBuilder.credentialsProvider(awsCredentialsProvider);
- }
- return stsClientBuilder.build();
- },
- configuration.getGcpCredentialsProvider()));
+ bind(configuration.getConfigurationStore()).to(PolarisConfigurationStore.class);
+ bind(configuration.getFileIOFactory()).to(FileIOFactory.class);
+ bind(configuration.getPolarisAuthenticator()).to(Authenticator.class);
+ bind(configuration.getTokenBrokerFactory()).to(TokenBrokerFactory.class);
+ bind(configuration.getOauth2Service()).to(IcebergRestOAuth2ApiService.class);
+ bind(configuration.getCallContextResolver()).to(CallContextResolver.class);
+ bind(configuration.getRealmContextResolver()).to(RealmContextResolver.class);
+ bind(configuration.getRateLimiter()).to(RateLimiter.class);
+ bindFactory(EntityCacheFactory.class).in(RealmScope.class).to(EntityCache.class);
- PolarisMetricRegistry polarisMetricRegistry =
- new PolarisMetricRegistry(new PrometheusMeterRegistry(PrometheusConfig.DEFAULT));
- metaStoreManagerFactory.setMetricRegistry(polarisMetricRegistry);
+ bindFactory(PolarisRemoteCacheFactory.class)
+ .in(RealmScope.class)
+ .to(PolarisRemoteCache.class);
- // factory to use a cache delegating grant cache
- // currently depends explicitly on the metaStoreManager as the delegate grant
- // manager
- bindFactory(PolarisMetaStoreManagerFactory.class)
- .in(RealmScope.class)
- .to(PolarisGrantManager.class);
- OpenTelemetry openTelemetry = setupTracing();
- if (metaStoreManagerFactory instanceof OpenTelemetryAware otAware) {
- otAware.setOpenTelemetry(openTelemetry);
- }
- PolarisConfigurationStore configurationStore = configuration.getConfigurationStore();
- if (metaStoreManagerFactory instanceof ConfigurationStoreAware) {
- ((ConfigurationStoreAware) metaStoreManagerFactory).setConfigurationStore(configurationStore);
- }
- ConcurrentHashMap<RealmContext, EntityCache> realmEntityCache = new ConcurrentHashMap<>();
- RealmEntityCacheFactory cacheFactory =
- realm ->
- realmEntityCache.computeIfAbsent(
- realm,
- (r) -> new EntityCache(metaStoreManagerFactory.getOrCreateMetaStoreManager(realm)));
- RealmEntityManagerFactory entityManagerFactory =
- new RealmEntityManagerFactory(metaStoreManagerFactory, cacheFactory);
- CallContextResolver callContextResolver = configuration.getCallContextResolver();
- callContextResolver.setMetaStoreManagerFactory(metaStoreManagerFactory);
- if (callContextResolver instanceof ConfigurationStoreAware csa) {
- csa.setConfigurationStore(configurationStore);
- }
+ bind(new PolarisStorageIntegrationProviderImpl(
+ () -> {
+ StsClientBuilder stsClientBuilder = StsClient.builder();
+ AwsCredentialsProvider awsCredentialsProvider =
+ configuration.credentialsProvider();
+ if (awsCredentialsProvider != null) {
+ stsClientBuilder.credentialsProvider(awsCredentialsProvider);
+ }
+ return stsClientBuilder.build();
+ },
+ configuration.getGcpCredentialsProvider()))
+ .to(PolarisStorageIntegrationProvider.class);
+ bind(new PolarisMetricRegistry(
+ new PrometheusMeterRegistry(PrometheusConfig.DEFAULT)))
+ .to(PolarisMetricRegistry.class);
+ bind(openTelemetry).to(OpenTelemetry.class);
+ bindAsContract(RealmEntityManagerFactory.class).in(RealmScope.class);
+ bind(PolarisCallContextCatalogFactory.class)
+ .to(CallContextCatalogFactory.class)
+ .in(Singleton.class);
++
++ bindFactory(CacheGrantManagerFactory.class)
++ .in(Singleton.class)
++ .to(PolarisGrantManager.class);
+ bind(PolarisAuthorizerImpl.class).in(Singleton.class).to(PolarisAuthorizer.class);
+ bind(IcebergCatalogAdapter.class)
+ .in(Singleton.class)
+ .to(IcebergRestCatalogApiService.class)
+ .to(IcebergRestConfigurationApiService.class);
+ bind(PolarisServiceImpl.class)
+ .in(Singleton.class)
+ .to(PolarisCatalogsApiService.class)
+ .to(PolarisPrincipalsApiService.class)
+ .to(PolarisPrincipalRolesApiService.class);
+ FileIOFactory fileIOFactory = configuration.getFileIOFactory();
+
+ TaskHandlerConfiguration taskConfig = configuration.getTaskHandler();
+ TaskExecutorImpl taskExecutor =
+ new TaskExecutorImpl(
+ taskConfig.executorService(), configuration.getMetaStoreManagerFactory());
+ TaskFileIOSupplier fileIOSupplier =
+ new TaskFileIOSupplier(
+ configuration.getMetaStoreManagerFactory(), fileIOFactory);
+ taskExecutor.addTaskHandler(
+ new TableCleanupTaskHandler(
+ taskExecutor, configuration.getMetaStoreManagerFactory(), fileIOSupplier));
+ taskExecutor.addTaskHandler(
+ new ManifestFileCleanupTaskHandler(
+ fileIOSupplier, Executors.newVirtualThreadPerTaskExecutor()));
+
+ bind(taskExecutor).to(TaskExecutor.class);
+ }
+ });
+ MetaStoreManagerFactory metaStoreManagerFactory = configuration.getMetaStoreManagerFactory();
+ environment
+ .jersey()
+ .register(
+ new Feature() {
+ @Inject ServiceLocator serviceLocator;
+
+ @Override
+ public boolean configure(FeatureContext context) {
+ serviceLocator.inject(configuration.getMetaStoreManagerFactory());
+ serviceLocator.inject(configuration.getConfigurationStore());
+ serviceLocator.inject(configuration.getPolarisAuthenticator());
+ serviceLocator.inject(configuration.getTokenBrokerFactory());
+ serviceLocator.inject(configuration.getOauth2Service());
+ serviceLocator.inject(configuration.getFileIOFactory());
+ serviceLocator.inject(configuration.getCallContextResolver());
+ serviceLocator.inject(configuration.getRealmContextResolver());
+ serviceLocator.inject(configuration.getRateLimiter());
+ return true;
+ }
+ });
RealmContextResolver realmContextResolver = configuration.getRealmContextResolver();
- realmContextResolver.setMetaStoreManagerFactory(metaStoreManagerFactory);
+ CallContextResolver callContextResolver = configuration.getCallContextResolver();
environment
.servlets()
.addFilter(
@@@ -509,31 -426,4 +508,45 @@@
}
}
}
+
+ private static class PolarisMetaStoreManagerFactory implements Factory<PolarisMetaStoreManager> {
+ @Inject MetaStoreManagerFactory metaStoreManagerFactory;
+
+ @RealmScope
+ @Override
+ public PolarisMetaStoreManager provide() {
+ RealmContext realmContext = CallContext.getCurrentContext().getRealmContext();
+ return metaStoreManagerFactory.getOrCreateMetaStoreManager(realmContext);
+ }
+
+ @Override
+ public void dispose(PolarisMetaStoreManager instance) {}
+ }
+
+ private static class PolarisRemoteCacheFactory implements Factory<PolarisRemoteCache> {
+ @Inject PolarisMetaStoreManager metaStoreManager;
+
+ @RealmScope
+ @Override
+ public PolarisRemoteCache provide() {
+ return metaStoreManager;
+ }
+
+ @Override
+ public void dispose(PolarisRemoteCache instance) {}
+ }
++
++ private static class CacheGrantManagerFactory implements Factory<PolarisGrantManager> {
++ @Inject private PolarisMetaStoreManager metaStoreManager;
++ @Inject private EntityCache entityCache;
++
++ @RealmScope
++ @Override
++ public PolarisGrantManager provide() {
++ return new EntityCacheGrantManager(metaStoreManager, entityCache);
++ }
++
++ @Override
++ public void dispose(PolarisGrantManager instance) {}
++ }
}
diff --cc polaris-service/src/main/java/org/apache/polaris/service/config/RealmEntityManagerFactory.java
index cb551a08,a316428b..796056b7
--- a/polaris-service/src/main/java/org/apache/polaris/service/config/RealmEntityManagerFactory.java
+++ b/polaris-service/src/main/java/org/apache/polaris/service/config/RealmEntityManagerFactory.java
@@@ -18,7 -18,6 +18,8 @@@
*/
package org.apache.polaris.service.config;
+import jakarta.inject.Inject;
++import jakarta.inject.Provider;
import java.util.HashMap;
import java.util.Map;
import org.apache.polaris.core.context.RealmContext;
@@@ -37,34 -35,39 +38,33 @@@ public class RealmEntityManagerFactory
// Key: realmIdentifier
private final Map<String, PolarisEntityManager> cachedEntityManagers = new HashMap<>();
- private final EntityCache entityCache;
- private final RealmEntityCacheFactory entityCacheFactory;
++ private final Provider<EntityCache> entityCacheFactory;
// Subclasses for test injection.
protected RealmEntityManagerFactory() {
this.metaStoreManagerFactory = null;
- this.entityCache = null;
+ this.entityCacheFactory = null;
}
+ @Inject
public RealmEntityManagerFactory(
- MetaStoreManagerFactory metaStoreManagerFactory, EntityCache entityCache) {
- @NotNull MetaStoreManagerFactory metaStoreManagerFactory,
- @NotNull RealmEntityCacheFactory entityCacheFactory) {
++ MetaStoreManagerFactory metaStoreManagerFactory, Provider<EntityCache> entityCacheFactory) {
this.metaStoreManagerFactory = metaStoreManagerFactory;
- this.entityCache = entityCache;
+ this.entityCacheFactory = entityCacheFactory;
}
public PolarisEntityManager getOrCreateEntityManager(RealmContext context) {
String realm = context.getRealmIdentifier();
LOGGER.debug("Looking up PolarisEntityManager for realm {}", realm);
- PolarisEntityManager entityManagerInstance = cachedEntityManagers.get(realm);
- if (entityManagerInstance == null
- && metaStoreManagerFactory != null
- && entityCacheFactory != null) {
- LOGGER.info("Initializing new PolarisEntityManager for realm {}", realm);
--
- entityManagerInstance =
- new PolarisEntityManager(
+ return cachedEntityManagers.computeIfAbsent(
+ realm,
+ r -> {
+ LOGGER.info("Initializing new PolarisEntityManager for realm {}", r);
+ return new PolarisEntityManager(
metaStoreManagerFactory.getOrCreateMetaStoreManager(context),
- metaStoreManagerFactory.getOrCreateStorageCredentialCache(context),
- entityCache);
- entityCacheFactory.getOrCreateEntityCache(context),
++ entityCacheFactory.get(),
+ metaStoreManagerFactory.getOrCreateStorageCredentialCache(context));
-
- cachedEntityManagers.put(realm, entityManagerInstance);
- }
- return entityManagerInstance;
+ });
}
}
diff --cc polaris-service/src/test/java/org/apache/polaris/service/admin/PolarisAuthzTestBase.java
index 5151f0f7,f2893365..e6b40249
--- a/polaris-service/src/test/java/org/apache/polaris/service/admin/PolarisAuthzTestBase.java
+++ b/polaris-service/src/test/java/org/apache/polaris/service/admin/PolarisAuthzTestBase.java
@@@ -177,11 -174,20 +174,19 @@@ public abstract class PolarisAuthzTestB
callContext = CallContext.of(realmContext, polarisContext);
CallContext.setCurrentContext(callContext);
+ EntityCache entityCache = new EntityCache(metaStoreManager);
+ polarisAuthorizer =
+ new PolarisAuthorizerImpl(
+ new DefaultConfigurationStore(
+ Map.of(
+ PolarisConfiguration.ENFORCE_PRINCIPAL_CREDENTIAL_ROTATION_REQUIRED_CHECKING
+ .key,
+ true)),
- new EntityCacheGrantManager.EntityCacheGrantManagerFactory(
- metaStoreManagerFactory, (realm) -> entityCache));
++ () -> new EntityCacheGrantManager(metaStoreManager, entityCache));
+ this.entityManager =
+ new PolarisEntityManager(metaStoreManager, entityCache, new StorageCredentialCache());
+ this.metaStoreManager = metaStoreManager;
+
PrincipalEntity rootEntity =
new PrincipalEntity(
PolarisEntity.of(
diff --cc polaris-service/src/test/java/org/apache/polaris/service/catalog/BasePolarisCatalogTest.java
index 9495365f,6349e40c..08cd8775
--- a/polaris-service/src/test/java/org/apache/polaris/service/catalog/BasePolarisCatalogTest.java
+++ b/polaris-service/src/test/java/org/apache/polaris/service/catalog/BasePolarisCatalogTest.java
@@@ -184,7 -186,11 +185,10 @@@ public class BasePolarisCatalogTest ext
entityManager,
metaStoreManager,
authenticatedRoot,
- new PolarisAuthorizerImpl(new PolarisConfigurationStore() {}));
+ new PolarisAuthorizerImpl(
+ new PolarisConfigurationStore() {},
- new EntityCacheGrantManager.EntityCacheGrantManagerFactory(
- (realm) -> metaStoreManager, (realm) -> entityCache)));
++ () -> new EntityCacheGrantManager(metaStoreManager, entityCache)));
+
String storageLocation = "s3://my-bucket/path/to/data";
storageConfigModel =
AwsStorageConfigInfo.builder()
diff --cc polaris-service/src/test/java/org/apache/polaris/service/catalog/BasePolarisCatalogViewTest.java
index 7ad1d53d,b9c8600d..5735dd0a
--- a/polaris-service/src/test/java/org/apache/polaris/service/catalog/BasePolarisCatalogViewTest.java
+++ b/polaris-service/src/test/java/org/apache/polaris/service/catalog/BasePolarisCatalogViewTest.java
@@@ -116,7 -117,10 +117,9 @@@ public class BasePolarisCatalogViewTes
entityManager,
metaStoreManager,
authenticatedRoot,
- new PolarisAuthorizerImpl(new PolarisConfigurationStore() {}));
+ new PolarisAuthorizerImpl(
+ new PolarisConfigurationStore() {},
- new EntityCacheGrantManager.EntityCacheGrantManagerFactory(
- (realm) -> metaStoreManager, (realm) -> entityCache)));
++ () -> new EntityCacheGrantManager(metaStoreManager, entityCache)));
adminService.createCatalog(
new CatalogEntity.Builder()
.setName(CATALOG_NAME)